hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e90c2f46616731f5e9b8f69e760ae82823146673 | 1,382 | hpp | C++ | include/Core/Collision/TrajectoryNode.hpp | lukefelsberg/ObEngine | a0385df4944adde7c1c8073ead15419286c70019 | [
"MIT"
] | 187 | 2021-05-22T07:56:34.000Z | 2022-03-30T20:23:16.000Z | include/Core/Collision/TrajectoryNode.hpp | lukefelsberg/ObEngine | a0385df4944adde7c1c8073ead15419286c70019 | [
"MIT"
] | 48 | 2021-05-25T01:46:49.000Z | 2022-03-23T21:32:54.000Z | include/Core/Collision/TrajectoryNode.hpp | Mizugola/ObEngine | e39437935516113852a08e2d8122075bddb442b9 | [
"MIT"
] | 11 | 2021-05-24T07:01:33.000Z | 2022-03-07T12:08:48.000Z | #pragma once
#include <unordered_map>
#include <Collision/PolygonalCollider.hpp>
#include <Collision/Trajectory.hpp>
#include <Scene/SceneNode.hpp>
namespace obe::Collision
{
/**
* \brief A Node containing trajectories, a SceneNode to drive and a probe to check
* for collisions
*/
class TrajectoryNode
{
private:
PolygonalCollider* m_probe = nullptr;
Scene::SceneNode& m_sceneNode;
std::unordered_map<std::string, std::unique_ptr<Trajectory>> m_trajectories {};
public:
explicit TrajectoryNode(Scene::SceneNode& sceneNode);
Trajectory& addTrajectory(
const std::string& id, Transform::Units unit = Transform::Units::SceneUnits);
[[nodiscard]] Scene::SceneNode& getSceneNode() const;
Trajectory& getTrajectory(const std::string& id);
void removeTrajectory(const std::string& id);
void setProbe(PolygonalCollider* probe);
void update(double dt);
};
class InnerTest
{
public:
class CoolChild
{
enum InnerEnum
{
Cool,
NotCool
};
InnerEnum yes()
{
return InnerEnum::Cool;
}
};
CoolChild build()
{
return CoolChild();
}
};
} // namespace obe::Collision
| 24.678571 | 89 | 0.578871 | [
"transform"
] |
e90f6ceb436d0b2d3877bbf2569bbfd0d395c278 | 8,034 | hpp | C++ | include/core/Defs.hpp | beroso/godot-cpp | eafe6d96226da5ebf02ec35ca1599a45dd794cfc | [
"MIT"
] | 4 | 2021-05-20T15:03:13.000Z | 2021-09-20T07:56:15.000Z | include/core/Defs.hpp | beroso/godot-cpp | eafe6d96226da5ebf02ec35ca1599a45dd794cfc | [
"MIT"
] | 15 | 2021-08-05T03:43:49.000Z | 2021-08-13T23:21:47.000Z | include/core/Defs.hpp | beroso/godot-cpp | eafe6d96226da5ebf02ec35ca1599a45dd794cfc | [
"MIT"
] | null | null | null | #ifndef DEFS_H
#define DEFS_H
namespace godot {
enum class Error {
OK,
FAILED, ///< Generic fail error
ERR_UNAVAILABLE, ///< What is requested is unsupported/unavailable
ERR_UNCONFIGURED, ///< The object being used hasnt been properly set up yet
ERR_UNAUTHORIZED, ///< Missing credentials for requested resource
ERR_PARAMETER_RANGE_ERROR, ///< Parameter given out of range (5)
ERR_OUT_OF_MEMORY, ///< Out of memory
ERR_FILE_NOT_FOUND,
ERR_FILE_BAD_DRIVE,
ERR_FILE_BAD_PATH,
ERR_FILE_NO_PERMISSION, // (10)
ERR_FILE_ALREADY_IN_USE,
ERR_FILE_CANT_OPEN,
ERR_FILE_CANT_WRITE,
ERR_FILE_CANT_READ,
ERR_FILE_UNRECOGNIZED, // (15)
ERR_FILE_CORRUPT,
ERR_FILE_MISSING_DEPENDENCIES,
ERR_FILE_EOF,
ERR_CANT_OPEN, ///< Can't open a resource/socket/file
ERR_CANT_CREATE, // (20)
ERR_QUERY_FAILED,
ERR_ALREADY_IN_USE,
ERR_LOCKED, ///< resource is locked
ERR_TIMEOUT,
ERR_CANT_CONNECT, // (25)
ERR_CANT_RESOLVE,
ERR_CONNECTION_ERROR,
ERR_CANT_AQUIRE_RESOURCE,
ERR_CANT_FORK,
ERR_INVALID_DATA, ///< Data passed is invalid (30)
ERR_INVALID_PARAMETER, ///< Parameter passed is invalid
ERR_ALREADY_EXISTS, ///< When adding, item already exists
ERR_DOES_NOT_EXIST, ///< When retrieving/erasing, it item does not exist
ERR_DATABASE_CANT_READ, ///< database is full
ERR_DATABASE_CANT_WRITE, ///< database is full (35)
ERR_COMPILATION_FAILED,
ERR_METHOD_NOT_FOUND,
ERR_LINK_FAILED,
ERR_SCRIPT_FAILED,
ERR_CYCLIC_LINK, // (40)
ERR_INVALID_DECLARATION,
ERR_DUPLICATE_SYMBOL,
ERR_PARSE_ERROR,
ERR_BUSY,
ERR_SKIP, // (45)
ERR_HELP, ///< user requested help!!
ERR_BUG, ///< a bug in the software certainly happened, due to a double check failing or unexpected behavior.
ERR_PRINTER_ON_FIRE, /// the parallel port printer is engulfed in flames
ERR_OMFG_THIS_IS_VERY_VERY_BAD, ///< shit happens, has never been used, though
ERR_WTF = ERR_OMFG_THIS_IS_VERY_VERY_BAD ///< short version of the above
};
} // namespace godot
#include <GodotGlobal.hpp>
// alloca() is non-standard. When using MSVC, it's in malloc.h.
#if defined(__linux__) || defined(__APPLE__)
#include <alloca.h>
#else
#include <malloc.h>
#endif
typedef float real_t;
// This epsilon should match the one used by Godot for consistency.
// Using `f` when `real_t` is float.
#define CMP_EPSILON 0.00001f
#define CMP_EPSILON2 (CMP_EPSILON * CMP_EPSILON)
#define Math_PI 3.1415926535897932384626433833
#define Math_TAU 6.2831853071795864769252867666
#define _PLANE_EQ_DOT_EPSILON 0.999
#define _PLANE_EQ_D_EPSILON 0.0001
#ifdef __GNUC__
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else
#define likely(x) x
#define unlikely(x) x
#endif
// Don't use this directly; instead, use any of the CRASH_* macros
#ifdef _MSC_VER
#define GENERATE_TRAP \
__debugbreak(); \
/* Avoid warning about control paths */ \
for (;;) { \
}
#else
#define GENERATE_TRAP __builtin_trap();
#endif
// ERR/WARN macros
#ifndef WARN_PRINT
#define WARN_PRINT(msg) godot::Godot::print_warning(msg, __func__, __FILE__, __LINE__)
#endif
#ifndef WARN_PRINTS
#define WARN_PRINTS(msg) WARN_PRINT((msg).utf8().get_data())
#endif
#ifndef ERR_PRINT
#define ERR_PRINT(msg) godot::Godot::print_error(msg, __func__, __FILE__, __LINE__)
#endif
#ifndef ERR_PRINTS
#define ERR_PRINTS(msg) ERR_PRINT((msg).utf8().get_data())
#endif
#ifndef FATAL_PRINT
#define FATAL_PRINT(msg) ERR_PRINT(godot::String("FATAL: ") + (msg))
#endif
#ifndef ERR_MSG_INDEX
#define ERR_MSG_INDEX(index, size) (godot::String("Index ") + #index + "=" + godot::String::num_int64(index) + " out of size (" + #size + "=" + godot::String::num_int64(size) + ")")
#endif
#ifndef ERR_MSG_NULL
#define ERR_MSG_NULL(param) (godot::String("Parameter '") + #param + "' is null.")
#endif
#ifndef ERR_MSG_COND
#define ERR_MSG_COND(cond) (godot::String("Condition '") + #cond + "' is true.")
#endif
#ifndef ERR_FAIL_INDEX
#define ERR_FAIL_INDEX(index, size) \
do { \
if (unlikely((index) < 0 || (index) >= (size))) { \
ERR_PRINT(ERR_MSG_INDEX(index, size)); \
return; \
} \
} while (0)
#endif
#ifndef ERR_FAIL_INDEX_V
#define ERR_FAIL_INDEX_V(index, size, ret) \
do { \
if (unlikely((index) < 0 || (index) >= (size))) { \
ERR_PRINT(ERR_MSG_INDEX(index, size)); \
return ret; \
} \
} while (0)
#endif
#ifndef ERR_FAIL_UNSIGNED_INDEX_V
#define ERR_FAIL_UNSIGNED_INDEX_V(index, size, ret) \
do { \
if (unlikely((index) >= (size))) { \
ERR_PRINT(ERR_MSG_INDEX(index, size)); \
return ret; \
} \
} while (0)
#endif
#ifndef CRASH_BAD_INDEX
#define CRASH_BAD_INDEX(index, size) \
do { \
if (unlikely((index) < 0 || (index) >= (size))) { \
FATAL_PRINT(ERR_MSG_INDEX(index, size)); \
GENERATE_TRAP; \
} \
} while (0)
#endif
#ifndef ERR_FAIL_NULL
#define ERR_FAIL_NULL(param) \
do { \
if (unlikely(!param)) { \
ERR_PRINT(ERR_MSG_NULL(param)); \
return; \
} \
} while (0)
#endif
#ifndef ERR_FAIL_NULL_V
#define ERR_FAIL_NULL_V(param, ret) \
do { \
if (unlikely(!param)) { \
ERR_PRINT(ERR_MSG_NULL(param)); \
return ret; \
} \
} while (0)
#endif
#ifndef ERR_FAIL_COND
#define ERR_FAIL_COND(cond) \
do { \
if (unlikely(cond)) { \
ERR_PRINT(ERR_MSG_COND(cond)); \
return; \
} \
} while (0)
#endif
#ifndef CRASH_COND
#define CRASH_COND(cond) \
do { \
if (unlikely(cond)) { \
FATAL_PRINT(ERR_MSG_COND(cond)); \
return; \
} \
} while (0)
#endif
#ifndef ERR_FAIL_COND_V
#define ERR_FAIL_COND_V(cond, ret) \
do { \
if (unlikely(cond)) { \
ERR_PRINT(ERR_MSG_COND(cond)); \
return ret; \
} \
} while (0)
#endif
#ifndef ERR_CONTINUE
#define ERR_CONTINUE(cond) \
{ \
if (unlikely(cond)) { \
ERR_PRINT(ERR_MSG_COND(cond)); \
continue; \
} \
}
#endif
#ifndef ERR_BREAK
#define ERR_BREAK(cond) \
{ \
if (unlikely(cond)) { \
ERR_PRINT(ERR_MSG_COND(cond)); \
break; \
} \
}
#endif
#ifndef ERR_FAIL
#define ERR_FAIL() \
do { \
ERR_PRINT("Method/Function Failed."); \
return; \
} while (0)
#endif
#ifndef ERR_FAIL_V
#define ERR_FAIL_V(ret) \
do { \
ERR_PRINT("Method/Function Failed."); \
return ret; \
} while (0)
#endif
#ifndef CRASH_NOW
#define CRASH_NOW() \
do { \
FATAL_PRINT("Method/Function Failed."); \
GENERATE_TRAP; \
} while (0)
#endif
#endif // DEFS_H
| 29.645756 | 181 | 0.547921 | [
"object"
] |
e90fe9b28129c0f8ed2825d5e6eeeae408860723 | 6,042 | cpp | C++ | src/luxrays/core/trianglemesh.cpp | bartoszek/LuxCore | 1d90c142f27734ac8035e2b8485d7f4ce946210d | [
"Apache-2.0"
] | 1 | 2020-07-19T22:00:26.000Z | 2020-07-19T22:00:26.000Z | src/luxrays/core/trianglemesh.cpp | MetaRabbit/LuxCore | ee4d881d7ccf64fb6bb29845d7af0409ef8fd3b9 | [
"Apache-2.0"
] | null | null | null | src/luxrays/core/trianglemesh.cpp | MetaRabbit/LuxCore | ee4d881d7ccf64fb6bb29845d7af0409ef8fd3b9 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright 1998-2018 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 <cassert>
#include <deque>
#include "luxrays/core/trianglemesh.h"
#include "luxrays/core/exttrianglemesh.h"
using namespace luxrays;
//------------------------------------------------------------------------------
// TriangleMesh
//------------------------------------------------------------------------------
BOOST_CLASS_EXPORT_IMPLEMENT(luxrays::Mesh)
//------------------------------------------------------------------------------
// TriangleMesh
//------------------------------------------------------------------------------
BOOST_CLASS_EXPORT_IMPLEMENT(luxrays::TriangleMesh)
TriangleMesh::TriangleMesh(const u_int meshVertCount,
const u_int meshTriCount, Point *meshVertices,
Triangle *meshTris) {
assert (meshVertCount > 0);
assert (meshTriCount > 0);
assert (meshVertices != NULL);
assert (meshTris != NULL);
// Check if the buffer has been really allocated with AllocVerticesBuffer() or not.
const float *vertBuff = (float *)meshVertices;
if (vertBuff[3 * meshVertCount] != 1234.1234f)
throw std::runtime_error("luxrays::TriangleMesh() used with a vertex buffer not allocated with luxrays::TriangleMesh::AllocVerticesBuffer()");
vertCount = meshVertCount;
triCount = meshTriCount;
vertices = meshVertices;
tris = meshTris;
cachedBBoxValid = false;
}
BBox TriangleMesh::GetBBox() const {
if (!cachedBBoxValid) {
BBox bbox;
for (u_int i = 0; i < vertCount; ++i)
bbox = Union(bbox, vertices[i]);
cachedBBox = bbox;
cachedBBoxValid = true;
}
return cachedBBox;
}
void TriangleMesh::ApplyTransform(const Transform &trans) {
for (u_int i = 0; i < vertCount; ++i)
vertices[i] *= trans;
cachedBBoxValid = false;
}
TriangleMesh *TriangleMesh::Merge(
const std::deque<const Mesh *> &meshes,
TriangleMeshID **preprocessedMeshIDs,
TriangleID **preprocessedMeshTriangleIDs) {
u_int totalVertexCount = 0;
u_int totalTriangleCount = 0;
for (std::deque<const Mesh *>::const_iterator m = meshes.begin(); m < meshes.end(); m++) {
totalVertexCount += (*m)->GetTotalVertexCount();
totalTriangleCount += (*m)->GetTotalTriangleCount();
}
assert (totalVertexCount > 0);
assert (totalTriangleCount > 0);
assert (meshes.size() > 0);
Point *v = AllocVerticesBuffer(totalVertexCount);
Triangle *i = AllocTrianglesBuffer(totalTriangleCount);
if (preprocessedMeshIDs)
*preprocessedMeshIDs = new TriangleMeshID[totalTriangleCount];
if (preprocessedMeshTriangleIDs)
*preprocessedMeshTriangleIDs = new TriangleID[totalTriangleCount];
u_int vIndex = 0;
u_int iIndex = 0;
TriangleMeshID currentID = 0;
for (std::deque<const Mesh *>::const_iterator m = meshes.begin(); m < meshes.end(); m++) {
// Copy the mesh vertices
memcpy(&v[vIndex], (*m)->GetVertices(), sizeof(Point) * (*m)->GetTotalVertexCount());
const Triangle *tris = (*m)->GetTriangles();
// Translate mesh indices
for (u_int j = 0; j < (*m)->GetTotalTriangleCount(); j++) {
i[iIndex].v[0] = tris[j].v[0] + vIndex;
i[iIndex].v[1] = tris[j].v[1] + vIndex;
i[iIndex].v[2] = tris[j].v[2] + vIndex;
if (preprocessedMeshIDs)
(*preprocessedMeshIDs)[iIndex] = currentID;
if (preprocessedMeshTriangleIDs)
(*preprocessedMeshTriangleIDs)[iIndex] = j;
++iIndex;
}
vIndex += (*m)->GetTotalVertexCount();
if (preprocessedMeshIDs) {
// To avoid compiler warning
currentID = currentID + 1;
}
}
return new TriangleMesh(totalVertexCount, totalTriangleCount, v, i);
}
//------------------------------------------------------------------------------
// InstanceTriangleMesh
//------------------------------------------------------------------------------
BOOST_CLASS_EXPORT_IMPLEMENT(luxrays::InstanceTriangleMesh)
InstanceTriangleMesh::InstanceTriangleMesh(TriangleMesh *m, const Transform &t) {
assert (m != NULL);
trans = t;
mesh = m;
cachedBBoxValid = false;
}
BBox InstanceTriangleMesh::GetBBox() const {
if (!cachedBBoxValid) {
cachedBBox = trans * mesh->GetBBox();
cachedBBoxValid = true;
}
return cachedBBox;
}
//------------------------------------------------------------------------------
// MotionTriangleMesh
//------------------------------------------------------------------------------
BOOST_CLASS_EXPORT_IMPLEMENT(luxrays::MotionTriangleMesh)
MotionTriangleMesh::MotionTriangleMesh(TriangleMesh *m, const MotionSystem &ms) {
assert (m != NULL);
motionSystem = ms;
mesh = m;
cachedBBoxValid = false;
}
BBox MotionTriangleMesh::GetBBox() const {
if (!cachedBBoxValid) {
cachedBBox = motionSystem.Bound(mesh->GetBBox(), true);
cachedBBoxValid = true;
}
return cachedBBox;
}
void MotionTriangleMesh::ApplyTransform(const Transform &trans) {
motionSystem.ApplyTransform(trans);
cachedBBoxValid = false;
}
| 31.8 | 144 | 0.566203 | [
"mesh",
"transform"
] |
e91280797d426e5c4994f2d55ba391c004b9cc05 | 11,530 | cc | C++ | DAQ/src/StrawRecoFromFragments_module.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | DAQ/src/StrawRecoFromFragments_module.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | DAQ/src/StrawRecoFromFragments_module.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | // ======================================================================
//
// StrawRecoFromFragmnets_plugin: Add tracker data products to the event
//
// ======================================================================
#include "art/Framework/Core/EDProducer.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Services/Registry/ServiceHandle.h"
#include "fhiclcpp/ParameterSet.h"
#include "art/Framework/Principal/Handle.h"
#include "mu2e-artdaq-core/Overlays/FragmentType.hh"
#include "mu2e-artdaq-core/Overlays/TrackerFragment.hh"
#include "mu2e-artdaq-core/Overlays/Mu2eEventFragment.hh"
#include "Offline/DataProducts/inc/TrkTypes.hh"
#include "Offline/RecoDataProducts/inc/StrawDigi.hh"
#include "Offline/RecoDataProducts/inc/ProtonBunchTime.hh"
#include <artdaq-core/Data/Fragment.hh>
#include <iostream>
#include <string>
#include <memory>
namespace art {
class StrawRecoFromFragmnets;
}
// ======================================================================
class art::StrawRecoFromFragmnets : public EDProducer {
public:
struct Config {
fhicl::Atom<int> diagLevel{fhicl::Name("diagLevel"), fhicl::Comment("diagnostic level")};
fhicl::Atom<int> useTrkADC{fhicl::Name("useTrkADC"), fhicl::Comment("parse tracker ADC waveforms")};
fhicl::Atom<art::InputTag> trkTag {fhicl::Name("trkTag"), fhicl::Comment("trkTag")};
};
// --- C'tor/d'tor:
explicit StrawRecoFromFragmnets(const art::EDProducer::Table<Config>& config);
virtual ~StrawRecoFromFragmnets() {}
// --- Production:
virtual void produce(Event&);
private:
void analyze_tracker_(const mu2e::TrackerFragment& cc,
std::unique_ptr<mu2e::StrawDigiCollection> const& straw_digis,
std::unique_ptr<mu2e::StrawDigiADCWaveformCollection> const& straw_digi_adcs);
int diagLevel_;
int useTrkADC_;
art::InputTag trkFragmentsTag_;
const int hexShiftPrint = 7;
}; // StrawRecoFromFragmnets
// ======================================================================
art::StrawRecoFromFragmnets::StrawRecoFromFragmnets(const art::EDProducer::Table<Config>& config) :
art::EDProducer{config},
diagLevel_(config().diagLevel()),
useTrkADC_(config().useTrkADC()),
trkFragmentsTag_(config().trkTag()){
produces<mu2e::StrawDigiCollection>();
if (useTrkADC_) {
produces<mu2e::StrawDigiADCWaveformCollection>();
}
//FIXME!
produces<mu2e::ProtonBunchTime>();
}
// ----------------------------------------------------------------------
void art::StrawRecoFromFragmnets::produce(Event& event) {
art::EventNumber_t eventNumber = event.event();
// Collection of StrawDigis for the event
std::unique_ptr<mu2e::StrawDigiCollection> straw_digis(new mu2e::StrawDigiCollection);
std::unique_ptr<mu2e::StrawDigiADCWaveformCollection> straw_digi_adcs(new mu2e::StrawDigiADCWaveformCollection);
//FIXME! this is temporary
std::unique_ptr<mu2e::ProtonBunchTime> pbt(new mu2e::ProtonBunchTime);
pbt->pbtime_ = 0;
pbt->pbterr_ = 0;
event.put(std::move(pbt));
size_t totalSize = 0;
size_t numTrkFrags = 0;
std::vector<art::Handle<artdaq::Fragments>> fragmentHandles =
event.getMany<std::vector<artdaq::Fragment>>();
for (const auto& handle : fragmentHandles) {
if (!handle.isValid() || handle->empty()) {
continue;
}
if (handle->front().type() == mu2e::detail::FragmentType::MU2EEVENT) {
for (const auto& cont : *handle) {
mu2e::Mu2eEventFragment mef(cont);
for (size_t ii = 0; ii < mef.tracker_block_count(); ++ii) {
auto pair = mef.trackerAtPtr(ii);
mu2e::TrackerFragment cc(pair);
analyze_tracker_(cc, straw_digis, straw_digi_adcs);
totalSize += pair.second;
numTrkFrags++;
}
}
} else {
if (handle->front().type() == mu2e::detail::FragmentType::TRK) {
for (auto frag : *handle) {
mu2e::TrackerFragment cc(frag.dataBegin(), frag.dataSizeBytes());
analyze_tracker_(cc, straw_digis, straw_digi_adcs);
totalSize += frag.dataSizeBytes();
numTrkFrags++;
}
}
}
}
if (numTrkFrags == 0) {
std::cout << "[StrawRecoFromFragmnets::produce] found no Tracker fragments!"
<< std::endl;
event.put(std::move(straw_digis));
return;
}
if (diagLevel_ > 1) {
std::cout << std::dec << "Producer: Run " << event.run() << ", subrun " << event.subRun()
<< ", event " << eventNumber << " has " << std::endl;
std::cout << numTrkFrags << " TRK fragments. "<< std::endl;
std::cout << "Total Size: " << (int)totalSize << " bytes." << std::endl;
}
if (diagLevel_ > 0) {
std::cout << "mu2e::StrawRecoFromFragmnets::produce exiting eventNumber="
<< (int)(event.event()) << " / timestamp=" << (int)eventNumber << std::endl;
}
// Store the straw digis in the event
event.put(std::move(straw_digis));
if (useTrkADC_) {
event.put(std::move(straw_digi_adcs));
}
} // produce()
void art::StrawRecoFromFragmnets::analyze_tracker_(
const mu2e::TrackerFragment& cc, std::unique_ptr<mu2e::StrawDigiCollection> const& straw_digis,
std::unique_ptr<mu2e::StrawDigiADCWaveformCollection> const& straw_digi_adcs) {
if (diagLevel_ > 1) {
std::cout << std::endl;
std::cout << "TrackerFragment: ";
std::cout << "\tBlock Count: " << std::dec << cc.block_count() << std::endl;
std::cout << std::endl;
std::cout << "\t"
<< "====== Example Block Sizes ======" << std::endl;
for (size_t i = 0; i < 10; i++) {
if (i < cc.block_count()) {
std::cout << "\t" << i << "\t" << cc.blockSizeBytes(i) << std::endl;
}
}
std::cout << "\t"
<< "=========================" << std::endl;
}
for (size_t curBlockIdx = 0; curBlockIdx < cc.block_count(); curBlockIdx++) {
#if 0 // TODO: Review this code and update as necessary
if (diagLevel_ > 1) {
// Print binary contents the first 3 packets starting at the current position
// In the case of the tracker simulation, this will be the whole tracker
// DataBlock. In the case of the calorimeter, the number of data packets
// following the header packet is variable.
cc.printPacketAtByte(cc.blockIndexBytes(0) + 16 * (0 + 3 * curBlockIdx));
cc.printPacketAtByte(cc.blockIndexBytes(0) + 16 * (1 + 3 * curBlockIdx));
cc.printPacketAtByte(cc.blockIndexBytes(0) + 16 * (2 + 3 * curBlockIdx));
// Print out decimal values of 16 bit chunks of packet data
for (int i = hexShiftPrint; i >= 0; i--) {
std::cout << "0x" << std::hex << std::setw(4) << std::setfill('0') << (adc_t) * (pos + i)
<< std::dec << std::setw(0);
std::cout << " ";
}
std::cout << std::endl;
}
#endif
auto block = cc.dataAtBlockIndex(curBlockIdx);
if (block == nullptr) {
mf::LogError("StrawRecoFromFragmnets")
<< "Unable to retrieve block " << curBlockIdx << "!" << std::endl;
continue;
}
auto hdr = block->GetHeader();
if (diagLevel_ > 1) {
std::cout << "timestamp: " << static_cast<int>(hdr->GetEventWindowTag().GetEventWindowTag(true))
<< std::endl;
std::cout << "hdr->SubsystemID: " << static_cast<int>(hdr->GetSubsystemID()) << std::endl;
std::cout << "dtcID: " << static_cast<int>(hdr->GetID()) << std::endl;
std::cout << "rocID: " << static_cast<int>(hdr->GetLinkID()) << std::endl;
std::cout << "packetCount: " << static_cast<int>(hdr->GetPacketCount()) << std::endl;
std::cout << "EVB mode: " << static_cast<int>(hdr->GetEVBMode()) << std::endl;
std::cout << std::endl;
}
// Parse phyiscs information from TRK packets
if (hdr->GetPacketCount() > 0) {
// Create the StrawDigi data products
auto trkDataVec = cc.GetTrackerData(curBlockIdx, useTrkADC_);
if (trkDataVec.empty()) {
mf::LogError("StrawRecoFromFragmnets")
<< "Error retrieving Tracker data from DataBlock " << curBlockIdx
<< "! Aborting processing of this block!";
continue;
}
for (auto& trkDataPair : trkDataVec) {
mu2e::StrawId sid(trkDataPair.first->StrawIndex);
mu2e::TrkTypes::TDCValues tdc = {trkDataPair.first->TDC0(), trkDataPair.first->TDC1()};
mu2e::TrkTypes::TOTValues tot = {trkDataPair.first->TOT0, trkDataPair.first->TOT1};
mu2e::TrkTypes::ADCValue pmp = trkDataPair.first->PMP;
// Fill the StrawDigiCollection
straw_digis->emplace_back(sid, tdc, tot, pmp);
if (useTrkADC_){
straw_digi_adcs->emplace_back(trkDataPair.second);
}
if (diagLevel_ > 1) {
std::cout << "MAKEDIGI: " << sid.asUint16() << " " << tdc[0] << " " << tdc[1] << " "
<< tot[0] << " " << tot[1] << " ";
for (size_t i = 0; i < trkDataPair.second.size(); i++) {
std::cout << trkDataPair.second[i];
if (i < trkDataPair.second.size() - 1) {
std::cout << " ";
}
}
std::cout << std::endl;
std::cout << std::endl;
std::cout << "strawIdx: " << sid.asUint16() << std::endl;
std::cout << "TDC0: " << tdc[0] << std::endl;
std::cout << "TDC1: " << tdc[1] << std::endl;
std::cout << "TOT0: " << tot[0] << std::endl;
std::cout << "TOT1: " << tot[1] << std::endl;
std::cout << "PMP: " << pmp << std::endl;
std::cout << "Waveform: {";
for (size_t i = 0; i < trkDataPair.second.size(); i++) {
std::cout << trkDataPair.second[i];
if (i < trkDataPair.second.size() - 1) {
std::cout << ",";
}
}
std::cout << "}" << std::endl;
std::cout << "FPGA Flags: ";
for (size_t i = 8; i < 16; i++) {
if (((0x0001 << (15 - i)) & trkDataPair.first->ErrorFlags) > 0) {
std::cout << "1";
} else {
std::cout << "0";
}
}
std::cout << std::endl;
std::cout << "LOOP: " << hdr->GetEventWindowTag().GetEventWindowTag(true) << " "
<< curBlockIdx
<< std::endl;
// Text format: timestamp strawidx tdc0 tdc1 nsamples sample0-11
// Example: 1 1113 36978 36829 12 1423 1390 1411 1354 2373 2392 2342 2254 1909 1611 1525
// 1438
std::cout << "GREPMETRK: " << hdr->GetEventWindowTag().GetEventWindowTag(true) << " ";
std::cout << sid.asUint16() << " ";
std::cout << tdc[0] << " ";
std::cout << tdc[1] << " ";
std::cout << tot[0] << " ";
std::cout << tot[1] << " ";
std::cout << pmp << " ";
std::cout << trkDataPair.second.size() << " ";
for (size_t i = 0; i < trkDataPair.second.size(); i++) {
std::cout << trkDataPair.second[i];
if (i < trkDataPair.second.size() - 1) {
std::cout << " ";
}
}
std::cout << std::endl;
} // End debug output
}
}
}
//cc.ClearUpgradedPackets();
}
// ======================================================================
DEFINE_ART_MODULE(art::StrawRecoFromFragmnets)
// ======================================================================
| 36.03125 | 114 | 0.555334 | [
"vector"
] |
e913df40e9ed0f86a55581b8698de60b8ad1c6a3 | 6,612 | cpp | C++ | src/Create.cpp | youngslab/vkx | ba119ab7674f281e965e783bee59983b35fe04da | [
"MIT"
] | null | null | null | src/Create.cpp | youngslab/vkx | ba119ab7674f281e965e783bee59983b35fe04da | [
"MIT"
] | null | null | null | src/Create.cpp | youngslab/vkx | ba119ab7674f281e965e783bee59983b35fe04da | [
"MIT"
] | null | null | null |
#include "vkx/Object.hpp"
#include <vulkan/vulkan_core.h>
namespace vkx {
auto CreateInstance(const VkInstanceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, Instance *pObject)
-> VkResult {
return CreateObject<Instance>(pCreateInfo, pAllocator, pObject);
}
auto CreateWindow(int width, int height, const char *title, Window *pWindow)
-> VkResult {
return CreateObject<Window>(width, height, title, pWindow);
}
auto CreateDebugReportCallbackEXT(
Instance const &instance, const VkDebugReportCallbackCreateInfoEXT *pCreateInfo,
const VkAllocationCallbacks *pAllocator, DebugReportCallbackEXT *pCallback)
-> VkResult {
return CreateObject<DebugReportCallbackEXT>(instance, pCreateInfo, pAllocator,
pCallback);
}
auto CreateSurfaceKHR(Instance const &instance, Window const &window,
const VkAllocationCallbacks *allocator,
SurfaceKHR *surface) -> VkResult {
return CreateObject<SurfaceKHR>(instance, window, allocator, surface);
}
auto CreateDevice(VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, Device *pDevice)
-> VkResult {
return CreateObject<Device>(physicalDevice, pCreateInfo, pAllocator, pDevice);
}
auto CreateSwapchainKHR(Device const &device,
const VkSwapchainCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
SwapchainKHR *pSwapchain) -> VkResult {
return CreateObject<SwapchainKHR>(device, pCreateInfo, pAllocator,
pSwapchain);
}
auto CreateRenderPass(Device const &device, const VkRenderPassCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
RenderPass *pRenderPass) -> VkResult {
return CreateObject<RenderPass>(device, pCreateInfo, pAllocator, pRenderPass);
}
auto CreateDescriptorSetLayout(
Device const &device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, DescriptorSetLayout *pSetLayout)
-> VkResult {
return CreateObject<DescriptorSetLayout>(device, pCreateInfo, pAllocator,
pSetLayout);
}
auto CreatePipelineLayout(Device const &device,
const VkPipelineLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
PipelineLayout *pPipelineLayout) -> VkResult {
return CreateObject<PipelineLayout>(device, pCreateInfo, pAllocator,
pPipelineLayout);
}
auto CreateGraphicsPipelines(Device const &device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
Pipeline *pPipelines) -> VkResult {
auto res = VK_SUCCESS;
for (int i = 0; i < createInfoCount; i++) {
auto res = CreateObject<Pipeline>(device, pipelineCache, 1, &pCreateInfos[i],
pAllocator, &pPipelines[i]);
if (res != VK_SUCCESS)
return res;
}
return res;
}
auto CreateImage(Device const &device, const VkImageCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, Image *pImage)
-> VkResult {
return CreateObject<Image>(device, pCreateInfo, pAllocator, pImage);
}
auto CreateImageView(Device const &device, const VkImageViewCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, ImageView *pView)
-> VkResult {
return CreateObject<ImageView>(device, pCreateInfo, pAllocator, pView);
}
auto CreateFramebuffer(Device const &device,
const VkFramebufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
Framebuffer *pFramebuffer) -> VkResult {
return CreateObject<Framebuffer>(device, pCreateInfo, pAllocator,
pFramebuffer);
}
auto CreateCommandPool(Device const &device,
const VkCommandPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
CommandPool *pCommandPool) -> VkResult {
return CreateObject<CommandPool>(device, pCreateInfo, pAllocator,
pCommandPool);
}
auto CreateSampler(Device const &device, const VkSamplerCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, Sampler *pSampler)
-> VkResult {
return CreateObject<Sampler>(device, pCreateInfo, pAllocator, pSampler);
}
auto CreateBuffer(Device const &device, const VkBufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, Buffer *pBuffer)
-> VkResult {
return CreateObject<Buffer>(device, pCreateInfo, pAllocator, pBuffer);
}
auto CreateDescriptorPool(Device const &device,
const VkDescriptorPoolCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
DescriptorPool *pDescriptorPool) -> VkResult {
return CreateObject<DescriptorPool>(device, pCreateInfo, pAllocator,
pDescriptorPool);
}
auto CreateSemaphore(Device const &device, const VkSemaphoreCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
Semaphore *pSemaphore) -> VkResult {
return CreateObject<Semaphore>(device, pCreateInfo, pAllocator, pSemaphore);
}
auto CreateFence(Device const &device, const VkFenceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, Fence *pFence)
-> VkResult {
return CreateObject<Fence>(device, pCreateInfo, pAllocator, pFence);
}
auto AllocateCommandBuffers(Device const &device, CommandPool const &commandPool,
const VkCommandBufferAllocateInfo *pAllocateInfo,
CommandBuffer *pCommandBuffers) -> VkResult {
auto count = pAllocateInfo->commandBufferCount;
auto res = VK_SUCCESS;
auto info = *pAllocateInfo;
info.commandBufferCount = 1;
for (auto i = 0u; i < count; i++) {
res = CreateObject<CommandBuffer>(device, commandPool, &info,
&pCommandBuffers[i]);
if (res != VK_SUCCESS)
return res;
}
return res;
}
auto AllocateMemory(Device const &device, const VkMemoryAllocateInfo *pAllocateInfo,
const VkAllocationCallbacks *pAllocator,
DeviceMemory *pMemory) -> VkResult {
return CreateObject<DeviceMemory>(device, pAllocateInfo, pAllocator, pMemory);
}
auto AllocateDescriptorSets(Device const &device, DescriptorPool const &descriptorPool,
const VkDescriptorSetAllocateInfo *pAllocateInfo,
DescriptorSet *pDescriptorSets) -> VkResult {
auto count = pAllocateInfo->descriptorSetCount;
auto res = VK_SUCCESS;
auto info = *pAllocateInfo;
info.descriptorSetCount = 1;
for (auto i = 0u; i < count; i++) {
res = CreateObject<DescriptorSet>(device, descriptorPool, &info,
&pDescriptorSets[i]);
if (res != VK_SUCCESS)
return res;
}
return res;
}
} // namespace vkx
| 35.934783 | 87 | 0.747429 | [
"object"
] |
e919484f1fe8621ed48a682cb158da879455a294 | 7,349 | hpp | C++ | include/System/Runtime/Remoting/Messaging/IllogicalCallContext.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Runtime/Remoting/Messaging/IllogicalCallContext.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Runtime/Remoting/Messaging/IllogicalCallContext.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: Hashtable
class Hashtable;
}
// Completed forward declares
// Type namespace: System.Runtime.Remoting.Messaging
namespace System::Runtime::Remoting::Messaging {
// Forward declaring type: IllogicalCallContext
class IllogicalCallContext;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Runtime::Remoting::Messaging::IllogicalCallContext);
DEFINE_IL2CPP_ARG_TYPE(::System::Runtime::Remoting::Messaging::IllogicalCallContext*, "System.Runtime.Remoting.Messaging", "IllogicalCallContext");
// Type namespace: System.Runtime.Remoting.Messaging
namespace System::Runtime::Remoting::Messaging {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: System.Runtime.Remoting.Messaging.IllogicalCallContext
// [TokenAttribute] Offset: FFFFFFFF
class IllogicalCallContext : public ::Il2CppObject {
public:
public:
// private System.Collections.Hashtable m_Datastore
// Size: 0x8
// Offset: 0x10
::System::Collections::Hashtable* m_Datastore;
// Field size check
static_assert(sizeof(::System::Collections::Hashtable*) == 0x8);
// private System.Object m_HostContext
// Size: 0x8
// Offset: 0x18
::Il2CppObject* m_HostContext;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
public:
// Get instance field reference: private System.Collections.Hashtable m_Datastore
[[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& dyn_m_Datastore();
// Get instance field reference: private System.Object m_HostContext
[[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn_m_HostContext();
// private System.Collections.Hashtable get_Datastore()
// Offset: 0x106A13C
::System::Collections::Hashtable* get_Datastore();
// System.Object get_HostContext()
// Offset: 0x106A1A4
::Il2CppObject* get_HostContext();
// System.Void set_HostContext(System.Object value)
// Offset: 0x106A1AC
void set_HostContext(::Il2CppObject* value);
// System.Boolean get_HasUserData()
// Offset: 0x106A1B4
bool get_HasUserData();
// public System.Runtime.Remoting.Messaging.IllogicalCallContext CreateCopy()
// Offset: 0x106A1E4
::System::Runtime::Remoting::Messaging::IllogicalCallContext* CreateCopy();
// public System.Void .ctor()
// Offset: 0x106A45C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IllogicalCallContext* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::Remoting::Messaging::IllogicalCallContext::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IllogicalCallContext*, creationType>()));
}
}; // System.Runtime.Remoting.Messaging.IllogicalCallContext
#pragma pack(pop)
static check_size<sizeof(IllogicalCallContext), 24 + sizeof(::Il2CppObject*)> __System_Runtime_Remoting_Messaging_IllogicalCallContextSizeCheck;
static_assert(sizeof(IllogicalCallContext) == 0x20);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::IllogicalCallContext::get_Datastore
// Il2CppName: get_Datastore
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Hashtable* (System::Runtime::Remoting::Messaging::IllogicalCallContext::*)()>(&System::Runtime::Remoting::Messaging::IllogicalCallContext::get_Datastore)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::IllogicalCallContext*), "get_Datastore", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::IllogicalCallContext::get_HostContext
// Il2CppName: get_HostContext
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Runtime::Remoting::Messaging::IllogicalCallContext::*)()>(&System::Runtime::Remoting::Messaging::IllogicalCallContext::get_HostContext)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::IllogicalCallContext*), "get_HostContext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::IllogicalCallContext::set_HostContext
// Il2CppName: set_HostContext
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Messaging::IllogicalCallContext::*)(::Il2CppObject*)>(&System::Runtime::Remoting::Messaging::IllogicalCallContext::set_HostContext)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::IllogicalCallContext*), "set_HostContext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::IllogicalCallContext::get_HasUserData
// Il2CppName: get_HasUserData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Runtime::Remoting::Messaging::IllogicalCallContext::*)()>(&System::Runtime::Remoting::Messaging::IllogicalCallContext::get_HasUserData)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::IllogicalCallContext*), "get_HasUserData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::IllogicalCallContext::CreateCopy
// Il2CppName: CreateCopy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Remoting::Messaging::IllogicalCallContext* (System::Runtime::Remoting::Messaging::IllogicalCallContext::*)()>(&System::Runtime::Remoting::Messaging::IllogicalCallContext::CreateCopy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::IllogicalCallContext*), "CreateCopy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::IllogicalCallContext::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 56.968992 | 273 | 0.751395 | [
"object",
"vector"
] |
e9199024b392c19657395263812bbc66de937928 | 5,350 | cpp | C++ | src/fileformat/file_format/intel_hex/intel_hex_format.cpp | mehrdad-shokri/retdec | a82f16e97b163afe789876e0a819489c5b9b358e | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 1 | 2021-09-28T01:59:35.000Z | 2021-09-28T01:59:35.000Z | src/fileformat/file_format/intel_hex/intel_hex_format.cpp | mehrdad-shokri/retdec | a82f16e97b163afe789876e0a819489c5b9b358e | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | null | null | null | src/fileformat/file_format/intel_hex/intel_hex_format.cpp | mehrdad-shokri/retdec | a82f16e97b163afe789876e0a819489c5b9b358e | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | null | null | null | /**
* @file src/fileformat/file_format/intel_hex/intel_hex_format.cpp
* @brief Definition of IntelHexFormat class.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <algorithm>
#include <string>
#include "retdec/fileformat/file_format/intel_hex/intel_hex_format.h"
using namespace retdec::utils;
namespace retdec {
namespace fileformat {
/**
* Constructor
* @param pathToFile Path to input file
* @param loadFlags Load flags
*/
IntelHexFormat::IntelHexFormat(std::string pathToFile, LoadFlags loadFlags) : FileFormat(pathToFile, loadFlags)
{
initStructures();
}
/**
* Constructor
* @param inputStream Input stream
* @param loadFlags Load flags
*/
IntelHexFormat::IntelHexFormat(std::istream &inputStream, LoadFlags loadFlags) : FileFormat(inputStream, loadFlags)
{
initStructures();
}
/**
* Constructor
* @param data Input data.
* @param size Input data size.
* @param loadFlags Load flags
*/
IntelHexFormat::IntelHexFormat(const std::uint8_t *data, std::size_t size, LoadFlags loadFlags) :
FileFormat(data, size, loadFlags)
{
initStructures();
}
/**
* Init internal structures
*/
void IntelHexFormat::initStructures()
{
stateIsValid = parser.parseStream(fileStream);
if(stateIsValid)
{
fileFormat = Format::INTEL_HEX;
initializeSections();
computeSectionTableHashes();
loadStrings();
}
}
/**
* Copy sections from parser to @c IntelHexFormat representation
*/
void IntelHexFormat::initializeSections()
{
for(auto §ion : parser.sections)
{
auto *tmp = new Section;
tmp->setName("ihex_section_" + std::to_string(section.index));
tmp->setIndex(section.index);
tmp->setAddress(section.address);
tmp->setSizeInFile(section.data.size());
tmp->setSizeInMemory(section.data.size());
tmp->setMemory(true);
tmp->setType(tmp->belong(parser.getEntryPoint()) ? SecSeg::Type::CODE : SecSeg::Type::CODE_DATA);
sections.push_back(tmp);
}
std::sort(parser.sections.begin(), parser.sections.end());
std::sort(sections.begin(), sections.end(),
[] (const auto *a, const auto *b)
{
return a->getAddress() < b->getAddress();
}
);
unsigned long long EIP = 0;
if(parser.hasEntryPoint())
{
EIP = parser.getEntryPoint();
}
unsigned long long index = 0;
unsigned long long sectionOffset = 0;
for(const auto §ion : parser.sections)
{
// Fill vector with serialized data
serialized.insert(serialized.end(), section.data.begin(), section.data.end());
// Set serialized offset of section
sections[index]->setOffset(sectionOffset);
// Set EP offset
if(!epOffset && EIP && (EIP >= section.address && EIP < (section.address + section.data.size())))
{
epOffset = sectionOffset + (EIP - section.address);
}
sectionOffset += section.data.size();
++index;
}
setLoadedBytes(&serialized);
for(auto *section : sections)
{
section->load(this);
}
}
std::size_t IntelHexFormat::initSectionTableHashOffsets()
{
return 0;
}
retdec::utils::Endianness IntelHexFormat::getEndianness() const
{
return endianness;
}
std::size_t IntelHexFormat::getBytesPerWord() const
{
return bytesPerWord;
}
bool IntelHexFormat::hasMixedEndianForDouble() const
{
return false;
}
std::size_t IntelHexFormat::getDeclaredFileLength() const
{
return getLoadedFileLength();
}
bool IntelHexFormat::areSectionsValid() const
{
return true;
}
bool IntelHexFormat::isObjectFile() const
{
return false;
}
bool IntelHexFormat::isDll() const
{
return false;
}
bool IntelHexFormat::isExecutable() const
{
return true;
}
bool IntelHexFormat::getMachineCode(unsigned long long &result) const
{
// Intel HEX does not provide such information
return false;
}
bool IntelHexFormat::getAbiVersion(unsigned long long &result) const
{
// Intel HEX does not provide such information
return false;
}
bool IntelHexFormat::getImageBaseAddress(unsigned long long &imageBase) const
{
// Intel HEX does not provide such information
return false;
}
bool IntelHexFormat::getEpAddress(unsigned long long &result) const
{
if(parser.hasEntryPoint())
{
result = parser.getEntryPoint();
return true;
}
return false;
}
bool IntelHexFormat::getEpOffset(unsigned long long &epOffset) const
{
if(parser.hasEntryPoint())
{
epOffset = this->epOffset;
return true;
}
return false;
}
Architecture IntelHexFormat::getTargetArchitecture() const
{
return architecture;
}
std::size_t IntelHexFormat::getDeclaredNumberOfSections() const
{
return parser.sections.size();
}
std::size_t IntelHexFormat::getDeclaredNumberOfSegments() const
{
// No segments in Intel HEX
return 0;
}
std::size_t IntelHexFormat::getSectionTableOffset() const
{
return 0;
}
std::size_t IntelHexFormat::getSectionTableEntrySize() const
{
return 0;
}
std::size_t IntelHexFormat::getSegmentTableOffset() const
{
return 0;
}
std::size_t IntelHexFormat::getSegmentTableEntrySize() const
{
return 0;
}
/**
* Set target architecture
* @param a Target architecture
*/
void IntelHexFormat::setTargetArchitecture(Architecture a)
{
architecture = a;
}
/**
* Set endianness
* @param e Endianness
*/
void IntelHexFormat::setEndianness(retdec::utils::Endianness e)
{
endianness = e;
}
/**
* Set bytes per word
* @param b Bytes per word
*/
void IntelHexFormat::setBytesPerWord(std::size_t b)
{
bytesPerWord = b;
}
} // namespace fileformat
} // namespace retdec
| 19.669118 | 115 | 0.728785 | [
"vector"
] |
e91b4717941fd77aea869392ee09e4177e300c41 | 2,084 | cpp | C++ | Example/Visualization/TimerEvent/main.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 42 | 2015-07-24T23:05:07.000Z | 2022-03-16T01:31:04.000Z | Example/Visualization/TimerEvent/main.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 4 | 2015-03-17T05:42:49.000Z | 2020-08-09T15:21:45.000Z | Example/Visualization/TimerEvent/main.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 29 | 2015-01-03T05:56:32.000Z | 2021-10-05T15:28:33.000Z | /*****************************************************************************/
/**
* @file main.cpp
* @brief Example program for kvs::TimerEventListener.
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#include <kvs/Application>
#include <kvs/Screen>
#include <kvs/HydrogenVolumeData>
#include <kvs/Isosurface>
#include <kvs/EventListener>
#include <kvs/RotationMatrix33>
/*===========================================================================*/
/**
* @brief Main function.
* @param argc [i] argument counter
* @param argv [i] argument values
*/
/*===========================================================================*/
int main( int argc, char** argv )
{
kvs::Application app( argc, argv );
kvs::Screen screen( &app );
screen.setTitle( "Timer event" );
screen.create();
// Create object and renderer.
auto* volume = new kvs::HydrogenVolumeData( { 64, 64, 64 } );
auto* object = new kvs::Isosurface( volume, 100 );
delete volume;
screen.registerObject( object );
// Create event listener.
const int interval = 10; // animation time interval in milli-second.
kvs::EventListener event;
// Timer event
event.timerEvent( [&]( kvs::TimeEvent* e )
{
// Rotate the object.
const float D = 0.5f;
const auto R =
kvs::XRotationMatrix33<float>( D ) *
kvs::YRotationMatrix33<float>( D ) *
kvs::ZRotationMatrix33<float>( D );
object->multiplyXform( kvs::Xform::Rotation( R ) );
screen.redraw();
}, interval );
// Key press event
event.keyPressEvent( [&]( kvs::KeyEvent* e )
{
// t: toggle switch timer start and stop
switch ( e->key() )
{
case kvs::Key::t:
{
auto* t = event.eventTimer();
if ( t->isStopped() ) t->start();
else t->stop();
break;
}
default: break;
}
} );
screen.addEvent( &event );
return app.run();
}
| 28.162162 | 79 | 0.481766 | [
"object"
] |
11e779b83d0a87013b03eff15976b722c2597f6b | 10,482 | cpp | C++ | Source/core/inspector/InspectorProfilerAgent.cpp | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit | 20e637e67a0c272870ae4d78466a68bcb77af041 | [
"BSD-3-Clause"
] | null | null | null | Source/core/inspector/InspectorProfilerAgent.cpp | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit | 20e637e67a0c272870ae4d78466a68bcb77af041 | [
"BSD-3-Clause"
] | null | null | null | Source/core/inspector/InspectorProfilerAgent.cpp | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit | 20e637e67a0c272870ae4d78466a68bcb77af041 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/inspector/InspectorProfilerAgent.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptProfiler.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptHost.h"
#include "core/inspector/InspectorOverlay.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/ScriptProfile.h"
#include "core/frame/ConsoleTypes.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/StringConcatenate.h"
namespace WebCore {
namespace ProfilerAgentState {
static const char samplingInterval[] = "samplingInterval";
static const char userInitiatedProfiling[] = "userInitiatedProfiling";
static const char profilerEnabled[] = "profilerEnabled";
static const char nextProfileId[] = "nextProfileId";
}
static PassRefPtr<TypeBuilder::Profiler::CPUProfile> createCPUProfile(const ScriptProfile& scriptProfile)
{
RefPtr<TypeBuilder::Profiler::CPUProfile> profile = TypeBuilder::Profiler::CPUProfile::create()
.setHead(scriptProfile.buildInspectorObjectForHead())
.setStartTime(scriptProfile.startTime())
.setEndTime(scriptProfile.endTime());
profile->setSamples(scriptProfile.buildInspectorObjectForSamples());
profile->setTimestamps(scriptProfile.buildInspectorObjectForTimestamps());
return profile.release();
}
static PassRefPtr<TypeBuilder::Debugger::Location> currentDebugLocation(ScriptState* scriptState)
{
RefPtrWillBeRawPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(scriptState, 1));
const ScriptCallFrame& lastCaller = callStack->at(0);
RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
.setScriptId(lastCaller.scriptId())
.setLineNumber(lastCaller.lineNumber());
location->setColumnNumber(lastCaller.columnNumber());
return location.release();
}
class InspectorProfilerAgent::ProfileDescriptor {
public:
ProfileDescriptor(const String& id, const String& title)
: m_id(id)
, m_title(title) { }
String m_id;
String m_title;
};
PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
{
return adoptPtr(new InspectorProfilerAgent(injectedScriptManager, overlay));
}
InspectorProfilerAgent::InspectorProfilerAgent(InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
: InspectorBaseAgent<InspectorProfilerAgent>("Profiler")
, m_injectedScriptManager(injectedScriptManager)
, m_frontend(0)
, m_recordingCPUProfile(false)
, m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
, m_idleStartTime(0.0)
, m_overlay(overlay)
{
}
InspectorProfilerAgent::~InspectorProfilerAgent()
{
}
void InspectorProfilerAgent::consoleProfile(const String& title, ScriptState* scriptState)
{
ASSERT(m_frontend && enabled());
String id = nextProfileId();
m_startedProfiles.append(ProfileDescriptor(id, title));
ScriptProfiler::start(id);
m_frontend->consoleProfileStarted(id, currentDebugLocation(scriptState), title.isNull() ? 0 : &title);
}
void InspectorProfilerAgent::consoleProfileEnd(const String& title, ScriptState* scriptState)
{
ASSERT(m_frontend && enabled());
String id;
String resolvedTitle;
// Take last started profile if no title was passed.
if (title.isNull()) {
if (m_startedProfiles.isEmpty())
return;
id = m_startedProfiles.last().m_id;
resolvedTitle = m_startedProfiles.last().m_title;
m_startedProfiles.removeLast();
} else {
for (size_t i = 0; i < m_startedProfiles.size(); i++) {
if (m_startedProfiles[i].m_title == title) {
resolvedTitle = title;
id = m_startedProfiles[i].m_id;
m_startedProfiles.remove(i);
break;
}
}
if (id.isEmpty())
return;
}
RefPtrWillBeRawPtr<ScriptProfile> profile = ScriptProfiler::stop(id);
if (!profile)
return;
RefPtr<TypeBuilder::Debugger::Location> location = currentDebugLocation(scriptState);
m_frontend->consoleProfileFinished(id, location, createCPUProfile(*profile), resolvedTitle.isNull() ? 0 : &resolvedTitle);
}
void InspectorProfilerAgent::enable(ErrorString*)
{
m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
doEnable();
}
void InspectorProfilerAgent::doEnable()
{
m_instrumentingAgents->setInspectorProfilerAgent(this);
}
void InspectorProfilerAgent::disable(ErrorString*)
{
for (Vector<ProfileDescriptor>::reverse_iterator it = m_startedProfiles.rbegin(); it != m_startedProfiles.rend(); ++it)
ScriptProfiler::stop(it->m_id);
m_startedProfiles.clear();
stop(0, 0);
m_instrumentingAgents->setInspectorProfilerAgent(0);
m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
}
bool InspectorProfilerAgent::enabled()
{
return m_state->getBoolean(ProfilerAgentState::profilerEnabled);
}
void InspectorProfilerAgent::setSamplingInterval(ErrorString* error, int interval)
{
if (m_recordingCPUProfile) {
*error = "Cannot change sampling interval when profiling.";
return;
}
m_state->setLong(ProfilerAgentState::samplingInterval, interval);
ScriptProfiler::setSamplingInterval(interval);
}
void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
{
m_frontend = frontend->profiler();
}
void InspectorProfilerAgent::clearFrontend()
{
m_frontend = 0;
ErrorString error;
disable(&error);
m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
}
void InspectorProfilerAgent::restore()
{
if (m_state->getBoolean(ProfilerAgentState::profilerEnabled))
doEnable();
if (long interval = m_state->getLong(ProfilerAgentState::samplingInterval, 0))
ScriptProfiler::setSamplingInterval(interval);
if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling)) {
ErrorString error;
start(&error);
}
}
void InspectorProfilerAgent::start(ErrorString* error)
{
if (m_recordingCPUProfile)
return;
if (!enabled()) {
*error = "Profiler is not enabled";
return;
}
m_recordingCPUProfile = true;
if (m_overlay)
m_overlay->startedRecordingProfile();
m_frontendInitiatedProfileId = nextProfileId();
ScriptProfiler::start(m_frontendInitiatedProfileId);
m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
}
void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::CPUProfile>& profile)
{
stop(errorString, &profile);
}
void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::CPUProfile>* profile)
{
if (!m_recordingCPUProfile) {
if (errorString)
*errorString = "No recording profiles found";
return;
}
m_recordingCPUProfile = false;
if (m_overlay)
m_overlay->finishedRecordingProfile();
RefPtrWillBeRawPtr<ScriptProfile> scriptProfile = ScriptProfiler::stop(m_frontendInitiatedProfileId);
m_frontendInitiatedProfileId = String();
if (scriptProfile && profile)
*profile = createCPUProfile(*scriptProfile);
else if (errorString)
*errorString = "Profile wasn't found";
m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
}
String InspectorProfilerAgent::nextProfileId()
{
long nextId = m_state->getLong(ProfilerAgentState::nextProfileId, 1);
m_state->setLong(ProfilerAgentState::nextProfileId, nextId + 1);
return String::number(nextId);
}
void InspectorProfilerAgent::idleFinished()
{
if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
return;
ScriptProfiler::setIdle(false);
if (!m_idleStartTime)
return;
double idleTime = WTF::monotonicallyIncreasingTime() - m_idleStartTime;
m_idleStartTime = 0.0;
ProfileNameIdleTimeMap::iterator end = m_profileNameIdleTimeMap->end();
for (ProfileNameIdleTimeMap::iterator it = m_profileNameIdleTimeMap->begin(); it != end; ++it)
it->value += idleTime;
}
void InspectorProfilerAgent::idleStarted()
{
if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
return;
m_idleStartTime = WTF::monotonicallyIncreasingTime();
ScriptProfiler::setIdle(true);
}
void InspectorProfilerAgent::willProcessTask()
{
idleFinished();
}
void InspectorProfilerAgent::didProcessTask()
{
idleStarted();
}
void InspectorProfilerAgent::willEnterNestedRunLoop()
{
idleStarted();
}
void InspectorProfilerAgent::didLeaveNestedRunLoop()
{
idleFinished();
}
} // namespace WebCore
| 34.94 | 138 | 0.736119 | [
"vector"
] |
11ec05f38d915cda0f7bdf2293f4bcb29120ca28 | 112,768 | cpp | C++ | gdal/frmts/pds/vicardataset.cpp | elil/gdal | 589a058306d5d7019cf441c2b0dda6725b02fb21 | [
"MIT"
] | null | null | null | gdal/frmts/pds/vicardataset.cpp | elil/gdal | 589a058306d5d7019cf441c2b0dda6725b02fb21 | [
"MIT"
] | null | null | null | gdal/frmts/pds/vicardataset.cpp | elil/gdal | 589a058306d5d7019cf441c2b0dda6725b02fb21 | [
"MIT"
] | null | null | null | /******************************************************************************
*
* Project: VICAR Driver; JPL/MIPL VICAR Format
* Purpose: Implementation of VICARDataset
* Author: Sebastian Walter <sebastian dot walter at fu-berlin dot de>
*
* NOTE: This driver code is loosely based on the ISIS and PDS drivers.
* It is not intended to diminish the contribution of the original authors
******************************************************************************
* Copyright (c) 2014, Sebastian Walter <sebastian dot walter at fu-berlin dot de>
*
* 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.
****************************************************************************/
constexpr int NULL1 = 0;
constexpr int NULL2 = -32768;
constexpr double NULL3 = -32768.0;
#include "cpl_port.h"
#include "cpl_safemaths.hpp"
#include "cpl_vax.h"
#include "cpl_vsi_error.h"
#include "vicardataset.h"
#include "nasakeywordhandler.h"
#include "vicarkeywordhandler.h"
#include <exception>
#include <limits>
#include <string>
CPL_CVSID("$Id$")
/************************************************************************/
/* OGRVICARBinaryPrefixesLayer */
/************************************************************************/
class OGRVICARBinaryPrefixesLayer final: public OGRLayer
{
VSILFILE* m_fp = nullptr;
OGRFeatureDefn* m_poFeatureDefn = nullptr;
int m_iRecord = 0;
int m_nRecords = 0;
vsi_l_offset m_nFileOffset = 0;
vsi_l_offset m_nStride = 0;
bool m_bError = false;
bool m_bByteSwapIntegers = false;
RawRasterBand::ByteOrder m_eBREALByteOrder;
enum Type
{
FIELD_UNKNOWN,
FIELD_UNSIGNED_CHAR,
FIELD_UNSIGNED_SHORT,
FIELD_UNSIGNED_INT,
FIELD_SHORT,
FIELD_INT,
FIELD_FLOAT,
FIELD_DOUBLE,
};
static Type GetTypeFromString(const char* pszStr);
struct Field
{
int nOffset;
Type eType;
};
std::vector<Field> m_aoFields;
std::vector<GByte> m_abyRecord;
OGRFeature* GetNextRawFeature();
public:
OGRVICARBinaryPrefixesLayer(VSILFILE* fp, int nRecords,
const CPLJSONObject& oDef,
vsi_l_offset nFileOffset,
vsi_l_offset nStride,
RawRasterBand::ByteOrder eBINTByteOrder,
RawRasterBand::ByteOrder eBREALByteOrder);
~OGRVICARBinaryPrefixesLayer();
bool HasError() const { return m_bError; }
void ResetReading() override { m_iRecord = 0; }
OGRFeatureDefn* GetLayerDefn() override { return m_poFeatureDefn; }
OGRFeature* GetNextFeature() override;
int TestCapability(const char*) override { return false; }
};
/************************************************************************/
/* GetTypeFromString() */
/************************************************************************/
OGRVICARBinaryPrefixesLayer::Type
OGRVICARBinaryPrefixesLayer::GetTypeFromString(const char* pszStr)
{
if( EQUAL(pszStr, "unsigned char") || EQUAL(pszStr, "unsigned byte") )
return FIELD_UNSIGNED_CHAR;
if( EQUAL(pszStr, "unsigned short") )
return FIELD_UNSIGNED_SHORT;
if( EQUAL(pszStr, "unsigned int") )
return FIELD_UNSIGNED_INT;
if( EQUAL(pszStr, "short") )
return FIELD_SHORT;
if( EQUAL(pszStr, "int") )
return FIELD_INT;
if( EQUAL(pszStr, "float") )
return FIELD_FLOAT;
if( EQUAL(pszStr, "double") )
return FIELD_DOUBLE;
return FIELD_UNKNOWN;
}
/************************************************************************/
/* OGRVICARBinaryPrefixesLayer() */
/************************************************************************/
OGRVICARBinaryPrefixesLayer::OGRVICARBinaryPrefixesLayer(
VSILFILE* fp,
int nRecords,
const CPLJSONObject& oDef,
vsi_l_offset nFileOffset,
vsi_l_offset nStride,
RawRasterBand::ByteOrder eBINTByteOrder,
RawRasterBand::ByteOrder eBREALByteOrder):
m_fp(fp),
m_nRecords(nRecords),
m_nFileOffset(nFileOffset),
m_nStride(nStride),
#ifdef CPL_LSB
m_bByteSwapIntegers(eBINTByteOrder != RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN),
#else
m_bByteSwapIntegers(eBINTByteOrder != RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN),
#endif
m_eBREALByteOrder(eBREALByteOrder)
{
m_poFeatureDefn = new OGRFeatureDefn("binary_prefixes");
SetDescription(m_poFeatureDefn->GetName());
m_poFeatureDefn->Reference();
m_poFeatureDefn->SetGeomType(wkbNone);
int nRecordSize = oDef.GetInteger("size");
const auto oFields = oDef.GetObj("fields");
if( oFields.IsValid() && oFields.GetType() == CPLJSONObject::Type::Array )
{
auto oFieldsArray = oFields.ToArray();
int nOffset = 0;
for( int i = 0; i < oFieldsArray.Size(); i++ )
{
auto oField = oFieldsArray[i];
if( oField.GetType() == CPLJSONObject::Type::Object )
{
auto osName = oField.GetString("name");
auto osType = oField.GetString("type");
auto bHidden = oField.GetBool("hidden");
auto eType = GetTypeFromString(osType.c_str());
if( eType == FIELD_UNKNOWN )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Field %s of type %s not supported",
osName.c_str(), osType.c_str());
m_bError = true;
return;
}
else if( !osName.empty() )
{
OGRFieldType eFieldType(OFTMaxType);
Field f;
f.nOffset = nOffset;
f.eType = eType;
switch(eType)
{
case FIELD_UNSIGNED_CHAR: nOffset += 1; eFieldType = OFTInteger; break;
case FIELD_UNSIGNED_SHORT: nOffset += 2; eFieldType = OFTInteger; break;
case FIELD_UNSIGNED_INT: nOffset += 4; eFieldType = OFTInteger64; break;
case FIELD_SHORT: nOffset += 2; eFieldType = OFTInteger; break;
case FIELD_INT: nOffset += 4; eFieldType = OFTInteger; break;
case FIELD_FLOAT: nOffset += 4; eFieldType = OFTReal; break;
case FIELD_DOUBLE: nOffset += 8; eFieldType = OFTReal; break;
default: CPLAssert(false); break;
}
if( nOffset > nRecordSize )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Field definitions not consistent with declared record size");
m_bError = true;
return;
}
if( !bHidden )
{
m_aoFields.push_back(f);
OGRFieldDefn oFieldDefn(osName.c_str(), eFieldType);
m_poFeatureDefn->AddFieldDefn(&oFieldDefn);
}
}
else
{
m_bError = true;
}
}
else
{
m_bError = true;
}
if( m_bError )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Error while reading binary prefix definition");
return;
}
}
}
m_abyRecord.resize(nRecordSize);
}
/************************************************************************/
/* ~OGRVICARBinaryPrefixesLayer() */
/************************************************************************/
OGRVICARBinaryPrefixesLayer::~OGRVICARBinaryPrefixesLayer()
{
m_poFeatureDefn->Release();
}
/************************************************************************/
/* GetNextRawFeature() */
/************************************************************************/
OGRFeature* OGRVICARBinaryPrefixesLayer::GetNextRawFeature()
{
if( m_iRecord >= m_nRecords )
return nullptr;
if( VSIFSeekL(m_fp, m_nFileOffset + m_iRecord * m_nStride, SEEK_SET) != 0 ||
VSIFReadL(&m_abyRecord[0], m_abyRecord.size(), 1, m_fp) != 1 )
{
return nullptr;
}
OGRFeature* poFeature = new OGRFeature(m_poFeatureDefn);
for( int i = 0; i < poFeature->GetFieldCount(); i++ )
{
int nOffset = m_aoFields[i].nOffset;
switch( m_aoFields[i].eType )
{
case FIELD_UNSIGNED_CHAR:
poFeature->SetField(i, m_abyRecord[nOffset]);
break;
case FIELD_UNSIGNED_SHORT:
{
unsigned short v;
memcpy(&v, &m_abyRecord[nOffset], sizeof(v));
if( m_bByteSwapIntegers )
{
CPL_SWAP16PTR(&v);
}
poFeature->SetField(i, v);
break;
}
case FIELD_UNSIGNED_INT:
{
unsigned int v;
memcpy(&v, &m_abyRecord[nOffset], sizeof(v));
if( m_bByteSwapIntegers )
{
CPL_SWAP32PTR(&v);
}
poFeature->SetField(i, static_cast<GIntBig>(v));
break;
}
case FIELD_SHORT:
{
short v;
memcpy(&v, &m_abyRecord[nOffset], sizeof(v));
if( m_bByteSwapIntegers )
{
CPL_SWAP16PTR(&v);
}
poFeature->SetField(i, v);
break;
}
case FIELD_INT:
{
int v;
memcpy(&v, &m_abyRecord[nOffset], sizeof(v));
if( m_bByteSwapIntegers )
{
CPL_SWAP32PTR(&v);
}
poFeature->SetField(i, v);
break;
}
case FIELD_FLOAT:
{
float v;
memcpy(&v, &m_abyRecord[nOffset], sizeof(v));
if( m_eBREALByteOrder == RawRasterBand::ByteOrder::ORDER_VAX )
{
CPLVaxToIEEEFloat(&v);
}
else if( m_eBREALByteOrder !=
#ifdef CPL_LSB
RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN
#else
RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN
#endif
)
{
CPL_SWAP32PTR(&v);
}
poFeature->SetField(i, v);
break;
}
case FIELD_DOUBLE:
{
double v;
memcpy(&v, &m_abyRecord[nOffset], sizeof(v));
if( m_eBREALByteOrder == RawRasterBand::ByteOrder::ORDER_VAX )
{
CPLVaxToIEEEDouble(&v);
}
else if( m_eBREALByteOrder !=
#ifdef CPL_LSB
RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN
#else
RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN
#endif
)
{
CPL_SWAP64PTR(&v);
}
poFeature->SetField(i, v);
break;
}
default:
CPLAssert(false);
}
}
poFeature->SetFID(m_iRecord);
m_iRecord++;
return poFeature;
}
/************************************************************************/
/* GetNextFeature() */
/************************************************************************/
OGRFeature *OGRVICARBinaryPrefixesLayer::GetNextFeature()
{
while( true )
{
auto poFeature = GetNextRawFeature();
if (poFeature == nullptr)
return nullptr;
if((m_poFilterGeom == nullptr
|| FilterGeometry( poFeature->GetGeometryRef() ) )
&& (m_poAttrQuery == nullptr
|| m_poAttrQuery->Evaluate( poFeature )) )
{
return poFeature;
}
else
delete poFeature;
}
}
/************************************************************************/
/* VICARRawRasterBand */
/************************************************************************/
class VICARRawRasterBand final: public RawRasterBand
{
protected:
friend class VICARDataset;
public:
VICARRawRasterBand(
VICARDataset *poDSIn, int nBandIn, VSILFILE* fpRawIn,
vsi_l_offset nImgOffsetIn, int nPixelOffsetIn,
int nLineOffsetIn,
GDALDataType eDataTypeIn,
ByteOrder eByteOrderIn);
virtual CPLErr IReadBlock( int, int, void * ) override;
virtual CPLErr IWriteBlock( int, int, void * ) override;
virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int,
void *, int, int, GDALDataType,
GSpacing nPixelSpace, GSpacing nLineSpace,
GDALRasterIOExtraArg* psExtraArg ) override;
};
/************************************************************************/
/* VICARRawRasterBand() */
/************************************************************************/
VICARRawRasterBand::VICARRawRasterBand(
VICARDataset *poDSIn, int nBandIn, VSILFILE* fpRawIn,
vsi_l_offset nImgOffsetIn, int nPixelOffsetIn,
int nLineOffsetIn,
GDALDataType eDataTypeIn,
ByteOrder eByteOrderIn):
RawRasterBand(poDSIn, nBandIn, fpRawIn, nImgOffsetIn, nPixelOffsetIn, nLineOffsetIn,
eDataTypeIn, eByteOrderIn, RawRasterBand::OwnFP::NO)
{
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr VICARRawRasterBand::IReadBlock( int nXBlock, int nYBlock, void *pImage )
{
VICARDataset* poGDS = reinterpret_cast<VICARDataset*>(poDS);
if( !poGDS->m_bIsLabelWritten )
poGDS->WriteLabel();
return RawRasterBand::IReadBlock( nXBlock, nYBlock, pImage );
}
/************************************************************************/
/* IWriteBlock() */
/************************************************************************/
CPLErr VICARRawRasterBand::IWriteBlock( int nXBlock, int nYBlock,
void *pImage )
{
VICARDataset* poGDS = reinterpret_cast<VICARDataset*>(poDS);
if( !poGDS->m_bIsLabelWritten )
poGDS->WriteLabel();
return RawRasterBand::IWriteBlock( nXBlock, nYBlock, pImage );
}
/************************************************************************/
/* IRasterIO() */
/************************************************************************/
CPLErr VICARRawRasterBand::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 )
{
VICARDataset* poGDS = reinterpret_cast<VICARDataset*>(poDS);
if( !poGDS->m_bIsLabelWritten )
poGDS->WriteLabel();
return RawRasterBand::IRasterIO( eRWFlag,
nXOff, nYOff, nXSize, nYSize,
pData, nBufXSize, nBufYSize,
eBufType,
nPixelSpace, nLineSpace,
psExtraArg );
}
/************************************************************************/
/* VICARBASICRasterBand */
/************************************************************************/
class VICARBASICRasterBand final: public GDALPamRasterBand
{
public:
VICARBASICRasterBand(VICARDataset *poDSIn, int nBandIn,
GDALDataType eType);
virtual CPLErr IReadBlock( int, int, void * ) override;
virtual CPLErr IWriteBlock( int, int, void * ) override;
};
/************************************************************************/
/* VICARBASICRasterBand() */
/************************************************************************/
VICARBASICRasterBand::VICARBASICRasterBand(VICARDataset *poDSIn, int nBandIn,
GDALDataType eType)
{
poDS = poDSIn;
nBand = nBandIn;
nBlockXSize = poDSIn->GetRasterXSize();
nBlockYSize = 1;
eDataType = eType;
}
namespace
{
class DecodeEncodeException: public std::exception
{
public:
DecodeEncodeException() = default;
};
}
//////////////////////////////////////////////////////////////////////////
/// Below functions are adapted from Public Domain VICAR project
/// from https://github.com/nasa/VICAR/blob/master/vos/rtl/source/basic_compression.c
//////////////////////////////////////////////////////////////////////////
/* masking array used in the algorithm to take out bits in memory */
const unsigned int cod1mask[25] = {0x0,0x1,0x3,0x7,0xf,0x1f,
0x3f,0x7f,0xff,0x1ff,0x3ff,
0x7ff,0xfff,0x1fff,0x3fff,
0x7fff,0xffff,0x1ffff,
0x3ffff,0x7ffff,0xfffff,
0x1fffff,0x3fffff,0x7fffff,
0xffffff};
/*****************************************************/
/* This function is a helper function for the BASIC */
/* compression algorithm to get a specified number */
/* of bits from buffer, convert it to a number and */
/* return it. */
/*****************************************************/
static unsigned char grab1(int nbit,
const unsigned char* buffer,
size_t buffer_size,
size_t& buffer_pos,
int& bit1ptr) /* bit position in the current byte of encrypted or decrypted buffer*/
{
unsigned char val;
int shift = 8-nbit-(bit1ptr);
if( buffer_pos >= buffer_size )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Out of decoding buffer");
throw DecodeEncodeException();
}
if (shift>0)
{
val = (buffer[buffer_pos]>>shift) & cod1mask[nbit];
bit1ptr += nbit;
return val;
}
if (shift<0)
{
unsigned v1 = buffer[buffer_pos] & cod1mask[nbit+shift];
buffer_pos++;
if( buffer_pos >= buffer_size )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Out of decoding buffer");
throw DecodeEncodeException();
}
unsigned v2 = (buffer[buffer_pos]>>(8+shift)) & cod1mask[-shift];
val = static_cast<unsigned char>((v1<<(-shift))+v2);
bit1ptr = -shift;
return val;
}
val = buffer[buffer_pos] & cod1mask[nbit];
buffer_pos++;
bit1ptr = 0;
return val;
}
/*****************************************************/
/* This function is the decoding algorithm for BASIC */
/* compression. The encoded buffer is passed into */
/* code and the decoded buffer is passed out in buf. */
/*****************************************************/
static void basic_decode(const unsigned char* code,
size_t code_size,
unsigned char* buf,
int ns, int wid)
{
int runInt = -3;
unsigned char runChar;
unsigned int nval = 999999;
static const int cmprtrns1[7] = { -3, -2, -1, 0, 1, 2, 3 };
size_t buffer_pos = 0;
int bit1ptr = 0;
unsigned int old = 0;
const int ptop = ns*wid;
for(int iw = 0; iw < wid; iw++)
{
for (int ip=iw;ip<ptop;ip+=wid)
{
if (runInt>(-3))
{
buf[ip] = static_cast<unsigned char>(nval);
runInt--;
continue;
}
unsigned char val = grab1(3, code, code_size, buffer_pos, bit1ptr);
if (val<7)
{
nval = CPLUnsanitizedAdd<unsigned>(old,cmprtrns1[val]);
buf[ip] = static_cast<unsigned char>(nval);
old = nval;
continue;
}
val = grab1(1, code, code_size, buffer_pos, bit1ptr);
if (val)
{
runChar = grab1(4, code, code_size, buffer_pos, bit1ptr);
if (runChar==15)
{
runChar = grab1(8, code, code_size, buffer_pos, bit1ptr);
if (runChar==255)
{
unsigned char part0 = grab1(8, code, code_size, buffer_pos, bit1ptr);
unsigned char part1 = grab1(8, code, code_size, buffer_pos, bit1ptr);
unsigned char part2 = grab1(8, code, code_size, buffer_pos, bit1ptr);
runInt = part0 | (part1 << 8) | (part2 << 16);
}
else
runInt = runChar + 15;
}
else
runInt = runChar;
val = grab1(3, code, code_size, buffer_pos, bit1ptr);
if (val<7)
nval = CPLUnsanitizedAdd<unsigned>(old,cmprtrns1[val]);
else
nval = grab1(8, code, code_size, buffer_pos, bit1ptr);
buf[ip] = static_cast<unsigned char>(nval);
old = nval;
}
else
{
val = grab1(8, code, code_size, buffer_pos, bit1ptr);
buf[ip] = val;
old = val;
}
}
}
}
/*****************************************************/
/* This function is a helper function for the BASIC */
/* encoding operation. It puts the value in val into*/
/* memory location pointed by pcode1+reg1 into nbit */
/* number of bits. */
/*****************************************************/
static void emit1(unsigned char val, int nbit, unsigned char *reg1,
int& bit1ptr,
unsigned char* coded_buffer,
size_t& coded_buffer_pos,
size_t coded_buffer_size)
{
int shift;
shift = 8-nbit-bit1ptr;
if (shift>0)
{
*reg1 = static_cast<unsigned char>(*reg1|(val<<shift));
bit1ptr += nbit;
return;
}
if (shift<0)
{
if( coded_buffer_pos >= coded_buffer_size )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Out of encoding buffer");
throw DecodeEncodeException();
}
coded_buffer[coded_buffer_pos] = static_cast<unsigned char>(*reg1|(val>>(-shift)));
coded_buffer_pos++;
*reg1 = static_cast<unsigned char>(val<<(8+shift));
bit1ptr = -shift;
return;
}
if( coded_buffer_pos >= coded_buffer_size )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Out of encoding buffer");
throw DecodeEncodeException();
}
coded_buffer[coded_buffer_pos] = static_cast<unsigned char>(*reg1|val);
coded_buffer_pos++;
*reg1 = 0;
bit1ptr = 0;
}
/*****************************************************/
/* This function is meat of the BASIC encoding */
/* algorithm. This function is called repeatedly by */
/* the basic_encode function to compress the data */
/* according to its run length (run), last 2 */
/* different values (vold and old), and the current */
/* value (val), into the memory location pointed by */
/* pcode1+reg1. */
/*****************************************************/
static void basic_encrypt(int *run, int *old, int *vold, int val,
unsigned char *reg1,
int& bit1ptr,
unsigned char* coded_buffer,
size_t& coded_buffer_pos,
size_t coded_buffer_size)
{
if(*run<4)
{
if(abs(*old-*vold)<4)
emit1((unsigned char)(*old-*vold+3),3,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
else
{
emit1((unsigned char)14,4,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
emit1((unsigned char)(*old),8,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
}
while(*run>1)
{
emit1((unsigned char)3,3,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
(*run)--;
}
*vold = *old; *old = val;
}
else
{
emit1((unsigned char)15,4,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
if (*run<19)
{
emit1((unsigned char)(*run-4),4,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
}
else
{
emit1((unsigned char)15,4,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
if(*run<274)
{
emit1((char)(*run-19),8,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
}
else
{
emit1((unsigned char)255,8,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
unsigned char part0 = static_cast<unsigned char>((*run-4) & 0xff);
unsigned char part1 = static_cast<unsigned char>(((*run-4) >> 8) & 0xff);
unsigned char part2 = static_cast<unsigned char>(((*run-4) >> 16) & 0xff);
emit1(part0, 8, reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
emit1(part1, 8, reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
emit1(part2, 8, reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
}
}
if (abs(*old-*vold)<4)
{
emit1((unsigned char)(*old-*vold+3),3,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
}
else
{
emit1((unsigned char)7,3,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
emit1((unsigned char)(*old),8,reg1,bit1ptr,coded_buffer,coded_buffer_pos,coded_buffer_size);
}
*vold = *old; *old = val; *run = 1;
}
}
/*****************************************************/
/* This function loops through the data given by */
/* unencodedBuf, keeping track of run length. When */
/* the value of the data changes, it passes the run */
/* length, last 2 differing values, the current */
/* value, and the pointer in pcode1 buffer to encode */
/* the data into, to basic_encrypt function. */
/*****************************************************/
static void basic_encode(const unsigned char *unencodedBuf,
unsigned char *coded_buffer,
size_t coded_buffer_size,
int ns, int wid, size_t *totBytes)
{
int val = 0;
int bit1ptr=0;
const int ptop = ns*wid;
unsigned char reg1 = 0;
int run = 0;
int old = unencodedBuf[0];
int vold = 999999;
size_t coded_buffer_pos = 0;
for (int iw=0;iw<wid;iw++)
{
for (int ip=iw;ip<ptop;ip+=wid)
{
val = unencodedBuf[ip];
if (val==old) run++;
else
basic_encrypt(&run, &old, &vold, val, ®1, bit1ptr, coded_buffer, coded_buffer_pos, coded_buffer_size);
}
}
/* purge of last code */
basic_encrypt(&run, &old, &vold, val, ®1, bit1ptr, coded_buffer, coded_buffer_pos, coded_buffer_size);
if( coded_buffer_pos >= coded_buffer_size )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Out of encoding buffer");
throw DecodeEncodeException();
}
coded_buffer[coded_buffer_pos] = reg1;
*totBytes = coded_buffer_pos;
if(bit1ptr > 0) (*totBytes)++;
}
//////////////////////////////////////////////////////////////////////////
/// End of VICAR code
//////////////////////////////////////////////////////////////////////////
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr VICARBASICRasterBand::IReadBlock( int /*nXBlock*/, int nYBlock, void *pImage )
{
VICARDataset* poGDS = reinterpret_cast<VICARDataset*>(poDS);
const int nRecord = (nBand - 1) * nRasterYSize + nYBlock;
const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
if( poGDS->eAccess == GA_Update &&
poGDS->m_anRecordOffsets[nRecord+1] == 0 )
{
memset( pImage, 0, static_cast<size_t>(nDTSize) * nRasterXSize );
return CE_None;
}
// Find at which offset the compressed record is.
// For BASIC compression, each compressed run is preceded by a uint32 value
// givin its size, including the size of this uint32 value
// For BASIC2 compression, the uint32 sizes of all records are put
// immediately after the label.
for( ; poGDS->m_nLastRecordOffset <= nRecord;
poGDS->m_nLastRecordOffset++ )
{
CPLAssert( poGDS->m_anRecordOffsets[poGDS->m_nLastRecordOffset+1] == 0 );
if( poGDS->m_eCompress == VICARDataset::COMPRESS_BASIC )
{
VSIFSeekL( poGDS->fpImage,
poGDS->m_anRecordOffsets[
poGDS->m_nLastRecordOffset] - sizeof(GUInt32),
SEEK_SET );
}
else
{
VSIFSeekL( poGDS->fpImage,
poGDS->m_nImageOffsetWithoutNBB +
static_cast<vsi_l_offset>(sizeof(GUInt32)) *
poGDS->m_nLastRecordOffset,
SEEK_SET );
}
GUInt32 nSize;
VSIFReadL( &nSize, 1, sizeof(nSize), poGDS->fpImage);
CPL_LSBPTR32(&nSize);
if( (poGDS->m_eCompress == VICARDataset::COMPRESS_BASIC &&
nSize < sizeof(GUInt32)) ||
(poGDS->m_eCompress == VICARDataset::COMPRESS_BASIC2 &&
nSize == 0) )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Wrong size at record %d",
poGDS->m_nLastRecordOffset);
return CE_Failure;
}
poGDS->m_anRecordOffsets[poGDS->m_nLastRecordOffset+1] =
poGDS->m_anRecordOffsets[poGDS->m_nLastRecordOffset] + nSize;
}
unsigned int nSize;
if( poGDS->m_eCompress == VICARDataset::COMPRESS_BASIC )
{
nSize = static_cast<unsigned>(poGDS->m_anRecordOffsets[nRecord+1] -
poGDS->m_anRecordOffsets[nRecord] - sizeof(GUInt32));
}
else
{
nSize = static_cast<unsigned>(poGDS->m_anRecordOffsets[nRecord+1] -
poGDS->m_anRecordOffsets[nRecord]);
}
if( nSize > 100 * 1000 * 1000 ||
(nSize > 1000 && (nSize - 11) / 4 > static_cast<unsigned>(nRasterXSize) * nDTSize) )
{
return CE_Failure;
}
if( poGDS->m_abyCodedBuffer.size() < nSize )
{
try
{
poGDS->m_abyCodedBuffer.resize(nSize);
}
catch( const std::exception& e )
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what() );
return CE_Failure;
}
}
if( VSIFSeekL(poGDS->fpImage,
poGDS->m_anRecordOffsets[nRecord], SEEK_SET) != 0 ||
VSIFReadL(&poGDS->m_abyCodedBuffer[0], nSize, 1, poGDS->fpImage) != 1 )
{
CPLError(CE_Failure, CPLE_FileIO, "Cannot read record %d", nRecord);
return CE_Failure;
}
try
{
basic_decode(poGDS->m_abyCodedBuffer.data(), nSize,
static_cast<unsigned char*>(pImage),
nRasterXSize, nDTSize);
}
catch( const DecodeEncodeException& )
{
return CE_Failure;
}
return CE_None;
}
/************************************************************************/
/* IWriteBlock() */
/************************************************************************/
CPLErr VICARBASICRasterBand::IWriteBlock( int /*nXBlock*/, int nYBlock,
void *pImage )
{
VICARDataset* poGDS = reinterpret_cast<VICARDataset*>(poDS);
if( poGDS->eAccess == GA_ReadOnly )
return CE_Failure;
if( !poGDS->m_bIsLabelWritten )
{
poGDS->WriteLabel();
poGDS->m_nLabelSize = VSIFTellL(poGDS->fpImage);
poGDS->m_anRecordOffsets[0] = poGDS->m_nLabelSize;
if( poGDS->m_eCompress == VICARDataset::COMPRESS_BASIC )
{
poGDS->m_anRecordOffsets[0] += sizeof(GUInt32);
}
else
{
poGDS->m_anRecordOffsets[0] +=
static_cast<vsi_l_offset>(sizeof(GUInt32)) * nRasterYSize;
}
}
if( nYBlock != poGDS->m_nLastRecordOffset )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Lines must be written in sequential order");
return CE_Failure;
}
const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
const size_t nMaxEncodedSize =
static_cast<size_t>(nRasterXSize) * nDTSize + static_cast<size_t>(nRasterXSize) * nDTSize / 2 + 11;
if( poGDS->m_abyCodedBuffer.size() < nMaxEncodedSize )
{
try
{
poGDS->m_abyCodedBuffer.resize(nMaxEncodedSize);
}
catch( const std::exception& e )
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what() );
return CE_Failure;
}
}
size_t nCodedSize = 0;
try
{
basic_encode(static_cast<unsigned char *>(pImage),
&poGDS->m_abyCodedBuffer[0],
poGDS->m_abyCodedBuffer.size(),
nRasterXSize, nDTSize, &nCodedSize);
}
catch( const DecodeEncodeException& )
{
return CE_Failure;
}
if( poGDS->m_eCompress == VICARDataset::COMPRESS_BASIC )
{
VSIFSeekL(poGDS->fpImage, poGDS->m_anRecordOffsets[nYBlock] - sizeof(GUInt32), SEEK_SET);
GUInt32 nSizeToWrite = static_cast<GUInt32>(nCodedSize + sizeof(GUInt32));
CPL_LSBPTR32(&nSizeToWrite);
VSIFWriteL(&nSizeToWrite, sizeof(GUInt32), 1, poGDS->fpImage);
VSIFWriteL(poGDS->m_abyCodedBuffer.data(), nCodedSize, 1, poGDS->fpImage);
poGDS->m_anRecordOffsets[nYBlock + 1] = poGDS->m_anRecordOffsets[nYBlock] + nCodedSize + sizeof(GUInt32);
}
else
{
VSIFSeekL(poGDS->fpImage, poGDS->m_nLabelSize + static_cast<vsi_l_offset>(nYBlock) * sizeof(GUInt32), SEEK_SET);
GUInt32 nSizeToWrite = static_cast<GUInt32>(nCodedSize);
CPL_LSBPTR32(&nSizeToWrite);
VSIFWriteL(&nSizeToWrite, sizeof(GUInt32), 1, poGDS->fpImage);
VSIFSeekL(poGDS->fpImage, poGDS->m_anRecordOffsets[nYBlock], SEEK_SET);
VSIFWriteL(poGDS->m_abyCodedBuffer.data(), nCodedSize, 1, poGDS->fpImage);
poGDS->m_anRecordOffsets[nYBlock + 1] = poGDS->m_anRecordOffsets[nYBlock] + nCodedSize;
}
poGDS->m_nLastRecordOffset ++;
return CE_None;
}
/************************************************************************/
/* VICARDataset() */
/************************************************************************/
VICARDataset::VICARDataset()
{
m_oJSonLabel.Deinit();
m_oSrcJSonLabel.Deinit();
}
/************************************************************************/
/* ~VICARDataset() */
/************************************************************************/
VICARDataset::~VICARDataset()
{
if( !m_bIsLabelWritten )
WriteLabel();
VICARDataset::FlushCache();
PatchLabel();
if( fpImage != nullptr )
VSIFCloseL( fpImage );
}
/************************************************************************/
/* GetSpatialRef() */
/************************************************************************/
const OGRSpatialReference* VICARDataset::GetSpatialRef() const
{
if( !m_oSRS.IsEmpty() )
return &m_oSRS;
return GDALPamDataset::GetSpatialRef();
}
/************************************************************************/
/* SetSpatialRef() */
/************************************************************************/
CPLErr VICARDataset::SetSpatialRef( const OGRSpatialReference* poSRS )
{
if( eAccess == GA_ReadOnly )
return GDALPamDataset::SetSpatialRef( poSRS );
if( poSRS )
m_oSRS = *poSRS;
else
m_oSRS.Clear();
InvalidateLabel();
return CE_None;
}
/************************************************************************/
/* GetGeoTransform() */
/************************************************************************/
CPLErr VICARDataset::GetGeoTransform( double * padfTransform )
{
if( m_bGotTransform )
{
memcpy( padfTransform, &m_adfGeoTransform[0], sizeof(double) * 6 );
return CE_None;
}
return GDALPamDataset::GetGeoTransform( padfTransform );
}
/************************************************************************/
/* SetGeoTransform() */
/************************************************************************/
CPLErr VICARDataset::SetGeoTransform( double * padfTransform )
{
if( eAccess == GA_ReadOnly )
return GDALPamDataset::SetGeoTransform( padfTransform );
if( padfTransform[1] <= 0.0 || padfTransform[1] != -padfTransform[5] ||
padfTransform[2] != 0.0 || padfTransform[4] != 0.0 )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Only north-up geotransform with square pixels supported");
return CE_Failure;
}
m_bGotTransform = true;
memcpy( &m_adfGeoTransform[0], padfTransform, sizeof(double) * 6 );
InvalidateLabel();
return CE_None;
}
/************************************************************************/
/* GetLabelOffset() */
/************************************************************************/
int VICARDataset::GetLabelOffset( GDALOpenInfo * poOpenInfo )
{
if( poOpenInfo->pabyHeader == nullptr || poOpenInfo->fpL == nullptr )
return -1;
std::string osHeader;
const char *pszHeader = reinterpret_cast<const char *>(poOpenInfo->pabyHeader);
// Some PDS3 images include a VICAR header pointed by ^IMAGE_HEADER.
// If the user sets GDAL_TRY_PDS3_WITH_VICAR=YES, then we will gracefully
// hand over the file to the VICAR dataset.
vsi_l_offset nOffset = 0;
if( CPLTestBool(CPLGetConfigOption("GDAL_TRY_PDS3_WITH_VICAR", "NO")) &&
!STARTS_WITH(poOpenInfo->pszFilename, "/vsisubfile/") &&
(nOffset = VICARDataset::GetVICARLabelOffsetFromPDS3(pszHeader, poOpenInfo->fpL, osHeader)) > 0 )
{
pszHeader = osHeader.c_str();
}
if( (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
(poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 )
{
// If opening in vector-only mode, then check when have NBB != 0
const char* pszNBB = strstr(pszHeader, "NBB");
if( pszNBB == nullptr )
return -1;
const char* pszEqualSign = strchr(pszNBB, '=');
if( pszEqualSign == nullptr )
return -1;
if( atoi(pszEqualSign+1) == 0 )
return -1;
}
if( strstr(pszHeader, "LBLSIZE") != nullptr &&
strstr(pszHeader, "FORMAT") != nullptr &&
strstr(pszHeader, "NL") != nullptr &&
strstr(pszHeader, "NS") != nullptr &&
strstr(pszHeader, "NB") != nullptr )
{
return static_cast<int>(nOffset);
}
return -1;
}
/************************************************************************/
/* Identify() */
/************************************************************************/
int VICARDataset::Identify( GDALOpenInfo * poOpenInfo )
{
return GetLabelOffset(poOpenInfo) >= 0;
}
/************************************************************************/
/* GetRawBinaryLayout() */
/************************************************************************/
bool VICARDataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout& sLayout)
{
if( !RawDataset::GetRawBinaryLayout(sLayout) )
return false;
sLayout.osRawFilename = GetDescription();
return true;
}
/************************************************************************/
/* GetMetadataDomainList() */
/************************************************************************/
char **VICARDataset::GetMetadataDomainList()
{
return BuildMetadataDomainList(
nullptr, FALSE, "", "json:VICAR", nullptr);
}
/************************************************************************/
/* GetMetadata() */
/************************************************************************/
char **VICARDataset::GetMetadata( const char* pszDomain )
{
if( pszDomain != nullptr && EQUAL( pszDomain, "json:VICAR" ) )
{
if( m_aosVICARMD.empty() )
{
if( eAccess == GA_Update && !m_oJSonLabel.IsValid() )
{
BuildLabel();
}
CPLAssert( m_oJSonLabel.IsValid() );
const CPLString osJson = m_oJSonLabel.Format(CPLJSONObject::Pretty);
m_aosVICARMD.InsertString(0, osJson.c_str());
}
return m_aosVICARMD.List();
}
return GDALPamDataset::GetMetadata(pszDomain);
}
/************************************************************************/
/* InvalidateLabel() */
/************************************************************************/
void VICARDataset::InvalidateLabel()
{
m_oJSonLabel.Deinit();
m_aosVICARMD.Clear();
}
/************************************************************************/
/* SetMetadata() */
/************************************************************************/
CPLErr VICARDataset::SetMetadata( char** papszMD, const char* pszDomain )
{
if( m_bUseSrcLabel && eAccess == GA_Update && pszDomain != nullptr &&
EQUAL( pszDomain, "json:VICAR" ) )
{
m_oSrcJSonLabel.Deinit();
InvalidateLabel();
if( papszMD != nullptr && papszMD[0] != nullptr )
{
CPLJSONDocument oJSONDocument;
const GByte *pabyData = reinterpret_cast<const GByte *>(papszMD[0]);
if( !oJSONDocument.LoadMemory( pabyData ) )
{
return CE_Failure;
}
m_oSrcJSonLabel = oJSONDocument.GetRoot();
if( !m_oSrcJSonLabel.IsValid() )
{
return CE_Failure;
}
}
return CE_None;
}
return GDALPamDataset::SetMetadata(papszMD, pszDomain);
}
/************************************************************************/
/* SerializeString() */
/************************************************************************/
static std::string SerializeString(const std::string& s)
{
return '\'' + CPLString(s).replaceAll('\'', "''").replaceAll('\n', "\\n") + '\'';
}
/************************************************************************/
/* WriteLabelItemValue() */
/************************************************************************/
static void WriteLabelItemValue(std::string& osLabel,
const CPLJSONObject& obj)
{
const auto eType(obj.GetType());
if( eType == CPLJSONObject::Type::Boolean )
{
osLabel += CPLSPrintf("%d", obj.ToBool() ? 1 : 0);
}
else if( eType == CPLJSONObject::Type::Integer )
{
osLabel += CPLSPrintf("%d", obj.ToInteger());
}
else if( eType == CPLJSONObject::Type::Long )
{
std::string osVal(CPLSPrintf("%.18g",
static_cast<double>(obj.ToLong())));
if( osVal.find('.') == std::string::npos )
osVal += ".0";
osLabel += osVal;
}
else if( eType == CPLJSONObject::Type::Double )
{
double dfVal = obj.ToDouble();
if( dfVal >= static_cast<double>(std::numeric_limits<GIntBig>::min()) &&
dfVal <= static_cast<double>(std::numeric_limits<GIntBig>::max()) &&
static_cast<double>(static_cast<GIntBig>(dfVal)) == dfVal )
{
std::string osVal(CPLSPrintf("%.18g", dfVal));
if( osVal.find('.') == std::string::npos )
osVal += ".0";
osLabel += osVal;
}
else
{
osLabel += CPLSPrintf("%.15g", dfVal);
}
}
else if ( eType == CPLJSONObject::Type::String )
{
osLabel += SerializeString(obj.ToString());
}
else if ( eType == CPLJSONObject::Type::Array )
{
const auto oArray = obj.ToArray();
osLabel += '(';
for( int i = 0; i < oArray.Size(); i++ )
{
if( i > 0 )
osLabel += ',';
WriteLabelItemValue(osLabel, oArray[i]);
}
osLabel += ')';
}
else if ( eType == CPLJSONObject::Type::Null )
{
osLabel += "'NULL'";
}
else
{
osLabel += SerializeString(obj.Format(CPLJSONObject::Plain));
}
}
/************************************************************************/
/* SanitizeItemName() */
/************************************************************************/
static std::string SanitizeItemName(const std::string& osItemName)
{
std::string osRet(osItemName);
if( osRet.size() > 32 )
osRet.resize(32);
if( osRet.empty() )
return "UNNAMED";
if( osRet[0] < 'A' || osRet[0] > 'Z' )
osRet[0] = 'X'; // item name must start with a letter
for( size_t i = 1; i < osRet.size(); i++ )
{
char ch = osRet[i];
if( ch >= 'a' && ch <= 'z' )
osRet[i] = ch - 'a' + 'A';
else if( !((ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '_') )
{
osRet[i] = '_';
}
}
if( osRet != osItemName )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Label item name %s has been sanitized to %s",
osItemName.c_str(), osRet.c_str());
}
return osRet;
}
/************************************************************************/
/* WriteLabelItem() */
/************************************************************************/
static void WriteLabelItem(std::string& osLabel,
const CPLJSONObject& obj,
const std::string& osItemName = std::string())
{
osLabel += ' ';
osLabel += SanitizeItemName(osItemName.empty() ? obj.GetName() : osItemName);
osLabel += '=';
WriteLabelItemValue(osLabel, obj);
}
/************************************************************************/
/* WriteLabel() */
/************************************************************************/
void VICARDataset::WriteLabel()
{
m_bIsLabelWritten = true;
if( !m_oJSonLabel.IsValid() )
BuildLabel();
std::string osLabel;
auto children = m_oJSonLabel.GetChildren();
for( const auto& child: children )
{
const auto osName(child.GetName());
if( osName == "LBLSIZE" || osName == "PROPERTY" || osName == "TASK" )
continue;
std::string osNameSubst;
if( osName == "DAT_TIM" || osName == "USER" )
{
osNameSubst = osName + '_';
}
WriteLabelItem(osLabel, child, osNameSubst);
}
auto property = m_oJSonLabel.GetObj("PROPERTY");
if( property.IsValid() && property.GetType() == CPLJSONObject::Type::Object )
{
children = property.GetChildren();
for( const auto& child: children )
{
if( child.GetType() == CPLJSONObject::Type::Object )
{
osLabel += " PROPERTY=" + SerializeString(child.GetName());
auto childrenProperty = child.GetChildren();
for( const auto& childProperty: childrenProperty )
{
const auto osName(child.GetName());
std::string osNameSubst;
if( osName == "LBLSIZE" || osName == "PROPERTY" ||
osName == "TASK" || osName == "DAT_TIM" || osName == "USER" )
{
osNameSubst = osName + '_';
}
WriteLabelItem(osLabel, childProperty, osNameSubst);
}
}
}
}
auto task = m_oJSonLabel.GetObj("TASK");
if( task.IsValid() && task.GetType() == CPLJSONObject::Type::Object )
{
children = task.GetChildren();
for( const auto& child: children )
{
if( child.GetType() == CPLJSONObject::Type::Object )
{
osLabel += " TASK=" + SerializeString(child.GetName());
auto oUser = child.GetObj("USER");
if( oUser.IsValid() )
WriteLabelItem(osLabel, oUser);
auto oDatTim = child.GetObj("DAT_TIM");
if( oDatTim.IsValid() )
WriteLabelItem(osLabel, oDatTim);
auto childrenProperty = child.GetChildren();
for( const auto& childProperty: childrenProperty )
{
const auto osName(child.GetName());
if( osName == "USER" || osName == "DAT_TIM" )
continue;
std::string osNameSubst;
if( osName == "LBLSIZE" || osName == "PROPERTY" ||
osName == "TASK" )
{
osNameSubst = osName + '_';
}
WriteLabelItem(osLabel, childProperty, osNameSubst);
}
}
}
}
// Figure out label size, round it to the next multiple of RECSIZE
constexpr size_t MAX_LOG10_LBLSIZE = 10;
size_t nLabelSize = strlen("LBLSIZE=") + MAX_LOG10_LBLSIZE + osLabel.size();
nLabelSize =
(nLabelSize + m_nRecordSize - 1) / m_nRecordSize * m_nRecordSize;
std::string osLabelSize(CPLSPrintf("LBLSIZE=%d", static_cast<int>(nLabelSize)));
while( osLabelSize.size() < strlen("LBLSIZE=") + MAX_LOG10_LBLSIZE )
osLabelSize += ' ';
osLabel = osLabelSize + osLabel;
CPLAssert( osLabel.size() <= nLabelSize );
// Write label
VSIFSeekL(fpImage, 0, SEEK_SET);
VSIFWriteL(osLabel.data(), 1, osLabel.size(), fpImage);
const size_t nZeroPadding = nLabelSize - osLabel.size();
if( nZeroPadding )
{
VSIFWriteL(std::string(nZeroPadding, '\0').data(),
1, nZeroPadding, fpImage);
}
if( m_bInitToNodata && m_eCompress == COMPRESS_NONE )
{
const int nDTSize = GDALGetDataTypeSizeBytes(GetRasterBand(1)->GetRasterDataType());
VSIFTruncateL( fpImage, VSIFTellL(fpImage) +
static_cast<vsi_l_offset>(nRasterXSize) * nRasterYSize * nBands * nDTSize );
}
// Patch band offsets to take into account label
for( int i = 0; i < nBands; i++ )
{
auto poBand = dynamic_cast<VICARRawRasterBand*>(GetRasterBand(i+1));
if( poBand )
poBand->nImgOffset += nLabelSize;
}
}
/************************************************************************/
/* PatchLabel() */
/************************************************************************/
void VICARDataset::PatchLabel()
{
if( eAccess == GA_ReadOnly || m_eCompress == COMPRESS_NONE )
return;
VSIFSeekL(fpImage, 0, SEEK_END);
const vsi_l_offset nFileSize = VSIFTellL(fpImage);
VSIFSeekL(fpImage, 0, SEEK_SET);
std::string osBuffer;
osBuffer.resize(1024);
size_t nRead = VSIFReadL(&osBuffer[0], 1, 1024, fpImage);
{
CPLString osEOCI1;
osEOCI1.Printf("%u", static_cast<unsigned>(nFileSize));
while( osEOCI1.size() < 10 )
osEOCI1 += ' ';
size_t nPos = osBuffer.find("EOCI1=");
CPLAssert(nPos <= nRead - (strlen("EOCI1=") + 10));
memcpy(&osBuffer[nPos + strlen("EOCI1=")], osEOCI1.data(), 10);
}
{
CPLString osEOCI2;
osEOCI2.Printf("%u", static_cast<unsigned>(nFileSize >> 32));
while( osEOCI2.size() < 10 )
osEOCI2 += ' ';
size_t nPos = osBuffer.find("EOCI2=");
CPLAssert(nPos <= nRead - (strlen("EOCI2=") + 10));
memcpy(&osBuffer[nPos + strlen("EOCI2=")], osEOCI2.data(), 10);
}
VSIFSeekL(fpImage, 0, SEEK_SET);
VSIFWriteL(&osBuffer[0], 1, nRead, fpImage);
}
/**
* Get or create CPLJSONObject.
* @param oParent Parent CPLJSONObject.
* @param osKey Key name.
* @return CPLJSONObject class instance.
*/
static CPLJSONObject GetOrCreateJSONObject(CPLJSONObject &oParent,
const std::string &osKey)
{
CPLJSONObject oChild = oParent[osKey];
if( oChild.IsValid() && oChild.GetType() != CPLJSONObject::Object )
{
oParent.Delete( osKey );
oChild.Deinit();
}
if( !oChild.IsValid() )
{
oChild = CPLJSONObject();
oParent.Add( osKey, oChild );
}
return oChild;
}
/************************************************************************/
/* BuildLabel() */
/************************************************************************/
void VICARDataset::BuildLabel()
{
CPLJSONObject oLabel = m_oSrcJSonLabel;
if( !oLabel.IsValid() )
{
oLabel = CPLJSONObject();
}
oLabel.Set("LBLSIZE", 0); // to be overridden later
if( !oLabel.GetObj("TYPE").IsValid() )
oLabel.Set("TYPE", "IMAGE");
const auto eType = GetRasterBand(1)->GetRasterDataType();
const char* pszFormat = "";
switch( eType )
{
case GDT_Byte: pszFormat = "BYTE"; break;
case GDT_Int16: pszFormat = "HALF"; break;
case GDT_Int32: pszFormat = "FULL"; break;
case GDT_Float32: pszFormat = "REAL"; break;
case GDT_Float64: pszFormat = "DOUB"; break;
case GDT_CFloat32: pszFormat = "COMP"; break;
default: CPLAssert(false); break;
}
oLabel.Set("FORMAT", pszFormat);
oLabel.Set("BUFSIZ", m_nRecordSize); // arbitrary value
oLabel.Set("DIM", 3);
oLabel.Set("EOL", 0);
oLabel.Set("RECSIZE", m_nRecordSize);
oLabel.Set("ORG", "BSQ");
oLabel.Set("NL", nRasterYSize);
oLabel.Set("NS", nRasterXSize);
oLabel.Set("NB", nBands);
oLabel.Set("N1", nRasterXSize);
oLabel.Set("N2", nRasterYSize);
oLabel.Set("N3", nBands);
oLabel.Set("N4", 0);
oLabel.Set("NBB", 0);
oLabel.Set("NLB", 0);
oLabel.Set("HOST", "X86-64-LINX");
oLabel.Set("INTFMT", "LOW");
oLabel.Set("REALFMT", "RIEEE");
oLabel.Set("BHOST", "X86-64-LINX");
oLabel.Set("BINTFMT", "LOW");
if( !oLabel.GetObj("BLTYPE").IsValid() )
oLabel.Set("BLTYPE", "");
oLabel.Set("COMPRESS", m_eCompress == COMPRESS_BASIC ? "BASIC":
m_eCompress == COMPRESS_BASIC2 ? "BASIC2": "NONE");
if( m_eCompress == COMPRESS_NONE )
{
oLabel.Set("EOCI1", 0);
oLabel.Set("EOCI2", 0);
}
else
{
// To be later patched. Those fake values must take 10 bytes
// (8 + 2 single quotes) so that they can be later replaced by a
// integer of maximum value 4294967295 (10 digits)
oLabel.Set("EOCI1", "XXXXXXXX");
oLabel.Set("EOCI2", "XXXXXXXX");
}
if( m_bUseSrcMap )
{
auto oMap = oLabel.GetObj("PROPERTY/MAP");
if( oMap.IsValid() &&
oMap.GetType() == CPLJSONObject::Object )
{
if( !m_osTargetName.empty() )
oMap.Set( "TARGET_NAME", m_osTargetName );
if( !m_osLatitudeType.empty() )
oMap.Set( "COORDINATE_SYSTEM_NAME", m_osLatitudeType );
if( !m_osLongitudeDirection.empty() )
oMap.Set( "POSITIVE_LONGITUDE_DIRECTION", m_osLongitudeDirection );
}
}
else
{
auto oProperty = oLabel.GetObj("PROPERTY");
if( oProperty.IsValid() )
{
oProperty.Delete( "MAP" );
}
if( !m_oSRS.IsEmpty() )
{
if( m_oSRS.IsProjected() || m_oSRS.IsGeographic() )
{
oProperty = GetOrCreateJSONObject(oLabel, "PROPERTY");
auto oMap = GetOrCreateJSONObject(oProperty, "MAP");
const char* pszDatum = m_oSRS.GetAttrValue("DATUM");
CPLString osTargetName( m_osTargetName );
if( osTargetName.empty() )
{
if( pszDatum && STARTS_WITH(pszDatum, "D_") )
{
osTargetName = pszDatum + 2;
}
else if( pszDatum )
{
osTargetName = pszDatum;
}
}
if( !osTargetName.empty() )
oMap.Add( "TARGET_NAME", osTargetName );
oMap.Add( "A_AXIS_RADIUS", m_oSRS.GetSemiMajor() / 1000.0 );
oMap.Add( "B_AXIS_RADIUS", m_oSRS.GetSemiMajor() / 1000.0 );
oMap.Add( "C_AXIS_RADIUS", m_oSRS.GetSemiMinor() / 1000.0 );
if( !m_osLatitudeType.empty() )
oMap.Add( "COORDINATE_SYSTEM_NAME", m_osLatitudeType );
else
oMap.Add( "COORDINATE_SYSTEM_NAME", "PLANETOCENTRIC" );
if( !m_osLongitudeDirection.empty() )
oMap.Add( "POSITIVE_LONGITUDE_DIRECTION", m_osLongitudeDirection );
else
oMap.Add( "POSITIVE_LONGITUDE_DIRECTION", "EAST" );
const char* pszProjection = m_oSRS.GetAttrValue("PROJECTION");
if( pszProjection == nullptr )
{
oMap.Add( "MAP_PROJECTION_TYPE", "SIMPLE_CYLINDRICAL" );
oMap.Add( "CENTER_LONGITUDE", 0.0 );
oMap.Add( "CENTER_LATITUDE", 0.0 );
}
else if( EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR) )
{
oMap.Add( "MAP_PROJECTION_TYPE", "EQUIRECTANGULAR" );
if( m_oSRS.GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 )
!= 0.0 )
{
CPLError(CE_Warning, CPLE_NotSupported,
"Ignoring %s. Only 0 value supported",
SRS_PP_LATITUDE_OF_ORIGIN);
}
oMap.Add( "CENTER_LONGITUDE",
m_oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0) );
const double dfCenterLat =
m_oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0);
oMap.Add( "CENTER_LATITUDE", dfCenterLat );
}
else if( EQUAL(pszProjection, SRS_PT_SINUSOIDAL) )
{
oMap.Add( "MAP_PROJECTION_TYPE", "SINUSOIDAL" );
oMap.Add( "CENTER_LONGITUDE",
m_oSRS.GetNormProjParm(SRS_PP_LONGITUDE_OF_CENTER, 0.0) );
oMap.Add( "CENTER_LATITUDE", 0.0 );
}
else
{
CPLError(CE_Warning, CPLE_NotSupported,
"Projection %s not supported",
pszProjection);
}
if( oMap["MAP_PROJECTION_TYPE"].IsValid() )
{
if( m_oSRS.GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ) != 0.0 )
{
CPLError(CE_Warning, CPLE_NotSupported,
"Ignoring %s. Only 0 value supported",
SRS_PP_FALSE_EASTING);
}
if( m_oSRS.GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ) != 0.0 )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Ignoring %s. Only 0 value supported",
SRS_PP_FALSE_NORTHING);
}
if( m_bGotTransform )
{
const double dfDegToMeter = m_oSRS.GetSemiMajor() * M_PI / 180.0;
if( m_oSRS.IsProjected() )
{
const double dfLinearUnits = m_oSRS.GetLinearUnits();
const double dfScale = m_adfGeoTransform[1] * dfLinearUnits;
oMap.Add( "SAMPLE_PROJECTION_OFFSET", -m_adfGeoTransform[0] * dfLinearUnits / dfScale - 0.5 );
oMap.Add( "LINE_PROJECTION_OFFSET", m_adfGeoTransform[3] * dfLinearUnits / dfScale - 0.5 );
oMap.Add( "MAP_SCALE", dfScale / 1000.0 );
}
else if( m_oSRS.IsGeographic() )
{
const double dfScale = m_adfGeoTransform[1] * dfDegToMeter;
oMap.Add( "SAMPLE_PROJECTION_OFFSET", -m_adfGeoTransform[0] * dfDegToMeter / dfScale - 0.5 );
oMap.Add( "LINE_PROJECTION_OFFSET", m_adfGeoTransform[3] * dfDegToMeter / dfScale - 0.5 );
oMap.Add( "MAP_SCALE", dfScale / 1000.0 );
}
}
}
}
else
{
CPLError(CE_Warning, CPLE_NotSupported,
"SRS not supported");
}
}
}
m_oJSonLabel = oLabel;
}
/************************************************************************/
/* Open() */
/************************************************************************/
GDALDataset *VICARDataset::Open( GDALOpenInfo * poOpenInfo )
{
/* -------------------------------------------------------------------- */
/* Does this look like a VICAR dataset? */
/* -------------------------------------------------------------------- */
const int nLabelOffset = GetLabelOffset( poOpenInfo );
if( nLabelOffset < 0 )
return nullptr;
if( nLabelOffset > 0 )
{
CPLString osSubFilename;
osSubFilename.Printf("/vsisubfile/%d,%s",
nLabelOffset,
poOpenInfo->pszFilename);
GDALOpenInfo oOpenInfo(osSubFilename.c_str(), poOpenInfo->eAccess);
return Open(&oOpenInfo);
}
VICARDataset *poDS = new VICARDataset();
poDS->fpImage = poOpenInfo->fpL;
poOpenInfo->fpL = nullptr;
if( ! poDS->oKeywords.Ingest( poDS->fpImage, poOpenInfo->pabyHeader ) ) {
delete poDS;
return nullptr;
}
/************ CHECK INSTRUMENT/DATA *****************/
bool bIsDTM = false;
const char* value = poDS->GetKeyword( "DTM.DTM_OFFSET" );
if (!EQUAL(value,"") ) {
bIsDTM = true;
}
bool bInstKnown = false;
// Check for HRSC
if ( EQUAL(poDS->GetKeyword("BLTYPE"),"M94_HRSC") )
bInstKnown = true;
// Check for Framing Camera on Dawn
else if ( EQUAL(poDS->GetKeyword("INSTRUMENT_ID"),"FC2") )
bInstKnown = true;
/************ Grab dimensions *****************/
const int nCols = atoi(poDS->GetKeyword("NS"));
const int nRows = atoi(poDS->GetKeyword("NL"));
const int nBands = atoi(poDS->GetKeyword("NB"));
if( !GDALCheckDatasetDimensions(nCols, nRows) ||
!GDALCheckBandCount(nBands, false) )
{
CPLError( CE_Failure, CPLE_AppDefined,
"File %s appears to be a VICAR file, but failed to find some "
"required keywords.",
poOpenInfo->pszFilename );
delete poDS;
return nullptr;
}
const GDALDataType eDataType = GetDataTypeFromFormat(poDS->GetKeyword( "FORMAT" ));
if( eDataType == GDT_Unknown )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Could not find known VICAR label entries!\n");
delete poDS;
return nullptr;
}
double dfNoData = 0.0;
if (eDataType == GDT_Byte) {
dfNoData = NULL1;
}
else if (eDataType == GDT_Int16) {
dfNoData = NULL2;
}
else if (eDataType == GDT_Float32) {
dfNoData = NULL3;
}
/***** CHECK ENDIANNESS **************/
RawRasterBand::ByteOrder eByteOrder = RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN;
if( GDALDataTypeIsInteger(eDataType) )
{
value = poDS->GetKeyword( "INTFMT", "LOW" );
if (EQUAL(value,"LOW") ) {
eByteOrder = RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN;
}
else if( EQUAL(value, "HIGH") ) {
eByteOrder = RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN;
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"INTFMT=%s layout not supported.", value);
delete poDS;
return nullptr;
}
}
else
{
value = poDS->GetKeyword( "REALFMT", "VAX" );
if (EQUAL(value,"RIEEE") ) {
eByteOrder = RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN;
}
else if (EQUAL(value,"IEEE") ) {
eByteOrder = RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN;
}
else if (EQUAL(value,"VAX") ) {
eByteOrder = RawRasterBand::ByteOrder::ORDER_VAX;
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"REALFMT=%s layout not supported.", value);
delete poDS;
return nullptr;
}
}
/* -------------------------------------------------------------------- */
/* Capture some information from the file that is of interest. */
/* -------------------------------------------------------------------- */
poDS->nRasterXSize = nCols;
poDS->nRasterYSize = nRows;
double dfXDim = 1.0;
double dfYDim = 1.0;
value = poDS->GetKeyword("MAP.MAP_SCALE");
if (strlen(value) > 0 ) {
dfXDim = CPLAtof(value) * 1000.0;
dfYDim = CPLAtof(value) * -1 * 1000.0;
}
const double dfSampleOffset_Shift =
CPLAtof(CPLGetConfigOption( "PDS_SampleProjOffset_Shift", "0.5" ));
const double dfLineOffset_Shift =
CPLAtof(CPLGetConfigOption( "PDS_LineProjOffset_Shift", "0.5" ));
const double dfSampleOffset_Mult =
CPLAtof(CPLGetConfigOption( "PDS_SampleProjOffset_Mult", "-1.0") );
const double dfLineOffset_Mult =
CPLAtof( CPLGetConfigOption( "PDS_LineProjOffset_Mult", "1.0") );
/*********** Grab LINE_PROJECTION_OFFSET ************/
double dfULYMap = 0.5;
value = poDS->GetKeyword("MAP.LINE_PROJECTION_OFFSET");
if (strlen(value) > 0) {
const double yulcenter = CPLAtof(value);
dfULYMap = ((yulcenter + dfLineOffset_Shift) * -dfYDim * dfLineOffset_Mult);
}
/*********** Grab SAMPLE_PROJECTION_OFFSET ************/
double dfULXMap=0.5;
value = poDS->GetKeyword("MAP.SAMPLE_PROJECTION_OFFSET");
if( strlen(value) > 0 ) {
const double xulcenter = CPLAtof(value);
dfULXMap = ((xulcenter + dfSampleOffset_Shift) * dfXDim * dfSampleOffset_Mult);
}
/* ==================================================================== */
/* Get the coordinate system. */
/* ==================================================================== */
bool bProjectionSet = true;
/*********** Grab TARGET_NAME ************/
/**** This is the planets name i.e. MARS ***/
const CPLString target_name = poDS->GetKeyword("MAP.TARGET_NAME");
/********** Grab MAP_PROJECTION_TYPE *****/
const CPLString map_proj_name
= poDS->GetKeyword( "MAP.MAP_PROJECTION_TYPE");
/****** Grab semi_major & convert to KM ******/
const double semi_major
= CPLAtof(poDS->GetKeyword( "MAP.A_AXIS_RADIUS")) * 1000.0;
/****** Grab semi-minor & convert to KM ******/
const double semi_minor
= CPLAtof(poDS->GetKeyword( "MAP.C_AXIS_RADIUS")) * 1000.0;
/*********** Grab CENTER_LAT ************/
const double center_lat =
CPLAtof(poDS->GetKeyword( "MAP.CENTER_LATITUDE"));
/*********** Grab CENTER_LON ************/
const double center_lon
= CPLAtof(poDS->GetKeyword( "MAP.CENTER_LONGITUDE"));
/********** Grab 1st std parallel *******/
const double first_std_parallel =
CPLAtof(poDS->GetKeyword( "MAP.FIRST_STANDARD_PARALLEL"));
/********** Grab 2nd std parallel *******/
const double second_std_parallel =
CPLAtof(poDS->GetKeyword( "MAP.SECOND_STANDARD_PARALLEL"));
/*** grab PROJECTION_LATITUDE_TYPE = "PLANETOCENTRIC" ****/
// Need to further study how ocentric/ographic will effect the gdal library.
// So far we will use this fact to define a sphere or ellipse for some projections
// Frank - may need to talk this over
bool bIsGeographic = true;
value = poDS->GetKeyword("MAP.COORDINATE_SYSTEM_NAME");
if (EQUAL( value, "PLANETOCENTRIC" ))
bIsGeographic = false;
/** Set oSRS projection and parameters --- all PDS supported types added if apparently supported in oSRS
"AITOFF", ** Not supported in GDAL??
"ALBERS",
"BONNE",
"BRIESEMEISTER", ** Not supported in GDAL??
"CYLINDRICAL EQUAL AREA",
"EQUIDISTANT",
"EQUIRECTANGULAR",
"GNOMONIC",
"HAMMER", ** Not supported in GDAL??
"HENDU", ** Not supported in GDAL??
"LAMBERT AZIMUTHAL EQUAL AREA",
"LAMBERT CONFORMAL",
"MERCATOR",
"MOLLWEIDE",
"OBLIQUE CYLINDRICAL",
"ORTHOGRAPHIC",
"SIMPLE CYLINDRICAL",
"SINUSOIDAL",
"STEREOGRAPHIC",
"TRANSVERSE MERCATOR",
"VAN DER GRINTEN", ** Not supported in GDAL??
"WERNER" ** Not supported in GDAL??
**/
CPLDebug( "PDS", "using projection %s\n\n", map_proj_name.c_str());
OGRSpatialReference oSRS;
if ((EQUAL( map_proj_name, "EQUIRECTANGULAR" )) ||
(EQUAL( map_proj_name, "SIMPLE_CYLINDRICAL" )) ||
(EQUAL( map_proj_name, "EQUIDISTANT" )) ) {
oSRS.SetEquirectangular2 ( 0.0, center_lon, center_lat, 0, 0 );
} else if (EQUAL( map_proj_name, "ORTHOGRAPHIC" )) {
oSRS.SetOrthographic ( center_lat, center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "SINUSOIDAL" )) {
oSRS.SetSinusoidal ( center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "MERCATOR" )) {
oSRS.SetMercator ( center_lat, center_lon, 1, 0, 0 );
} else if (EQUAL( map_proj_name, "STEREOGRAPHIC" )) {
if ((fabs(center_lat)-90) < 0.0000001) {
oSRS.SetPS ( center_lat, center_lon, 1, 0, 0 );
} else {
oSRS.SetStereographic ( center_lat, center_lon, 1, 0, 0 );
}
} else if (EQUAL( map_proj_name, "POLAR_STEREOGRAPHIC")) {
oSRS.SetPS ( center_lat, center_lon, 1, 0, 0 );
} else if (EQUAL( map_proj_name, "TRANSVERSE_MERCATOR" )) {
oSRS.SetTM ( center_lat, center_lon, 1, 0, 0 );
} else if (EQUAL( map_proj_name, "LAMBERT_CONFORMAL_CONIC" )) {
oSRS.SetLCC ( first_std_parallel, second_std_parallel,
center_lat, center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "LAMBERT_AZIMUTHAL_EQUAL_AREA" )) {
oSRS.SetLAEA( center_lat, center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "CYLINDRICAL_EQUAL_AREA" )) {
oSRS.SetCEA ( first_std_parallel, center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "MOLLWEIDE" )) {
oSRS.SetMollweide ( center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "ALBERS" )) {
oSRS.SetACEA ( first_std_parallel, second_std_parallel,
center_lat, center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "BONNE" )) {
oSRS.SetBonne ( first_std_parallel, center_lon, 0, 0 );
} else if (EQUAL( map_proj_name, "GNOMONIC" )) {
oSRS.SetGnomonic ( center_lat, center_lon, 0, 0 );
#ifdef FIXME
} else if (EQUAL( map_proj_name, "OBLIQUE_CYLINDRICAL" )) {
// hope Swiss Oblique Cylindrical is the same
oSRS.SetSOC ( center_lat, center_lon, 0, 0 );
#endif
} else {
CPLDebug( "VICAR",
"Dataset projection %s is not supported. Continuing...",
map_proj_name.c_str() );
bProjectionSet = false;
}
if (bProjectionSet) {
//Create projection name, i.e. MERCATOR MARS and set as ProjCS keyword
const CPLString proj_target_name = map_proj_name + " " + target_name;
oSRS.SetProjCS(proj_target_name); //set ProjCS keyword
//The geographic/geocentric name will be the same basic name as the body name
//'GCS' = Geographic/Geocentric Coordinate System
const CPLString geog_name = "GCS_" + target_name;
//The datum and sphere names will be the same basic name aas the planet
const CPLString datum_name = "D_" + target_name;
CPLString sphere_name = target_name; // + "_IAU_IAG"); //Might not be IAU defined so don't add
//calculate inverse flattening from major and minor axis: 1/f = a/(a-b)
double iflattening = 0.0;
if ((semi_major - semi_minor) < 0.0000001)
iflattening = 0;
else
iflattening = semi_major / (semi_major - semi_minor);
//Set the body size but take into consideration which proj is being used to help w/ compatibility
//Notice that most PDS projections are spherical based on the fact that ISIS/PICS are spherical
//Set the body size but take into consideration which proj is being used to help w/ proj4 compatibility
//The use of a Sphere, polar radius or ellipse here is based on how ISIS does it internally
if ( ( (EQUAL( map_proj_name, "STEREOGRAPHIC" ) && (fabs(center_lat) == 90)) ) ||
(EQUAL( map_proj_name, "POLAR_STEREOGRAPHIC" )))
{
if (bIsGeographic) {
//Geograpraphic, so set an ellipse
oSRS.SetGeogCS( geog_name, datum_name, sphere_name,
semi_major, iflattening,
"Reference_Meridian", 0.0 );
} else {
//Geocentric, so force a sphere using the semi-minor axis. I hope...
sphere_name += "_polarRadius";
oSRS.SetGeogCS( geog_name, datum_name, sphere_name,
semi_minor, 0.0,
"Reference_Meridian", 0.0 );
}
}
else if ( (EQUAL( map_proj_name, "SIMPLE_CYLINDRICAL" )) ||
(EQUAL( map_proj_name, "EQUIDISTANT" )) ||
(EQUAL( map_proj_name, "ORTHOGRAPHIC" )) ||
(EQUAL( map_proj_name, "STEREOGRAPHIC" )) ||
(EQUAL( map_proj_name, "SINUSOIDAL" )) ) {
//isis uses the spherical equation for these projections so force a sphere
oSRS.SetGeogCS( geog_name, datum_name, sphere_name,
semi_major, 0.0,
"Reference_Meridian", 0.0 );
}
else if (EQUAL( map_proj_name, "EQUIRECTANGULAR" )) {
//isis uses local radius as a sphere, which is pre-calculated in the PDS label as the semi-major
sphere_name += "_localRadius";
oSRS.SetGeogCS( geog_name, datum_name, sphere_name,
semi_major, 0.0,
"Reference_Meridian", 0.0 );
}
else
{
//All other projections: Mercator, Transverse Mercator, Lambert Conformal, etc.
//Geographic, so set an ellipse
if (bIsGeographic) {
oSRS.SetGeogCS( geog_name, datum_name, sphere_name,
semi_major, iflattening,
"Reference_Meridian", 0.0 );
}
else
{
//Geocentric, so force a sphere. I hope...
oSRS.SetGeogCS( geog_name, datum_name, sphere_name,
semi_major, 0.0,
"Reference_Meridian", 0.0 );
}
}
poDS->m_oSRS = oSRS;
poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
}
if( bProjectionSet )
{
poDS->m_bGotTransform = true;
poDS->m_adfGeoTransform[0] = dfULXMap;
poDS->m_adfGeoTransform[1] = dfXDim;
poDS->m_adfGeoTransform[2] = 0.0;
poDS->m_adfGeoTransform[3] = dfULYMap;
poDS->m_adfGeoTransform[4] = 0.0;
poDS->m_adfGeoTransform[5] = dfYDim;
}
if( !poDS->m_bGotTransform )
poDS->m_bGotTransform = CPL_TO_BOOL(
GDALReadWorldFile( poOpenInfo->pszFilename, "wld",
&poDS->m_adfGeoTransform[0] ));
poDS->eAccess = poOpenInfo->eAccess;
poDS->m_oJSonLabel = poDS->oKeywords.GetJsonObject();
/* -------------------------------------------------------------------- */
/* Compute the line offsets. */
/* -------------------------------------------------------------------- */
GUInt64 nPixelOffset;
GUInt64 nLineOffset;
GUInt64 nBandOffset;
GUInt64 nImageOffsetWithoutNBB;
GUInt64 nNBB;
GUInt64 nImageSize;
if( !GetSpacings(poDS->oKeywords, nPixelOffset, nLineOffset, nBandOffset,
nImageOffsetWithoutNBB, nNBB, nImageSize) )
{
delete poDS;
return nullptr;
}
poDS->m_nRecordSize = atoi(poDS->GetKeyword("RECSIZE", ""));
if( nNBB != 0 )
{
const char* pszBLType = poDS->GetKeyword("BLTYPE", nullptr);
const char* pszVicarConf = CPLFindFile("gdal", "vicar.json");
if( pszBLType && pszVicarConf && poDS->m_nRecordSize > 0 )
{
RawRasterBand::ByteOrder eBINTByteOrder =
RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN;
value = poDS->GetKeyword( "BINTFMT", "LOW" );
if (EQUAL(value,"LOW") ) {
eBINTByteOrder = RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN;
}
else if( EQUAL(value, "HIGH") ) {
eBINTByteOrder = RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN;
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"BINTFMT=%s layout not supported.", value);
}
RawRasterBand::ByteOrder eBREALByteOrder =
RawRasterBand::ByteOrder::ORDER_VAX;
value = poDS->GetKeyword( "BREALFMT", "VAX" );
if (EQUAL(value,"RIEEE") ) {
eBREALByteOrder = RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN;
}
else if (EQUAL(value,"IEEE") ) {
eBREALByteOrder = RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN;
}
else if (EQUAL(value,"VAX") ) {
eBREALByteOrder = RawRasterBand::ByteOrder::ORDER_VAX;
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"BREALFMT=%s layout not supported.", value);
}
CPLJSONDocument oDoc;
if( oDoc.Load(pszVicarConf) )
{
const auto oRoot = oDoc.GetRoot();
if( oRoot.GetType() == CPLJSONObject::Type::Object )
{
auto oDef = oRoot.GetObj(pszBLType);
if( oDef.IsValid() &&
oDef.GetType() == CPLJSONObject::Type::Object &&
static_cast<GUInt64>(oDef.GetInteger("size")) == nNBB )
{
auto poLayer = std::unique_ptr<OGRVICARBinaryPrefixesLayer>(
new OGRVICARBinaryPrefixesLayer(
poDS->fpImage,
static_cast<int>(nImageSize / poDS->m_nRecordSize),
oDef,
nImageOffsetWithoutNBB,
poDS->m_nRecordSize,
eBINTByteOrder,
eBREALByteOrder));
if( !poLayer->HasError() )
{
poDS->m_poLayer = std::move(poLayer);
}
}
}
}
}
}
poDS->m_nImageOffsetWithoutNBB =
static_cast<vsi_l_offset>(nImageOffsetWithoutNBB);
CPLString osCompress = poDS->GetKeyword("COMPRESS", "NONE");
if( EQUAL(osCompress, "BASIC") || EQUAL(osCompress, "BASIC2") )
{
if( poOpenInfo->eAccess == GA_Update )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Update of compressed VICAR file not supported");
delete poDS;
return nullptr;
}
poDS->SetMetadataItem("COMPRESS", osCompress, "IMAGE_STRUCTURE");
poDS->m_eCompress = EQUAL(osCompress, "BASIC") ?
COMPRESS_BASIC : COMPRESS_BASIC2;
if( poDS->nRasterYSize > 100 * 1000 * 1000 / nBands )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Too many records for compressed dataset");
delete poDS;
return nullptr;
}
if( !GDALDataTypeIsInteger(eDataType) )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Data type incompatible of compression");
delete poDS;
return nullptr;
}
// To avoid potential issues in basic_decode()
const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
if( nDTSize == 0 || poDS->nRasterXSize > INT_MAX / nDTSize )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Too large scanline");
delete poDS;
return nullptr;
}
const int nRecords = poDS->nRasterYSize * nBands;
try
{
// + 1 to store implicitly the size of the last record
poDS->m_anRecordOffsets.resize( nRecords + 1 );
}
catch( const std::exception& e )
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what() );
delete poDS;
return nullptr;
}
if( poDS->m_eCompress == COMPRESS_BASIC )
{
poDS->m_anRecordOffsets[0] =
poDS->m_nImageOffsetWithoutNBB + sizeof(GUInt32);
}
else
{
poDS->m_anRecordOffsets[0] =
poDS->m_nImageOffsetWithoutNBB + sizeof(GUInt32) * nRecords;
}
}
else if( !EQUAL(osCompress, "NONE") )
{
CPLError(CE_Failure, CPLE_NotSupported,
"COMPRESS=%s not supported", osCompress.c_str());
delete poDS;
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Create band information objects. */
/* -------------------------------------------------------------------- */
for( int i = 0; i < nBands; i++ )
{
GDALRasterBand *poBand;
if( poDS->m_eCompress == COMPRESS_BASIC ||
poDS->m_eCompress == COMPRESS_BASIC2 )
{
poBand = new VICARBASICRasterBand( poDS, i+1, eDataType );
}
else
{
poBand = new VICARRawRasterBand( poDS, i+1, poDS->fpImage,
static_cast<vsi_l_offset>(
nImageOffsetWithoutNBB + nNBB + nBandOffset * i),
static_cast<int>(nPixelOffset),
static_cast<int>(nLineOffset),
eDataType,
eByteOrder );
}
poDS->SetBand( i+1, poBand );
//only set NoData if instrument is supported
if (bInstKnown)
poBand->SetNoDataValue( dfNoData );
if (bIsDTM) {
poBand->SetScale( static_cast<double>(
CPLAtof(poDS->GetKeyword( "DTM.DTM_SCALING_FACTOR") ) ) );
poBand->SetOffset( static_cast<double>(
CPLAtof(poDS->GetKeyword( "DTM.DTM_OFFSET") ) ) );
const char* pszMin = poDS->GetKeyword( "DTM.DTM_MINIMUM_DN", nullptr );
const char* pszMax = poDS->GetKeyword( "DTM.DTM_MAXIMUM_DN", nullptr );
if (pszMin != nullptr && pszMax != nullptr )
poBand->SetStatistics(CPLAtofM(pszMin),CPLAtofM(pszMax),0,0);
const char* pszNoData = poDS->GetKeyword( "DTM.DTM_MISSING_DN", nullptr );
if (pszNoData != nullptr )
poBand->SetNoDataValue( CPLAtofM(pszNoData) );
} else if (EQUAL( poDS->GetKeyword( "BLTYPE"), "M94_HRSC" )) {
double scale=CPLAtof(poDS->GetKeyword("DLRTO8.REFLECTANCE_SCALING_FACTOR","-1."));
if (scale < 0.) {
scale = CPLAtof(poDS->GetKeyword( "HRCAL.REFLECTANCE_SCALING_FACTOR","1."));
}
poBand->SetScale( scale );
double offset=CPLAtof(poDS->GetKeyword("DLRTO8.REFLECTANCE_OFFSET","-1."));
if (offset < 0.) {
offset = CPLAtof(poDS->GetKeyword( "HRCAL.REFLECTANCE_OFFSET","0."));
}
poBand->SetOffset( offset );
}
const char* pszMin = poDS->GetKeyword( "STATISTICS.MINIMUM", nullptr );
const char* pszMax = poDS->GetKeyword( "STATISTICS.MAXIMUM", nullptr );
const char* pszMean = poDS->GetKeyword( "STATISTICS.MEAN", nullptr );
const char* pszStdDev = poDS->GetKeyword( "STATISTICS.STANDARD_DEVIATION", nullptr );
if (pszMin != nullptr && pszMax != nullptr && pszMean != nullptr && pszStdDev != nullptr )
poBand->SetStatistics(CPLAtofM(pszMin),CPLAtofM(pszMax),CPLAtofM(pszMean),CPLAtofM(pszStdDev));
}
/* -------------------------------------------------------------------- */
/* Instrument-specific keywords as metadata. */
/* -------------------------------------------------------------------- */
/****************** HRSC ******************************/
if (EQUAL( poDS->GetKeyword( "BLTYPE"), "M94_HRSC" ) ) {
poDS->SetMetadataItem( "SPACECRAFT_NAME", poDS->GetKeyword( "M94_INSTRUMENT.INSTRUMENT_HOST_NAME") );
poDS->SetMetadataItem( "PRODUCT_TYPE", poDS->GetKeyword( "TYPE"));
if (EQUAL( poDS->GetKeyword( "M94_INSTRUMENT.DETECTOR_ID"), "MEX_HRSC_SRC" )) {
static const char * const apszKeywords[] = {
"M94_ORBIT.IMAGE_TIME",
"FILE.EVENT_TYPE",
"FILE.PROCESSING_LEVEL_ID",
"M94_INSTRUMENT.DETECTOR_ID",
"M94_CAMERAS.EXPOSURE_DURATION",
"HRCONVER.INSTRUMENT_TEMPERATURE", nullptr
};
for( int i = 0; apszKeywords[i] != nullptr; i++ ) {
const char *pszKeywordValue = poDS->GetKeyword( apszKeywords[i] );
if( pszKeywordValue != nullptr )
poDS->SetMetadataItem( apszKeywords[i], pszKeywordValue );
}
} else {
static const char * const apszKeywords[] = {
"M94_ORBIT.START_TIME", "M94_ORBIT.STOP_TIME",
"M94_INSTRUMENT.DETECTOR_ID",
"M94_CAMERAS.MACROPIXEL_SIZE",
"FILE.EVENT_TYPE",
"M94_INSTRUMENT.MISSION_PHASE_NAME",
"HRORTHO.SPICE_FILE_NAME",
"HRCONVER.MISSING_FRAMES", "HRCONVER.OVERFLOW_FRAMES", "HRCONVER.ERROR_FRAMES",
"HRFOOT.BEST_GROUND_SAMPLING_DISTANCE",
"DLRTO8.RADIANCE_SCALING_FACTOR", "DLRTO8.RADIANCE_OFFSET",
"DLRTO8.REFLECTANCE_SCALING_FACTOR", "DLRTO8.REFLECTANCE_OFFSET",
"HRCAL.RADIANCE_SCALING_FACTOR", "HRCAL.RADIANCE_OFFSET",
"HRCAL.REFLECTANCE_SCALING_FACTOR", "HRCAL.REFLECTANCE_OFFSET",
"HRORTHO.DTM_NAME", "HRORTHO.EXTORI_FILE_NAME", "HRORTHO.GEOMETRIC_CALIB_FILE_NAME",
nullptr
};
for( int i = 0; apszKeywords[i] != nullptr; i++ ) {
const char *pszKeywordValue = poDS->GetKeyword( apszKeywords[i], nullptr );
if( pszKeywordValue != nullptr )
poDS->SetMetadataItem( apszKeywords[i], pszKeywordValue );
}
}
}
if (bIsDTM && EQUAL( poDS->GetKeyword( "MAP.TARGET_NAME"), "MARS" )) {
poDS->SetMetadataItem( "SPACECRAFT_NAME", "MARS_EXPRESS" );
poDS->SetMetadataItem( "PRODUCT_TYPE", "DTM");
static const char * const apszKeywords[] = {
"DTM.DTM_MISSING_DN", "DTM.DTM_OFFSET", "DTM.DTM_SCALING_FACTOR", "DTM.DTM_A_AXIS_RADIUS",
"DTM.DTM_B_AXIS_RADIUS", "DTM.DTM_C_AXIS_RADIUS", "DTM.DTM_DESC", "DTM.DTM_MINIMUM_DN",
"DTM.DTM_MAXIMUM_DN", nullptr };
for( int i = 0; apszKeywords[i] != nullptr; i++ ) {
const char *pszKeywordValue = poDS->GetKeyword( apszKeywords[i] );
if( pszKeywordValue != nullptr )
poDS->SetMetadataItem( apszKeywords[i], pszKeywordValue );
}
}
/****************** DAWN ******************************/
else if (EQUAL( poDS->GetKeyword( "INSTRUMENT_ID"), "FC2" )) {
poDS->SetMetadataItem( "SPACECRAFT_NAME", "DAWN" );
static const char * const apszKeywords[] = {"ORBIT_NUMBER","FILTER_NUMBER",
"FRONT_DOOR_STATUS",
"FIRST_LINE",
"FIRST_LINE_SAMPLE",
"PRODUCER_INSTITUTION_NAME",
"SOURCE_FILE_NAME",
"PROCESSING_LEVEL_ID",
"TARGET_NAME",
"LIMB_IN_IMAGE",
"POLE_IN_IMAGE",
"REFLECTANCE_SCALING_FACTOR",
"SPICE_FILE_NAME",
"SPACECRAFT_CENTRIC_LATITUDE",
"SPACECRAFT_EASTERN_LONGITUDE",
"FOOTPRINT_POSITIVE_LONGITUDE",
nullptr };
for( int i = 0; apszKeywords[i] != nullptr; i++ ) {
const char *pszKeywordValue = poDS->GetKeyword( apszKeywords[i] );
if( pszKeywordValue != nullptr )
poDS->SetMetadataItem( apszKeywords[i], pszKeywordValue );
}
}
else if (bIsDTM && ( EQUAL( poDS->GetKeyword( "TARGET_NAME"), "VESTA" ) || EQUAL( poDS->GetKeyword( "TARGET_NAME"), "CERES" )))
{
poDS->SetMetadataItem( "SPACECRAFT_NAME", "DAWN" );
poDS->SetMetadataItem( "PRODUCT_TYPE", "DTM");
static const char * const apszKeywords[] = {
"DTM_MISSING_DN", "DTM_OFFSET", "DTM_SCALING_FACTOR", "DTM_A_AXIS_RADIUS",
"DTM_B_AXIS_RADIUS", "DTM_C_AXIS_RADIUS", "DTM_MINIMUM_DN",
"DTM_MAXIMUM_DN", "MAP_PROJECTION_TYPE", "COORDINATE_SYSTEM_NAME",
"POSITIVE_LONGITUDE_DIRECTION", "MAP_SCALE",
"CENTER_LONGITUDE", "LINE_PROJECTION_OFFSET", "SAMPLE_PROJECTION_OFFSET",
nullptr };
for( int i = 0; apszKeywords[i] != nullptr; i++ )
{
const char *pszKeywordValue = poDS->GetKeyword( apszKeywords[i] );
if( pszKeywordValue != nullptr )
poDS->SetMetadataItem( apszKeywords[i], pszKeywordValue );
}
}
/* -------------------------------------------------------------------- */
/* Initialize any PAM information. */
/* -------------------------------------------------------------------- */
poDS->TryLoadXML();
/* -------------------------------------------------------------------- */
/* Check for overviews. */
/* -------------------------------------------------------------------- */
poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename );
return poDS;
}
/************************************************************************/
/* GetKeyword() */
/************************************************************************/
const char *VICARDataset::GetKeyword( const char *pszPath,
const char *pszDefault )
{
return oKeywords.GetKeyword( pszPath, pszDefault );
}
/************************************************************************/
/* GetDataTypeFromFormat() */
/************************************************************************/
GDALDataType VICARDataset::GetDataTypeFromFormat(const char* pszFormat)
{
if (EQUAL( pszFormat, "BYTE" ))
return GDT_Byte;
if (EQUAL( pszFormat, "HALF" ) || EQUAL( pszFormat, "WORD") )
return GDT_Int16;
if (EQUAL( pszFormat, "FULL" ) || EQUAL( pszFormat, "LONG") )
return GDT_Int32;
if (EQUAL( pszFormat, "REAL" ))
return GDT_Float32;
if (EQUAL( pszFormat, "DOUB" ))
return GDT_Float64;
if (EQUAL( pszFormat, "COMP" ) || EQUAL( pszFormat, "COMPLEX" ))
return GDT_CFloat32;
return GDT_Unknown;
}
/************************************************************************/
/* GetSpacings() */
/************************************************************************/
bool VICARDataset::GetSpacings(const VICARKeywordHandler& keywords,
GUInt64& nPixelOffset,
GUInt64& nLineOffset,
GUInt64& nBandOffset,
GUInt64& nImageOffsetWithoutNBB,
GUInt64& nNBB,
GUInt64& nImageSize)
{
const GDALDataType eDataType = GetDataTypeFromFormat(keywords.GetKeyword( "FORMAT", "" ));
if( eDataType == GDT_Unknown )
return false;
const GUInt64 nItemSize = GDALGetDataTypeSizeBytes(eDataType);
const char* value = keywords.GetKeyword( "ORG", "BSQ" );
// number of bytes of binary prefix before each record
nNBB = atoi(keywords.GetKeyword("NBB", ""));
const GUInt64 nCols64 = atoi(keywords.GetKeyword("NS", ""));
const GUInt64 nRows64 = atoi(keywords.GetKeyword("NL", ""));
const GUInt64 nBands64 = atoi(keywords.GetKeyword("NB", ""));
try
{
if (EQUAL(value,"BIP") )
{
nPixelOffset = (CPLSM(nItemSize) * CPLSM(nBands64)).v();
nBandOffset = nItemSize;
nLineOffset = (CPLSM(nNBB) + CPLSM(nPixelOffset) * CPLSM(nCols64)).v();
nImageSize = (CPLSM(nLineOffset) * CPLSM(nRows64)).v();
}
else if (EQUAL(value,"BIL") )
{
nPixelOffset = nItemSize;
nBandOffset = (CPLSM(nItemSize) * CPLSM(nCols64)).v();
nLineOffset = (CPLSM(nNBB) + CPLSM(nBandOffset) * CPLSM(nBands64)).v();
nImageSize = (CPLSM(nLineOffset) * CPLSM(nRows64)).v();
}
else if (EQUAL(value,"BSQ") )
{
nPixelOffset = nItemSize;
nLineOffset = (CPLSM(nNBB) + CPLSM(nPixelOffset) * CPLSM(nCols64)).v();
nBandOffset = (CPLSM(nLineOffset) * CPLSM(nRows64)).v();
nImageSize = (CPLSM(nBandOffset) * CPLSM(nBands64)).v();
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"ORG=%s layout not supported.", value);
return false;
}
}
catch( const CPLSafeIntOverflow& )
{
return false;
}
const GUInt64 nLabelSize = atoi(keywords.GetKeyword("LBLSIZE", ""));
const GUInt64 nRecordSize = atoi(keywords.GetKeyword("RECSIZE", ""));
const GUInt64 nNLB = atoi(keywords.GetKeyword("NLB", ""));
try
{
nImageOffsetWithoutNBB = (CPLSM(nLabelSize) + CPLSM(nRecordSize) * CPLSM(nNLB) + CPLSM(nNBB)).v();
nImageOffsetWithoutNBB -= nNBB;
}
catch( const CPLSafeIntOverflow& )
{
return false;
}
return true;
}
/************************************************************************/
/* Create() */
/************************************************************************/
GDALDataset *VICARDataset::Create(const char* pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType,
char** papszOptions)
{
return CreateInternal(pszFilename, nXSize, nYSize, nBands, eType,
papszOptions);
}
VICARDataset *VICARDataset::CreateInternal(const char* pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType,
char** papszOptions)
{
if( eType != GDT_Byte && eType != GDT_Int16 && eType != GDT_Int32 &&
eType != GDT_Float32 && eType != GDT_Float64 && eType != GDT_CFloat32 )
{
CPLError(CE_Failure, CPLE_NotSupported, "Unsupported data type");
return nullptr;
}
const int nPixelOffset = GDALGetDataTypeSizeBytes(eType);
if( nXSize == 0 || nYSize == 0 || nPixelOffset > INT_MAX / nXSize )
{
CPLError(CE_Failure, CPLE_NotSupported, "Unsupported raster dimensions");
return nullptr;
}
const int nLineOffset = nXSize * nPixelOffset;
if( nBands == 0 || nBands > 32767 )
{
CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count");
return nullptr;
}
const char* pszCompress = CSLFetchNameValueDef(papszOptions, "COMPRESS", "NONE");
CompressMethod eCompress = COMPRESS_NONE;
if( EQUAL(pszCompress, "NONE") )
{
eCompress = COMPRESS_NONE;
}
else if( EQUAL(pszCompress, "BASIC") )
{
eCompress = COMPRESS_BASIC;
}
else if( EQUAL(pszCompress, "BASIC2") )
{
eCompress = COMPRESS_BASIC2;
}
else
{
CPLError(CE_Failure, CPLE_NotSupported, "Unsupported COMPRESS value");
return nullptr;
}
if( eCompress != COMPRESS_NONE &&
(!GDALDataTypeIsInteger(eType) || nBands != 1) )
{
CPLError(CE_Failure, CPLE_NotSupported,
"BASIC/BASIC2 compression only supports one-band integer datasets");
return nullptr;
}
std::vector<vsi_l_offset> anRecordOffsets;
if( eCompress != COMPRESS_NONE )
{
const GUInt64 nMaxEncodedSize =
static_cast<GUInt64>(nXSize) * nPixelOffset + static_cast<GUInt64>(nXSize) * nPixelOffset / 2 + 11;
// To avoid potential later int overflows
if( nMaxEncodedSize > static_cast<GUInt64>(INT_MAX) )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Too large scanline");
return nullptr;
}
if( nYSize > 100 * 1000 * 1000 )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Too many records for compressed dataset");
return nullptr;
}
try
{
// + 1 to store implicitly the size of the last record
anRecordOffsets.resize( nYSize + 1 );
}
catch( const std::exception& e )
{
CPLError(CE_Failure, CPLE_OutOfMemory, "%s", e.what() );
return nullptr;
}
}
CPLJSONObject oSrcJSonLabel;
oSrcJSonLabel.Deinit();
const char* pszLabel = CSLFetchNameValue(papszOptions, "LABEL");
if( pszLabel )
{
CPLJSONDocument oJSONDocument;
if( pszLabel[0] == '{' )
{
const GByte *pabyData = reinterpret_cast<const GByte *>(pszLabel);
if( !oJSONDocument.LoadMemory( pabyData ) )
{
return nullptr;
}
}
else
{
if( !oJSONDocument.Load(pszLabel) )
{
return nullptr;
}
}
oSrcJSonLabel = oJSONDocument.GetRoot();
if( !oSrcJSonLabel.IsValid() )
{
return nullptr;
}
}
VSILFILE* fp = VSIFOpenExL(pszFilename, "wb+", true);
if( fp == nullptr )
{
CPLError( CE_Failure, CPLE_FileIO,
"Cannot create %s: %s",
pszFilename, VSIGetLastErrorMsg() );
return nullptr;
}
VICARDataset* poDS = new VICARDataset();
poDS->fpImage = fp;
poDS->nRasterXSize = nXSize;
poDS->nRasterYSize = nYSize;
poDS->m_nRecordSize = nLineOffset;
poDS->m_bIsLabelWritten = false;
poDS->m_bUseSrcLabel = CPLFetchBool(papszOptions, "USE_SRC_LABEL", true);
poDS->m_bUseSrcMap = CPLFetchBool(papszOptions, "USE_SRC_MAP", false);
poDS->m_osLatitudeType = CSLFetchNameValueDef(papszOptions,
"COORDINATE_SYSTEM_NAME", "");
poDS->m_osLongitudeDirection = CSLFetchNameValueDef(papszOptions,
"POSITIVE_LONGITUDE_DIRECTION", "");
poDS->m_osTargetName = CSLFetchNameValueDef(papszOptions,
"TARGET_NAME", "");
poDS->m_bInitToNodata = true;
poDS->m_oSrcJSonLabel = oSrcJSonLabel;
poDS->m_eCompress = eCompress;
poDS->m_anRecordOffsets = std::move(anRecordOffsets);
poDS->eAccess = GA_Update;
/* -------------------------------------------------------------------- */
/* Create band information objects. */
/* -------------------------------------------------------------------- */
const vsi_l_offset nBandOffset =
static_cast<vsi_l_offset>(nLineOffset) * nYSize;
for( int i = 0; i < nBands; i++ )
{
GDALRasterBand *poBand;
if( eCompress != COMPRESS_NONE )
{
poBand = new VICARBASICRasterBand( poDS, i+1, eType );
}
else
{
poBand = new VICARRawRasterBand(
poDS, i+1, poDS->fpImage,
i * nBandOffset, // will be set later to final value since we need to include the label size
nPixelOffset,
nLineOffset,
eType,
RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN );
}
poDS->SetBand( i+1, poBand );
}
return poDS;
}
/************************************************************************/
/* CreateCopy() */
/************************************************************************/
GDALDataset* VICARDataset::CreateCopy( const char *pszFilename,
GDALDataset *poSrcDS,
int /*bStrict*/,
char ** papszOptions,
GDALProgressFunc pfnProgress,
void * pProgressData )
{
if( poSrcDS->GetRasterCount() == 0 )
{
CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count");
return nullptr;
}
const int nXSize = poSrcDS->GetRasterXSize();
const int nYSize = poSrcDS->GetRasterYSize();
const int nBands = poSrcDS->GetRasterCount();
GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType();
auto poDS = CreateInternal(
pszFilename, nXSize, nYSize, nBands, eType, papszOptions );
if( poDS == nullptr )
return nullptr;
double adfGeoTransform[6] = { 0.0 };
if( poSrcDS->GetGeoTransform( adfGeoTransform ) == CE_None
&& (adfGeoTransform[0] != 0.0
|| adfGeoTransform[1] != 1.0
|| adfGeoTransform[2] != 0.0
|| adfGeoTransform[3] != 0.0
|| adfGeoTransform[4] != 0.0
|| adfGeoTransform[5] != 1.0) )
{
poDS->SetGeoTransform( adfGeoTransform );
}
auto poSrcSRS = poSrcDS->GetSpatialRef();
if( poSrcSRS )
{
poDS->SetSpatialRef( poSrcSRS );
}
if( poDS->m_bUseSrcLabel && !poDS->m_oSrcJSonLabel.IsValid() )
{
char** papszMD_VICAR = poSrcDS->GetMetadata("json:VICAR");
if( papszMD_VICAR != nullptr )
{
poDS->SetMetadata( papszMD_VICAR, "json:VICAR" );
}
}
poDS->m_bInitToNodata = false;
CPLErr eErr = GDALDatasetCopyWholeRaster( poSrcDS, poDS,
nullptr, pfnProgress, pProgressData );
poDS->FlushCache();
if( eErr != CE_None )
{
delete poDS;
return nullptr;
}
return poDS;
}
/************************************************************************/
/* GetVICARLabelOffsetFromPDS3() */
/************************************************************************/
vsi_l_offset VICARDataset::GetVICARLabelOffsetFromPDS3(const char* pszHdr,
VSILFILE* fp,
std::string& osVICARHeader)
{
const char* pszPDSVersionID = strstr(pszHdr,"PDS_VERSION_ID");
int nOffset = 0;
if (pszPDSVersionID)
nOffset = static_cast<int>(pszPDSVersionID - pszHdr);
NASAKeywordHandler oKeywords;
if( oKeywords.Ingest( fp, nOffset ) )
{
const int nRecordBytes = atoi(oKeywords.GetKeyword("RECORD_BYTES", "0"));
const int nImageHeader = atoi(oKeywords.GetKeyword("^IMAGE_HEADER", "0"));
if( nRecordBytes > 0 && nImageHeader > 0 )
{
const auto nImgHeaderOffset =
static_cast<vsi_l_offset>(nImageHeader - 1) * nRecordBytes;
osVICARHeader.resize(1024);
size_t nMemb;
if( VSIFSeekL( fp, nImgHeaderOffset, SEEK_SET ) == 0 &&
(nMemb = VSIFReadL( &osVICARHeader[0], 1,
osVICARHeader.size(), fp )) != 0 &&
osVICARHeader.find("LBLSIZE") != std::string::npos )
{
osVICARHeader.resize(nMemb);
return nImgHeaderOffset;
}
}
}
return 0;
}
/************************************************************************/
/* GDALRegister_VICAR() */
/************************************************************************/
void GDALRegister_VICAR()
{
if( GDALGetDriverByName( "VICAR" ) != nullptr )
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription( "VICAR" );
poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );
poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" );
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "MIPL VICAR file" );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/vicar.html" );
poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );
poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES,
"Byte Int16 Int32 Float32 Float64 CFloat32" );
poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>"
" <Option name='COORDINATE_SYSTEM_NAME' type='string-select' "
"description='Value of MAP.COORDINATE_SYSTEM_NAME' default='PLANETOCENTRIC'>"
" <Value>PLANETOCENTRIC</Value>"
" <Value>PLANETOGRAPHIC</Value>"
" </Option>"
" <Option name='POSITIVE_LONGITUDE_DIRECTION' type='string-select' "
"description='Value of MAP.POSITIVE_LONGITUDE_DIRECTION' "
"default='EAST'>"
" <Value>EAST</Value>"
" <Value>WEST</Value>"
" </Option>"
" <Option name='TARGET_NAME' type='string' description='Value of "
"MAP.TARGET_NAME'/>"
" <Option name='USE_SRC_LABEL' type='boolean'"
"description='Whether to use source label in VICAR to VICAR conversions' "
"default='YES'/>"
" <Option name='USE_SRC_MAP' type='boolean'"
"description='Whether to use MAP property from source label in "
"VICAR to VICAR conversions' "
"default='NO'/>"
" <Option name='LABEL' type='string'"
"description='Label to use, either as a JSON string or a filename containing one'/>"
" <Option name='COMPRESS' type='string-select' "
"description='Compression method' default='NONE'>"
" <Value>NONE</Value>"
" <Value>BASIC</Value>"
" <Value>BASIC2</Value>"
" </Option>"
"</CreationOptionList>"
);
poDriver->pfnOpen = VICARDataset::Open;
poDriver->pfnIdentify = VICARDataset::Identify;
poDriver->pfnCreate = VICARDataset::Create;
poDriver->pfnCreateCopy = VICARDataset::CreateCopy;
GetGDALDriverManager()->RegisterDriver( poDriver );
}
| 37.981812 | 131 | 0.496187 | [
"object",
"vector"
] |
11ef45f39def5f3298af05717e24607730513c3e | 26,289 | cpp | C++ | src/MarkerArtist.cpp | ravidavi/OpenFrames | 67cce87f1ccd23df91d6d070d86c06ceb180dadb | [
"Apache-2.0"
] | 26 | 2017-08-16T18:17:50.000Z | 2022-03-11T10:23:52.000Z | src/MarkerArtist.cpp | ravidavi/OpenFrames | 67cce87f1ccd23df91d6d070d86c06ceb180dadb | [
"Apache-2.0"
] | 4 | 2018-10-18T12:31:19.000Z | 2020-08-12T08:59:25.000Z | src/MarkerArtist.cpp | ravidavi/OpenFrames | 67cce87f1ccd23df91d6d070d86c06ceb180dadb | [
"Apache-2.0"
] | 11 | 2018-09-10T18:29:07.000Z | 2022-03-09T13:53:52.000Z | /***********************************
Copyright 2020 Ravishankar Mathur
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.
***********************************/
/** \file MarkerArtist.cpp
* Definitions for the MarkerArtist class.
*/
#include <OpenFrames/DoubleSingleUtils.hpp>
#include <OpenFrames/MarkerArtist.hpp>
#include <osg/BlendFunc>
#include <osg/Point>
#include <osg/PointSprite>
#include <osg/Texture2D>
#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
#include <iostream>
namespace OpenFrames
{
/** Updates a MarkerArtist's internal geometry when its target Trajectory changes. */
class MarkerArtistUpdateCallback : public osg::Callback
{
public:
MarkerArtistUpdateCallback()
: _numPoints(0),
_dataAdded(true),
_dataCleared(true),
_computeAttenuation(false)
{
resetIntermediateData();
}
void dataAdded() { _dataAdded = true; }
void dataCleared() { _dataCleared = true; }
void setComputeAttenuation(bool computeAttenuation) { _computeAttenuation = computeAttenuation; }
bool getComputeAttenuation() const { return _computeAttenuation; }
virtual bool run(osg::Object* object, osg::Object* data)
{
// Get the arrays that hold vertex data
// Note that all object types are known, since this callback is only added to a MarkerArtist
// This is why we don't have to use dynamic_cast
_ma = static_cast<MarkerArtist*>(object);
_endpointGeom = _ma->getDrawable(0)->asGeometry();
_endpointVertexHigh = static_cast<osg::Vec3Array*>(_endpointGeom->getVertexArray());
_endpointVertexLow = static_cast<osg::Vec3Array*>(_endpointGeom->getVertexAttribArray(TrajectoryArtist::OF_VERTEXLOW));
_endpointDrawArrays = static_cast<osg::DrawArrays*>(_endpointGeom->getPrimitiveSet(0));
_intermediateGeom = _ma->getDrawable(1)->asGeometry();
_intermediateVertexHigh = static_cast<osg::Vec3Array*>(_intermediateGeom->getVertexArray());
_intermediateVertexLow = static_cast<osg::Vec3Array*>(_intermediateGeom->getVertexAttribArray(TrajectoryArtist::OF_VERTEXLOW));
_intermediateDrawArrays = static_cast<osg::DrawArrays*>(_intermediateGeom->getPrimitiveSet(0));
// Clear data if it is invalid
if (!_ma->isDataValid())
{
// Clear all points
clearVertexData();
dirtyVertexData(0);
}
// Otherwise process trajectory points and update vertex data as needed
else
{
// Clear all points if needed
if (_dataCleared)
{
clearVertexData();
resetIntermediateData();
_numPoints = 0;
_dataCleared = false;
_dataAdded = true; // Ensure arrays are marked as dirty
}
// Process new data if needed
if (_dataAdded)
{
_dataAdded = false;
_traj = _ma->getTrajectory();
unsigned int newNumPoints;
if (_ma->isDataZero()) newNumPoints = 1;
else
{
_traj->lockData(); // Lock trajectory so its data doesn't move while being analyzed
// Compute number of drawable points
newNumPoints = _traj->getNumPoints(_ma->getDataSource());
}
// Process trajectory points
processPoints(newNumPoints);
// Unlock trajectory
if (!_ma->isDataZero()) _traj->unlockData();
// Mark data as changed
dirtyVertexData(newNumPoints);
}
}
// Compute point attenuation
if (_computeAttenuation) _ma->computeAttenuation();
// Traverse nested callbacks
return traverse(object, data);
}
private:
void resetIntermediateData()
{
_currTime = DBL_MAX;
_currIndex = INT_MAX;
}
void clearVertexData()
{
// Don't clear endpoint vertex array because it should always contain 2 points
// Clear intermediate vertex array
_intermediateVertexHigh->clear();
_intermediateVertexLow->clear();
}
void dirtyVertexData(unsigned int newNumPoints)
{
_numPoints = newNumPoints;
// Dirty vertex arrays to indicate they've changed
_endpointVertexHigh->dirty();
_endpointVertexLow->dirty();
_intermediateVertexHigh->dirty();
_intermediateVertexLow->dirty();
// Show endpoint markers using their primitive set
if (_ma->getMarkers() & (MarkerArtist::START | MarkerArtist::END)) // Using START and/or END
{
_endpointGeom->setNodeMask(~0); // Enable endpoints
GLint first;
GLsizei count;
// Determine 'first' and 'count' params for primitive set to draw desired markers
if (!(_ma->getMarkers() & MarkerArtist::END)) // Only using START
{
first = 0;
count = 1;
}
else if (!(_ma->getMarkers() & MarkerArtist::START)) // Only using END
{
first = 1;
count = 1;
}
else // Usign START and END
{
first = 0;
count = 2;
}
_endpointDrawArrays->setFirst(first);
_endpointDrawArrays->setCount(count);
_endpointDrawArrays->dirty();
_endpointGeom->dirtyBound();
}
else _endpointGeom->setNodeMask(0); // Disable endpoints
// Show/hide intermediate markers
if (_intermediateVertexHigh->empty()) _intermediateGeom->setNodeMask(0);
else
{
_intermediateGeom->setNodeMask(~0);
_intermediateDrawArrays->setCount(_intermediateVertexHigh->size());
_intermediateDrawArrays->dirty();
_intermediateGeom->dirtyBound();
}
}
void processPoints(unsigned int newNumPoints)
{
// Parameters for each new point
osg::Vec3d newPoint, prevPoint;
osg::Vec3f high, low; // High and Low portions of each point for GPU-based RTE rendering
// Compute start point
if (_ma->getMarkers() & MarkerArtist::START)
{
if (_ma->isDataZero() || (newNumPoints > 0))
{
// Get point and split it into high and low portions
if(_traj != nullptr) _traj->getPoint(0, _ma->getDataSource(), newPoint._v);
else newPoint.set(0.0, 0.0, 0.0);
OpenFrames::DS_Split(newPoint, high, low);
(*_endpointVertexHigh)[0] = high;
(*_endpointVertexLow)[0] = low;
}
}
// Compute end point
if ((_ma->getMarkers() & MarkerArtist::END) && (newNumPoints > 1))
{
// Get point and split it into high and low portions
_traj->getPoint(newNumPoints - 1, _ma->getDataSource(), newPoint._v);
OpenFrames::DS_Split(newPoint, high, low);
(*_endpointVertexHigh)[1] = high;
(*_endpointVertexLow)[1] = low;
}
// Compute intermediate points
if ((_ma->getMarkers() & MarkerArtist::INTERMEDIATE) && (newNumPoints > 2) && (newNumPoints > _numPoints))
{
// Compute points at specified time increments
if (_ma->getIntermediateType() == MarkerArtist::TIME)
{
// Get the start & end times of the trajectory, depending on
// whether we want to plot points from beginning or from end
// of the trajectory
double start, end;
if (_ma->getIntermediateDirection() == MarkerArtist::START)
{
_traj->getTimeRange(start, end);
}
else
{
_traj->getTimeRange(end, start);
// Need to clear and recompute all vertices since new points are at the
// back of the trajectory array and time intervals are computed from the back
// to the front of the trajectory array
clearVertexData();
resetIntermediateData();
}
// Determine whether times are increasing or decreasing
int direction = (start <= end) ? 1 : -1;
double spacing = direction*_ma->getIntermediateSpacing();
if (spacing == 0.0) spacing = direction;
int index; // Used to find index of data to plot
if (_currTime == DBL_MAX) _currTime = start + spacing; // Initialize time if needed
for (; direction*_currTime < direction*end; _currTime += spacing)
{
// Get the lower bounding index for the current time
_traj->getTimeIndex(_currTime, index);
// Compute the distance between the lower & upper bounding times
double t_a = _traj->getTimeList()[index];
double t_b = _traj->getTimeList()[index + 1];
// Make sure bounding times are not equal
if (t_a == t_b)
{
// Get the data point at the lower time
_traj->getPoint(index, _ma->getDataSource(), newPoint._v);
}
else
{
double frac = (_currTime - t_a) / (t_b - t_a);
// Get the data points at the lower and upper times
_traj->getPoint(index, _ma->getDataSource(), prevPoint._v);
_traj->getPoint(index + 1, _ma->getDataSource(), newPoint._v);
// Extrapolate the data point to be plotted
newPoint = prevPoint + (newPoint - prevPoint)*frac;
}
// Store the interpolated point
OpenFrames::DS_Split(newPoint, high, low);
_intermediateVertexHigh->push_back(high);
_intermediateVertexLow->push_back(low);
}
}
// Compute points at specified distances between points. The distance
// here is defined by the arc-length between the two points.
else if (_ma->getIntermediateType() == MarkerArtist::DISTANCE)
{
double frac;
int start, end, direction;
// Determine start & end indices depending on whether we want to
// plot intermediate points from start or end of trajectory.
if (_ma->getIntermediateDirection() == MarkerArtist::START)
{
start = 0;
end = newNumPoints;
direction = 1;
}
else
{
start = newNumPoints - 1;
end = -1;
direction = -1;
// Need to clear and recompute all vertices since new points are at the back
// of the trajectory array and all distance intervals would be invalidated
clearVertexData();
resetIntermediateData();
}
if (_currIndex == INT_MAX)
{
_currIndex = start + direction;
_currDistance = 0.0;
_prevDistance = 0.0;
_targetDistance = _ma->getIntermediateSpacing();
}
// Iterate over every point, integrating the arc length by
// assuming a straight line between points. Draw a marker each
// time the arc length reaches the appropriate spacing distance.
// Note that if the trajectory's total arc length is less than
// the desired marker spacing, then no markers will be drawn.
_traj->getPoint(_currIndex - direction, _ma->getDataSource(), prevPoint._v);
for (; _currIndex != end; _currIndex += direction)
{
// Get the current point
_traj->getPoint(_currIndex, _ma->getDataSource(), newPoint._v);
// Add the incremental length from the previous point
_currDistance += (newPoint - prevPoint).length();
// If we have reached (or overshot) the target distance, then
// start plotting points
while (_currDistance >= _targetDistance)
{
// Interpolate the data point to be plotted
frac = (_targetDistance - _prevDistance) / (_currDistance - _prevDistance);
osg::Vec3d temp = prevPoint + (newPoint - prevPoint)*frac;
OpenFrames::DS_Split(temp, high, low);
_intermediateVertexHigh->push_back(high);
_intermediateVertexLow->push_back(low);
_targetDistance += _ma->getIntermediateSpacing();
}
// Prepare for next iteration
_prevDistance = _currDistance;
prevPoint = newPoint;
}
}
// Draw points at specified data intervals
else if (_ma->getIntermediateType() == MarkerArtist::DATA)
{
int spacing, start, end, direction;
// Make sure requested spacing is valid
spacing = (int)_ma->getIntermediateSpacing();
if (spacing == 0) spacing = 1;
// Determine start & end points depending on whether we want to
// plot intermediate points from start or end of trajectory.
if (_ma->getIntermediateDirection() == MarkerArtist::START)
{
start = spacing;
end = newNumPoints - 1;
direction = 1;
}
else
{
start = (newNumPoints - 1) - spacing;
end = 0;
direction = -1;
spacing = -spacing;
// Need to clear and recompute all vertices since new points are at the back
// of the trajectory array and all index intervals would be invalidated
clearVertexData();
resetIntermediateData();
}
if (_currIndex == INT_MAX) _currIndex = start;
// Iterate over the data points, skipping the first one and
// stopping before the last one
for (; direction*_currIndex < end; _currIndex += spacing)
{
_traj->getPoint(_currIndex, _ma->getDataSource(), newPoint._v);
OpenFrames::DS_Split(newPoint, high, low);
_intermediateVertexHigh->push_back(high);
_intermediateVertexLow->push_back(low);
}
}
}
}
// Number of points last processed
unsigned int _numPoints;
// Whether data was added to trajectory or trajectory was cleared
bool _dataAdded, _dataCleared;
// Whether attenuation parameters should be computed
bool _computeAttenuation;
// Data used to restart intermediate point computations in TIME mode
double _currTime;
// Data used to restart intermediate point computations in DISTANCE mode
int _currIndex;
double _currDistance, _prevDistance, _targetDistance;
// Vertex data arrays
osg::Geometry* _endpointGeom;
osg::Vec3Array* _endpointVertexHigh;
osg::Vec3Array* _endpointVertexLow;
osg::DrawArrays* _endpointDrawArrays;
osg::Geometry* _intermediateGeom;
osg::Vec3Array* _intermediateVertexHigh;
osg::Vec3Array* _intermediateVertexLow;
osg::DrawArrays* _intermediateDrawArrays;
const Trajectory* _traj;
MarkerArtist* _ma;
};
// Fragment shader that draws a texture on a PointSprite
static const char *FragSource_Texture = {
"#version 120\n"
"uniform sampler2D tex;\n"
"void main(void)\n"
"{\n"
// Discard fragments with small alpha values
" vec4 t2d = texture2D(tex, gl_TexCoord[0].st);\n"
" if(t2d.a < 0.05)\n"
" {\n"
" discard;\n"
" }\n"
// Color the texture with user-specified color
" gl_FragColor = t2d*gl_Color;\n"
"}\n"
};
// Fragment shader that draws a solid disk on a PointSprite
static const char *FragSource_Disk = {
"#version 120\n"
"vec2 v;\n"
"void main(void)\n"
"{\n"
// gl_PointCoord has range (x,y) in [0, 1] each, with y-down
// Move origin to point center, with extents [-0.5, 0.5]
" v = gl_PointCoord - vec2(0.5);\n"
// Throw away fragments outside the disk (radius > 0.5)
" if(dot(v, v) > 0.25)\n"
" {\n"
" discard;\n"
" }\n"
// Remaining fragments get the user-specified color
" gl_FragColor = gl_Color;\n"
"}\n"
};
MarkerArtist::MarkerArtist(const Trajectory *traj)
: _markers(START | END), _intermediateType(DATA), _intermediateSpacing(1.0),
_intermediateDirection(START), _dataValid(true), _dataZero(true), _attenuationDirty(true)
{
setTrajectory(traj); // Set the specified trajectory
unsigned int dof = 0;
if (_traj.valid()) dof = _traj->getDOF();
// By default, the MarkerArtist will draw a point at the origin. If
// a trajectory is specified, then it will instead attempt to draw
// the position components of the trajectory.
Trajectory::DataSource data;
data._src = Trajectory::POSOPT;
if (dof >= 1)
{
data._element = 0;
setXData(data);
}
if (dof >= 2)
{
data._element = 1;
setYData(data);
}
if (dof >= 3)
{
data._element = 2;
setZData(data);
}
// Initialize point properties
osg::StateSet *ss = getOrCreateStateSet();
ss->setAttribute(new osg::Point); // Allows marker resizing
osg::PointSprite *sprite = new osg::PointSprite();
ss->setTextureAttributeAndModes(0, sprite);
// Assume marker may have transparency
ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
// Set up alpha blending for marker
osg::BlendFunc *fn = new osg::BlendFunc();
fn->setFunction(osg::BlendFunc::SRC_ALPHA,
osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
ss->setAttributeAndModes(fn);
// Install fragment shader to draw the marker
_fragShader = new osg::Shader(osg::Shader::FRAGMENT);
_program->addShader(_fragShader);
resetMarkerShader(); // Set default shader
// Initialize colors for Start & End markers
_endpointColors = new osg::Vec4Array(2);
(*_endpointColors)[0] = osg::Vec4(1.0, 0.0, 0.0, 1.0); // Start marker
(*_endpointColors)[1] = osg::Vec4(1.0, 0.0, 0.0, 1.0); // End marker
_endpointColors->setBinding(osg::Array::BIND_PER_VERTEX);
// Initialize color for Intermediate markers
// Currently we use one color for the whole trajectory, but this can be
// changed later for per-vertex colors
_intermediateColors = new osg::Vec4Array(1);
(*_intermediateColors)[0] = osg::Vec4(1.0, 1.0, 1.0, 1.0);
_intermediateColors->setBinding(osg::Array::BIND_OVERALL);
// Set default marker color and size
setMarkerColor(_markers, 1.0, 0.0, 0.0);
setMarkerSize(10);
// Initialize geometry that will draw Start and End markers
osg::Geometry *endpointGeom = new osg::Geometry;
endpointGeom->setDataVariance(osg::Object::DYNAMIC);
endpointGeom->setUseDisplayList(false);
endpointGeom->setUseVertexBufferObjects(true);
endpointGeom->setVertexArray(new osg::Vec3Array(2)); // Always 2 endpoints
endpointGeom->setVertexAttribArray(OF_VERTEXLOW, new osg::Vec3Array(2), osg::Array::BIND_PER_VERTEX);
endpointGeom->setColorArray(_endpointColors);
endpointGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS, 0, 0));
addDrawable(endpointGeom);
// Initialize geometry that will draw Intermediate markers
osg::Geometry *intermediateGeom = new osg::Geometry;
intermediateGeom->setDataVariance(osg::Object::DYNAMIC);
intermediateGeom->setUseDisplayList(false);
intermediateGeom->setUseVertexBufferObjects(true);
intermediateGeom->setVertexArray(new osg::Vec3Array());
intermediateGeom->setVertexAttribArray(OF_VERTEXLOW, new osg::Vec3Array(), osg::Array::BIND_PER_VERTEX);
intermediateGeom->setColorArray(_intermediateColors);
intermediateGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS, 0, 0));
addDrawable(intermediateGeom);
// Add callback that updates our geometry when the Trajectory changes
addUpdateCallback(new MarkerArtistUpdateCallback());
// Set the auto point size attenuation
setAutoAttenuate(false);
}
// Not using the copy constructor
MarkerArtist::MarkerArtist( const MarkerArtist &ca, const osg::CopyOp& copyop )
{}
MarkerArtist::~MarkerArtist()
{}
void MarkerArtist::setTrajectory(const Trajectory *traj)
{
// Do nothing if this artist is already drawing the given Trajectory
if(_traj == traj) return;
// Handle default behavior
TrajectoryArtist::setTrajectory(traj);
verifyData(); // Verify whether the trajectory data is valid
}
bool MarkerArtist::setXData(const Trajectory::DataSource &src)
{
if(_dataSource[0] == src) return _dataValid;
_dataSource[0] = src;
verifyData();
return _dataValid;
}
bool MarkerArtist::setYData(const Trajectory::DataSource &src)
{
if(_dataSource[1] == src) return _dataValid;
_dataSource[1] = src;
verifyData();
return _dataValid;
}
bool MarkerArtist::setZData(const Trajectory::DataSource &src)
{
if(_dataSource[2] == src) return _dataValid;
_dataSource[2] = src;
verifyData();
return _dataValid;
}
void MarkerArtist::setMarkers(unsigned int markers)
{
if(_markers == markers) return;
_markers = markers;
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
cb->dataCleared();
}
void MarkerArtist::setMarkerColor(unsigned int markers,
float r, float g, float b)
{
if(markers & START)
{
(*_endpointColors)[0].set(r, g, b, 1.0); // Start marker
_endpointColors->dirty();
}
if(markers & END)
{
(*_endpointColors)[1].set(r, g, b, 1.0); // End marker
_endpointColors->dirty();
}
if(markers & INTERMEDIATE)
{
(*_intermediateColors)[0].set(r, g, b, 1.0); // Intermediate markers
_intermediateColors->dirty();
}
}
void MarkerArtist::setMarkerSize(unsigned int size)
{
if(size > 0)
{
osg::Point *point = static_cast<osg::Point*>(getOrCreateStateSet()->getAttribute(osg::StateAttribute::POINT));
point->setSize(size);
point->setMaxSize(size);
}
}
bool MarkerArtist::setMarkerImage(const std::string &fname)
{
// Remove any existing marker image
if(fname.length() == 0)
{
resetMarkerShader();
return true;
}
// Load image from file
osg::Image *image = osgDB::readImageFile(fname);
if(image)
{
osg::StateSet *ss = getOrCreateStateSet();
// Specify texture to use for point sprite
osg::Texture2D *tex = new osg::Texture2D(image);
ss->setTextureAttributeAndModes(0, tex);
// Fragment shader to draw the marker texture
_fragShader->setShaderSource(FragSource_Texture);
return true;
}
else
{
OSG_WARN << "OpenFrames::MarkerArtist ERROR: Image file \'" << fname << "\' could not be found!" << std::endl;
return false; // Image was not found
}
}
bool MarkerArtist::setMarkerShader(const std::string &fname)
{
// Reset shader
if(fname.length() == 0)
{
resetMarkerShader();
return true;
}
// Load shader source from file
std::string fullFile = osgDB::findDataFile(fname);
bool success = _fragShader->loadShaderSourceFromFile(fullFile);
if(!success)
{
OSG_WARN << "OpenFrames::MarkerArtist ERROR: Shader file \'" << fname << "\' not properly loaded!" << std::endl;
return false;
}
return true;
}
void MarkerArtist::setAutoAttenuate(bool attenuate)
{
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
cb->setComputeAttenuation(attenuate);
}
bool MarkerArtist::getAutoAttenuate() const
{
const MarkerArtistUpdateCallback *cb = static_cast<const MarkerArtistUpdateCallback*>(getUpdateCallback());
return cb->getComputeAttenuation();
}
void MarkerArtist::setIntermediateType(IntermediateType type)
{
if(_intermediateType != type)
{
_intermediateType = type;
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
return cb->dataCleared();
}
}
void MarkerArtist::setIntermediateSpacing(double spacing)
{
if((_intermediateSpacing != spacing) && (spacing > 0.0))
{
_intermediateSpacing = spacing;
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
return cb->dataCleared();
}
}
void MarkerArtist::setIntermediateDirection(DrawnMarkers direction)
{
if(_intermediateDirection != direction)
{
_intermediateDirection = direction;
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
return cb->dataCleared();
}
}
void MarkerArtist::dataCleared(const Trajectory* traj)
{
verifyData();
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
cb->dataCleared();
}
void MarkerArtist::dataAdded(const Trajectory* traj)
{
MarkerArtistUpdateCallback *cb = static_cast<MarkerArtistUpdateCallback*>(getUpdateCallback());
cb->dataAdded();
}
void MarkerArtist::computeAttenuation()
{
// Make sure we need to recompute the attenuation parameters
if(!_attenuationDirty) return;
// The computed point size is based on the specified point size and
// the attenuation parameters a, b, c. See glPointParameter with the
// parameter of GL_POINT_DISTANCE_ATTENUATION for more info.
// The equation is:
// computed size = clamp(specified size * sqrt(1/(a + b*d + c*d*d)))
// where d is the eye-distance to the point
// Here we compute attenuation parameters such that the tick marks
// will be visible at distances proportional to the size of the sphere
// encompassing all of the markers.
float a, b, c; // Coefficients for attenuation
bool computedParams;
if(_boundingSphere.valid())
{
// Get size of the bounding sphere
double length = _boundingSphere._radius;
// If size is too small, then don't auto-attenuate
if(length < 1.0e-8)
{
a = 1.0;
b = c = 0.0;
}
else // Otherwise auto-attenuate normally
{
a = c = 0.0;
b = 1.0/length;
}
computedParams = true;
}
else
{
// Disable attenuation until the bounding sphere is available
a = 1.0;
b = c = 0.0;
computedParams = false;
}
osg::Vec3 attenuation(a, b, c);
// Get the Point parameter for the major tick marks
osg::Point *point = static_cast<osg::Point*>(getOrCreateStateSet()->getAttribute(osg::StateAttribute::POINT));
point->setDistanceAttenuation(attenuation);
if(computedParams) _attenuationDirty = false; // Parameters computed
}
void MarkerArtist::verifyData() const
{
if(_dataSource[0]._src == Trajectory::ZERO &&
_dataSource[1]._src == Trajectory::ZERO &&
_dataSource[2]._src == Trajectory::ZERO)
{
_dataValid = true;
_dataZero = true;
}
else if(_traj.valid())
{
_dataValid = _traj->verifyData(_dataSource);
_dataZero = false;
}
else
{
_dataValid = false;
_dataZero = false;
}
}
void MarkerArtist::resetMarkerShader()
{
osg::StateSet *ss = getOrCreateStateSet();
// Remove existing image texture
ss->removeTextureAttribute(0, osg::StateAttribute::TEXTURE);
// Default to circular point marker
_fragShader->setShaderSource(FragSource_Disk);
}
}
| 30.711449 | 131 | 0.667237 | [
"geometry",
"object",
"solid"
] |
11f019b9b8920f25fe9a4cb6aba7aba87a73efb2 | 85,880 | cc | C++ | media/gpu/video_encode_accelerator_unittest.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | media/gpu/video_encode_accelerator_unittest.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | media/gpu/video_encode_accelerator_unittest.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/bits.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/aligned_memory.h"
#include "base/memory/scoped_vector.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/process_handle.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/bitstream_buffer.h"
#include "media/base/cdm_context.h"
#include "media/base/decoder_buffer.h"
#include "media/base/media_util.h"
#include "media/base/test_data_util.h"
#include "media/base/video_decoder.h"
#include "media/base/video_frame.h"
#include "media/filters/ffmpeg_glue.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "media/filters/h264_parser.h"
#include "media/filters/ivf_parser.h"
#include "media/gpu/video_accelerator_unittest_helpers.h"
#include "media/video/fake_video_encode_accelerator.h"
#include "media/video/video_encode_accelerator.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_CHROMEOS)
#if defined(USE_V4L2_CODEC)
#include "base/threading/thread_task_runner_handle.h"
#include "media/gpu/v4l2_video_encode_accelerator.h"
#endif
#if defined(ARCH_CPU_X86_FAMILY)
#include "media/gpu/vaapi_video_encode_accelerator.h"
#include "media/gpu/vaapi_wrapper.h"
// Status has been defined as int in Xlib.h.
#undef Status
#endif // defined(ARCH_CPU_X86_FAMILY)
#elif defined(OS_MACOSX)
#include "media/gpu/vt_video_encode_accelerator_mac.h"
#elif defined(OS_WIN)
#include "media/gpu/media_foundation_video_encode_accelerator_win.h"
#else
#error The VideoEncodeAcceleratorUnittest is not supported on this platform.
#endif
namespace media {
namespace {
const VideoPixelFormat kInputFormat = PIXEL_FORMAT_I420;
// The absolute differences between original frame and decoded frame usually
// ranges aroud 1 ~ 7. So we pick 10 as an extreme value to detect abnormal
// decoded frames.
const double kDecodeSimilarityThreshold = 10.0;
// Arbitrarily chosen to add some depth to the pipeline.
const unsigned int kNumOutputBuffers = 4;
const unsigned int kNumExtraInputFrames = 4;
// Maximum delay between requesting a keyframe and receiving one, in frames.
// Arbitrarily chosen as a reasonable requirement.
const unsigned int kMaxKeyframeDelay = 4;
// Default initial bitrate.
const uint32_t kDefaultBitrate = 2000000;
// Default ratio of requested_subsequent_bitrate to initial_bitrate
// (see test parameters below) if one is not provided.
const double kDefaultSubsequentBitrateRatio = 2.0;
// Default initial framerate.
const uint32_t kDefaultFramerate = 30;
// Default ratio of requested_subsequent_framerate to initial_framerate
// (see test parameters below) if one is not provided.
const double kDefaultSubsequentFramerateRatio = 0.1;
// Tolerance factor for how encoded bitrate can differ from requested bitrate.
const double kBitrateTolerance = 0.1;
// Minimum required FPS throughput for the basic performance test.
const uint32_t kMinPerfFPS = 30;
// Minimum (arbitrary) number of frames required to enforce bitrate requirements
// over. Streams shorter than this may be too short to realistically require
// an encoder to be able to converge to the requested bitrate over.
// The input stream will be looped as many times as needed in bitrate tests
// to reach at least this number of frames before calculating final bitrate.
const unsigned int kMinFramesForBitrateTests = 300;
// The percentiles to measure for encode latency.
const unsigned int kLoggedLatencyPercentiles[] = {50, 75, 95};
// The syntax of multiple test streams is:
// test-stream1;test-stream2;test-stream3
// The syntax of each test stream is:
// "in_filename:width:height:profile:out_filename:requested_bitrate
// :requested_framerate:requested_subsequent_bitrate
// :requested_subsequent_framerate"
// Instead of ":", "," can be used as a seperator as well. Note that ":" does
// not work on Windows as it interferes with file paths.
// - |in_filename| must be an I420 (YUV planar) raw stream
// (see http://www.fourcc.org/yuv.php#IYUV).
// - |width| and |height| are in pixels.
// - |profile| to encode into (values of VideoCodecProfile).
// - |out_filename| filename to save the encoded stream to (optional). The
// format for H264 is Annex-B byte stream. The format for VP8 is IVF. Output
// stream is saved for the simple encode test only. H264 raw stream and IVF
// can be used as input of VDA unittest. H264 raw stream can be played by
// "mplayer -fps 25 out.h264" and IVF can be played by mplayer directly.
// Helpful description: http://wiki.multimedia.cx/index.php?title=IVF
// Further parameters are optional (need to provide preceding positional
// parameters if a specific subsequent parameter is required):
// - |requested_bitrate| requested bitrate in bits per second.
// - |requested_framerate| requested initial framerate.
// - |requested_subsequent_bitrate| bitrate to switch to in the middle of the
// stream.
// - |requested_subsequent_framerate| framerate to switch to in the middle
// of the stream.
// Bitrate is only forced for tests that test bitrate.
const char* g_default_in_filename = "bear_320x192_40frames.yuv";
#if defined(OS_CHROMEOS)
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(":320:192:1:out.h264:200000");
#elif defined(OS_MACOSX) || defined(OS_WIN)
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(",320,192,0,out.h264,200000");
#endif // defined(OS_CHROMEOS)
// Enabled by including a --fake_encoder flag to the command line invoking the
// test.
bool g_fake_encoder = false;
// Environment to store test stream data for all test cases.
class VideoEncodeAcceleratorTestEnvironment;
VideoEncodeAcceleratorTestEnvironment* g_env;
// The number of frames to be encoded. This variable is set by the switch
// "--num_frames_to_encode". Ignored if 0.
int g_num_frames_to_encode = 0;
#ifdef ARCH_CPU_ARMEL
// ARM performs CPU cache management with CPU cache line granularity. We thus
// need to ensure our buffers are CPU cache line-aligned (64 byte-aligned).
// Otherwise newer kernels will refuse to accept them, and on older kernels
// we'll be treating ourselves to random corruption.
// Moreover, some hardware codecs require 128-byte alignment for physical
// buffers.
const size_t kPlatformBufferAlignment = 128;
#else
const size_t kPlatformBufferAlignment = 8;
#endif
inline static size_t AlignToPlatformRequirements(size_t value) {
return base::bits::Align(value, kPlatformBufferAlignment);
}
// An aligned STL allocator.
template <typename T, size_t ByteAlignment>
class AlignedAllocator : public std::allocator<T> {
public:
typedef size_t size_type;
typedef T* pointer;
template <class T1>
struct rebind {
typedef AlignedAllocator<T1, ByteAlignment> other;
};
AlignedAllocator() {}
explicit AlignedAllocator(const AlignedAllocator&) {}
template <class T1>
explicit AlignedAllocator(const AlignedAllocator<T1, ByteAlignment>&) {}
~AlignedAllocator() {}
pointer allocate(size_type n, const void* = 0) {
return static_cast<pointer>(base::AlignedAlloc(n, ByteAlignment));
}
void deallocate(pointer p, size_type n) {
base::AlignedFree(static_cast<void*>(p));
}
size_type max_size() const {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
};
struct TestStream {
TestStream()
: num_frames(0),
aligned_buffer_size(0),
requested_bitrate(0),
requested_framerate(0),
requested_subsequent_bitrate(0),
requested_subsequent_framerate(0) {}
~TestStream() {}
gfx::Size visible_size;
gfx::Size coded_size;
unsigned int num_frames;
// Original unaligned input file name provided as an argument to the test.
// And the file must be an I420 (YUV planar) raw stream.
std::string in_filename;
// A vector used to prepare aligned input buffers of |in_filename|. This
// makes sure starting addresses of YUV planes are aligned to
// kPlatformBufferAlignment bytes.
std::vector<char, AlignedAllocator<char, kPlatformBufferAlignment>>
aligned_in_file_data;
// Byte size of a frame of |aligned_in_file_data|.
size_t aligned_buffer_size;
// Byte size for each aligned plane of a frame.
std::vector<size_t> aligned_plane_size;
std::string out_filename;
VideoCodecProfile requested_profile;
unsigned int requested_bitrate;
unsigned int requested_framerate;
unsigned int requested_subsequent_bitrate;
unsigned int requested_subsequent_framerate;
};
// Return the |percentile| from a sorted vector.
static base::TimeDelta Percentile(
const std::vector<base::TimeDelta>& sorted_values,
unsigned int percentile) {
size_t size = sorted_values.size();
LOG_ASSERT(size > 0UL);
LOG_ASSERT(percentile <= 100UL);
// Use Nearest Rank method in http://en.wikipedia.org/wiki/Percentile.
int index =
std::max(static_cast<int>(ceil(0.01f * percentile * size)) - 1, 0);
return sorted_values[index];
}
static bool IsH264(VideoCodecProfile profile) {
return profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX;
}
static bool IsVP8(VideoCodecProfile profile) {
return profile >= VP8PROFILE_MIN && profile <= VP8PROFILE_MAX;
}
// Helper functions to do string conversions.
static base::FilePath::StringType StringToFilePathStringType(
const std::string& str) {
#if defined(OS_WIN)
return base::UTF8ToWide(str);
#else
return str;
#endif // defined(OS_WIN)
}
static std::string FilePathStringTypeToString(
const base::FilePath::StringType& str) {
#if defined(OS_WIN)
return base::WideToUTF8(str);
#else
return str;
#endif // defined(OS_WIN)
}
// Some platforms may have requirements on physical memory buffer alignment.
// Since we are just mapping and passing chunks of the input file directly to
// the VEA as input frames, to avoid copying large chunks of raw data on each
// frame, and thus affecting performance measurements, we have to prepare a
// temporary file with all planes aligned to the required alignment beforehand.
static void CreateAlignedInputStreamFile(const gfx::Size& coded_size,
TestStream* test_stream) {
// Test case may have many encoders and memory should be prepared once.
if (test_stream->coded_size == coded_size &&
!test_stream->aligned_in_file_data.empty())
return;
// All encoders in multiple encoder test reuse the same test_stream, make
// sure they requested the same coded_size
ASSERT_TRUE(test_stream->aligned_in_file_data.empty() ||
coded_size == test_stream->coded_size);
test_stream->coded_size = coded_size;
size_t num_planes = VideoFrame::NumPlanes(kInputFormat);
std::vector<size_t> padding_sizes(num_planes);
std::vector<size_t> coded_bpl(num_planes);
std::vector<size_t> visible_bpl(num_planes);
std::vector<size_t> visible_plane_rows(num_planes);
// Calculate padding in bytes to be added after each plane required to keep
// starting addresses of all planes at a byte boundary required by the
// platform. This padding will be added after each plane when copying to the
// temporary file.
// At the same time we also need to take into account coded_size requested by
// the VEA; each row of visible_bpl bytes in the original file needs to be
// copied into a row of coded_bpl bytes in the aligned file.
for (size_t i = 0; i < num_planes; i++) {
const size_t size =
VideoFrame::PlaneSize(kInputFormat, i, coded_size).GetArea();
test_stream->aligned_plane_size.push_back(
AlignToPlatformRequirements(size));
test_stream->aligned_buffer_size += test_stream->aligned_plane_size.back();
coded_bpl[i] = VideoFrame::RowBytes(i, kInputFormat, coded_size.width());
visible_bpl[i] = VideoFrame::RowBytes(i, kInputFormat,
test_stream->visible_size.width());
visible_plane_rows[i] =
VideoFrame::Rows(i, kInputFormat, test_stream->visible_size.height());
const size_t padding_rows =
VideoFrame::Rows(i, kInputFormat, coded_size.height()) -
visible_plane_rows[i];
padding_sizes[i] =
padding_rows * coded_bpl[i] + AlignToPlatformRequirements(size) - size;
}
base::FilePath src_file(StringToFilePathStringType(test_stream->in_filename));
int64_t src_file_size = 0;
LOG_ASSERT(base::GetFileSize(src_file, &src_file_size));
size_t visible_buffer_size =
VideoFrame::AllocationSize(kInputFormat, test_stream->visible_size);
LOG_ASSERT(src_file_size % visible_buffer_size == 0U)
<< "Stream byte size is not a product of calculated frame byte size";
test_stream->num_frames =
static_cast<unsigned int>(src_file_size / visible_buffer_size);
LOG_ASSERT(test_stream->aligned_buffer_size > 0UL);
test_stream->aligned_in_file_data.resize(test_stream->aligned_buffer_size *
test_stream->num_frames);
base::File src(src_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
std::vector<char> src_data(visible_buffer_size);
off_t src_offset = 0, dest_offset = 0;
for (size_t frame = 0; frame < test_stream->num_frames; frame++) {
LOG_ASSERT(src.Read(src_offset, &src_data[0],
static_cast<int>(visible_buffer_size)) ==
static_cast<int>(visible_buffer_size));
const char* src_ptr = &src_data[0];
for (size_t i = 0; i < num_planes; i++) {
// Assert that each plane of frame starts at required byte boundary.
ASSERT_EQ(0u, dest_offset & (kPlatformBufferAlignment - 1))
<< "Planes of frame should be mapped per platform requirements";
for (size_t j = 0; j < visible_plane_rows[i]; j++) {
memcpy(&test_stream->aligned_in_file_data[dest_offset], src_ptr,
visible_bpl[i]);
src_ptr += visible_bpl[i];
dest_offset += static_cast<off_t>(coded_bpl[i]);
}
dest_offset += static_cast<off_t>(padding_sizes[i]);
}
src_offset += static_cast<off_t>(visible_buffer_size);
}
src.Close();
LOG_ASSERT(test_stream->num_frames > 0UL);
}
// Parse |data| into its constituent parts, set the various output fields
// accordingly, read in video stream, and store them to |test_streams|.
static void ParseAndReadTestStreamData(const base::FilePath::StringType& data,
ScopedVector<TestStream>* test_streams) {
// Split the string to individual test stream data.
std::vector<base::FilePath::StringType> test_streams_data =
base::SplitString(data, base::FilePath::StringType(1, ';'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
LOG_ASSERT(test_streams_data.size() >= 1U) << data;
// Parse each test stream data and read the input file.
for (size_t index = 0; index < test_streams_data.size(); ++index) {
std::vector<base::FilePath::StringType> fields = base::SplitString(
test_streams_data[index], base::FilePath::StringType(1, ','),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
// Try using ":" as the seperator if "," isn't used.
if (fields.size() == 1U) {
fields = base::SplitString(test_streams_data[index],
base::FilePath::StringType(1, ':'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
}
LOG_ASSERT(fields.size() >= 4U) << data;
LOG_ASSERT(fields.size() <= 9U) << data;
TestStream* test_stream = new TestStream();
test_stream->in_filename = FilePathStringTypeToString(fields[0]);
int width, height;
bool result = base::StringToInt(fields[1], &width);
LOG_ASSERT(result);
result = base::StringToInt(fields[2], &height);
LOG_ASSERT(result);
test_stream->visible_size = gfx::Size(width, height);
LOG_ASSERT(!test_stream->visible_size.IsEmpty());
int profile;
result = base::StringToInt(fields[3], &profile);
LOG_ASSERT(result);
LOG_ASSERT(profile > VIDEO_CODEC_PROFILE_UNKNOWN);
LOG_ASSERT(profile <= VIDEO_CODEC_PROFILE_MAX);
test_stream->requested_profile = static_cast<VideoCodecProfile>(profile);
if (fields.size() >= 5 && !fields[4].empty())
test_stream->out_filename = FilePathStringTypeToString(fields[4]);
if (fields.size() >= 6 && !fields[5].empty())
LOG_ASSERT(
base::StringToUint(fields[5], &test_stream->requested_bitrate));
if (fields.size() >= 7 && !fields[6].empty())
LOG_ASSERT(
base::StringToUint(fields[6], &test_stream->requested_framerate));
if (fields.size() >= 8 && !fields[7].empty()) {
LOG_ASSERT(base::StringToUint(
fields[7], &test_stream->requested_subsequent_bitrate));
}
if (fields.size() >= 9 && !fields[8].empty()) {
LOG_ASSERT(base::StringToUint(
fields[8], &test_stream->requested_subsequent_framerate));
}
test_streams->push_back(test_stream);
}
}
static std::unique_ptr<VideoEncodeAccelerator> CreateFakeVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
if (g_fake_encoder) {
encoder.reset(new FakeVideoEncodeAccelerator(
scoped_refptr<base::SingleThreadTaskRunner>(
base::ThreadTaskRunnerHandle::Get())));
}
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateV4L2VEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_CHROMEOS) && defined(USE_V4L2_CODEC)
scoped_refptr<V4L2Device> device = V4L2Device::Create();
if (device)
encoder.reset(new V4L2VideoEncodeAccelerator(device));
#endif
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateVaapiVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)
encoder.reset(new VaapiVideoEncodeAccelerator());
#endif
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateVTVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_MACOSX)
encoder.reset(new VTVideoEncodeAccelerator());
#endif
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateMFVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_WIN)
MediaFoundationVideoEncodeAccelerator::PreSandboxInitialization();
encoder.reset(new MediaFoundationVideoEncodeAccelerator());
#endif
return encoder;
}
// Basic test environment shared across multiple test cases. We only need to
// setup it once for all test cases.
// It helps
// - maintain test stream data and other test settings.
// - clean up temporary aligned files.
// - output log to file.
class VideoEncodeAcceleratorTestEnvironment : public ::testing::Environment {
public:
VideoEncodeAcceleratorTestEnvironment(
std::unique_ptr<base::FilePath::StringType> data,
const base::FilePath& log_path,
bool run_at_fps,
bool needs_encode_latency,
bool verify_all_output)
: test_stream_data_(std::move(data)),
log_path_(log_path),
run_at_fps_(run_at_fps),
needs_encode_latency_(needs_encode_latency),
verify_all_output_(verify_all_output) {}
virtual void SetUp() {
if (!log_path_.empty()) {
log_file_.reset(new base::File(
log_path_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE));
LOG_ASSERT(log_file_->IsValid());
}
ParseAndReadTestStreamData(*test_stream_data_, &test_streams_);
}
virtual void TearDown() {
log_file_.reset();
}
// Log one entry of machine-readable data to file and LOG(INFO).
// The log has one data entry per line in the format of "<key>: <value>".
// Note that Chrome OS video_VEAPerf autotest parses the output key and value
// pairs. Be sure to keep the autotest in sync.
void LogToFile(const std::string& key, const std::string& value) {
std::string s = base::StringPrintf("%s: %s\n", key.c_str(), value.c_str());
LOG(INFO) << s;
if (log_file_) {
log_file_->WriteAtCurrentPos(s.data(), static_cast<int>(s.length()));
}
}
// Feed the encoder with the input buffers at the requested framerate. If
// false, feed as fast as possible. This is set by the command line switch
// "--run_at_fps".
bool run_at_fps() const { return run_at_fps_; }
// Whether to measure encode latency. This is set by the command line switch
// "--measure_latency".
bool needs_encode_latency() const { return needs_encode_latency_; }
// Verify the encoder output of all testcases. This is set by the command line
// switch "--verify_all_output".
bool verify_all_output() const { return verify_all_output_; }
ScopedVector<TestStream> test_streams_;
private:
std::unique_ptr<base::FilePath::StringType> test_stream_data_;
base::FilePath log_path_;
std::unique_ptr<base::File> log_file_;
bool run_at_fps_;
bool needs_encode_latency_;
bool verify_all_output_;
};
enum ClientState {
CS_CREATED,
CS_INITIALIZED,
CS_ENCODING,
// Encoding has finished.
CS_FINISHED,
// Encoded frame quality has been validated.
CS_VALIDATED,
CS_ERROR,
};
// Performs basic, codec-specific sanity checks on the stream buffers passed
// to ProcessStreamBuffer(): whether we've seen keyframes before non-keyframes,
// correct sequences of H.264 NALUs (SPS before PPS and before slices), etc.
// Calls given FrameFoundCallback when a complete frame is found while
// processing.
class StreamValidator {
public:
// To be called when a complete frame is found while processing a stream
// buffer, passing true if the frame is a keyframe. Returns false if we
// are not interested in more frames and further processing should be aborted.
typedef base::Callback<bool(bool)> FrameFoundCallback;
virtual ~StreamValidator() {}
// Provide a StreamValidator instance for the given |profile|.
static std::unique_ptr<StreamValidator> Create(
VideoCodecProfile profile,
const FrameFoundCallback& frame_cb);
// Process and verify contents of a bitstream buffer.
virtual void ProcessStreamBuffer(const uint8_t* stream, size_t size) = 0;
protected:
explicit StreamValidator(const FrameFoundCallback& frame_cb)
: frame_cb_(frame_cb) {}
FrameFoundCallback frame_cb_;
};
class H264Validator : public StreamValidator {
public:
explicit H264Validator(const FrameFoundCallback& frame_cb)
: StreamValidator(frame_cb),
seen_sps_(false),
seen_pps_(false),
seen_idr_(false) {}
void ProcessStreamBuffer(const uint8_t* stream, size_t size) override;
private:
// Set to true when encoder provides us with the corresponding NALU type.
bool seen_sps_;
bool seen_pps_;
bool seen_idr_;
H264Parser h264_parser_;
};
void H264Validator::ProcessStreamBuffer(const uint8_t* stream, size_t size) {
h264_parser_.SetStream(stream, static_cast<off_t>(size));
while (1) {
H264NALU nalu;
H264Parser::Result result;
result = h264_parser_.AdvanceToNextNALU(&nalu);
if (result == H264Parser::kEOStream)
break;
ASSERT_EQ(H264Parser::kOk, result);
bool keyframe = false;
switch (nalu.nal_unit_type) {
case H264NALU::kIDRSlice:
ASSERT_TRUE(seen_sps_);
ASSERT_TRUE(seen_pps_);
seen_idr_ = true;
keyframe = true;
// fallthrough
case H264NALU::kNonIDRSlice: {
ASSERT_TRUE(seen_idr_);
seen_sps_ = seen_pps_ = false;
if (!frame_cb_.Run(keyframe))
return;
break;
}
case H264NALU::kSPS: {
int sps_id;
ASSERT_EQ(H264Parser::kOk, h264_parser_.ParseSPS(&sps_id));
seen_sps_ = true;
break;
}
case H264NALU::kPPS: {
ASSERT_TRUE(seen_sps_);
int pps_id;
ASSERT_EQ(H264Parser::kOk, h264_parser_.ParsePPS(&pps_id));
seen_pps_ = true;
break;
}
default:
break;
}
}
}
class VP8Validator : public StreamValidator {
public:
explicit VP8Validator(const FrameFoundCallback& frame_cb)
: StreamValidator(frame_cb), seen_keyframe_(false) {}
void ProcessStreamBuffer(const uint8_t* stream, size_t size) override;
private:
// Have we already got a keyframe in the stream?
bool seen_keyframe_;
};
void VP8Validator::ProcessStreamBuffer(const uint8_t* stream, size_t size) {
bool keyframe = !(stream[0] & 0x01);
if (keyframe)
seen_keyframe_ = true;
EXPECT_TRUE(seen_keyframe_);
frame_cb_.Run(keyframe);
// TODO(posciak): We could be getting more frames in the buffer, but there is
// no simple way to detect this. We'd need to parse the frames and go through
// partition numbers/sizes. For now assume one frame per buffer.
}
// static
std::unique_ptr<StreamValidator> StreamValidator::Create(
VideoCodecProfile profile,
const FrameFoundCallback& frame_cb) {
std::unique_ptr<StreamValidator> validator;
if (IsH264(profile)) {
validator.reset(new H264Validator(frame_cb));
} else if (IsVP8(profile)) {
validator.reset(new VP8Validator(frame_cb));
} else {
LOG(FATAL) << "Unsupported profile: " << GetProfileName(profile);
}
return validator;
}
class VideoFrameQualityValidator {
public:
VideoFrameQualityValidator(const VideoCodecProfile profile,
const base::Closure& flush_complete_cb,
const base::Closure& decode_error_cb);
void Initialize(const gfx::Size& coded_size, const gfx::Rect& visible_size);
// Save original YUV frame to compare it with the decoded frame later.
void AddOriginalFrame(scoped_refptr<VideoFrame> frame);
void AddDecodeBuffer(const scoped_refptr<DecoderBuffer>& buffer);
// Flush the decoder.
void Flush();
private:
void InitializeCB(bool success);
void DecodeDone(DecodeStatus status);
void FlushDone(DecodeStatus status);
void VerifyOutputFrame(const scoped_refptr<VideoFrame>& output_frame);
void Decode();
enum State { UNINITIALIZED, INITIALIZED, DECODING, DECODER_ERROR };
const VideoCodecProfile profile_;
std::unique_ptr<FFmpegVideoDecoder> decoder_;
VideoDecoder::DecodeCB decode_cb_;
// Decode callback of an EOS buffer.
VideoDecoder::DecodeCB eos_decode_cb_;
// Callback of Flush(). Called after all frames are decoded.
const base::Closure flush_complete_cb_;
const base::Closure decode_error_cb_;
State decoder_state_;
std::queue<scoped_refptr<VideoFrame>> original_frames_;
std::queue<scoped_refptr<DecoderBuffer>> decode_buffers_;
};
VideoFrameQualityValidator::VideoFrameQualityValidator(
const VideoCodecProfile profile,
const base::Closure& flush_complete_cb,
const base::Closure& decode_error_cb)
: profile_(profile),
decoder_(new FFmpegVideoDecoder()),
decode_cb_(base::Bind(&VideoFrameQualityValidator::DecodeDone,
base::Unretained(this))),
eos_decode_cb_(base::Bind(&VideoFrameQualityValidator::FlushDone,
base::Unretained(this))),
flush_complete_cb_(flush_complete_cb),
decode_error_cb_(decode_error_cb),
decoder_state_(UNINITIALIZED) {
// Allow decoding of individual NALU. Entire frames are required by default.
decoder_->set_decode_nalus(true);
}
void VideoFrameQualityValidator::Initialize(const gfx::Size& coded_size,
const gfx::Rect& visible_size) {
FFmpegGlue::InitializeFFmpeg();
gfx::Size natural_size(visible_size.size());
// The default output format of ffmpeg video decoder is YV12.
VideoDecoderConfig config;
if (IsVP8(profile_))
config.Initialize(kCodecVP8, VP8PROFILE_ANY, kInputFormat,
COLOR_SPACE_UNSPECIFIED, coded_size, visible_size,
natural_size, EmptyExtraData(), Unencrypted());
else if (IsH264(profile_))
config.Initialize(kCodecH264, H264PROFILE_MAIN, kInputFormat,
COLOR_SPACE_UNSPECIFIED, coded_size, visible_size,
natural_size, EmptyExtraData(), Unencrypted());
else
LOG_ASSERT(0) << "Invalid profile " << GetProfileName(profile_);
decoder_->Initialize(
config, false, nullptr,
base::Bind(&VideoFrameQualityValidator::InitializeCB,
base::Unretained(this)),
base::Bind(&VideoFrameQualityValidator::VerifyOutputFrame,
base::Unretained(this)));
}
void VideoFrameQualityValidator::InitializeCB(bool success) {
if (success) {
decoder_state_ = INITIALIZED;
Decode();
} else {
decoder_state_ = DECODER_ERROR;
if (IsH264(profile_))
LOG(ERROR) << "Chromium does not support H264 decode. Try Chrome.";
decode_error_cb_.Run();
FAIL() << "Decoder initialization error";
}
}
void VideoFrameQualityValidator::AddOriginalFrame(
scoped_refptr<VideoFrame> frame) {
original_frames_.push(frame);
}
void VideoFrameQualityValidator::DecodeDone(DecodeStatus status) {
if (status == DecodeStatus::OK) {
decoder_state_ = INITIALIZED;
Decode();
} else {
decoder_state_ = DECODER_ERROR;
decode_error_cb_.Run();
FAIL() << "Unexpected decode status = " << status << ". Stop decoding.";
}
}
void VideoFrameQualityValidator::FlushDone(DecodeStatus status) {
flush_complete_cb_.Run();
}
void VideoFrameQualityValidator::Flush() {
if (decoder_state_ != DECODER_ERROR) {
decode_buffers_.push(DecoderBuffer::CreateEOSBuffer());
Decode();
}
}
void VideoFrameQualityValidator::AddDecodeBuffer(
const scoped_refptr<DecoderBuffer>& buffer) {
if (decoder_state_ != DECODER_ERROR) {
decode_buffers_.push(buffer);
Decode();
}
}
void VideoFrameQualityValidator::Decode() {
if (decoder_state_ == INITIALIZED && !decode_buffers_.empty()) {
scoped_refptr<DecoderBuffer> next_buffer = decode_buffers_.front();
decode_buffers_.pop();
decoder_state_ = DECODING;
if (next_buffer->end_of_stream())
decoder_->Decode(next_buffer, eos_decode_cb_);
else
decoder_->Decode(next_buffer, decode_cb_);
}
}
void VideoFrameQualityValidator::VerifyOutputFrame(
const scoped_refptr<VideoFrame>& output_frame) {
scoped_refptr<VideoFrame> original_frame = original_frames_.front();
original_frames_.pop();
gfx::Size visible_size = original_frame->visible_rect().size();
int planes[] = {VideoFrame::kYPlane, VideoFrame::kUPlane,
VideoFrame::kVPlane};
double difference = 0;
for (int plane : planes) {
uint8_t* original_plane = original_frame->data(plane);
uint8_t* output_plane = output_frame->data(plane);
size_t rows = VideoFrame::Rows(plane, kInputFormat, visible_size.height());
size_t columns =
VideoFrame::Columns(plane, kInputFormat, visible_size.width());
size_t stride = original_frame->stride(plane);
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < columns; j++) {
difference += std::abs(original_plane[stride * i + j] -
output_plane[stride * i + j]);
}
}
}
// Divide the difference by the size of frame.
difference /= VideoFrame::AllocationSize(kInputFormat, visible_size);
EXPECT_TRUE(difference <= kDecodeSimilarityThreshold)
<< "difference = " << difference << " > decode similarity threshold";
}
// Base class for all VEA Clients in this file
class VEAClientBase : public VideoEncodeAccelerator::Client {
public:
~VEAClientBase() override { LOG_ASSERT(!has_encoder()); }
void NotifyError(VideoEncodeAccelerator::Error error) override {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ERROR);
}
protected:
VEAClientBase(ClientStateNotification<ClientState>* note)
: note_(note), next_output_buffer_id_(0) {}
bool has_encoder() { return encoder_.get(); }
virtual void SetState(ClientState new_state) = 0;
std::unique_ptr<VideoEncodeAccelerator> encoder_;
// Used to notify another thread about the state. VEAClientBase does not own
// this.
ClientStateNotification<ClientState>* note_;
// All methods of this class should be run on the same thread.
base::ThreadChecker thread_checker_;
ScopedVector<base::SharedMemory> output_shms_;
int32_t next_output_buffer_id_;
};
class VEAClient : public VEAClientBase {
public:
VEAClient(TestStream* test_stream,
ClientStateNotification<ClientState>* note,
bool save_to_file,
unsigned int keyframe_period,
bool force_bitrate,
bool test_perf,
bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch,
bool verify_output,
bool verify_output_timestamp);
void CreateEncoder();
void DestroyEncoder();
void TryToSetupEncodeOnSeperateThread();
void DestroyEncodeOnSeperateThread();
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) override;
private:
void BitstreamBufferReadyOnMainThread(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp);
// Return the number of encoded frames per second.
double frames_per_second();
void SetState(ClientState new_state) override;
// Set current stream parameters to given |bitrate| at |framerate|.
void SetStreamParameters(unsigned int bitrate, unsigned int framerate);
// Called when encoder is done with a VideoFrame.
void InputNoLongerNeededCallback(int32_t input_id);
// Feed the encoder with one input frame.
void FeedEncoderWithOneInput();
// Provide the encoder with a new output buffer.
void FeedEncoderWithOutput(base::SharedMemory* shm);
// Called on finding a complete frame (with |keyframe| set to true for
// keyframes) in the stream, to perform codec-independent, per-frame checks
// and accounting. Returns false once we have collected all frames we needed.
bool HandleEncodedFrame(bool keyframe);
// Verify the minimum FPS requirement.
void VerifyMinFPS();
// Verify that stream bitrate has been close to current_requested_bitrate_,
// assuming current_framerate_ since the last time VerifyStreamProperties()
// was called. Fail the test if |force_bitrate_| is true and the bitrate
// is not within kBitrateTolerance.
void VerifyStreamProperties();
// Log the performance data.
void LogPerf();
// Write IVF file header to test_stream_->out_filename.
void WriteIvfFileHeader();
// Write an IVF frame header to test_stream_->out_filename.
void WriteIvfFrameHeader(int frame_index, size_t frame_size);
// Create and return a VideoFrame wrapping the data at |position| bytes in the
// input stream.
scoped_refptr<VideoFrame> CreateFrame(off_t position);
// Prepare and return a frame wrapping the data at |position| bytes in the
// input stream, ready to be sent to encoder.
// The input frame id is returned in |input_id|.
scoped_refptr<VideoFrame> PrepareInputFrame(off_t position,
int32_t* input_id);
// Update the parameters according to |mid_stream_bitrate_switch| and
// |mid_stream_framerate_switch|.
void UpdateTestStreamData(bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch);
// Callback function of the |input_timer_|.
void OnInputTimer();
// Called when the quality validator has decoded all the frames.
void DecodeCompleted();
// Called when the quality validator fails to decode a frame.
void DecodeFailed();
// Verify that the output timestamp matches input timestamp.
void VerifyOutputTimestamp(base::TimeDelta timestamp);
ClientState state_;
TestStream* test_stream_;
// Ids assigned to VideoFrames.
std::set<int32_t> inputs_at_client_;
int32_t next_input_id_;
// Encode start time of all encoded frames. The position in the vector is the
// frame input id.
std::vector<base::TimeTicks> encode_start_time_;
// The encode latencies of all encoded frames. We define encode latency as the
// time delay from input of each VideoFrame (VEA::Encode()) to output of the
// corresponding BitstreamBuffer (VEA::Client::BitstreamBufferReady()).
std::vector<base::TimeDelta> encode_latencies_;
// Ids for output BitstreamBuffers.
typedef std::map<int32_t, base::SharedMemory*> IdToSHM;
IdToSHM output_buffers_at_client_;
// Current offset into input stream.
off_t pos_in_input_stream_;
gfx::Size input_coded_size_;
// Requested by encoder.
unsigned int num_required_input_buffers_;
size_t output_buffer_size_;
// Number of frames to encode. This may differ from the number of frames in
// stream if we need more frames for bitrate tests.
unsigned int num_frames_to_encode_;
// Number of encoded frames we've got from the encoder thus far.
unsigned int num_encoded_frames_;
// Frames since last bitrate verification.
unsigned int num_frames_since_last_check_;
// True if received a keyframe while processing current bitstream buffer.
bool seen_keyframe_in_this_buffer_;
// True if we are to save the encoded stream to a file.
bool save_to_file_;
// Request a keyframe every keyframe_period_ frames.
const unsigned int keyframe_period_;
// Number of keyframes requested by now.
unsigned int num_keyframes_requested_;
// Next keyframe expected before next_keyframe_at_ + kMaxKeyframeDelay.
unsigned int next_keyframe_at_;
// True if we are asking encoder for a particular bitrate.
bool force_bitrate_;
// Current requested bitrate.
unsigned int current_requested_bitrate_;
// Current expected framerate.
unsigned int current_framerate_;
// Byte size of the encoded stream (for bitrate calculation) since last
// time we checked bitrate.
size_t encoded_stream_size_since_last_check_;
// If true, verify performance at the end of the test.
bool test_perf_;
// Check the output frame quality of the encoder.
bool verify_output_;
// Check whether the output timestamps match input timestamps.
bool verify_output_timestamp_;
// Used to perform codec-specific sanity checks on the stream.
std::unique_ptr<StreamValidator> stream_validator_;
// Used to validate the encoded frame quality.
std::unique_ptr<VideoFrameQualityValidator> quality_validator_;
// The time when the first frame is submitted for encode.
base::TimeTicks first_frame_start_time_;
// The time when the last encoded frame is ready.
base::TimeTicks last_frame_ready_time_;
// Requested bitrate in bits per second.
unsigned int requested_bitrate_;
// Requested initial framerate.
unsigned int requested_framerate_;
// Bitrate to switch to in the middle of the stream.
unsigned int requested_subsequent_bitrate_;
// Framerate to switch to in the middle of the stream.
unsigned int requested_subsequent_framerate_;
// The timer used to feed the encoder with the input frames.
std::unique_ptr<base::RepeatingTimer> input_timer_;
// The timestamps for each frame in the order of CreateFrame() invocation.
std::queue<base::TimeDelta> frame_timestamps_;
// The last timestamp popped from |frame_timestamps_|.
base::TimeDelta previous_timestamp_;
// Dummy thread used to redirect encode tasks, represents GPU IO thread.
base::Thread io_thread_;
// Task runner on which |encoder_| is created.
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
// Task runner used for posting encode tasks. If
// TryToSetupEncodeOnSeperateThread() is true, |io_thread|'s task runner is
// used, otherwise |main_thread_task_runner_|.
scoped_refptr<base::SingleThreadTaskRunner> encode_task_runner_;
// Weak factory used for posting tasks on |encode_task_runner_|.
std::unique_ptr<base::WeakPtrFactory<VideoEncodeAccelerator>>
encoder_weak_factory_;
// Weak factory used for TryToSetupEncodeOnSeperateThread().
base::WeakPtrFactory<VEAClient> client_weak_factory_for_io_;
};
VEAClient::VEAClient(TestStream* test_stream,
ClientStateNotification<ClientState>* note,
bool save_to_file,
unsigned int keyframe_period,
bool force_bitrate,
bool test_perf,
bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch,
bool verify_output,
bool verify_output_timestamp)
: VEAClientBase(note),
state_(CS_CREATED),
test_stream_(test_stream),
next_input_id_(0),
pos_in_input_stream_(0),
num_required_input_buffers_(0),
output_buffer_size_(0),
num_frames_to_encode_(0),
num_encoded_frames_(0),
num_frames_since_last_check_(0),
seen_keyframe_in_this_buffer_(false),
save_to_file_(save_to_file),
keyframe_period_(keyframe_period),
num_keyframes_requested_(0),
next_keyframe_at_(0),
force_bitrate_(force_bitrate),
current_requested_bitrate_(0),
current_framerate_(0),
encoded_stream_size_since_last_check_(0),
test_perf_(test_perf),
verify_output_(verify_output),
verify_output_timestamp_(verify_output_timestamp),
requested_bitrate_(0),
requested_framerate_(0),
requested_subsequent_bitrate_(0),
requested_subsequent_framerate_(0),
io_thread_("IOThread"),
client_weak_factory_for_io_(this) {
if (keyframe_period_)
LOG_ASSERT(kMaxKeyframeDelay < keyframe_period_);
// Fake encoder produces an invalid stream, so skip validating it.
if (!g_fake_encoder) {
stream_validator_ = StreamValidator::Create(
test_stream_->requested_profile,
base::Bind(&VEAClient::HandleEncodedFrame, base::Unretained(this)));
CHECK(stream_validator_);
}
if (save_to_file_) {
LOG_ASSERT(!test_stream_->out_filename.empty());
#if defined(OS_POSIX)
base::FilePath out_filename(test_stream_->out_filename);
#elif defined(OS_WIN)
base::FilePath out_filename(base::UTF8ToWide(test_stream_->out_filename));
#endif
// This creates or truncates out_filename.
// Without it, AppendToFile() will not work.
EXPECT_EQ(0, base::WriteFile(out_filename, NULL, 0));
}
// Initialize the parameters of the test streams.
UpdateTestStreamData(mid_stream_bitrate_switch, mid_stream_framerate_switch);
thread_checker_.DetachFromThread();
}
void VEAClient::CreateEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
LOG_ASSERT(!has_encoder());
main_thread_task_runner_ = base::ThreadTaskRunnerHandle::Get();
encode_task_runner_ = main_thread_task_runner_;
std::unique_ptr<VideoEncodeAccelerator> encoders[] = {
CreateFakeVEA(), CreateV4L2VEA(), CreateVaapiVEA(), CreateVTVEA(),
CreateMFVEA()};
DVLOG(1) << "Profile: " << test_stream_->requested_profile
<< ", initial bitrate: " << requested_bitrate_;
for (size_t i = 0; i < arraysize(encoders); ++i) {
if (!encoders[i])
continue;
encoder_ = std::move(encoders[i]);
if (encoder_->Initialize(kInputFormat, test_stream_->visible_size,
test_stream_->requested_profile,
requested_bitrate_, this)) {
encoder_weak_factory_.reset(
new base::WeakPtrFactory<VideoEncodeAccelerator>(encoder_.get()));
TryToSetupEncodeOnSeperateThread();
SetStreamParameters(requested_bitrate_, requested_framerate_);
SetState(CS_INITIALIZED);
if (verify_output_ && !g_fake_encoder)
quality_validator_.reset(new VideoFrameQualityValidator(
test_stream_->requested_profile,
base::Bind(&VEAClient::DecodeCompleted, base::Unretained(this)),
base::Bind(&VEAClient::DecodeFailed, base::Unretained(this))));
return;
}
}
encoder_.reset();
LOG(ERROR) << "VideoEncodeAccelerator::Initialize() failed";
SetState(CS_ERROR);
}
void VEAClient::DecodeCompleted() {
SetState(CS_VALIDATED);
}
void VEAClient::TryToSetupEncodeOnSeperateThread() {
// Start dummy thread if not started already.
if (!io_thread_.IsRunning())
ASSERT_TRUE(io_thread_.Start());
if (!encoder_->TryToSetupEncodeOnSeparateThread(
client_weak_factory_for_io_.GetWeakPtr(), io_thread_.task_runner())) {
io_thread_.Stop();
return;
}
encode_task_runner_ = io_thread_.task_runner();
}
void VEAClient::DecodeFailed() {
SetState(CS_ERROR);
}
void VEAClient::DestroyEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder())
return;
if (io_thread_.IsRunning()) {
encode_task_runner_->PostTask(
FROM_HERE, base::Bind(&VEAClient::DestroyEncodeOnSeperateThread,
client_weak_factory_for_io_.GetWeakPtr()));
io_thread_.Stop();
} else {
DestroyEncodeOnSeperateThread();
}
// Clear the objects that should be destroyed on the same thread as creation.
encoder_.reset();
input_timer_.reset();
quality_validator_.reset();
}
void VEAClient::DestroyEncodeOnSeperateThread() {
encoder_weak_factory_->InvalidateWeakPtrs();
// |client_weak_factory_for_io_| is used only when
// TryToSetupEncodeOnSeperateThread() returns true, in order to have weak
// pointers to use when posting tasks on |io_thread_|. It is safe to
// invalidate here because |encode_task_runner_| points to |io_thread_| in
// this case. If not, it is safe to invalidate it on
// |main_thread_task_runner_| as no weak pointers are used.
client_weak_factory_for_io_.InvalidateWeakPtrs();
}
void VEAClient::UpdateTestStreamData(bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch) {
// Use defaults for bitrate/framerate if they are not provided.
if (test_stream_->requested_bitrate == 0)
requested_bitrate_ = kDefaultBitrate;
else
requested_bitrate_ = test_stream_->requested_bitrate;
if (test_stream_->requested_framerate == 0)
requested_framerate_ = kDefaultFramerate;
else
requested_framerate_ = test_stream_->requested_framerate;
// If bitrate/framerate switch is requested, use the subsequent values if
// provided, or, if not, calculate them from their initial values using
// the default ratios.
// Otherwise, if a switch is not requested, keep the initial values.
if (mid_stream_bitrate_switch) {
if (test_stream_->requested_subsequent_bitrate == 0)
requested_subsequent_bitrate_ =
requested_bitrate_ * kDefaultSubsequentBitrateRatio;
else
requested_subsequent_bitrate_ =
test_stream_->requested_subsequent_bitrate;
} else {
requested_subsequent_bitrate_ = requested_bitrate_;
}
if (requested_subsequent_bitrate_ == 0)
requested_subsequent_bitrate_ = 1;
if (mid_stream_framerate_switch) {
if (test_stream_->requested_subsequent_framerate == 0)
requested_subsequent_framerate_ =
requested_framerate_ * kDefaultSubsequentFramerateRatio;
else
requested_subsequent_framerate_ =
test_stream_->requested_subsequent_framerate;
} else {
requested_subsequent_framerate_ = requested_framerate_;
}
if (requested_subsequent_framerate_ == 0)
requested_subsequent_framerate_ = 1;
}
double VEAClient::frames_per_second() {
LOG_ASSERT(num_encoded_frames_ != 0UL);
base::TimeDelta duration = last_frame_ready_time_ - first_frame_start_time_;
return num_encoded_frames_ / duration.InSecondsF();
}
void VEAClient::RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
DCHECK(thread_checker_.CalledOnValidThread());
ASSERT_EQ(CS_INITIALIZED, state_);
SetState(CS_ENCODING);
if (quality_validator_)
quality_validator_->Initialize(input_coded_size,
gfx::Rect(test_stream_->visible_size));
CreateAlignedInputStreamFile(input_coded_size, test_stream_);
num_frames_to_encode_ = test_stream_->num_frames;
if (g_num_frames_to_encode > 0)
num_frames_to_encode_ = g_num_frames_to_encode;
// We may need to loop over the stream more than once if more frames than
// provided is required for bitrate tests.
if (force_bitrate_ && num_frames_to_encode_ < kMinFramesForBitrateTests) {
DVLOG(1) << "Stream too short for bitrate test ("
<< test_stream_->num_frames << " frames), will loop it to reach "
<< kMinFramesForBitrateTests << " frames";
num_frames_to_encode_ = kMinFramesForBitrateTests;
}
if (save_to_file_ && IsVP8(test_stream_->requested_profile))
WriteIvfFileHeader();
input_coded_size_ = input_coded_size;
num_required_input_buffers_ = input_count;
ASSERT_GT(num_required_input_buffers_, 0UL);
output_buffer_size_ = output_size;
ASSERT_GT(output_buffer_size_, 0UL);
for (unsigned int i = 0; i < kNumOutputBuffers; ++i) {
base::SharedMemory* shm = new base::SharedMemory();
LOG_ASSERT(shm->CreateAndMapAnonymous(output_buffer_size_));
output_shms_.push_back(shm);
FeedEncoderWithOutput(shm);
}
if (g_env->run_at_fps()) {
input_timer_.reset(new base::RepeatingTimer());
input_timer_->Start(
FROM_HERE, base::TimeDelta::FromSeconds(1) / current_framerate_,
base::Bind(&VEAClient::OnInputTimer, base::Unretained(this)));
} else {
while (inputs_at_client_.size() <
num_required_input_buffers_ + kNumExtraInputFrames)
FeedEncoderWithOneInput();
}
}
void VEAClient::VerifyOutputTimestamp(base::TimeDelta timestamp) {
// One input frame may be mapped to multiple output frames, so the current
// timestamp should be equal to previous timestamp or the top of
// frame_timestamps_.
if (timestamp != previous_timestamp_) {
ASSERT_TRUE(!frame_timestamps_.empty());
EXPECT_EQ(frame_timestamps_.front(), timestamp);
previous_timestamp_ = frame_timestamps_.front();
frame_timestamps_.pop();
}
}
void VEAClient::BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
ASSERT_TRUE(encode_task_runner_->BelongsToCurrentThread());
main_thread_task_runner_->PostTask(
FROM_HERE, base::Bind(&VEAClient::BitstreamBufferReadyOnMainThread,
base::Unretained(this), bitstream_buffer_id,
payload_size, key_frame, timestamp));
}
void VEAClient::BitstreamBufferReadyOnMainThread(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
DCHECK(thread_checker_.CalledOnValidThread());
ASSERT_LE(payload_size, output_buffer_size_);
IdToSHM::iterator it = output_buffers_at_client_.find(bitstream_buffer_id);
ASSERT_NE(it, output_buffers_at_client_.end());
base::SharedMemory* shm = it->second;
output_buffers_at_client_.erase(it);
if (state_ == CS_FINISHED || state_ == CS_VALIDATED)
return;
if (verify_output_timestamp_) {
VerifyOutputTimestamp(timestamp);
}
encoded_stream_size_since_last_check_ += payload_size;
const uint8_t* stream_ptr = static_cast<const uint8_t*>(shm->memory());
if (payload_size > 0) {
if (stream_validator_) {
stream_validator_->ProcessStreamBuffer(stream_ptr, payload_size);
} else {
HandleEncodedFrame(key_frame);
}
if (quality_validator_) {
scoped_refptr<DecoderBuffer> buffer(DecoderBuffer::CopyFrom(
reinterpret_cast<const uint8_t*>(shm->memory()),
static_cast<int>(payload_size)));
quality_validator_->AddDecodeBuffer(buffer);
// Insert EOS buffer to flush the decoder.
if (num_encoded_frames_ == num_frames_to_encode_)
quality_validator_->Flush();
}
if (save_to_file_) {
if (IsVP8(test_stream_->requested_profile))
WriteIvfFrameHeader(num_encoded_frames_ - 1, payload_size);
EXPECT_TRUE(base::AppendToFile(
base::FilePath::FromUTF8Unsafe(test_stream_->out_filename),
static_cast<char*>(shm->memory()),
base::checked_cast<int>(payload_size)));
}
}
EXPECT_EQ(key_frame, seen_keyframe_in_this_buffer_);
seen_keyframe_in_this_buffer_ = false;
FeedEncoderWithOutput(shm);
}
void VEAClient::SetState(ClientState new_state) {
DVLOG(4) << "Changing state " << state_ << "->" << new_state;
note_->Notify(new_state);
state_ = new_state;
}
void VEAClient::SetStreamParameters(unsigned int bitrate,
unsigned int framerate) {
current_requested_bitrate_ = bitrate;
current_framerate_ = framerate;
LOG_ASSERT(current_requested_bitrate_ > 0UL);
LOG_ASSERT(current_framerate_ > 0UL);
encode_task_runner_->PostTask(
FROM_HERE,
base::Bind(&VideoEncodeAccelerator::RequestEncodingParametersChange,
encoder_weak_factory_->GetWeakPtr(), bitrate, framerate));
DVLOG(1) << "Switched parameters to " << current_requested_bitrate_
<< " bps @ " << current_framerate_ << " FPS";
}
void VEAClient::InputNoLongerNeededCallback(int32_t input_id) {
std::set<int32_t>::iterator it = inputs_at_client_.find(input_id);
ASSERT_NE(it, inputs_at_client_.end());
inputs_at_client_.erase(it);
if (!g_env->run_at_fps())
FeedEncoderWithOneInput();
}
scoped_refptr<VideoFrame> VEAClient::CreateFrame(off_t position) {
uint8_t* frame_data_y =
reinterpret_cast<uint8_t*>(&test_stream_->aligned_in_file_data[0]) +
position;
uint8_t* frame_data_u = frame_data_y + test_stream_->aligned_plane_size[0];
uint8_t* frame_data_v = frame_data_u + test_stream_->aligned_plane_size[1];
CHECK_GT(current_framerate_, 0U);
scoped_refptr<VideoFrame> video_frame = VideoFrame::WrapExternalYuvData(
kInputFormat, input_coded_size_, gfx::Rect(test_stream_->visible_size),
test_stream_->visible_size, input_coded_size_.width(),
input_coded_size_.width() / 2, input_coded_size_.width() / 2,
frame_data_y, frame_data_u, frame_data_v,
// Timestamp needs to avoid starting from 0.
base::TimeDelta().FromMilliseconds((next_input_id_ + 1) *
base::Time::kMillisecondsPerSecond /
current_framerate_));
EXPECT_NE(nullptr, video_frame.get());
return video_frame;
}
scoped_refptr<VideoFrame> VEAClient::PrepareInputFrame(off_t position,
int32_t* input_id) {
CHECK_LE(position + test_stream_->aligned_buffer_size,
test_stream_->aligned_in_file_data.size());
scoped_refptr<VideoFrame> frame = CreateFrame(position);
EXPECT_TRUE(frame);
frame->AddDestructionObserver(
BindToCurrentLoop(base::Bind(&VEAClient::InputNoLongerNeededCallback,
base::Unretained(this), next_input_id_)));
LOG_ASSERT(inputs_at_client_.insert(next_input_id_).second);
*input_id = next_input_id_++;
return frame;
}
void VEAClient::OnInputTimer() {
if (!has_encoder() || state_ != CS_ENCODING)
input_timer_.reset();
else if (inputs_at_client_.size() <
num_required_input_buffers_ + kNumExtraInputFrames)
FeedEncoderWithOneInput();
else
DVLOG(1) << "Dropping input frame";
}
void VEAClient::FeedEncoderWithOneInput() {
if (!has_encoder() || state_ != CS_ENCODING)
return;
size_t bytes_left =
test_stream_->aligned_in_file_data.size() - pos_in_input_stream_;
if (bytes_left < test_stream_->aligned_buffer_size) {
DCHECK_EQ(bytes_left, 0UL);
// Rewind if at the end of stream and we are still encoding.
// This is to flush the encoder with additional frames from the beginning
// of the stream, or if the stream is shorter that the number of frames
// we require for bitrate tests.
pos_in_input_stream_ = 0;
}
if (quality_validator_)
quality_validator_->AddOriginalFrame(CreateFrame(pos_in_input_stream_));
int32_t input_id;
scoped_refptr<VideoFrame> video_frame =
PrepareInputFrame(pos_in_input_stream_, &input_id);
frame_timestamps_.push(video_frame->timestamp());
pos_in_input_stream_ += static_cast<off_t>(test_stream_->aligned_buffer_size);
bool force_keyframe = false;
if (keyframe_period_ && input_id % keyframe_period_ == 0) {
force_keyframe = true;
++num_keyframes_requested_;
}
if (input_id == 0) {
first_frame_start_time_ = base::TimeTicks::Now();
}
if (g_env->needs_encode_latency()) {
LOG_ASSERT(input_id == static_cast<int32_t>(encode_start_time_.size()));
encode_start_time_.push_back(base::TimeTicks::Now());
}
encode_task_runner_->PostTask(
FROM_HERE, base::Bind(&VideoEncodeAccelerator::Encode,
encoder_weak_factory_->GetWeakPtr(), video_frame,
force_keyframe));
}
void VEAClient::FeedEncoderWithOutput(base::SharedMemory* shm) {
if (!has_encoder())
return;
if (state_ != CS_ENCODING)
return;
base::SharedMemoryHandle dup_handle;
LOG_ASSERT(shm->ShareToProcess(base::GetCurrentProcessHandle(), &dup_handle));
BitstreamBuffer bitstream_buffer(next_output_buffer_id_++, dup_handle,
output_buffer_size_);
LOG_ASSERT(output_buffers_at_client_
.insert(std::make_pair(bitstream_buffer.id(), shm))
.second);
encode_task_runner_->PostTask(
FROM_HERE,
base::Bind(&VideoEncodeAccelerator::UseOutputBitstreamBuffer,
encoder_weak_factory_->GetWeakPtr(), bitstream_buffer));
}
bool VEAClient::HandleEncodedFrame(bool keyframe) {
// This would be a bug in the test, which should not ignore false
// return value from this method.
LOG_ASSERT(num_encoded_frames_ <= num_frames_to_encode_);
last_frame_ready_time_ = base::TimeTicks::Now();
if (g_env->needs_encode_latency()) {
LOG_ASSERT(num_encoded_frames_ < encode_start_time_.size());
base::TimeTicks start_time = encode_start_time_[num_encoded_frames_];
LOG_ASSERT(!start_time.is_null());
encode_latencies_.push_back(last_frame_ready_time_ - start_time);
}
++num_encoded_frames_;
++num_frames_since_last_check_;
// Because the keyframe behavior requirements are loose, we give
// the encoder more freedom here. It could either deliver a keyframe
// immediately after we requested it, which could be for a frame number
// before the one we requested it for (if the keyframe request
// is asynchronous, i.e. not bound to any concrete frame, and because
// the pipeline can be deeper than one frame), at that frame, or after.
// So the only constraints we put here is that we get a keyframe not
// earlier than we requested one (in time), and not later than
// kMaxKeyframeDelay frames after the frame, for which we requested
// it, comes back encoded.
if (keyframe) {
if (num_keyframes_requested_ > 0) {
--num_keyframes_requested_;
next_keyframe_at_ += keyframe_period_;
}
seen_keyframe_in_this_buffer_ = true;
}
if (num_keyframes_requested_ > 0)
EXPECT_LE(num_encoded_frames_, next_keyframe_at_ + kMaxKeyframeDelay);
if (num_encoded_frames_ == num_frames_to_encode_ / 2) {
VerifyStreamProperties();
if (requested_subsequent_bitrate_ != current_requested_bitrate_ ||
requested_subsequent_framerate_ != current_framerate_) {
SetStreamParameters(requested_subsequent_bitrate_,
requested_subsequent_framerate_);
if (g_env->run_at_fps() && input_timer_)
input_timer_->Start(
FROM_HERE, base::TimeDelta::FromSeconds(1) / current_framerate_,
base::Bind(&VEAClient::OnInputTimer, base::Unretained(this)));
}
} else if (num_encoded_frames_ == num_frames_to_encode_) {
LogPerf();
VerifyMinFPS();
VerifyStreamProperties();
SetState(CS_FINISHED);
if (!quality_validator_)
SetState(CS_VALIDATED);
if (verify_output_timestamp_) {
// There may be some timestamps left because we push extra frames to flush
// encoder.
EXPECT_LE(frame_timestamps_.size(),
static_cast<size_t>(next_input_id_ - num_frames_to_encode_));
}
return false;
}
return true;
}
void VEAClient::LogPerf() {
g_env->LogToFile("Measured encoder FPS",
base::StringPrintf("%.3f", frames_per_second()));
// Log encode latencies.
if (g_env->needs_encode_latency()) {
std::sort(encode_latencies_.begin(), encode_latencies_.end());
for (const auto& percentile : kLoggedLatencyPercentiles) {
base::TimeDelta latency = Percentile(encode_latencies_, percentile);
g_env->LogToFile(
base::StringPrintf("Encode latency for the %dth percentile",
percentile),
base::StringPrintf("%" PRId64 " us", latency.InMicroseconds()));
}
}
}
void VEAClient::VerifyMinFPS() {
if (test_perf_)
EXPECT_GE(frames_per_second(), kMinPerfFPS);
}
void VEAClient::VerifyStreamProperties() {
LOG_ASSERT(num_frames_since_last_check_ > 0UL);
LOG_ASSERT(encoded_stream_size_since_last_check_ > 0UL);
unsigned int bitrate = static_cast<unsigned int>(
encoded_stream_size_since_last_check_ * 8 * current_framerate_ /
num_frames_since_last_check_);
DVLOG(1) << "Current chunk's bitrate: " << bitrate
<< " (expected: " << current_requested_bitrate_ << " @ "
<< current_framerate_ << " FPS,"
<< " num frames in chunk: " << num_frames_since_last_check_;
num_frames_since_last_check_ = 0;
encoded_stream_size_since_last_check_ = 0;
if (force_bitrate_) {
EXPECT_NEAR(bitrate, current_requested_bitrate_,
kBitrateTolerance * current_requested_bitrate_);
}
// All requested keyframes should've been provided. Allow the last requested
// frame to remain undelivered if we haven't reached the maximum frame number
// by which it should have arrived.
if (num_encoded_frames_ < next_keyframe_at_ + kMaxKeyframeDelay)
EXPECT_LE(num_keyframes_requested_, 1UL);
else
EXPECT_EQ(0UL, num_keyframes_requested_);
}
void VEAClient::WriteIvfFileHeader() {
IvfFileHeader header = {};
memcpy(header.signature, kIvfHeaderSignature, sizeof(header.signature));
header.version = 0;
header.header_size = sizeof(header);
header.fourcc = 0x30385056; // VP80
header.width =
base::checked_cast<uint16_t>(test_stream_->visible_size.width());
header.height =
base::checked_cast<uint16_t>(test_stream_->visible_size.height());
header.timebase_denum = requested_framerate_;
header.timebase_num = 1;
header.num_frames = num_frames_to_encode_;
header.ByteSwap();
EXPECT_TRUE(base::AppendToFile(
base::FilePath::FromUTF8Unsafe(test_stream_->out_filename),
reinterpret_cast<char*>(&header), sizeof(header)));
}
void VEAClient::WriteIvfFrameHeader(int frame_index, size_t frame_size) {
IvfFrameHeader header = {};
header.frame_size = static_cast<uint32_t>(frame_size);
header.timestamp = frame_index;
header.ByteSwap();
EXPECT_TRUE(base::AppendToFile(
base::FilePath::FromUTF8Unsafe(test_stream_->out_filename),
reinterpret_cast<char*>(&header), sizeof(header)));
}
// Base class for simple VEA Clients
class SimpleVEAClientBase : public VEAClientBase {
public:
void CreateEncoder();
void DestroyEncoder();
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
protected:
SimpleVEAClientBase(ClientStateNotification<ClientState>* note,
const int width,
const int height);
void SetState(ClientState new_state) override;
// Provide the encoder with a new output buffer.
void FeedEncoderWithOutput(base::SharedMemory* shm, size_t output_size);
const int width_;
const int height_;
const int bitrate_;
const int fps_;
};
SimpleVEAClientBase::SimpleVEAClientBase(
ClientStateNotification<ClientState>* note,
const int width,
const int height)
: VEAClientBase(note),
width_(width),
height_(height),
bitrate_(200000),
fps_(30) {
thread_checker_.DetachFromThread();
}
void SimpleVEAClientBase::CreateEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
LOG_ASSERT(!has_encoder());
LOG_ASSERT(g_env->test_streams_.size());
std::unique_ptr<VideoEncodeAccelerator> encoders[] = {
CreateFakeVEA(), CreateV4L2VEA(), CreateVaapiVEA(), CreateVTVEA(),
CreateMFVEA()};
gfx::Size visible_size(width_, height_);
for (auto& encoder : encoders) {
if (!encoder)
continue;
encoder_ = std::move(encoder);
if (encoder_->Initialize(kInputFormat, visible_size,
g_env->test_streams_[0]->requested_profile,
bitrate_, this)) {
encoder_->RequestEncodingParametersChange(bitrate_, fps_);
SetState(CS_INITIALIZED);
return;
}
}
encoder_.reset();
LOG(ERROR) << "VideoEncodeAccelerator::Initialize() failed";
SetState(CS_ERROR);
}
void SimpleVEAClientBase::DestroyEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder())
return;
// Clear the objects that should be destroyed on the same thread as creation.
encoder_.reset();
}
void SimpleVEAClientBase::SetState(ClientState new_state) {
DVLOG(4) << "Changing state to " << new_state;
note_->Notify(new_state);
}
void SimpleVEAClientBase::RequireBitstreamBuffers(
unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ENCODING);
ASSERT_GT(output_size, 0UL);
for (unsigned int i = 0; i < kNumOutputBuffers; ++i) {
base::SharedMemory* shm = new base::SharedMemory();
LOG_ASSERT(shm->CreateAndMapAnonymous(output_size));
output_shms_.push_back(shm);
FeedEncoderWithOutput(shm, output_size);
}
}
void SimpleVEAClientBase::FeedEncoderWithOutput(base::SharedMemory* shm,
size_t output_size) {
if (!has_encoder())
return;
base::SharedMemoryHandle dup_handle;
LOG_ASSERT(shm->ShareToProcess(base::GetCurrentProcessHandle(), &dup_handle));
BitstreamBuffer bitstream_buffer(next_output_buffer_id_++, dup_handle,
output_size);
encoder_->UseOutputBitstreamBuffer(bitstream_buffer);
}
// This client is only used to make sure the encoder does not return an encoded
// frame before getting any input.
class VEANoInputClient : public SimpleVEAClientBase {
public:
explicit VEANoInputClient(ClientStateNotification<ClientState>* note);
void DestroyEncoder();
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) override;
private:
// The timer used to monitor the encoder doesn't return an output buffer in
// a period of time.
std::unique_ptr<base::Timer> timer_;
};
VEANoInputClient::VEANoInputClient(ClientStateNotification<ClientState>* note)
: SimpleVEAClientBase(note, 320, 240) {}
void VEANoInputClient::DestroyEncoder() {
SimpleVEAClientBase::DestroyEncoder();
// Clear the objects that should be destroyed on the same thread as creation.
timer_.reset();
}
void VEANoInputClient::RequireBitstreamBuffers(
unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
SimpleVEAClientBase::RequireBitstreamBuffers(input_count, input_coded_size,
output_size);
// Timer is used to make sure there is no output frame in 100ms.
timer_.reset(new base::Timer(FROM_HERE,
base::TimeDelta::FromMilliseconds(100),
base::Bind(&VEANoInputClient::SetState,
base::Unretained(this), CS_FINISHED),
false));
timer_->Reset();
}
void VEANoInputClient::BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ERROR);
}
// This client is only used to test input frame with the size of U and V planes
// unaligned to cache line.
// To have both width and height divisible by 16 but not 32 will make the size
// of U/V plane (width * height / 4) unaligned to 128-byte cache line.
class VEACacheLineUnalignedInputClient : public SimpleVEAClientBase {
public:
explicit VEACacheLineUnalignedInputClient(
ClientStateNotification<ClientState>* note);
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) override;
private:
// Feed the encoder with one input frame.
void FeedEncoderWithOneInput(const gfx::Size& input_coded_size);
};
VEACacheLineUnalignedInputClient::VEACacheLineUnalignedInputClient(
ClientStateNotification<ClientState>* note)
: SimpleVEAClientBase(note, 368, 368) {
} // 368 is divisible by 16 but not 32
void VEACacheLineUnalignedInputClient::RequireBitstreamBuffers(
unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
SimpleVEAClientBase::RequireBitstreamBuffers(input_count, input_coded_size,
output_size);
FeedEncoderWithOneInput(input_coded_size);
}
void VEACacheLineUnalignedInputClient::BitstreamBufferReady(
int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
DCHECK(thread_checker_.CalledOnValidThread());
// It's enough to encode just one frame. If plane size is not aligned,
// VideoEncodeAccelerator::Encode will fail.
SetState(CS_FINISHED);
}
void VEACacheLineUnalignedInputClient::FeedEncoderWithOneInput(
const gfx::Size& input_coded_size) {
if (!has_encoder())
return;
std::vector<char, AlignedAllocator<char, kPlatformBufferAlignment>>
aligned_data_y, aligned_data_u, aligned_data_v;
aligned_data_y.resize(
VideoFrame::PlaneSize(kInputFormat, 0, input_coded_size).GetArea());
aligned_data_u.resize(
VideoFrame::PlaneSize(kInputFormat, 1, input_coded_size).GetArea());
aligned_data_v.resize(
VideoFrame::PlaneSize(kInputFormat, 2, input_coded_size).GetArea());
uint8_t* frame_data_y = reinterpret_cast<uint8_t*>(&aligned_data_y[0]);
uint8_t* frame_data_u = reinterpret_cast<uint8_t*>(&aligned_data_u[0]);
uint8_t* frame_data_v = reinterpret_cast<uint8_t*>(&aligned_data_v[0]);
scoped_refptr<VideoFrame> video_frame = VideoFrame::WrapExternalYuvData(
kInputFormat, input_coded_size, gfx::Rect(input_coded_size),
input_coded_size, input_coded_size.width(), input_coded_size.width() / 2,
input_coded_size.width() / 2, frame_data_y, frame_data_u, frame_data_v,
base::TimeDelta().FromMilliseconds(base::Time::kMillisecondsPerSecond /
fps_));
encoder_->Encode(video_frame, false);
}
// Test parameters:
// - Number of concurrent encoders. The value takes effect when there is only
// one input stream; otherwise, one encoder per input stream will be
// instantiated.
// - If true, save output to file (provided an output filename was supplied).
// - Force a keyframe every n frames.
// - Force bitrate; the actual required value is provided as a property
// of the input stream, because it depends on stream type/resolution/etc.
// - If true, measure performance.
// - If true, switch bitrate mid-stream.
// - If true, switch framerate mid-stream.
// - If true, verify the output frames of encoder.
// - If true, verify the timestamps of output frames.
class VideoEncodeAcceleratorTest
: public ::testing::TestWithParam<
std::tuple<int, bool, int, bool, bool, bool, bool, bool, bool>> {};
TEST_P(VideoEncodeAcceleratorTest, TestSimpleEncode) {
size_t num_concurrent_encoders = std::get<0>(GetParam());
const bool save_to_file = std::get<1>(GetParam());
const unsigned int keyframe_period = std::get<2>(GetParam());
const bool force_bitrate = std::get<3>(GetParam());
const bool test_perf = std::get<4>(GetParam());
const bool mid_stream_bitrate_switch = std::get<5>(GetParam());
const bool mid_stream_framerate_switch = std::get<6>(GetParam());
const bool verify_output =
std::get<7>(GetParam()) || g_env->verify_all_output();
const bool verify_output_timestamp = std::get<8>(GetParam());
ScopedVector<ClientStateNotification<ClientState>> notes;
ScopedVector<VEAClient> clients;
base::Thread encoder_thread("EncoderThread");
ASSERT_TRUE(encoder_thread.Start());
if (g_env->test_streams_.size() > 1)
num_concurrent_encoders = g_env->test_streams_.size();
// Create all encoders.
for (size_t i = 0; i < num_concurrent_encoders; i++) {
size_t test_stream_index = i % g_env->test_streams_.size();
// Disregard save_to_file if we didn't get an output filename.
bool encoder_save_to_file =
(save_to_file &&
!g_env->test_streams_[test_stream_index]->out_filename.empty());
notes.push_back(new ClientStateNotification<ClientState>());
clients.push_back(new VEAClient(
g_env->test_streams_[test_stream_index], notes.back(),
encoder_save_to_file, keyframe_period, force_bitrate, test_perf,
mid_stream_bitrate_switch, mid_stream_framerate_switch, verify_output,
verify_output_timestamp));
encoder_thread.task_runner()->PostTask(
FROM_HERE, base::Bind(&VEAClient::CreateEncoder,
base::Unretained(clients.back())));
}
// All encoders must pass through states in this order.
enum ClientState state_transitions[] = {CS_INITIALIZED, CS_ENCODING,
CS_FINISHED, CS_VALIDATED};
// Wait for all encoders to go through all states and finish.
// Do this by waiting for all encoders to advance to state n before checking
// state n+1, to verify that they are able to operate concurrently.
// It also simulates the real-world usage better, as the main thread, on which
// encoders are created/destroyed, is a single GPU Process ChildThread.
// Moreover, we can't have proper multithreading on X11, so this could cause
// hard to debug issues there, if there were multiple "ChildThreads".
for (const auto& state : state_transitions) {
for (size_t i = 0; i < num_concurrent_encoders && !HasFailure(); i++) {
EXPECT_EQ(state, notes[i]->Wait());
}
if (HasFailure()) {
break;
}
}
for (size_t i = 0; i < num_concurrent_encoders; ++i) {
encoder_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&VEAClient::DestroyEncoder, base::Unretained(clients[i])));
}
// This ensures all tasks have finished.
encoder_thread.Stop();
}
// Test parameters:
// - Test type
// 0: No input test
// 1: Cache line-unaligned test
class VideoEncodeAcceleratorSimpleTest : public ::testing::TestWithParam<int> {
};
template <class TestClient>
void SimpleTestFunc() {
std::unique_ptr<ClientStateNotification<ClientState>> note(
new ClientStateNotification<ClientState>());
std::unique_ptr<TestClient> client(new TestClient(note.get()));
base::Thread encoder_thread("EncoderThread");
ASSERT_TRUE(encoder_thread.Start());
encoder_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&TestClient::CreateEncoder, base::Unretained(client.get())));
// Encoder must pass through states in this order.
enum ClientState state_transitions[] = {CS_INITIALIZED, CS_ENCODING,
CS_FINISHED};
for (const auto& state : state_transitions) {
EXPECT_EQ(state, note->Wait());
if (testing::Test::HasFailure()) {
break;
}
}
encoder_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&TestClient::DestroyEncoder, base::Unretained(client.get())));
// This ensures all tasks have finished.
encoder_thread.Stop();
}
TEST_P(VideoEncodeAcceleratorSimpleTest, TestSimpleEncode) {
const int test_type = GetParam();
ASSERT_LT(test_type, 2) << "Invalid test type=" << test_type;
if (test_type == 0)
SimpleTestFunc<VEANoInputClient>();
else if (test_type == 1)
SimpleTestFunc<VEACacheLineUnalignedInputClient>();
}
#if defined(OS_CHROMEOS)
INSTANTIATE_TEST_CASE_P(
SimpleEncode,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, true, 0, false, false, false, false, false, false),
std::make_tuple(1, true, 0, false, false, false, false, true, false)));
INSTANTIATE_TEST_CASE_P(
EncoderPerf,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, false, true, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(ForceKeyframes,
VideoEncodeAcceleratorTest,
::testing::Values(std::make_tuple(1,
false,
10,
false,
false,
false,
false,
false,
false)));
INSTANTIATE_TEST_CASE_P(
ForceBitrate,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(
MidStreamParamSwitchBitrate,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, true, false, false, false)));
INSTANTIATE_TEST_CASE_P(
MidStreamParamSwitchFPS,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, false, true, false, false)));
INSTANTIATE_TEST_CASE_P(
MultipleEncoders,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(3, false, 0, false, false, false, false, false, false),
std::make_tuple(3, false, 0, true, false, false, true, false, false),
std::make_tuple(3, false, 0, true, false, true, false, false, false)));
INSTANTIATE_TEST_CASE_P(
VerifyTimestamp,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, false, false, false, false, false, true)));
INSTANTIATE_TEST_CASE_P(NoInputTest,
VideoEncodeAcceleratorSimpleTest,
::testing::Values(0));
INSTANTIATE_TEST_CASE_P(CacheLineUnalignedInputTest,
VideoEncodeAcceleratorSimpleTest,
::testing::Values(1));
#elif defined(OS_MACOSX) || defined(OS_WIN)
INSTANTIATE_TEST_CASE_P(
SimpleEncode,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, true, 0, false, false, false, false, false, false),
std::make_tuple(1, true, 0, false, false, false, false, true, false)));
INSTANTIATE_TEST_CASE_P(
EncoderPerf,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, false, true, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(MultipleEncoders,
VideoEncodeAcceleratorTest,
::testing::Values(std::make_tuple(3,
false,
0,
false,
false,
false,
false,
false,
false)));
#if defined(OS_WIN)
INSTANTIATE_TEST_CASE_P(
ForceBitrate,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, false, false, false, false)));
#endif // defined(OS_WIN)
#endif // defined(OS_CHROMEOS)
// TODO(posciak): more tests:
// - async FeedEncoderWithOutput
// - out-of-order return of outputs to encoder
// - multiple encoders + decoders
// - mid-stream encoder_->Destroy()
} // namespace
} // namespace media
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv); // Removes gtest-specific args.
base::CommandLine::Init(argc, argv);
base::ShadowingAtExitManager at_exit_manager;
base::MessageLoop main_loop;
std::unique_ptr<base::FilePath::StringType> test_stream_data(
new base::FilePath::StringType(
media::GetTestDataFilePath(media::g_default_in_filename).value()));
test_stream_data->append(media::g_default_in_parameters);
// Needed to enable DVLOG through --vmodule.
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
LOG_ASSERT(logging::InitLogging(settings));
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
DCHECK(cmd_line);
bool run_at_fps = false;
bool needs_encode_latency = false;
bool verify_all_output = false;
base::FilePath log_path;
base::CommandLine::SwitchMap switches = cmd_line->GetSwitches();
for (base::CommandLine::SwitchMap::const_iterator it = switches.begin();
it != switches.end(); ++it) {
if (it->first == "test_stream_data") {
test_stream_data->assign(it->second.c_str());
continue;
}
// Output machine-readable logs with fixed formats to a file.
if (it->first == "output_log") {
log_path = base::FilePath(
base::FilePath::StringType(it->second.begin(), it->second.end()));
continue;
}
if (it->first == "num_frames_to_encode") {
std::string input(it->second.begin(), it->second.end());
LOG_ASSERT(base::StringToInt(input, &media::g_num_frames_to_encode));
continue;
}
if (it->first == "measure_latency") {
needs_encode_latency = true;
continue;
}
if (it->first == "fake_encoder") {
media::g_fake_encoder = true;
continue;
}
if (it->first == "run_at_fps") {
run_at_fps = true;
continue;
}
if (it->first == "verify_all_output") {
verify_all_output = true;
continue;
}
if (it->first == "v" || it->first == "vmodule")
continue;
if (it->first == "ozone-platform" || it->first == "ozone-use-surfaceless")
continue;
LOG(FATAL) << "Unexpected switch: " << it->first << ":" << it->second;
}
if (needs_encode_latency && !run_at_fps) {
// Encode latency can only be measured with --run_at_fps. Otherwise, we get
// skewed results since it may queue too many frames at once with the same
// encode start time.
LOG(FATAL) << "--measure_latency requires --run_at_fps enabled to work.";
}
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)
media::VaapiWrapper::PreSandboxInitialization();
#endif
media::g_env =
reinterpret_cast<media::VideoEncodeAcceleratorTestEnvironment*>(
testing::AddGlobalTestEnvironment(
new media::VideoEncodeAcceleratorTestEnvironment(
std::move(test_stream_data), log_path, run_at_fps,
needs_encode_latency, verify_all_output)));
return RUN_ALL_TESTS();
}
| 36.685177 | 80 | 0.698242 | [
"vector"
] |
11f21b5def4f52d3c3e69bb32eb64db24aaaed8d | 54,451 | cc | C++ | chrome_frame/utils.cc | MIPS/external-chromium_org | e31b3128a419654fd14003d6117caa8da32697e7 | [
"BSD-3-Clause"
] | 2 | 2018-11-24T07:58:44.000Z | 2019-02-22T21:02:46.000Z | chrome_frame/utils.cc | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome_frame/utils.cc | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-07-31T19:09:52.000Z | 2019-01-04T18:48:50.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/utils.h"
#include <atlsafe.h>
#include <atlsecurity.h>
#include <htiframe.h>
#include <mshtml.h>
#include <shlobj.h>
#include "base/file_version_info.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_local.h"
#include "base/win/registry.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_variant.h"
#include "chrome/common/automation_messages.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/url_constants.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome_frame/chrome_tab.h"
#include "chrome_frame/extra_system_apis.h"
#include "chrome_frame/html_utils.h"
#include "chrome_frame/navigation_constraints.h"
#include "chrome_frame/policy_settings.h"
#include "chrome_frame/registry_list_preferences_holder.h"
#include "chrome_frame/simple_resource_loader.h"
#include "extensions/common/constants.h"
#include "grit/chromium_strings.h"
#include "net/base/escape.h"
#include "net/http/http_util.h"
#include "ui/base/models/menu_model.h"
#include "url/gurl.h"
#include "url/url_canon.h"
using base::win::RegKey;
// Note that these values are all lower case and are compared to
// lower-case-transformed values.
const char kGCFProtocol[] = "gcf";
const wchar_t kBodyTag[] = L"body";
const wchar_t kContentAttribName[] = L"content";
const wchar_t kChromeContentPrefix[] = L"chrome=";
const wchar_t kChromeMimeType[] = L"application/chromepage";
const wchar_t kChromeProtocolPrefix[] = L"gcf:";
const wchar_t kHttpEquivAttribName[] = L"http-equiv";
const wchar_t kIexploreProfileName[] = L"iexplore";
const wchar_t kMetaTag[] = L"meta";
const wchar_t kRundllProfileName[] = L"rundll32";
const wchar_t kXUACompatValue[] = L"x-ua-compatible";
// Registry key and value names related to Chrome Frame configuration options.
const wchar_t kAllowUnsafeURLs[] = L"AllowUnsafeURLs";
const wchar_t kChromeFrameConfigKey[] = L"Software\\Google\\ChromeFrame";
const wchar_t kEnableBuggyBhoIntercept[] = L"EnableBuggyBhoIntercept";
const wchar_t kEnableGCFRendererByDefault[] = L"IsDefaultRenderer";
const wchar_t kExcludeUAFromDomainList[] = L"ExcludeUAFromDomain";
const wchar_t kPatchProtocols[] = L"PatchProtocols";
const wchar_t kRenderInGCFUrlList[] = L"RenderInGcfUrls";
const wchar_t kRenderInHostUrlList[] = L"RenderInHostUrls";
static const wchar_t kChromeFramePersistNPAPIReg[] = L"PersistNPAPIReg";
const char kAttachExternalTabPrefix[] = "attach_external_tab";
// Indicates that we are running in a test environment, where execptions, etc
// are handled by the chrome test crash server.
const wchar_t kChromeFrameHeadlessMode[] = L"ChromeFrameHeadlessMode";
// Indicates that we are running in an environment that expects chrome renderer
// accessibility to be enabled for use in automation tests.
const wchar_t kChromeFrameAccessibleMode[] = L"ChromeFrameAccessibleMode";
// Indicates that we are running in an environment that wishes to avoid
// DLL pinning, such as the perf tests.
const wchar_t kChromeFrameUnpinnedMode[] = L"kChromeFrameUnpinnedMode";
// Controls whether we download subresources, etc on the chrome frame page in
// the background worker thread. Defaults to true.
const wchar_t kUseBackgroundThreadForSubResources[]
= L"BackgroundHTTPWorkerThread";
// {1AF32B6C-A3BA-48B9-B24E-8AA9C41F6ECD}
static const IID IID_IWebBrowserPriv2IE7 = { 0x1AF32B6C, 0xA3BA, 0x48B9,
{ 0xB2, 0x4E, 0x8A, 0xA9, 0xC4, 0x1F, 0x6E, 0xCD } };
// {3ED72303-6FFC-4214-BA90-FAF1862DEC8A}
static const IID IID_IWebBrowserPriv2IE8 = { 0x3ED72303, 0x6FFC, 0x4214,
{ 0xBA, 0x90, 0xFA, 0xF1, 0x86, 0x2D, 0xEC, 0x8A } };
// {486F6159-9F3F-4827-82D4-283CEF397733}
static const IID IID_IWebBrowserPriv2IE8XP = { 0x486F6159, 0x9F3F, 0x4827,
{ 0x82, 0xD4, 0x28, 0x3C, 0xEF, 0x39, 0x77, 0x33 } };
// {38339692-0BC9-46CB-8E5C-4677A5C83DD5}
static const IID IID_IWebBrowserPriv2IE8XPBeta = { 0x38339692, 0x0BC9, 0x46CB,
{ 0x8E, 0x5C, 0x46, 0x77, 0xA5, 0xC8, 0x3D, 0xD5 } };
namespace {
// A flag used to signal when an active browser instance on the current thread
// is loading a Chrome Frame document. There's no reference stored with the
// pointer so it should not be dereferenced and used for comparison against a
// living instance only.
base::LazyInstance<base::ThreadLocalPointer<IBrowserService> >
g_tls_browser_for_cf_navigation = LAZY_INSTANCE_INITIALIZER;
// Holds the cached preferences for the per-url render type settings.
base::LazyInstance<RegistryListPreferencesHolder>::Leaky
g_render_type_for_url_holder;
// Holds the cached preferences for the per-url user agent filter.
base::LazyInstance<RegistryListPreferencesHolder>::Leaky
g_user_agent_filter_holder;
} // end anonymous namespace
HRESULT UtilRegisterTypeLib(HINSTANCE tlb_instance,
LPCOLESTR index,
bool for_current_user_only) {
CComBSTR path;
CComPtr<ITypeLib> type_lib;
HRESULT hr = AtlLoadTypeLib(tlb_instance, index, &path, &type_lib);
if (SUCCEEDED(hr)) {
hr = UtilRegisterTypeLib(type_lib, path, NULL, for_current_user_only);
}
return hr;
}
HRESULT UtilUnRegisterTypeLib(HINSTANCE tlb_instance,
LPCOLESTR index,
bool for_current_user_only) {
CComBSTR path;
CComPtr<ITypeLib> type_lib;
HRESULT hr = AtlLoadTypeLib(tlb_instance, index, &path, &type_lib);
if (SUCCEEDED(hr)) {
hr = UtilUnRegisterTypeLib(type_lib, for_current_user_only);
}
return hr;
}
HRESULT UtilRegisterTypeLib(LPCWSTR typelib_path,
bool for_current_user_only) {
if (NULL == typelib_path) {
return E_INVALIDARG;
}
CComBSTR path;
CComPtr<ITypeLib> type_lib;
HRESULT hr = ::LoadTypeLib(typelib_path, &type_lib);
if (SUCCEEDED(hr)) {
hr = UtilRegisterTypeLib(type_lib,
typelib_path,
NULL,
for_current_user_only);
}
return hr;
}
HRESULT UtilUnRegisterTypeLib(LPCWSTR typelib_path,
bool for_current_user_only) {
CComPtr<ITypeLib> type_lib;
HRESULT hr = ::LoadTypeLib(typelib_path, &type_lib);
if (SUCCEEDED(hr)) {
hr = UtilUnRegisterTypeLib(type_lib, for_current_user_only);
}
return hr;
}
HRESULT UtilRegisterTypeLib(ITypeLib* typelib,
LPCWSTR typelib_path,
LPCWSTR help_dir,
bool for_current_user_only) {
typedef HRESULT(WINAPI *RegisterTypeLibPrototype)(ITypeLib FAR* type_lib,
OLECHAR FAR* full_path,
OLECHAR FAR* help_dir);
LPCSTR function_name =
for_current_user_only ? "RegisterTypeLibForUser" : "RegisterTypeLib";
RegisterTypeLibPrototype reg_tlb =
reinterpret_cast<RegisterTypeLibPrototype>(
GetProcAddress(GetModuleHandle(_T("oleaut32.dll")),
function_name));
if (NULL == reg_tlb) {
return E_FAIL;
}
return reg_tlb(typelib,
const_cast<OLECHAR*>(typelib_path),
const_cast<OLECHAR*>(help_dir));
}
HRESULT UtilUnRegisterTypeLib(ITypeLib* typelib,
bool for_current_user_only) {
if (NULL == typelib) {
return E_INVALIDARG;
}
typedef HRESULT(WINAPI *UnRegisterTypeLibPrototype)(
REFGUID libID,
unsigned short wVerMajor, // NOLINT
unsigned short wVerMinor, // NOLINT
LCID lcid,
SYSKIND syskind);
LPCSTR function_name =
for_current_user_only ? "UnRegisterTypeLibForUser" : "UnRegisterTypeLib";
UnRegisterTypeLibPrototype unreg_tlb =
reinterpret_cast<UnRegisterTypeLibPrototype>(
GetProcAddress(GetModuleHandle(_T("oleaut32.dll")),
function_name));
if (NULL == unreg_tlb) {
return E_FAIL;
}
TLIBATTR* tla = NULL;
HRESULT hr = typelib->GetLibAttr(&tla);
if (SUCCEEDED(hr)) {
hr = unreg_tlb(tla->guid,
tla->wMajorVerNum,
tla->wMinorVerNum,
tla->lcid,
tla->syskind);
typelib->ReleaseTLibAttr(tla);
}
return hr;
}
bool UtilRemovePersistentNPAPIMarker() {
BrowserDistribution* cf_dist = BrowserDistribution::GetDistribution();
std::wstring cf_state_key_path(cf_dist->GetStateKey());
RegKey cf_state_key;
LONG result = cf_state_key.Open(HKEY_LOCAL_MACHINE, cf_state_key_path.c_str(),
KEY_SET_VALUE);
if (result == ERROR_SUCCESS)
result = cf_state_key.DeleteValue(kChromeFramePersistNPAPIReg);
return (result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND);
}
HRESULT UtilGetXUACompatContentValue(const std::wstring& html_string,
std::wstring* content_value) {
if (!content_value) {
return E_POINTER;
}
// Fail fast if the string X-UA-Compatible isn't in html_string
if (StringToLowerASCII(html_string).find(kXUACompatValue) ==
std::wstring::npos) {
return E_FAIL;
}
HTMLScanner scanner(html_string.c_str());
// Build the list of meta tags that occur before the body tag is hit.
HTMLScanner::StringRangeList tag_list;
scanner.GetTagsByName(kMetaTag, &tag_list, kBodyTag);
// Search the list of meta tags for one with an http-equiv="X-UA-Compatible"
// attribute.
HTMLScanner::StringRange attribute;
std::string search_attribute_ascii(WideToASCII(kXUACompatValue));
HTMLScanner::StringRangeList::const_iterator tag_list_iter(tag_list.begin());
for (; tag_list_iter != tag_list.end(); tag_list_iter++) {
if (!tag_list_iter->GetTagAttribute(kHttpEquivAttribName, &attribute)) {
continue;
}
// We found an http-equiv meta tag, check its value using the ascii
// case-insensitive comparison method.
if (!attribute.LowerCaseEqualsASCII(search_attribute_ascii.c_str())) {
continue;
}
// We found our X-UA-Compatible meta tag so look for and extract
// the value of the content attribute.
if (!tag_list_iter->GetTagAttribute(kContentAttribName, &attribute)) {
continue;
}
// Found the content string, copy and return.
content_value->assign(attribute.Copy());
return S_OK;
}
return E_FAIL;
}
void DisplayVersionMismatchWarning(HWND parent,
const std::string& server_version) {
// Obtain the current module version.
scoped_ptr<FileVersionInfo> module_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
string16 version_string(module_version_info->file_version());
std::wstring wide_server_version;
if (server_version.empty()) {
wide_server_version = SimpleResourceLoader::Get(IDS_VERSIONUNKNOWN);
} else {
wide_server_version = ASCIIToWide(server_version);
}
std::wstring title = SimpleResourceLoader::Get(IDS_VERSIONMISMATCH_HEADER);
std::wstring message;
base::SStringPrintf(&message,
SimpleResourceLoader::Get(IDS_VERSIONMISMATCH).c_str(),
wide_server_version.c_str(),
version_string.c_str());
::MessageBox(parent, message.c_str(), title.c_str(), MB_OK);
}
std::string CreateJavascript(const std::string& function_name,
const std::string args) {
std::string script_string = "javascript:";
script_string += function_name + "(";
if (!args.empty()) {
script_string += "'";
script_string += args;
script_string += "'";
}
script_string += ")";
return script_string;
}
AddRefModule::AddRefModule() {
// TODO(tommi): Override the module's Lock/Unlock methods to call
// npapi::SetValue(NPPVpluginKeepLibraryInMemory) and keep the dll loaded
// while the module's refcount is > 0. Only do this when we're being
// used as an NPAPI module.
_pAtlModule->Lock();
}
AddRefModule::~AddRefModule() {
_pAtlModule->Unlock();
}
bool IsChrome(RendererType renderer_type) {
DCHECK_GE(renderer_type, RENDERER_TYPE_UNDETERMINED);
DCHECK_LE(renderer_type, RENDERER_TYPE_OTHER);
return renderer_type >= RENDERER_TYPE_CHROME_MIN &&
renderer_type <= RENDERER_TYPE_CHROME_MAX;
}
namespace {
const char kIEImageName[] = "iexplore.exe";
} // namespace
std::wstring GetHostProcessName(bool include_extension) {
base::FilePath exe;
if (PathService::Get(base::FILE_EXE, &exe))
exe = exe.BaseName();
if (!include_extension) {
exe = exe.RemoveExtension();
}
return exe.value();
}
BrowserType GetBrowserType() {
static BrowserType browser_type = BROWSER_INVALID;
if (browser_type == BROWSER_INVALID) {
std::wstring exe(GetHostProcessName(true));
if (!exe.empty()) {
std::wstring::const_iterator begin = exe.begin();
std::wstring::const_iterator end = exe.end();
if (LowerCaseEqualsASCII(begin, end, kIEImageName)) {
browser_type = BROWSER_IE;
} else {
browser_type = BROWSER_UNKNOWN;
}
} else {
NOTREACHED();
}
}
return browser_type;
}
uint32 GetIEMajorVersion() {
static uint32 ie_major_version = UINT_MAX;
if (ie_major_version == UINT_MAX) {
wchar_t exe_path[MAX_PATH];
HMODULE mod = GetModuleHandle(NULL);
GetModuleFileName(mod, exe_path, arraysize(exe_path) - 1);
std::wstring exe_name = base::FilePath(exe_path).BaseName().value();
if (!LowerCaseEqualsASCII(exe_name, kIEImageName)) {
ie_major_version = 0;
} else {
uint32 high = 0;
uint32 low = 0;
if (GetModuleVersion(mod, &high, &low)) {
ie_major_version = HIWORD(high);
} else {
ie_major_version = 0;
}
}
}
return ie_major_version;
}
IEVersion GetIEVersion() {
static IEVersion ie_version = IE_INVALID;
if (ie_version == IE_INVALID) {
uint32 major_version = GetIEMajorVersion();
switch (major_version) {
case 0:
ie_version = NON_IE;
break;
case 6:
ie_version = IE_6;
break;
case 7:
ie_version = IE_7;
break;
case 8:
ie_version = IE_8;
break;
case 9:
ie_version = IE_9;
break;
default:
ie_version = (major_version >= 10) ? IE_10 : IE_UNSUPPORTED;
break;
}
}
return ie_version;
}
base::FilePath GetIETemporaryFilesFolder() {
LPITEMIDLIST tif_pidl = NULL;
HRESULT hr = SHGetFolderLocation(NULL, CSIDL_INTERNET_CACHE, NULL,
SHGFP_TYPE_CURRENT, &tif_pidl);
if (SUCCEEDED(hr) && tif_pidl) {
base::win::ScopedComPtr<IShellFolder> parent_folder;
LPITEMIDLIST relative_pidl = NULL;
hr = SHBindToParent(tif_pidl, IID_IShellFolder,
reinterpret_cast<void**>(parent_folder.Receive()),
const_cast<LPCITEMIDLIST*>(&relative_pidl));
if (SUCCEEDED(hr) && relative_pidl) {
STRRET path = {0};
hr = parent_folder->GetDisplayNameOf(relative_pidl,
SHGDN_NORMAL | SHGDN_FORPARSING,
&path);
DCHECK(SUCCEEDED(hr));
base::win::ScopedBstr temp_internet_files_bstr;
StrRetToBSTR(&path, relative_pidl, temp_internet_files_bstr.Receive());
base::FilePath temp_internet_files(
static_cast<BSTR>(temp_internet_files_bstr));
ILFree(tif_pidl);
return temp_internet_files;
} else {
NOTREACHED() << "SHBindToParent failed with Error:" << hr;
ILFree(tif_pidl);
}
} else {
NOTREACHED() << "SHGetFolderLocation for internet cache failed. Error:"
<< hr;
}
// As a last ditch effort we use the SHGetFolderPath function to retrieve the
// path. This function has a limitation of MAX_PATH.
wchar_t path[MAX_PATH + 1] = {0};
hr = SHGetFolderPath(NULL, CSIDL_INTERNET_CACHE, NULL, SHGFP_TYPE_CURRENT,
path);
if (SUCCEEDED(hr)) {
return base::FilePath(path);
} else {
NOTREACHED() << "SHGetFolderPath for internet cache failed. Error:"
<< hr;
}
return base::FilePath();
}
bool IsIEInPrivate() {
typedef BOOL (WINAPI* IEIsInPrivateBrowsingPtr)();
bool incognito_mode = false;
HMODULE h = GetModuleHandle(L"ieframe.dll");
if (h) {
IEIsInPrivateBrowsingPtr IsInPrivate =
reinterpret_cast<IEIsInPrivateBrowsingPtr>(GetProcAddress(h,
"IEIsInPrivateBrowsing"));
if (IsInPrivate) {
incognito_mode = !!IsInPrivate();
}
}
return incognito_mode;
}
HRESULT DoFileDownloadInIE(const wchar_t* url) {
DCHECK(url);
HMODULE mod = ::GetModuleHandleA("ieframe.dll");
if (!mod)
mod = ::GetModuleHandleA("shdocvw.dll");
if (!mod) {
NOTREACHED();
return E_UNEXPECTED;
}
typedef HRESULT (WINAPI* DoFileDownloadFn)(const wchar_t*);
DoFileDownloadFn fn = reinterpret_cast<DoFileDownloadFn>(
::GetProcAddress(mod, "DoFileDownload"));
DCHECK(fn);
return fn ? fn(url) : E_UNEXPECTED;
}
bool GetModuleVersion(HMODULE module, uint32* high, uint32* low) {
DCHECK(module != NULL)
<< "Please use GetModuleHandle(NULL) to get the process name";
DCHECK(high);
bool ok = false;
HRSRC res = FindResource(module,
reinterpret_cast<const wchar_t*>(VS_VERSION_INFO), RT_VERSION);
if (res) {
HGLOBAL res_data = LoadResource(module, res);
DWORD version_resource_size = SizeofResource(module, res);
const void* readonly_resource_data = LockResource(res_data);
if (readonly_resource_data && version_resource_size) {
// Copy data as VerQueryValue tries to modify the data. This causes
// exceptions and heap corruption errors if debugger is attached.
scoped_ptr<char[]> data(new char[version_resource_size]);
if (data.get()) {
memcpy(data.get(), readonly_resource_data, version_resource_size);
VS_FIXEDFILEINFO* ver_info = NULL;
UINT info_size = 0;
if (VerQueryValue(data.get(), L"\\",
reinterpret_cast<void**>(&ver_info), &info_size)) {
*high = ver_info->dwFileVersionMS;
if (low != NULL)
*low = ver_info->dwFileVersionLS;
ok = true;
}
UnlockResource(res_data);
}
FreeResource(res_data);
}
}
return ok;
}
namespace {
const int kMaxSubmenuDepth = 10;
// Builds a Windows menu from the menu model sent from Chrome. The
// caller is responsible for closing the returned HMENU. This does
// not currently handle bitmaps (e.g. hbmpChecked, hbmpUnchecked or
// hbmpItem), so checkmarks, radio buttons, and custom icons won't work.
// It also copies over submenus up to a maximum depth of kMaxSubMenuDepth.
HMENU BuildContextMenuImpl(const ContextMenuModel* menu_model, int depth) {
if (depth >= kMaxSubmenuDepth)
return NULL;
HMENU menu = CreatePopupMenu();
for (size_t i = 0; i < menu_model->items.size(); i++) {
const ContextMenuModel::Item& item = menu_model->items[i];
MENUITEMINFO item_info = { 0 };
item_info.cbSize = sizeof(MENUITEMINFO);
switch (item.type) {
case ui::MenuModel::TYPE_COMMAND:
case ui::MenuModel::TYPE_CHECK:
item_info.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
item_info.fType = MFT_STRING;
item_info.wID = item.item_id;
item_info.dwTypeData = const_cast<LPWSTR>(item.label.c_str());
break;
case ui::MenuModel::TYPE_RADIO:
item_info.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
item_info.fType = MFT_STRING | MFT_RADIOCHECK;
item_info.wID = item.item_id;
item_info.dwTypeData = const_cast<LPWSTR>(item.label.c_str());
break;
case ui::MenuModel::TYPE_SEPARATOR:
item_info.fMask = MIIM_FTYPE;
item_info.fType = MFT_SEPARATOR;
break;
case ui::MenuModel::TYPE_SUBMENU:
item_info.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_SUBMENU;
item_info.fType = MFT_STRING;
item_info.wID = item.item_id;
item_info.dwTypeData = const_cast<LPWSTR>(item.label.c_str());
item_info.hSubMenu = BuildContextMenuImpl(item.submenu, depth + 1);
break;
default:
NOTREACHED() << "Unsupported MenuModel::ItemType " << item.type;
break;
}
item_info.fMask |= MIIM_STATE;
item_info.fState =
(item.checked ? MFS_CHECKED : MFS_UNCHECKED) |
(item.enabled ? MFS_ENABLED : (MFS_DISABLED | MFS_GRAYED));
InsertMenuItem(menu, i, TRUE, &item_info);
}
return menu;
}
} // namespace
HMENU BuildContextMenu(const ContextMenuModel& menu_model) {
return BuildContextMenuImpl(&menu_model, 0);
}
std::string ResolveURL(const std::string& document,
const std::string& relative) {
if (document.empty()) {
return GURL(relative).spec();
} else {
return GURL(document).Resolve(relative).spec();
}
}
bool HaveSameOrigin(const std::string& url1, const std::string& url2) {
GURL a(url1), b(url2);
bool ret;
if (a.is_valid() != b.is_valid()) {
// Either (but not both) url is invalid, so they can't match.
ret = false;
} else if (!a.is_valid()) {
// Both URLs are invalid (see first check). Just check if the opaque
// strings match exactly.
ret = url1.compare(url2) == 0;
} else if (a.GetOrigin() != b.GetOrigin()) {
// The origins don't match.
ret = false;
} else {
// we have a match.
ret = true;
}
return ret;
}
int GetConfigInt(int default_value, const wchar_t* value_name) {
int ret = default_value;
RegKey config_key;
if (config_key.Open(HKEY_CURRENT_USER, kChromeFrameConfigKey,
KEY_QUERY_VALUE) == ERROR_SUCCESS) {
config_key.ReadValueDW(value_name, reinterpret_cast<DWORD*>(&ret));
}
return ret;
}
int64 GetConfigInt64(int64 default_value, const wchar_t* value_name) {
int64 ret = default_value;
RegKey config_key;
if (config_key.Open(HKEY_CURRENT_USER, kChromeFrameConfigKey,
KEY_QUERY_VALUE) == ERROR_SUCCESS) {
config_key.ReadInt64(value_name, &ret);
}
return ret;
}
bool GetConfigBool(bool default_value, const wchar_t* value_name) {
DWORD value = GetConfigInt(default_value, value_name);
return (value != FALSE);
}
bool SetConfigInt(const wchar_t* value_name, int value) {
RegKey config_key;
if (config_key.Create(HKEY_CURRENT_USER, kChromeFrameConfigKey,
KEY_SET_VALUE) == ERROR_SUCCESS) {
if (config_key.WriteValue(value_name, value) == ERROR_SUCCESS) {
return true;
}
}
return false;
}
bool SetConfigBool(const wchar_t* value_name, bool value) {
return SetConfigInt(value_name, value);
}
bool SetConfigInt64(const wchar_t* value_name, int64 value) {
RegKey config_key;
if (config_key.Create(HKEY_CURRENT_USER, kChromeFrameConfigKey,
KEY_SET_VALUE) == ERROR_SUCCESS) {
if (config_key.WriteValue(value_name, &value, sizeof(value),
REG_QWORD) == ERROR_SUCCESS) {
return true;
}
}
return false;
}
bool DeleteConfigValue(const wchar_t* value_name) {
RegKey config_key;
if (config_key.Open(HKEY_CURRENT_USER, kChromeFrameConfigKey,
KEY_WRITE) == ERROR_SUCCESS) {
if (config_key.DeleteValue(value_name) == ERROR_SUCCESS) {
return true;
}
}
return false;
}
bool IsGcfDefaultRenderer() {
DWORD is_default = 0; // NOLINT
// First check policy settings
PolicySettings::RendererForUrl renderer =
PolicySettings::GetInstance()->default_renderer();
if (renderer != PolicySettings::RENDERER_NOT_SPECIFIED) {
is_default = (renderer == PolicySettings::RENDER_IN_CHROME_FRAME);
} else {
// TODO(tommi): Implement caching for this config value as it gets
// checked frequently.
RegKey config_key;
if (config_key.Open(HKEY_CURRENT_USER, kChromeFrameConfigKey,
KEY_READ) == ERROR_SUCCESS) {
config_key.ReadValueDW(kEnableGCFRendererByDefault, &is_default);
}
}
return is_default != 0;
}
RendererType RendererTypeForUrl(const std::wstring& url) {
// First check if the default renderer settings are specified by policy.
// If so, then that overrides the user settings.
PolicySettings::RendererForUrl renderer =
PolicySettings::GetInstance()->GetRendererForUrl(url.c_str());
if (renderer != PolicySettings::RENDERER_NOT_SPECIFIED) {
// We may know at this point that policy says do NOT render in Chrome Frame.
// To maintain consistency, we return RENDERER_TYPE_UNDETERMINED so that
// content sniffing, etc. still take place.
// TODO(tommi): Clarify the intent here.
return (renderer == PolicySettings::RENDER_IN_CHROME_FRAME) ?
RENDERER_TYPE_CHROME_OPT_IN_URL : RENDERER_TYPE_UNDETERMINED;
}
// TODO(robertshield): Move this into a holder-type class that listens
// for reg change events as well.
static int render_in_cf_by_default = FALSE;
RegistryListPreferencesHolder& render_type_for_url_holder =
g_render_type_for_url_holder.Get();
if (!render_type_for_url_holder.Valid()) {
const wchar_t* url_list_name = kRenderInGCFUrlList;
if (IsGcfDefaultRenderer()) {
url_list_name = kRenderInHostUrlList;
render_in_cf_by_default = TRUE;
} else {
render_in_cf_by_default = FALSE;
}
render_type_for_url_holder.Init(HKEY_CURRENT_USER,
kChromeFrameConfigKey,
url_list_name);
}
DCHECK(render_type_for_url_holder.Valid());
RendererType renderer_type =
render_in_cf_by_default ? RENDERER_TYPE_CHROME_DEFAULT_RENDERER :
RENDERER_TYPE_UNDETERMINED;
if (render_type_for_url_holder.ListMatches(url)) {
renderer_type = render_in_cf_by_default ?
RENDERER_TYPE_UNDETERMINED :
RENDERER_TYPE_CHROME_OPT_IN_URL;
}
return renderer_type;
}
bool ShouldRemoveUAForUrl(const string16& url) {
// TODO(robertshield): Wire up the stuff in PolicySettings here so the value
// can be specified via group policy.
// TODO(robertshield): Add a default list of exclusions here for site with
// known bad UA parsing.
RegistryListPreferencesHolder& user_agent_filter_holder =
g_user_agent_filter_holder.Get();
if (!user_agent_filter_holder.Valid()) {
user_agent_filter_holder.Init(HKEY_CURRENT_USER,
kChromeFrameConfigKey,
kExcludeUAFromDomainList);
}
DCHECK(user_agent_filter_holder.Valid());
return user_agent_filter_holder.ListMatches(url);
}
RegistryListPreferencesHolder& GetRendererTypePreferencesHolderForTesting() {
return g_render_type_for_url_holder.Get();
}
RegistryListPreferencesHolder& GetUserAgentPreferencesHolderForTesting() {
return g_user_agent_filter_holder.Get();
}
HRESULT NavigateBrowserToMoniker(IUnknown* browser, IMoniker* moniker,
const wchar_t* headers, IBindCtx* bind_ctx,
const wchar_t* fragment, IStream* post_data,
VARIANT* flags) {
DCHECK(browser);
DCHECK(moniker);
DCHECK(bind_ctx);
base::win::ScopedComPtr<IWebBrowser2> web_browser2;
HRESULT hr = DoQueryService(SID_SWebBrowserApp, browser,
web_browser2.Receive());
DCHECK(web_browser2);
DLOG_IF(WARNING, FAILED(hr)) << base::StringPrintf(L"SWebBrowserApp 0x%08X",
hr);
if (FAILED(hr))
return hr;
// If the data to be downloaded was received in response to a post request
// then we need to reissue the post request.
base::win::ScopedVariant post_data_variant;
if (post_data) {
RewindStream(post_data);
CComSafeArray<uint8> safe_array_post;
STATSTG stat;
post_data->Stat(&stat, STATFLAG_NONAME);
if (stat.cbSize.LowPart > 0) {
std::string data;
HRESULT hr = E_FAIL;
while ((hr = ReadStream(post_data, 0xffff, &data)) == S_OK) {
safe_array_post.Add(
data.size(),
reinterpret_cast<unsigned char*>(const_cast<char*>(data.data())));
data.clear();
}
} else {
// If we get here it means that the navigation is being reissued for a
// POST request with no data. To ensure that the new window used as a
// target to handle the new navigation issues a POST request
// we need valid POST data. In this case we create a dummy 1 byte array.
// May not work as expected with some web sites.
DLOG(WARNING) << "Reissuing navigation with empty POST data. May not"
<< " work as expected";
safe_array_post.Create(1);
}
post_data_variant.Set(safe_array_post.Detach());
}
// Create a new bind context that's not associated with our callback.
// Calling RevokeBindStatusCallback doesn't disassociate the callback with
// the bind context in IE7. The returned bind context has the same
// implementation of GetRunningObjectTable as the bind context we held which
// basically delegates to ole32's GetRunningObjectTable. The object table
// is then used to determine if the moniker is already running and via
// that mechanism is associated with the same internet request as has already
// been issued.
// TODO(tommi): See if we can get HlinkSimpleNavigateToMoniker to work
// instead. Looks like we'll need to support IHTMLDocument2 (get_URL in
// particular), access to IWebBrowser2 etc.
// HlinkSimpleNavigateToMoniker(moniker, url, NULL, host, bind_context,
// NULL, 0, 0);
base::win::ScopedComPtr<IUriContainer> uri_container;
hr = uri_container.QueryFrom(moniker);
base::win::ScopedVariant headers_var;
if (headers && headers[0])
headers_var.Set(headers);
if (uri_container) {
// IE7 and IE8.
const IID* interface_ids[] = {
&IID_IWebBrowserPriv2IE7,
&IID_IWebBrowserPriv2IE8,
&IID_IWebBrowserPriv2IE8XP,
&IID_IWebBrowserPriv2IE8XPBeta,
};
base::win::ScopedComPtr<IWebBrowserPriv2Common, NULL> browser_priv2;
for (int i = 0; i < arraysize(interface_ids) && browser_priv2 == NULL;
++i) {
hr = web_browser2.QueryInterface(*interface_ids[i],
reinterpret_cast<void**>(browser_priv2.Receive()));
}
DCHECK(browser_priv2);
if (browser_priv2) {
base::win::ScopedComPtr<IUri> uri_obj;
uri_container->GetIUri(uri_obj.Receive());
DCHECK(uri_obj);
if (GetIEVersion() < IE_9) {
hr = browser_priv2->NavigateWithBindCtx2(
uri_obj, flags, NULL, post_data_variant.AsInput(),
headers_var.AsInput(), bind_ctx,
const_cast<wchar_t*>(fragment));
} else {
IWebBrowserPriv2CommonIE9* browser_priv2_ie9 =
reinterpret_cast<IWebBrowserPriv2CommonIE9*>(browser_priv2.get());
hr = browser_priv2_ie9->NavigateWithBindCtx2(
uri_obj, flags, NULL, post_data_variant.AsInput(),
headers_var.AsInput(), bind_ctx,
const_cast<wchar_t*>(fragment), 0);
}
DLOG_IF(WARNING, FAILED(hr))
<< base::StringPrintf(L"NavigateWithBindCtx2 0x%08X", hr);
}
} else {
// IE6
LPOLESTR url = NULL;
if (SUCCEEDED(hr = moniker->GetDisplayName(bind_ctx, NULL, &url))) {
DVLOG(1) << __FUNCTION__ << " " << url;
base::win::ScopedComPtr<IWebBrowserPriv> browser_priv;
if (SUCCEEDED(hr = browser_priv.QueryFrom(web_browser2))) {
GURL target_url(url);
// On IE6 if the original URL has a fragment then the navigation
// attempt is ignored. To workaround this we strip the fragment from
// the url and initiate the navigation. When the active document loads
// we retrieve the original url with the fragment from the Navigation
// manager and use it.
if (target_url.has_ref()) {
url_parse::Component comp;
GURL::Replacements replacements;
replacements.SetRef("", comp);
target_url = target_url.ReplaceComponents(replacements);
fragment = NULL;
}
base::win::ScopedVariant var_url(UTF8ToWide(target_url.spec()).c_str());
hr = browser_priv->NavigateWithBindCtx(var_url.AsInput(), flags, NULL,
post_data_variant.AsInput(),
headers_var.AsInput(), bind_ctx,
const_cast<wchar_t*>(fragment));
DLOG_IF(WARNING, FAILED(hr))
<< base::StringPrintf(L"NavigateWithBindCtx 0x%08X", hr);
} else {
NOTREACHED();
}
::CoTaskMemFree(url);
} else {
DLOG(ERROR) << base::StringPrintf("GetDisplayName: 0x%08X", hr);
}
}
return hr;
}
void MarkBrowserOnThreadForCFNavigation(IBrowserService* browser) {
DCHECK(browser != NULL);
DCHECK(g_tls_browser_for_cf_navigation.Pointer()->Get() == NULL ||
g_tls_browser_for_cf_navigation.Pointer()->Get() == browser);
g_tls_browser_for_cf_navigation.Pointer()->Set(browser);
}
bool CheckForCFNavigation(IBrowserService* browser, bool clear_flag) {
DCHECK(browser);
bool ret = (g_tls_browser_for_cf_navigation.Pointer()->Get() == browser);
if (ret && clear_flag)
g_tls_browser_for_cf_navigation.Pointer()->Set(NULL);
return ret;
}
bool IsValidUrlScheme(const GURL& url, bool is_privileged) {
if (url.is_empty())
return false;
if (url.SchemeIs(chrome::kHttpScheme) ||
url.SchemeIs(chrome::kHttpsScheme) ||
url.SchemeIs(chrome::kAboutScheme))
return true;
// Additional checking for view-source. Allow only http and https
// URLs in view source.
if (url.SchemeIs(content::kViewSourceScheme)) {
GURL sub_url(url.GetContent());
if (sub_url.SchemeIs(chrome::kHttpScheme) ||
sub_url.SchemeIs(chrome::kHttpsScheme))
return true;
else
return false;
}
if (is_privileged &&
(url.SchemeIs(chrome::kDataScheme) ||
url.SchemeIs(extensions::kExtensionScheme)))
return true;
return false;
}
std::string GetRawHttpHeaders(IWinInetHttpInfo* info) {
DCHECK(info);
std::string buffer;
DWORD size = 0;
DWORD flags = 0;
DWORD reserved = 0;
HRESULT hr = info->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, NULL, &size,
&flags, &reserved);
if (!size) {
DLOG(WARNING) << "Failed to query HTTP headers size. Error: " << hr;
} else {
buffer.resize(size + 1);
hr = info->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF, &buffer[0],
&size, &flags, &reserved);
if (FAILED(hr)) {
DLOG(WARNING) << "Failed to query HTTP headers. Error: " << hr;
}
}
return buffer;
}
bool IsSubFrameRequest(IUnknown* service_provider) {
DCHECK(service_provider);
// We need to be able to get at an IWebBrowser2 if we are to decide whether
// this request originates from a non-top-level frame.
base::win::ScopedComPtr<IWebBrowser2> web_browser;
HRESULT hr = DoQueryService(IID_ITargetFrame2, service_provider,
web_browser.Receive());
bool is_sub_frame_request = false;
if (web_browser) {
// Now check to see if we are in a sub-frame.
base::win::ScopedComPtr<IHTMLWindow2> current_frame, parent_frame;
hr = DoQueryService(IID_IHTMLWindow2, service_provider,
current_frame.Receive());
if (current_frame) {
// Only the top level window will return self when get_parent is called.
current_frame->get_parent(parent_frame.Receive());
if (parent_frame != current_frame) {
DVLOG(1) << "Sub frame detected";
is_sub_frame_request = true;
}
}
} else {
DVLOG(1) << "IsSubFrameRequest - no IWebBrowser2";
is_sub_frame_request = true;
}
return is_sub_frame_request;
}
bool IsHeadlessMode() {
bool headless = GetConfigBool(false, kChromeFrameHeadlessMode);
return headless;
}
bool IsAccessibleMode() {
bool accessible = GetConfigBool(false, kChromeFrameAccessibleMode);
return accessible;
}
bool IsUnpinnedMode() {
// We only check this value once and then cache it since changing the registry
// once we've pinned the DLL won't have any effect.
static bool unpinned = GetConfigBool(false, kChromeFrameUnpinnedMode);
return unpinned;
}
std::wstring GetActualUrlFromMoniker(IMoniker* moniker,
IBindCtx* bind_context,
const std::wstring& bho_url) {
CComHeapPtr<WCHAR> display_name;
moniker->GetDisplayName(bind_context, NULL, &display_name);
std::wstring moniker_url = display_name;
GURL parsed_url(WideToUTF8(bho_url));
if (!parsed_url.has_ref())
return moniker_url;
if (StartsWith(bho_url, moniker_url, false) &&
bho_url[moniker_url.length()] == L'#')
return bho_url;
return moniker_url;
}
bool IsTopLevelWindow(HWND window) {
long style = GetWindowLong(window, GWL_STYLE); // NOLINT
if (!(style & WS_CHILD))
return true;
HWND parent = GetParent(window);
return !parent || (parent == GetDesktopWindow());
}
HRESULT RewindStream(IStream* stream) {
HRESULT hr = E_POINTER;
if (stream) {
LARGE_INTEGER zero = {0};
ULARGE_INTEGER new_pos = {0};
hr = stream->Seek(zero, STREAM_SEEK_SET, &new_pos);
}
return hr;
}
std::wstring GuidToString(const GUID& guid) {
std::wstring ret;
::StringFromGUID2(guid, WriteInto(&ret, 39), 39);
return ret;
}
int32 MapCookieStateToCookieAction(InternetCookieState cookie_state) {
int32 cookie_action = COOKIEACTION_NONE;
switch (cookie_state) {
case COOKIE_STATE_UNKNOWN:
cookie_action = COOKIEACTION_NONE;
break;
case COOKIE_STATE_ACCEPT:
cookie_action = COOKIEACTION_ACCEPT;
break;
case COOKIE_STATE_LEASH:
cookie_action = COOKIEACTION_LEASH;
break;
case COOKIE_STATE_DOWNGRADE:
cookie_action = COOKIEACTION_DOWNGRADE;
break;
case COOKIE_STATE_REJECT:
cookie_action = COOKIEACTION_REJECT;
break;
default:
cookie_action = COOKIEACTION_REJECT;
break;
}
return cookie_action;
}
GURL GetUrlWithoutFragment(const wchar_t* url) {
GURL parsed_url(url);
if (parsed_url.has_ref()) {
url_parse::Component comp;
GURL::Replacements replacements;
replacements.SetRef("", comp);
parsed_url = parsed_url.ReplaceComponents(replacements);
}
return parsed_url;
}
bool CompareUrlsWithoutFragment(const wchar_t* url1, const wchar_t* url2) {
GURL parsed_url1 = GetUrlWithoutFragment(url1);
GURL parsed_url2 = GetUrlWithoutFragment(url2);
return parsed_url1 == parsed_url2;
}
std::string FindReferrerFromHeaders(const wchar_t* headers,
const wchar_t* additional_headers) {
std::string referrer;
const wchar_t* both_headers[] = { headers, additional_headers };
for (int i = 0; referrer.empty() && i < arraysize(both_headers); ++i) {
if (!both_headers[i])
continue;
std::string raw_headers_utf8 = WideToUTF8(both_headers[i]);
net::HttpUtil::HeadersIterator it(raw_headers_utf8.begin(),
raw_headers_utf8.end(), "\r\n");
while (it.GetNext()) {
if (LowerCaseEqualsASCII(it.name(), "referer")) {
referrer = it.values();
break;
}
}
}
return referrer;
}
std::string GetHttpHeadersFromBinding(IBinding* binding) {
if (binding == NULL) {
DLOG(WARNING) << "GetHttpResponseStatus - no binding_";
return std::string();
}
base::win::ScopedComPtr<IWinInetHttpInfo> info;
if (FAILED(info.QueryFrom(binding))) {
DLOG(WARNING) << "Failed to QI for IWinInetHttpInfo";
return std::string();
}
return GetRawHttpHeaders(info);
}
int GetHttpResponseStatusFromBinding(IBinding* binding) {
DVLOG(1) << __FUNCTION__;
if (binding == NULL) {
DLOG(WARNING) << "GetHttpResponseStatus - no binding_";
return 0;
}
int http_status = 0;
base::win::ScopedComPtr<IWinInetHttpInfo> info;
if (SUCCEEDED(info.QueryFrom(binding))) {
char status[10] = {0};
DWORD buf_size = sizeof(status);
DWORD flags = 0;
DWORD reserved = 0;
if (SUCCEEDED(info->QueryInfo(HTTP_QUERY_STATUS_CODE, status, &buf_size,
&flags, &reserved))) {
base::StringToInt(status, &http_status);
} else {
NOTREACHED() << "Failed to get HTTP status";
}
} else {
NOTREACHED() << "failed to get IWinInetHttpInfo from binding_";
}
return http_status;
}
CLIPFORMAT GetTextHtmlClipboardFormat() {
static const CLIPFORMAT text_html = RegisterClipboardFormat(CFSTR_MIME_HTML);
return text_html;
}
bool IsTextHtmlMimeType(const wchar_t* mime_type) {
return IsTextHtmlClipFormat(RegisterClipboardFormatW(mime_type));
}
bool IsTextHtmlClipFormat(CLIPFORMAT cf) {
return cf == GetTextHtmlClipboardFormat();
}
bool IsSystemProcess() {
bool is_system = false;
CAccessToken process_token;
if (process_token.GetProcessToken(TOKEN_QUERY, GetCurrentProcess())) {
CSid logon_sid;
if (process_token.GetUser(&logon_sid)) {
is_system = logon_sid == Sids::System();
}
}
return is_system;
}
std::string BindStatus2Str(ULONG bind_status) {
std::string s;
static const char* const bindstatus_txt[] = {
"BINDSTATUS_FINDINGRESOURCE",
"BINDSTATUS_CONNECTING",
"BINDSTATUS_REDIRECTING",
"BINDSTATUS_BEGINDOWNLOADDATA",
"BINDSTATUS_DOWNLOADINGDATA",
"BINDSTATUS_ENDDOWNLOADDATA",
"BINDSTATUS_BEGINDOWNLOADCOMPONENTS",
"BINDSTATUS_INSTALLINGCOMPONENTS",
"BINDSTATUS_ENDDOWNLOADCOMPONENTS",
"BINDSTATUS_USINGCACHEDCOPY",
"BINDSTATUS_SENDINGREQUEST",
"BINDSTATUS_CLASSIDAVAILABLE",
"BINDSTATUS_MIMETYPEAVAILABLE",
"BINDSTATUS_CACHEFILENAMEAVAILABLE",
"BINDSTATUS_BEGINSYNCOPERATION",
"BINDSTATUS_ENDSYNCOPERATION",
"BINDSTATUS_BEGINUPLOADDATA",
"BINDSTATUS_UPLOADINGDATA",
"BINDSTATUS_ENDUPLOADINGDATA",
"BINDSTATUS_PROTOCOLCLASSID",
"BINDSTATUS_ENCODING",
"BINDSTATUS_VERFIEDMIMETYPEAVAILABLE",
"BINDSTATUS_CLASSINSTALLLOCATION",
"BINDSTATUS_DECODING",
"BINDSTATUS_LOADINGMIMEHANDLER",
"BINDSTATUS_CONTENTDISPOSITIONATTACH",
"BINDSTATUS_FILTERREPORTMIMETYPE",
"BINDSTATUS_CLSIDCANINSTANTIATE",
"BINDSTATUS_IUNKNOWNAVAILABLE",
"BINDSTATUS_DIRECTBIND",
"BINDSTATUS_RAWMIMETYPE",
"BINDSTATUS_PROXYDETECTING",
"BINDSTATUS_ACCEPTRANGES",
"BINDSTATUS_COOKIE_SENT",
"BINDSTATUS_COMPACT_POLICY_RECEIVED",
"BINDSTATUS_COOKIE_SUPPRESSED",
"BINDSTATUS_COOKIE_STATE_UNKNOWN",
"BINDSTATUS_COOKIE_STATE_ACCEPT",
"BINDSTATUS_COOKIE_STATE_REJECT",
"BINDSTATUS_COOKIE_STATE_PROMPT",
"BINDSTATUS_COOKIE_STATE_LEASH",
"BINDSTATUS_COOKIE_STATE_DOWNGRADE",
"BINDSTATUS_POLICY_HREF",
"BINDSTATUS_P3P_HEADER",
"BINDSTATUS_SESSION_COOKIE_RECEIVED",
"BINDSTATUS_PERSISTENT_COOKIE_RECEIVED",
"BINDSTATUS_SESSION_COOKIES_ALLOWED",
"BINDSTATUS_CACHECONTROL",
"BINDSTATUS_CONTENTDISPOSITIONFILENAME",
"BINDSTATUS_MIMETEXTPLAINMISMATCH",
"BINDSTATUS_PUBLISHERAVAILABLE",
"BINDSTATUS_DISPLAYNAMEAVAILABLE",
"BINDSTATUS_SSLUX_NAVBLOCKED",
"BINDSTATUS_SERVER_MIMETYPEAVAILABLE",
"BINDSTATUS_SNIFFED_CLASSIDAVAILABLE",
"BINDSTATUS_64BIT_PROGRESS"
};
if (bind_status >= 1 && bind_status <= BINDSTATUS_64BIT_PROGRESS)
s = bindstatus_txt[bind_status - 1];
else
s = base::StringPrintf("UnDoc[%#x]", bind_status);
return s;
}
std::string PiFlags2Str(DWORD flags) {
#define ADD_PI_FLAG(x) \
if (flags & x) { \
s.append(#x ## " "); \
flags &= ~x; \
}
std::string s = " flags ";
ADD_PI_FLAG(PI_PARSE_URL);
ADD_PI_FLAG(PI_FILTER_MODE);
ADD_PI_FLAG(PI_FORCE_ASYNC);
ADD_PI_FLAG(PI_USE_WORKERTHREAD);
ADD_PI_FLAG(PI_MIMEVERIFICATION);
ADD_PI_FLAG(PI_CLSIDLOOKUP);
ADD_PI_FLAG(PI_DATAPROGRESS);
ADD_PI_FLAG(PI_SYNCHRONOUS);
ADD_PI_FLAG(PI_APARTMENTTHREADED);
ADD_PI_FLAG(PI_CLASSINSTALL);
ADD_PI_FLAG(PI_PASSONBINDCTX);
ADD_PI_FLAG(PI_NOMIMEHANDLER);
ADD_PI_FLAG(PI_LOADAPPDIRECT);
ADD_PI_FLAG(PD_FORCE_SWITCH);
ADD_PI_FLAG(PI_PREFERDEFAULTHANDLER);
if (flags)
s += base::StringPrintf("+UnDoc[%#x]", flags);
return s;
#undef ADD_PI_FLAG
}
std::string Bscf2Str(DWORD flags) {
#define ADD_BSCF_FLAG(x) \
if (flags & x) {\
s.append(#x ## " "); \
flags &= ~x; \
}
std::string s = " flags ";
ADD_BSCF_FLAG(BSCF_FIRSTDATANOTIFICATION)
ADD_BSCF_FLAG(BSCF_INTERMEDIATEDATANOTIFICATION)
ADD_BSCF_FLAG(BSCF_LASTDATANOTIFICATION)
ADD_BSCF_FLAG(BSCF_DATAFULLYAVAILABLE)
ADD_BSCF_FLAG(BSCF_AVAILABLEDATASIZEUNKNOWN)
ADD_BSCF_FLAG(BSCF_SKIPDRAINDATAFORFILEURLS)
ADD_BSCF_FLAG(BSCF_64BITLENGTHDOWNLOAD)
if (flags)
s += base::StringPrintf("+UnDoc[%#x]", flags);
return s;
#undef ADD_BSCF_FLAG
}
// Reads data from a stream into a string.
HRESULT ReadStream(IStream* stream, size_t size, std::string* data) {
DCHECK(stream);
DCHECK_GT(size, 0u);
DCHECK(data);
DWORD read = 0;
HRESULT hr = stream->Read(WriteInto(data, size + 1), size, &read);
DCHECK(hr == S_OK || hr == S_FALSE || hr == E_PENDING);
if (read) {
data->erase(read);
DCHECK_EQ(read, data->length());
} else {
data->clear();
// Return S_FALSE if the underlying stream returned S_OK and zero bytes.
if (hr == S_OK)
hr = S_FALSE;
}
return hr;
}
ChromeFrameUrl::ChromeFrameUrl() {
Reset();
}
bool ChromeFrameUrl::Parse(const std::wstring& url) {
Reset();
parsed_url_ = GURL(url);
if (parsed_url_.is_empty())
return false;
is_chrome_protocol_ = parsed_url_.SchemeIs(kGCFProtocol);
if (is_chrome_protocol_) {
parsed_url_ = GURL(url.c_str() + lstrlen(kChromeProtocolPrefix));
return true;
}
return ParseAttachExternalTabUrl();
}
bool ChromeFrameUrl::ParseAttachExternalTabUrl() {
std::string query = parsed_url_.query();
if (!StartsWithASCII(query, kAttachExternalTabPrefix, false)) {
return parsed_url_.is_valid();
}
attach_to_external_tab_ = true;
base::StringTokenizer tokenizer(query, "&");
// Skip over kChromeAttachExternalTabPrefix
tokenizer.GetNext();
// Read the following items in order.
// 1. cookie
// 2. disposition
// 3. dimension.x
// 4. dimension.y
// 5. dimension.width
// 6. dimension.height.
if (tokenizer.GetNext()) {
char* end_ptr = 0;
cookie_ = _strtoui64(tokenizer.token().c_str(), &end_ptr, 10);
} else {
return false;
}
if (tokenizer.GetNext()) {
disposition_ = atoi(tokenizer.token().c_str());
} else {
return false;
}
if (tokenizer.GetNext()) {
dimensions_.set_x(atoi(tokenizer.token().c_str()));
} else {
return false;
}
if (tokenizer.GetNext()) {
dimensions_.set_y(atoi(tokenizer.token().c_str()));
} else {
return false;
}
if (tokenizer.GetNext()) {
dimensions_.set_width(atoi(tokenizer.token().c_str()));
} else {
return false;
}
if (tokenizer.GetNext()) {
dimensions_.set_height(atoi(tokenizer.token().c_str()));
} else {
return false;
}
if (tokenizer.GetNext()) {
profile_name_ = tokenizer.token();
// Escape out special characters like %20, etc.
profile_name_ = net::UnescapeURLComponent(profile_name_,
net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
} else {
return false;
}
return true;
}
void ChromeFrameUrl::Reset() {
attach_to_external_tab_ = false;
is_chrome_protocol_ = false;
cookie_ = 0;
dimensions_.SetRect(0, 0, 0, 0);
disposition_ = 0;
profile_name_.clear();
}
bool CanNavigate(const GURL& url,
NavigationConstraints* navigation_constraints) {
if (!url.is_valid()) {
DLOG(ERROR) << "Invalid URL passed to InitiateNavigation: " << url;
return false;
}
if (!navigation_constraints) {
NOTREACHED() << "Invalid NavigationConstraints passed in";
return false;
}
// No sanity checks if unsafe URLs are allowed
if (navigation_constraints->AllowUnsafeUrls())
return true;
if (!navigation_constraints->IsSchemeAllowed(url)) {
DLOG(WARNING) << __FUNCTION__ << " Disallowing navigation to url: " << url;
return false;
}
if (!navigation_constraints->IsZoneAllowed(url)) {
DLOG(WARNING) << __FUNCTION__
<< " Disallowing navigation to restricted url: " << url;
return false;
}
return true;
}
void WaitWithMessageLoop(HANDLE* handles, int count, DWORD timeout) {
base::Time now = base::Time::Now();
base::Time wait_until = now + base::TimeDelta::FromMilliseconds(timeout);
while (wait_until >= now) {
base::TimeDelta wait_time = wait_until - now;
DWORD wait = MsgWaitForMultipleObjects(
count, handles, FALSE, static_cast<DWORD>(wait_time.InMilliseconds()),
QS_ALLINPUT);
switch (wait) {
case WAIT_OBJECT_0:
case WAIT_TIMEOUT:
return;
case WAIT_OBJECT_0 + 1: {
MSG msg = {0};
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
break;
}
default: {
NOTREACHED() << "Unexpected return from MsgWaitForMultipleObjects :"
<< wait;
return;
}
}
now = base::Time::Now();
}
}
// Returns -1 if no directive is found, std::numeric_limits<int>::max() if the
// directive matches all IE versions ('Chrome=1') or the maximum IE version
// matched ('Chrome=IE7' => 7)
int GetXUaCompatibleDirective(const std::string& directive, char delimiter) {
net::HttpUtil::NameValuePairsIterator name_value_pairs(directive.begin(),
directive.end(),
delimiter);
// Loop through the values until a valid 'Chrome=<FILTER>' entry is found
while (name_value_pairs.GetNext()) {
if (!LowerCaseEqualsASCII(name_value_pairs.name_begin(),
name_value_pairs.name_end(),
"chrome")) {
continue;
}
std::string::const_iterator filter_begin = name_value_pairs.value_begin();
std::string::const_iterator filter_end = name_value_pairs.value_end();
size_t filter_length = filter_end - filter_begin;
if (filter_length == 1 && *filter_begin == '1') {
return std::numeric_limits<int>::max();
}
if (filter_length < 3 ||
!LowerCaseEqualsASCII(filter_begin, filter_begin + 2, "ie") ||
!isdigit(*(filter_begin + 2))) { // ensure no leading +/-
continue;
}
int header_ie_version = 0;
if (!base::StringToInt(base::StringPiece(filter_begin + 2,
filter_end),
&header_ie_version) ||
header_ie_version == 0) { // ensure it's not a sequence of 0's
continue;
}
// The first valid directive we find wins, whether it matches or not
return header_ie_version;
}
return -1;
}
bool CheckXUaCompatibleDirective(const std::string& directive,
int ie_major_version) {
int header_ie_version = GetXUaCompatibleDirective(directive, ';');
if (header_ie_version == -1) {
header_ie_version = GetXUaCompatibleDirective(directive, ',');
}
return header_ie_version >= ie_major_version;
}
void EnumerateKeyValues(HKEY parent_key, const wchar_t* sub_key_name,
std::vector<std::wstring>* values) {
DCHECK(values);
base::win::RegistryValueIterator url_list(parent_key, sub_key_name);
while (url_list.Valid()) {
values->push_back(url_list.Value());
++url_list;
}
}
std::wstring GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> module_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
DCHECK(module_version_info.get() != NULL);
return module_version_info->file_version();
}
bool IsChromeFrameDocument(IWebBrowser2* web_browser) {
if (!web_browser)
return false;
base::win::ScopedComPtr<IDispatch> doc;
web_browser->get_Document(doc.Receive());
if (doc) {
// Detect if CF is rendering based on whether the document is a
// ChromeActiveDocument. Detecting based on hwnd is problematic as
// the CF Active Document window may not have been created yet.
base::win::ScopedComPtr<IChromeFrame> chrome_frame;
chrome_frame.QueryFrom(doc);
return chrome_frame.get() != NULL;
}
return false;
}
bool IncreaseWinInetConnections(DWORD connections) {
static bool wininet_connection_count_updated = false;
if (wininet_connection_count_updated) {
return true;
}
static int connection_options[] = {
INTERNET_OPTION_MAX_CONNS_PER_SERVER,
INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER,
};
BOOL ret = FALSE;
for (int option_index = 0; option_index < arraysize(connection_options);
++option_index) {
DWORD connection_value_size = sizeof(DWORD);
DWORD current_connection_limit = 0;
InternetQueryOption(NULL, connection_options[option_index],
¤t_connection_limit, &connection_value_size);
if (current_connection_limit > connections) {
continue;
}
ret = InternetSetOption(NULL, connection_options[option_index],
&connections, connection_value_size);
if (!ret) {
return false;
}
}
wininet_connection_count_updated = true;
return true;
}
void GetChromeFrameProfilePath(const string16& profile_name,
base::FilePath* profile_path) {
chrome::GetChromeFrameUserDataDirectory(profile_path);
*profile_path = profile_path->Append(profile_name);
DVLOG(1) << __FUNCTION__ << ": " << profile_path->value();
}
| 32.334323 | 80 | 0.675451 | [
"render",
"object",
"vector",
"model"
] |
11f263e047b93502255b8003471a286aaeee687b | 8,289 | cpp | C++ | source/test/TestRunCheck_DoubleEntry.cpp | dougpuob/namelint | 6a144cdc4b3935994059961fe712525ce30ff269 | [
"MIT"
] | 30 | 2020-08-01T07:29:23.000Z | 2022-03-30T13:21:43.000Z | source/test/TestRunCheck_DoubleEntry.cpp | dougpuob/namelint | 6a144cdc4b3935994059961fe712525ce30ff269 | [
"MIT"
] | 48 | 2019-01-02T18:19:41.000Z | 2020-04-26T02:53:23.000Z | source/test/TestRunCheck_DoubleEntry.cpp | dougpuob/namelint | 6a144cdc4b3935994059961fe712525ce30ff269 | [
"MIT"
] | 5 | 2019-08-30T08:41:17.000Z | 2020-05-19T01:17:15.000Z | #include <vector>
#include <gtest/gtest.h>
#include "../Common.h"
#include "../TraceMemo.h"
using namespace namelint;
const string ConfigToml = "\
[General.Options] \n\
Version = 0.3 \n\
CheckFileName = false \n\
CheckVariableName = true \n\
CheckFunctionName = true \n\
CheckEnum = true \n\
CheckStruct = true \n\
AllowedPrintResult = false \n\
AllowedWriteJsonResult = false \n\
AllowedUnderscopeChar = false \n\
AllowedArrayAffected = false \n\
\n\
[General.Rules] \n\
FileName = 0 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 3: lower_snake \n\
\n\
FunctionName = 0 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
\n\
VariableName = 4 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
# 4: Hungarian \n\
\n\
ClassName = 0 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
# 5: UPPER_SNAKE \n\
\n\
EnumTagName = 0 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
# 5: UPPER_SNAKE \n\
\n\
EnumValueName = 0 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
# 5: UPPER_SNAKE \n\
\n\
StructTagName = 0 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
# 5: UPPER_SNAKE \n\
\n\
StructValueName = 4 # 0: Default (UpperCamel) \n\
# 1: UpperCamel \n\
# 2: lowerCamel \n\
# 3: lower_snake \n\
# 4: Hungarian \n\
# 5: UPPER_SNAKE \n\
\n\
\n\
[Hungarian.Others] \n\
PreferUpperCamelIfMissed = true \n\
\n\
[Hungarian.NullStringList] \n\
\"char*\" = \"sz\" \n\
\"wchar_t*\" = \"wsz\" \n\
\"char**\" = \"psz\" \n\
\"wchar_t**\" = \"pwsz\" \n\
\"char[]\" = \"sz\" \n\
\"wchar_t[]\" = \"wsz\" \n\
\n\
[Hungarian.WordList] \n\
# C Primitive Type \n\
\"void\" = \"\" \n\
\"size_t\" = \"n\" \n\
\"int8_t\" = \"i8\" \n\
\"int16_t\" = \"i16\" \n\
\"int32_t\" = \"i32\" \n\
\"int64_t\" = \"i64\" \n\
\"uint8_t\" = \"u8\" \n\
\"uint16_t\" = \"u16\" \n\
\"uint32_t\" = \"u32\" \n\
\"uint64_t\" = \"u64\" \n\
\"char\" = \"c\" \n\
\"_Bool\" = \"b\" \n\
\"bool\" = \"b\" \n\
\"wchar_t\" = \"wc\" \n\
\"signed char\" = \"sc\" \n\
\"unsigned char\" = \"uc\" \n\
\"short\" = \"s\" \n\
\"short int\" = \"si\" \n\
\"signed short\" = \"ss\" \n\
\"signed short int\" = \"ssi\" \n\
\"unsigned short\" = \"us\" \n\
\"unsigned short int\" = \"usi\" \n\
\"int\" = \"i\" \n\
\"signed\" = \"s\" \n\
\"signed int\" = \"si\" \n\
\"unsigned\" = \"u\" \n\
\"unsigned int\" = \"ui\" \n\
\"long\" = \"l\" \n\
\"long int\" = \"li\" \n\
\"signed long\" = \"sl\" \n\
\"signed long int\" = \"sli\" \n\
\"unsigned long\" = \"ul\" \n\
\"unsigned long int\" = \"uli\" \n\
\"long long\" = \"ll\" \n\
\"long long int\" = \"lli\" \n\
\"signed long long\" = \"sll\" \n\
\"signed long long int\" = \"slli\" \n\
\"unsigned long long\" = \"ull\" \n\
\"unsigned long long int\" = \"ulli\" \n\
\"float\" = \"f\" \n\
\"double\" = \"d\" \n\
\"long double\" = \"ld\" \n\
\n\
# Windows Type \n\
\"ULONG\" = \"ul\" \n\
\"DWORD\" = \"dw\" \n\
\"DWORD64\" = \"dw64\" \n\
\"WORD\" = \"w\" \n\
\"CHAR\" = \"c\" \n\
\"BYTE\" = \"by\" \n\
\"HANDLE\" = \"h\" \n\
\"BOOLEAN\" = \"b\" \n\
\"LONGLONG\" = \"ll\" \n\
";
namespace RunCheckDoubleEntry {} // namespace RunCheckDoubleEntry
| 59.207143 | 65 | 0.215949 | [
"vector"
] |
11f32bf9edffa05e3ffe6f71d71cbee4b43843be | 2,280 | cc | C++ | src/generate/generate_xyz.cc | ojcole/re-pairing-brackets | 1bd76bd5f19381d881116564bbaaa5e4e1395942 | [
"MIT"
] | null | null | null | src/generate/generate_xyz.cc | ojcole/re-pairing-brackets | 1bd76bd5f19381d881116564bbaaa5e4e1395942 | [
"MIT"
] | null | null | null | src/generate/generate_xyz.cc | ojcole/re-pairing-brackets | 1bd76bd5f19381d881116564bbaaa5e4e1395942 | [
"MIT"
] | null | null | null | // MIT License
// Copyright (c) 2020-2021 Oliver Cole
// 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 "generate_xyz.h"
#include <cassert>
#include <cmath>
#include "solve/solution.h"
namespace generate {
// Separate recursive call to ensure that a copy is only made once
std::string GenerateXR(std::vector<int> &xs) {
std::string begin(xs.back(), OPENING_BRACKET);
std::string end(xs.back(), CLOSING_BRACKET);
// Base case
if (xs.size() == 1) {
return begin + end;
}
// Set the value as defined by https://dl.acm.org/doi/10.1145/3373718.3394752
xs.pop_back();
std::string recursed = GenerateX(xs);
return begin + recursed + recursed + end;
}
std::string GenerateX(std::vector<int> xs) {
assert(xs.size() > 0);
return GenerateXR(xs);
}
std::string GenerateZ(int n) { return GenerateY(1, n); }
std::string GenerateY(int l) {
return GenerateY(static_cast<int>(floor(l * log2(l))), l);
}
std::string GenerateY(int m, int l) {
std::vector<int> nums;
// Construct the vector of values
// https://dl.acm.org/doi/10.1145/3373718.3394752
for (int i{}; i < m * l; i++) {
auto ai = static_cast<int>(pow(2, floor(i / l)));
nums.push_back(ai);
}
return GenerateX(nums);
}
} // namespace generate
| 30 | 80 | 0.710526 | [
"vector"
] |
11f3a276c7c7e7e98489fc77e8ba8d912e2dcbfb | 8,789 | cpp | C++ | clang/test/SemaCXX/attr-target-mv.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | clang/test/SemaCXX/attr-target-mv.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 497 | 2017-04-04T14:22:22.000Z | 2020-03-10T14:12:27.000Z | clang/test/SemaCXX/attr-target-mv.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -verify -fexceptions -fcxx-exceptions %s -std=c++14
void __attribute__((target("default"))) invalid_features(void);
//expected-error@+2 {{function declaration is missing 'target' attribute in a multiversioned function}}
//expected-warning@+1 {{unsupported 'hello_world' in the 'target' attribute string; 'target' attribute ignored}}
void __attribute__((target("hello_world"))) invalid_features(void);
//expected-error@+1 {{function multiversioning doesn't support feature 'no-sse4.2'}}
void __attribute__((target("no-sse4.2"))) invalid_features(void);
void __attribute__((target("sse4.2"))) no_default(void);
void __attribute__((target("arch=sandybridge"))) no_default(void);
void use1(void){
// expected-error@+1 {{no matching function for call to 'no_default'}}
no_default();
}
constexpr int __attribute__((target("sse4.2"))) foo(void) { return 0; }
constexpr int __attribute__((target("arch=sandybridge"))) foo(void);
//expected-error@+1 {{multiversioned function declaration has a different constexpr specification}}
int __attribute__((target("arch=ivybridge"))) foo(void) {return 1;}
constexpr int __attribute__((target("default"))) foo(void) { return 2; }
int __attribute__((target("sse4.2"))) foo2(void) { return 0; }
//expected-error@+1 {{multiversioned function declaration has a different constexpr specification}}
constexpr int __attribute__((target("arch=sandybridge"))) foo2(void);
int __attribute__((target("arch=ivybridge"))) foo2(void) {return 1;}
int __attribute__((target("default"))) foo2(void) { return 2; }
static int __attribute__((target("sse4.2"))) bar(void) { return 0; }
static int __attribute__((target("arch=sandybridge"))) bar(void);
//expected-error@+1 {{multiversioned function declaration has a different storage class}}
int __attribute__((target("arch=ivybridge"))) bar(void) {return 1;}
static int __attribute__((target("default"))) bar(void) { return 2; }
int __attribute__((target("sse4.2"))) bar2(void) { return 0; }
//expected-error@+1 {{multiversioned function declaration has a different storage class}}
static int __attribute__((target("arch=sandybridge"))) bar2(void);
int __attribute__((target("arch=ivybridge"))) bar2(void) {return 1;}
int __attribute__((target("default"))) bar2(void) { return 2; }
inline int __attribute__((target("sse4.2"))) baz(void) { return 0; }
inline int __attribute__((target("arch=sandybridge"))) baz(void);
//expected-error@+1 {{multiversioned function declaration has a different inline specification}}
int __attribute__((target("arch=ivybridge"))) baz(void) {return 1;}
inline int __attribute__((target("default"))) baz(void) { return 2; }
int __attribute__((target("sse4.2"))) baz2(void) { return 0; }
//expected-error@+1 {{multiversioned function declaration has a different inline specification}}
inline int __attribute__((target("arch=sandybridge"))) baz2(void);
int __attribute__((target("arch=ivybridge"))) baz2(void) {return 1;}
int __attribute__((target("default"))) baz2(void) { return 2; }
float __attribute__((target("sse4.2"))) bock(void) { return 0; }
//expected-error@+1 {{multiversioned function declaration has a different return type}}
int __attribute__((target("arch=sandybridge"))) bock(void);
//expected-error@+1 {{multiversioned function declaration has a different return type}}
int __attribute__((target("arch=ivybridge"))) bock(void) {return 1;}
//expected-error@+1 {{multiversioned function declaration has a different return type}}
int __attribute__((target("default"))) bock(void) { return 2; }
int __attribute__((target("sse4.2"))) bock2(void) { return 0; }
//expected-error@+1 {{multiversioned function declaration has a different return type}}
float __attribute__((target("arch=sandybridge"))) bock2(void);
int __attribute__((target("arch=ivybridge"))) bock2(void) {return 1;}
int __attribute__((target("default"))) bock2(void) { return 2; }
auto __attribute__((target("sse4.2"))) bock3(void) -> int { return 0; }
//expected-error@+1 {{multiversioned function declaration has a different return type}}
auto __attribute__((target("arch=sandybridge"))) bock3(void) -> short { return (short)0;}
int __attribute__((target("sse4.2"))) bock4(void) noexcept(false) { return 0; }
//expected-error@+2 {{exception specification in declaration does not match previous declaration}}
//expected-note@-2 {{previous declaration is here}}
int __attribute__((target("arch=sandybridge"))) bock4(void) noexcept(true) { return 1;}
// FIXME: Add support for templates and virtual functions!
template<typename T>
int __attribute__((target("sse4.2"))) foo(T) { return 0; }
// expected-error@+2 {{multiversioned functions do not yet support function templates}}
template<typename T>
int __attribute__((target("arch=sandybridge"))) foo(T);
// expected-error@+2 {{multiversioned functions do not yet support function templates}}
template<typename T>
int __attribute__((target("default"))) foo(T) { return 2; }
struct S {
template<typename T>
int __attribute__((target("sse4.2"))) foo(T) { return 0; }
// expected-error@+2 {{multiversioned functions do not yet support function templates}}
template<typename T>
int __attribute__((target("arch=sandybridge"))) foo(T);
// expected-error@+2 {{multiversioned functions do not yet support function templates}}
template<typename T>
int __attribute__((target("default"))) foo(T) { return 2; }
// expected-error@+1 {{multiversioned functions do not yet support virtual functions}}
virtual void __attribute__((target("default"))) virt();
};
extern "C" {
int __attribute__((target("sse4.2"))) diff_mangle(void) { return 0; }
}
//expected-error@+1 {{multiversioned function declaration has a different linkage}}
int __attribute__((target("arch=sandybridge"))) diff_mangle(void) { return 0; }
// expected-error@+1 {{multiversioned functions do not yet support deduced return types}}
auto __attribute__((target("default"))) deduced_return(void) { return 0; }
// expected-error@-1 {{cannot initialize return object of type 'auto' with an rvalue of type 'int'}}
auto __attribute__((target("default"))) trailing_return(void)-> int { return 0; }
__attribute__((target("default"))) void DiffDecl();
namespace N {
using ::DiffDecl;
// expected-error@+3 {{declaration conflicts with target of using declaration already in scope}}
// expected-note@-4 {{target of using declaration}}
// expected-note@-3 {{using declaration}}
__attribute__((target("arch=sandybridge"))) void DiffDecl();
} // namespace N
struct SpecialFuncs {
// expected-error@+1 {{multiversioned functions do not yet support constructors}}
__attribute__((target("default"))) SpecialFuncs();
// expected-error@+1 {{multiversioned functions do not yet support destructors}}
__attribute__((target("default"))) ~SpecialFuncs();
// expected-error@+1 {{multiversioned functions do not yet support defaulted functions}}
SpecialFuncs& __attribute__((target("default"))) operator=(const SpecialFuncs&) = default;
// expected-error@+1 {{multiversioned functions do not yet support deleted functions}}
SpecialFuncs& __attribute__((target("default"))) operator=(SpecialFuncs&&) = delete;
};
class Secret {
int i = 0;
__attribute__((target("default")))
friend int SecretAccessor(Secret &s);
__attribute__((target("arch=sandybridge")))
friend int SecretAccessor(Secret &s);
};
__attribute__((target("default")))
int SecretAccessor(Secret &s) {
return s.i;
}
__attribute__((target("arch=sandybridge")))
int SecretAccessor(Secret &s) {
return s.i + 2;
}
__attribute__((target("arch=ivybridge")))
int SecretAccessor(Secret &s) {
//expected-error@+2{{'i' is a private member of 'Secret'}}
//expected-note@-20{{implicitly declared private here}}
return s.i + 3;
}
constexpr int __attribute__((target("sse4.2"))) constexpr_foo(void) {
return 0;
}
constexpr int __attribute__((target("arch=sandybridge"))) constexpr_foo(void);
constexpr int __attribute__((target("arch=ivybridge"))) constexpr_foo(void) {
return 1;
}
constexpr int __attribute__((target("default"))) constexpr_foo(void) {
return 2;
}
void constexpr_test() {
static_assert(foo() == 2, "Should call 'default' in a constexpr context");
}
struct BadOutOfLine {
int __attribute__((target("sse4.2"))) foo(int);
int __attribute__((target("default"))) foo(int);
};
int __attribute__((target("sse4.2"))) BadOutOfLine::foo(int) { return 0; }
int __attribute__((target("default"))) BadOutOfLine::foo(int) { return 1; }
// expected-error@+3 {{out-of-line definition of 'foo' does not match any declaration in 'BadOutOfLine'}}
// expected-note@-3 {{member declaration nearly matches}}
// expected-note@-3 {{member declaration nearly matches}}
int __attribute__((target("arch=atom"))) BadOutOfLine::foo(int) { return 1; }
| 47.252688 | 112 | 0.732734 | [
"object"
] |
11f7555d1c02e7044d90941b2a696999bd0a2a96 | 22,459 | cpp | C++ | EBUCoreProcessor/src/EBUCore_1_4/metadata/base/ebucoreDataFormatBase.cpp | Limecraft/ebu-mxfsdk | d2461c778f7980c4e116a53123c2ba744b1362a0 | [
"Apache-2.0"
] | 20 | 2015-02-24T23:54:23.000Z | 2022-03-29T12:42:32.000Z | EBUCoreProcessor/src/EBUCore_1_4/metadata/base/ebucoreDataFormatBase.cpp | ebu/ebu-mxfsdk | d66e4b05354ec2b80365f1956f14678c6f7f6514 | [
"Apache-2.0"
] | 1 | 2018-10-26T00:44:05.000Z | 2018-10-26T00:44:05.000Z | EBUCoreProcessor/src/EBUCore_1_4/metadata/base/ebucoreDataFormatBase.cpp | ebu/ebu-mxfsdk | d66e4b05354ec2b80365f1956f14678c6f7f6514 | [
"Apache-2.0"
] | 6 | 2015-02-05T09:54:14.000Z | 2022-02-26T20:56:32.000Z | /*
* Copyright 2012-2013 European Broadcasting Union and Limecraft, NV.
*
* 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.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <memory>
#include <libMXF++/MXF.h>
#include <EBUCore_1_4/metadata/EBUCoreDMS++.h>
using namespace std;
using namespace mxfpp;
using namespace EBUSDK::EBUCore::EBUCore_1_4::KLV;
const mxfKey ebucoreDataFormatBase::setKey = MXF_SET_K(ebucoreDataFormat);
ebucoreDataFormatBase::ebucoreDataFormatBase(HeaderMetadata *headerMetadata)
: InterchangeObject(headerMetadata, headerMetadata->createCSet(&setKey))
{
headerMetadata->add(this);
}
ebucoreDataFormatBase::ebucoreDataFormatBase(HeaderMetadata *headerMetadata, ::MXFMetadataSet *cMetadataSet)
: InterchangeObject(headerMetadata, cMetadataSet)
{}
ebucoreDataFormatBase::~ebucoreDataFormatBase()
{}
bool ebucoreDataFormatBase::havedataFormatID() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatID));
}
std::string ebucoreDataFormatBase::getdataFormatID() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatID));
}
bool ebucoreDataFormatBase::havedataFormatVersionID() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatVersionID));
}
std::string ebucoreDataFormatBase::getdataFormatVersionID() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatVersionID));
}
bool ebucoreDataFormatBase::havedataFormatName() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatName));
}
std::string ebucoreDataFormatBase::getdataFormatName() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatName));
}
bool ebucoreDataFormatBase::havedataFormatDefinition() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatDefinition));
}
std::string ebucoreDataFormatBase::getdataFormatDefinition() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatDefinition));
}
bool ebucoreDataFormatBase::havedataTrackId() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackId));
}
std::string ebucoreDataFormatBase::getdataTrackId() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackId));
}
bool ebucoreDataFormatBase::havedataTrackName() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackName));
}
std::string ebucoreDataFormatBase::getdataTrackName() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackName));
}
bool ebucoreDataFormatBase::havedataTrackLanguageCode() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackLanguageCode));
}
std::string ebucoreDataFormatBase::getdataTrackLanguageCode() const
{
return getStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackLanguageCode));
}
bool ebucoreDataFormatBase::havecaptioning() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, captioning));
}
std::vector<ebucoreCaptioning*> ebucoreDataFormatBase::getcaptioning() const
{
vector<ebucoreCaptioning*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, captioning)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreCaptioning*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreCaptioning*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havesubtitling() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, subtitling));
}
std::vector<ebucoreSubtitling*> ebucoreDataFormatBase::getsubtitling() const
{
vector<ebucoreSubtitling*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, subtitling)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreSubtitling*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreSubtitling*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::haveancillaryData() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, ancillaryData));
}
std::vector<ebucoreAncillaryData*> ebucoreDataFormatBase::getancillaryData() const
{
vector<ebucoreAncillaryData*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, ancillaryData)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreAncillaryData*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreAncillaryData*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeString() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeString));
}
std::vector<ebucoreTechnicalAttributeString*> ebucoreDataFormatBase::getdataTechnicalAttributeString() const
{
vector<ebucoreTechnicalAttributeString*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeString)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeString*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeString*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeInt8() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt8));
}
std::vector<ebucoreTechnicalAttributeInt8*> ebucoreDataFormatBase::getdataTechnicalAttributeInt8() const
{
vector<ebucoreTechnicalAttributeInt8*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt8)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeInt8*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeInt8*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeInt16() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt16));
}
std::vector<ebucoreTechnicalAttributeInt16*> ebucoreDataFormatBase::getdataTechnicalAttributeInt16() const
{
vector<ebucoreTechnicalAttributeInt16*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt16)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeInt16*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeInt16*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeInt32() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt32));
}
std::vector<ebucoreTechnicalAttributeInt32*> ebucoreDataFormatBase::getdataTechnicalAttributeInt32() const
{
vector<ebucoreTechnicalAttributeInt32*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt32)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeInt32*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeInt32*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeInt64() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt64));
}
std::vector<ebucoreTechnicalAttributeInt64*> ebucoreDataFormatBase::getdataTechnicalAttributeInt64() const
{
vector<ebucoreTechnicalAttributeInt64*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt64)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeInt64*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeInt64*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeUInt8() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt8));
}
std::vector<ebucoreTechnicalAttributeUInt8*> ebucoreDataFormatBase::getdataTechnicalAttributeUInt8() const
{
vector<ebucoreTechnicalAttributeUInt8*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt8)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeUInt8*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeUInt8*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeUInt16() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt16));
}
std::vector<ebucoreTechnicalAttributeUInt16*> ebucoreDataFormatBase::getdataTechnicalAttributeUInt16() const
{
vector<ebucoreTechnicalAttributeUInt16*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt16)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeUInt16*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeUInt16*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeUInt32() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt32));
}
std::vector<ebucoreTechnicalAttributeUInt32*> ebucoreDataFormatBase::getdataTechnicalAttributeUInt32() const
{
vector<ebucoreTechnicalAttributeUInt32*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt32)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeUInt32*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeUInt32*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeUInt64() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt64));
}
std::vector<ebucoreTechnicalAttributeUInt64*> ebucoreDataFormatBase::getdataTechnicalAttributeUInt64() const
{
vector<ebucoreTechnicalAttributeUInt64*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt64)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeUInt64*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeUInt64*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeFloat() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeFloat));
}
std::vector<ebucoreTechnicalAttributeFloat*> ebucoreDataFormatBase::getdataTechnicalAttributeFloat() const
{
vector<ebucoreTechnicalAttributeFloat*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeFloat)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeFloat*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeFloat*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeRational() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeRational));
}
std::vector<ebucoreTechnicalAttributeRational*> ebucoreDataFormatBase::getdataTechnicalAttributeRational() const
{
vector<ebucoreTechnicalAttributeRational*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeRational)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeRational*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeRational*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeAnyURI() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeAnyURI));
}
std::vector<ebucoreTechnicalAttributeAnyURI*> ebucoreDataFormatBase::getdataTechnicalAttributeAnyURI() const
{
vector<ebucoreTechnicalAttributeAnyURI*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeAnyURI)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeAnyURI*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeAnyURI*>(iter->get()));
}
return result;
}
bool ebucoreDataFormatBase::havedataTechnicalAttributeBoolean() const
{
return haveItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeBoolean));
}
std::vector<ebucoreTechnicalAttributeBoolean*> ebucoreDataFormatBase::getdataTechnicalAttributeBoolean() const
{
vector<ebucoreTechnicalAttributeBoolean*> result;
auto_ptr<ObjectIterator> iter(getStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeBoolean)));
while (iter->next())
{
MXFPP_CHECK(dynamic_cast<ebucoreTechnicalAttributeBoolean*>(iter->get()) != 0);
result.push_back(dynamic_cast<ebucoreTechnicalAttributeBoolean*>(iter->get()));
}
return result;
}
void ebucoreDataFormatBase::setdataFormatID(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatID), value);
}
void ebucoreDataFormatBase::setdataFormatVersionID(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatVersionID), value);
}
void ebucoreDataFormatBase::setdataFormatName(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatName), value);
}
void ebucoreDataFormatBase::setdataFormatDefinition(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataFormatDefinition), value);
}
void ebucoreDataFormatBase::setdataTrackId(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackId), value);
}
void ebucoreDataFormatBase::setdataTrackName(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackName), value);
}
void ebucoreDataFormatBase::setdataTrackLanguageCode(std::string value)
{
setStringItem(&MXF_ITEM_K(ebucoreDataFormat, dataTrackLanguageCode), value);
}
void ebucoreDataFormatBase::setcaptioning(const std::vector<ebucoreCaptioning*>& value)
{
WrapObjectVectorIterator<ebucoreCaptioning> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, captioning), &iter);
}
void ebucoreDataFormatBase::appendcaptioning(ebucoreCaptioning* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, captioning), value);
}
void ebucoreDataFormatBase::setsubtitling(const std::vector<ebucoreSubtitling*>& value)
{
WrapObjectVectorIterator<ebucoreSubtitling> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, subtitling), &iter);
}
void ebucoreDataFormatBase::appendsubtitling(ebucoreSubtitling* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, subtitling), value);
}
void ebucoreDataFormatBase::setancillaryData(const std::vector<ebucoreAncillaryData*>& value)
{
WrapObjectVectorIterator<ebucoreAncillaryData> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, ancillaryData), &iter);
}
void ebucoreDataFormatBase::appendancillaryData(ebucoreAncillaryData* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, ancillaryData), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeString(const std::vector<ebucoreTechnicalAttributeString*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeString> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeString), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeString(ebucoreTechnicalAttributeString* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeString), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeInt8(const std::vector<ebucoreTechnicalAttributeInt8*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeInt8> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt8), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeInt8(ebucoreTechnicalAttributeInt8* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt8), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeInt16(const std::vector<ebucoreTechnicalAttributeInt16*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeInt16> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt16), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeInt16(ebucoreTechnicalAttributeInt16* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt16), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeInt32(const std::vector<ebucoreTechnicalAttributeInt32*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeInt32> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt32), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeInt32(ebucoreTechnicalAttributeInt32* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt32), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeInt64(const std::vector<ebucoreTechnicalAttributeInt64*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeInt64> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt64), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeInt64(ebucoreTechnicalAttributeInt64* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeInt64), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeUInt8(const std::vector<ebucoreTechnicalAttributeUInt8*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeUInt8> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt8), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeUInt8(ebucoreTechnicalAttributeUInt8* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt8), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeUInt16(const std::vector<ebucoreTechnicalAttributeUInt16*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeUInt16> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt16), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeUInt16(ebucoreTechnicalAttributeUInt16* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt16), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeUInt32(const std::vector<ebucoreTechnicalAttributeUInt32*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeUInt32> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt32), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeUInt32(ebucoreTechnicalAttributeUInt32* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt32), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeUInt64(const std::vector<ebucoreTechnicalAttributeUInt64*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeUInt64> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt64), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeUInt64(ebucoreTechnicalAttributeUInt64* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeUInt64), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeFloat(const std::vector<ebucoreTechnicalAttributeFloat*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeFloat> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeFloat), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeFloat(ebucoreTechnicalAttributeFloat* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeFloat), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeRational(const std::vector<ebucoreTechnicalAttributeRational*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeRational> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeRational), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeRational(ebucoreTechnicalAttributeRational* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeRational), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeAnyURI(const std::vector<ebucoreTechnicalAttributeAnyURI*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeAnyURI> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeAnyURI), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeAnyURI(ebucoreTechnicalAttributeAnyURI* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeAnyURI), value);
}
void ebucoreDataFormatBase::setdataTechnicalAttributeBoolean(const std::vector<ebucoreTechnicalAttributeBoolean*>& value)
{
WrapObjectVectorIterator<ebucoreTechnicalAttributeBoolean> iter(value);
setStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeBoolean), &iter);
}
void ebucoreDataFormatBase::appenddataTechnicalAttributeBoolean(ebucoreTechnicalAttributeBoolean* value)
{
appendStrongRefArrayItem(&MXF_ITEM_K(ebucoreDataFormat, dataTechnicalAttributeBoolean), value);
}
| 37.245439 | 123 | 0.799457 | [
"vector"
] |
11f9014fc1052909f5d46a7ebb916450a769890d | 10,258 | cpp | C++ | OpenSees/SRC/analysis/integrator/Houbolt.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | null | null | null | OpenSees/SRC/analysis/integrator/Houbolt.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | null | null | null | OpenSees/SRC/analysis/integrator/Houbolt.cpp | kuanshi/ductile-fracture | ccb350564df54f5c5ec3a079100effe261b46650 | [
"MIT"
] | 1 | 2020-08-06T21:12:16.000Z | 2020-08-06T21:12:16.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.1 $
// $Date: 2009-03-20 18:36:30 $
// $Source: /usr/local/cvs/OpenSees/SRC/analysis/integrator/Houbolt.cpp,v $
// Written : krm
// Created : 11/2012
//
// Description: This file contains the implementation of the Houbolt class.
// See comments in the header file for description of algorithm.
//
// What: "@(#) Houbolt.C, revA"
#include <Houbolt.h>
#include <FE_Element.h>
#include <LinearSOE.h>
#include <AnalysisModel.h>
#include <Vector.h>
#include <DOF_Group.h>
#include <DOF_GrpIter.h>
#include <AnalysisModel.h>
#include <Channel.h>
#include <FEM_ObjectBroker.h>
void* OPS_Houbolt()
{
return new Houbolt();
}
Houbolt::Houbolt()
: TransientIntegrator(INTEGRATOR_TAGS_Houbolt),
step(0), dt(0.0),
c1(0.0), c2(0.0), c3(0.0),
Utm2(0), Utm1(0),
Ut(0), Utdot(0), Utdotdot(0),
U(0), Udot(0), Udotdot(0)
{
}
Houbolt::~Houbolt()
{
// clean up the memory created
if (Utm2 != 0)
delete Utm2;
if (Utm1 != 0)
delete Utm1;
if (Ut != 0)
delete Ut;
if (Utdot != 0)
delete Utdot;
if (Utdotdot != 0)
delete Utdotdot;
if (U != 0)
delete U;
if (Udot != 0)
delete Udot;
if (Udotdot != 0)
delete Udotdot;
}
int Houbolt::newStep(double deltaT)
{
// check the vectors have been created
if (U == 0) {
opserr << "Houbolt::newStep() - domainChange() failed or hasn't been called\n";
return -3;
}
// mark step as bootstrap or not
if ( deltaT != dt )
step = 0;
else
step++;
// get a pointer to the AnalysisModel
AnalysisModel *theModel = this->getAnalysisModel();
// set response at t to be that at t+deltaT of previous step
dt = deltaT;
// save storage quantites before updating
(*Utm2) = *Utm1;
(*Utm1) = *Ut;
(*Ut) = *U;
(*Utdot) = *Udot;
(*Utdotdot) = *Udotdot;
// set the constants
if (step < 2) { // trapezoidal
c1 = 1.0;
c2 = 2.0/deltaT;
c3 = 4.0/(deltaT*deltaT);
(*Udot) *= -1.0;
double a3 = -4.0/deltaT;
double a4 = -1;
Udotdot->addVector(a4, *Utdot, a3);
} else { // Houbolt
c1 = 1.0;
c2 = 11.0/(6.0*deltaT);
c3 = 2.0/(deltaT*deltaT);
(*Udot) = *Utm2;
Udot->addVector(-1.0/(3.0*deltaT), *Utm1, 3.0/(2.0*deltaT));
Udot->addVector(1.0, *Ut, -7.0/(6.0*deltaT));
(*Udotdot) = *Utm2;
Udotdot->addVector(-1.0/(deltaT*deltaT), *Utm1, 4.0/(deltaT*deltaT));
Udotdot->addVector(1.0, *Ut, -3.0/(deltaT*deltaT));
}
// set the trial response quantities
theModel->setVel(*Udot);
theModel->setAccel(*Udotdot);
// increment the time to t+deltaT and apply the load
double time = theModel->getCurrentDomainTime();
time += deltaT;
if (theModel->updateDomain(time, deltaT) < 0) {
opserr << "Houbolt::newStep() - failed to update the domain\n";
return -4;
}
return 0;
}
int Houbolt::revertToLastStep()
{
// set response at t+deltaT to be that at t .. for next newStep
if (U != 0) {
(*U) = *Ut;
(*Udot) = *Utdot;
(*Udotdot) = *Utdotdot;
// this is crude, should be based on previous steps taken
step = 0;
}
return 0;
}
int Houbolt::formEleTangent(FE_Element *theEle)
{
theEle->zeroTangent();
if (statusFlag == CURRENT_TANGENT) {
theEle->addKtToTang(c1);
theEle->addCtoTang(c2);
theEle->addMtoTang(c3);
} else if (statusFlag == INITIAL_TANGENT) {
theEle->addKiToTang(c1);
theEle->addCtoTang(c2);
theEle->addMtoTang(c3);
} else if (statusFlag == HALL_TANGENT) {
theEle->addKtToTang(c1*cFactor);
theEle->addKiToTang(c1*iFactor);
theEle->addCtoTang(c2);
theEle->addMtoTang(c3);
} else {
opserr << "Houbold::formEleTangent - unknown FLAG\n";
}
return 0;
}
int Houbolt::formNodTangent(DOF_Group *theDof)
{
theDof->zeroTangent();
theDof->addCtoTang(c2);
theDof->addMtoTang(c3);
return 0;
}
int Houbolt::domainChanged()
{
AnalysisModel *myModel = this->getAnalysisModel();
LinearSOE *theLinSOE = this->getLinearSOE();
const Vector &x = theLinSOE->getX();
int size = x.Size();
// create the new Vector objects
if (Ut == 0 || Ut->Size() != size) {
// delete the old
if (Utm2 != 0)
delete Utm2;
if (Utm1 != 0)
delete Utm1;
if (Ut != 0)
delete Ut;
if (Utdot != 0)
delete Utdot;
if (Utdotdot != 0)
delete Utdotdot;
if (U != 0)
delete U;
if (Udot != 0)
delete Udot;
if (Udotdot != 0)
delete Udotdot;
// create the new
Utm2 = new Vector(size);
Utm1 = new Vector(size);
Ut = new Vector(size);
Utdot = new Vector(size);
Utdotdot = new Vector(size);
U = new Vector(size);
Udot = new Vector(size);
Udotdot = new Vector(size);
// check we obtained the new
if (Utm2 == 0 || Utm2->Size() != size ||
Utm1 == 0 || Utm1->Size() != size ||
Ut == 0 || Ut->Size() != size ||
Utdot == 0 || Utdot->Size() != size ||
Utdotdot == 0 || Utdotdot->Size() != size ||
U == 0 || U->Size() != size ||
Udot == 0 || Udot->Size() != size ||
Udotdot == 0 || Udotdot->Size() != size) {
// delete the old
if (Utm2 != 0)
delete Utm2;
if (Utm1 != 0)
delete Utm1;
if (Ut != 0)
delete Ut;
if (Utdot != 0)
delete Utdot;
if (Utdotdot != 0)
delete Utdotdot;
if (U != 0)
delete U;
if (Udot != 0)
delete Udot;
if (Udotdot != 0)
delete Udotdot;
Utm2 = 0; Utm1 = 0;
Ut = 0; Utdot = 0; Utdotdot = 0;
U = 0; Udot = 0; Udotdot = 0;
return -1;
}
}
// now go through and populate U, Udot and Udotdot by iterating through
// the DOF_Groups and getting the last committed velocity and accel
DOF_GrpIter &theDOFs = myModel->getDOFs();
DOF_Group *dofPtr;
while ((dofPtr = theDOFs()) != 0) {
const ID &id = dofPtr->getID();
int idSize = id.Size();
int i;
const Vector &disp = dofPtr->getCommittedDisp();
for (i=0; i < idSize; i++) {
int loc = id(i);
if (loc >= 0) {
(*U)(loc) = disp(i);
}
}
const Vector &vel = dofPtr->getCommittedVel();
for (i=0; i < idSize; i++) {
int loc = id(i);
if (loc >= 0) {
(*Udot)(loc) = vel(i);
}
}
const Vector &accel = dofPtr->getCommittedAccel();
for (i=0; i < idSize; i++) {
int loc = id(i);
if (loc >= 0) {
(*Udotdot)(loc) = accel(i);
}
}
}
return 0;
}
int Houbolt::update(const Vector &deltaU)
{
AnalysisModel *theModel = this->getAnalysisModel();
if (theModel == 0) {
opserr << "WARNING Houbolt::update() - no AnalysisModel set\n";
return -1;
}
// check domainChanged() has been called, i.e. Ut will not be zero
if (Ut == 0) {
opserr << "WARNING Houbolt::update() - domainChange() failed or not called\n";
return -2;
}
// check deltaU is of correct size
if (deltaU.Size() != U->Size()) {
opserr << "WARNING Houbolt::update() - Vectors of incompatible size ";
opserr << " expecting " << U->Size() << " obtained " << deltaU.Size() << endln;
return -3;
}
// determine the response at t+deltaT
(*U) += deltaU;
Udot->addVector(1.0, deltaU, c2);
Udotdot->addVector(1.0, deltaU, c3);
// update the response at the DOFs
theModel->setResponse(*U,*Udot,*Udotdot);
if (theModel->updateDomain() < 0) {
opserr << "Houbolt::update() - failed to update the domain\n";
return -4;
}
return 0;
}
int Houbolt::sendSelf(int cTag, Channel &theChannel)
{
// nothing to send
return 0;
}
int Houbolt::recvSelf(int cTag, Channel &theChannel, FEM_ObjectBroker &theBroker)
{
// nothing to receive
return 0;
}
void Houbolt::Print(OPS_Stream &s, int flag)
{
AnalysisModel *theModel = this->getAnalysisModel();
if (theModel != 0) {
double currentTime = theModel->getCurrentDomainTime();
s << "\t Houbolt - currentTime: " << currentTime;
} else
s << "\t Houbolt - no associated AnalysisModel\n";
}
| 26.923885 | 87 | 0.49688 | [
"vector"
] |
11fb1cd3794376102b56a0e8d2fdb0149b1a244a | 7,135 | cpp | C++ | classfunction.cpp | pankajsingh016/PayRoll-Management-System | 4b8608885299468dfc40a33a2e6abd6a74bf1c3d | [
"MIT"
] | null | null | null | classfunction.cpp | pankajsingh016/PayRoll-Management-System | 4b8608885299468dfc40a33a2e6abd6a74bf1c3d | [
"MIT"
] | null | null | null | classfunction.cpp | pankajsingh016/PayRoll-Management-System | 4b8608885299468dfc40a33a2e6abd6a74bf1c3d | [
"MIT"
] | null | null | null | #include "class.h"
void wrtie_change(int col,string epoy,string change);
void show(string s)//ff
{
for(int i=0;s[i]!='\0';i++)
{
if(s[i]==',')
{
cout<<"\t\t";
}
else
cout<<s[i];
}
cout<<endl;
}
bool verify(string i,string m) //ff
{
ifstream fin;
fin.open(m,ios::in);
while(!fin.eof())
{
vector <char> c;
string s;
getline(fin,s);
for(int i=0;s[i]!=',';i++)
{
c.push_back(s[i]);
}
std::string sn(c.begin(),c.end());
if(sn == i)
{
return true;
}
s.clear();
c.clear();
sn.clear();
}
return false;
}
void organization::getData() //ocf
{
ide:
cout<<"Enter the ID of the Employeer -:";;//1d
fflush(stdin);
cin>>id;
bool cv = verify(id,"data//employeer.csv");
if(cv)
{
cout<<":: This ID is previously registerd enter a new ID ::"<<endl;
id.clear();
goto ide;
}
fflush(stdin);//id match verify()
cout<<"Enter Name -:"; getline(cin,name); //2d
fflush(stdin);
pass:
cout<<"Enter Password-:"; getline(cin,password); //3d
fflush(stdin);
cout<<"Confirm Password -:"; getline(cin,conpass);//4d
if(conpass == password)
cout<<"Password Set"<<endl;
else{
cout<<"Password doesn't match with the currnet entered password"<<endl;
password.clear();
conpass.clear();
goto pass;
}
bool check = organization::writedata(); //ocf
if(check)
{
cout<<"The Data has Stored Successfully -:"<<endl;
}
else
{
cout<<"File not opened"<<endl;
}
}
bool organization::writedata() //ocf
{
fstream fout;
fout.open("data//employeer.csv",ios::out|ios::app); //writing to file
if(!fout)
{
return false;
}
fout<<endl;
fout<<id<<","<<name<<","<<password;
return true;
}
void organization::showdata(string p) //ocf
{
fstream fin;
fin.open(p,ios::in);
if(!fin)
{
cout<<"File opening fail"<<endl;
return;
}
while(!fin.eof())
{
string s;
getline(fin,s);
show(s);
// for(int i=0;s[i]!='\0';i++)
// {
// if(s[i]==',')
// {
// s[i] = '\t';
// }
// }
// cout<<s<<endl;
}
}
void Employee::setemployeer(string s)
{
empno = s;
}
void Employee::get_Data()
{
eid:
fflush(stdin);
id.clear();
cout<<"Enter the ID of the Employee -:";//1d
fflush(stdin);
cin>>id;
fflush(stdin);//id match verify()
if(verify(id,"data//employee.csv"))
{
cout<<"\n :: Enter a unique ID this ID is taken earlier ::"<<endl;
goto eid;
}
cout<<"Enter Name -:"; getline(cin,name); //2d
fflush(stdin);
epass:
cout<<"Enter Password-:"; getline(cin,password); //3d
fflush(stdin);
cout<<"Confirm Password -:"; getline(cin,conpass);//4d
if(conpass == password)
cout<<"Password Set"<<endl;
else{
cout<<"\n Password Don't Match with the Confirm Password"<<endl;
password.clear();
conpass.clear();
goto epass;
}
cout<<"Enter Total Days of work -:"; cin>>ndays;
cout<<"Enter Salary Per Day -:"; cin>>spd;
bool check = Employee::write_Data(); //ocf
if(check)
{
cout<<"The Data has Stored Successfully -:"<<endl;
}
else
{
cout<<"File not opened"<<endl;
}
}
bool Employee::write_Data()
{
fstream fout;
fout.open("data//employee.csv",ios::out|ios::app); //writing to file
if(!fout)
{
return false;
}
fout<<endl;
fout<<id<<","<<empno<<","<<name<<","<<password<<","<<ndays<<","<<spd<<","<<ndays*spd;
return true;
}
void choosecolor()
{
system("cls");
cout<<"\n\n";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),4);
line176(97,176);
cout<<"\t\t\t"<<char(176); cout<<"\t\t\t\t\t\t\t\t\t\t\t\t"<<char(176)<<endl;
cout<<"\t\t\t"<<char(176);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),10);
cout<<"\t\t\t CHOOSE THE DETAIL YOU WANT TO UPDATE ";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),4);
cout<<"\t\t\t\t"<<char(176);
cout<<endl;
cout<<"\t\t\t"<<char(176); cout<<"\t\t\t\t\t\t\t\t\t\t\t\t"<<char(176)<<endl;
line176(97,176);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),10);
cout<<"\n\n";
}
//-----------------------------------------------Update data
void changing_menu()//ff
{
system("cls");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),128);
cout<<"\n\n";
choosecolor();
cout<<"\n";
cout<<"\t\t\t\t1.NUMBER OF DAYS WORKED"<<endl;
cout<<"\t\t\t\t2.SALARY PER DAY"<<endl;
cout<<"\t\t\t\t3.PAIED THE SALARY"<<endl;
}
int get_line(string epoy)//ff
{
fstream fio;
fio.open("data//employee.csv",ios::in);
int refline=0;
while(!fio.eof())
{
string s;
getline(fio,s);
vector <char> c;
for(int i=0;s[i]!=',';i++)
{
c.push_back(s[i]);
}
std::string p(c.begin(),c.end());
refline++;
if(p==epoy)
{
return refline;
}
p.clear();
c.clear();
}
return 0;
}
void write_change(string epoy,string change,int col)
{
fstream fio;
fio.open("data//employee.csv",ios::in|ios::out);
char ch;
int line=0;
int count=0;
int m=1;
int pos;
int offset = -4;
int refline=0;
refline = get_line(epoy);
refline--;
fio.seekg(0,ios::beg);
fio.seekp(0,ios::beg);
while(!fio.eof())
{
ch = fio.get();
if(ch=='\n')
{
count=0;
line++;
}
if(ch==',')
count++;
if((col==count) && (line==refline))
{
if(m)
{
pos= fio.tellg();
offset = line+offset;
if(offset>=0)
offset=0;
fio.seekg(offset,ios::cur);
fio<<change;
cout<<"\n\n"<<pos<<endl;
m=0;
}
}
}
}
void Employee::update_data()
{
string epoy;
cout<<"Enter The Employee ID of the Employeer -:";
cin>>epoy;
string change;
changing_menu();
int col;
int a;
cin>>a;
cout<<"Enter The Change you want to put in -:"<<endl;
fflush(stdin);
switch(a)
{
case 1:
{
getline(cin,change);
col = 4;
break;
}
case 2:
{
getline(cin,change);
col = 5;
break;
}
case 3:
{
getline(cin,change);
col = 6;
break;
}
default:
exit(0);
}
write_change(epoy,change,col);
}
//-----------------------------------------------------------Update data end here()
void Employee::show_Data(string id,string f)
{
fstream fin;
fin.open(f,ios::in);
while(!fin.eof())
{
int count =0;
vector <char> c;
string s;
getline(fin,s);
fflush(stdin);
for(int i=0;count<2;i++)
{
if(s[i]==',')
count++;
if(count==1 && s[i]!=',')
{
c.push_back(s[i]);
}
}
std::string m(c.begin(),c.end());
c.clear();
if(m==id)
{
show(s);
}
s.clear();
m.clear();
}
system("pause");
}
void Employee::remove(string rid)// it will not delete the lastest employee
{
fstream fin;
fin.open("data//employee.csv",ios::in|ios::out);
while(!fin.eof())
{
int count =0;
vector <char> c;
string s;
getline(fin,s);
fflush(stdin);
for(int i=0;count<1;i++)
{
if(s[i]==',')
count++;
if(count==0 && s[i]!=',')
{
c.push_back(s[i]);
}
}
std::string m(c.begin(),c.end());
c.clear();
if(rid==m)
{
long back = s.length();
fin.seekp(-back,ios::cur);
for(int i=0; (i<(back-5)) && (s[i]!='\0') ;i++)
{
if(s[i]==',')
fin<<',';
else
fin<<'-';
}
fin.seekp(ios::end);
return;
}
s.clear();
m.clear();
}
system("pause");
}
| 14.958071 | 86 | 0.559636 | [
"vector",
"3d"
] |
11fb3e8241e2126e205c72aec0acf22572680386 | 867 | cc | C++ | src/ops/concat.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | src/ops/concat.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | src/ops/concat.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | #include "ctranslate2/ops/concat.h"
#include "device_dispatch.h"
#include "type_dispatch.h"
namespace ctranslate2 {
namespace ops {
Concat::Concat(int axis)
: _axis(axis) {
}
void Concat::operator()(const std::vector<StorageView*>& inputs,
StorageView& output) const {
PROFILE("Concat");
const dim_t rank = inputs.front()->rank();
const dim_t axis = _axis < 0 ? rank + _axis : _axis;
dim_t concat_dims = 0;
for (const auto& x : inputs) {
assert(x->rank() == rank);
concat_dims += x->dim(axis);
}
Shape output_shape(inputs.front()->shape());
output_shape[axis] = concat_dims;
output.resize(output_shape);
DEVICE_DISPATCH(output.device(),
TYPE_DISPATCH(output.dtype(), (compute<D, T>(inputs, output))));
}
}
}
| 25.5 | 86 | 0.582468 | [
"shape",
"vector"
] |
11fd292f4611b273e6944799dc881c5bbca2f9e8 | 1,412 | cpp | C++ | vnext/Desktop.UnitTests/StringConversionTest_Desktop.cpp | tahmidbintaslim/react-native-windows | ff72d1b4acc9cc82771b5b58a625c987c93d1f8f | [
"MIT"
] | 2 | 2019-02-08T18:11:24.000Z | 2022-01-04T17:46:46.000Z | vnext/Desktop.UnitTests/StringConversionTest_Desktop.cpp | tahmidbintaslim/react-native-windows | ff72d1b4acc9cc82771b5b58a625c987c93d1f8f | [
"MIT"
] | 2 | 2019-04-03T04:44:06.000Z | 2019-04-03T04:46:36.000Z | vnext/Desktop.UnitTests/StringConversionTest_Desktop.cpp | tahmidbintaslim/react-native-windows | ff72d1b4acc9cc82771b5b58a625c987c93d1f8f | [
"MIT"
] | 1 | 2022-03-22T20:00:29.000Z | 2022-03-22T20:00:29.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <CppUnitTest.h>
#include <string>
#include <vector>
#include "../Chakra/Utf8DebugExtensions.h"
#include "UnicodeTestStrings.h"
using namespace facebook::react;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace Microsoft::React::Test {
TEST_CLASS (StringConversionTest_Desktop) {
private:
JsRuntimeHandle runtime;
TEST_METHOD_INITIALIZE(Setup) {
JsContextRef context;
unsigned currentSourceContext = 0;
// Create a runtime.
JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime);
// Create an execution context.
JsCreateContext(runtime, &context);
// Now set the current execution context.
JsSetCurrentContext(context);
}
TEST_METHOD_CLEANUP(TearDown) {
// Dispose runtime
JsSetCurrentContext(JS_INVALID_REFERENCE);
JsDisposeRuntime(runtime);
}
TEST_METHOD(StringConversionTest_WIN32Test) {
JsValueRef value;
string str;
for (size_t i = 0; i < g_utf8TestStrings.size(); i++) {
JsPointerToStringUtf8(g_utf8TestStrings[i].c_str(), g_utf8TestStrings[i].length(), &value);
JsStringToStdStringUtf8(value, str);
Assert::IsTrue(str.compare(g_utf8TestStrings[i]) == 0);
}
}
};
} // namespace Microsoft::React::Test
| 27.686275 | 98 | 0.704674 | [
"vector"
] |
11fed72f92c37b4fe0df69295b75196a177765e1 | 6,819 | hpp | C++ | libraries/include/msgpack/v1/adaptor/ext.hpp | red-panda-productions/SDALib | ff5505b3454374792589529de1c45308c4d119e7 | [
"MIT"
] | null | null | null | libraries/include/msgpack/v1/adaptor/ext.hpp | red-panda-productions/SDALib | ff5505b3454374792589529de1c45308c4d119e7 | [
"MIT"
] | null | null | null | libraries/include/msgpack/v1/adaptor/ext.hpp | red-panda-productions/SDALib | ff5505b3454374792589529de1c45308c4d119e7 | [
"MIT"
] | null | null | null | //
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2015-2016 KONDO Takatoshi
//
// 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 MSGPACK_V1_TYPE_EXT_HPP
#define MSGPACK_V1_TYPE_EXT_HPP
#include "msgpack/v1/adaptor/ext_decl.hpp"
#include "msgpack/adaptor/check_container_size.hpp"
#include <cstring>
#include <string>
namespace msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond
namespace type {
class ext {
public:
ext() : m_data(1, 0) {}
ext(int8_t t, const char* p, uint32_t s) {
msgpack::detail::check_container_size_for_ext<sizeof(std::size_t)>(s);
m_data.reserve(static_cast<std::size_t>(s) + 1);
m_data.push_back(static_cast<char>(t));
m_data.insert(m_data.end(), p, p + s);
}
ext(int8_t t, uint32_t s) {
msgpack::detail::check_container_size_for_ext<sizeof(std::size_t)>(s);
m_data.resize(static_cast<std::size_t>(s) + 1);
m_data[0] = static_cast<char>(t);
}
explicit ext(ext_ref const&);
int8_t type() const {
return static_cast<int8_t>(m_data[0]);
}
const char* data() const {
return &m_data[0] + 1;
}
char* data() {
return &m_data[0] + 1;
}
uint32_t size() const {
return static_cast<uint32_t>(m_data.size()) - 1;
}
bool operator== (const ext& x) const {
return m_data == x.m_data;
}
bool operator!= (const ext& x) const {
return !(*this == x);
}
bool operator< (const ext& x) const {
return m_data < x.m_data;
}
bool operator> (const ext& x) const {
return m_data > x.m_data;
}
private:
std::vector<char> m_data;
friend class ext_ref;
};
} // namespace type
namespace adaptor {
template <>
struct convert<msgpack::type::ext> {
msgpack::object const& operator()(msgpack::object const& o, msgpack::type::ext& v) const {
if(o.type != msgpack::type::EXT) {
throw msgpack::type_error();
}
v = msgpack::type::ext(o.via.ext.type(), o.via.ext.data(), o.via.ext.size);
return o;
}
};
template <>
struct pack<msgpack::type::ext> {
template <typename Stream>
msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const msgpack::type::ext& v) const {
// size limit has already been checked at ext's constructor
uint32_t size = v.size();
o.pack_ext(size, v.type());
o.pack_ext_body(v.data(), size);
return o;
}
};
template <>
struct object_with_zone<msgpack::type::ext> {
void operator()(msgpack::object::with_zone& o, const msgpack::type::ext& v) const {
// size limit has already been checked at ext's constructor
uint32_t size = v.size();
o.type = msgpack::type::EXT;
char* ptr = static_cast<char*>(o.zone.allocate_align(size + 1, MSGPACK_ZONE_ALIGNOF(char)));
o.via.ext.ptr = ptr;
o.via.ext.size = size;
ptr[0] = static_cast<char>(v.type());
std::memcpy(ptr + 1, v.data(), size);
}
};
} // namespace adaptor
namespace type {
class ext_ref {
public:
// ext_ref should be default constructible to support 'convert'.
// A default constructed ext_ref object::m_ptr doesn't have the buffer to point to.
// In order to avoid nullptr checking branches, m_ptr points to m_size.
// So type() returns unspecified but valid value. It might be a zero because m_size
// is initialized as zero, but shouldn't assume that.
ext_ref() : m_ptr(static_cast<char*>(static_cast<void*>(&m_size))), m_size(0) {}
ext_ref(const char* p, uint32_t s) :
m_ptr(s == 0 ? static_cast<char*>(static_cast<void*>(&m_size)) : p),
m_size(s == 0 ? 0 : s - 1) {
msgpack::detail::check_container_size_for_ext<sizeof(std::size_t)>(s);
}
// size limit has already been checked at ext's constructor
ext_ref(ext const& x) : m_ptr(&x.m_data[0]), m_size(x.size()) {}
const char* data() const {
return m_ptr + 1;
}
uint32_t size() const {
return m_size;
}
int8_t type() const {
return static_cast<int8_t>(m_ptr[0]);
}
std::string str() const {
return std::string(m_ptr + 1, m_size);
}
bool operator== (const ext_ref& x) const {
return m_size == x.m_size && std::memcmp(m_ptr, x.m_ptr, m_size) == 0;
}
bool operator!= (const ext_ref& x) const {
return !(*this == x);
}
bool operator< (const ext_ref& x) const {
if (m_size < x.m_size) return true;
if (m_size > x.m_size) return false;
return std::memcmp(m_ptr, x.m_ptr, m_size) < 0;
}
bool operator> (const ext_ref& x) const {
if (m_size > x.m_size) return true;
if (m_size < x.m_size) return false;
return std::memcmp(m_ptr, x.m_ptr, m_size) > 0;
}
private:
const char* m_ptr;
uint32_t m_size;
friend struct adaptor::object<msgpack::type::ext_ref>;
};
inline ext::ext(ext_ref const& x) {
// size limit has already been checked at ext_ref's constructor
m_data.reserve(x.size() + 1);
m_data.push_back(static_cast<char>(x.type()));
m_data.insert(m_data.end(), x.data(), x.data() + x.size());
}
} // namespace type
namespace adaptor {
template <>
struct convert<msgpack::type::ext_ref> {
msgpack::object const& operator()(msgpack::object const& o, msgpack::type::ext_ref& v) const {
if(o.type != msgpack::type::EXT) { throw msgpack::type_error(); }
v = msgpack::type::ext_ref(o.via.ext.ptr, o.via.ext.size + 1);
return o;
}
};
template <>
struct pack<msgpack::type::ext_ref> {
template <typename Stream>
msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const msgpack::type::ext_ref& v) const {
// size limit has already been checked at ext_ref's constructor
uint32_t size = v.size();
o.pack_ext(size, v.type());
o.pack_ext_body(v.data(), size);
return o;
}
};
template <>
struct object<msgpack::type::ext_ref> {
void operator()(msgpack::object& o, const msgpack::type::ext_ref& v) const {
// size limit has already been checked at ext_ref's constructor
uint32_t size = v.size();
o.type = msgpack::type::EXT;
o.via.ext.ptr = v.m_ptr;
o.via.ext.size = size;
}
};
template <>
struct object_with_zone<msgpack::type::ext_ref> {
void operator()(msgpack::object::with_zone& o, const msgpack::type::ext_ref& v) const {
static_cast<msgpack::object&>(o) << v;
}
};
} // namespace adaptor
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond
} // namespace msgpack
#endif // MSGPACK_V1_TYPE_EXT_HPP
| 28.772152 | 108 | 0.617539 | [
"object",
"vector"
] |
f50030af5ccf49287e023c248f3ef30769402192 | 43,039 | cpp | C++ | sakura_core/view/CEditView_Paint.cpp | k-takata/sakura | c4cb5683f62f4ac27e6dd7d3d0d266790b352977 | [
"Zlib"
] | null | null | null | sakura_core/view/CEditView_Paint.cpp | k-takata/sakura | c4cb5683f62f4ac27e6dd7d3d0d266790b352977 | [
"Zlib"
] | null | null | null | sakura_core/view/CEditView_Paint.cpp | k-takata/sakura | c4cb5683f62f4ac27e6dd7d3d0d266790b352977 | [
"Zlib"
] | null | null | null | /*! @file */
/*
Copyright (C) 2008, kobake
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "StdAfx.h"
#include <vector>
#include <limits.h>
#pragma comment(lib, "Msimg32.lib")
#include "view/CEditView_Paint.h"
#include "view/CEditView.h"
#include "view/CViewFont.h"
#include "view/CRuler.h"
#include "view/colors/CColorStrategy.h"
#include "view/colors/CColor_Found.h"
#include "view/figures/CFigureManager.h"
#include "types/CTypeSupport.h"
#include "doc/CEditDoc.h"
#include "doc/layout/CLayout.h"
#include "window/CEditWnd.h"
#include "parse/CWordParse.h"
#include "util/string_ex2.h"
#ifdef USE_SSE2
#ifdef __MINGW32__
#include <x86intrin.h>
#else
#include <intrin.h>
#endif
#endif
void _DispWrap(CGraphics& gr, DispPos* pDispPos, const CEditView* pcView, CLayoutYInt nLineNum);
/*
PAINT_LINENUMBER = (1<<0), //!< 行番号
PAINT_RULER = (1<<1), //!< ルーラー
PAINT_BODY = (1<<2), //!< 本文
*/
void CEditView_Paint::Call_OnPaint(
int nPaintFlag, //!< 描画する領域を選択する
bool bUseMemoryDC //!< メモリDCを使用する
)
{
CEditView* pView = GetEditView();
//各要素
CMyRect rcLineNumber(0,pView->GetTextArea().GetAreaTop(),pView->GetTextArea().GetAreaLeft(),pView->GetTextArea().GetAreaBottom());
CMyRect rcRuler(pView->GetTextArea().GetAreaLeft(),0,pView->GetTextArea().GetAreaRight(),pView->GetTextArea().GetAreaTop());
CMyRect rcBody(pView->GetTextArea().GetAreaLeft(),pView->GetTextArea().GetAreaTop(),pView->GetTextArea().GetAreaRight(),pView->GetTextArea().GetAreaBottom());
//領域を作成 -> rc
std::vector<CMyRect> rcs;
if(nPaintFlag & PAINT_LINENUMBER)rcs.push_back(rcLineNumber);
if(nPaintFlag & PAINT_RULER)rcs.push_back(rcRuler);
if(nPaintFlag & PAINT_BODY)rcs.push_back(rcBody);
if(rcs.size()==0)return;
CMyRect rc=rcs[0];
int nSize = (int)rcs.size();
for(int i=1;i<nSize;i++)
rc=MergeRect(rc,rcs[i]);
//描画
PAINTSTRUCT ps;
ps.rcPaint = rc;
HDC hdc = pView->GetDC();
pView->OnPaint( hdc, &ps, bUseMemoryDC );
pView->ReleaseDC( hdc );
}
/* フォーカス移動時の再描画
@date 2001/06/21 asa-o 「スクロールバーの状態を更新する」「カーソル移動」削除
*/
void CEditView::RedrawAll()
{
if( NULL == GetHwnd() ){
return;
}
if( GetDrawSwitch() ){
// ウィンドウ全体を再描画
PAINTSTRUCT ps;
HDC hdc = ::GetDC( GetHwnd() );
::GetClientRect( GetHwnd(), &ps.rcPaint );
OnPaint( hdc, &ps, FALSE );
::ReleaseDC( GetHwnd(), hdc );
}
// キャレットの表示
GetCaret().ShowEditCaret();
// キャレットの行桁位置を表示する
GetCaret().ShowCaretPosInfo();
// 親ウィンドウのタイトルを更新
m_pcEditWnd->UpdateCaption();
// Jul. 9, 2005 genta 選択範囲の情報をステータスバーへ表示
GetSelectionInfo().PrintSelectionInfoMsg();
// スクロールバーの状態を更新する
AdjustScrollBars();
}
// 2001/06/21 Start by asa-o 再描画
void CEditView::Redraw()
{
if( NULL == GetHwnd() ){
return;
}
if( !GetDrawSwitch() ){
return;
}
HDC hdc;
PAINTSTRUCT ps;
hdc = ::GetDC( GetHwnd() );
::GetClientRect( GetHwnd(), &ps.rcPaint );
OnPaint( hdc, &ps, FALSE );
::ReleaseDC( GetHwnd(), hdc );
}
// 2001/06/21 End
void CEditView::RedrawLines( CLayoutYInt top, CLayoutYInt bottom )
{
if( NULL == GetHwnd() ){
return;
}
if( !GetDrawSwitch() ){
return;
}
if( bottom < GetTextArea().GetViewTopLine() ){
return;
}
if( GetTextArea().GetBottomLine() <= top ){
return;
}
HDC hdc;
PAINTSTRUCT ps;
hdc = GetDC();
ps.rcPaint.left = 0;
ps.rcPaint.right = GetTextArea().GetAreaRight();
ps.rcPaint.top = GetTextArea().GenerateYPx(top);
ps.rcPaint.bottom = GetTextArea().GenerateYPx(bottom);
OnPaint( hdc, &ps, FALSE );
ReleaseDC( hdc );
}
void MyFillRect(HDC hdc, RECT& re)
{
::ExtTextOut(hdc, re.left, re.top, ETO_OPAQUE|ETO_CLIPPED, &re, L"", 0, NULL);
}
void CEditView::DrawBackImage(HDC hdc, RECT& rcPaint, HDC hdcBgImg)
{
#if 0
// テスト背景パターン
static int testColorIndex = 0;
testColorIndex = testColorIndex % 7;
COLORREF cols[7] = {RGB(255,255,255),
RGB(200,255,255),RGB(255,200,255),RGB(255,255,200),
RGB(200,200,255),RGB(255,200,200),RGB(200,255,200),
};
COLORREF colorOld = ::SetBkColor(hdc, cols[testColorIndex]);
MyFillRect(hdc, rcPaint);
::SetBkColor(hdc, colorOld);
testColorIndex++;
#else
CTypeSupport cTextType(this,COLORIDX_TEXT);
COLORREF colorOld = ::SetBkColor(hdc, cTextType.GetBackColor());
MyFillRect(hdc, rcPaint);
const CTextArea& area = GetTextArea();
const CEditDoc& doc = *m_pcEditDoc;
const STypeConfig& typeConfig = doc.m_cDocType.GetDocumentAttribute();
CMyRect rcImagePos;
switch( typeConfig.m_backImgPos ){
case BGIMAGE_TOP_LEFT:
case BGIMAGE_BOTTOM_LEFT:
case BGIMAGE_CENTER_LEFT:
rcImagePos.left = area.GetAreaLeft();
break;
case BGIMAGE_TOP_RIGHT:
case BGIMAGE_BOTTOM_RIGHT:
case BGIMAGE_CENTER_RIGHT:
rcImagePos.left = area.GetAreaRight() - doc.m_nBackImgWidth;
break;
case BGIMAGE_TOP_CENTER:
case BGIMAGE_BOTTOM_CENTER:
case BGIMAGE_CENTER:
rcImagePos.left = area.GetAreaLeft() + area.GetAreaWidth()/2 - doc.m_nBackImgWidth/2;
break;
default:
assert_warning(0 != typeConfig.m_backImgPos);
break;
}
switch( typeConfig.m_backImgPos ){
case BGIMAGE_TOP_LEFT:
case BGIMAGE_TOP_RIGHT:
case BGIMAGE_TOP_CENTER:
rcImagePos.top = area.GetAreaTop();
break;
case BGIMAGE_BOTTOM_LEFT:
case BGIMAGE_BOTTOM_RIGHT:
case BGIMAGE_BOTTOM_CENTER:
rcImagePos.top = area.GetAreaBottom() - doc.m_nBackImgHeight;
break;
case BGIMAGE_CENTER_LEFT:
case BGIMAGE_CENTER_RIGHT:
case BGIMAGE_CENTER:
rcImagePos.top = area.GetAreaTop() + area.GetAreaHeight()/2 - doc.m_nBackImgHeight/2;
break;
default:
assert_warning(0 != typeConfig.m_backImgPos);
break;
}
rcImagePos.left += typeConfig.m_backImgPosOffset.x;
rcImagePos.top += typeConfig.m_backImgPosOffset.y;
// スクロール時の画面の端を作画するときの位置あたりへ移動
if( typeConfig.m_backImgScrollX ){
int tile = typeConfig.m_backImgRepeatX ? doc.m_nBackImgWidth : INT_MAX;
Int posX = (area.GetViewLeftCol() % tile) * GetTextMetrics().GetCharPxWidth();
rcImagePos.left -= posX % tile;
}
if( typeConfig.m_backImgScrollY ){
int tile = typeConfig.m_backImgRepeatY ? doc.m_nBackImgHeight : INT_MAX;
Int posY = (area.GetViewTopLine() % tile) * GetTextMetrics().GetHankakuDy();
rcImagePos.top -= posY % tile;
}
if( typeConfig.m_backImgRepeatX ){
if( 0 < rcImagePos.left ){
// rcImagePos.left = rcImagePos.left - (rcImagePos.left / doc.m_nBackImgWidth + 1) * doc.m_nBackImgWidth;
rcImagePos.left = rcImagePos.left % doc.m_nBackImgWidth - doc.m_nBackImgWidth;
}
}
if( typeConfig.m_backImgRepeatY ){
if( 0 < rcImagePos.top ){
// rcImagePos.top = rcImagePos.top - (rcImagePos.top / doc.m_nBackImgHeight + 1) * doc.m_nBackImgHeight;
rcImagePos.top = rcImagePos.top % doc.m_nBackImgHeight - doc.m_nBackImgHeight;
}
}
rcImagePos.SetSize(doc.m_nBackImgWidth, doc.m_nBackImgHeight);
RECT rc = rcPaint;
// rc.left = t_max((int)rc.left, area.GetAreaLeft());
rc.top = t_max((int)rc.top, area.GetRulerHeight()); // ルーラーを除外
const int nXEnd = area.GetAreaRight();
const int nYEnd = area.GetAreaBottom();
CMyRect rcBltAll;
rcBltAll.SetLTRB(INT_MAX, INT_MAX, -INT_MAX, -INT_MAX);
CMyRect rcImagePosOrg = rcImagePos;
BLENDFUNCTION bf;
bf.BlendOp = AC_SRC_OVER;
bf.BlendFlags = 0;
bf.SourceConstantAlpha = typeConfig.m_backImgOpacity;
bf.AlphaFormat = AC_SRC_ALPHA;
for(; rcImagePos.top <= nYEnd; ){
for(; rcImagePos.left <= nXEnd; ){
CMyRect rcBlt;
if( ::IntersectRect(&rcBlt, &rc, &rcImagePos) ){
int width = rcBlt.right - rcBlt.left;
int height = rcBlt.bottom - rcBlt.top;
::AlphaBlend(
hdc,
rcBlt.left,
rcBlt.top,
width,
height,
hdcBgImg,
rcBlt.left - rcImagePos.left,
rcBlt.top - rcImagePos.top,
width,
height,
bf
);
rcBltAll.left = t_min(rcBltAll.left, rcBlt.left);
rcBltAll.top = t_min(rcBltAll.top, rcBlt.top);
rcBltAll.right = t_max(rcBltAll.right, rcBlt.right);
rcBltAll.bottom = t_max(rcBltAll.bottom, rcBlt.bottom);
}
rcImagePos.left += doc.m_nBackImgWidth;
rcImagePos.right += doc.m_nBackImgWidth;
if( !typeConfig.m_backImgRepeatX ){
break;
}
}
rcImagePos.left = rcImagePosOrg.left;
rcImagePos.right = rcImagePosOrg.right;
rcImagePos.top += doc.m_nBackImgHeight;
rcImagePos.bottom += doc.m_nBackImgHeight;
if( !typeConfig.m_backImgRepeatY ){
break;
}
}
if( rcBltAll.left != INT_MAX ){
// 上下左右ななめの隙間を埋める
CMyRect rcFill;
LONG& x1 = rc.left;
LONG& x2 = rcBltAll.left;
LONG& x3 = rcBltAll.right;
LONG& x4 = rc.right;
LONG& y1 = rc.top;
LONG& y2 = rcBltAll.top;
LONG& y3 = rcBltAll.bottom;
LONG& y4 = rc.bottom;
if( y1 < y2 ){
rcFill.SetLTRB(x1,y1, x4,y2); MyFillRect(hdc, rcFill);
}
if( x1 < x2 ){
rcFill.SetLTRB(x1,y2, x2,y3); MyFillRect(hdc, rcFill);
}
if( x3 < x4 ){
rcFill.SetLTRB(x3,y2, x4,y3); MyFillRect(hdc, rcFill);
}
if( y3 < y4 ){
rcFill.SetLTRB(x1,y3, x4,y4); MyFillRect(hdc, rcFill);
}
}
::SetBkColor(hdc, colorOld);
#endif
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 色設定 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
/*! 指定位置のColorIndexの取得
CEditView::DrawLogicLineを元にしたためCEditView::DrawLogicLineに
修正があった場合は、ここも修正が必要。
*/
CColor3Setting CEditView::GetColorIndex(
const CLayout* pcLayout,
CLayoutYInt nLineNum,
int nIndex,
SColorStrategyInfo* pInfo, // 2010.03.31 ryoji 追加
bool bPrev // 指定位置の色変更直前まで 2010.06.19 ryoji 追加
)
{
EColorIndexType eRet = COLORIDX_TEXT;
if(!pcLayout){
CColor3Setting cColor = { COLORIDX_TEXT, COLORIDX_TEXT, COLORIDX_TEXT };
return cColor;
}
// 2014.12.30 Skipモードの時もCOLORIDX_TEXT
if (CColorStrategyPool::getInstance()->IsSkipBeforeLayout()) {
CColor3Setting cColor = { COLORIDX_TEXT, COLORIDX_TEXT, COLORIDX_TEXT };
return cColor;
}
const CLayoutColorInfo* colorInfo;
const CLayout* pcLayoutLineFirst = pcLayout;
CLayoutYInt nLineNumFirst = nLineNum;
{
// 2002/2/10 aroka CMemory変更
pInfo->m_pLineOfLogic = pcLayout->GetDocLineRef()->GetPtr();
// 論理行の最初のレイアウト情報を取得 -> pcLayoutLineFirst
while( 0 != pcLayoutLineFirst->GetLogicOffset() ){
pcLayoutLineFirst = pcLayoutLineFirst->GetPrevLayout();
nLineNumFirst--;
// 論理行の先頭まで戻らないと確実には正確な色は得られない
// (正規表現キーワードにマッチした長い強調表示がその位置のレイアウト行頭をまたいでいる場合など)
//if( pcLayout->GetLogicOffset() - pcLayoutLineFirst->GetLogicOffset() > 260 )
// break;
}
// 2005.11.20 Moca 色が正しくないことがある問題に対処
eRet = pcLayoutLineFirst->GetColorTypePrev(); /* 現在の色を指定 */ // 02/12/18 ai
colorInfo = pcLayoutLineFirst->GetColorInfo();
pInfo->m_nPosInLogic = pcLayoutLineFirst->GetLogicOffset();
//CColorStrategyPool初期化
CColorStrategyPool* pool = CColorStrategyPool::getInstance();
pool->SetCurrentView(this);
pool->NotifyOnStartScanLogic();
// 2009.02.07 ryoji この関数では pInfo->CheckChangeColor() で色を調べるだけなので以下の処理は不要
//
////############超仮。本当はVisitorを使うべき
//class TmpVisitor{
//public:
// static int CalcLayoutIndex(const CLayout* pcLayout)
// {
// int n = -1;
// while(pcLayout){
// pcLayout = pcLayout->GetPrevLayout(); //prev or null
// n++;
// }
// return n;
// }
//};
//pInfo->pDispPos->SetLayoutLineRef(CLayoutInt(TmpVisitor::CalcLayoutIndex(pcLayout)));
// 2013.12.11 Moca カレント行の色替えで必要になりました
pInfo->m_pDispPos->SetLayoutLineRef(nLineNumFirst);
}
//文字列参照
const CDocLine* pcDocLine = pcLayout->GetDocLineRef();
CStringRef cLineStr(pcDocLine->GetPtr(),pcDocLine->GetLengthWithEOL());
//color strategy
CColorStrategyPool* pool = CColorStrategyPool::getInstance();
pInfo->m_pStrategy = pool->GetStrategyByColor(eRet);
if(pInfo->m_pStrategy){
pInfo->m_pStrategy->InitStrategyStatus();
pInfo->m_pStrategy->SetStrategyColorInfo(colorInfo);
}
const CLayout* pcLayoutNext = pcLayoutLineFirst->GetNextLayout();
CLayoutYInt nLineNumScan = nLineNumFirst;
int nPosTo = pcLayout->GetLogicOffset() + t_min(nIndex, (int)pcLayout->GetLengthWithEOL() - 1);
while(pInfo->m_nPosInLogic <= nPosTo){
if( bPrev && pInfo->m_nPosInLogic == nPosTo )
break;
//色切替
pInfo->CheckChangeColor(cLineStr);
//1文字進む
pInfo->m_nPosInLogic += CNativeW::GetSizeOfChar(
cLineStr.GetPtr(),
cLineStr.GetLength(),
pInfo->m_nPosInLogic
);
if( pcLayoutNext && pcLayoutNext->GetLogicOffset() <= pInfo->m_nPosInLogic ){
nLineNumScan++;
pInfo->m_pDispPos->SetLayoutLineRef(nLineNumScan);
pcLayoutNext = pcLayoutNext->GetNextLayout();
}
}
CColor3Setting cColor;
pInfo->DoChangeColor(&cColor);
return cColor;
}
/*! 現在の色を指定
@param eColorIndex 選択を含む現在の色
@param eColorIndex2 選択以外の現在の色
@param eColorIndexBg 背景色
@date 2013.05.08 novice 範囲外チェック削除
*/
void CEditView::SetCurrentColor( CGraphics& gr, EColorIndexType eColorIndex, EColorIndexType eColorIndex2, EColorIndexType eColorIndexBg)
{
//インデックス決定
int nColorIdx = ToColorInfoArrIndex(eColorIndex);
int nColorIdx2 = ToColorInfoArrIndex(eColorIndex2);
int nColorIdxBg = ToColorInfoArrIndex(eColorIndexBg);
//実際に色を設定
const ColorInfo& info = m_pTypeData->m_ColorInfoArr[nColorIdx];
const ColorInfo& info2 = m_pTypeData->m_ColorInfoArr[nColorIdx2];
const ColorInfo& infoBg = m_pTypeData->m_ColorInfoArr[nColorIdxBg];
COLORREF fgcolor = GetTextColorByColorInfo2(info, info2);
gr.SetTextForeColor(fgcolor);
// 2012.11.21 背景色がテキストとおなじなら背景色はカーソル行背景
const ColorInfo& info3 = (info2.m_sColorAttr.m_cBACK == m_crBack ? infoBg : info2);
COLORREF bkcolor = (nColorIdx == nColorIdx2) ? info3.m_sColorAttr.m_cBACK : GetBackColorByColorInfo2(info, info3);
gr.SetTextBackColor(bkcolor);
SFONT sFont;
sFont.m_sFontAttr = (info.m_sColorAttr.m_cTEXT != info.m_sColorAttr.m_cBACK) ? info.m_sFontAttr : info2.m_sFontAttr;
sFont.m_hFont = GetFontset().ChooseFontHandle( 0, sFont.m_sFontAttr );
gr.SetMyFont(sFont);
}
inline COLORREF MakeColor2(COLORREF a, COLORREF b, int alpha)
{
#ifdef USE_SSE2
// (a * alpha + b * (256 - alpha)) / 256 -> ((a - b) * alpha) / 256 + b
__m128i xmm0, xmm1, xmm2, xmm3;
COLORREF color;
xmm0 = _mm_setzero_si128();
xmm1 = _mm_cvtsi32_si128( a );
xmm2 = _mm_cvtsi32_si128( b );
xmm3 = _mm_cvtsi32_si128( alpha );
xmm1 = _mm_unpacklo_epi8( xmm1, xmm0 ); // a:a:a:a
xmm2 = _mm_unpacklo_epi8( xmm2, xmm0 ); // b:b:b:b
xmm3 = _mm_shufflelo_epi16( xmm3, 0 ); // alpha:alpha:alpha:alpha
xmm1 = _mm_sub_epi16( xmm1, xmm2 ); // (a - b)
xmm1 = _mm_mullo_epi16( xmm1, xmm3 ); // (a - b) * alpha
xmm1 = _mm_srli_epi16( xmm1, 8 ); // ((a - b) * alpha) / 256
xmm1 = _mm_add_epi8( xmm1, xmm2 ); // ((a - b) * alpha) / 256 + b
xmm1 = _mm_packus_epi16( xmm1, xmm0 );
color = _mm_cvtsi128_si32( xmm1 );
return color;
#else
const int ap = alpha;
const int bp = 256 - ap;
BYTE valR = (BYTE)((GetRValue(a) * ap + GetRValue(b) * bp) / 256);
BYTE valG = (BYTE)((GetGValue(a) * ap + GetGValue(b) * bp) / 256);
BYTE valB = (BYTE)((GetBValue(a) * ap + GetBValue(b) * bp) / 256);
return RGB(valR, valG, valB);
#endif
}
COLORREF CEditView::GetTextColorByColorInfo2(const ColorInfo& info, const ColorInfo& info2)
{
if( info.m_sColorAttr.m_cTEXT != info.m_sColorAttr.m_cBACK ){
return info.m_sColorAttr.m_cTEXT;
}
// 反転表示
if( info.m_sColorAttr.m_cBACK == m_crBack ){
return info2.m_sColorAttr.m_cTEXT ^ 0x00FFFFFF;
}
int alpha = 255*30/100; // 30%
return MakeColor2(info.m_sColorAttr.m_cTEXT, info2.m_sColorAttr.m_cTEXT, alpha);
}
COLORREF CEditView::GetBackColorByColorInfo2(const ColorInfo& info, const ColorInfo& info2)
{
if( info.m_sColorAttr.m_cTEXT != info.m_sColorAttr.m_cBACK ){
return info.m_sColorAttr.m_cBACK;
}
// 反転表示
if( info.m_sColorAttr.m_cBACK == m_crBack ){
return info2.m_sColorAttr.m_cBACK ^ 0x00FFFFFF;
}
int alpha = 255*30/100; // 30%
return MakeColor2(info.m_sColorAttr.m_cBACK, info2.m_sColorAttr.m_cBACK, alpha);
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 描画 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
void CEditView::OnPaint( HDC _hdc, PAINTSTRUCT *pPs, BOOL bDrawFromComptibleBmp )
{
if (m_pcEditWnd->m_pPrintPreview) {
return;
}
bool bChangeFont = m_bMiniMap;
if( bChangeFont ){
SelectCharWidthCache( CWM_FONT_MINIMAP, CWM_CACHE_LOCAL );
}
OnPaint2( _hdc, pPs, bDrawFromComptibleBmp );
if( bChangeFont ){
SelectCharWidthCache( CWM_FONT_EDIT, m_pcEditWnd->GetLogfontCacheMode() );
}
}
/*! 通常の描画処理 new
@param pPs pPs.rcPaint は正しい必要がある
@param bDrawFromComptibleBmp TRUE 画面バッファからhdcに作画する(コピーするだけ)。
TRUEの場合、pPs.rcPaint領域外は作画されないが、FALSEの場合は作画される事がある。
互換DC/BMPが無い場合は、普通の作画処理をする。
@date 2007.09.09 Moca 元々無効化されていた第三パラメータのbUseMemoryDCをbDrawFromComptibleBmpに変更。
@date 2009.03.26 ryoji 行番号のみ描画を通常の行描画と分離(効率化)
*/
void CEditView::OnPaint2( HDC _hdc, PAINTSTRUCT *pPs, BOOL bDrawFromComptibleBmp )
{
// MY_RUNNINGTIMER( cRunningTimer, "CEditView::OnPaint" );
CGraphics gr(_hdc);
// 2004.01.28 Moca デスクトップに作画しないように
if( NULL == GetHwnd() || NULL == _hdc )return;
if( !GetDrawSwitch() )return;
//@@@
#if 0
::MYTRACE( L"OnPaint(%d,%d)-(%d,%d) : %d\n",
pPs->rcPaint.left,
pPs->rcPaint.top,
pPs->rcPaint.right,
pPs->rcPaint.bottom,
bDrawFromComptibleBmp
);
#endif
// From Here 2007.09.09 Moca 互換BMPによる画面バッファ
// 互換BMPからの転送のみによる作画
if( bDrawFromComptibleBmp
&& m_hdcCompatDC && m_hbmpCompatBMP ){
::BitBlt(
gr,
pPs->rcPaint.left,
pPs->rcPaint.top,
pPs->rcPaint.right - pPs->rcPaint.left,
pPs->rcPaint.bottom - pPs->rcPaint.top,
m_hdcCompatDC,
pPs->rcPaint.left,
pPs->rcPaint.top,
SRCCOPY
);
if ( m_pcEditWnd->GetActivePane() == m_nMyIndex ){
/* アクティブペインは、アンダーライン描画 */
GetCaret().m_cUnderLine.CaretUnderLineON( true, false );
}
return;
}
if( m_hdcCompatDC && NULL == m_hbmpCompatBMP
|| m_nCompatBMPWidth < (pPs->rcPaint.right - pPs->rcPaint.left)
|| m_nCompatBMPHeight < (pPs->rcPaint.bottom - pPs->rcPaint.top) ){
RECT rect;
::GetWindowRect( this->GetHwnd(), &rect );
CreateOrUpdateCompatibleBitmap( rect.right - rect.left, rect.bottom - rect.top );
}
// To Here 2007.09.09 Moca
// キャレットを隠す
bool bCaretShowFlag_Old = GetCaret().GetCaretShowFlag(); // 2008.06.09 ryoji
GetCaret().HideCaret_( this->GetHwnd() ); // 2002/07/22 novice
RECT rc;
int nLineHeight = GetTextMetrics().GetHankakuDy();
int nCharDx = GetTextMetrics().GetCharPxWidth();
//サポート
CTypeSupport cTextType(this,COLORIDX_TEXT);
//@@@ 2001.11.17 add start MIK
//変更があればタイプ設定を行う。
if( m_pTypeData->m_bUseRegexKeyword || m_cRegexKeyword->m_bUseRegexKeyword ) //OFFなのに前回のデータが残ってる
{
//タイプ別設定をする。設定済みかどうかは呼び先でチェックする。
m_cRegexKeyword->RegexKeySetTypes(m_pTypeData);
}
//@@@ 2001.11.17 add end MIK
bool bTransText = IsBkBitmap();
// メモリDCを利用した再描画の場合は描画先のDCを切り替える
HDC hdcOld = 0;
// 2007.09.09 Moca bUseMemoryDCを有効化。
// bUseMemoryDC = FALSE;
BOOL bUseMemoryDC = (m_hdcCompatDC != NULL);
assert_warning(gr != m_hdcCompatDC);
bool bClipping = false;
if( bUseMemoryDC ){
hdcOld = gr;
gr = m_hdcCompatDC;
}else{
if( bTransText || pPs->rcPaint.bottom - pPs->rcPaint.top <= 2 || pPs->rcPaint.right - pPs->rcPaint.left <= 2 ){
// 透過処理の場合フォントの輪郭が重ね塗りになるため自分でクリッピング領域を設定
// 2以下はたぶんアンダーライン・カーソル行縦線の作画
// MemoryDCの場合は転送が矩形クリッピングの代わりになっている
gr.SetClipping(pPs->rcPaint);
bClipping = true;
}
}
/* 03/02/18 対括弧の強調表示(消去) ai */
if( !bUseMemoryDC ){
// MemoryDCだとスクロール時に先に括弧だけ表示されて不自然なので後でやる。
DrawBracketPair( false );
}
CEditView& cActiveView = m_pcEditWnd->GetActiveView();
m_nPageViewTop = cActiveView.GetTextArea().GetViewTopLine();
m_nPageViewBottom = cActiveView.GetTextArea().GetBottomLine();
// 背景の表示
if( bTransText ){
HDC hdcBgImg = CreateCompatibleDC(gr);
HBITMAP hOldBmp = (HBITMAP)::SelectObject(hdcBgImg, m_pcEditDoc->m_hBackImg);
DrawBackImage(gr, pPs->rcPaint, hdcBgImg);
SelectObject(hdcBgImg, hOldBmp);
DeleteObject(hdcBgImg);
}
/* ルーラーとテキストの間の余白 */
//@@@ 2002.01.03 YAZAKI 余白が0のときは無駄でした。
if ( GetTextArea().GetTopYohaku() ){
if( !bTransText ){
rc.left = 0;
rc.top = GetTextArea().GetRulerHeight();
rc.right = GetTextArea().GetAreaRight();
rc.bottom = GetTextArea().GetAreaTop();
cTextType.FillBack(gr,rc);
}
}
/* 行番号の表示 */
// From Here Sep. 7, 2001 genta
// Sep. 23, 2002 genta 行番号非表示でも行番号色の帯があるので隙間を埋める
if( GetTextArea().GetTopYohaku() ){
if( bTransText && m_pTypeData->m_ColorInfoArr[COLORIDX_GYOU].m_sColorAttr.m_cBACK == cTextType.GetBackColor() ){
}else{
rc.left = 0;
rc.top = GetTextArea().GetRulerHeight();
rc.right = GetTextArea().GetLineNumberWidth(); // Sep. 23 ,2002 genta 余白はテキスト色のまま残す
rc.bottom = GetTextArea().GetAreaTop();
gr.SetTextBackColor(m_pTypeData->m_ColorInfoArr[COLORIDX_GYOU].m_sColorAttr.m_cBACK);
gr.FillMyRectTextBackColor(rc);
}
}
// To Here Sep. 7, 2001 genta
::SetBkMode( gr, TRANSPARENT );
cTextType.SetGraphicsState_WhileThisObj(gr);
int nTop = pPs->rcPaint.top;
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 描画開始レイアウト絶対行 -> nLayoutLine //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
CLayoutInt nLayoutLine;
if( 0 > nTop - GetTextArea().GetAreaTop() ){
nLayoutLine = GetTextArea().GetViewTopLine(); //ビュー上部から描画
}else{
nLayoutLine = GetTextArea().GetViewTopLine() + CLayoutInt( ( nTop - GetTextArea().GetAreaTop() ) / nLineHeight ); //ビュー途中から描画
}
// ※ ここにあった描画範囲の 260 文字ロールバック処理は GetColorIndex() に吸収 // 2009.02.11 ryoji
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 描画終了レイアウト絶対行 -> nLayoutLineTo //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
CLayoutInt nLayoutLineTo = GetTextArea().GetViewTopLine()
+ CLayoutInt( ( pPs->rcPaint.bottom - GetTextArea().GetAreaTop() + (nLineHeight - 1) ) / nLineHeight ) - 1; // 2007.02.17 ryoji 計算を精密化
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 描画座標 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
DispPos sPos(nCharDx, GetTextMetrics().GetHankakuDy());
sPos.InitDrawPos(CMyPoint(
GetTextArea().GetAreaLeft() - (Int)GetTextArea().GetViewLeftCol() * nCharDx,
GetTextArea().GetAreaTop() + (Int)( nLayoutLine - GetTextArea().GetViewTopLine() ) * nLineHeight
));
sPos.SetLayoutLineRef(nLayoutLine);
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 全部の行を描画 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
//必要な行を描画する // 2009.03.26 ryoji 行番号のみ描画を通常の行描画と分離(効率化)
if(pPs->rcPaint.right <= GetTextArea().GetAreaLeft()){
while(sPos.GetLayoutLineRef() <= nLayoutLineTo)
{
if(!sPos.GetLayoutRef())
break;
//1行描画(行番号のみ)
GetTextDrawer().DispLineNumber(
gr,
sPos.GetLayoutLineRef(),
sPos.GetDrawPos().y
);
//行を進める
sPos.ForwardDrawLine(1); //描画Y座標++
sPos.ForwardLayoutLineRef(1); //レイアウト行++
}
}else{
while(sPos.GetLayoutLineRef() <= nLayoutLineTo)
{
//描画X位置リセット
sPos.ResetDrawCol();
//1行描画
bool bDispResult = DrawLogicLine(
gr,
&sPos,
nLayoutLineTo
);
if(bDispResult){
// EOF再描画対応
nLayoutLineTo++;
int nBackImageTop = pPs->rcPaint.bottom;
pPs->rcPaint.bottom += nLineHeight;
if(bClipping){
gr.SetClipping(pPs->rcPaint);
}
if(bTransText){
HDC hdcBgImg = CreateCompatibleDC(gr);
HBITMAP hOldBmp = (HBITMAP)::SelectObject(hdcBgImg, m_pcEditDoc->m_hBackImg);
RECT rc = pPs->rcPaint;
rc.top = nBackImageTop;
DrawBackImage(gr, rc, hdcBgImg);
SelectObject(hdcBgImg, hOldBmp);
DeleteObject(hdcBgImg);
}
}
}
}
cTextType.RewindGraphicsState(gr);
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// ルーラー描画 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
if ( pPs->rcPaint.top < GetTextArea().GetRulerHeight() ) { // ルーラーが再描画範囲にあるときのみ再描画する 2002.02.25 Add By KK
GetRuler().SetRedrawFlag(); //2002.02.25 Add By KK ルーラー全体を描画。
GetRuler().DispRuler( gr );
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// その他後始末など //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
/* メモリDCを利用した再描画の場合はメモリDCに描画した内容を画面へコピーする */
if( bUseMemoryDC ){
// 2010.10.11 先に描くと背景固定のスクロールなどでの表示が不自然になる
DrawBracketPair( false );
::BitBlt(
hdcOld,
pPs->rcPaint.left,
pPs->rcPaint.top,
pPs->rcPaint.right - pPs->rcPaint.left,
pPs->rcPaint.bottom - pPs->rcPaint.top,
gr,
pPs->rcPaint.left,
pPs->rcPaint.top,
SRCCOPY
);
}
// From Here 2007.09.09 Moca 互換BMPによる画面バッファ
// アンダーライン描画をメモリDCからのコピー前処理から後に移動
if ( m_pcEditWnd->GetActivePane() == m_nMyIndex ){
/* アクティブペインは、アンダーライン描画 */
GetCaret().m_cUnderLine.CaretUnderLineON( true, false );
}
// To Here 2007.09.09 Moca
/* 03/02/18 対括弧の強調表示(描画) ai */
DrawBracketPair( true );
/* キャレットを現在位置に表示します */
if( bCaretShowFlag_Old ) // 2008.06.09 ryoji
GetCaret().ShowCaret_( this->GetHwnd() ); // 2002/07/22 novice
return;
}
/*!
行のテキスト/選択状態の描画
1回で1ロジック行分を作画する。
@return EOFを作画したらtrue
@date 2001.02.17 MIK
@date 2001.12.21 YAZAKI 改行記号の描きかたを変更
@date 2007.08.31 kobake 引数 bDispBkBitmap を削除
*/
bool CEditView::DrawLogicLine(
HDC _hdc, //!< [in] 作画対象
DispPos* _pDispPos, //!< [in,out] 描画する箇所、描画元ソース
CLayoutInt nLineTo //!< [in] 作画終了するレイアウト行番号
)
{
// MY_RUNNINGTIMER( cRunningTimer, "CEditView::DrawLogicLine" );
bool bDispEOF = false;
SColorStrategyInfo _sInfo;
SColorStrategyInfo* pInfo = &_sInfo;
pInfo->m_gr.Init(_hdc);
pInfo->m_pDispPos = _pDispPos;
pInfo->m_pcView = this;
//CColorStrategyPool初期化
CColorStrategyPool* pool = CColorStrategyPool::getInstance();
pool->SetCurrentView(this);
pool->NotifyOnStartScanLogic();
bool bSkipBeforeLayout = pool->IsSkipBeforeLayout();
//DispPosを保存しておく
pInfo->m_sDispPosBegin = *pInfo->m_pDispPos;
//処理する文字位置
pInfo->m_nPosInLogic = CLogicInt(0); //☆開始
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 論理行データの取得 -> pLine, pLineLen //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 前行の最終設定色
{
const CLayout* pcLayout = pInfo->m_pDispPos->GetLayoutRef();
if( bSkipBeforeLayout ){
EColorIndexType eRet = COLORIDX_TEXT;
const CLayoutColorInfo* colorInfo = NULL;
if( pcLayout ){
eRet = pcLayout->GetColorTypePrev(); // COLORIDX_TEXTのはず
colorInfo = pcLayout->GetColorInfo();
}
pInfo->m_pStrategy = pool->GetStrategyByColor(eRet);
if( pInfo->m_pStrategy ){
pInfo->m_pStrategy->InitStrategyStatus();
pInfo->m_pStrategy->SetStrategyColorInfo(colorInfo);
}
}else{
CColor3Setting cColor = GetColorIndex(pcLayout, pInfo->m_pDispPos->GetLayoutLineRef(), 0, pInfo, true);
SetCurrentColor(pInfo->m_gr, cColor.eColorIndex, cColor.eColorIndex2, cColor.eColorIndexBg);
}
}
//開始ロジック位置を算出
{
const CLayout* pcLayout = pInfo->m_pDispPos->GetLayoutRef();
pInfo->m_nPosInLogic = pcLayout?pcLayout->GetLogicOffset():CLogicInt(0);
}
for (;;) {
//対象行が描画範囲外だったら終了
if( GetTextArea().GetBottomLine() < pInfo->m_pDispPos->GetLayoutLineRef() ){
pInfo->m_pDispPos->SetLayoutLineRef(nLineTo + CLayoutInt(1));
break;
}
if( nLineTo < pInfo->m_pDispPos->GetLayoutLineRef() ){
break;
}
//レイアウト行を1行描画
bDispEOF = DrawLayoutLine(pInfo);
//行を進める
CLogicInt nOldLogicLineNo = CLayout::GetLogicLineNo_Safe(pInfo->m_pDispPos->GetLayoutRef());
pInfo->m_pDispPos->ForwardDrawLine(1); //描画Y座標++
pInfo->m_pDispPos->ForwardLayoutLineRef(1); //レイアウト行++
// ロジック行を描画し終わったら抜ける
if(CLayout::GetLogicLineNo_Safe(pInfo->m_pDispPos->GetLayoutRef()) != nOldLogicLineNo){
break;
}
// nLineToを超えたら抜ける
if(pInfo->m_pDispPos->GetLayoutLineRef() >= nLineTo + CLayoutInt(1)){
break;
}
}
return bDispEOF;
}
/*!
レイアウト行を1行描画
*/
//改行記号を描画した場合はtrueを返す?
bool CEditView::DrawLayoutLine(SColorStrategyInfo* pInfo)
{
bool bDispEOF = false;
CTypeSupport cTextType(this,COLORIDX_TEXT);
const CLayout* pcLayout = pInfo->m_pDispPos->GetLayoutRef(); //m_pcEditDoc->m_cLayoutMgr.SearchLineByLayoutY( pInfo->pDispPos->GetLayoutLineRef() );
// レイアウト情報
if( pcLayout ){
pInfo->m_pLineOfLogic = pcLayout->GetDocLineRef()->GetPtr();
}
else{
pInfo->m_pLineOfLogic = NULL;
}
//文字列参照
const CDocLine* pcDocLine = pInfo->GetDocLine();
CStringRef cLineStr = CDocLine::GetStringRefWithEOL_Safe(pcDocLine);
// 描画範囲外の場合は色切替だけで抜ける
if(pInfo->m_pDispPos->GetDrawPos().y < GetTextArea().GetAreaTop()){
if(pcLayout){
bool bChange = false;
int nPosTo = pcLayout->GetLogicOffset() + pcLayout->GetLengthWithEOL();
CColor3Setting cColor;
while(pInfo->m_nPosInLogic < nPosTo){
//色切替
bChange |= pInfo->CheckChangeColor(cLineStr);
//1文字進む
pInfo->m_nPosInLogic += CNativeW::GetSizeOfChar(
cLineStr.GetPtr(),
cLineStr.GetLength(),
pInfo->m_nPosInLogic
);
}
if( bChange ){
pInfo->DoChangeColor(&cColor);
SetCurrentColor(pInfo->m_gr, cColor.eColorIndex, cColor.eColorIndex2, cColor.eColorIndexBg);
}
}
return false;
}
// コンフィグ
int nLineHeight = GetTextMetrics().GetHankakuDy(); //行の縦幅?
CTypeSupport cCaretLineBg(this, COLORIDX_CARETLINEBG);
CTypeSupport cEvenLineBg(this, COLORIDX_EVENLINEBG);
CTypeSupport cPageViewBg(this, COLORIDX_PAGEVIEW);
CEditView& cActiveView = m_pcEditWnd->GetActiveView();
CTypeSupport& cBackType = (cCaretLineBg.IsDisp() &&
GetCaret().GetCaretLayoutPos().GetY() == pInfo->m_pDispPos->GetLayoutLineRef() && !m_bMiniMap
? cCaretLineBg
: cEvenLineBg.IsDisp() && pInfo->m_pDispPos->GetLayoutLineRef() % 2 == 1 && !m_bMiniMap
? cEvenLineBg
: (cPageViewBg.IsDisp() && m_bMiniMap
&& cActiveView.GetTextArea().GetViewTopLine() <= pInfo->m_pDispPos->GetLayoutLineRef()
&& pInfo->m_pDispPos->GetLayoutLineRef() < cActiveView.GetTextArea().GetBottomLine())
? cPageViewBg
: cTextType);
bool bTransText = IsBkBitmap();
if( bTransText ){
bTransText = cBackType.GetBackColor() == cTextType.GetBackColor();
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 行番号描画 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
GetTextDrawer().DispLineNumber(
pInfo->m_gr,
pInfo->m_pDispPos->GetLayoutLineRef(),
pInfo->m_pDispPos->GetDrawPos().y
);
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 本文描画開始 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
pInfo->m_pDispPos->ResetDrawCol();
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 行頭(インデント)背景描画 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
if(pcLayout && pcLayout->GetIndent()!=0)
{
RECT rcClip;
if(!bTransText && GetTextArea().GenerateClipRect(&rcClip, *pInfo->m_pDispPos, pcLayout->GetIndent())){
cBackType.FillBack(pInfo->m_gr,rcClip);
}
//描画位置進める
pInfo->m_pDispPos->ForwardDrawCol(pcLayout->GetIndent());
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 本文描画 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
bool bSkipRight = false; // 続きを描画しなくていい場合はスキップする
if(pcLayout){
const CLayout* pcLayoutNext = pcLayout->GetNextLayout();
if( NULL == pcLayoutNext ){
bSkipRight = true;
}else if( pcLayoutNext->GetLogicOffset() == 0 ){
bSkipRight = true; // 次の行は別のロジック行なのでスキップ可能
}
if( !bSkipRight ){
bSkipRight = CColorStrategyPool::getInstance()->IsSkipBeforeLayout();
}
}
//行終端または折り返しに達するまでループ
if(pcLayout){
int nPosTo = pcLayout->GetLogicOffset() + pcLayout->GetLengthWithEOL();
CFigureManager* pcFigureManager = CFigureManager::getInstance();
while(pInfo->m_nPosInLogic < nPosTo){
//色切替
if( pInfo->CheckChangeColor(cLineStr) ){
CColor3Setting cColor;
pInfo->DoChangeColor(&cColor);
SetCurrentColor(pInfo->m_gr, cColor.eColorIndex, cColor.eColorIndex2, cColor.eColorIndexBg);
}
//1文字情報取得 $$高速化可能
CFigure& cFigure = pcFigureManager->GetFigure(&cLineStr.GetPtr()[pInfo->GetPosInLogic()],
cLineStr.GetLength() - pInfo->GetPosInLogic());
//1文字描画
cFigure.DrawImp(pInfo);
if( bSkipRight && GetTextArea().GetAreaRight() < pInfo->m_pDispPos->GetDrawPos().x ){
pInfo->m_nPosInLogic = nPosTo;
break;
}
}
}
// 必要ならEOF描画
void _DispEOF( CGraphics& gr, DispPos* pDispPos, const CEditView* pcView);
if(pcLayout && pcLayout->GetNextLayout()==NULL && pcLayout->GetLayoutEol().GetLen()==0){
// 有文字行のEOF
_DispEOF(pInfo->m_gr,pInfo->m_pDispPos,this);
bDispEOF = true;
}
else if(!pcLayout && pInfo->m_pDispPos->GetLayoutLineRef()==m_pcEditDoc->m_cLayoutMgr.GetLineCount()){
// 空行のEOF
const CLayout* pBottom = m_pcEditDoc->m_cLayoutMgr.GetBottomLayout();
if(pBottom==NULL || (pBottom && pBottom->GetLayoutEol().GetLen())){
_DispEOF(pInfo->m_gr,pInfo->m_pDispPos,this);
bDispEOF = true;
}
}
// 必要なら折り返し記号描画
if(pcLayout && pcLayout->GetLayoutEol().GetLen()==0 && pcLayout->GetNextLayout()!=NULL){
_DispWrap(pInfo->m_gr,pInfo->m_pDispPos,this,pInfo->m_pDispPos->GetLayoutLineRef());
}
// 行末背景描画
RECT rcClip;
bool rcClipRet = GetTextArea().GenerateClipRectRight(&rcClip,*pInfo->m_pDispPos);
if(rcClipRet){
if( !bTransText ){
cBackType.FillBack(pInfo->m_gr,rcClip);
}
CTypeSupport cSelectType(this, COLORIDX_SELECT);
if( GetSelectionInfo().IsTextSelected() && cSelectType.IsDisp() ){
// 選択範囲の指定色:必要ならテキストのない部分の矩形選択を作画
CLayoutRange selectArea = GetSelectionInfo().GetSelectAreaLine(pInfo->m_pDispPos->GetLayoutLineRef(), pcLayout);
// 2010.10.04 スクロール分の足し忘れ
CPixelXInt nSelectFromPx = GetTextMetrics().GetCharPxWidth(selectArea.GetFrom().x - GetTextArea().GetViewLeftCol());
CPixelXInt nSelectToPx = GetTextMetrics().GetCharPxWidth(selectArea.GetTo().x - GetTextArea().GetViewLeftCol());
if( nSelectFromPx < nSelectToPx && selectArea.GetTo().x != INT_MAX ){
RECT rcSelect; // Pixel
rcSelect.top = pInfo->m_pDispPos->GetDrawPos().y;
rcSelect.bottom = pInfo->m_pDispPos->GetDrawPos().y + GetTextMetrics().GetHankakuDy();
rcSelect.left = GetTextArea().GetAreaLeft() + nSelectFromPx;
rcSelect.right = GetTextArea().GetAreaLeft() + nSelectToPx;
RECT rcDraw;
if( ::IntersectRect(&rcDraw, &rcClip, &rcSelect) ){
COLORREF color = GetBackColorByColorInfo2(cSelectType.GetColorInfo(), cBackType.GetColorInfo());
if( color != cBackType.GetBackColor() ){
pInfo->m_gr.FillSolidMyRect(rcDraw, color);
}
}
}
}
}
// ノート線描画
if( !m_bMiniMap ){
GetTextDrawer().DispNoteLine(
pInfo->m_gr,
pInfo->m_pDispPos->GetDrawPos().y,
pInfo->m_pDispPos->GetDrawPos().y + nLineHeight,
GetTextArea().GetAreaLeft(),
GetTextArea().GetAreaRight()
);
}
// 指定桁縦線描画
GetTextDrawer().DispVerticalLines(
pInfo->m_gr,
pInfo->m_pDispPos->GetDrawPos().y,
pInfo->m_pDispPos->GetDrawPos().y + nLineHeight,
CLayoutInt(0),
CLayoutInt(-1)
);
// 折り返し桁縦線描画
if( !m_bMiniMap ){
GetTextDrawer().DispWrapLine(
pInfo->m_gr,
pInfo->m_pDispPos->GetDrawPos().y,
pInfo->m_pDispPos->GetDrawPos().y + nLineHeight
);
}
// 反転描画
if( pcLayout && GetSelectionInfo().IsTextSelected() ){
DispTextSelected(
pInfo->m_gr,
pInfo->m_pDispPos->GetLayoutLineRef(),
CMyPoint(pInfo->m_sDispPosBegin.GetDrawPos().x, pInfo->m_pDispPos->GetDrawPos().y),
pcLayout->CalcLayoutWidth(m_pcEditDoc->m_cLayoutMgr)
+ CLayoutInt(pcLayout->GetLayoutEol().GetLen()
? (CTypeSupport(this, COLORIDX_EOL).IsDisp()
? (GetTextMetrics().GetLayoutXDefault()+CLayoutXInt(4)) // HACK:EOLの描画幅分だけ確保する。4pxはCRLFのはみ出している分
: CLayoutXInt(2)) // 非表示 = 2px
: CLayoutInt(0))
);
}
return bDispEOF;
}
/* テキスト反転
@param hdc
@param nLineNum
@param x
@param y
@param nX
@note
CCEditView::DrawLogicLine() での作画(WM_PAINT)時に、1レイアウト行をまとめて反転処理するための関数。
範囲選択の随時更新は、CEditView::DrawSelectArea() が選択・反転解除を行う。
*/
void CEditView::DispTextSelected(
HDC hdc, //!< 作画対象ビットマップを含むデバイス
CLayoutInt nLineNum, //!< 反転処理対象レイアウト行番号(0開始)
const CMyPoint& ptXY, //!< (相対レイアウト0桁目の左端座標, 対象行の上端座標)
CLayoutInt nX_Layout //!< 対象行の終了桁位置。 [ABC\n]なら改行の後ろで4
)
{
CLayoutInt nSelectFrom;
CLayoutInt nSelectTo;
RECT rcClip;
int nLineHeight = GetTextMetrics().GetHankakuDy();
int nCharWidth = GetTextMetrics().GetCharPxWidth();
HRGN hrgnDraw;
const CLayout* pcLayout = m_pcEditDoc->m_cLayoutMgr.SearchLineByLayoutY( nLineNum );
CLayoutRange& sSelect = GetSelectionInfo().m_sSelect;
/* 選択範囲内の行かな */
// if( IsTextSelected() ){
if( nLineNum >= sSelect.GetFrom().y && nLineNum <= sSelect.GetTo().y ){
CLayoutRange selectArea = GetSelectionInfo().GetSelectAreaLine(nLineNum, pcLayout);
nSelectFrom = selectArea.GetFrom().x;
nSelectTo = selectArea.GetTo().x;
if( nSelectFrom == INT_MAX ){
nSelectFrom = nX_Layout;
}
if( nSelectTo == INT_MAX ){
nSelectTo = nX_Layout;
}
// 2006.03.28 Moca 表示域外なら何もしない
if( GetTextArea().GetRightCol() < nSelectFrom ){
return;
}
if( nSelectTo < GetTextArea().GetViewLeftCol() ){ // nSelectTo == GetTextArea().GetViewLeftCol()のケースは後で0文字マッチでないことを確認してから抜ける
return;
}
if( nSelectFrom < GetTextArea().GetViewLeftCol() ){
nSelectFrom = GetTextArea().GetViewLeftCol();
}
rcClip.left = ptXY.x + (Int)nSelectFrom * nCharWidth;
rcClip.right = ptXY.x + (Int)nSelectTo * nCharWidth;
rcClip.top = ptXY.y;
rcClip.bottom = ptXY.y + nLineHeight;
bool bOMatch = false;
// 2005/04/02 かろと 0文字マッチだと反転幅が0となり反転されないので、1/3文字幅だけ反転させる
// 2005/06/26 zenryaku 選択解除でキャレットの残骸が残る問題を修正
// 2005/09/29 ryoji スクロール時にキャレットのようなゴミが表示される問題を修正
if (GetSelectionInfo().IsTextSelected() && rcClip.right == rcClip.left &&
sSelect.IsLineOne() &&
sSelect.GetFrom().x >= GetTextArea().GetViewLeftCol())
{
HWND hWnd = ::GetForegroundWindow();
if( hWnd && (hWnd == m_pcEditWnd->m_cDlgFind.GetHwnd() || hWnd == m_pcEditWnd->m_cDlgReplace.GetHwnd()) ){
rcClip.right = rcClip.left + 2;
bOMatch = true;
}
}
if( rcClip.right == rcClip.left ){
return; //0文字マッチによる反転幅拡張なし
}
// 2006.03.28 Moca ウィンドウ幅が大きいと正しく反転しない問題を修正
if( rcClip.right > GetTextArea().GetAreaRight() ){
rcClip.right = GetTextArea().GetAreaRight();
}
// 選択色表示なら反転しない
if( !bOMatch && CTypeSupport(this, COLORIDX_SELECT).IsDisp() ){
return;
}
HBRUSH hBrush = ::CreateSolidBrush( SELECTEDAREA_RGB );
int nROP_Old = ::SetROP2( hdc, SELECTEDAREA_ROP2 );
HBRUSH hBrushOld = (HBRUSH)::SelectObject( hdc, hBrush );
hrgnDraw = ::CreateRectRgn( rcClip.left, rcClip.top, rcClip.right, rcClip.bottom );
::PaintRgn( hdc, hrgnDraw );
::DeleteObject( hrgnDraw );
SetROP2( hdc, nROP_Old );
SelectObject( hdc, hBrushOld );
DeleteObject( hBrush );
}
// }
return;
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// 画面バッファ //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
/*!
画面の互換ビットマップを作成または更新する。
必要の無いときは何もしない。
@param cx ウィンドウの高さ
@param cy ウィンドウの幅
@return true: ビットマップを利用可能 / false: ビットマップの作成・更新に失敗
@date 2007.09.09 Moca CEditView::OnSizeから分離。
単純に生成するだけだったものを、仕様変更に従い内容コピーを追加。
サイズが同じときは何もしないように変更
@par 互換BMPにはキャレット・カーソル位置横縦線・対括弧以外の情報を全て書き込む。
選択範囲変更時の反転処理は、画面と互換BMPの両方を別々に変更する。
カーソル位置横縦線変更時には、互換BMPから画面に元の情報を復帰させている。
*/
bool CEditView::CreateOrUpdateCompatibleBitmap( int cx, int cy )
{
if( NULL == m_hdcCompatDC ){
return false;
}
// サイズを64の倍数で整列
int nBmpWidthNew = ((cx + 63) & (0x7fffffff - 63));
int nBmpHeightNew = ((cy + 63) & (0x7fffffff - 63));
if( nBmpWidthNew > m_nCompatBMPWidth || nBmpHeightNew > m_nCompatBMPHeight ){
#if 0
MYTRACE( L"CEditView::CreateOrUpdateCompatibleBitmap( %d, %d ): resized\n", cx, cy );
#endif
HDC hdc = ::GetDC( GetHwnd() );
HBITMAP hBitmapNew = NULL;
if( m_hbmpCompatBMP ){
// BMPの更新
HDC hdcTemp = ::CreateCompatibleDC( hdc );
hBitmapNew = ::CreateCompatibleBitmap( hdc, nBmpWidthNew, nBmpHeightNew );
if( hBitmapNew ){
HBITMAP hBitmapOld = (HBITMAP)::SelectObject( hdcTemp, hBitmapNew );
// 前の画面内容をコピーする
::BitBlt( hdcTemp, 0, 0,
t_min( nBmpWidthNew,m_nCompatBMPWidth ),
t_min( nBmpHeightNew, m_nCompatBMPHeight ),
m_hdcCompatDC, 0, 0, SRCCOPY );
::SelectObject( hdcTemp, hBitmapOld );
::SelectObject( m_hdcCompatDC, m_hbmpCompatBMPOld );
::DeleteObject( m_hbmpCompatBMP );
}
::DeleteDC( hdcTemp );
}else{
// BMPの新規作成
hBitmapNew = ::CreateCompatibleBitmap( hdc, nBmpWidthNew, nBmpHeightNew );
}
if( hBitmapNew ){
m_hbmpCompatBMP = hBitmapNew;
m_nCompatBMPWidth = nBmpWidthNew;
m_nCompatBMPHeight = nBmpHeightNew;
m_hbmpCompatBMPOld = (HBITMAP)::SelectObject( m_hdcCompatDC, m_hbmpCompatBMP );
}else{
// 互換BMPの作成に失敗
// 今後も失敗を繰り返す可能性が高いので
// m_hdcCompatDCをNULLにすることで画面バッファ機能をこのウィンドウのみ無効にする。
// 2007.09.29 genta 関数化.既存のBMPも解放
UseCompatibleDC(FALSE);
}
::ReleaseDC( GetHwnd(), hdc );
}
return NULL != m_hbmpCompatBMP;
}
/*!
互換メモリBMPを削除
@note 分割ビューが非表示になった場合と
親ウィンドウが非表示・最小化された場合に削除される。
@date 2007.09.09 Moca 新規作成
*/
void CEditView::DeleteCompatibleBitmap()
{
if( m_hbmpCompatBMP ){
::SelectObject( m_hdcCompatDC, m_hbmpCompatBMPOld );
::DeleteObject( m_hbmpCompatBMP );
m_hbmpCompatBMP = NULL;
m_hbmpCompatBMPOld = NULL;
m_nCompatBMPWidth = -1;
m_nCompatBMPHeight = -1;
}
}
/** 画面キャッシュ用CompatibleDCを用意する
@param[in] TRUE: 画面キャッシュON
@date 2007.09.30 genta 関数化
*/
void CEditView::UseCompatibleDC(BOOL fCache)
{
// From Here 2007.09.09 Moca 互換BMPによる画面バッファ
if( fCache ){
if( m_hdcCompatDC == NULL ){
HDC hdc;
hdc = ::GetDC( GetHwnd() );
m_hdcCompatDC = ::CreateCompatibleDC( hdc );
::ReleaseDC( GetHwnd(), hdc );
DEBUG_TRACE(L"CEditView::UseCompatibleDC: Created\n", fCache);
}
else {
DEBUG_TRACE(L"CEditView::UseCompatibleDC: Reused\n", fCache);
}
}
else {
// CompatibleBitmapが残っているかもしれないので最初に削除
DeleteCompatibleBitmap();
if( m_hdcCompatDC != NULL ){
::DeleteDC( m_hdcCompatDC );
DEBUG_TRACE(L"CEditView::UseCompatibleDC: Deleted.\n");
m_hdcCompatDC = NULL;
}
}
}
| 30.287825 | 159 | 0.662074 | [
"vector"
] |
f503dfc8988ba7c3547698408a2774027f7b31e9 | 1,888 | cpp | C++ | EX6/src/main.cpp | zuimrs/ImageProcess | 8a699668c71e45e7910a6bfcb3ab0589d878cbfa | [
"MIT"
] | 1 | 2018-06-20T12:29:52.000Z | 2018-06-20T12:29:52.000Z | EX6/src/main.cpp | zuimrs/ImageProcess | 8a699668c71e45e7910a6bfcb3ab0589d878cbfa | [
"MIT"
] | null | null | null | EX6/src/main.cpp | zuimrs/ImageProcess | 8a699668c71e45e7910a6bfcb3ab0589d878cbfa | [
"MIT"
] | null | null | null | #include <algorithm>
#include "CImg.h"
#include "stitch.h"
using namespace std;
vector<string> getFiles(string cate_dir);
int main()
{
string basepath = "./TEST-ImageData(2)/";
string outputpath = "../result/";
vector<string> filenames = getFiles(basepath);
Stitch * stitch = new Stitch();
for(int i = 0; i < filenames.size();++i)
{
string img_filepath = basepath+filenames[i];
stitch->LoadImg(img_filepath);
}
stitch->Perform();
}
vector<string> getFiles(string cate_dir)
{
vector<string> files;//存放文件名
#ifdef WIN32
_finddata_t file;
long lf;
//输入文件夹路径
if ((lf=_findfirst(cate_dir.c_str(), &file)) == -1) {
cout<<cate_dir<<" not found!!!"<<endl;
} else {
while(_findnext(lf, &file) == 0) {
//输出文件名
//cout<<file.name<<endl;
if (strcmp(file.name, ".") == 0 || strcmp(file.name, "..") == 0)
continue;
files.push_back(file.name);
}
}
_findclose(lf);
#endif
#ifdef linux
DIR *dir;
struct dirent *ptr;
char base[1000];
if ((dir=opendir(cate_dir.c_str())) == NULL)
{
perror("Open dir error...");
exit(1);
}
while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir
continue;
else if(ptr->d_type == 8) ///file
files.push_back(ptr->d_name);
else if(ptr->d_type == 10) ///link file
continue;
else if(ptr->d_type == 4) ///dir
{
files.push_back(ptr->d_name);
}
}
closedir(dir);
#endif
//排序,按从小到大排序
sort(files.begin(), files.end());
return files;
} | 25.513514 | 104 | 0.496292 | [
"vector"
] |
f50af765423b09f061c8dff2f1152c0c894be839 | 7,939 | cpp | C++ | modules/clipper/clipper/core/hkl_info.cpp | jorgediazjr/dials-dev20191018 | 77d66c719b5746f37af51ad593e2941ed6fbba17 | [
"BSD-3-Clause"
] | null | null | null | modules/clipper/clipper/core/hkl_info.cpp | jorgediazjr/dials-dev20191018 | 77d66c719b5746f37af51ad593e2941ed6fbba17 | [
"BSD-3-Clause"
] | null | null | null | modules/clipper/clipper/core/hkl_info.cpp | jorgediazjr/dials-dev20191018 | 77d66c719b5746f37af51ad593e2941ed6fbba17 | [
"BSD-3-Clause"
] | 1 | 2020-02-04T15:39:06.000Z | 2020-02-04T15:39:06.000Z | /* hkl_info.cpp: class file for hkl_info class + children */
//C Copyright (C) 2000-2004 Kevin Cowtan and University of York
//C Copyright (C) 2000-2005 Kevin Cowtan and University of York
//L
//L This library is free software and is distributed under the terms
//L and conditions of version 2.1 of the GNU Lesser General Public
//L Licence (LGPL) with the following additional clause:
//L
//L `You may also combine or link a "work that uses the Library" to
//L produce a work containing portions of the Library, and distribute
//L that work under terms of your choice, provided that you give
//L prominent notice with each copy of the work that the specified
//L version of the Library is used in it, and that you include or
//L provide public access to the complete corresponding
//L machine-readable source code for the Library including whatever
//L changes were used in the work. (i.e. If you make changes to the
//L Library you must distribute those, but you do not need to
//L distribute source or object code to those portions of the work
//L not covered by this licence.)'
//L
//L Note that this clause grants an additional right and does not impose
//L any additional restriction, and so does not affect compatibility
//L with the GNU General Public Licence (GPL). If you wish to negotiate
//L other terms, please contact the maintainer.
//L
//L You can redistribute it and/or modify the library under the terms of
//L the GNU Lesser General Public License as published by the Free Software
//L Foundation; either version 2.1 of the License, or (at your option) any
//L later version.
//L
//L This library is distributed in the hope that it will be useful, but
//L WITHOUT ANY WARRANTY; without even the implied warranty of
//L MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//L Lesser General Public License for more details.
//L
//L You should have received a copy of the CCP4 licence and/or GNU
//L Lesser General Public License along with this library; if not, write
//L to the CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK.
//L The GNU Lesser General Public can also be obtained by writing to the
//L Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
//L MA 02111-1307 USA
#include "hkl_info.h"
namespace clipper {
Message_fatal message_recip_asu_error( "HKL_info: find_sym reciprocal space ASU error" );
Message_ctor message_ctor_hkl_info( " [HKL_info: constructed]" );
// methods for 'HKL_info'
// private methods:
/*! Update all the lookup tables to be consistent with the modified
reflection list */
void HKL_info::update_hkl_list() {
lookup.init( hkl );
hkl_class_lookup.resize( num_reflections() );
invresolsq_lookup.resize( num_reflections() );
invresolsq_range_ = Range<ftype>();
for ( int i = 0; i < num_reflections(); i++ ) {
hkl_class_lookup[i] = spacegroup_.hkl_class( hkl_of( i ) );
invresolsq_lookup[i] = hkl_of( i ).invresolsq( cell_ );
invresolsq_range_.include( invresolsq_lookup[i] );
}
}
// public methods:
// constructors/destructor
HKL_info::HKL_info()
{
Message::message( message_ctor_hkl_info );
}
/*! Construct and initialise HKL_info object. This updates the
spacegroup and cell and clears the reflection list. The resolution
is used as a rejection criterion for reflections - no HKL will be
stored beyond the given limit. Initially there are no reflections in
the reflection list: see generate_hkl_list().
If any of the parameters have null values, the existing values will
be unchanged. The object will only be fully initialised once all
parameters are available.
\param spacegroup The spacegroup.
\param cell The unit cell.
\param resolution The resolution limit. */
HKL_info::HKL_info( const Spacegroup& spacegroup, const Cell& cell, const Resolution& resolution, const bool& generate )
{
init( spacegroup, cell, resolution, generate );
Message::message( message_ctor_hkl_info );
}
/*! Initialise the HKL_info object. This updates the spacegroup and
cell and clears the reflection list. The resolution is used as a
rejection criterion for reflections - no HKL will be stored beyond
the given limit. Initially there are no reflections in the
reflection list: see generate_hkl_list().
If any of the parameters have null values, the existing values will
be unchanged. The object will only be fully initialised once all
parameters are available.
\param spacegroup The spacegroup.
\param cell The unit cell.
\param resolution The resolution limit.
\param generate If true, a reflection list will be generated for an ASU. */
void HKL_info::init( const Spacegroup& spacegroup, const Cell& cell, const Resolution& resolution, const bool& generate )
{
// set spacegroup and cell
spacegroup_ = spacegroup;
cell_ = cell;
resolution_ = resolution;
// check parameters
if ( is_null() ) return;
// Create the intergised symops (grid irrelevent)
Grid g( 24, 24, 24 );
isymop.resize( spacegroup_.num_symops() );
for ( int sym = 0; sym < spacegroup_.num_symops(); sym++ )
isymop[sym] = Isymop( spacegroup_.symop(sym), g );
// reflection lists
hkl.clear();
if ( generate ) generate_hkl_list();
update_hkl_list();
}
/*! \return true if the object has not been initalised. */
bool HKL_info::is_null() const
{ return ( spacegroup_.is_null() || cell_.is_null() || resolution_.is_null() ); }
/*! Using current cell, spacegroup, resolution. */
void HKL_info::generate_hkl_list()
{
std::vector<HKL> add;
// make a reflection list for the given cell, symm and resolution
/* TO MAKE A BOX TO HOLD A SPHERE IN REAL OR RECIPROCAL SPACE
In reciprocal space, use the real space cell dimension / resolution
In real space, use the recip space dimension * radius */
HKL rfl;
int hmax = int(cell_.descr().a()/resolution_.limit());
int kmax = int(cell_.descr().b()/resolution_.limit());
int lmax = int(cell_.descr().c()/resolution_.limit());
ftype s_lim = resolution_.invresolsq_limit();
// make a list of valid reflections
for (rfl.h()=-hmax; rfl.h()<=hmax; rfl.h()++)
for (rfl.k()=-kmax; rfl.k()<=kmax; rfl.k()++)
for (rfl.l()=-lmax; rfl.l()<=lmax; rfl.l()++)
if ( spacegroup_.recip_asu(rfl) && rfl.invresolsq(cell_) < s_lim &&
!( spacegroup_.hkl_class(rfl).sys_abs() ) ) add.push_back(rfl);
// update the reflection data lists
hkl.clear();
add_hkl_list( add );
}
/*! The new HKLs are transformed to the default reciprocal ASU, and
added to the reflection list. Duplicates and reflections outside the
resoluution limit are ignored. Then the fast lookup tables for HKL,
invresolsq, and reflection class are rebuilt.
\param add The list of new reflections to add. */
void HKL_info::add_hkl_list( const std::vector<HKL>& add ) {
HKL equiv; int sym; bool friedel;
for ( int i = 0; i < add.size(); i++ ) {
if ( add[i].invresolsq( cell_ ) <= resolution_.invresolsq_limit() ) {
equiv = find_sym( add[i], sym, friedel );
if ( lookup.index_of( equiv ) < 0 ) hkl.push_back( equiv );
}
}
update_hkl_list();
}
/*! Returns the index of the reflection, the sym no. and Friedel flag.
\internal */
HKL HKL_info::find_sym( const HKL& rfl, int& sym, bool& friedel ) const
{
// find the symmetry operator mapping hkl into the reflection
// list and determine the friedel flag
HKL equiv;
// now find the symop which gives a reflection from the list
for (sym = 0; sym < spacegroup_.num_primops(); sym++) {
equiv = rfl.transform(isymop[sym]);
if ( spacegroup_.recip_asu(equiv) ) { friedel = false; return equiv; }
equiv = -equiv;
if ( spacegroup_.recip_asu(equiv) ) { friedel = true ; return equiv; }
}
Message::message( message_recip_asu_error );
return equiv;
}
void HKL_info::debug() const
{
std::cout << "Num reflns " << hkl.size() << "\n";
}
} // namespace clipper
| 37.804762 | 121 | 0.7147 | [
"object",
"vector",
"transform"
] |
f50e9062d2bfbbf82d69f111fbeb690da18f35f5 | 93,600 | cpp | C++ | src/terminal/Screen.cpp | christianparpart/contour | ce8feb1332c3cc71ca22354b62bcceb2dbb511e4 | [
"Apache-2.0"
] | 376 | 2019-08-10T11:55:39.000Z | 2021-07-01T09:44:37.000Z | src/terminal/Screen.cpp | christianparpart/contour | ce8feb1332c3cc71ca22354b62bcceb2dbb511e4 | [
"Apache-2.0"
] | 192 | 2019-09-24T23:07:19.000Z | 2021-07-01T09:45:55.000Z | src/terminal/Screen.cpp | christianparpart/contour | ce8feb1332c3cc71ca22354b62bcceb2dbb511e4 | [
"Apache-2.0"
] | 38 | 2019-09-27T19:53:37.000Z | 2021-07-01T09:47:44.000Z | /**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 <terminal/InputGenerator.h>
#include <terminal/Screen.h>
#include <terminal/VTType.h>
#include <terminal/logging.h>
#include <crispy/App.h>
#include <crispy/Comparison.h>
#include <crispy/algorithm.h>
#include <crispy/escape.h>
#include <crispy/size.h>
#include <crispy/times.h>
#include <crispy/utils.h>
#include <unicode/convert.h>
#include <unicode/emoji_segmenter.h>
#include <unicode/grapheme_segmenter.h>
#include <unicode/utf8.h>
#include <unicode/word_segmenter.h>
#include <range/v3/view.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string_view>
#include <tuple>
#include <variant>
using namespace std::string_view_literals;
using crispy::escape;
using crispy::for_each;
using crispy::times;
using crispy::toHexString;
using gsl::span;
using std::accumulate;
using std::array;
using std::clamp;
using std::distance;
using std::endl;
using std::fill;
using std::function;
using std::get;
using std::holds_alternative;
using std::make_shared;
using std::max;
using std::min;
using std::monostate;
using std::next;
using std::nullopt;
using std::optional;
using std::ostringstream;
using std::pair;
using std::prev;
using std::ref;
using std::rotate;
using std::shared_ptr;
using std::string;
using std::string_view;
using std::tuple;
using std::vector;
namespace terminal
{
namespace
{
namespace views
{
template <typename T>
auto as()
{
return ranges::views::transform([](auto in) { return T(in); });
}
template <typename T>
auto n_times(int n)
{
return ranges::views::ints(0, n) | as<T>();
}
} // namespace views
} // namespace
namespace // {{{ helper
{
std::string vtSequenceParameterString(GraphicsAttributes const& _sgr)
{
std::string output;
auto const sgrSep = [&]() {
if (!output.empty())
output += ';';
};
auto const sgrAdd = [&](unsigned _value) {
sgrSep();
output += std::to_string(_value);
};
auto const sgrAddStr = [&](string_view _value) {
sgrSep();
output += _value;
};
auto const sgrAddSub = [&](unsigned _value) {
output += std::to_string(_value);
};
if (isIndexedColor(_sgr.foregroundColor))
{
auto const colorValue = getIndexedColor(_sgr.foregroundColor);
if (static_cast<unsigned>(colorValue) < 8)
sgrAdd(30 + static_cast<unsigned>(colorValue));
else
{
sgrAdd(38);
sgrAddSub(5);
sgrAddSub(static_cast<unsigned>(colorValue));
}
}
else if (isDefaultColor(_sgr.foregroundColor))
sgrAdd(39);
else if (isBrightColor(_sgr.foregroundColor))
sgrAdd(90 + static_cast<unsigned>(getBrightColor(_sgr.foregroundColor)));
else if (isRGBColor(_sgr.foregroundColor))
{
auto const rgb = getRGBColor(_sgr.foregroundColor);
sgrAdd(38);
sgrAddSub(2);
sgrAddSub(static_cast<unsigned>(rgb.red));
sgrAddSub(static_cast<unsigned>(rgb.green));
sgrAddSub(static_cast<unsigned>(rgb.blue));
}
if (isIndexedColor(_sgr.backgroundColor))
{
auto const colorValue = getIndexedColor(_sgr.backgroundColor);
if (static_cast<unsigned>(colorValue) < 8)
sgrAdd(40 + static_cast<unsigned>(colorValue));
else
{
sgrAdd(48);
sgrAddSub(5);
sgrAddSub(static_cast<unsigned>(colorValue));
}
}
else if (isDefaultColor(_sgr.backgroundColor))
sgrAdd(49);
else if (isBrightColor(_sgr.backgroundColor))
sgrAdd(100 + getBrightColor(_sgr.backgroundColor));
else if (isRGBColor(_sgr.backgroundColor))
{
auto const& rgb = getRGBColor(_sgr.backgroundColor);
sgrAdd(48);
sgrAddSub(2);
sgrAddSub(static_cast<unsigned>(rgb.red));
sgrAddSub(static_cast<unsigned>(rgb.green));
sgrAddSub(static_cast<unsigned>(rgb.blue));
}
if (isRGBColor(_sgr.underlineColor))
{
auto const& rgb = getRGBColor(_sgr.underlineColor);
sgrAdd(58);
sgrAddSub(2);
sgrAddSub(static_cast<unsigned>(rgb.red));
sgrAddSub(static_cast<unsigned>(rgb.green));
sgrAddSub(static_cast<unsigned>(rgb.blue));
}
// TODO: _sgr.styles;
auto constexpr masks = array {
pair { CellFlags::Bold, "1"sv },
pair { CellFlags::Faint, "2"sv },
pair { CellFlags::Italic, "3"sv },
pair { CellFlags::Underline, "4"sv },
pair { CellFlags::Blinking, "5"sv },
pair { CellFlags::Inverse, "7"sv },
pair { CellFlags::Hidden, "8"sv },
pair { CellFlags::CrossedOut, "9"sv },
pair { CellFlags::DoublyUnderlined, "4:2"sv },
pair { CellFlags::CurlyUnderlined, "4:3"sv },
pair { CellFlags::DottedUnderline, "4:4"sv },
pair { CellFlags::DashedUnderline, "4:5"sv },
pair { CellFlags::Framed, "51"sv },
// TODO(impl or completely remove): pair{CellFlags::Encircled, ""sv},
pair { CellFlags::Overline, "53"sv },
};
for (auto const& mask: masks)
if (_sgr.styles & mask.first)
sgrAddStr(mask.second);
return output;
}
class VTWriter
{
public:
// TODO: compare with old sgr value set instead to be more generic in reusing stuff
using Writer = std::function<void(char const*, size_t)>;
explicit VTWriter(Writer writer): writer_ { std::move(writer) } {}
explicit VTWriter(std::ostream& output):
VTWriter { [&](auto d, auto n) {
output.write(d, n);
} }
{
}
explicit VTWriter(std::vector<char>& output):
VTWriter { [&](auto d, auto n) {
output.insert(output.end(), d, d + n);
} }
{
}
void write(char32_t v)
{
flush();
char buf[4];
auto enc = unicode::encoder<char> {};
auto count = distance(buf, enc(v, buf));
write(string_view(buf, count));
}
void write(std::string_view const& _s)
{
flush();
writer_(_s.data(), _s.size());
}
template <typename... Args>
void write(std::string_view const& _s, Args&&... _args)
{
write(fmt::format(_s, std::forward<Args>(_args)...));
}
void flush()
{
if (sgr_.empty())
return;
auto const f = flush(sgr_);
if (sgr_ != lastSGR_)
writer_(f.data(), f.size());
sgr_rewind();
}
string flush(vector<unsigned> const& _sgr)
{
if (_sgr.empty())
return "";
auto const params =
_sgr.size() != 1 || _sgr[0] != 0
? accumulate(begin(_sgr),
end(_sgr),
string {},
[](auto a, auto b) {
return a.empty() ? fmt::format("{}", b) : fmt::format("{};{}", a, b);
})
: string();
return fmt::format("\033[{}m", params);
}
void sgr_add(unsigned n)
{
if (n == 0)
{
sgr_.clear();
sgr_.push_back(n);
currentForegroundColor_ = DefaultColor();
currentBackgroundColor_ = DefaultColor();
currentUnderlineColor_ = DefaultColor();
}
else
{
if (sgr_.empty() || sgr_.back() != n)
sgr_.push_back(n);
if (sgr_.size() == 16)
{
flush();
}
}
}
void sgr_rewind()
{
swap(lastSGR_, sgr_);
sgr_.clear();
}
void sgr_add(GraphicsRendition m) { sgr_add(static_cast<unsigned>(m)); }
void setForegroundColor(Color _color)
{
// if (_color == currentForegroundColor_)
// return;
currentForegroundColor_ = _color;
switch (_color.type())
{
case ColorType::Default: sgr_add(39); break;
case ColorType::Indexed:
if (static_cast<unsigned>(_color.index()) < 8)
sgr_add(30 + static_cast<unsigned>(_color.index()));
else
{
sgr_add(38);
sgr_add(5);
sgr_add(static_cast<unsigned>(_color.index()));
}
break;
case ColorType::Bright: sgr_add(90 + static_cast<unsigned>(getBrightColor(_color))); break;
case ColorType::RGB:
sgr_add(38);
sgr_add(2);
sgr_add(static_cast<unsigned>(_color.rgb().red));
sgr_add(static_cast<unsigned>(_color.rgb().green));
sgr_add(static_cast<unsigned>(_color.rgb().blue));
case ColorType::Undefined: break;
}
}
void setBackgroundColor(Color _color)
{
// if (_color == currentBackgroundColor_)
// return;
currentBackgroundColor_ = _color;
switch (_color.type())
{
case ColorType::Default: sgr_add(49); break;
case ColorType::Indexed:
if (static_cast<unsigned>(_color.index()) < 8)
sgr_add(40 + static_cast<unsigned>(_color.index()));
else
{
sgr_add(48);
sgr_add(5);
sgr_add(static_cast<unsigned>(_color.index()));
}
break;
case ColorType::Bright: sgr_add(100 + static_cast<unsigned>(getBrightColor(_color))); break;
case ColorType::RGB:
sgr_add(48);
sgr_add(2);
sgr_add(static_cast<unsigned>(_color.rgb().red));
sgr_add(static_cast<unsigned>(_color.rgb().green));
sgr_add(static_cast<unsigned>(_color.rgb().blue));
case ColorType::Undefined: break;
}
}
private:
Writer writer_;
std::vector<unsigned> sgr_;
std::stringstream sstr;
std::vector<unsigned> lastSGR_;
Color currentForegroundColor_ = DefaultColor();
Color currentUnderlineColor_ = DefaultColor();
Color currentBackgroundColor_ = DefaultColor();
};
array<Grid<Cell>, 2> emptyGrids(PageSize _size, bool _reflowOnResize, LineCount _maxHistoryLineCount)
{
return array<Grid<Cell>, 2> { Grid<Cell>(_size, _reflowOnResize, _maxHistoryLineCount),
Grid<Cell>(_size, false, LineCount(0)) };
}
} // namespace
// }}}
template <typename EventListener>
Screen<EventListener>::Screen(PageSize _size,
EventListener& _eventListener,
bool _logRaw,
bool _logTrace,
LineCount _maxHistoryLineCount,
ImageSize _maxImageSize,
int _maxImageColorRegisters,
bool _sixelCursorConformance,
ColorPalette _colorPalette,
bool _allowReflowOnResize):
eventListener_ { _eventListener },
logRaw_ { _logRaw },
logTrace_ { _logTrace },
modes_ {},
savedModes_ {},
defaultColorPalette_ { _colorPalette },
colorPalette_ { _colorPalette },
maxImageColorRegisters_ { _maxImageColorRegisters },
maxImageSize_ { _maxImageSize },
maxImageSizeLimit_ { _maxImageSize },
imageColorPalette_(make_shared<SixelColorPalette>(maxImageColorRegisters_, maxImageColorRegisters_)),
imagePool_ { [this](Image const* _image) {
eventListener_.discardImage(*_image);
} },
imageFragments_ {
80lu * 25lu * 8lu, // TODO: make this resource limit configurable
},
sequencer_ { *this, _maxImageSize, colorPalette_.defaultBackground, imageColorPalette_ },
parser_ { ref(sequencer_) },
pageSize_ { _size },
sixelCursorConformance_ { _sixelCursorConformance },
margin_ { Margin::Vertical { {}, pageSize_.lines.as<LineOffset>() - LineOffset(1) },
Margin::Horizontal { {}, pageSize_.columns.as<ColumnOffset>() - ColumnOffset(1) } },
allowReflowOnResize_ { _allowReflowOnResize },
grids_ { emptyGrids(pageSize_, _allowReflowOnResize, _maxHistoryLineCount) },
activeGrid_ { &primaryGrid() },
cursor_ {},
lastCursorPosition_ {},
hyperlinks_ { HyperlinkCache { 1024 } },
respondToTCapQuery_ { false }
{
#if 0
resetHard();
#else
setMode(DECMode::AutoWrap, true);
setMode(DECMode::TextReflow, true);
#endif
}
template <typename T>
unsigned Screen<T>::numericCapability(capabilities::Code _cap) const
{
using namespace capabilities::literals;
switch (_cap)
{
case "li"_tcap: return pageSize_.lines.as<unsigned>();
case "co"_tcap: return pageSize_.columns.as<unsigned>();
case "it"_tcap: return tabWidth_.as<unsigned>();
default: return StaticDatabase::numericCapability(_cap);
}
}
template <typename T>
void Screen<T>::setMaxHistoryLineCount(LineCount _maxHistoryLineCount)
{
primaryGrid().setMaxHistoryLineCount(_maxHistoryLineCount);
}
template <typename T>
void Screen<T>::resizeColumns(ColumnCount _newColumnCount, bool _clear)
{
// DECCOLM / DECSCPP
if (_clear)
{
// Sets the left, right, top and bottom scrolling margins to their default positions.
setTopBottomMargin({}, pageSize_.lines.as<LineOffset>() - LineOffset(1)); // DECSTBM
setLeftRightMargin({}, pageSize_.columns.as<ColumnOffset>() - ColumnOffset(1)); // DECRLM
// Erases all data in page memory
clearScreen();
}
// resets vertical split screen mode (DECLRMM) to unavailable
setMode(DECMode::LeftRightMargin, false); // DECSLRM
// Pre-resize in case the event callback right after is not actually resizing the window
// (e.g. either by choice or because the window manager does not allow that, such as tiling WMs).
auto const newSize = PageSize { pageSize_.lines, _newColumnCount };
resize(newSize);
eventListener_.resizeWindow(newSize);
}
template <typename T>
void Screen<T>::resize(PageSize _newSize)
{
// NOTE: This will only resize the currently active buffer.
// Any other buffer will be resized when it is switched to.
auto const oldCursorPos = cursor_.position;
cursor_.position = activeGrid_->resize(_newSize, oldCursorPos, wrapPending_);
if (_newSize.columns > pageSize_.columns)
wrapPending_ = false;
pageSize_ = _newSize;
// Reset margin to their default.
margin_ = Margin { Margin::Vertical { {}, _newSize.lines.as<LineOffset>() - 1 },
Margin::Horizontal { {}, _newSize.columns.as<ColumnOffset>() - 1 } };
applyPageSizeToCurrentBuffer();
}
template <typename T>
void Screen<T>::applyPageSizeToCurrentBuffer()
{
// Ensure correct screen buffer size for the buffer we've just switched to.
cursor_.position = activeGrid_->resize(pageSize_, cursor_.position, wrapPending_);
cursor_.position = clampCoordinate(cursor_.position);
// update last-cursor position & iterators
lastCursorPosition_ = cursor_.position;
lastCursorPosition_ = clampCoordinate(lastCursorPosition_);
// truncating tabs
while (!tabs_.empty() && tabs_.back() >= pageSize_.columns.as<ColumnOffset>())
tabs_.pop_back();
// TODO: find out what to do with DECOM mode. Reset it to?
#if 0
dumpState("after resize", std::cout);
fmt::print("applyPageSizeToCurrentBuffer: cursor pos before: {} after: {}\n", oldCursorPos, cursor_.position);
#endif
verifyState();
}
template <typename T>
void Screen<T>::verifyState() const
{
#if !defined(NDEBUG)
Require(activeGrid_->pageSize() == pageSize_);
Require(*cursor_.position.column < *pageSize_.columns);
Require(*cursor_.position.line < *pageSize_.lines);
Require(tabs_.empty() || tabs_.back() < pageSize_.columns.as<ColumnOffset>());
if (*pageSize_.lines != static_cast<int>(grid().mainPage().size()))
fail(fmt::format("Line count mismatch. Actual line count {} but should be {}.",
grid().mainPage().size(),
pageSize_.lines));
// verify cursor positions
[[maybe_unused]] auto const clampedCursorPos = clampToScreen(cursor_.position);
if (cursor_.position != clampedCursorPos)
fail(fmt::format("Cursor {} does not match clamp to screen {}.", cursor_, clampedCursorPos));
// FIXME: the above triggers on tmux vertical screen split (cursor.column off-by-one)
#endif
}
template <typename T>
void Screen<T>::fail(std::string const& _message) const
{
dumpState(_message, std::cerr);
abort();
}
template <typename T>
void Screen<T>::write(std::string_view _data)
{
if (_data.empty())
return;
#if defined(LIBTERMINAL_LOG_RAW)
if (ScreenRawOutputLog)
LOGSTORE(ScreenRawOutputLog)("Received bytes: \"{}\"", escape(_data));
#endif
parser_.parseFragment(_data);
if (modes_.enabled(DECMode::BatchedRendering))
return;
eventListener_.screenUpdated();
}
template <typename T>
void Screen<T>::write(std::u32string_view _data)
{
#if defined(LIBTERMINAL_LOG_RAW)
if (ScreenRawOutputLog)
LOGSTORE(ScreenRawOutputLog)("Received bytes: \"{}\"", escape(unicode::convert_to<char>(_data)));
#endif
parser_.parseFragment(_data);
if (modes_.enabled(DECMode::BatchedRendering))
return;
eventListener_.screenUpdated();
}
template <typename T>
void Screen<T>::writeText(string_view _chars)
{
//#define LIBTERMINAL_BULK_TEXT_OPTIMIZATION 1
#if defined(LIBTERMINAL_BULK_TEXT_OPTIMIZATION)
if (margin_ == pageSize_)
{
#if defined(LIBTERMINAL_LOG_TRACE)
if (VTParserTraceLog)
LOGSTORE(VTParserTraceLog)("text: \"{}\"", _chars);
#endif
// XXX
// Case B) AutoWrap disabled
// 1. write (charsLeft - 1) chars, then last char of range
// Case A) AutoWrap enabled
// 1. write charsCount chars
// 2. reset remaining columns in last line with cursor.SGR
// 3. scroll up accordingly
// 4. udpate cursor position
// 5. if line is wrappable, then update consecutive line flags with Wrapped
// TODO: make sure handle the grapheme cluster case?
// auto const lastChar = sequencer_.precedingGraphicCharacter();
// auto const isAsciiBreakable = lastChar < 128 && _chars.front() < 128; // NB: This is an
// optimization for US-ASCII text versus grapheme cluster segmentation.
auto constexpr ASCII_Width = 1;
if (isModeEnabled(DECMode::AutoWrap))
{
// Case A)
if (wrapPending_)
linefeed();
auto const marginColumnCount = margin_.horizontal.length();
auto const writeCharsToLine =
[this, ASCII_Width, marginColumnCount](
string_view text, LineOffset lineOffset, ColumnOffset columnOffset) noexcept -> size_t {
// fmt::print("writeCharsToLine({}:{}): \"{}\"\n", lineOffset, columnOffset, text);
auto const columnsAvailable = marginColumnCount - *columnOffset;
auto const cutoff = std::min(columnsAvailable.as<size_t>(), text.size());
auto const charsToWrite = text.substr(0, cutoff);
Line<Cell>& line = grid().lineAt(lineOffset);
line.fill(columnOffset, cursor_.graphicsRendition, charsToWrite);
return cutoff;
};
if (*cursor_.position.column + static_cast<int>(_chars.size()) < *marginColumnCount)
{
// fill line partially
writeCharsToLine(_chars, cursor_.position.line, cursor_.position.column);
cursor_.position.column += ColumnOffset::cast_from(_chars.size());
}
else if ((cursor_.position.column + static_cast<int>(_chars.size())).as<ColumnCount>()
== marginColumnCount)
{
// fill line up to the right margin
writeCharsToLine(_chars, cursor_.position.line, cursor_.position.column);
cursor_.position.column = boxed_cast<ColumnOffset>(marginColumnCount - 1);
wrapPending_ = true;
}
else
{
// fill more than one line
// TODO: Ensure Wrappable|Wrapped line flag is set accordingly.
auto const n = writeCharsToLine(_chars, cursor_.position.line, cursor_.position.column);
_chars.remove_prefix(n);
bool const lineWrappable = currentLine().wrappable();
linefeed(margin_.horizontal.from);
currentLine().setFlag(LineFlags::Wrappable | LineFlags::Wrapped, lineWrappable);
if (!_chars.empty())
{
// middle lines
while (_chars.size() > marginColumnCount.as<size_t>())
{
writeCharsToLine(_chars, cursor_.position.line, ColumnOffset(0));
_chars.remove_prefix(marginColumnCount.as<size_t>());
linefeed(margin_.horizontal.from);
currentLine().setFlag(LineFlags::Wrappable | LineFlags::Wrapped, lineWrappable);
}
// tail line
writeCharsToLine(_chars, cursor_.position.line, ColumnOffset(0));
}
if (_chars.size() == marginColumnCount.as<size_t>())
{
wrapPending_ = true;
cursor_.position.column = marginColumnCount.as<ColumnOffset>() - 1;
}
else
{
cursor_.position.column = ColumnOffset::cast_from(_chars.size());
// reset remaining columns in last line with cursor.SGR
Line<Cell>& line = grid().lineAt(cursor_.position.line);
line.fill(cursor_.position.column, cursor_.graphicsRendition, {});
}
}
}
else
{
// Case B - AutoWrap disabled
auto const topLineColumnsAvailable =
pageSize_.columns - cursor_.position.column.as<ColumnCount>();
char const* s = _chars.data();
auto const n = min(_chars.size(), topLineColumnsAvailable.as<size_t>());
auto const* e = s + n;
auto t = &useCurrentCell();
for (; s != e; s++, t++)
t->write(
cursor_.graphicsRendition, static_cast<char32_t>(*s), ASCII_Width, cursor_.hyperlink);
if (s + 1 != e)
(t - 1)->setCharacter(_chars.back(), 1);
cursor_.position.column = min(cursor_.position.column + ColumnOffset::cast_from(n),
pageSize_.columns.as<ColumnOffset>() - 1);
}
// TODO: Call this but with range range of point.
// markCellDirty(oldCursorPos, newCursorPos);
// XXX: But even if we keep it but enable the setReportDamage(bool),
// then this should still be cheap as it's only invoked when something
// is actually selected.
// eventListener_.markRegionDirty(
// cursor_.position.line,
// cursor_.position.column
// );
sequencer_.resetInstructionCounter();
return;
}
#endif
for (char const ch: _chars)
writeText(static_cast<char32_t>(ch));
}
template <typename T>
void Screen<T>::writeText(char32_t _char)
{
#if defined(LIBTERMINAL_LOG_TRACE)
if (VTParserTraceLog)
LOGSTORE(VTParserTraceLog)("text: \"{}\"", unicode::convert_to<char>(_char));
#endif
if (wrapPending_ && cursor_.autoWrap) // && !isModeEnabled(DECMode::TextReflow))
{
bool const lineWrappable = currentLine().wrappable();
linefeed(margin_.horizontal.from);
if (lineWrappable)
currentLine().setFlag(LineFlags::Wrappable | LineFlags::Wrapped, true);
}
char32_t const codepoint = cursor_.charsets.map(_char);
auto const lastChar = sequencer_.precedingGraphicCharacter();
auto const isAsciiBreakable =
lastChar < 128
&& codepoint
< 128; // NB: This is an optimization for US-ASCII text versus grapheme cluster segmentation.
if (!lastChar || isAsciiBreakable || unicode::grapheme_segmenter::breakable(lastChar, codepoint))
{
writeCharToCurrentAndAdvance(codepoint);
}
else
{
auto const extendedWidth = usePreviousCell().appendCharacter(codepoint);
if (extendedWidth > 0)
clearAndAdvance(extendedWidth);
eventListener_.markCellDirty(lastCursorPosition_);
}
sequencer_.resetInstructionCounter();
}
template <typename T>
void Screen<T>::writeCharToCurrentAndAdvance(char32_t _character) noexcept
{
Line<Cell>& line = grid().lineAt(cursor_.position.line);
Cell& cell = line.useCellAt(cursor_.position.column);
#if defined(LINE_AVOID_CELL_RESET)
bool const consecutiveTextWrite = sequencer_.instructionCounter() == 1;
if (!consecutiveTextWrite)
cell.reset();
#endif
cell.write(cursor_.graphicsRendition, _character, unicode::width(_character), cursor_.hyperlink);
lastCursorPosition_ = cursor_.position;
#if 1
clearAndAdvance(cell.width());
#else
bool const cursorInsideMargin = isModeEnabled(DECMode::LeftRightMargin) && isCursorInsideMargins();
auto const cellsAvailable = cursorInsideMargin ? *(margin_.horizontal.to - cursor_.position.column) - 1
: *pageSize_.columns - *cursor_.position.column - 1;
auto const n = min(cell.width(), cellsAvailable);
if (n == cell.width())
{
assert(n > 0);
cursor_.position.column++;
for (int i = 1; i < n; ++i)
{
currentCell().reset(cursor_.graphicsRendition, cursor_.hyperlink);
cursor_.position.column++;
}
}
else if (cursor_.autoWrap)
wrapPending_ = true;
#endif
// TODO: maybe move selector API up? So we can make this call conditional,
// and only call it when something is selected?
// Alternatively we could add a boolean to make this callback
// conditional, something like: setReportDamage(bool);
// The latter is probably the easiest.
eventListener_.markCellDirty(cursor_.position);
}
template <typename T>
void Screen<T>::clearAndAdvance(int _offset) noexcept
{
if (_offset == 0)
return;
bool const cursorInsideMargin = isModeEnabled(DECMode::LeftRightMargin) && isCursorInsideMargins();
auto const cellsAvailable = cursorInsideMargin ? *(margin_.horizontal.to - cursor_.position.column) - 1
: *pageSize_.columns - *cursor_.position.column - 1;
auto const n = min(_offset, cellsAvailable);
if (n == _offset)
{
cursor_.position.column++;
for (int i = 1; i < n; ++i)
{
useCurrentCell().reset(cursor_.graphicsRendition, cursor_.hyperlink);
cursor_.position.column++;
}
}
else if (cursor_.autoWrap)
{
wrapPending_ = true;
}
}
template <typename T>
std::string Screen<T>::screenshot(function<string(LineOffset)> const& _postLine) const
{
auto result = std::stringstream {};
auto writer = VTWriter(result);
for (int const line: ranges::views::iota(-unbox<int>(historyLineCount()), *pageSize_.lines))
{
for (int const col: ranges::views::iota(0, *pageSize_.columns))
{
Cell const& cell = at(LineOffset(line), ColumnOffset(col));
if (cell.styles() & CellFlags::Bold)
writer.sgr_add(GraphicsRendition::Bold);
else
writer.sgr_add(GraphicsRendition::Normal);
// TODO: other styles (such as underline, ...)?
writer.setForegroundColor(cell.foregroundColor());
writer.setBackgroundColor(cell.backgroundColor());
if (!cell.codepointCount())
writer.write(U' ');
else
writer.write(cell.toUtf8());
}
writer.sgr_add(GraphicsRendition::Reset);
if (_postLine)
writer.write(_postLine(LineOffset(line)));
writer.write('\r');
writer.write('\n');
}
return result.str();
}
template <typename T>
optional<LineOffset> Screen<T>::findMarkerUpwards(LineOffset _startLine) const
{
// XXX _startLine is an absolute history line coordinate
if (isAlternateScreen())
return nullopt;
if (*_startLine <= -*historyLineCount())
return nullopt;
_startLine = min(_startLine, boxed_cast<LineOffset>(pageSize_.lines - 1));
for (LineOffset i = _startLine - 1; i >= -boxed_cast<LineOffset>(historyLineCount()); --i)
if (grid().lineAt(i).marked())
return { i };
return nullopt;
}
template <typename T>
optional<LineOffset> Screen<T>::findMarkerDownwards(LineOffset _lineOffset) const
{
if (!isPrimaryScreen())
return nullopt;
auto const top = std::clamp(_lineOffset,
-boxed_cast<LineOffset>(historyLineCount()),
+boxed_cast<LineOffset>(pageSize_.lines) - 1);
auto const bottom = LineOffset(0);
for (LineOffset i = top + 1; i <= bottom; ++i)
if (grid().lineAt(i).marked())
return { i };
return nullopt;
}
// {{{ tabs related
template <typename T>
void Screen<T>::clearAllTabs()
{
tabs_.clear();
}
template <typename T>
void Screen<T>::clearTabUnderCursor()
{
// populate tabs vector in case of default tabWidth is used (until now).
if (tabs_.empty() && *tabWidth_ != 0)
for (auto column = tabWidth_.as<ColumnOffset>(); column < pageSize_.columns.as<ColumnOffset>();
column += tabWidth_.as<ColumnOffset>())
tabs_.emplace_back(column - 1);
// erase the specific tab underneath
for (auto i = begin(tabs_); i != end(tabs_); ++i)
{
if (*i == realCursorPosition().column)
{
tabs_.erase(i);
break;
}
}
}
template <typename T>
void Screen<T>::setTabUnderCursor()
{
tabs_.emplace_back(realCursorPosition().column);
sort(begin(tabs_), end(tabs_));
}
// }}}
// {{{ others
template <typename T>
void Screen<T>::saveCursor()
{
// https://vt100.net/docs/vt510-rm/DECSC.html
savedCursor_ = cursor_;
}
template <typename T>
void Screen<T>::restoreCursor()
{
// https://vt100.net/docs/vt510-rm/DECRC.html
restoreCursor(savedCursor_);
setMode(DECMode::AutoWrap, savedCursor_.autoWrap);
setMode(DECMode::Origin, savedCursor_.originMode);
}
template <typename T>
void Screen<T>::restoreCursor(Cursor const& _savedCursor)
{
wrapPending_ = false;
cursor_ = _savedCursor;
cursor_.position = clampCoordinate(_savedCursor.position);
verifyState();
}
template <typename T>
void Screen<T>::resetSoft()
{
// https://vt100.net/docs/vt510-rm/DECSTR.html
setMode(DECMode::BatchedRendering, false);
setMode(DECMode::TextReflow, allowReflowOnResize_);
setGraphicsRendition(GraphicsRendition::Reset); // SGR
savedCursor_.position = {}; // DECSC (Save cursor state)
setMode(DECMode::VisibleCursor, true); // DECTCEM (Text cursor enable)
setMode(DECMode::Origin, false); // DECOM
setMode(AnsiMode::KeyboardAction, false); // KAM
setMode(DECMode::AutoWrap, false); // DECAWM
setMode(AnsiMode::Insert, false); // IRM
setMode(DECMode::UseApplicationCursorKeys, false); // DECCKM (Cursor keys)
setTopBottomMargin({}, pageSize_.lines.as<LineOffset>() - LineOffset(1)); // DECSTBM
setLeftRightMargin({}, pageSize_.columns.as<ColumnOffset>() - ColumnOffset(1)); // DECRLM
cursor_.hyperlink = {};
colorPalette_ = defaultColorPalette_;
// TODO: DECNKM (Numeric keypad)
// TODO: DECSCA (Select character attribute)
// TODO: DECNRCM (National replacement character set)
// TODO: GL, GR (G0, G1, G2, G3)
// TODO: DECAUPSS (Assign user preference supplemental set)
// TODO: DECSASD (Select active status display)
// TODO: DECKPM (Keyboard position mode)
// TODO: DECPCTERM (PCTerm mode)
}
template <typename T>
void Screen<T>::resetHard()
{
setBuffer(ScreenType::Main);
modes_ = Modes {};
setMode(DECMode::AutoWrap, true);
setMode(DECMode::TextReflow, allowReflowOnResize_);
clearAllTabs();
for (auto& grid: grids_)
grid.reset();
cursor_ = {};
lastCursorPosition_ = cursor_.position;
margin_ = Margin { Margin::Vertical { {}, pageSize_.lines.as<LineOffset>() - 1 },
Margin::Horizontal { {}, pageSize_.columns.as<ColumnOffset>() - 1 } };
colorPalette_ = defaultColorPalette_;
verifyState();
eventListener_.hardReset();
}
template <typename T>
void Screen<T>::moveCursorTo(LineOffset _line, ColumnOffset _column)
{
auto const [line, column] = [&]() {
if (!cursor_.originMode)
return pair { _line, _column };
else
return pair { _line + margin_.vertical.from, _column + margin_.horizontal.from };
}();
wrapPending_ = false;
cursor_.position.line = clampedLine(line);
cursor_.position.column = clampedColumn(column);
}
template <typename T>
void Screen<T>::setBuffer(ScreenType _type)
{
if (bufferType() == _type)
return;
switch (_type)
{
case ScreenType::Main:
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::Default);
activeGrid_ = &primaryGrid();
break;
case ScreenType::Alternate:
if (isModeEnabled(DECMode::MouseAlternateScroll))
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::ApplicationCursorKeys);
else
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::NormalCursorKeys);
activeGrid_ = &alternateGrid();
break;
}
screenType_ = _type;
// Reset wrapPending-flag when switching buffer.
wrapPending_ = false;
// Reset last-cursor position.
lastCursorPosition_ = cursor_.position;
// Ensure correct screen buffer size for the buffer we've just switched to.
applyPageSizeToCurrentBuffer();
eventListener_.bufferChanged(_type);
}
template <typename T>
void Screen<T>::linefeed(ColumnOffset _newColumn)
{
wrapPending_ = false;
cursor_.position.column = _newColumn;
if (*realCursorPosition().line == *margin_.vertical.to)
{
// TODO(perf) if we know that we text is following this LF
// (i.e. parser state will be ground state),
// then invoke scrollUpUninitialized instead
// and make sure the subsequent text write will
// possibly also reset remaining grid cells in that line
// if the incoming text did not write to the full line
scrollUp(LineCount(1), {}, margin_);
}
else
{
// using moveCursorTo() would embrace code reusage,
// but due to the fact that it's fully recalculating iterators,
// it may be faster to just incrementally update them.
// moveCursorTo({logicalCursorPosition().line + 1, margin_.horizontal.from});
cursor_.position.line++;
}
}
template <typename T>
void Screen<T>::scrollUp(LineCount n, GraphicsAttributes sgr, Margin margin)
{
auto const scrollCount = grid().scrollUp(n, sgr, margin);
eventListener_.onBufferScrolled(scrollCount);
}
template <typename T>
void Screen<T>::scrollUp(LineCount _n, Margin _margin)
{
scrollUp(_n, cursor().graphicsRendition, _margin);
}
template <typename T>
void Screen<T>::scrollDown(LineCount _n, Margin _margin)
{
grid().scrollDown(_n, cursor().graphicsRendition, _margin);
}
template <typename T>
void Screen<T>::setCurrentColumn(ColumnOffset _n)
{
auto const col = cursor_.originMode ? margin_.horizontal.from + _n : _n;
auto const clampedCol = min(col, boxed_cast<ColumnOffset>(pageSize_.columns) - 1);
wrapPending_ = false;
cursor_.position.column = clampedCol;
}
template <typename T>
string Screen<T>::renderMainPageText() const
{
return grid().renderMainPageText();
}
// }}}
// {{{ ops
template <typename T>
void Screen<T>::linefeed()
{
if (isModeEnabled(AnsiMode::AutomaticNewLine))
linefeed(margin_.horizontal.from);
else
linefeed(realCursorPosition().column);
}
template <typename T>
void Screen<T>::backspace()
{
if (cursor_.position.column.value)
cursor_.position.column--;
}
template <typename T>
void Screen<T>::deviceStatusReport()
{
reply("\033[0n");
}
template <typename T>
void Screen<T>::reportCursorPosition()
{
reply("\033[{};{}R", logicalCursorPosition().line + 1, logicalCursorPosition().column + 1);
}
template <typename T>
void Screen<T>::reportExtendedCursorPosition()
{
auto const pageNum = 1;
reply("\033[{};{};{}R", logicalCursorPosition().line + 1, logicalCursorPosition().column + 1, pageNum);
}
template <typename T>
void Screen<T>::selectConformanceLevel(VTType _level)
{
// Don't enforce the selected conformance level, just remember it.
terminalId_ = _level;
}
template <typename T>
void Screen<T>::sendDeviceAttributes()
{
// See https://vt100.net/docs/vt510-rm/DA1.html
auto const id = [&]() -> string_view {
switch (terminalId_)
{
case VTType::VT100: return "1";
case VTType::VT220:
case VTType::VT240: return "62";
case VTType::VT320:
case VTType::VT330:
case VTType::VT340: return "63";
case VTType::VT420: return "64";
case VTType::VT510:
case VTType::VT520:
case VTType::VT525: return "65";
}
return "1"; // Should never be reached.
}();
auto const attrs = to_params(DeviceAttributes::AnsiColor | DeviceAttributes::AnsiTextLocator
| DeviceAttributes::CaptureScreenBuffer | DeviceAttributes::Columns132 |
// TODO: DeviceAttributes::NationalReplacementCharacterSets |
DeviceAttributes::RectangularEditing |
// TODO: DeviceAttributes::SelectiveErase |
DeviceAttributes::SixelGraphics |
// TODO: DeviceAttributes::TechnicalCharacters |
DeviceAttributes::UserDefinedKeys);
reply("\033[?{};{}c", id, attrs);
}
template <typename T>
void Screen<T>::sendTerminalId()
{
// Note, this is "Secondary DA".
// It requests for the terminalID
// terminal protocol type
auto const Pp = static_cast<unsigned>(terminalId_);
// version number
// TODO: (PACKAGE_VERSION_MAJOR * 100 + PACKAGE_VERSION_MINOR) * 100 + PACKAGE_VERSION_MICRO
auto constexpr Pv =
(LIBTERMINAL_VERSION_MAJOR * 100 + LIBTERMINAL_VERSION_MINOR) * 100 + LIBTERMINAL_VERSION_PATCH;
// ROM cardridge registration number (always 0)
auto constexpr Pc = 0;
reply("\033[>{};{};{}c", Pp, Pv, Pc);
}
template <typename T>
void Screen<T>::clearToEndOfScreen()
{
clearToEndOfLine();
for (auto const lineOffset:
ranges::views::iota(cursor_.position.line.as<int>() + 1, pageSize_.lines.as<int>()))
{
Line<Cell>& line = grid().lineAt(LineOffset::cast_from(lineOffset));
line.reset(grid().defaultLineFlags(), cursor_.graphicsRendition);
}
}
template <typename T>
void Screen<T>::clearToBeginOfScreen()
{
clearToBeginOfLine();
for (auto const lineOffset: ranges::views::iota(0, *cursor_.position.line))
{
Line<Cell>& line = grid().lineAt(LineOffset::cast_from(lineOffset));
line.reset(grid().defaultLineFlags(), cursor_.graphicsRendition);
}
}
template <typename T>
void Screen<T>::clearScreen()
{
// Instead of *just* clearing the screen, and thus, losing potential important content,
// we scroll up by RowCount number of lines, so move it all into history, so the user can scroll
// up in case the content is still needed.
scrollUp(pageSize_.lines);
}
template <typename T>
void Screen<T>::clearScrollbackBuffer()
{
primaryGrid().clearHistory();
alternateGrid().clearHistory();
eventListener_.scrollbackBufferCleared();
}
template <typename T>
void Screen<T>::eraseCharacters(ColumnCount _n)
{
// Spec: https://vt100.net/docs/vt510-rm/ECH.html
// It's not clear from the spec how to perform erase when inside margin and number of chars to be erased
// would go outside margins.
// TODO: See what xterm does ;-)
// erase characters from current colum to the right
auto const columnsAvailable = pageSize_.columns - boxed_cast<ColumnCount>(realCursorPosition().column);
auto const n = unbox<long>(clamp(_n, ColumnCount(1), columnsAvailable));
auto& line = grid().lineAt(cursor_.position.line);
for (int i = 0; i < n; ++i)
line.useCellAt(cursor_.position.column + i).reset(cursor_.graphicsRendition);
}
template <typename T>
void Screen<T>::clearToEndOfLine()
{
Cell* i = &at(cursor_.position);
Cell* e = i + (pageSize_.columns.as<int>() - cursor_.position.column.as<int>());
while (i != e)
{
i->reset(cursor_.graphicsRendition);
++i;
}
auto const line = cursor_.position.line;
auto const left = cursor_.position.column;
auto const right = boxed_cast<ColumnOffset>(pageSize_.columns - 1);
auto const area = Rect { Top(*line), Left(*left), Bottom(*line), Right(*right) };
eventListener_.markRegionDirty(area);
}
template <typename T>
void Screen<T>::clearToBeginOfLine()
{
Cell* i = &at(cursor_.position.line, ColumnOffset(0));
Cell* e = i + cursor_.position.column.as<int>() + 1;
while (i != e)
{
i->reset(cursor_.graphicsRendition);
++i;
}
}
template <typename T>
void Screen<T>::clearLine()
{
Cell* i = &at(cursor_.position.line, ColumnOffset(0));
Cell* e = i + pageSize_.columns.as<int>();
while (i != e)
{
i->reset(cursor_.graphicsRendition);
++i;
}
auto const line = cursor_.position.line;
auto const left = ColumnOffset(0);
auto const right = boxed_cast<ColumnOffset>(pageSize_.columns - 1);
auto const area = Rect { Top(*line), Left(*left), Bottom(*line), Right(*right) };
eventListener_.markRegionDirty(area);
}
template <typename T>
void Screen<T>::moveCursorToNextLine(LineCount _n)
{
moveCursorTo(logicalCursorPosition().line + _n.as<LineOffset>(), ColumnOffset(0));
}
template <typename T>
void Screen<T>::moveCursorToPrevLine(LineCount _n)
{
auto const n = min(_n.as<LineOffset>(), logicalCursorPosition().line);
moveCursorTo(logicalCursorPosition().line - n, ColumnOffset(0));
}
template <typename T>
void Screen<T>::insertCharacters(ColumnCount _n)
{
if (isCursorInsideMargins())
insertChars(realCursorPosition().line, _n);
}
/// Inserts @p _n characters at given line @p _lineNo.
template <typename T>
void Screen<T>::insertChars(LineOffset _lineNo, ColumnCount _n)
{
auto const n = min(*_n, *margin_.horizontal.to - *logicalCursorPosition().column + 1);
auto column0 = grid().lineAt(_lineNo).begin() + *realCursorPosition().column;
auto column1 = grid().lineAt(_lineNo).begin() + *margin_.horizontal.to - n + 1;
auto column2 = grid().lineAt(_lineNo).begin() + *margin_.horizontal.to + 1;
rotate(column0, column1, column2);
for (Cell& cell: grid().lineAt(_lineNo).useRange(cursor_.position.column.as<ColumnOffset>(),
ColumnCount::cast_from(n)))
{
cell.write(cursor_.graphicsRendition, L' ', 1);
}
grid().lineAt(_lineNo).markUsedFirst(_n);
}
template <typename T>
void Screen<T>::insertLines(LineCount _n)
{
if (isCursorInsideMargins())
{
scrollDown(
_n,
Margin { Margin::Vertical { cursor_.position.line, margin_.vertical.to }, margin_.horizontal });
}
}
template <typename T>
void Screen<T>::insertColumns(ColumnCount _n)
{
if (isCursorInsideMargins())
for (auto lineNo = margin_.vertical.from; lineNo <= margin_.vertical.to; ++lineNo)
insertChars(lineNo, _n);
}
template <typename T>
void Screen<T>::copyArea(Rect _sourceArea, int _page, Coordinate _targetTopLeft, int _targetPage)
{
(void) _page;
(void) _targetPage;
// The space at https://vt100.net/docs/vt510-rm/DECCRA.html states:
// "If Pbs is greater than Pts, // or Pls is greater than Prs, the terminal ignores DECCRA."
//
// However, the first part "Pbs is greater than Pts" does not make sense.
if (*_sourceArea.bottom < *_sourceArea.top || *_sourceArea.right < *_sourceArea.left)
return;
if (*_sourceArea.top == *_targetTopLeft.line && *_sourceArea.left == *_targetTopLeft.column)
// Copy to its own location => no-op.
return;
auto const [x0, xInc, xEnd] = [&]() {
if (*_targetTopLeft.column > *_sourceArea.left) // moving right
return std::tuple { *_sourceArea.right - *_sourceArea.left, -1, -1 };
else
return std::tuple { 0, +1, *_sourceArea.right - *_sourceArea.left + 1 };
}();
auto const [y0, yInc, yEnd] = [&]() {
if (*_targetTopLeft.line > *_sourceArea.top) // moving down
return std::tuple { *_sourceArea.bottom - *_sourceArea.top, -1, -1 };
else
return std::tuple { 0, +1, *_sourceArea.bottom - *_sourceArea.top + 1 };
}();
for (auto y = y0; y != yEnd; y += yInc)
{
for (auto x = x0; x != xEnd; x += xInc)
{
Cell const& sourceCell = at(LineOffset::cast_from(*_sourceArea.top + y),
ColumnOffset::cast_from(_sourceArea.left + x));
Cell& targetCell = at(LineOffset::cast_from(_targetTopLeft.line + y),
ColumnOffset::cast_from(_targetTopLeft.column + x));
targetCell = sourceCell;
}
}
}
template <typename T>
void Screen<T>::eraseArea(int _top, int _left, int _bottom, int _right)
{
assert(_right <= unbox<int>(pageSize_.columns));
assert(_bottom <= unbox<int>(pageSize_.lines));
if (_top > _bottom || _left > _right)
return;
for (int y = _top; y <= _bottom; ++y)
{
for (Cell& cell: grid()
.lineAt(LineOffset::cast_from(y))
.useRange(ColumnOffset(_left), ColumnCount(_right - _left + 1)))
{
cell.write(cursor_.graphicsRendition, L' ', 1);
}
}
}
template <typename T>
void Screen<T>::fillArea(char32_t _ch, int _top, int _left, int _bottom, int _right)
{
// "Pch can be any value from 32 to 126 or from 160 to 255."
if (!(32 <= _ch && _ch <= 126) && !(160 <= _ch && _ch <= 255))
return;
auto const w = unicode::width(_ch);
for (int y = _top; y <= _bottom; ++y)
{
for (Cell& cell:
grid()
.lineAt(LineOffset::cast_from(y))
.useRange(ColumnOffset::cast_from(_left), ColumnCount::cast_from(_right - _left + 1)))
{
cell.write(cursor().graphicsRendition, _ch, w);
}
}
}
template <typename T>
void Screen<T>::deleteLines(LineCount _n)
{
if (isCursorInsideMargins())
{
scrollUp(
_n,
Margin { Margin::Vertical { cursor_.position.line, margin_.vertical.to }, margin_.horizontal });
}
}
template <typename T>
void Screen<T>::deleteCharacters(ColumnCount _n)
{
if (isCursorInsideMargins() && *_n != 0)
deleteChars(realCursorPosition().line, realCursorPosition().column, _n);
}
template <typename T>
void Screen<T>::deleteChars(LineOffset _line, ColumnOffset _column, ColumnCount _n)
{
auto& line = grid().lineAt(_line);
auto lineBuffer = line.cells();
Cell* left = const_cast<Cell*>(lineBuffer.data() + _column.as<size_t>());
Cell* right = const_cast<Cell*>(lineBuffer.data() + *margin_.horizontal.to + 1);
long const n = min(_n.as<long>(), static_cast<long>(distance(left, right)));
Cell* mid = left + n;
rotate(left, mid, right);
for (Cell& cell: gsl::make_span(right - n, right))
{
cell.write(cursor_.graphicsRendition, L' ', 1);
}
line.markUsedFirst(ColumnCount::cast_from(*margin_.horizontal.to + 1));
}
template <typename T>
void Screen<T>::deleteColumns(ColumnCount _n)
{
if (isCursorInsideMargins())
for (auto lineNo = margin_.vertical.from; lineNo <= margin_.vertical.to; ++lineNo)
deleteChars(lineNo, realCursorPosition().column, _n);
}
template <typename T>
void Screen<T>::horizontalTabClear(HorizontalTabClear _which)
{
switch (_which)
{
case HorizontalTabClear::AllTabs: clearAllTabs(); break;
case HorizontalTabClear::UnderCursor: clearTabUnderCursor(); break;
}
}
template <typename T>
void Screen<T>::horizontalTabSet()
{
setTabUnderCursor();
}
template <typename T>
void Screen<T>::setCurrentWorkingDirectory(string const& _url)
{
currentWorkingDirectory_ = _url;
}
template <typename T>
void Screen<T>::hyperlink(string _id, string _uri)
{
if (_uri.empty())
cursor_.hyperlink = {};
else if (!_id.empty())
cursor_.hyperlink = hyperlinks_.hyperlinkIdByUserId(_id);
else
{
cursor_.hyperlink = hyperlinks_.nextHyperlinkId++;
hyperlinks_.cache.emplace(cursor_.hyperlink,
make_shared<HyperlinkInfo>(HyperlinkInfo { move(_id), move(_uri) }));
}
// TODO:
// Care about eviction.
// Move hyperlink store into ScreenBuffer, so it gets reset upon every switch into
// alternate screen (not for main screen!)
}
template <typename T>
void Screen<T>::moveCursorUp(LineCount _n)
{
wrapPending_ = 0;
auto const n = min(_n.as<LineOffset>(),
logicalCursorPosition().line > margin_.vertical.from
? logicalCursorPosition().line - margin_.vertical.from
: logicalCursorPosition().line);
cursor_.position.line -= n;
}
template <typename T>
void Screen<T>::moveCursorDown(LineCount _n)
{
wrapPending_ = 0;
auto const currentLineNumber = logicalCursorPosition().line;
auto const n = min(_n.as<LineOffset>(),
currentLineNumber <= margin_.vertical.to
? margin_.vertical.to - currentLineNumber
: (pageSize_.lines.as<LineOffset>() - 1) - currentLineNumber);
cursor_.position.line += n;
}
template <typename T>
void Screen<T>::moveCursorForward(ColumnCount _n)
{
wrapPending_ = 0;
cursor_.position.column = min(cursor_.position.column + _n.as<ColumnOffset>(), margin_.horizontal.to);
}
template <typename T>
void Screen<T>::moveCursorBackward(ColumnCount _n)
{
// even if you move to 80th of 80 columns, it'll first write a char and THEN flag wrap pending
wrapPending_ = false;
// TODO: skip cells that in counting when iterating backwards over a wide cell (such as emoji)
auto const n = min(_n.as<ColumnOffset>(), cursor_.position.column);
setCurrentColumn(cursor_.position.column - n);
}
template <typename T>
void Screen<T>::moveCursorToColumn(ColumnOffset _column)
{
setCurrentColumn(_column);
}
template <typename T>
void Screen<T>::moveCursorToBeginOfLine()
{
setCurrentColumn(ColumnOffset(0));
}
template <typename T>
void Screen<T>::moveCursorToLine(LineOffset _row)
{
moveCursorTo(_row, cursor_.position.column);
}
template <typename T>
void Screen<T>::moveCursorToNextTab()
{
// TODO: I guess something must remember when a \t was added, for proper move-back?
// TODO: respect HTS/TBC
if (!tabs_.empty())
{
// advance to the next tab
size_t i = 0;
while (i < tabs_.size() && realCursorPosition().column >= tabs_[i])
++i;
auto const currentCursorColumn = logicalCursorPosition().column;
if (i < tabs_.size())
moveCursorForward(boxed_cast<ColumnCount>(tabs_[i] - currentCursorColumn));
else if (realCursorPosition().column < margin_.horizontal.to)
moveCursorForward(boxed_cast<ColumnCount>(margin_.horizontal.to - currentCursorColumn));
else
moveCursorToNextLine(LineCount(1));
}
else if (tabWidth_.value)
{
// default tab settings
if (realCursorPosition().column < margin_.horizontal.to)
{
auto const n = min((tabWidth_ - cursor_.position.column.as<ColumnCount>() % tabWidth_),
pageSize_.columns - boxed_cast<ColumnCount>(logicalCursorPosition().column));
moveCursorForward(n);
}
else
moveCursorToNextLine(LineCount(1));
}
else
{
// no tab stops configured
if (realCursorPosition().column < margin_.horizontal.to)
// then TAB moves to the end of the screen
moveCursorToColumn(margin_.horizontal.to);
else
// then TAB moves to next line left margin
moveCursorToNextLine(LineCount(1));
}
}
template <typename T>
void Screen<T>::notify(string const& _title, string const& _content)
{
std::cout << "Screen.NOTIFY: title: '" << _title << "', content: '" << _content << "'\n";
eventListener_.notify(_title, _content);
}
template <typename T>
void Screen<T>::captureBuffer(int _lineCount, bool _logicalLines)
{
// TODO: Unit test case! (for ensuring line numbering and limits are working as expected)
auto capturedBuffer = std::string();
auto writer = VTWriter([&](auto buf, auto len) { capturedBuffer += string_view(buf, len); });
// TODO: when capturing _lineCount < screenSize.lines, start at the lowest non-empty line.
auto const relativeStartLine =
_logicalLines ? grid().computeLogicalLineNumberFromBottom(LineCount::cast_from(_lineCount))
: unbox<int>(pageSize_.lines) - _lineCount;
auto const startLine =
clamp(relativeStartLine, -unbox<int>(historyLineCount()), unbox<int>(pageSize_.lines));
// dumpState();
auto const trimSpaceRight = [](string& value) {
while (!value.empty() && value.back() == ' ')
value.pop_back();
};
for (LineOffset line = LineOffset(startLine); line < pageSize_.lines.as<LineOffset>(); ++line)
{
if (_logicalLines && grid().lineAt(line).wrapped() && !capturedBuffer.empty())
capturedBuffer.pop_back();
if (grid().isLineBlank(line))
continue;
for (ColumnOffset col = ColumnOffset { 0 }; col < pageSize_.columns.as<ColumnOffset>(); ++col)
{
Cell const& cell = at({ line, col });
if (!cell.codepointCount())
writer.write(U' ');
else
{
writer.write(cell.codepoint(0));
for (size_t i = 1; i < cell.codepointCount(); ++i)
writer.write(cell.codepoint(i));
}
}
trimSpaceRight(capturedBuffer);
writer.write('\n');
}
while (crispy::endsWith(string_view(capturedBuffer), "\n\n"sv)) // TODO: unit test
capturedBuffer.pop_back();
auto constexpr PageSize = size_t { 4096 };
for (size_t i = 0; i < capturedBuffer.size(); i += PageSize)
{
auto const start = capturedBuffer.data() + i;
auto const count = min(PageSize, capturedBuffer.size() - i);
reply("\033]314;{}\033\\", string_view(start, count));
}
reply("\033]314;\033\\"); // mark the end
}
template <typename T>
void Screen<T>::cursorForwardTab(TabStopCount _count)
{
for (int i = 0; i < unbox<int>(_count); ++i)
moveCursorToNextTab();
}
template <typename T>
void Screen<T>::cursorBackwardTab(TabStopCount _count)
{
if (!_count)
return;
if (!tabs_.empty())
{
for (unsigned k = 0; k < unbox<unsigned>(_count); ++k)
{
auto const i = std::find_if(rbegin(tabs_), rend(tabs_), [&](ColumnOffset tabPos) -> bool {
return tabPos < logicalCursorPosition().column;
});
if (i != rend(tabs_))
{
// prev tab found -> move to prev tab
moveCursorToColumn(*i);
}
else
{
moveCursorToColumn(margin_.horizontal.from);
break;
}
}
}
else if (tabWidth_.value)
{
// default tab settings
if (*cursor_.position.column < *tabWidth_)
moveCursorToBeginOfLine();
else
{
auto const m = (*cursor_.position.column + 1) % *tabWidth_;
auto const n = m ? (*_count - 1) * *tabWidth_ + m : *_count * *tabWidth_ + m;
moveCursorBackward(ColumnCount(n - 1));
}
}
else
{
// no tab stops configured
moveCursorToBeginOfLine();
}
}
template <typename T>
void Screen<T>::index()
{
if (*realCursorPosition().line == *margin_.vertical.to)
scrollUp(LineCount(1));
else
moveCursorDown(LineCount(1));
}
template <typename T>
void Screen<T>::reverseIndex()
{
if (unbox<int>(realCursorPosition().line) == unbox<int>(margin_.vertical.from))
scrollDown(LineCount(1));
else
moveCursorUp(LineCount(1));
}
template <typename T>
void Screen<T>::backIndex()
{
if (realCursorPosition().column == margin_.horizontal.from)
; // TODO: scrollRight(1);
else
moveCursorForward(ColumnCount(1));
}
template <typename T>
void Screen<T>::forwardIndex()
{
if (*realCursorPosition().column == *margin_.horizontal.to)
grid().scrollLeft(GraphicsAttributes {}, margin_);
else
moveCursorForward(ColumnCount(1));
}
template <typename T>
void Screen<T>::setForegroundColor(Color _color)
{
cursor_.graphicsRendition.foregroundColor = _color;
}
template <typename T>
void Screen<T>::setBackgroundColor(Color _color)
{
cursor_.graphicsRendition.backgroundColor = _color;
}
template <typename T>
void Screen<T>::setUnderlineColor(Color _color)
{
cursor_.graphicsRendition.underlineColor = _color;
}
template <typename T>
void Screen<T>::setCursorStyle(CursorDisplay _display, CursorShape _shape)
{
cursorDisplay_ = _display;
cursorShape_ = _shape;
eventListener_.setCursorStyle(_display, _shape);
}
template <typename T>
void Screen<T>::setGraphicsRendition(GraphicsRendition _rendition)
{
// TODO: optimize this as there are only 3 cases
// 1.) reset
// 2.) set some bits |=
// 3.) clear some bits &= ~
switch (_rendition)
{
case GraphicsRendition::Reset: cursor_.graphicsRendition = {}; break;
case GraphicsRendition::Bold: cursor_.graphicsRendition.styles |= CellFlags::Bold; break;
case GraphicsRendition::Faint: cursor_.graphicsRendition.styles |= CellFlags::Faint; break;
case GraphicsRendition::Italic: cursor_.graphicsRendition.styles |= CellFlags::Italic; break;
case GraphicsRendition::Underline: cursor_.graphicsRendition.styles |= CellFlags::Underline; break;
case GraphicsRendition::Blinking: cursor_.graphicsRendition.styles |= CellFlags::Blinking; break;
case GraphicsRendition::Inverse: cursor_.graphicsRendition.styles |= CellFlags::Inverse; break;
case GraphicsRendition::Hidden: cursor_.graphicsRendition.styles |= CellFlags::Hidden; break;
case GraphicsRendition::CrossedOut: cursor_.graphicsRendition.styles |= CellFlags::CrossedOut; break;
case GraphicsRendition::DoublyUnderlined:
cursor_.graphicsRendition.styles |= CellFlags::DoublyUnderlined;
break;
case GraphicsRendition::CurlyUnderlined:
cursor_.graphicsRendition.styles |= CellFlags::CurlyUnderlined;
break;
case GraphicsRendition::DottedUnderline:
cursor_.graphicsRendition.styles |= CellFlags::DottedUnderline;
break;
case GraphicsRendition::DashedUnderline:
cursor_.graphicsRendition.styles |= CellFlags::DashedUnderline;
break;
case GraphicsRendition::Framed: cursor_.graphicsRendition.styles |= CellFlags::Framed; break;
case GraphicsRendition::Overline: cursor_.graphicsRendition.styles |= CellFlags::Overline; break;
case GraphicsRendition::Normal:
cursor_.graphicsRendition.styles &= ~(CellFlags::Bold | CellFlags::Faint);
break;
case GraphicsRendition::NoItalic: cursor_.graphicsRendition.styles &= ~CellFlags::Italic; break;
case GraphicsRendition::NoUnderline:
cursor_.graphicsRendition.styles &=
~(CellFlags::Underline | CellFlags::DoublyUnderlined | CellFlags::CurlyUnderlined
| CellFlags::DottedUnderline | CellFlags::DashedUnderline);
break;
case GraphicsRendition::NoBlinking: cursor_.graphicsRendition.styles &= ~CellFlags::Blinking; break;
case GraphicsRendition::NoInverse: cursor_.graphicsRendition.styles &= ~CellFlags::Inverse; break;
case GraphicsRendition::NoHidden: cursor_.graphicsRendition.styles &= ~CellFlags::Hidden; break;
case GraphicsRendition::NoCrossedOut: cursor_.graphicsRendition.styles &= ~CellFlags::CrossedOut; break;
case GraphicsRendition::NoFramed: cursor_.graphicsRendition.styles &= ~CellFlags::Framed; break;
case GraphicsRendition::NoOverline: cursor_.graphicsRendition.styles &= ~CellFlags::Overline; break;
}
}
template <typename T>
void Screen<T>::setMark()
{
currentLine().setMarked(true);
}
template <typename T>
void Screen<T>::saveModes(std::vector<DECMode> const& _modes)
{
modes_.save(_modes);
}
template <typename T>
void Screen<T>::restoreModes(std::vector<DECMode> const& _modes)
{
modes_.restore(_modes);
}
template <typename T>
void Screen<T>::setMode(AnsiMode _mode, bool _enable)
{
if (!isValidAnsiMode(static_cast<int>(_mode)))
return;
modes_.set(_mode, _enable);
}
template <typename T>
void Screen<T>::setMode(DECMode _mode, bool _enable)
{
if (!isValidDECMode(static_cast<int>(_mode)))
return;
switch (_mode)
{
case DECMode::AutoWrap: cursor_.autoWrap = _enable; break;
case DECMode::LeftRightMargin:
// Resetting DECLRMM also resets the horizontal margins back to screen size.
if (!_enable)
margin_.horizontal =
Margin::Horizontal { ColumnOffset(0), boxed_cast<ColumnOffset>(pageSize_.columns - 1) };
break;
case DECMode::Origin: cursor_.originMode = _enable; break;
case DECMode::Columns132:
if (!isModeEnabled(DECMode::AllowColumns80to132))
break;
if (_enable != isModeEnabled(DECMode::Columns132))
{
auto const clear = _enable != isModeEnabled(_mode);
// sets the number of columns on the page to 80 or 132 and selects the
// corresponding 80- or 132-column font
auto const columns = ColumnCount(_enable ? 132 : 80);
resizeColumns(columns, clear);
}
break;
case DECMode::BatchedRendering:
if (modes_.enabled(DECMode::BatchedRendering) != _enable)
eventListener_.synchronizedOutput(_enable);
break;
case DECMode::TextReflow:
if (allowReflowOnResize_ && isPrimaryScreen())
{
// Enabling reflow enables every line in the main page area.
// Disabling reflow only affects currently line and below.
auto const startLine = _enable ? LineOffset(0) : realCursorPosition().line;
for (auto line = startLine; line < pageSize_.lines.as<LineOffset>(); ++line)
grid().lineAt(line).setWrappable(_enable);
}
break;
case DECMode::DebugLogging:
// Since this mode (Xterm extension) does not support finer graind control,
// we'll be just globally enable/disable all debug logging.
for (auto& category: logstore::get())
category.get().enable(_enable);
break;
case DECMode::UseAlternateScreen:
if (_enable)
setBuffer(ScreenType::Alternate);
else
setBuffer(ScreenType::Main);
break;
case DECMode::UseApplicationCursorKeys:
eventListener_.useApplicationCursorKeys(_enable);
if (isAlternateScreen())
{
if (_enable)
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::ApplicationCursorKeys);
else
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::NormalCursorKeys);
}
break;
case DECMode::BracketedPaste: eventListener_.setBracketedPaste(_enable); break;
case DECMode::MouseSGR:
if (_enable)
eventListener_.setMouseTransport(MouseTransport::SGR);
else
eventListener_.setMouseTransport(MouseTransport::Default);
break;
case DECMode::MouseExtended: eventListener_.setMouseTransport(MouseTransport::Extended); break;
case DECMode::MouseURXVT: eventListener_.setMouseTransport(MouseTransport::URXVT); break;
case DECMode::MouseAlternateScroll:
if (_enable)
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::ApplicationCursorKeys);
else
eventListener_.setMouseWheelMode(InputGenerator::MouseWheelMode::NormalCursorKeys);
break;
case DECMode::FocusTracking: eventListener_.setGenerateFocusEvents(_enable); break;
case DECMode::UsePrivateColorRegisters: sequencer_.setUsePrivateColorRegisters(_enable); break;
case DECMode::VisibleCursor:
cursor_.visible = _enable;
eventListener_.setCursorVisibility(_enable);
break;
case DECMode::MouseProtocolX10: sendMouseEvents(MouseProtocol::X10, _enable); break;
case DECMode::MouseProtocolNormalTracking: sendMouseEvents(MouseProtocol::NormalTracking, _enable); break;
case DECMode::MouseProtocolHighlightTracking:
sendMouseEvents(MouseProtocol::HighlightTracking, _enable);
break;
case DECMode::MouseProtocolButtonTracking: sendMouseEvents(MouseProtocol::ButtonTracking, _enable); break;
case DECMode::MouseProtocolAnyEventTracking:
sendMouseEvents(MouseProtocol::AnyEventTracking, _enable);
break;
case DECMode::SaveCursor:
if (_enable)
saveCursor();
else
restoreCursor();
break;
case DECMode::ExtendedAltScreen:
if (_enable)
{
savedPrimaryCursor_ = cursor();
setMode(DECMode::UseAlternateScreen, true);
clearScreen();
}
else
{
setMode(DECMode::UseAlternateScreen, false);
restoreCursor(savedPrimaryCursor_);
}
break;
default: break;
}
modes_.set(_mode, _enable);
}
enum class ModeResponse
{ // TODO: respect response 0, 3, 4.
NotRecognized = 0,
Set = 1,
Reset = 2,
PermanentlySet = 3,
PermanentlyReset = 4
};
template <typename T>
void Screen<T>::requestAnsiMode(int _mode)
{
ModeResponse const modeResponse =
isValidAnsiMode(_mode)
? isModeEnabled(static_cast<AnsiMode>(_mode)) ? ModeResponse::Set : ModeResponse::Reset
: ModeResponse::NotRecognized;
auto const code = toAnsiModeNum(static_cast<AnsiMode>(_mode));
reply("\033[{};{}$y", code, static_cast<unsigned>(modeResponse));
}
template <typename T>
void Screen<T>::requestDECMode(int _mode)
{
ModeResponse const modeResponse =
isValidDECMode(_mode)
? isModeEnabled(static_cast<DECMode>(_mode)) ? ModeResponse::Set : ModeResponse::Reset
: ModeResponse::NotRecognized;
auto const code = toDECModeNum(static_cast<DECMode>(_mode));
reply("\033[?{};{}$y", code, static_cast<unsigned>(modeResponse));
}
template <typename T>
void Screen<T>::setTopBottomMargin(optional<LineOffset> _top, optional<LineOffset> _bottom)
{
auto const bottom = _bottom.has_value() ? min(_bottom.value(), pageSize_.lines.as<LineOffset>() - 1)
: pageSize_.lines.as<LineOffset>() - 1;
auto const top = _top.value_or(LineOffset(0));
if (top < bottom)
{
margin_.vertical.from = top;
margin_.vertical.to = bottom;
moveCursorTo({}, {});
}
}
template <typename T>
void Screen<T>::setLeftRightMargin(optional<ColumnOffset> _left, optional<ColumnOffset> _right)
{
if (isModeEnabled(DECMode::LeftRightMargin))
{
auto const right = _right.has_value()
? min(_right.value(), pageSize_.columns.as<ColumnOffset>() - ColumnOffset(1))
: pageSize_.columns.as<ColumnOffset>() - ColumnOffset(1);
auto const left = _left.value_or(ColumnOffset(0));
if (left < right)
{
margin_.horizontal.from = left;
margin_.horizontal.to = right;
moveCursorTo({}, {});
}
}
}
template <typename T>
void Screen<T>::screenAlignmentPattern()
{
// sets the margins to the extremes of the page
margin_.vertical.from = LineOffset(0);
margin_.vertical.to = pageSize_.lines.as<LineOffset>() - LineOffset(1);
margin_.horizontal.from = ColumnOffset(0);
margin_.horizontal.to = pageSize_.columns.as<ColumnOffset>() - ColumnOffset(1);
// and moves the cursor to the home position
moveCursorTo({}, {});
// fills the complete screen area with a test pattern
for (auto& line: grid().mainPage())
{
line.reset(grid().defaultLineFlags(), GraphicsAttributes {}, U'E', 1);
}
}
template <typename T>
void Screen<T>::sendMouseEvents(MouseProtocol _protocol, bool _enable)
{
eventListener_.setMouseProtocol(_protocol, _enable);
}
template <typename T>
void Screen<T>::applicationKeypadMode(bool _enable)
{
eventListener_.setApplicationkeypadMode(_enable);
}
template <typename T>
void Screen<T>::designateCharset(CharsetTable _table, CharsetId _charset)
{
// TODO: unit test SCS and see if they also behave well with reset/softreset
// Also, is the cursor shared between the two buffers?
cursor_.charsets.select(_table, _charset);
}
template <typename T>
void Screen<T>::singleShiftSelect(CharsetTable _table)
{
// TODO: unit test SS2, SS3
cursor_.charsets.singleShift(_table);
}
template <typename T>
void Screen<T>::sixelImage(ImageSize _pixelSize, Image::Data&& _data)
{
auto const columnCount =
ColumnCount::cast_from(ceilf(float(*_pixelSize.width) / float(*cellPixelSize_.width)));
auto const lineCount =
LineCount::cast_from(ceilf(float(*_pixelSize.height) / float(*cellPixelSize_.height)));
auto const extent = GridSize { lineCount, columnCount };
auto const autoScrollAtBottomMargin =
isModeEnabled(DECMode::SixelScrolling); // If DECSDM is enabled, scrolling is meant to be disabled.
auto const topLeft = autoScrollAtBottomMargin ? logicalCursorPosition() : Coordinate {};
auto const alignmentPolicy = ImageAlignment::TopStart;
auto const resizePolicy = ImageResize::NoResize;
auto const imageOffset = Coordinate {};
auto const imageSize = _pixelSize;
shared_ptr<Image const> imageRef = uploadImage(ImageFormat::RGBA, _pixelSize, move(_data));
renderImage(imageRef->id(),
topLeft,
extent,
imageOffset,
imageSize,
alignmentPolicy,
resizePolicy,
autoScrollAtBottomMargin);
if (!sixelCursorConformance_)
linefeed(topLeft.column);
}
template <typename T>
shared_ptr<Image const> Screen<T>::uploadImage(ImageFormat _format,
ImageSize _imageSize,
Image::Data&& _pixmap)
{
return imagePool_.create(_format, _imageSize, move(_pixmap));
}
template <typename T>
void Screen<T>::renderImage(ImageId _imageId,
Coordinate _topLeft,
GridSize _gridSize,
Coordinate _imageOffset,
ImageSize _imageSize,
ImageAlignment _alignmentPolicy,
ImageResize _resizePolicy,
bool _autoScroll)
{
// TODO: make use of _imageOffset and _imageSize
(void) _imageOffset;
(void) _imageSize;
auto const linesAvailable = pageSize_.lines - _topLeft.line.as<LineCount>();
auto const linesToBeRendered = min(_gridSize.lines, linesAvailable);
auto const columnsAvailable = *pageSize_.columns - *_topLeft.column;
auto const columnsToBeRendered = ColumnCount(min(columnsAvailable, *_gridSize.columns));
auto const gapColor = RGBAColor {}; // TODO: cursor_.graphicsRendition.backgroundColor;
// TODO: make use of _imageOffset and _imageSize
auto const rasterizedImage =
imagePool_.rasterize(_imageId, _alignmentPolicy, _resizePolicy, gapColor, _gridSize, cellPixelSize_);
if (*linesToBeRendered)
{
for (GridSize::Offset const offset: GridSize { linesToBeRendered, columnsToBeRendered })
{
auto const imageFragmentId = createImageFragmentId();
Cell& cell = at(_topLeft + offset);
cell.setHyperlink(cursor_.hyperlink);
cell.setImage(imageFragmentId);
imageFragments_.emplace(
imageFragmentId,
ImageFragment { rasterizedImage, Coordinate { offset.line, offset.column } });
};
moveCursorTo(_topLeft.line + unbox<int>(linesToBeRendered) - 1, _topLeft.column);
}
// If there're lines to be rendered missing (because it didn't fit onto the screen just yet)
// AND iff sixel !sixelScrolling is enabled, then scroll as much as needed to render the remaining lines.
if (linesToBeRendered != _gridSize.lines && _autoScroll)
{
auto const remainingLineCount = _gridSize.lines - linesToBeRendered;
for (auto const lineOffset: crispy::times(*remainingLineCount))
{
linefeed(_topLeft.column);
for (auto const columnOffset: views::n_times<ColumnOffset>(*columnsToBeRendered))
{
auto const imageFragmentId = createImageFragmentId();
Cell& cell = at(pageSize_.lines.as<LineOffset>() - 1, _topLeft.column + columnOffset);
cell.setImage(imageFragmentId);
imageFragments_.emplace(
imageFragmentId,
ImageFragment { rasterizedImage,
Coordinate { boxed_cast<LineOffset>(linesToBeRendered) + lineOffset,
columnOffset } });
cell.setHyperlink(cursor_.hyperlink);
};
}
}
// move ansi text cursor to position of the sixel cursor
moveCursorToColumn(_topLeft.column + _gridSize.columns.as<ColumnOffset>());
}
template <typename T>
void Screen<T>::setWindowTitle(std::string const& _title)
{
windowTitle_ = _title;
eventListener_.setWindowTitle(_title);
}
template <typename T>
void Screen<T>::saveWindowTitle()
{
savedWindowTitles_.push(windowTitle_);
}
template <typename T>
void Screen<T>::restoreWindowTitle()
{
if (!savedWindowTitles_.empty())
{
windowTitle_ = savedWindowTitles_.top();
savedWindowTitles_.pop();
eventListener_.setWindowTitle(windowTitle_);
}
}
template <typename T>
void Screen<T>::requestDynamicColor(DynamicColorName _name)
{
auto const color = [&]() -> optional<RGBColor> {
switch (_name)
{
case DynamicColorName::DefaultForegroundColor: return colorPalette_.defaultForeground;
case DynamicColorName::DefaultBackgroundColor: return colorPalette_.defaultBackground;
case DynamicColorName::TextCursorColor:
if (holds_alternative<CellForegroundColor>(colorPalette_.cursor.color))
return colorPalette_.defaultForeground;
else if (holds_alternative<CellBackgroundColor>(colorPalette_.cursor.color))
return colorPalette_.defaultBackground;
else
return get<RGBColor>(colorPalette_.cursor.color);
case DynamicColorName::MouseForegroundColor: return colorPalette_.mouseForeground;
case DynamicColorName::MouseBackgroundColor: return colorPalette_.mouseBackground;
case DynamicColorName::HighlightForegroundColor:
if (colorPalette_.selectionForeground.has_value())
return colorPalette_.selectionForeground.value();
else
return nullopt;
case DynamicColorName::HighlightBackgroundColor:
if (colorPalette_.selectionBackground.has_value())
return colorPalette_.selectionBackground.value();
else
return nullopt;
}
return nullopt; // should never happen
}();
if (color.has_value())
{
reply("\033]{};{}\033\\", setDynamicColorCommand(_name), setDynamicColorValue(color.value()));
}
}
template <typename T>
void Screen<T>::requestPixelSize(RequestPixelSize _area)
{
switch (_area)
{
case RequestPixelSize::WindowArea: [[fallthrough]]; // TODO
case RequestPixelSize::TextArea:
// Result is CSI 4 ; height ; width t
reply("\033[4;{};{}t",
*cellPixelSize_.height * *pageSize_.lines,
*cellPixelSize_.width * *pageSize_.columns);
break;
case RequestPixelSize::CellArea:
// Result is CSI 6 ; height ; width t
reply("\033[6;{};{}t", cellPixelSize_.height, cellPixelSize_.width);
break;
}
}
template <typename T>
void Screen<T>::requestCharacterSize(RequestPixelSize _area) // TODO: rename RequestPixelSize to RequestArea?
{
switch (_area)
{
case RequestPixelSize::TextArea: reply("\033[8;{};{}t", pageSize_.lines, pageSize_.columns); break;
case RequestPixelSize::WindowArea: reply("\033[9;{};{}t", pageSize_.lines, pageSize_.columns); break;
case RequestPixelSize::CellArea:
assert(
!"Screen.requestCharacterSize: Doesn't make sense, and cannot be called, therefore, fortytwo.");
break;
}
}
template <typename T>
void Screen<T>::requestStatusString(RequestStatusString _value)
{
// xterm responds with DCS 1 $ r Pt ST for valid requests
// or DCS 0 $ r Pt ST for invalid requests.
auto const response = [&](RequestStatusString _value) -> optional<string> {
switch (_value)
{
case RequestStatusString::DECSCL: {
auto level = 61;
switch (terminalId_)
{
case VTType::VT525:
case VTType::VT520:
case VTType::VT510: level = 65; break;
case VTType::VT420: level = 64; break;
case VTType::VT340:
case VTType::VT330:
case VTType::VT320: level = 63; break;
case VTType::VT240:
case VTType::VT220: level = 62; break;
case VTType::VT100: level = 61; break;
}
auto const c1TransmittionMode = ControlTransmissionMode::S7C1T;
auto const c1t = c1TransmittionMode == ControlTransmissionMode::S7C1T ? 1 : 0;
return fmt::format("{};{}\"p", level, c1t);
}
case RequestStatusString::DECSCUSR: // Set cursor style (DECSCUSR), VT520
{
int const blinkingOrSteady = cursorDisplay_ == CursorDisplay::Steady ? 1 : 0;
int const shape = [&]() {
switch (cursorShape_)
{
case CursorShape::Block: return 1;
case CursorShape::Underscore: return 3;
case CursorShape::Bar: return 5;
case CursorShape::Rectangle: return 7;
}
return 1;
}();
return fmt::format("{} q", shape + blinkingOrSteady);
}
case RequestStatusString::DECSLPP:
// Ps >= 2 4 -> Resize to Ps lines (DECSLPP), VT340 and VT420.
// xterm adapts this by resizing its window.
if (*pageSize_.lines >= 24)
return fmt::format("{}t", pageSize_.lines);
#if defined(LIBTERMINAL_LOG_RAW)
LOGSTORE(ScreenRawOutputLog)
("Requesting device status for {} not with line count < 24 is undefined.");
#endif
return nullopt;
case RequestStatusString::DECSTBM:
return fmt::format("{};{}r", 1 + *margin_.vertical.from, *margin_.vertical.to);
case RequestStatusString::DECSLRM:
return fmt::format("{};{}s", 1 + *margin_.horizontal.from, *margin_.horizontal.to);
case RequestStatusString::DECSCPP:
// EXTENSION: Usually DECSCPP only knows about 80 and 132, but we take any.
return fmt::format("{}|$", pageSize_.columns);
case RequestStatusString::DECSNLS: return fmt::format("{}*|", pageSize_.lines);
case RequestStatusString::SGR:
return fmt::format("0;{}m", vtSequenceParameterString(cursor_.graphicsRendition));
case RequestStatusString::DECSCA: // TODO
#if defined(LIBTERMINAL_LOG_RAW)
LOGSTORE(ScreenRawOutputLog)("Requesting device status for {} not implemented yet.", _value);
#endif
break;
}
return nullopt;
}(_value);
reply("\033P{}$r{}\033\\", response.has_value() ? 1 : 0, response.value_or(""), "\"p");
}
template <typename T>
void Screen<T>::requestTabStops()
{
// Response: `DCS 2 $ u Pt ST`
ostringstream dcs;
dcs << "\033P2$u"sv; // DCS
if (!tabs_.empty())
{
for (size_t const i: times(tabs_.size()))
{
if (i)
dcs << '/';
dcs << *tabs_[i] + 1;
}
}
else if (*tabWidth_ != 0)
{
dcs << 1;
for (auto column = *tabWidth_ + 1; column <= *pageSize_.columns; column += *tabWidth_)
dcs << '/' << column;
}
dcs << "\033\\"sv; // ST
reply(dcs.str());
}
namespace
{
std::string asHex(std::string_view _value)
{
std::string output;
for (char const ch: _value)
output += fmt::format("{:02X}", unsigned(ch));
return output;
}
} // namespace
template <typename T>
void Screen<T>::requestCapability(std::string_view _name)
{
if (!respondToTCapQuery_)
{
#if defined(LIBTERMINAL_LOG_RAW)
LOGSTORE(ScreenRawOutputLog)
("Requesting terminal capability {} ignored. Experimental tcap feature disabled.", _name);
#endif
return;
}
if (booleanCapability(_name))
reply("\033P1+r{}\033\\", toHexString(_name));
else if (auto const value = numericCapability(_name); value >= 0)
{
auto hexValue = fmt::format("{:X}", value);
if (hexValue.size() % 2)
hexValue.insert(hexValue.begin(), '0');
reply("\033P1+r{}={}\033\\", toHexString(_name), hexValue);
}
else if (auto const value = stringCapability(_name); !value.empty())
reply("\033P1+r{}={}\033\\", toHexString(_name), asHex(value));
else
reply("\033P0+r\033\\");
}
template <typename T>
void Screen<T>::requestCapability(capabilities::Code _code)
{
if (!respondToTCapQuery_)
{
#if defined(LIBTERMINAL_LOG_RAW)
if (ScreenRawOutputLog)
LOGSTORE(ScreenRawOutputLog)
("Requesting terminal capability {} ignored. Experimental tcap feature disabled.", _code);
#endif
return;
}
#if defined(LIBTERMINAL_LOG_RAW)
if (ScreenRawOutputLog)
LOGSTORE(ScreenRawOutputLog)("Requesting terminal capability: {}", _code);
#endif
if (booleanCapability(_code))
reply("\033P1+r{}\033\\", _code.hex());
else if (auto const value = numericCapability(_code); value >= 0)
{
auto hexValue = fmt::format("{:X}", value);
if (hexValue.size() % 2)
hexValue.insert(hexValue.begin(), '0');
reply("\033P1+r{}={}\033\\", _code.hex(), hexValue);
}
else if (auto const value = stringCapability(_code); !value.empty())
reply("\033P1+r{}={}\033\\", _code.hex(), asHex(value));
else
reply("\033P0+r\033\\");
}
template <typename T>
void Screen<T>::resetDynamicColor(DynamicColorName _name)
{
switch (_name)
{
case DynamicColorName::DefaultForegroundColor:
colorPalette_.defaultForeground = defaultColorPalette_.defaultForeground;
break;
case DynamicColorName::DefaultBackgroundColor:
colorPalette_.defaultBackground = defaultColorPalette_.defaultBackground;
break;
case DynamicColorName::TextCursorColor: colorPalette_.cursor = defaultColorPalette_.cursor; break;
case DynamicColorName::MouseForegroundColor:
colorPalette_.mouseForeground = defaultColorPalette_.mouseForeground;
break;
case DynamicColorName::MouseBackgroundColor:
colorPalette_.mouseBackground = defaultColorPalette_.mouseBackground;
break;
case DynamicColorName::HighlightForegroundColor:
colorPalette_.selectionForeground = defaultColorPalette_.selectionForeground;
break;
case DynamicColorName::HighlightBackgroundColor:
colorPalette_.selectionBackground = defaultColorPalette_.selectionBackground;
break;
}
}
template <typename T>
void Screen<T>::setDynamicColor(DynamicColorName _name, RGBColor _value)
{
switch (_name)
{
case DynamicColorName::DefaultForegroundColor: colorPalette_.defaultForeground = _value; break;
case DynamicColorName::DefaultBackgroundColor: colorPalette_.defaultBackground = _value; break;
case DynamicColorName::TextCursorColor: colorPalette_.cursor.color = _value; break;
case DynamicColorName::MouseForegroundColor: colorPalette_.mouseForeground = _value; break;
case DynamicColorName::MouseBackgroundColor: colorPalette_.mouseBackground = _value; break;
case DynamicColorName::HighlightForegroundColor: colorPalette_.selectionForeground = _value; break;
case DynamicColorName::HighlightBackgroundColor: colorPalette_.selectionBackground = _value; break;
}
}
template <typename T>
void Screen<T>::dumpState()
{
eventListener_.dumpState();
}
template <typename T>
void Screen<T>::dumpState(std::string const& _message, std::ostream& _os) const
{
auto const hline = [&]() {
for_each(crispy::times(*pageSize_.columns), [&](auto) { _os << '='; });
_os << endl;
};
auto const gridInfoLine = [&](Grid<Cell> const& grid) {
return fmt::format(
"main page lines: scrollback cur {} max {}, main page lines {}, used lines {}, zero index {}\n",
grid.historyLineCount(),
grid.maxHistoryLineCount(),
grid.pageSize().lines,
grid.linesUsed(),
grid.zero_index());
};
if (!_message.empty())
{
hline();
_os << "\033[1;37;41m" << _message << "\033[m" << endl;
hline();
}
_os << fmt::format("Rendered screen at the time of failure\n");
_os << fmt::format("main page size : {}\n", pageSize_);
_os << fmt::format("history line count : {} (max {})\n", historyLineCount(), maxHistoryLineCount());
_os << fmt::format("cursor position : {}\n", cursor_);
if (cursor_.originMode)
_os << fmt::format("real cursor position : {})\n", toRealCoordinate(cursor_.position));
_os << fmt::format("vertical margins : {}\n", margin_.vertical);
_os << fmt::format("horizontal margins : {}\n", margin_.horizontal);
_os << gridInfoLine(grid());
hline();
_os << screenshot([this](LineOffset _lineNo) -> string {
// auto const absoluteLine = grid().toAbsoluteLine(_lineNo);
return fmt::format("| {:>4}: {}", _lineNo.value, grid().lineAt(_lineNo).flags());
});
hline();
// TODO: print more useful debug information
// - screen size
// - left/right margin
// - top/down margin
// - cursor position
// - autoWrap
// - ... other output related modes
}
template <typename T>
void Screen<T>::smGraphics(XtSmGraphics::Item _item, XtSmGraphics::Action _action, XtSmGraphics::Value _value)
{
using Item = XtSmGraphics::Item;
using Action = XtSmGraphics::Action;
constexpr auto NumberOfColorRegistersItem = 1;
constexpr auto SixelItem = 2;
constexpr auto Success = 0;
constexpr auto Failure = 3;
switch (_item)
{
case Item::NumberOfColorRegisters:
switch (_action)
{
case Action::Read: {
auto const value = imageColorPalette_->size();
reply("\033[?{};{};{}S", NumberOfColorRegistersItem, Success, value);
break;
}
case Action::ReadLimit: {
auto const value = imageColorPalette_->maxSize();
reply("\033[?{};{};{}S", NumberOfColorRegistersItem, Success, value);
break;
}
case Action::ResetToDefault: {
auto const value = maxImageColorRegisters_;
imageColorPalette_->setSize(value);
reply("\033[?{};{};{}S", NumberOfColorRegistersItem, Success, value);
break;
}
case Action::SetToValue: {
visit(overloaded {
[&](int _number) {
imageColorPalette_->setSize(_number);
reply("\033[?{};{};{}S", NumberOfColorRegistersItem, Success, _number);
},
[&](ImageSize) { reply("\033[?{};{};{}S", NumberOfColorRegistersItem, Failure, 0); },
[&](monostate) { reply("\033[?{};{};{}S", NumberOfColorRegistersItem, Failure, 0); },
},
_value);
break;
}
}
break;
case Item::SixelGraphicsGeometry:
switch (_action)
{
case Action::Read:
reply("\033[?{};{};{};{}S", SixelItem, Success, maxImageSize_.width, maxImageSize_.height);
break;
case Action::ReadLimit:
reply("\033[?{};{};{};{}S",
SixelItem,
Success,
maxImageSizeLimit_.width,
maxImageSizeLimit_.height);
break;
case Action::ResetToDefault:
// The limit is the default at the same time.
maxImageSize_ = maxImageSizeLimit_;
break;
case Action::SetToValue:
if (holds_alternative<ImageSize>(_value))
{
auto size = get<ImageSize>(_value);
size.width = min(size.width, maxImageSizeLimit_.width);
size.height = min(size.height, maxImageSizeLimit_.height);
maxImageSize_ = size;
reply("\033[?{};{};{};{}S", SixelItem, Success, size.width, size.height);
}
else
reply("\033[?{};{};{}S", SixelItem, Failure, 0);
break;
}
break;
case Item::ReGISGraphicsGeometry: // Surely, we don't do ReGIS just yet. :-)
break;
}
}
// }}}
} // namespace terminal
#include <terminal/Terminal.h>
template class terminal::Screen<terminal::Terminal>;
#include <terminal/MockTerm.h>
template class terminal::Screen<terminal::MockTerm>;
// template class terminal::Screen<terminal::MockScreenEvents>;
| 33.999274 | 114 | 0.617137 | [
"render",
"shape",
"vector",
"transform"
] |
f50ee25dd07c63b3e3fb834181260c36f4b12998 | 13,216 | cpp | C++ | src/tests/utils/test_fdm_rungekutta4.cpp | fe5084/mscsim | 2b0025a9e4bda69b0d83147b1e701375fef437f8 | [
"MIT"
] | 1 | 2020-02-11T08:17:23.000Z | 2020-02-11T08:17:23.000Z | src/tests/utils/test_fdm_rungekutta4.cpp | fe5084/mscsim | 2b0025a9e4bda69b0d83147b1e701375fef437f8 | [
"MIT"
] | null | null | null | src/tests/utils/test_fdm_rungekutta4.cpp | fe5084/mscsim | 2b0025a9e4bda69b0d83147b1e701375fef437f8 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <QString>
#include <QtTest>
#include <fdm/utils/fdm_RungeKutta4.h>
////////////////////////////////////////////////////////////////////////////////
#define ZERO 1.0e-9
#define T_MAX 10.0
#define T_STEP 1.0e-2
// max error due to T_STEP for 4th order method ( 10^-2 )^4 = 10^-6
#define DELTA_MAX 1.0e-6
////////////////////////////////////////////////////////////////////////////////
using namespace std;
////////////////////////////////////////////////////////////////////////////////
/**
* @brief The RungeKutta4Test class, a fdm::RungeKutta4 integrator unit test class.
*
* Linear homogeneous ordinary differential (Cauchy–Euler) equation is used to
* test RungeKutta4 numerical integration class. Results obtained using a
* fdm::RungeKutta4 are going to be compared with results of differential equation
* analytical solution.
*
* Mass-Spring-Damper (MSD) model is used as an example. MSD is described
* by the following differential equation:
* m * (d^2 x)/(d t^2) = -k * x - c * dx/dt
* Where:
* m - mass
* k - stiffness
* c - damping
*
* This equation can be transformed to the following form:
* m * (d^2 x)/(d t^2) + c * dx/dt + k * x = 0 [1]
*
* Initial values are given as follows:
* x_0 = x ( t_0 = 0 )
* x_1 = x'( t_0 = 0 )
*
* Assuming that:
* x = e^( r * t )
* Then:
* x' = r * e^( r * t )
* x'' = r^2 * e^( r * t )
*
* Subsituting this into equation [1] gives:
* m * r^2 * e^( r * t ) + c * r * e^( r * t ) + k * e^( r * t ) = 0
*
* Dividing this equation by e^( r * t ) gives:
* m * r^2 + c * r + k = 0
*
* Discriminant of this equation is:
* Delta = c^2 - 4 * m * k
*
* If Delta > 0 then equation [1] has solution in the following form:
* x( t ) = C_1 * e^( r_1 * t ) + C_2 * e^( r_2 * t )
* Where:
* r_1 = ( -c - sqrt( Delta ) ) / ( 2 * m )
* r_2 = ( -c + sqrt( Delta ) ) / ( 2 * m )
* Then:
* x'( t ) = C_1 * r_1 * e^( r_1 * t ) + C_2 * r_2 * e^( r_2 * t )
* x'( 0 ) = C_1 * r_1 + C_2 * r_2
*
* If Delta = 0 then equation [1] has solution in the following form:
* x( t ) = ( C_1 * t + C_2 ) * e^( r_1 * t )
* Where:
* r_1 = -c / ( 2 * m )
* Then:
* x'( t ) = C_1 * e^( r_1 * t ) + ( C_1 * t + C_2 ) * r_1 * e^( r_1 * t )
* x'( 0 ) = C_1 + C_2 * r_1
*
* If Delta < 0 then equation [1] has solution in the following form:
* x( t ) = e^( a * t ) * ( C_1 * cos( b*t ) + C_2 * sin( b*t ) )
* Where:
* a = -c / ( 2 * m )
* b = sqrt( 4 * m * k - c^2 ) / ( 2 * m )
* Then:
* x'( t ) = a * e^( a * t ) * ( C_1 * cos( b*t ) + C_2 * sin( b*t ) )
* + e^( a * t ) * ( -C_1 * b * sin( b*t ) + C_2 * b * cos( b*t ) )
* x'( 0 ) = C_1 * a + C_2 * b
*
* @see Krysicki W., Wlodarski L.: Analiza matematyczna w zadaniach, Tom II. PWN, Ed. XXVII, 2018 [in Polish], p.287
*/
class RungeKutta4Test : public QObject
{
Q_OBJECT
public:
typedef fdm::RungeKutta4< 2, RungeKutta4Test > Integrator;
RungeKutta4Test();
void computeStateDeriv( const fdm::Vector< 2 > &state,
fdm::Vector< 2 > &deriv );
private:
double _m; ///< [kg] mass
double _k; ///< [N/m] stiffness
double _c; ///< [N/(m/s)] damping`
bool solve( double m,
double k,
double c,
double x_0,
double x_1 );
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void test1_1();
void test1_2();
void test1_3();
void test2_1();
void test2_2();
void test2_3();
void test3_1();
void test3_2();
void test3_3();
};
////////////////////////////////////////////////////////////////////////////////
double calcDelta( double a, double b, double c )
{
return b*b - 4.0 * a * c;
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::computeStateDeriv( const fdm::Vector< 2 > &state,
fdm::Vector< 2 > &deriv )
{
deriv( 0 ) = state( 1 );
deriv( 1 ) = -_k * state( 0 ) - _c * state( 1 );
}
////////////////////////////////////////////////////////////////////////////////
bool RungeKutta4Test::solve( double m,
double k,
double c,
double x_0,
double x_1 )
{
_m = m;
_k = k;
_c = c;
// state vector
// index 0: x
// index 1: dx/dt
fdm::Vector< 2 > s;
// initial conditions
s( 0 ) = x_0;
s( 1 ) = x_1;
Integrator *integrator = new Integrator( this, &RungeKutta4Test::computeStateDeriv );
double t = 0.0;
double x = 0.0;
// m * r^2 + c * r + k = 0
double delta = calcDelta( _m, _c, _k );
std::cout << "Delta= " << delta << std::endl;
if ( delta < -ZERO ) // numerical zero
{
// x( t ) = e^( a * t ) * ( C_1 * cos( b*t ) + C_2 * sin( b*t ) )
// a = -c / ( 2 * m )
// b = sqrt( 4 * m * k - c^2 ) / ( 2 * m )
double a = -c / ( 2.0 * m );
double b = sqrt( 4.0*m*k - c*c ) / ( 2.0 * m );
// x ( t ) = e^( a * t ) * ( C_1 * cos( b*t ) + C_2 * sin( b*t ) )
// x'( t ) = a * e^( a * t ) * ( C_1 * cos( b*t ) + C_2 * sin( b*t ) )
// + e^( a * t ) * ( -C_1 * b * sin( b*t ) + C_2 * b * cos( b*t ) )
//
// x ( 0 ) = C_1
// x'( 0 ) = C_1 * a + C_2 * b
//
// x_0 = C_1
// x_1 = C_1 * a + C_2 * b
//
// C_1 = x_0
// C_2 = ( x_1 - C_1 * a ) / b
double c_1 = x_0;
double c_2 = ( x_1 - c_1 * a ) / b;
while ( t <= T_MAX )
{
x = exp( a * t ) * ( c_1 * cos( b*t ) + c_2 * sin( b*t ) );
//std::cout << t << "," << x << "," << s( 0 ) << std::endl;
if ( fabs( s( 0 ) - x ) > DELTA_MAX ) return false;
t += T_STEP;
integrator->integrate( T_STEP, s );
}
}
else if ( delta > ZERO ) // numerical zero
{
// x( t ) = C_1 * e^( r_1 * t ) + C_2 * e^( r_2 * t )
// r_1 = ( -c - sqrt( Delta ) ) / ( 2 * m )
// r_2 = ( -c + sqrt( Delta ) ) / ( 2 * m )
double sqrt_delta = sqrt( delta );
double r_1 = ( -_c - sqrt_delta ) / ( 2.0 * _m );
double r_2 = ( -_c + sqrt_delta ) / ( 2.0 * _m );
// x ( t ) = C_1 * e^( r_1 * t ) + C_2 * e^( r_2 * t )
// x'( t ) = C_1 * r_1 * e^( r_1 * t ) + C_2 * r_2 * e^( r_2 * t )
//
// x ( 0 ) = C_1 + C_2
// x'( 0 ) = C_1 * r_1 + C_2 * r_2
//
// x_0 = C_1 + C_2
// x_1 = C_1 * r_1 + C_2 * r_2
//
// C_2 = ( x_1 - x_0 * r_1 ) / ( r_2 - r_1 )
// C_1 = x_0 - C_2
double c_2 = ( x_1 - x_0 * r_1 ) / ( r_2 - r_1 );
double c_1 = x_0 - c_2;
while ( t <= T_MAX )
{
x = c_1 * exp( r_1 * t ) + c_2 * exp( r_2 * t );
//std::cout << t << "," << x << "," << s( 0 ) << std::endl;
if ( fabs( s( 0 ) - x ) > DELTA_MAX ) return false;
t += T_STEP;
integrator->integrate( T_STEP, s );
}
}
else // delta == numerical zero
{
// x( t ) = ( C_1 * t + C_2 ) * e^( r_1 * t )
// r_1 = -c / ( 2 * m )
double r_1 = -c / ( 2.0 * m );
// x ( t ) = ( C_1 * t + C_2 ) * e^( r_1 * t )
// x'( t ) = C_1 * e^( r_1 * t ) + ( C_1 * t + C_2 ) * r_1 * e^( r_1 * t )
//
// x ( 0 ) = C_2
// x'( 0 ) = C_1 + C_2 * r_1
//
// x_0 = C_2
// x_1 = C_1 + C_2 * r_1
//
// C_2 = x_0
// C_1 = x_1 - C_2 * r_1
double c_2 = x_0;
double c_1 = x_1 - c_2 * r_1;
while ( t <= T_MAX )
{
x = ( c_1 * t + c_2 ) * exp( r_1 * t );
//std::cout << t << "," << x << "," << s( 0 ) << std::endl;
if ( fabs( s( 0 ) - x ) > DELTA_MAX ) return false;
t += T_STEP;
integrator->integrate( T_STEP, s );
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
RungeKutta4Test::RungeKutta4Test() {}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::initTestCase() {}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::cleanupTestCase() {}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test1_1()
{
std::cout << "test1_1()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 3.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 0.0; // [m]
const double x_1 = 1.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test1_2()
{
std::cout << "test1_2()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 3.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 1.0; // [m]
const double x_1 = 0.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test1_3()
{
std::cout << "test1_3()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 3.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 1.0; // [m]
const double x_1 = 1.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test2_1()
{
std::cout << "test2_1()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 1.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 0.0; // [m]
const double x_1 = 1.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test2_2()
{
std::cout << "test2_2()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 1.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 1.0; // [m]
const double x_1 = 0.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test2_3()
{
std::cout << "test2_3()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 1.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 1.0; // [m]
const double x_1 = 1.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test3_1()
{
std::cout << "test3_1()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 2.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 0.0; // [m]
const double x_1 = 1.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test3_2()
{
std::cout << "test3_2()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 2.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 1.0; // [m]
const double x_1 = 0.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
void RungeKutta4Test::test3_3()
{
std::cout << "test3_3()" << std::endl;
// model parameters:
const double m = 1.0; // [kg]
const double k = 1.0; // [N/m]
const double c = 2.0; // [N/(m/s)]
// initial conditions:
const double x_0 = 1.0; // [m]
const double x_1 = 1.0; // [m/s]
QVERIFY2( solve( m, k, c, x_0, x_1 ), "Failure" );
}
////////////////////////////////////////////////////////////////////////////////
QTEST_APPLESS_MAIN(RungeKutta4Test)
////////////////////////////////////////////////////////////////////////////////
#include "test_fdm_rungekutta4.moc"
| 27.706499 | 116 | 0.390814 | [
"vector",
"model"
] |
f51593dd584f3d5f906a05294126eee75381acec | 1,704 | cpp | C++ | source/Kai/Exception.cpp | ioquatix/kai | 4f8d00cd05b4123b6389f8dc3187ec1421b4f2da | [
"Unlicense",
"MIT"
] | 4 | 2016-07-19T08:53:09.000Z | 2021-08-03T10:06:41.000Z | source/Kai/Exception.cpp | ioquatix/kai | 4f8d00cd05b4123b6389f8dc3187ec1421b4f2da | [
"Unlicense",
"MIT"
] | null | null | null | source/Kai/Exception.cpp | ioquatix/kai | 4f8d00cd05b4123b6389f8dc3187ec1421b4f2da | [
"Unlicense",
"MIT"
] | null | null | null | //
// Exception.cpp
// This file is part of the "Kai" project, and is released under the MIT license.
//
// Created by Samuel Williams on 13/04/10.
// Copyright 2010 Samuel Williams. All rights reserved.
//
//
#include "Exception.hpp"
#include "Object.hpp"
#include "Symbol.hpp"
#include "Frame.hpp"
namespace Kai {
Exception::Exception(StringT what, Frame * frame) : _what(what), _object(NULL), _frame(frame) {
}
Exception::Exception(StringT what, Object * object, Frame * frame) : _what(what), _object(object), _frame(frame) {
}
Exception::~Exception() {
}
Frame * Exception::top () {
return _frame;
}
StringT Exception::message () noexcept {
if (_object)
return name() + " : " + _what + " : " + Object::to_string(_frame, _object);
else
return name() + " : " + _what;
}
const char* Exception::what() const noexcept {
return _what.c_str();
}
StringT Exception::name() noexcept {
return "Exception";
}
// MARK: -
ArgumentError::ArgumentError(StringT name, StringT type, Object * value, Frame * frame) : Exception("Error converting argument", value, frame), _name(name), _type(type) {
}
StringT ArgumentError::message() noexcept {
if (_object) {
return name() + " : Expecting " + _name + " of type " + _type + ", got " + _object->identity(_frame)->value() + "!";
} else {
return name() + " : Expecting " + _name + " of type " + _type + ", got nil!";
}
}
StringT ArgumentError::name() noexcept {
return "Argument Error";
}
// MARK: -
RangeError::RangeError(StringT what, Object * value, Frame * frame) : Exception(what, value, frame) {
}
StringT RangeError::name() noexcept {
return "Range Error";
}
}
| 22.421053 | 171 | 0.635563 | [
"object"
] |
f51670d9ef1a7ead2a76cecb9bc5fdc232ccb65c | 6,403 | cc | C++ | content/browser/contacts/contacts_provider_android.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | content/browser/contacts/contacts_provider_android.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | content/browser/contacts/contacts_provider_android.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/contacts/contacts_provider_android.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/android/jni_string.h"
#include "base/callback.h"
#include "base/metrics/histogram_functions.h"
#include "components/url_formatter/elide_url.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/public/android/content_jni_headers/ContactsDialogHost_jni.h"
#include "content/public/browser/contacts_picker_properties_requested.h"
#include "content/public/browser/web_contents.h"
#include "url/origin.h"
namespace content {
namespace {
void RecordAddressContainsDerivedField(
const payments::mojom::PaymentAddress& address) {
if (address.address_line.empty() || address.address_line.front().empty())
return;
bool has_derived_field = !address.city.empty() || !address.country.empty() ||
!address.postal_code.empty() ||
!address.region.empty();
base::UmaHistogramBoolean("Android.ContactsPicker.AddressHasDerivedField",
has_derived_field);
}
} // namespace
ContactsProviderAndroid::ContactsProviderAndroid(
RenderFrameHostImpl* render_frame_host) {
JNIEnv* env = base::android::AttachCurrentThread();
WebContents* web_contents =
WebContents::FromRenderFrameHost(render_frame_host);
if (!web_contents || !web_contents->GetTopLevelNativeWindow())
return;
formatted_origin_ = url_formatter::FormatUrlForSecurityDisplay(
render_frame_host->GetLastCommittedOrigin().GetURL(),
url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC);
dialog_.Reset(
Java_ContactsDialogHost_create(env, web_contents->GetJavaWebContents(),
reinterpret_cast<intptr_t>(this)));
DCHECK(!dialog_.is_null());
}
ContactsProviderAndroid::~ContactsProviderAndroid() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_ContactsDialogHost_destroy(env, dialog_);
}
void ContactsProviderAndroid::Select(bool multiple,
bool include_names,
bool include_emails,
bool include_tel,
bool include_addresses,
bool include_icons,
ContactsSelectedCallback callback) {
if (!dialog_) {
std::move(callback).Run(absl::nullopt, /*percentage_shared=*/-1,
PROPERTIES_NONE);
return;
}
callback_ = std::move(callback);
JNIEnv* env = base::android::AttachCurrentThread();
Java_ContactsDialogHost_showDialog(
env, dialog_, multiple, include_names, include_emails, include_tel,
include_addresses, include_icons,
base::android::ConvertUTF16ToJavaString(env, formatted_origin_));
}
void ContactsProviderAndroid::AddContact(
JNIEnv* env,
const base::android::JavaParamRef<jobjectArray>& names_java,
const base::android::JavaParamRef<jobjectArray>& emails_java,
const base::android::JavaParamRef<jobjectArray>& tel_java,
const base::android::JavaParamRef<jobjectArray>& addresses_java,
const base::android::JavaParamRef<jobjectArray>& icons_java) {
DCHECK(callback_);
absl::optional<std::vector<std::string>> names;
if (names_java) {
std::vector<std::string> names_vector;
AppendJavaStringArrayToStringVector(env, names_java, &names_vector);
names = std::move(names_vector);
}
absl::optional<std::vector<std::string>> emails;
if (emails_java) {
std::vector<std::string> emails_vector;
AppendJavaStringArrayToStringVector(env, emails_java, &emails_vector);
emails = std::move(emails_vector);
}
absl::optional<std::vector<std::string>> tel;
if (tel_java) {
std::vector<std::string> tel_vector;
AppendJavaStringArrayToStringVector(env, tel_java, &tel_vector);
tel = std::move(tel_vector);
}
absl::optional<std::vector<payments::mojom::PaymentAddressPtr>> addresses;
if (addresses_java) {
std::vector<payments::mojom::PaymentAddressPtr> addresses_vector;
for (const base::android::JavaRef<jbyteArray>& j_address :
addresses_java.ReadElements<jbyteArray>()) {
payments::mojom::PaymentAddressPtr address;
if (!payments::mojom::PaymentAddress::Deserialize(
static_cast<jbyte*>(env->GetDirectBufferAddress(j_address.obj())),
env->GetDirectBufferCapacity(j_address.obj()), &address)) {
continue;
}
RecordAddressContainsDerivedField(*address);
addresses_vector.push_back(std::move(address));
}
addresses = std::move(addresses_vector);
}
absl::optional<std::vector<blink::mojom::ContactIconBlobPtr>> icons;
if (icons_java) {
std::vector<blink::mojom::ContactIconBlobPtr> icons_vector;
for (const base::android::JavaRef<jbyteArray>& j_icon :
icons_java.ReadElements<jbyteArray>()) {
blink::mojom::ContactIconBlobPtr icon;
if (!blink::mojom::ContactIconBlob::Deserialize(
static_cast<jbyte*>(env->GetDirectBufferAddress(j_icon.obj())),
env->GetDirectBufferCapacity(j_icon.obj()), &icon)) {
continue;
}
icons_vector.push_back(std::move(icon));
}
icons = std::move(icons_vector);
}
blink::mojom::ContactInfoPtr contact = blink::mojom::ContactInfo::New(
std::move(names), std::move(emails), std::move(tel), std::move(addresses),
std::move(icons));
contacts_.push_back(std::move(contact));
}
void ContactsProviderAndroid::EndContactsList(JNIEnv* env,
jint percentage_shared,
jint properties_requested) {
DCHECK(callback_);
ContactsPickerPropertiesRequested properties =
static_cast<ContactsPickerPropertiesRequested>(properties_requested);
std::move(callback_).Run(std::move(contacts_), percentage_shared, properties);
}
void ContactsProviderAndroid::EndWithPermissionDenied(JNIEnv* env) {
DCHECK(callback_);
std::move(callback_).Run(absl::nullopt, /*percentage_shared=*/-1,
PROPERTIES_NONE);
}
} // namespace content
| 36.380682 | 80 | 0.682493 | [
"vector"
] |
f51bdb752084685c585c52be05330cc2efc1b15a | 949 | hh | C++ | src/network/server/RsDevice.hh | IntelRealSenseArchive/lrs-net | 2bfd0f5532673733c0506af3d18fb1c2cabcd40d | [
"Apache-2.0"
] | null | null | null | src/network/server/RsDevice.hh | IntelRealSenseArchive/lrs-net | 2bfd0f5532673733c0506af3d18fb1c2cabcd40d | [
"Apache-2.0"
] | 2 | 2020-05-14T11:10:06.000Z | 2020-05-14T11:10:15.000Z | src/network/server/RsDevice.hh | IntelRealSenseArchive/lrs-net | 2bfd0f5532673733c0506af3d18fb1c2cabcd40d | [
"Apache-2.0"
] | null | null | null | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.
#pragma once
#include <librealsense2/rs.hpp>
#include "RsUsageEnvironment.h"
#include "RsSensor.hh"
#include <map>
#include <librealsense2/hpp/rs_device.hpp>
class RsDevice
{
public:
RsDevice(UsageEnvironment *t_env, rs2::device dev);
~RsDevice();
std::vector<RsSensor>& getSensors()
{
return m_sensors;
}
static int getPhysicalSensorUniqueKey(rs2_stream stream_type, int sensors_index);
// sensor index
// map for stream pysical sensor
// key is generated by rs2_stream+index: depth=1,color=2,irl=3,irr=4
// todo: make smart_ptr
std::map<std::pair<int, int>, rs2_extrinsics> minimal_extrinsics_map;
rs2::device getDevice()
{
return m_device;
}
private:
rs2::device m_device;
std::vector<RsSensor> m_sensors;
UsageEnvironment* env;
};
| 22.595238 | 85 | 0.691254 | [
"vector"
] |
f51d563fc5ee1084b054feaa2c5c095fc2a25345 | 668 | hpp | C++ | src/VkRenderer/ImageView.hpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | 2 | 2020-05-31T19:54:19.000Z | 2021-09-14T12:00:12.000Z | src/VkRenderer/ImageView.hpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | src/VkRenderer/ImageView.hpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | #pragma once
#include "VulkanDevice.hpp"
#include <vector>
namespace cdm
{
class Image;
class ImageView final : public VulkanDeviceObject
{
std::reference_wrapper<Image> m_image;
Movable<VkImageView> m_imageView = nullptr;
VkFormat m_format;
public:
ImageView(const VulkanDevice& device_, Image& image_);
ImageView(const VulkanDevice& device_, Image& image_, VkFormat format);
~ImageView();
void setImage(Image& image_);
void setImage(Image& image_, VkFormat format);
VkImageView imageView();
operator VkImageView() { return imageView(); }
private:
bool outdated() const;
void recreate();
};
} // namespace cdm
| 19.085714 | 73 | 0.708084 | [
"vector"
] |
f51d835f9ce38613badfe1599d2e9f60844537a1 | 29,075 | cpp | C++ | Settings/src/Types/LocaleWakeWordsSetting.cpp | tsweet77/avs-device-sdk | 703b06188eae146af396f58be4e47442d7ce5b1e | [
"Apache-2.0"
] | 1 | 2018-07-09T16:44:28.000Z | 2018-07-09T16:44:28.000Z | Settings/src/Types/LocaleWakeWordsSetting.cpp | tsweet77/avs-device-sdk | 703b06188eae146af396f58be4e47442d7ce5b1e | [
"Apache-2.0"
] | null | null | null | Settings/src/Types/LocaleWakeWordsSetting.cpp | tsweet77/avs-device-sdk | 703b06188eae146af396f58be4e47442d7ce5b1e | [
"Apache-2.0"
] | 2 | 2019-02-05T23:42:48.000Z | 2020-03-01T11:11:30.000Z | /*
* Copyright 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 <algorithm>
#include <atomic>
#include <limits>
#include <AVSCommon/Utils/Error/FinallyGuard.h>
#include <AVSCommon/Utils/Logger/Logger.h>
#include "Settings/SettingStringConversion.h"
#include "Settings/Types/LocaleWakeWordsSetting.h"
/// String to identify log entries originating from this file.
static const std::string TAG("LocaleWakeWordsSetting");
/**
* Create a LogEntry using this file's TAG and the specified event string.
*
* @param The event string for this @c LogEntry.
*/
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)
namespace alexaClientSDK {
namespace settings {
namespace types {
using namespace avsCommon::sdkInterfaces;
using namespace avsCommon::utils::error;
using namespace avsCommon::utils::json;
/// Key used for locale.
static const std::string LOCALE_KEY = "System.locales";
/// Key used for locale.
static const std::string WAKE_WORDS_KEY = "SpeechRecognizer.wakeWords";
/// Default wake word.
static const WakeWords DEFAULT_WAKE_WORDS{"ALEXA"};
/// The index of the primary locale.
static constexpr size_t PRIMARY_LOCALE_INDEX = 0;
/**
* Convert wakewords to the expected json.
*
* @param wakeWords The wake words to be converted to string.
* @return The wake words string representation.
*/
static std::string toJsonString(const WakeWords& wakeWords) {
return toSettingString<WakeWords>(wakeWords).second;
}
/**
* Utility function to send ChangedEvent for local changes and Report for AVS requested changes.
*
* @param sender The sender used to send the event to AVS.
* @param status The current setting status.
* @param jsonString The json string representing the value to be sent to AVS.
* @return true if event was sent successfully; @c false otherwise.
*/
static bool sendEvent(
const std::shared_ptr<SettingEventSenderInterface>& sender,
SettingStatus status,
const std::string& jsonString) {
switch (status) {
case SettingStatus::LOCAL_CHANGE_IN_PROGRESS:
case SettingStatus::NOT_AVAILABLE:
return sender->sendChangedEvent(jsonString).get();
case SettingStatus::AVS_CHANGE_IN_PROGRESS:
return sender->sendReportEvent(jsonString).get();
case SettingStatus::SYNCHRONIZED:
return false;
}
return false;
}
/**
* Create a request type given the setting status.
*
* @param status The setting status that will determine the type of request.
* @return The request type expected given @c status.
*/
static LocaleWakeWordsSetting::RequestType toRequestType(SettingStatus status) {
switch (status) {
case SettingStatus::LOCAL_CHANGE_IN_PROGRESS:
return LocaleWakeWordsSetting::RequestType::LOCAL;
case SettingStatus::AVS_CHANGE_IN_PROGRESS:
return LocaleWakeWordsSetting::RequestType::AVS;
case SettingStatus::NOT_AVAILABLE:
return LocaleWakeWordsSetting::RequestType::LOCAL;
case SettingStatus::SYNCHRONIZED:
return LocaleWakeWordsSetting::RequestType::NONE;
}
return LocaleWakeWordsSetting::RequestType::NONE;
}
/**
* Convert json to wake words.
*
* @param json The wake words json string representation.
* @return The wake words retrieved from the json string.
*/
static WakeWords toWakeWords(const std::string& jsonValue) {
return settings::fromSettingString<WakeWords>(jsonValue, WakeWords()).second;
}
/**
* Thread safe method used to get the next request id.
* @return The next id.
*/
static LocaleWakeWordsSetting::RequestId nextId() {
static std::atomic<LocaleWakeWordsSetting::RequestId> m_requestCounter{0};
return ++m_requestCounter;
}
/**
* Get primary locale.
*
* @param locales A collection of locales.
* @return The primary locale from this collection.
*/
static Locale getPrimary(const DeviceLocales& locales) {
if (locales.empty()) {
return "";
}
return locales[PRIMARY_LOCALE_INDEX];
}
std::shared_ptr<LocaleWakeWordsSetting> LocaleWakeWordsSetting::create(
std::shared_ptr<SettingEventSenderInterface> localeEventSender,
std::shared_ptr<SettingEventSenderInterface> wakeWordsEventSender,
std::shared_ptr<storage::DeviceSettingStorageInterface> settingStorage,
std::shared_ptr<avsCommon::sdkInterfaces::LocaleAssetsManagerInterface> assetsManager) {
ACSDK_DEBUG5(LX(__func__).d("settingName", "LocaleWakeWords"));
if (!localeEventSender) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullLocaleEventSender"));
return nullptr;
}
if (!wakeWordsEventSender) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullWakeWordsEventSender"));
return nullptr;
}
if (!settingStorage) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullSettingStorage"));
return nullptr;
}
if (!assetsManager) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullAssetsManager"));
return nullptr;
}
auto setting = std::shared_ptr<LocaleWakeWordsSetting>(
new LocaleWakeWordsSetting(localeEventSender, wakeWordsEventSender, settingStorage, assetsManager));
setting->restoreInitialValue();
return setting;
}
LocaleWakeWordsSetting::~LocaleWakeWordsSetting() {
std::lock_guard<std::mutex> lock{m_mutex};
if (m_pendingRequest) {
m_assetsManager->cancelOngoingChange();
}
}
SetSettingResult LocaleWakeWordsSetting::setLocales(const DeviceLocales& locales, RequestType requestType) {
const auto supportedLocales = m_assetsManager->getSupportedLocales();
for (const auto& locale : locales) {
if (supportedLocales.find(locale) == supportedLocales.end()) {
ACSDK_ERROR(LX("setLocalChangeFailed")
.d("reason", "unsupportedLocale")
.d("locale", locale)
.d("supported", toJsonString(supportedLocales)));
return SetSettingResult::INVALID_VALUE;
}
}
// make sure the locale combination is valid as well.
if (locales.size() > 1) {
const auto supportedLocaleCombinations = m_assetsManager->getSupportedLocaleCombinations();
if (supportedLocaleCombinations.find(locales) == supportedLocaleCombinations.end()) {
ACSDK_ERROR(LX("setLocalChangeFailed")
.d("reason", "unsupportedLocaleCombination")
.d("locales", toSettingString<DeviceLocales>(locales).second));
return SetSettingResult::INVALID_VALUE;
}
}
ACSDK_INFO(LX(__func__).d("locales", toSettingString<DeviceLocales>(locales).second));
std::lock_guard<std::mutex> lock{m_mutex};
if (m_pendingRequest) {
if (m_pendingRequest->locales == locales) {
ACSDK_DEBUG5(LX(__func__)
.d("result", "changeAlreadyPending")
.d("locale", toSettingString<DeviceLocales>(locales).second));
return SetSettingResult::NO_CHANGE;
}
m_assetsManager->cancelOngoingChange();
}
// If the changed is done locally and the value being set did not change, then we are done.
// If the changed is done via AVS, we still need to respond with an event even though the value is the same.
if ((RequestType::AVS != requestType) && (locales == LocalesSetting::get())) {
ACSDK_DEBUG5(LX(__func__)
.d("result", "requestValueAlreadyApplied")
.d("locale", toSettingString<DeviceLocales>(locales).second));
return SetSettingResult::NO_CHANGE;
}
WakeWords wakeWords;
bool allSupported = false;
auto wakeWordsRequestType = RequestType::NONE;
if (m_pendingRequest && (m_pendingRequest->wakeWordsRequestType != RequestType::NONE)) {
wakeWordsRequestType = m_pendingRequest->wakeWordsRequestType;
std::tie(allSupported, wakeWords) = supportedWakeWords(locales, m_pendingRequest->wakeWords);
} else {
std::tie(allSupported, wakeWords) = supportedWakeWords(locales, WakeWordsSetting::get());
}
if (!allSupported) {
wakeWordsRequestType = RequestType::LOCAL;
if (wakeWords.empty()) {
wakeWords = DEFAULT_WAKE_WORDS;
}
}
// If this is a request from AVS, set the state to AVS_CHANGE_IN_PROGRESS to ensure that any disruption while
// applying the setting will ensure that an event to AVS will be sent in response.
if (RequestType::AVS == requestType) {
m_localeStatus = SettingStatus::AVS_CHANGE_IN_PROGRESS;
if (!m_storage->updateSettingStatus(LOCALE_KEY, m_localeStatus)) {
ACSDK_WARN(LX(__func__).d("reason", "storageUpdateFailed"));
}
}
RequestParameters request{requestType, locales, wakeWordsRequestType, wakeWords};
m_pendingRequest.reset(new RequestParameters(request));
m_executor.submit([this, request] { executeChangeValue(request); });
return SetSettingResult::ENQUEUED;
}
SetSettingResult LocaleWakeWordsSetting::setWakeWords(const WakeWords& wakeWords, RequestType requestType) {
ACSDK_INFO(LX(__func__).d("wakeWords", toJsonString(wakeWords)));
DeviceLocales locales;
auto localeRequestType = RequestType::NONE;
if (wakeWords.empty()) {
ACSDK_ERROR(LX("setWakeWordsFailed").d("reason", "requireAtLeastOneWakeWord"));
return SetSettingResult::INVALID_VALUE;
}
std::lock_guard<std::mutex> lock{m_mutex};
if (m_pendingRequest) {
if (m_pendingRequest->wakeWords == wakeWords) {
ACSDK_DEBUG5(LX(__func__).d("result", "changeAlreadyPending").d("wakeWords", toJsonString(wakeWords)));
return SetSettingResult::NO_CHANGE;
}
m_assetsManager->cancelOngoingChange();
}
// If the changed is done locally and the value being set did not change, then we are done.
// If the changed is done via AVS, we still need to respond with an event even though the value is the same.
if ((RequestType::AVS != requestType) && (wakeWords == WakeWordsSetting::get())) {
ACSDK_DEBUG5(LX(__func__).d("result", "requestValueAlreadyApplied").d("wakeWords", toJsonString(wakeWords)));
return SetSettingResult::NO_CHANGE;
}
if (m_pendingRequest && (m_pendingRequest->localeRequestType != RequestType::NONE)) {
localeRequestType = m_pendingRequest->localeRequestType;
locales = m_pendingRequest->locales;
} else {
locales = LocalesSetting::get();
}
if (!supportedWakeWords(locales, wakeWords).first) {
ACSDK_ERROR(LX("setAvsWakeWordsChangeFailed")
.d("reason", "unsupportedWakeWords")
.d("wakeWords", toJsonString(wakeWords))
.d("locale", getPrimary(locales)));
return SetSettingResult::INVALID_VALUE;
}
// If this is a request from AVS, set the state to AVS_CHANGE_IN_PROGRESS to ensure that any disruption while
// applying the setting will ensure that an event to AVS will be sent in response.
if (RequestType::AVS == requestType) {
m_wakeWordsStatus = SettingStatus::AVS_CHANGE_IN_PROGRESS;
if (!m_storage->updateSettingStatus(WAKE_WORDS_KEY, m_wakeWordsStatus)) {
ACSDK_WARN(LX(__func__).d("reason", "storageUpdateFailed"));
}
}
RequestParameters request{localeRequestType, locales, requestType, wakeWords};
m_pendingRequest.reset(new RequestParameters(request));
m_executor.submit([this, request] { executeChangeValue(request); });
return SetSettingResult::ENQUEUED;
}
SetSettingResult LocaleWakeWordsSetting::setLocalChange(const WakeWords& wakeWords) {
return setWakeWords(wakeWords, RequestType::LOCAL);
}
SetSettingResult LocaleWakeWordsSetting::setLocalChange(const DeviceLocales& locales) {
return setLocales(locales, RequestType::LOCAL);
}
static bool returnValueFromSetSettingResult(const SetSettingResult& status) {
switch (status) {
case SetSettingResult::NO_CHANGE:
// fall-through
case SetSettingResult::ENQUEUED:
return true;
case SetSettingResult::BUSY:
// fall-through
case SetSettingResult::UNAVAILABLE_SETTING:
// fall-through
case SetSettingResult::INVALID_VALUE:
// fall-through
case SetSettingResult::INTERNAL_ERROR:
// fall-through
case SetSettingResult::UNSUPPORTED_OPERATION:
return false;
}
return false;
}
bool LocaleWakeWordsSetting::setAvsChange(const DeviceLocales& locales) {
auto status = setLocales(locales, RequestType::AVS);
return returnValueFromSetSettingResult(status);
}
bool LocaleWakeWordsSetting::setAvsChange(const WakeWords& wakeWords) {
auto status = setWakeWords(wakeWords, RequestType::AVS);
return returnValueFromSetSettingResult(status);
}
bool LocaleWakeWordsSetting::clearData(const DeviceLocales& locales) {
ACSDK_DEBUG5(LX(__func__).d("setting", LOCALE_KEY));
std::lock_guard<std::mutex> lock{m_mutex};
m_pendingRequest.reset();
m_localeStatus = SettingStatus::NOT_AVAILABLE;
LocalesSetting::m_value = locales;
// Clear customer's data before restoring the initial value
auto result = m_storage->deleteSetting(LOCALE_KEY);
if (result) {
// As m_localeStatus == SettingStatus::NOT_AVAILABLE restoreInitialValue()
// calls LocalesSetting::get() which returns LocalesSetting::m_value
restoreInitialValue();
}
return result;
}
bool LocaleWakeWordsSetting::clearData(const WakeWords& wakeWords) {
ACSDK_DEBUG5(LX(__func__).d("setting", WAKE_WORDS_KEY));
std::lock_guard<std::mutex> lock{m_mutex};
m_pendingRequest.reset();
m_wakeWordsStatus = SettingStatus::NOT_AVAILABLE;
WakeWordsSetting::m_value = wakeWords;
// Clear customer's data before restoring the initial value
auto result = m_storage->deleteSetting(WAKE_WORDS_KEY);
if (result) {
// As m_wakeWordsStatus == SettingStatus::NOT_AVAILABLE restoreInitialValue()
// calls WakeWordsSetting::get() which returns WakeWordsSetting::m_value
restoreInitialValue();
}
return result;
}
void LocaleWakeWordsSetting::restoreInitialValue() {
std::string localeJsonValue;
std::tie(m_localeStatus, localeJsonValue) = m_storage->loadSetting(LOCALE_KEY);
if (m_localeStatus != SettingStatus::NOT_AVAILABLE) {
LocalesSetting::m_value = fromSettingString<DeviceLocales>(localeJsonValue, LocalesSetting::get()).second;
}
if (m_assetsManager->getDefaultSupportedWakeWords().empty()) {
// No wake words are supported by this device so there's no need to restore its value.
m_wakeWordsStatus = SettingStatus::SYNCHRONIZED;
WakeWordsSetting::m_value = WakeWords();
} else {
std::string wakeWordsJsonValue;
std::tie(m_wakeWordsStatus, wakeWordsJsonValue) = m_storage->loadSetting(WAKE_WORDS_KEY);
if (m_wakeWordsStatus != SettingStatus::NOT_AVAILABLE) {
WakeWordsSetting::m_value = toWakeWords(wakeWordsJsonValue);
}
}
DeviceLocales locales = LocalesSetting::get();
WakeWords wakeWords = WakeWordsSetting::get();
ACSDK_DEBUG2(LX(__func__)
.d("wakeWords", toJsonString(wakeWords))
.d("locale", toSettingString<DeviceLocales>(locales).second));
if (m_localeStatus != SettingStatus::SYNCHRONIZED || m_wakeWordsStatus != SettingStatus::SYNCHRONIZED) {
// If not synchronized, apply changes and synchronize.
RequestType localeRequestType = toRequestType(m_localeStatus);
RequestType wakeWordsRequestType = toRequestType(m_wakeWordsStatus);
auto pendingRequest = RequestParameters(localeRequestType, locales, wakeWordsRequestType, wakeWords);
m_pendingRequest.reset(new RequestParameters(pendingRequest));
m_executor.submit([this, pendingRequest] { executeChangeValue(pendingRequest); });
} else {
m_executor.submit([this, locales, wakeWords] {
// Make sure assets manager is correctly initialized.
if (!m_assetsManager->changeAssets(locales, wakeWords)) {
ACSDK_ERROR(LX("restoreInitialValueFailed")
.d("reason", "unableToRestoreAssetsManager")
.d("locale", toSettingString<DeviceLocales>(locales).second)
.d("wakeWords", toJsonString(wakeWords)));
}
});
}
}
LocaleWakeWordsSetting::LocaleWakeWordsSetting(
std::shared_ptr<SettingEventSenderInterface> localeEventSender,
std::shared_ptr<SettingEventSenderInterface> wakeWordsEventSender,
std::shared_ptr<storage::DeviceSettingStorageInterface> settingStorage,
std::shared_ptr<avsCommon::sdkInterfaces::LocaleAssetsManagerInterface> assetsManager) :
LocalesSetting{assetsManager->getDefaultLocales()},
WakeWordsSetting{DEFAULT_WAKE_WORDS},
m_localeEventSender{localeEventSender},
m_wakeWordsEventSender{wakeWordsEventSender},
m_storage{settingStorage},
m_localeStatus{SettingStatus::NOT_AVAILABLE},
m_wakeWordsStatus{SettingStatus::NOT_AVAILABLE},
m_assetsManager{assetsManager} {
}
void LocaleWakeWordsSetting::synchronize(const RequestParameters& request) {
if (m_wakeWordsStatus != SettingStatus::SYNCHRONIZED) {
synchronizeWakeWords(request);
}
if (m_localeStatus != SettingStatus::SYNCHRONIZED) {
synchronizeLocale(request);
}
}
void LocaleWakeWordsSetting::synchronizeWakeWords(const RequestParameters& request) {
if (sendEvent(m_wakeWordsEventSender, m_wakeWordsStatus, toJsonString(WakeWordsSetting::get()))) {
std::lock_guard<std::mutex> lock{m_mutex};
if (isLatestRequestLocked(request)) {
// Store SYNCHRONIZED in the database if no other request is in the queue.
m_wakeWordsStatus = SettingStatus::SYNCHRONIZED;
if (!this->m_storage->updateSettingStatus(WAKE_WORDS_KEY, m_wakeWordsStatus)) {
ACSDK_ERROR(LX("synchronizeWakeWordsFailed").d("reason", "cannotUpdateWakeWord"));
}
}
} else {
ACSDK_ERROR(LX("synchronizeWakeWordsFailed").d("reason", "sendEventFailed"));
}
}
void LocaleWakeWordsSetting::synchronizeLocale(const RequestParameters& request) {
if (sendEvent(m_localeEventSender, m_localeStatus, toSettingString<DeviceLocales>(LocalesSetting::get()).second)) {
std::lock_guard<std::mutex> lock{m_mutex};
if (isLatestRequestLocked(request)) {
// Store SYNCHRONIZED in the database if no other request is in the queue.
m_localeStatus = SettingStatus::SYNCHRONIZED;
if (!this->m_storage->updateSettingStatus(LOCALE_KEY, m_localeStatus)) {
ACSDK_ERROR(LX("synchronizeLocaleFailed").d("reason", "cannotUpdateLocale"));
}
}
} else {
ACSDK_ERROR(LX("synchronizeLocaleFailed").d("reason", "sendEventFailed"));
}
}
void LocaleWakeWordsSetting::handleFailure(const RequestParameters& request) {
{
std::lock_guard<std::mutex> lock{m_mutex};
if (!isLatestRequestLocked(request)) {
// Stop immediately if a new request is already in the queue.
notifyObserversOfCancellationLocked(request);
return;
}
}
// Notify observers of failure.
ACSDK_ERROR(LX(__func__)
.d("wakeWords", toJsonString(request.wakeWords))
.d("locale", toSettingString<DeviceLocales>(request.locales).second));
notifyObserversOfFailure(request);
// Send report if we have a pending report.
synchronize(request);
}
bool LocaleWakeWordsSetting::storeValues(const RequestParameters& request) {
std::lock_guard<std::mutex> lock{m_mutex};
if (isLatestRequestLocked(request)) {
std::vector<std::tuple<std::string, std::string, SettingStatus>> dbValues;
auto localeStatus = m_localeStatus;
auto wakeWordsStatus = m_wakeWordsStatus;
if (request.localeRequestType != RequestType::NONE) {
localeStatus = (LocaleWakeWordsSetting::RequestType::AVS == request.localeRequestType)
? SettingStatus::AVS_CHANGE_IN_PROGRESS
: SettingStatus::LOCAL_CHANGE_IN_PROGRESS;
dbValues.push_back(
std::make_tuple(LOCALE_KEY, toSettingString<DeviceLocales>(request.locales).second, localeStatus));
}
if (request.wakeWordsRequestType != RequestType::NONE) {
wakeWordsStatus = (LocaleWakeWordsSetting::RequestType::AVS == request.wakeWordsRequestType)
? SettingStatus::AVS_CHANGE_IN_PROGRESS
: SettingStatus::LOCAL_CHANGE_IN_PROGRESS;
dbValues.push_back(std::make_tuple(WAKE_WORDS_KEY, toJsonString(request.wakeWords), wakeWordsStatus));
}
if (!dbValues.empty()) {
if (!this->m_storage->storeSettings(dbValues)) {
ACSDK_ERROR(LX("storeValueFailed").d("reason", "cannotSaveLocaleWakeWord"));
return false;
}
if (request.localeRequestType != RequestType::NONE) {
LocalesSetting::m_value = request.locales;
m_localeStatus = localeStatus;
}
if (request.wakeWordsRequestType != RequestType::NONE) {
WakeWordsSetting::m_value = request.wakeWords;
m_wakeWordsStatus = wakeWordsStatus;
}
}
}
return true;
}
void LocaleWakeWordsSetting::notifyObserversOfChangeInProgress(const RequestParameters& request) {
if (request.localeRequestType != RequestType::NONE) {
LocalesSetting::notifyObservers(
RequestType::AVS == request.localeRequestType ? SettingNotifications::AVS_CHANGE_IN_PROGRESS
: SettingNotifications::LOCAL_CHANGE_IN_PROGRESS);
}
if (request.wakeWordsRequestType != RequestType::NONE) {
WakeWordsSetting::notifyObservers(
RequestType::AVS == request.wakeWordsRequestType ? SettingNotifications::AVS_CHANGE_IN_PROGRESS
: SettingNotifications::LOCAL_CHANGE_IN_PROGRESS);
}
}
void LocaleWakeWordsSetting::notifyObserversOfCancellationLocked(const RequestParameters& request) {
ACSDK_DEBUG5(LX(__func__).d("id", request.id).d("pendingId", m_pendingRequest ? m_pendingRequest->id : -1));
if (request.localeRequestType != RequestType::NONE && (request.locales != m_pendingRequest->locales)) {
auto notification = (RequestType::AVS == request.localeRequestType)
? SettingNotifications::AVS_CHANGE_CANCELLED
: SettingNotifications::LOCAL_CHANGE_CANCELLED;
LocalesSetting::notifyObservers(notification);
}
if ((request.wakeWordsRequestType != RequestType::NONE) && (request.wakeWords != m_pendingRequest->wakeWords)) {
auto notification = (RequestType::AVS == request.wakeWordsRequestType)
? SettingNotifications::AVS_CHANGE_CANCELLED
: SettingNotifications::LOCAL_CHANGE_CANCELLED;
WakeWordsSetting::notifyObservers(notification);
}
}
void LocaleWakeWordsSetting::notifyObserversOfFailure(const RequestParameters& request) {
ACSDK_DEBUG5(LX(__func__).d("id", request.id));
if (request.localeRequestType != RequestType::NONE) {
auto notification = (RequestType::AVS == request.localeRequestType) ? SettingNotifications::AVS_CHANGE_FAILED
: SettingNotifications::LOCAL_CHANGE_FAILED;
LocalesSetting::notifyObservers(notification);
}
if ((request.wakeWordsRequestType != RequestType::NONE)) {
auto notification = (RequestType::AVS == request.wakeWordsRequestType)
? SettingNotifications::AVS_CHANGE_FAILED
: SettingNotifications::LOCAL_CHANGE_FAILED;
WakeWordsSetting::notifyObservers(notification);
}
}
void LocaleWakeWordsSetting::notifyObserversOfSuccess(const RequestParameters& request) {
ACSDK_DEBUG5(LX(__func__).d("id", request.id));
if (request.localeRequestType != RequestType::NONE) {
auto notification = (RequestType::AVS == request.localeRequestType) ? SettingNotifications::AVS_CHANGE
: SettingNotifications::LOCAL_CHANGE;
LocalesSetting::notifyObservers(notification);
}
if ((request.wakeWordsRequestType != RequestType::NONE)) {
auto notification = (RequestType::AVS == request.wakeWordsRequestType) ? SettingNotifications::AVS_CHANGE
: SettingNotifications::LOCAL_CHANGE;
WakeWordsSetting::notifyObservers(notification);
}
}
bool LocaleWakeWordsSetting::isLatestRequestLocked(const RequestParameters& request) const {
return !m_pendingRequest || (m_pendingRequest->id == request.id);
}
void LocaleWakeWordsSetting::clearPendingRequest(const RequestParameters& request) {
std::lock_guard<std::mutex> lock{m_mutex};
if (isLatestRequestLocked(request)) {
m_pendingRequest.reset();
}
}
void LocaleWakeWordsSetting::executeChangeValue(const RequestParameters& request) {
ACSDK_DEBUG5(LX(__func__)
.d("RequestId", request.id)
.d("wwRequest", toJsonString(request.wakeWords))
.d("localeRequest", toSettingString<DeviceLocales>(request.locales).second));
{
std::lock_guard<std::mutex> lock{m_mutex};
if (!isLatestRequestLocked(request)) {
notifyObserversOfCancellationLocked(request);
return;
}
}
auto locales = (request.localeRequestType != RequestType::NONE) ? request.locales : LocalesSetting::get();
auto wakeWords = (request.wakeWordsRequestType != RequestType::NONE) ? request.wakeWords : WakeWordsSetting::get();
notifyObserversOfChangeInProgress(request);
// Apply the change.
bool ok = m_assetsManager->changeAssets(locales, wakeWords);
// Clear pending request field by the end of this method.
FinallyGuard finally{[this, &request] { clearPendingRequest(request); }};
if (!ok) {
ACSDK_ERROR(LX("changeAssetsFailed"));
handleFailure(request);
return;
}
if (!storeValues(request)) {
m_assetsManager->changeAssets(LocalesSetting::get(), WakeWordsSetting::get());
ACSDK_ERROR(LX("storeFailed"));
handleFailure(request);
return;
}
notifyObserversOfSuccess(request);
synchronize(request);
}
void LocaleWakeWordsSetting::onConnectionStatusChanged(const Status status, const ChangedReason reason) {
// Handle only transition to connected state.
if (Status::CONNECTED == status) {
// Create a dummy request that doesn't interrupt any ongoing operation but that respect newer requests.
RequestParameters request(RequestType::NONE, DeviceLocales(), RequestType::NONE, WakeWords());
m_executor.submit([this, request] { synchronize(request); });
}
}
std::pair<bool, WakeWords> LocaleWakeWordsSetting::supportedWakeWords(
const DeviceLocales& locales,
const WakeWords& wakeWords) {
auto supportedWakeWords = m_assetsManager->getSupportedWakeWords(getPrimary(locales));
WakeWords intersection;
if (supportedWakeWords.find(wakeWords) != supportedWakeWords.end()) {
intersection = wakeWords;
}
return std::make_pair(intersection.size() == wakeWords.size(), intersection);
}
LocaleWakeWordsSetting::RequestParameters::RequestParameters(
const LocaleWakeWordsSetting::RequestType requestTypeLocale,
const DeviceLocales& localesValue,
const LocaleWakeWordsSetting::RequestType requestTypeWakeWords,
const WakeWords& wakeWordsValue) :
id{nextId()},
localeRequestType{requestTypeLocale},
locales{localesValue},
wakeWordsRequestType{requestTypeWakeWords},
wakeWords{wakeWordsValue} {
}
} // namespace types
} // namespace settings
} // namespace alexaClientSDK
| 41.535714 | 120 | 0.683199 | [
"vector"
] |
f51f8387bbacc4842deaedccd27bc32b947ab907 | 10,243 | cpp | C++ | applications/GeoMechanicsApplication/custom_constitutive/bilinear_cohesive_2D_law.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | applications/GeoMechanicsApplication/custom_constitutive/bilinear_cohesive_2D_law.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | applications/GeoMechanicsApplication/custom_constitutive/bilinear_cohesive_2D_law.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | // KRATOS___
// // ) )
// // ___ ___
// // ____ //___) ) // ) )
// // / / // // / /
// ((____/ / ((____ ((___/ / MECHANICS
//
// License: geo_mechanics_application/license.txt
//
//
// Main authors: Ignasi de Pouplana,
// Vahid Galavi
//
// Application includes
#include "custom_constitutive/bilinear_cohesive_2D_law.hpp"
namespace Kratos
{
//Default Constructor
BilinearCohesive2DLaw::BilinearCohesive2DLaw() : BilinearCohesive3DLaw() {}
//----------------------------------------------------------------------------------------
//Copy Constructor
BilinearCohesive2DLaw::BilinearCohesive2DLaw(const BilinearCohesive2DLaw& rOther) : BilinearCohesive3DLaw(rOther) {}
//----------------------------------------------------------------------------------------
//Destructor
BilinearCohesive2DLaw::~BilinearCohesive2DLaw() {}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::GetLawFeatures(Features& rFeatures)
{
//Set the type of law
rFeatures.mOptions.Set( PLANE_STRAIN_LAW );
rFeatures.mOptions.Set( INFINITESIMAL_STRAINS );
rFeatures.mOptions.Set( ISOTROPIC );
//Set strain measure required by the consitutive law
rFeatures.mStrainMeasures.push_back(StrainMeasure_Infinitesimal);
//rFeatures.mStrainMeasures.push_back(StrainMeasure_Deformation_Gradient);
//Set the spacedimension
rFeatures.mSpaceDimension = WorkingSpaceDimension();
//Set the strain size
rFeatures.mStrainSize = GetStrainSize();
}
//----------------------------------------------------------------------------------------
ConstitutiveLaw::Pointer BilinearCohesive2DLaw::Clone() const
{
BilinearCohesive2DLaw::Pointer p_clone(new BilinearCohesive2DLaw(*this));
return p_clone;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeEquivalentStrain(double& rEquivalentStrain,
const Vector& StrainVector,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rEquivalentStrain = sqrt(StrainVector[0]*StrainVector[0]+StrainVector[1]*StrainVector[1])/CriticalDisplacement;
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeEquivalentStrainContact(double& rEquivalentStrain,
const Vector& StrainVector,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rEquivalentStrain = fabs(StrainVector[0])/CriticalDisplacement;
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeConstitutiveMatrixLoading(Matrix& rConstitutiveMatrix,
const Vector& StrainVector,
const double& YieldStress,
const double& DamageThreshold,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rConstitutiveMatrix(0,0) = YieldStress/((1.0-DamageThreshold)*CriticalDisplacement) * ( (1.0-mStateVariable)/mStateVariable-
StrainVector[0]*StrainVector[0]/(CriticalDisplacement*CriticalDisplacement*mStateVariable*mStateVariable*mStateVariable) );
rConstitutiveMatrix(1,1) = YieldStress/((1.0-DamageThreshold)*CriticalDisplacement) * ( (1.0-mStateVariable)/mStateVariable-
StrainVector[1]*StrainVector[1]/(CriticalDisplacement*CriticalDisplacement*mStateVariable*mStateVariable*mStateVariable) );
rConstitutiveMatrix(0,1) = -YieldStress*StrainVector[0]*StrainVector[1]/( (1.0-DamageThreshold)*
CriticalDisplacement*CriticalDisplacement*CriticalDisplacement*mStateVariable*mStateVariable*mStateVariable );
rConstitutiveMatrix(1,0) = rConstitutiveMatrix(0,1);
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeConstitutiveMatrixContactLoading(Matrix& rConstitutiveMatrix,
const Vector& StrainVector,
const double& YoungModulus,
const double& FrictionCoefficient,
const double& YieldStress,
const double& DamageThreshold,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rConstitutiveMatrix(0,0) = YieldStress/((1.0-DamageThreshold)*CriticalDisplacement) * ( (1.0-mStateVariable)/mStateVariable-
StrainVector[0]*StrainVector[0]/(CriticalDisplacement*CriticalDisplacement*mStateVariable*mStateVariable*mStateVariable) );
rConstitutiveMatrix(1,1) = YoungModulus/(DamageThreshold*CriticalDisplacement);
if(StrainVector[0] > 1.0e-20)
{
rConstitutiveMatrix(0,1) = -YieldStress*StrainVector[0]*StrainVector[1]/( (1.0-DamageThreshold)*
CriticalDisplacement*CriticalDisplacement*CriticalDisplacement*mStateVariable*mStateVariable*mStateVariable ) -
YoungModulus*FrictionCoefficient/(DamageThreshold*CriticalDisplacement);
}
else if(StrainVector[0] < -1.0e-20)
{
rConstitutiveMatrix(0,1) = -YieldStress*StrainVector[0]*StrainVector[1]/( (1.0-DamageThreshold)*
CriticalDisplacement*CriticalDisplacement*CriticalDisplacement*mStateVariable*mStateVariable*mStateVariable ) +
YoungModulus*FrictionCoefficient/(DamageThreshold*CriticalDisplacement);
}
else
{
rConstitutiveMatrix(0,1) = 0.0;
}
rConstitutiveMatrix(1,0) = 0.0;
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeConstitutiveMatrixUnloading(Matrix& rConstitutiveMatrix,
const double& YieldStress,
const double& DamageThreshold,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rConstitutiveMatrix(0,0) = YieldStress/(CriticalDisplacement*mStateVariable)*(1.0-mStateVariable)/(1.0-DamageThreshold);
rConstitutiveMatrix(1,1) = rConstitutiveMatrix(0,0);
rConstitutiveMatrix(0,1) = 0.0;
rConstitutiveMatrix(1,0) = 0.0;
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeConstitutiveMatrixContactUnloading(Matrix& rConstitutiveMatrix,
const Vector& StrainVector,
const double& YoungModulus,
const double& FrictionCoefficient,
const double& YieldStress,
const double& DamageThreshold,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rConstitutiveMatrix(0,0) = YieldStress/(CriticalDisplacement*mStateVariable)*(1.0-mStateVariable)/(1.0-DamageThreshold);
rConstitutiveMatrix(1,1) = YoungModulus/(DamageThreshold*CriticalDisplacement);
if(StrainVector[0] > 1.0e-20)
{
rConstitutiveMatrix(0,1) = -YoungModulus*FrictionCoefficient/(DamageThreshold*CriticalDisplacement);
}
else if(StrainVector[0] < -1.0e-20)
{
rConstitutiveMatrix(0,1) = YoungModulus*FrictionCoefficient/(DamageThreshold*CriticalDisplacement);
}
else
{
rConstitutiveMatrix(0,1) = 0.0;
}
rConstitutiveMatrix(1,0) = 0.0;
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeStressVector(Vector& rStressVector,
const Vector& StrainVector,
const double& YieldStress,
const double& DamageThreshold,
const double& CriticalDisplacement)
{
KRATOS_TRY;
rStressVector[0] = YieldStress/(CriticalDisplacement*mStateVariable)*(1.0-mStateVariable)/(1.0-DamageThreshold) * StrainVector[0];
rStressVector[1] = YieldStress/(CriticalDisplacement*mStateVariable)*(1.0-mStateVariable)/(1.0-DamageThreshold) * StrainVector[1];
KRATOS_CATCH("")
}
//----------------------------------------------------------------------------------------
void BilinearCohesive2DLaw::
ComputeStressVectorContact(Vector& rStressVector,
const Vector& StrainVector,
const double& YoungModulus,
const double& FrictionCoefficient,
const double& YieldStress,
const double& DamageThreshold,
const double& CriticalDisplacement)
{
KRATOS_TRY;
// Note: StrainVector[1] < 0.0
rStressVector[1] = YoungModulus/(DamageThreshold*CriticalDisplacement)*StrainVector[1];
if(StrainVector[0] > 1.0e-20)
{
rStressVector[0] = YieldStress/(CriticalDisplacement*mStateVariable)*(1.0-mStateVariable)/(1.0-DamageThreshold)*StrainVector[0] - FrictionCoefficient*rStressVector[1];
}
else if(StrainVector[0] < -1.0e-20)
{
rStressVector[0] = YieldStress/(CriticalDisplacement*mStateVariable)*(1.0-mStateVariable)/(1.0-DamageThreshold)*StrainVector[0] + FrictionCoefficient*rStressVector[1];
}
else
{
rStressVector[0] = 0.0;
}
KRATOS_CATCH("")
}
} // Namespace Kratos
| 39.09542 | 180 | 0.54896 | [
"vector"
] |
f520ca39e8208319ce928812ae8bfcfdcf6ca46d | 18,442 | cpp | C++ | source/ppm.cpp | tomberek/RaySAR | b8f885e1b640662b67a568cf8c41b8dcfc9a9c8d | [
"Zlib"
] | null | null | null | source/ppm.cpp | tomberek/RaySAR | b8f885e1b640662b67a568cf8c41b8dcfc9a9c8d | [
"Zlib"
] | null | null | null | source/ppm.cpp | tomberek/RaySAR | b8f885e1b640662b67a568cf8c41b8dcfc9a9c8d | [
"Zlib"
] | null | null | null | /****************************************************************************
* ppm.cpp
*
* This module contains the code to read and write the PPM file format.
*
* from Persistence of Vision(tm) Ray Tracer version 3.6.
* Copyright 1991-2003 Persistence of Vision Team
* Copyright 2003-2004 Persistence of Vision Raytracer Pty. Ltd.
*---------------------------------------------------------------------------
* NOTICE: This source code file is provided so that users may experiment
* with enhancements to POV-Ray and to port the software to platforms other
* than those supported by the POV-Ray developers. There are strict rules
* regarding how you are permitted to use this file. These rules are contained
* in the distribution and derivative versions licenses which should have been
* provided with this file.
*
* These licences may be found online, linked from the end-user license
* agreement that is located at http://www.povray.org/povlegal.html
*---------------------------------------------------------------------------
* This program is based on the popular DKB raytracer version 2.12.
* DKBTrace was originally written by David K. Buck.
* DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
*---------------------------------------------------------------------------
* $File: //depot/povray/3.6-release/source/ppm.cpp $
* $Revision: #3 $
* $Change: 3032 $
* $DateTime: 2004/08/02 18:43:41 $
* $Author: chrisc $
* $Log$
*****************************************************************************/
/****************************************************************************
*
* PPM format according to NetPBM specs (http://netpbm.sourceforge.net/doc/):
*
* This module implements read support for PPM image maps and
* write support for PPM output.
*
* For reading both ASCII and binary files are supported ('P3' and 'P6').
*
* For writing we use binary files. OutputQuality > 8 leads to 16 bit files.
* Special handling of HF_GRAY_16 -> 16 bit PGM files ('P5')
* All formats supported for writing can now also be used in continued trace.
*
*****************************************************************************/
#include "frame.h"
#include "povray.h"
#include "optout.h"
#include "pgm.h"
#include "ppm.h"
#include "pov_util.h"
#include "povmsend.h"
#include "colour.h"
#include <ctype.h>
BEGIN_POV_NAMESPACE
/*****************************************************************************
* Local preprocessor defines
******************************************************************************/
/*****************************************************************************
* Local typedefs
******************************************************************************/
/*****************************************************************************
* Local variables
******************************************************************************/
/*****************************************************************************
* Static functions
******************************************************************************/
/*****************************************************************************
*
* FUNCTION
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* DESCRIPTION
*
* CHANGES
*
******************************************************************************/
PPM_Image::PPM_Image(char *name, int w, int h, int m, int l)
{
int file_type;
unsigned char header[2];
char line[1024];
char *ptr;
int depth;
mode = m;
filename = name;
in_file = NULL;
out_file = NULL;
width = w ;
height = h ;
line_number = l;
// HF_GRAY_16 leads to 16 bit grayscale (PGM) output
if (opts.Options & HF_GRAY_16) file_type = POV_File_Image_PGM;
else file_type = POV_File_Image_PPM;
switch (mode)
{
case READ_MODE:
// We can't resume from stdout.
if (opts.Options & TO_STDOUT || (in_file = New_Checked_IStream(name, file_type)) == NULL)
{
return;
}
// --- Read Header ---
if (!in_file->read((char *)header, 2)) return;
if(header[0] != 'P') return;
if((header[1] != '5') && (header[1] != '6')) return;
do
{
in_file->getline (line, 1024);
line[1023] = '\0';
if ((ptr = strchr(line, '#')) != NULL) *ptr = '\0'; // remove comment
}
while (line[0]=='\0'); // read until line without comment from beginning
// --- First: two numbers: with and height ---
if (sscanf(line,"%d %d",&width, &height) != 2) return;
do
{
in_file->getline (line, 1024);
line[1023] = '\0';
if ((ptr = strchr(line, '#')) != NULL) *ptr = '\0'; // remove comment
}
while (line[0]=='\0'); // read until line without comment from beginning
// --- Second: one number: color depth ---
if (sscanf(line,"%d",&depth) != 1) return;
if ((depth > 65535) || (depth < 1)) return;
if (w != width || h != height)
Error ("PPM file dimensions do not match render resolution.");
Send_Progress("Resuming interrupted trace", PROGRESS_RESUMING_INTERRUPTED_TRACE);
break;
case WRITE_MODE:
if (opts.Options & TO_STDOUT)
{
out_file = New_OStream("stdout", file_type, false);
}
else if ((out_file = New_Checked_OStream(name, file_type, false)) == NULL)
{
return;
}
// HF_GRAY_16 leads to 16 bit grayscale (PGM) output
if (opts.Options & HF_GRAY_16)
{
out_file->printf("P5\n%d %d\n65535\n", w, h);
}
else
{
out_file->printf("P6\n%d %d\n%d\n", w, h, (1 << opts.OutputQuality) - 1);
}
width = w;
height = h;
break;
case APPEND_MODE:
if (opts.Options & TO_STDOUT)
{
out_file = New_OStream("stdout", file_type, true);
}
else if ((out_file = New_Checked_OStream(name, file_type, true)) == NULL)
{
return;
}
break;
}
valid = true;
}
/*****************************************************************************
*
* FUNCTION
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* DESCRIPTION
*
* CHANGES
*
* Identical to targa version
*
******************************************************************************/
PPM_Image::~PPM_Image()
{
// Close the input file (if open)
if(in_file != NULL)
delete in_file;
// Close the output file (if open)
if(out_file != NULL)
{
out_file->flush();
delete out_file;
}
in_file = NULL;
out_file = NULL;
}
/*****************************************************************************
*
* FUNCTION
*
* PPM_Image::Write_Line
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Christoph Hormann
*
* DESCRIPTION
*
* Writes an image line to PPM image file
*
* CHANGES
*
* August 2003 - New implementation based on targa/png code
*
******************************************************************************/
void PPM_Image::Write_Line(COLOUR *line_data)
{
if(valid == false)
Error("Cannot access output image file.");
register int x;
unsigned int rval, gval, bval, gray;
unsigned int mask;
COLC fac;
for (x = 0; x < width; x++)
{
// HF_GRAY_16 leads to 16 bit grayscale (PGM) output
if (opts.Options & HF_GRAY_16)
{
gray = (int)floor((GREY_SCALE3(line_data[x][pRED],line_data[x][pGREEN],line_data[x][pBLUE])) * 65535.0);
out_file->Write_Byte((gray >> 8) & 0xFF);
if (!out_file->Write_Byte(gray & 0xFF))
Error("Cannot write PPM output data to %s.",filename);
}
else
// otherwise 3*OutputQuality bit pixel coloring written to 8 or 16 bit file
{
mask = (1 << opts.OutputQuality) - 1 ;
fac = (COLC) (mask) ;
rval = (unsigned int)floor(line_data[x][pRED] * fac) & mask;
gval = (unsigned int)floor(line_data[x][pGREEN] * fac) & mask;
bval = (unsigned int)floor(line_data[x][pBLUE] * fac) & mask;
if (opts.OutputQuality>8) // 16 bit per value
{
out_file->Write_Byte(rval >> 8) ;
out_file->Write_Byte(rval & 0xFF) ;
out_file->Write_Byte(gval >> 8) ;
out_file->Write_Byte(gval & 0xFF) ;
out_file->Write_Byte(bval >> 8) ;
if (!out_file->Write_Byte(bval & 0xFF))
{
Error("Error writing PPM output data to %s.",filename);
}
}
else // 8 bit per value
{
out_file->Write_Byte(rval & 0xFF) ;
out_file->Write_Byte(gval & 0xFF) ;
if (!out_file->Write_Byte(bval & 0xFF))
{
Error("Cannot write PPM output data to %s.",filename);
}
}
}
}
line_number++;
out_file->flush();
}
/*****************************************************************************
*
* FUNCTION
*
* PPM_Image::Read_Line
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Christoph Hormann
*
* DESCRIPTION
*
* Reads a PPM image line for continued trace
*
* CHANGES
*
* August 2003 - New implementation based on targa/png code
*
******************************************************************************/
int PPM_Image::Read_Line(COLOUR *line_data)
{
if(valid == false)
Error("Cannot access output image file.");
int data, x;
int data_hi, data_lo;
if (in_file->eof()) return 0;
if (opts.Options & HF_GRAY_16)
{
for (x = 0; x < width; x++)
{
if ((data_hi = in_file->Read_Byte ()) == EOF)
{
if (x == 0)
{
return 0;
}
else
{
return -1;
}
}
if ((data_lo = in_file->Read_Byte ()) == EOF) return -1;
line_data[x][pRED] = ((COLC)(256*data_hi + data_lo))/65535.0;
line_data[x][pGREEN] = line_data[x][pRED];
line_data[x][pBLUE] = line_data[x][pRED];
}
}
/* depending on the output Quality settings we expect
* an 8 or 16 bit file. So using continued trace requires
* correct OutputQuality settings
*/
else if (opts.OutputQuality>8)
{
COLC fac = (COLC)((1 << opts.OutputQuality) - 1);
for (x = 0; x < width; x++)
{
/* Read the first data byte. If EOF is reached on the first
* character read, then this line hasn't been rendered yet.
* Return 0. If an EOF occurs somewhere within the line, this
* is an error - return -1.
*/
if ((data_hi = in_file->Read_Byte ()) == EOF)
{
if (x == 0)
{
return 0;
}
else
{
return -1;
}
}
if ((data_lo = in_file->Read_Byte ()) == EOF) return -1;
line_data[x][pRED] = ((COLC)(256*data_hi + data_lo))/fac;
if ((data_hi = in_file->Read_Byte ()) == EOF) return -1;
if ((data_lo = in_file->Read_Byte ()) == EOF) return -1;
line_data[x][pGREEN] = ((COLC)(256*data_hi + data_lo))/fac;
if ((data_hi = in_file->Read_Byte ()) == EOF) return -1;
if ((data_lo = in_file->Read_Byte ()) == EOF) return -1;
line_data[x][pBLUE] = ((COLC)(256*data_hi + data_lo))/fac;
}
}
else
{
for (x = 0; x < width; x++)
{
/* Read the first data byte. If EOF is reached on the first
* character read, then this line hasn't been rendered yet.
* Return 0. If an EOF occurs somewhere within the line, this
* is an error - return -1.
*/
if ((data = in_file->Read_Byte ()) == EOF)
{
if (x == 0)
{
return 0;
}
else
{
return -1;
}
}
line_data[x][pRED] = (DBL) data / 255.0;
// Read the GREEN data byte.
if ((data = in_file->Read_Byte ()) == EOF)
{
return -1;
}
line_data[x][pGREEN] = (DBL) data / 255.0;
// Read the BLUE data byte.
if ((data = in_file->Read_Byte ()) == EOF)
{
return -1;
}
line_data[x][pBLUE] = (DBL) data / 255.0;
}
}
line_number++;
return 1;
}
/*****************************************************************************
*
* FUNCTION
*
* Read_PPM_Image
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Christoph Hormann
*
* DESCRIPTION
*
* Reads an PPM image file
*
* CHANGES
*
* August 2003 - New implementation based on targa/png reading code
*
******************************************************************************/
void Read_PPM_Image(IMAGE *Image, char *name)
{
IStream *filep;
unsigned char header[2];
char line[1024];
char *ptr;
int nbr;
int width, height;
unsigned int depth;
IMAGE8_LINE *line_data;
IMAGE16_LINE *line_16_data;
int data_hi, data_lo;
int x, i;
// --- Start by trying to open the file ---
if((filep = Locate_File(name,POV_File_Image_PPM,NULL,true)) == NULL)
Error ("Cannot open PPM image %s.", name);
// --- Read Header ---
if (!filep->read((char *)header, 2))
Error ("Cannot read header of PPM image %s.", name);
if(header[0] != 'P') Error ("File is not in PPM format.");
if((header[1] != '3') && (header[1] != '6'))
Error ("File is not in PPM format (type %d).", header[1]);
do
{
filep->getline (line, 1024);
line[1023] = '\0';
if ((ptr = strchr(line, '#')) != NULL) *ptr = '\0'; // remove comment
}
while (line[0]=='\0'); // read until line without comment from beginning
// --- First: two numbers: with and height ---
if (sscanf(line,"%d %d",&width, &height) != 2)
Error ("Cannot read width and height from PPM image.");
if (width <= 0 || height <= 0)
Error ("Invalid width or height read from PPM image.");
do
{
filep->getline (line, 1024) ;
line[1023] = '\0';
if ((ptr = strchr(line, '#')) != NULL) *ptr = '\0'; // remove comment
}
while (line[0]=='\0'); // read until line without comment from beginning
// --- Second: one number: color depth ---
if (sscanf(line,"%d",&depth) != 1)
Error ("Cannot read color depth from PPM image.");
if ((depth > 65535) || (depth < 1))
Error ("Unsupported number of colors (%d) in PPM image.", depth);
Image->iwidth = width;
Image->iheight = height;
Image->width = (DBL)width;
Image->height = (DBL)height;
Image->Colour_Map = NULL;
Image->Colour_Map_Size = 0;
if (depth < 256)
{
Image->data.rgb8_lines = (IMAGE8_LINE *)POV_MALLOC(height * sizeof(IMAGE8_LINE), "PPM image");
for (i = 0; i < height; i++)
{
line_data = &Image->data.rgb8_lines[i];
line_data->red = (unsigned char *)POV_MALLOC(width, "PPM image line");
line_data->green = (unsigned char *)POV_MALLOC(width, "PPM image line");
line_data->blue = (unsigned char *)POV_MALLOC(width, "PPM image line");
line_data->transm = (unsigned char *)NULL;
if (header[1] == '3') // --- ASCII PPM file (type 3) ---
{
for (x = 0; x < width; x++)
{
nbr = Read_ASCII_File_Number(filep);
if (nbr >= 0) line_data->red[x] = (nbr*255)/depth;
else Error ("Cannot read image data from PPM image.");
nbr = Read_ASCII_File_Number(filep);
if (nbr >= 0) line_data->green[x] = (nbr*255)/depth;
else Error ("Cannot read image data from PPM image.");
nbr = Read_ASCII_File_Number(filep);
if (nbr >= 0) line_data->blue[x] = (nbr*255)/depth;
else Error ("Cannot read image data from PPM image.");
}
}
else // --- binary PPM file (type 6) ---
{
for (x = 0; x < width; x++)
{
if ((nbr = filep->Read_Byte ()) == EOF)
Error("Cannot read data from PPM image.");
line_data->red[x] = (nbr*255)/depth;
if ((nbr = filep->Read_Byte ()) == EOF)
Error("Cannot read data from PPM image.");
line_data->green[x] = (nbr*255)/depth;
if ((nbr = filep->Read_Byte ()) == EOF)
Error("Cannot read data from PPM image.");
line_data->blue[x] = (nbr*255)/depth;
}
}
}
}
else // --- 16 bit PPM (binary or ASCII) ---
{
Image->Image_Type |= IS16BITIMAGE;
Image->data.rgb16_lines = (IMAGE16_LINE *)POV_MALLOC(height * sizeof(IMAGE16_LINE), "PPM image");
for (i = 0; i < height; i++)
{
line_16_data = &Image->data.rgb16_lines[i];
line_16_data->red = (unsigned short *)POV_MALLOC(width * sizeof(unsigned short), "PPM image line");
line_16_data->green = (unsigned short *)POV_MALLOC(width * sizeof(unsigned short), "PPM image line");
line_16_data->blue = (unsigned short *)POV_MALLOC(width * sizeof(unsigned short), "PPM image line");
line_16_data->transm = (unsigned short *)NULL;
if (header[1] == '3') // --- ASCII PPM file (type 3) ---
{
for (x = 0; x < width; x++)
{
nbr = Read_ASCII_File_Number(filep);
if (nbr >= 0) line_16_data->red[x] = (nbr*65535)/depth;
else Error ("Cannot read image data from PPM image.");
nbr = Read_ASCII_File_Number(filep);
if (nbr >= 0) line_16_data->green[x] = (nbr*65535)/depth;
else Error ("Cannot read image data from PPM image.");
nbr = Read_ASCII_File_Number(filep);
if (nbr >= 0) line_16_data->blue[x] = (nbr*65535)/depth;
else Error ("Cannot read image data from PPM image.");
}
}
else // --- binary PPM file (type 6) ---
{
for (x = 0; x < width; x++)
{
if ((data_hi = filep->Read_Byte ()) == EOF)
Error ("Cannot read data from PPM image.");
if ((data_lo = filep->Read_Byte ()) == EOF)
Error ("Cannot read data from PPM image.");
line_16_data->red[x] = (256*data_hi + data_lo)*65535/depth;
if ((data_hi = filep->Read_Byte ()) == EOF)
Error ("Cannot read data from PPM image.");
if ((data_lo = filep->Read_Byte ()) == EOF)
Error ("Cannot read data from PPM image.");
line_16_data->green[x] = (256*data_hi + data_lo)*65535/depth;
if ((data_hi = filep->Read_Byte ()) == EOF)
Error ("Cannot read data from PPM image.");
if ((data_lo = filep->Read_Byte ()) == EOF)
Error ("Cannot read data from PPM image.");
line_16_data->blue[x] = (256*data_hi + data_lo)*65535/depth;
}
}
}
}
// Close the image file
delete filep;
}
END_POV_NAMESPACE
| 27.041056 | 110 | 0.509055 | [
"render"
] |
f5216c4e914afc42c877f833309fb70d6705fa19 | 5,023 | cpp | C++ | src/output.cpp | derektmueller/node-midi | 6bd679cbe5bca553dbac26f9568198fe9cf96cc7 | [
"MIT"
] | 10 | 2017-03-12T01:18:40.000Z | 2021-07-03T10:01:01.000Z | node_modules/midi/src/output.cpp | Adam13531/keyiano | 4cbb483a13726a933aff200ab78260f1eccedad1 | [
"MIT"
] | 1 | 2018-12-12T09:21:31.000Z | 2018-12-12T09:21:31.000Z | node_modules/midi/src/output.cpp | Adam13531/keyiano | 4cbb483a13726a933aff200ab78260f1eccedad1 | [
"MIT"
] | 3 | 2018-01-12T01:52:08.000Z | 2020-05-21T13:55:01.000Z | #include <nan.h>
#include "lib/RtMidi/RtMidi.h"
#include "output.h"
void NodeMidiOutput::Init(v8::Local<v8::Object> target)
{
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(NodeMidiOutput::New);
s_ct.Reset(t);
t->SetClassName(Nan::New<v8::String>("NodeMidiOutput").ToLocalChecked());
t->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(t, "getPortCount", GetPortCount);
Nan::SetPrototypeMethod(t, "getPortName", GetPortName);
Nan::SetPrototypeMethod(t, "openPort", OpenPort);
Nan::SetPrototypeMethod(t, "openVirtualPort", OpenVirtualPort);
Nan::SetPrototypeMethod(t, "closePort", ClosePort);
Nan::SetPrototypeMethod(t, "isPortOpen", IsPortOpen);
Nan::SetPrototypeMethod(t, "sendMessage", SendMessage);
Nan::Set(target, Nan::New<v8::String>("Output").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked());
}
NodeMidiOutput::NodeMidiOutput()
{
try {
out = new RtMidiOut();
}
catch(RtMidiError &e) {
out = NULL;
}
}
NodeMidiOutput::~NodeMidiOutput()
{
if (out) {
delete out;
}
}
NAN_METHOD(NodeMidiOutput::New)
{
Nan::HandleScope scope;
if (!info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to create instances of this object.");
}
NodeMidiOutput* output = new NodeMidiOutput();
output->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NodeMidiOutput::GetPortCount)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
v8::Local<v8::Integer> result = Nan::New<v8::Uint32>(output-> out ? output->out->getPortCount() : 0);
info.GetReturnValue().Set(result);
}
NAN_METHOD(NodeMidiOutput::GetPortName)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
if (info.Length() == 0 || !info[0]->IsUint32()) {
return Nan::ThrowTypeError("First argument must be an integer");
}
unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust();
try {
v8::Local<v8::String> result = Nan::New<v8::String>(output->out ? output->out->getPortName(portNumber).c_str() : "").ToLocalChecked();
info.GetReturnValue().Set(result);
}
catch(RtMidiError& e) {
info.GetReturnValue().Set(Nan::New<v8::String>("").ToLocalChecked());
}
}
NAN_METHOD(NodeMidiOutput::OpenPort)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
if (!output->out) return;
if (info.Length() == 0 || !info[0]->IsUint32()) {
return Nan::ThrowTypeError("First argument must be an integer");
}
unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust();
if (portNumber >= output->out->getPortCount()) {
return Nan::ThrowRangeError("Invalid MIDI port number");
}
try {
output->out->openPort(portNumber);
}
catch(RtMidiError& e) {
;
}
return;
}
NAN_METHOD(NodeMidiOutput::OpenVirtualPort)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
if (!output->out) return;
if (info.Length() == 0 || !info[0]->IsString()) {
return Nan::ThrowTypeError("First argument must be a string");
}
std::string name(*Nan::Utf8String(info[0]));
try {
output->out->openVirtualPort(name);
}
catch(RtMidiError& e) {
;
}
return;
}
NAN_METHOD(NodeMidiOutput::ClosePort)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
if (!output->out) return;
output->out->closePort();
return;
}
NAN_METHOD(NodeMidiOutput::IsPortOpen)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
if (!output->out) return;
v8::Local<v8::Boolean> result = Nan::New<v8::Boolean>(output->out->isPortOpen());
info.GetReturnValue().Set(result);
}
NAN_METHOD(NodeMidiOutput::SendMessage)
{
Nan::HandleScope scope;
NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This());
if (!output->out) return;
if (info.Length() == 0 || !info[0]->IsArray()) {
return Nan::ThrowTypeError("First argument must be an array");
}
v8::Local<v8::Object> message = Nan::To<v8::Object>(info[0]).ToLocalChecked();
int32_t messageLength = Nan::To<int32_t>(Nan::Get(message, Nan::New<v8::String>("length").ToLocalChecked()).ToLocalChecked()).FromJust();
std::vector<unsigned char> messageOutput;
for (int32_t i = 0; i != messageLength; ++i) {
messageOutput.push_back(Nan::To<unsigned int>(Nan::Get(message, Nan::New<v8::Integer>(i)).ToLocalChecked()).FromJust());
}
try {
output->out->sendMessage(&messageOutput);
}
catch(RtMidiError& e) {
;
}
return;
}
| 27.905556 | 142 | 0.648218 | [
"object",
"vector"
] |
f5238c1fb3ffb9d7c19b3c55f3d3fc1ecd5f55d7 | 1,281 | cc | C++ | default/vm/longjump.cc | ChangMinPark/immix-gc-dart | aad91578d9d80f13626f95d14c6513ced1d20286 | [
"MIT"
] | null | null | null | default/vm/longjump.cc | ChangMinPark/immix-gc-dart | aad91578d9d80f13626f95d14c6513ced1d20286 | [
"MIT"
] | null | null | null | default/vm/longjump.cc | ChangMinPark/immix-gc-dart | aad91578d9d80f13626f95d14c6513ced1d20286 | [
"MIT"
] | null | null | null | // Copyright (c) 2011, 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/longjump.h"
#include "include/dart_api.h"
#include "vm/dart_api_impl.h"
#include "vm/isolate.h"
#include "vm/object.h"
#include "vm/object_store.h"
#include "vm/os.h"
namespace dart {
jmp_buf* LongJumpScope::Set() {
ASSERT(top_ == NULL);
top_ = Thread::Current()->top_resource();
return &environment_;
}
void LongJumpScope::Jump(int value, const Error& error) {
// A zero is the default return value from setting up a LongJumpScope
// using Set.
ASSERT(value != 0);
Thread* thread = Thread::Current();
#if defined(DEBUG)
#define CHECK_REUSABLE_HANDLE(name) \
ASSERT(!thread->reusable_##name##_handle_scope_active());
REUSABLE_HANDLE_LIST(CHECK_REUSABLE_HANDLE)
#undef CHECK_REUSABLE_HANDLE
#endif // defined(DEBUG)
// Remember the error in the sticky error of this isolate.
thread->set_sticky_error(error);
// Destruct all the active StackResource objects.
StackResource::UnwindAbove(thread, top_);
longjmp(environment_, value);
UNREACHABLE();
}
} // namespace dart
| 27.255319 | 80 | 0.704137 | [
"object"
] |
f52527bc5d0b73eb47b2d41a368dea9b1af1e87c | 2,001 | cc | C++ | cloud-functions/functions/node_modules/grpc/third_party/boringssl/tool/ciphers.cc | Fumitoshi/friendlychat | e65b47032f0ede7963962601f5a9142628ed6a1b | [
"CC-BY-4.0"
] | 91 | 2018-11-24T05:33:58.000Z | 2022-03-16T05:58:05.000Z | cloud-functions/functions/node_modules/grpc/third_party/boringssl/tool/ciphers.cc | Fumitoshi/friendlychat | e65b47032f0ede7963962601f5a9142628ed6a1b | [
"CC-BY-4.0"
] | 11 | 2019-06-02T23:50:17.000Z | 2022-02-04T23:58:56.000Z | cloud-functions/functions/node_modules/grpc/third_party/boringssl/tool/ciphers.cc | Fumitoshi/friendlychat | e65b47032f0ede7963962601f5a9142628ed6a1b | [
"CC-BY-4.0"
] | 18 | 2018-11-24T10:35:29.000Z | 2021-04-22T07:22:10.000Z | /* Copyright (c) 2015, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <string>
#include <vector>
#include <stdint.h>
#include <stdlib.h>
#include <openssl/ssl.h>
#include "internal.h"
bool Ciphers(const std::vector<std::string> &args) {
if (args.size() != 1) {
fprintf(stderr, "Usage: bssl ciphers <cipher suite string>\n");
return false;
}
const std::string &ciphers_string = args.back();
bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(SSLv23_client_method()));
if (!SSL_CTX_set_cipher_list(ctx.get(), ciphers_string.c_str())) {
fprintf(stderr, "Failed to parse cipher suite config.\n");
ERR_print_errors_fp(stderr);
return false;
}
const struct ssl_cipher_preference_list_st *pref_list = ctx->cipher_list;
STACK_OF(SSL_CIPHER) *ciphers = pref_list->ciphers;
bool last_in_group = false;
for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
bool in_group = pref_list->in_group_flags[i];
const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
if (in_group && !last_in_group) {
printf("[\n ");
} else if (last_in_group) {
printf(" ");
}
printf("%s\n", SSL_CIPHER_get_name(cipher));
if (!in_group && last_in_group) {
printf("]\n");
}
last_in_group = in_group;
}
return true;
}
| 30.784615 | 79 | 0.70065 | [
"vector"
] |
f525addbba46cbfd0312dff10d468dd4e3f6277a | 5,660 | cpp | C++ | src/third_party/angle/src/libANGLE/VertexAttribute.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 20 | 2019-04-18T07:37:34.000Z | 2022-02-02T21:43:47.000Z | src/third_party/angle/src/libANGLE/VertexAttribute.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 11 | 2019-10-21T13:39:41.000Z | 2021-11-05T08:11:54.000Z | src/third_party/angle/src/libANGLE/VertexAttribute.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 1 | 2021-12-03T18:11:36.000Z | 2021-12-03T18:11:36.000Z | //
// Copyright 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Implementation of the state classes for mananging GLES 3.1 Vertex Array Objects.
//
#include "libANGLE/VertexAttribute.h"
namespace gl
{
// [OpenGL ES 3.1] (November 3, 2016) Section 20 Page 361
// Table 20.2: Vertex Array Object State
VertexBinding::VertexBinding() : VertexBinding(0) {}
VertexBinding::VertexBinding(GLuint boundAttribute) : mStride(16u), mDivisor(0), mOffset(0)
{
mBoundAttributesMask.set(boundAttribute);
}
VertexBinding::VertexBinding(VertexBinding &&binding)
{
*this = std::move(binding);
}
VertexBinding::~VertexBinding() {}
VertexBinding &VertexBinding::operator=(VertexBinding &&binding)
{
if (this != &binding)
{
mStride = binding.mStride;
mDivisor = binding.mDivisor;
mOffset = binding.mOffset;
mBoundAttributesMask = binding.mBoundAttributesMask;
std::swap(binding.mBuffer, mBuffer);
}
return *this;
}
void VertexBinding::onContainerBindingChanged(const Context *context, int incr) const
{
if (mBuffer.get())
mBuffer->onNonTFBindingChanged(incr);
}
VertexAttribute::VertexAttribute(GLuint bindingIndex)
: enabled(false),
format(&angle::Format::Get(angle::FormatID::R32G32B32A32_FLOAT)),
pointer(nullptr),
relativeOffset(0),
vertexAttribArrayStride(0),
bindingIndex(bindingIndex),
mCachedElementLimit(0)
{}
VertexAttribute::VertexAttribute(VertexAttribute &&attrib)
: enabled(attrib.enabled),
format(attrib.format),
pointer(attrib.pointer),
relativeOffset(attrib.relativeOffset),
vertexAttribArrayStride(attrib.vertexAttribArrayStride),
bindingIndex(attrib.bindingIndex),
mCachedElementLimit(attrib.mCachedElementLimit)
{}
VertexAttribute &VertexAttribute::operator=(VertexAttribute &&attrib)
{
if (this != &attrib)
{
enabled = attrib.enabled;
format = attrib.format;
pointer = attrib.pointer;
relativeOffset = attrib.relativeOffset;
vertexAttribArrayStride = attrib.vertexAttribArrayStride;
bindingIndex = attrib.bindingIndex;
mCachedElementLimit = attrib.mCachedElementLimit;
}
return *this;
}
void VertexAttribute::updateCachedElementLimit(const VertexBinding &binding)
{
Buffer *buffer = binding.getBuffer().get();
if (!buffer)
{
mCachedElementLimit = 0;
return;
}
angle::CheckedNumeric<GLint64> bufferSize(buffer->getSize());
angle::CheckedNumeric<GLint64> bufferOffset(binding.getOffset());
angle::CheckedNumeric<GLint64> attribOffset(relativeOffset);
angle::CheckedNumeric<GLint64> attribSize(ComputeVertexAttributeTypeSize(*this));
// (buffer.size - buffer.offset - attrib.relativeOffset - attrib.size) / binding.stride
angle::CheckedNumeric<GLint64> elementLimit =
(bufferSize - bufferOffset - attribOffset - attribSize);
// Use the special integer overflow value if there was a math error.
if (!elementLimit.IsValid())
{
static_assert(kIntegerOverflow < 0, "Unexpected value");
mCachedElementLimit = kIntegerOverflow;
return;
}
mCachedElementLimit = elementLimit.ValueOrDie();
if (mCachedElementLimit < 0)
{
return;
}
if (binding.getStride() == 0)
{
// Special case for a zero stride. If we can fit one vertex we can fit infinite vertices.
mCachedElementLimit = std::numeric_limits<GLint64>::max();
return;
}
angle::CheckedNumeric<GLint64> bindingStride(binding.getStride());
elementLimit /= bindingStride;
if (binding.getDivisor() > 0)
{
// For instanced draws, the element count is floor(instanceCount - 1) / binding.divisor.
angle::CheckedNumeric<GLint64> bindingDivisor(binding.getDivisor());
elementLimit *= bindingDivisor;
// We account for the floor() part rounding by adding a rounding constant.
elementLimit += bindingDivisor - 1;
}
mCachedElementLimit = elementLimit.ValueOrDefault(kIntegerOverflow);
}
size_t ComputeVertexAttributeStride(const VertexAttribute &attrib, const VertexBinding &binding)
{
// In ES 3.1, VertexAttribPointer will store the type size in the binding stride.
// Hence, rendering always uses the binding's stride.
return attrib.enabled ? binding.getStride() : 16u;
}
// Warning: you should ensure binding really matches attrib.bindingIndex before using this function.
GLintptr ComputeVertexAttributeOffset(const VertexAttribute &attrib, const VertexBinding &binding)
{
return attrib.relativeOffset + binding.getOffset();
}
size_t ComputeVertexBindingElementCount(GLuint divisor, size_t drawCount, size_t instanceCount)
{
// For instanced rendering, we draw "instanceDrawCount" sets of "vertexDrawCount" vertices.
//
// A vertex attribute with a positive divisor loads one instanced vertex for every set of
// non-instanced vertices, and the instanced vertex index advances once every "mDivisor"
// instances.
if (instanceCount > 0 && divisor > 0)
{
// When instanceDrawCount is not a multiple attrib.divisor, the division must round up.
// For instance, with 5 non-instanced vertices and a divisor equal to 3, we need 2 instanced
// vertices.
return (instanceCount + divisor - 1u) / divisor;
}
return drawCount;
}
} // namespace gl
| 33.099415 | 100 | 0.690459 | [
"object"
] |
f528777a0428bd748cafb7a5befcc4dc35effd68 | 6,967 | cpp | C++ | src/game/window.cpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | src/game/window.cpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | src/game/window.cpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | #include "window.hpp"
#include <SDL.h>
#include <iostream>
#include <map>
namespace gold {
using namespace std;
obj& window::getPrototype() {
static auto proto = obj{
{"x", SDL_WINDOWPOS_CENTERED},
{"y", SDL_WINDOWPOS_CENTERED},
{"width", 1360},
{"height", 800},
{"maximize", false},
{"fullscreen", false},
{"borderless", false},
{"matchDesktop", false},
{"title", (char*)"RED2D"},
{"setSize", method(&window::setSize)},
{"setPos", method(&window::setPos)},
{"setTitle", method(&window::setTitle)},
{"setFullscreen", method(&window::setFullscreen)},
{"setBorderless", method(&window::setBorderless)},
{"create", method(&window::create)},
{"destroy", method(&window::destroy)},
{"handleEvent", method(&window::handleEvent)},
{"getConfig", method(&window::getConfig)},
};
return proto;
}
auto windowConfigDefault = obj({
{"x", SDL_WINDOWPOS_CENTERED},
{"y", SDL_WINDOWPOS_CENTERED},
{"width", 1360},
{"height", 800},
{"fullscreen", false},
{"borderless", false},
{"matchDesktop", false},
});
const auto DefaultWindowFlags =
SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN |
SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS |
SDL_WINDOW_ALLOW_HIGHDPI;
var window::setSize(list args) {
auto handle = (SDL_Window*)getPtr("handle");
int32_t width = SDL_WINDOWPOS_CENTERED;
int32_t height = SDL_WINDOWPOS_CENTERED;
if (args[0].getType() == typeList) {
auto arr = args[0].getList();
if (arr.getType(0) == typeInt32) width = arr.getInt32(0);
if (arr.getType(1) == typeInt32) height = arr.getInt32(1);
} else if (args[0].isVec2()) {
width = args[0].getInt32(0);
height = args[0].getInt32(1);
} else if (args[0].isNumber() && args[1].isNumber()) {
width = args[0].getInt32();
height = args[1].getInt32();
}
setInt32("width", width);
setInt32("height", height);
if (handle != nullptr)
SDL_SetWindowSize(handle, width, height);
return var();
}
var window::setPos(list args) {
auto handle = (SDL_Window*)getPtr("handle");
int32_t x = SDL_WINDOWPOS_CENTERED;
int32_t y = SDL_WINDOWPOS_CENTERED;
if (args[0].getType() == typeList) {
auto arr = args[0].getList();
if (arr.getType(0) == typeInt32) x = arr.getInt32(0);
if (arr.getType(1) == typeInt32) y = arr.getInt32(1);
} else if (args[0].isVec2()) {
x = args[0].getInt32(0);
y = args[0].getInt32(1);
} else if (args[0].isNumber() && args[1].isNumber()) {
x = args[0].getInt32();
y = args[1].getInt32();
}
setInt32("x", x);
setInt32("y", y);
if (handle != nullptr) SDL_SetWindowPosition(handle, x, y);
return var();
}
var window::setTitle(list args) {
auto handle = (SDL_Window*)getPtr("handle");
string title;
if (args[0].getType() == typeString)
title = args[0].getString();
if (title.size() > 0) {
setString("title", title);
if (handle != nullptr)
SDL_SetWindowTitle(handle, title.c_str());
} else
setNull("title");
return var();
}
var window::setFullscreen(list args) {
auto handle = (SDL_Window*)getPtr("handle");
bool fullscreen = false;
bool desktop = false;
if (args[0].getType() == typeBool)
fullscreen = (bool)args[0];
else if (args[0].getType() == typeList) {
auto arr = args[0].getList();
if (arr.getType(0) == typeBool)
fullscreen = arr.getBool(0);
if (arr.getType(1) == typeBool) desktop = arr.getBool(1);
}
setBool("fullscreen", fullscreen);
setBool("desktop", desktop);
if (handle)
SDL_SetWindowFullscreen(
handle,
(fullscreen ? (desktop ? SDL_WINDOW_FULLSCREEN_DESKTOP
: SDL_WINDOW_FULLSCREEN)
: 0));
return var();
}
var window::setBorderless(list args) {
auto handle = (SDL_Window*)getPtr("handle");
bool borderless = false;
if (args[0].getType() == typeBool)
borderless = args[0].getBool();
setBool("borderless", borderless);
if (handle)
SDL_SetWindowBordered(handle, (SDL_bool)(!borderless));
return var();
}
var window::create(list) {
if (getType("handle") == typePtr) callMethod("destroy");
int32_t windowX = getInt32("x");
int32_t windowY = getInt32("y");
int32_t width = getInt32("width");
int32_t height = getInt32("height");
bool fullscreen = getBool("fullscreen");
bool borderless = getBool("borderless");
bool maximize = getBool("maximize");
bool desktop = getBool("desktop");
auto title = getString("title");
uint32_t flags =
DefaultWindowFlags |
(fullscreen ? (desktop ? SDL_WINDOW_FULLSCREEN_DESKTOP
: SDL_WINDOW_FULLSCREEN)
: 0) |
(borderless ? SDL_WINDOW_BORDERLESS : 0) |
(maximize ? SDL_WINDOW_MAXIMIZED : 0);
SDL_Window* window = SDL_CreateWindow(
title.c_str(), windowX, windowY, width, height, flags);
SDL_SetWindowData(window, "object", this);
setPtr("handle", window);
return var();
}
var window::destroy(list) {
SDL_Window* window = (SDL_Window*)getPtr("handle");
if (window != nullptr) SDL_DestroyWindow(window);
return var();
}
var window::handleEvent(list args) {
if (args[0].getType() == typePtr) {
auto event = (SDL_Event*)args[0].getPtr();
auto window = (SDL_Window*)getPtr("handle");
if (event && event->type == SDL_WINDOWEVENT) {
switch (event->window.event) {
case SDL_WINDOWEVENT_SHOWN:
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESTORED:
setBool("hidden", false);
break;
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_HIDDEN:
setBool("hidden", true);
break;
case SDL_WINDOWEVENT_MOVED:
setInt32("x", event->window.data1);
setInt32("y", event->window.data2);
break;
case SDL_WINDOWEVENT_RESIZED:
case SDL_WINDOWEVENT_SIZE_CHANGED: {
setInt32("width", event->window.data1);
setInt32("height", event->window.data2);
auto flags = SDL_GetWindowFlags(window);
setBool(
"fullscreen", flags & SDL_WINDOW_FULLSCREEN);
setBool(
"desktop", flags & SDL_WINDOW_FULLSCREEN_DESKTOP);
setBool("maximize", flags & SDL_WINDOW_MAXIMIZED);
break;
}
case SDL_WINDOWEVENT_FOCUS_GAINED:
setBool("active", true);
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
setBool("active", false);
break;
#if SDL_VERSION_ATLEAST(2, 0, 5)
case SDL_WINDOWEVENT_TAKE_FOCUS:
setBool("active", true);
break;
case SDL_WINDOWEVENT_HIT_TEST:
setBool("active", true);
break;
#endif
default:
break;
}
}
}
return var();
}
var window::getConfig(list) {
auto allowed = windowConfigDefault;
auto config = obj(windowConfigDefault);
for (auto it = begin(); it != end(); ++it) {
auto def = allowed[it->first];
if (def.getType() != typeNull && it->second != def)
config.setVar(it->first, it->second);
}
return config;
}
window::window() : obj() {}
window::window(obj config) : obj() {
copy(config);
setParent(getPrototype());
}
} // namespace gold | 28.092742 | 61 | 0.64217 | [
"object"
] |
f529b6d998c8a529b93f23aa10e523bb33f16ce7 | 8,295 | hpp | C++ | include/zeep/unicode-support.hpp | mhekkel/libzeep | 52360b25b2667cf46dc8fd8a0384ea28825ab147 | [
"BSL-1.0"
] | 7 | 2017-01-04T19:27:03.000Z | 2020-07-06T11:19:33.000Z | include/zeep/unicode-support.hpp | mhekkel/libzeep | 52360b25b2667cf46dc8fd8a0384ea28825ab147 | [
"BSL-1.0"
] | 11 | 2016-01-14T14:08:46.000Z | 2022-02-26T08:08:15.000Z | include/zeep/unicode-support.hpp | mhekkel/libzeep | 52360b25b2667cf46dc8fd8a0384ea28825ab147 | [
"BSL-1.0"
] | 3 | 2018-10-11T22:39:28.000Z | 2020-11-12T02:44:41.000Z | // Copyright Maarten L. Hekkelman, Radboud University 2008-2013.
// Copyright Maarten L. Hekkelman, 2014-2020
// 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)
#pragma once
/// \file
/// various definitions of data types and routines used to work with Unicode encoded text
#include <zeep/config.hpp>
#include <zeep/exception.hpp>
#include <vector>
#include <string>
#include <tuple>
namespace zeep
{
/// \brief typedef of our own unicode type
///
/// We use our own unicode type since wchar_t might be too small.
/// This type should be able to contain a UCS4 encoded character.
using unicode = char32_t;
/// \brief the (admittedly limited) set of supported text encodings in libzeep
///
/// these are the supported encodings. Perhaps we should extend this list a bit?
enum class encoding_type
{
ASCII, ///< 7-bit ascii
UTF8, ///< UTF-8
UTF16BE, ///< UTF-16 Big Endian
UTF16LE, ///< UTF 16 Little Endian
ISO88591 ///< Default single byte encoding, is a subset of utf-8
};
/// \brief utf-8 is not single byte e.g.
constexpr bool is_single_byte_encoding(encoding_type enc)
{
return enc == encoding_type::ASCII or enc == encoding_type::ISO88591 or enc == encoding_type::UTF8;
}
/// Convert a string from UCS4 to UTF-8
std::string wstring_to_string(const std::wstring& s);
/// manipulate UTF-8 encoded strings
void append(std::string& s, unicode ch);
unicode pop_last_char(std::string& s);
template<typename Iter>
std::tuple<unicode,Iter> get_first_char(Iter ptr, Iter end);
/// \brief our own implementation of iequals: compares \a a with \a b case-insensitive
///
/// This is a limited use function, works only reliably with ASCII. But that's OK.
inline bool iequals(const std::string& a, const std::string& b)
{
bool equal = a.length() == b.length();
for (std::string::size_type i = 0; equal and i < a.length(); ++i)
equal = std::toupper(a[i]) == std::toupper(b[i]);
return equal;
}
// inlines
/// \brief Append a single unicode character to an utf-8 string
inline void append(std::string& s, unicode uc)
{
if (uc < 0x080)
s += (static_cast<char>(uc));
else if (uc < 0x0800)
{
char ch[2] = {
static_cast<char>(0x0c0 | (uc >> 6)),
static_cast<char>(0x080 | (uc & 0x3f))
};
s.append(ch, 2);
}
else if (uc < 0x00010000)
{
char ch[3] = {
static_cast<char>(0x0e0 | (uc >> 12)),
static_cast<char>(0x080 | ((uc >> 6) & 0x3f)),
static_cast<char>(0x080 | (uc & 0x3f))
};
s.append(ch, 3);
}
else
{
char ch[4] = {
static_cast<char>(0x0f0 | (uc >> 18)),
static_cast<char>(0x080 | ((uc >> 12) & 0x3f)),
static_cast<char>(0x080 | ((uc >> 6) & 0x3f)),
static_cast<char>(0x080 | (uc & 0x3f))
};
s.append(ch, 4);
}
}
/// \brief remove the last unicode character from an utf-8 string
inline unicode pop_last_char(std::string& s)
{
unicode result = 0;
if (not s.empty())
{
std::string::iterator ch = s.end() - 1;
if ((*ch & 0x0080) == 0)
{
result = *ch;
s.erase(ch);
}
else
{
int o = 0;
do
{
result |= (*ch & 0x03F) << o;
o += 6;
--ch;
}
while (ch != s.begin() and (*ch & 0x0C0) == 0x080);
switch (o)
{
case 6: result |= (*ch & 0x01F) << 6; break;
case 12: result |= (*ch & 0x00F) << 12; break;
case 18: result |= (*ch & 0x007) << 18; break;
}
s.erase(ch, s.end());
}
}
return result;
}
// I used to have this comment here:
//
// this code only works if the input is valid utf-8
//
// That was a bad idea....
//
/// \brief return the first unicode and the advanced pointer from a string
template<typename Iter>
std::tuple<unicode,Iter> get_first_char(Iter ptr, Iter end)
{
unicode result = static_cast<unsigned char>(*ptr);
++ptr;
if (result > 0x07f)
{
unsigned char ch[3];
if ((result & 0x0E0) == 0x0C0)
{
if (ptr >= end)
throw zeep::exception("Invalid utf-8");
ch[0] = static_cast<unsigned char>(*ptr); ++ptr;
if ((ch[0] & 0x0c0) != 0x080)
throw zeep::exception("Invalid utf-8");
result = ((result & 0x01F) << 6) | (ch[0] & 0x03F);
}
else if ((result & 0x0F0) == 0x0E0)
{
if (ptr + 1 >= end)
throw zeep::exception("Invalid utf-8");
ch[0] = static_cast<unsigned char>(*ptr); ++ptr;
ch[1] = static_cast<unsigned char>(*ptr); ++ptr;
if ((ch[0] & 0x0c0) != 0x080 or (ch[1] & 0x0c0) != 0x080)
throw zeep::exception("Invalid utf-8");
result = ((result & 0x00F) << 12) | ((ch[0] & 0x03F) << 6) | (ch[1] & 0x03F);
}
else if ((result & 0x0F8) == 0x0F0)
{
if (ptr + 2 >= end)
throw zeep::exception("Invalid utf-8");
ch[0] = static_cast<unsigned char>(*ptr); ++ptr;
ch[1] = static_cast<unsigned char>(*ptr); ++ptr;
ch[2] = static_cast<unsigned char>(*ptr); ++ptr;
if ((ch[0] & 0x0c0) != 0x080 or (ch[1] & 0x0c0) != 0x080 or (ch[2] & 0x0c0) != 0x080)
throw zeep::exception("Invalid utf-8");
result = ((result & 0x007) << 18) | ((ch[0] & 0x03F) << 12) | ((ch[1] & 0x03F) << 6) | (ch[2] & 0x03F);
}
}
return std::make_tuple(result, ptr);
}
// --------------------------------------------------------------------
inline std::string to_hex(uint32_t i)
{
char s[sizeof(i) * 2 + 3];
char* p = s + sizeof(s);
*--p = 0;
const char kHexChars[] = "0123456789abcdef";
while (i)
{
*--p = kHexChars[i & 0x0F];
i >>= 4;
}
*--p = 'x';
*--p = '0';
return p;
}
// --------------------------------------------------------------------
/// \brief A simple implementation of trim, removing white space from start and end of \a s
inline void trim(std::string& s)
{
std::string::iterator b = s.begin();
while (b != s.end() and *b > 0 and std::isspace(*b))
++b;
std::string::iterator e = s.end();
while (e > b and *(e - 1) > 0 and std::isspace(*(e - 1)))
--e;
if (b != s.begin() or e != s.end())
s = { b, e };
}
// --------------------------------------------------------------------
/// \brief Simplistic implementation of starts_with
inline bool starts_with(std::string_view s, std::string_view p)
{
return s.compare(0, p.length(), p) == 0;
}
// --------------------------------------------------------------------
/// \brief Simplistic implementation of ends_with
inline bool ends_with(std::string_view s, std::string_view p)
{
return s.length() >= p.length() and s.compare(s.length() - p.length(), p.length(), p) == 0;
}
// --------------------------------------------------------------------
/// \brief Simplistic implementation of contains
inline bool contains(std::string_view s, std::string_view p)
{
return s.find(p) != std::string_view::npos;
}
// --------------------------------------------------------------------
/// \brief Simplistic implementation of split, with std:string in the vector
inline void split(std::vector<std::string>& v, std::string_view s, std::string_view p, bool compress = false)
{
v.clear();
std::string_view::size_type i = 0;
const auto e = s.length();
while (i <= e)
{
auto n = s.find(p, i);
if (n > e)
n = e;
if (n > i or compress == false)
v.emplace_back(s.substr(i, n - i));
if (n == std::string_view::npos)
break;
i = n + p.length();
}
}
// --------------------------------------------------------------------
/// \brief Simplistic to_lower function, works for one byte charsets only...
inline void to_lower(std::string& s, const std::locale& loc = std::locale())
{
for (char& ch: s)
ch = std::tolower(ch, loc);
}
// --------------------------------------------------------------------
/// \brief Simplistic join function
template<typename Container = std::vector<std::string> >
std::string join(const Container& v, std::string_view d)
{
std::string result;
if (not v.empty())
{
auto i = v.begin();
for (;;)
{
result += *i++;
if (i == v.end())
break;
result += d;
}
}
return result;
}
// --------------------------------------------------------------------
/// \brief Simplistic replace_all
inline void replace_all(std::string& s, std::string_view p, std::string_view r)
{
std::string::size_type i = 0;
for (;;)
{
auto l = s.find(p, i);
if (l == std::string::npos)
break;
s.replace(l, p.length(), r);
i = l + r.length();
}
}
} // namespace xml
| 24.113372 | 109 | 0.564678 | [
"vector"
] |
f52c79aac7c521ee03e523998f429d2e03385119 | 5,831 | cc | C++ | base/unnamed_event.cc | rchardzhu/gbase | 484f5f9c8adf2ae770d902c49824087870f2921d | [
"Apache-2.0"
] | 1 | 2016-12-06T15:33:36.000Z | 2016-12-06T15:33:36.000Z | base/unnamed_event.cc | rchardzhu/gbase | 484f5f9c8adf2ae770d902c49824087870f2921d | [
"Apache-2.0"
] | null | null | null | base/unnamed_event.cc | rchardzhu/gbase | 484f5f9c8adf2ae770d902c49824087870f2921d | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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 "base/unnamed_event.h"
#ifdef OS_WIN
#include <windows.h>
#else // OS_WIN
#include <errno.h>
#include <pthread.h>
#include <sys/time.h>
#endif // OS_WIN
#include "base/logging.h"
#include "base/port.h"
namespace gbase {
#ifdef OS_WIN
UnnamedEvent::UnnamedEvent()
: handle_(::CreateEvent(NULL, FALSE, FALSE, NULL)) {
// Use Auto reset mode of Win32 Event. (2nd arg of CreateEvent).
// pthread_cond_signal: auto reset mode.
// pthread_cond_broadcast: manual reset mode.
if (NULL == handle_.get()) {
LOG(ERROR) << "CreateEvent failed: " << ::GetLastError();
}
}
UnnamedEvent::~UnnamedEvent() {}
bool UnnamedEvent::IsAvailable() const {
return (NULL != handle_.get());
}
bool UnnamedEvent::Notify() {
if (!IsAvailable()) {
LOG(WARNING) << "Event object is not available";
return false;
}
if (!::SetEvent(handle_.get())) {
LOG(ERROR) << "SetEvent failed: " << ::GetLastError();
return false;
}
return true;
}
bool UnnamedEvent::Wait(int msec) {
if (!IsAvailable()) {
return true; // assume that it is already raised
}
if (msec < 0) {
msec = INFINITE;
}
return WAIT_TIMEOUT !=
::WaitForSingleObject(handle_.get(), msec);
}
#else // OS_WIN
namespace {
class ScopedPthreadMutexLock {
public:
explicit ScopedPthreadMutexLock(pthread_mutex_t *mutex) : mutex_(mutex) {
pthread_mutex_lock(mutex_);
}
~ScopedPthreadMutexLock() {
pthread_mutex_unlock(mutex_);
}
private:
pthread_mutex_t *mutex_;
DISALLOW_COPY_AND_ASSIGN(ScopedPthreadMutexLock);
};
} // namespace
UnnamedEvent::UnnamedEvent() : notified_(false) {
pthread_mutex_init(&mutex_, NULL);
pthread_cond_init(&cond_, NULL);
}
// It is necessary to ensure that no threads wait for this event before the
// destruction.
UnnamedEvent::~UnnamedEvent() {
pthread_mutex_destroy(&mutex_);
pthread_cond_destroy(&cond_);
}
bool UnnamedEvent::IsAvailable() const {
return true;
}
bool UnnamedEvent::Notify() {
{
ScopedPthreadMutexLock lock(&mutex_);
notified_ = true;
}
// Note: Need to awake all threads waiting for this event. Otherwise
// some thread would start to work incorrectly in some cases.
// An example error scenario is:
// - there are four threads, A, B, C and D.
// - A and B are producers. C and D are consumers.
// - C and D start to wait this event.
// - Then A notifies.
// - A takes the lock.
// - set notified_ true.
// - A releases the lock.
// - Then before A sends a signal to awake a thread (either C or D),
// B takes the lock.
// - A sends a signal, but both C and D are sleeping as the lock is
// still taken by B.
// - B releases the lock. So one of the thread (let's assume C for this
// example) starts to run, because it can take the lock.
// - B also sends a signal again.
// - C overrides notified_ to false, and releases the lock.
// - At last, D starts to run wrongly.
// The broadcast and while (in Wait) idiom is a popular way to fix such
// cases.
pthread_cond_broadcast(&cond_);
return true;
}
bool UnnamedEvent::Wait(int msec) {
ScopedPthreadMutexLock lock(&mutex_);
if (!notified_) {
// Need to wait actually.
if (msec < 0) {
// Wait forever.
while (!notified_) {
pthread_cond_wait(&cond_, &mutex_);
}
} else {
// Wait with time out.
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0) {
LOG(ERROR) << "Failed to take the current time: " << errno;
return false;
}
struct timespec timeout;
timeout.tv_sec = tv.tv_sec + msec / 1000;
timeout.tv_nsec = 1000 * (tv.tv_usec + 1000 * (msec % 1000));
// if tv_nsec >= 10^9, pthread_cond_timedwait may return EINVAL
while (timeout.tv_nsec >= 1000000000) {
timeout.tv_sec++;
timeout.tv_nsec -= 1000000000;
}
int result = 0;
while (!notified_ && result == 0) {
result = pthread_cond_timedwait(&cond_, &mutex_, &timeout);
}
if (result != 0) {
// Time out.
return false;
}
}
}
DCHECK(notified_);
notified_ = false;
return true;
}
#endif // OS_WIN
} // namespace gbase
| 29.449495 | 77 | 0.666781 | [
"object"
] |
f52ca2c51543ebcf87e25280f675fa95a62c7923 | 6,028 | cc | C++ | dali/operators/reader/loader/numpy_loader.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/reader/loader/numpy_loader.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/reader/loader/numpy_loader.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-04-26T14:59:51.000Z | 2020-04-26T14:59:51.000Z | // Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <dirent.h>
#include <errno.h>
#include <memory>
#include "dali/core/common.h"
#include "dali/operators/reader/loader/numpy_loader.h"
#include "dali/util/file.h"
#include "dali/operators/reader/loader/utils.h"
namespace dali {
TypeInfo TypeFromNumpyStr(const std::string &format) {
if (format == "i8")
return TypeInfo::Create<int64_t>();
else if (format == "i4")
return TypeInfo::Create<int32_t>();
else if (format == "f4")
return TypeInfo::Create<float>();
else if (format == "f8")
return TypeInfo::Create<double>();
else
return TypeInfo();
}
std::unique_ptr<FileStream> NumpyLoader::ParseHeader(std::unique_ptr<FileStream> file,
NumpyParseTarget& target) {
// check if the file is actually a numpy file
std::vector<uint8_t> token(11);
int64_t nread = file->Read(token.data(), 10);
DALI_ENFORCE(nread == 10, "Can not read header.");
token[nread] = '\0';
// check if heqder is too short
std::string header = std::string(reinterpret_cast<char*>(token.data()));
DALI_ENFORCE(header.find_first_of("NUMPY") != std::string::npos,
"File is not a numpy file.");
// extract header length
uint16_t header_len = 0;
memcpy(&header_len, &token[8], 2);
DALI_ENFORCE((header_len + 10) % 16 == 0,
"Error extracting header length.");
// read header: the offset is a magic number
int64 offset = (6+1+1+2);
// the header_len can be 4GiB according to the NPYv2 file format
// specification: https://numpy.org/neps/nep-0001-npy-format.html
// while this allocation could be sizable, it is performed on the host.
token.resize(header_len+1);
file->Seek(offset);
nread = file->Read(token.data(), header_len);
DALI_ENFORCE(nread == header_len, "Can not read header.");
token[header_len] = '\0';
header = std::string(reinterpret_cast<char*>(token.data()));
DALI_ENFORCE(header.find_first_of("{") != std::string::npos, "Header is corrupted.");
offset += header_len;
// prepare file for later reads
file->Seek(offset);
// extract dictionary info from header
std::smatch header_match;
DALI_ENFORCE(std::regex_search(header, header_match, header_regex_),
"Can not parse header.");
// now extract header information
// type
std::string typestring = header_match[1].str();
// < means LE, | means N/A, = means native. In all those cases, we can read
bool little_endian =
(typestring[0] == '<' || typestring[0] == '|' || typestring[0] == '=');
DALI_ENFORCE(little_endian,
"Big Endian files are not supported.");
std::string tid = typestring.substr(1);
// get type in a safe way
target.type_info = TypeFromNumpyStr(tid);
// check for data order
if (header_match[2].str() == "False")
target.fortran_order = false;
else
target.fortran_order = true;
// set sizes
std::string shapestring = header_match[3].str();
std::regex shape_regex{R"(,+)"}; // split on comma
std::sregex_token_iterator it{shapestring.begin(), shapestring.end(), shape_regex, -1};
std::vector<std::string> shapevec{it, {}};
// if shapevec size is 1 and shapevec[0] is the empty string,
// the array is actually a scalar/singleton (denoted as ())
// and thus the size needs to be set to one:
if ( (shapevec.size() == 1) && (shapevec[0] == "") ) shapevec[0] = "1";
// determine shapes
size_t shapesize = shapevec.size();
target.shape.resize(shapesize);
// cheapest thing to do is to define the tensor in an reversed way
if (target.fortran_order) {
for (size_t i = 0; i < shapesize; ++i)
target.shape[i] = static_cast<int64_t>(stoi(shapevec[shapesize-i-1]));
} else {
for (size_t i = 0; i < shapesize; ++i)
target.shape[i] = static_cast<int64_t>(stoi(shapevec[i]));
}
return file;
}
void NumpyLoader::ReadSample(ImageFileWrapper& imfile) {
auto image_file = images_[current_index_++];
// handle wrap-around
MoveToNextShard(current_index_);
// metadata info
DALIMeta meta;
meta.SetSourceInfo(image_file);
meta.SetSkipSample(false);
// if image is cached, skip loading
if (ShouldSkipImage(image_file)) {
meta.SetSkipSample(true);
imfile.image.Reset();
imfile.image.SetMeta(meta);
imfile.image.set_type(TypeInfo::Create<uint8_t>());
imfile.image.Resize({0});
imfile.filename = "";
return;
}
auto current_image = FileStream::Open(file_root_ + "/" + image_file, read_ahead_);
// read the header
NumpyParseTarget target;
current_image = ParseHeader(std::move(current_image), target);
Index image_bytes = target.nbytes();
if (copy_read_data_) {
if (imfile.image.shares_data()) {
imfile.image.Reset();
}
imfile.image.Resize(target.shape, target.type_info);
// copy the image
current_image->Read(static_cast<uint8_t*>(imfile.image.raw_mutable_data()), image_bytes);
} else {
auto p = current_image->Get(image_bytes);
// Wrap the raw data in the Tensor object.
imfile.image.ShareData(p, image_bytes, {image_bytes});
imfile.image.Resize(target.shape, target.type_info);
}
// close the file handle
current_image->Close();
// set metadata
imfile.image.SetMeta(meta);
// set file path
imfile.filename = file_root_ + "/" + image_file;
// set meta
imfile.meta = (target.fortran_order ? "transpose:true" : "transpose:false");
}
} // namespace dali
| 32.76087 | 93 | 0.674685 | [
"object",
"shape",
"vector"
] |
f52cad157663f580652250f670eb306c2709f40b | 470,235 | cpp | C++ | runtime/test/generated/spec_V1_2/layer_norm_lstm.example.cpp | riscv-android-src/platform-packages-modules-NeuralNetworks | 32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5 | [
"Apache-2.0"
] | null | null | null | runtime/test/generated/spec_V1_2/layer_norm_lstm.example.cpp | riscv-android-src/platform-packages-modules-NeuralNetworks | 32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5 | [
"Apache-2.0"
] | null | null | null | runtime/test/generated/spec_V1_2/layer_norm_lstm.example.cpp | riscv-android-src/platform-packages-modules-NeuralNetworks | 32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5 | [
"Apache-2.0"
] | null | null | null | // Generated from layer_norm_lstm.mod.py
// DO NOT EDIT
// clang-format off
#include "TestHarness.h"
using namespace test_helper; // NOLINT(google-build-using-namespace)
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm() {
static TestModel model = {
.main = {
.operands = {{ // input
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.8f, 0.1f, 0.2f, 0.3f, 0.3f, 0.2f, 0.9f, 0.8f, 0.1f})
}, { // input_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.5f, 0.6f, 0.7f, -0.8f, -0.9f, 0.1f, 0.2f, 0.3f, -0.4f, 0.5f, -0.8f, 0.7f, -0.6f, 0.5f, -0.4f, -0.5f, -0.4f, -0.3f, -0.2f, -0.1f})
}, { // input_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // input_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // input_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // recurrent_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.2f, -0.3f, 0.4f, 0.1f, -0.5f, 0.9f, -0.2f, -0.3f, -0.7f, 0.05f, -0.2f, -0.6f})
}, { // recurrent_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // recurrent_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // recurrent_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // cell_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, 0.1f, 0.25f, 0.15f})
}, { // cell_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // cell_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // input_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.03f, 0.15f, 0.22f, 0.38f})
}, { // forget_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // cell_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // output_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // projection_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // projection_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // activation_param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, 0.2f, 0.3f, 0.5f})
}, { // forget_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // cell_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // output_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // scratch_buffer
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 16},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.024407668039203f, 0.128027379512787f, -0.001709178090096f, -0.006924282759428f, 0.08487406373024f, 0.06344497948885f})
}, { // cell_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.451771229505539f, 0.376915663480759f, 0.225425109267235f, 0.232406347990036f, -0.252585828304291f, 0.330421179533005f, 0.017305245622993f, 0.366601228713989f})
}, { // output
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.024407668039203f, 0.128027379512787f, -0.001709178090096f, -0.006924282759428f, 0.08487406373024f, 0.06344497948885f})
}},
.operations = {{
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm = TestModelManager::get().add("layer_norm_lstm_NoCifgPeepholeProjectionNoClippingLayerNormLstm", get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // activation_param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // scratch_buffer
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 16},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.024407668039203f, 0.128027379512787f, -0.001709178090096f, -0.006924282759428f, 0.08487406373024f, 0.06344497948885f})
}, { // cell_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.451771229505539f, 0.376915663480759f, 0.225425109267235f, 0.232406347990036f, -0.252585828304291f, 0.330421179533005f, 0.017305245622993f, 0.366601228713989f})
}, { // output
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.024407668039203f, 0.128027379512787f, -0.001709178090096f, -0.006924282759428f, 0.08487406373024f, 0.06344497948885f})
}, { // input_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.8f, 0.1f, 0.2f, 0.3f, 0.3f, 0.2f, 0.9f, 0.8f, 0.1f})
}, { // placeholder
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.5f, 0.6f, 0.7f, -0.8f, -0.9f, 0.1f, 0.2f, 0.3f, -0.4f, 0.5f, -0.8f, 0.7f, -0.6f, 0.5f, -0.4f, -0.5f, -0.4f, -0.3f, -0.2f, -0.1f})
}, { // placeholder1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // placeholder2
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param2
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_cell_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // placeholder3
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param3
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // placeholder4
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param4
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.2f, -0.3f, 0.4f, 0.1f, -0.5f, 0.9f, -0.2f, -0.3f, -0.7f, 0.05f, -0.2f, -0.6f})
}, { // placeholder5
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param5
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // placeholder6
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param6
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_cell_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // placeholder7
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param7
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // placeholder8
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param8
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, 0.1f, 0.25f, 0.15f})
}, { // placeholder9
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param9
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // placeholder10
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param10
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // placeholder11
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param11
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.03f, 0.15f, 0.22f, 0.38f})
}, { // placeholder12
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param12
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // placeholder13
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param13
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // placeholder14
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param14
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // placeholder15
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param15
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // projection_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // placeholder16
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param16
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_state_in_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // placeholder17
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param17
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_state_in_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // placeholder18
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param18
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, 0.2f, 0.3f, 0.5f})
}, { // placeholder19
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param19
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // placeholder20
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param20
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // placeholder21
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param21
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // placeholder22
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param22
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {31, 32, 33},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {34, 35, 36},
.outputs = {1}
}, {
.type = TestOperationType::ADD,
.inputs = {37, 38, 39},
.outputs = {2}
}, {
.type = TestOperationType::ADD,
.inputs = {40, 41, 42},
.outputs = {3}
}, {
.type = TestOperationType::ADD,
.inputs = {43, 44, 45},
.outputs = {4}
}, {
.type = TestOperationType::ADD,
.inputs = {46, 47, 48},
.outputs = {5}
}, {
.type = TestOperationType::ADD,
.inputs = {49, 50, 51},
.outputs = {6}
}, {
.type = TestOperationType::ADD,
.inputs = {52, 53, 54},
.outputs = {7}
}, {
.type = TestOperationType::ADD,
.inputs = {55, 56, 57},
.outputs = {8}
}, {
.type = TestOperationType::ADD,
.inputs = {58, 59, 60},
.outputs = {9}
}, {
.type = TestOperationType::ADD,
.inputs = {61, 62, 63},
.outputs = {10}
}, {
.type = TestOperationType::ADD,
.inputs = {64, 65, 66},
.outputs = {11}
}, {
.type = TestOperationType::ADD,
.inputs = {67, 68, 69},
.outputs = {12}
}, {
.type = TestOperationType::ADD,
.inputs = {70, 71, 72},
.outputs = {13}
}, {
.type = TestOperationType::ADD,
.inputs = {73, 74, 75},
.outputs = {14}
}, {
.type = TestOperationType::ADD,
.inputs = {76, 77, 78},
.outputs = {15}
}, {
.type = TestOperationType::ADD,
.inputs = {79, 80, 81},
.outputs = {16}
}, {
.type = TestOperationType::ADD,
.inputs = {82, 83, 84},
.outputs = {18}
}, {
.type = TestOperationType::ADD,
.inputs = {85, 86, 87},
.outputs = {19}
}, {
.type = TestOperationType::ADD,
.inputs = {88, 89, 90},
.outputs = {23}
}, {
.type = TestOperationType::ADD,
.inputs = {91, 92, 93},
.outputs = {24}
}, {
.type = TestOperationType::ADD,
.inputs = {94, 95, 96},
.outputs = {25}
}, {
.type = TestOperationType::ADD,
.inputs = {97, 98, 99},
.outputs = {26}
}, {
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {17, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal = TestModelManager::get().add("layer_norm_lstm_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal", get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_2() {
static TestModel model = {
.main = {
.operands = {{ // input
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.8f, 0.1f, 0.2f, 0.4f, 0.5f, 0.1f, 0.5f, 0.2f, 0.4f, 0.2f})
}, { // input_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.5f, 0.6f, 0.7f, -0.8f, -0.9f, 0.1f, 0.2f, 0.3f, -0.4f, 0.5f, -0.8f, 0.7f, -0.6f, 0.5f, -0.4f, -0.5f, -0.4f, -0.3f, -0.2f, -0.1f})
}, { // input_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // input_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // input_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // recurrent_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.2f, -0.3f, 0.4f, 0.1f, -0.5f, 0.9f, -0.2f, -0.3f, -0.7f, 0.05f, -0.2f, -0.6f})
}, { // recurrent_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // recurrent_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // recurrent_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // cell_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, 0.1f, 0.25f, 0.15f})
}, { // cell_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // cell_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // input_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.03f, 0.15f, 0.22f, 0.38f})
}, { // forget_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // cell_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // output_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // projection_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // projection_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.024407668039203f, 0.128027379512787f, -0.001709178090096f, -0.006924282759428f, 0.08487406373024f, 0.06344497948885f})
}, { // cell_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.451771229505539f, 0.376915663480759f, 0.225425109267235f, 0.232406347990036f, -0.252585828304291f, 0.330421179533005f, 0.017305245622993f, 0.366601228713989f})
}, { // activation_param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, 0.2f, 0.3f, 0.5f})
}, { // forget_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // cell_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // output_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // scratch_buffer
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 16},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.013764165341854f, 0.140751048922539f, 0.039583537727594f, -0.004039138555527f, 0.139963015913963f, 0.072681039571762f})
}, { // cell_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.645632147789001f, 0.518238246440887f, 0.168679088354111f, 0.555787742137909f, -0.49367481470108f, 0.475847363471985f, 0.106874041259289f, 0.50430965423584f})
}, { // output
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.013764165341854f, 0.140751048922539f, 0.039583537727594f, -0.004039138555527f, 0.139963015913963f, 0.072681039571762f})
}},
.operations = {{
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_2 = TestModelManager::get().add("layer_norm_lstm_NoCifgPeepholeProjectionNoClippingLayerNormLstm_2", get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_2());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2() {
static TestModel model = {
.main = {
.operands = {{ // input
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // activation_param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // scratch_buffer
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 16},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.013764165341854f, 0.140751048922539f, 0.039583537727594f, -0.004039138555527f, 0.139963015913963f, 0.072681039571762f})
}, { // cell_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.645632147789001f, 0.518238246440887f, 0.168679088354111f, 0.555787742137909f, -0.49367481470108f, 0.475847363471985f, 0.106874041259289f, 0.50430965423584f})
}, { // output
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.013764165341854f, 0.140751048922539f, 0.039583537727594f, -0.004039138555527f, 0.139963015913963f, 0.072681039571762f})
}, { // input_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.8f, 0.1f, 0.2f, 0.4f, 0.5f, 0.1f, 0.5f, 0.2f, 0.4f, 0.2f})
}, { // placeholder23
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param23
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.5f, 0.6f, 0.7f, -0.8f, -0.9f, 0.1f, 0.2f, 0.3f, -0.4f, 0.5f, -0.8f, 0.7f, -0.6f, 0.5f, -0.4f, -0.5f, -0.4f, -0.3f, -0.2f, -0.1f})
}, { // placeholder24
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param24
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // placeholder25
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param25
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_cell_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // placeholder26
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param26
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // placeholder27
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param27
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.2f, -0.3f, 0.4f, 0.1f, -0.5f, 0.9f, -0.2f, -0.3f, -0.7f, 0.05f, -0.2f, -0.6f})
}, { // placeholder28
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param28
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // placeholder29
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param29
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_cell_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // placeholder30
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param30
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // placeholder31
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param31
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, 0.1f, 0.25f, 0.15f})
}, { // placeholder32
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param32
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // placeholder33
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param33
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // placeholder34
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param34
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.03f, 0.15f, 0.22f, 0.38f})
}, { // placeholder35
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param35
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // placeholder36
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param36
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // placeholder37
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param37
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // placeholder38
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param38
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // projection_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // placeholder39
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param39
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_state_in_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.024407668039203f, 0.128027379512787f, -0.001709178090096f, -0.006924282759428f, 0.08487406373024f, 0.06344497948885f})
}, { // placeholder40
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param40
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_state_in_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.451771229505539f, 0.376915663480759f, 0.225425109267235f, 0.232406347990036f, -0.252585828304291f, 0.330421179533005f, 0.017305245622993f, 0.366601228713989f})
}, { // placeholder41
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param41
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, 0.2f, 0.3f, 0.5f})
}, { // placeholder42
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param42
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // placeholder43
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param43
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // placeholder44
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param44
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // placeholder45
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param45
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {31, 32, 33},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {34, 35, 36},
.outputs = {1}
}, {
.type = TestOperationType::ADD,
.inputs = {37, 38, 39},
.outputs = {2}
}, {
.type = TestOperationType::ADD,
.inputs = {40, 41, 42},
.outputs = {3}
}, {
.type = TestOperationType::ADD,
.inputs = {43, 44, 45},
.outputs = {4}
}, {
.type = TestOperationType::ADD,
.inputs = {46, 47, 48},
.outputs = {5}
}, {
.type = TestOperationType::ADD,
.inputs = {49, 50, 51},
.outputs = {6}
}, {
.type = TestOperationType::ADD,
.inputs = {52, 53, 54},
.outputs = {7}
}, {
.type = TestOperationType::ADD,
.inputs = {55, 56, 57},
.outputs = {8}
}, {
.type = TestOperationType::ADD,
.inputs = {58, 59, 60},
.outputs = {9}
}, {
.type = TestOperationType::ADD,
.inputs = {61, 62, 63},
.outputs = {10}
}, {
.type = TestOperationType::ADD,
.inputs = {64, 65, 66},
.outputs = {11}
}, {
.type = TestOperationType::ADD,
.inputs = {67, 68, 69},
.outputs = {12}
}, {
.type = TestOperationType::ADD,
.inputs = {70, 71, 72},
.outputs = {13}
}, {
.type = TestOperationType::ADD,
.inputs = {73, 74, 75},
.outputs = {14}
}, {
.type = TestOperationType::ADD,
.inputs = {76, 77, 78},
.outputs = {15}
}, {
.type = TestOperationType::ADD,
.inputs = {79, 80, 81},
.outputs = {16}
}, {
.type = TestOperationType::ADD,
.inputs = {82, 83, 84},
.outputs = {18}
}, {
.type = TestOperationType::ADD,
.inputs = {85, 86, 87},
.outputs = {19}
}, {
.type = TestOperationType::ADD,
.inputs = {88, 89, 90},
.outputs = {23}
}, {
.type = TestOperationType::ADD,
.inputs = {91, 92, 93},
.outputs = {24}
}, {
.type = TestOperationType::ADD,
.inputs = {94, 95, 96},
.outputs = {25}
}, {
.type = TestOperationType::ADD,
.inputs = {97, 98, 99},
.outputs = {26}
}, {
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {17, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2 = TestModelManager::get().add("layer_norm_lstm_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2", get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_3() {
static TestModel model = {
.main = {
.operands = {{ // input
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.7f, 0.7f, 0.1f, 0.7f, 0.6f, 0.9f, 0.2f, 0.5f, 0.7f})
}, { // input_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.5f, 0.6f, 0.7f, -0.8f, -0.9f, 0.1f, 0.2f, 0.3f, -0.4f, 0.5f, -0.8f, 0.7f, -0.6f, 0.5f, -0.4f, -0.5f, -0.4f, -0.3f, -0.2f, -0.1f})
}, { // input_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // input_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // input_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // recurrent_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.2f, -0.3f, 0.4f, 0.1f, -0.5f, 0.9f, -0.2f, -0.3f, -0.7f, 0.05f, -0.2f, -0.6f})
}, { // recurrent_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // recurrent_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // recurrent_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // cell_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, 0.1f, 0.25f, 0.15f})
}, { // cell_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // cell_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // input_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.03f, 0.15f, 0.22f, 0.38f})
}, { // forget_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // cell_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // output_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // projection_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // projection_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.013764165341854f, 0.140751048922539f, 0.039583537727594f, -0.004039138555527f, 0.139963015913963f, 0.072681039571762f})
}, { // cell_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.645632147789001f, 0.518238246440887f, 0.168679088354111f, 0.555787742137909f, -0.49367481470108f, 0.475847363471985f, 0.106874041259289f, 0.50430965423584f})
}, { // activation_param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, 0.2f, 0.3f, 0.5f})
}, { // forget_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // cell_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // output_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // scratch_buffer
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 16},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.004592306911945f, 0.155278354883194f, 0.083737745881081f, 0.007527053356171f, 0.161902531981468f, 0.056137066334486f})
}, { // cell_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.742560744285583f, 0.579139292240143f, 0.114988230168819f, 0.649957716464996f, -0.686565399169922f, 0.548869132995605f, 0.17313876748085f, 0.587379336357117f})
}, { // output
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.004592306911945f, 0.155278354883194f, 0.083737745881081f, 0.007527053356171f, 0.161902531981468f, 0.056137066334486f})
}},
.operations = {{
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_3 = TestModelManager::get().add("layer_norm_lstm_NoCifgPeepholeProjectionNoClippingLayerNormLstm_3", get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_3());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3() {
static TestModel model = {
.main = {
.operands = {{ // input
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_cell_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_input_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_output_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_gate_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_bias
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_state_in
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // activation_param
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_layer_norm_weights
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // scratch_buffer
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 16},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.004592306911945f, 0.155278354883194f, 0.083737745881081f, 0.007527053356171f, 0.161902531981468f, 0.056137066334486f})
}, { // cell_state_out
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.742560744285583f, 0.579139292240143f, 0.114988230168819f, 0.649957716464996f, -0.686565399169922f, 0.548869132995605f, 0.17313876748085f, 0.587379336357117f})
}, { // output
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.004592306911945f, 0.155278354883194f, 0.083737745881081f, 0.007527053356171f, 0.161902531981468f, 0.056137066334486f})
}, { // input_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.7f, 0.7f, 0.1f, 0.7f, 0.6f, 0.9f, 0.2f, 0.5f, 0.7f})
}, { // placeholder46
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param46
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.5f, 0.6f, 0.7f, -0.8f, -0.9f, 0.1f, 0.2f, 0.3f, -0.4f, 0.5f, -0.8f, 0.7f, -0.6f, 0.5f, -0.4f, -0.5f, -0.4f, -0.3f, -0.2f, -0.1f})
}, { // placeholder47
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param47
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // placeholder48
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param48
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_cell_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // placeholder49
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param49
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // placeholder50
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param50
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.2f, -0.3f, 0.4f, 0.1f, -0.5f, 0.9f, -0.2f, -0.3f, -0.7f, 0.05f, -0.2f, -0.6f})
}, { // placeholder51
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param51
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // placeholder52
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param52
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_cell_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // placeholder53
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param53
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // placeholder54
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param54
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_input_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, 0.1f, 0.25f, 0.15f})
}, { // placeholder55
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param55
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_forget_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // placeholder56
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param56
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_output_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // placeholder57
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param57
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.03f, 0.15f, 0.22f, 0.38f})
}, { // placeholder58
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param58
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // placeholder59
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param59
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // placeholder60
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param60
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_gate_bias_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // placeholder61
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param61
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // projection_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // placeholder62
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param62
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_state_in_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.013764165341854f, 0.140751048922539f, 0.039583537727594f, -0.004039138555527f, 0.139963015913963f, 0.072681039571762f})
}, { // placeholder63
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param63
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_state_in_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.645632147789001f, 0.518238246440887f, 0.168679088354111f, 0.555787742137909f, -0.49367481470108f, 0.475847363471985f, 0.106874041259289f, 0.50430965423584f})
}, { // placeholder64
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param64
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, 0.2f, 0.3f, 0.5f})
}, { // placeholder65
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param65
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // placeholder66
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param66
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // placeholder67
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param67
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_layer_norm_weights_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // placeholder68
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param68
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {31, 32, 33},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {34, 35, 36},
.outputs = {1}
}, {
.type = TestOperationType::ADD,
.inputs = {37, 38, 39},
.outputs = {2}
}, {
.type = TestOperationType::ADD,
.inputs = {40, 41, 42},
.outputs = {3}
}, {
.type = TestOperationType::ADD,
.inputs = {43, 44, 45},
.outputs = {4}
}, {
.type = TestOperationType::ADD,
.inputs = {46, 47, 48},
.outputs = {5}
}, {
.type = TestOperationType::ADD,
.inputs = {49, 50, 51},
.outputs = {6}
}, {
.type = TestOperationType::ADD,
.inputs = {52, 53, 54},
.outputs = {7}
}, {
.type = TestOperationType::ADD,
.inputs = {55, 56, 57},
.outputs = {8}
}, {
.type = TestOperationType::ADD,
.inputs = {58, 59, 60},
.outputs = {9}
}, {
.type = TestOperationType::ADD,
.inputs = {61, 62, 63},
.outputs = {10}
}, {
.type = TestOperationType::ADD,
.inputs = {64, 65, 66},
.outputs = {11}
}, {
.type = TestOperationType::ADD,
.inputs = {67, 68, 69},
.outputs = {12}
}, {
.type = TestOperationType::ADD,
.inputs = {70, 71, 72},
.outputs = {13}
}, {
.type = TestOperationType::ADD,
.inputs = {73, 74, 75},
.outputs = {14}
}, {
.type = TestOperationType::ADD,
.inputs = {76, 77, 78},
.outputs = {15}
}, {
.type = TestOperationType::ADD,
.inputs = {79, 80, 81},
.outputs = {16}
}, {
.type = TestOperationType::ADD,
.inputs = {82, 83, 84},
.outputs = {18}
}, {
.type = TestOperationType::ADD,
.inputs = {85, 86, 87},
.outputs = {19}
}, {
.type = TestOperationType::ADD,
.inputs = {88, 89, 90},
.outputs = {23}
}, {
.type = TestOperationType::ADD,
.inputs = {91, 92, 93},
.outputs = {24}
}, {
.type = TestOperationType::ADD,
.inputs = {94, 95, 96},
.outputs = {25}
}, {
.type = TestOperationType::ADD,
.inputs = {97, 98, 99},
.outputs = {26}
}, {
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {17, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3 = TestModelManager::get().add("layer_norm_lstm_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3", get_test_model_NoCifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm() {
static TestModel model = {
.main = {
.operands = {{ // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.8f, 0.1f, 0.2f, 0.3f, 0.3f, 0.2f, 0.9f, 0.8f, 0.1f})
}, { // input_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // input_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // input_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // recurrent_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // recurrent_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // recurrent_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // cell_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // cell_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // input_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // cell_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // output_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // projection_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // projection_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // activation_param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // cell_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // output_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // scratch_buffer1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 12},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3510298f, 0.4261035f, 0.2146365f, 0.2771652f, -0.1885517f, 0.32522f, 0.0203665f, 0.4896766f})
}, { // output1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.02129706f, 0.140816242f, 0.0112733059f, -0.0226350538f, 0.0916948169f, 0.0769175813f})
}},
.operations = {{
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm = TestModelManager::get().add("layer_norm_lstm_CifgPeepholeProjectionNoClippingLayerNormLstm", get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal() {
static TestModel model = {
.main = {
.operands = {{ // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // activation_param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // scratch_buffer1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 12},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3510298f, 0.4261035f, 0.2146365f, 0.2771652f, -0.1885517f, 0.32522f, 0.0203665f, 0.4896766f})
}, { // output1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.02129706f, 0.140816242f, 0.0112733059f, -0.0226350538f, 0.0916948169f, 0.0769175813f})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.8f, 0.1f, 0.2f, 0.3f, 0.3f, 0.2f, 0.9f, 0.8f, 0.1f})
}, { // placeholder69
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param69
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // placeholder70
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param70
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_cell_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // placeholder71
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param71
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // placeholder72
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param72
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // placeholder73
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param73
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_cell_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // placeholder74
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param74
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // placeholder75
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param75
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // placeholder76
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param76
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // placeholder77
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param77
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // placeholder78
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param78
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // placeholder79
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param79
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // placeholder80
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param80
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // projection_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // placeholder81
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param81
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_state_in1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // placeholder82
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param82
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_state_in1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // placeholder83
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param83
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // placeholder84
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param84
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // placeholder85
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param85
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // placeholder86
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param86
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {31, 32, 33},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {34, 35, 36},
.outputs = {2}
}, {
.type = TestOperationType::ADD,
.inputs = {37, 38, 39},
.outputs = {3}
}, {
.type = TestOperationType::ADD,
.inputs = {40, 41, 42},
.outputs = {4}
}, {
.type = TestOperationType::ADD,
.inputs = {43, 44, 45},
.outputs = {6}
}, {
.type = TestOperationType::ADD,
.inputs = {46, 47, 48},
.outputs = {7}
}, {
.type = TestOperationType::ADD,
.inputs = {49, 50, 51},
.outputs = {8}
}, {
.type = TestOperationType::ADD,
.inputs = {52, 53, 54},
.outputs = {10}
}, {
.type = TestOperationType::ADD,
.inputs = {55, 56, 57},
.outputs = {11}
}, {
.type = TestOperationType::ADD,
.inputs = {58, 59, 60},
.outputs = {13}
}, {
.type = TestOperationType::ADD,
.inputs = {61, 62, 63},
.outputs = {14}
}, {
.type = TestOperationType::ADD,
.inputs = {64, 65, 66},
.outputs = {15}
}, {
.type = TestOperationType::ADD,
.inputs = {67, 68, 69},
.outputs = {16}
}, {
.type = TestOperationType::ADD,
.inputs = {70, 71, 72},
.outputs = {18}
}, {
.type = TestOperationType::ADD,
.inputs = {73, 74, 75},
.outputs = {19}
}, {
.type = TestOperationType::ADD,
.inputs = {76, 77, 78},
.outputs = {24}
}, {
.type = TestOperationType::ADD,
.inputs = {79, 80, 81},
.outputs = {25}
}, {
.type = TestOperationType::ADD,
.inputs = {82, 83, 84},
.outputs = {26}
}, {
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {1, 5, 9, 12, 17, 23, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal = TestModelManager::get().add("layer_norm_lstm_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal", get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_2() {
static TestModel model = {
.main = {
.operands = {{ // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.8f, 0.1f, 0.2f, 0.4f, 0.5f, 0.1f, 0.5f, 0.2f, 0.4f, 0.2f})
}, { // input_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // input_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // input_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // recurrent_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // recurrent_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // recurrent_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // cell_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // cell_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // input_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // cell_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // output_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // projection_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // projection_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.02129706f, 0.140816242f, 0.0112733059f, -0.0226350538f, 0.0916948169f, 0.0769175813f})
}, { // cell_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3510298f, 0.4261035f, 0.2146365f, 0.2771652f, -0.1885517f, 0.32522f, 0.0203665f, 0.4896766f})
}, { // activation_param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // cell_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // output_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // scratch_buffer1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 12},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5069088f, 0.5386363f, 0.1980069f, 0.5355753f, -0.3866257f, 0.4749442f, 0.1074765f, 0.7124508f})
}, { // output1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0132302344f, 0.152308047f, 0.0346313119f, -0.0269966982f, 0.149707705f, 0.094149217f})
}},
.operations = {{
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_2 = TestModelManager::get().add("layer_norm_lstm_CifgPeepholeProjectionNoClippingLayerNormLstm_2", get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_2());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2() {
static TestModel model = {
.main = {
.operands = {{ // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // activation_param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // scratch_buffer1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 12},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5069088f, 0.5386363f, 0.1980069f, 0.5355753f, -0.3866257f, 0.4749442f, 0.1074765f, 0.7124508f})
}, { // output1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0132302344f, 0.152308047f, 0.0346313119f, -0.0269966982f, 0.149707705f, 0.094149217f})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.8f, 0.1f, 0.2f, 0.4f, 0.5f, 0.1f, 0.5f, 0.2f, 0.4f, 0.2f})
}, { // placeholder87
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param87
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // placeholder88
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param88
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_cell_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // placeholder89
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param89
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // placeholder90
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param90
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // placeholder91
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param91
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_cell_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // placeholder92
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param92
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // placeholder93
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param93
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // placeholder94
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param94
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // placeholder95
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param95
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // placeholder96
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param96
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // placeholder97
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param97
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // placeholder98
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param98
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // projection_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // placeholder99
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param99
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_state_in1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.02129706f, 0.140816242f, 0.0112733059f, -0.0226350538f, 0.0916948169f, 0.0769175813f})
}, { // placeholder100
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param100
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_state_in1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3510298f, 0.4261035f, 0.2146365f, 0.2771652f, -0.1885517f, 0.32522f, 0.0203665f, 0.4896766f})
}, { // placeholder101
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param101
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // placeholder102
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param102
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // placeholder103
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param103
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // placeholder104
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param104
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {31, 32, 33},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {34, 35, 36},
.outputs = {2}
}, {
.type = TestOperationType::ADD,
.inputs = {37, 38, 39},
.outputs = {3}
}, {
.type = TestOperationType::ADD,
.inputs = {40, 41, 42},
.outputs = {4}
}, {
.type = TestOperationType::ADD,
.inputs = {43, 44, 45},
.outputs = {6}
}, {
.type = TestOperationType::ADD,
.inputs = {46, 47, 48},
.outputs = {7}
}, {
.type = TestOperationType::ADD,
.inputs = {49, 50, 51},
.outputs = {8}
}, {
.type = TestOperationType::ADD,
.inputs = {52, 53, 54},
.outputs = {10}
}, {
.type = TestOperationType::ADD,
.inputs = {55, 56, 57},
.outputs = {11}
}, {
.type = TestOperationType::ADD,
.inputs = {58, 59, 60},
.outputs = {13}
}, {
.type = TestOperationType::ADD,
.inputs = {61, 62, 63},
.outputs = {14}
}, {
.type = TestOperationType::ADD,
.inputs = {64, 65, 66},
.outputs = {15}
}, {
.type = TestOperationType::ADD,
.inputs = {67, 68, 69},
.outputs = {16}
}, {
.type = TestOperationType::ADD,
.inputs = {70, 71, 72},
.outputs = {18}
}, {
.type = TestOperationType::ADD,
.inputs = {73, 74, 75},
.outputs = {19}
}, {
.type = TestOperationType::ADD,
.inputs = {76, 77, 78},
.outputs = {24}
}, {
.type = TestOperationType::ADD,
.inputs = {79, 80, 81},
.outputs = {25}
}, {
.type = TestOperationType::ADD,
.inputs = {82, 83, 84},
.outputs = {26}
}, {
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {1, 5, 9, 12, 17, 23, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2 = TestModelManager::get().add("layer_norm_lstm_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2", get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_2());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_3() {
static TestModel model = {
.main = {
.operands = {{ // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.7f, 0.7f, 0.1f, 0.7f, 0.6f, 0.9f, 0.2f, 0.5f, 0.7f})
}, { // input_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // input_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // input_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // recurrent_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // recurrent_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // recurrent_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // cell_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // cell_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // input_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // cell_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // output_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // projection_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // projection_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0132302344f, 0.152308047f, 0.0346313119f, -0.0269966982f, 0.149707705f, 0.094149217f})
}, { // cell_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5069088f, 0.5386363f, 0.1980069f, 0.5355753f, -0.3866257f, 0.4749442f, 0.1074765f, 0.7124508f})
}, { // activation_param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // cell_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // output_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // scratch_buffer1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 12},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5736622f, 0.5952501f, 0.129295f, 0.711027f, -0.5323033f, 0.5556133f, 0.1800992f, 0.7845056f})
}, { // output1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.0123688057f, 0.165790111f, 0.0893077999f, -0.0103429332f, 0.173016444f, 0.0720508844f})
}},
.operations = {{
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_3 = TestModelManager::get().add("layer_norm_lstm_CifgPeepholeProjectionNoClippingLayerNormLstm_3", get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_3());
} // namespace generated_tests::layer_norm_lstm
namespace generated_tests::layer_norm_lstm {
const TestModel& get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3() {
static TestModel model = {
.main = {
.operands = {{ // input1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0, 0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_cell_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // recurrent_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_input_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_forget_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_to_output_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // input_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_gate_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // projection_bias1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_state_in1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // activation_param1
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({4})
}, { // cell_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // proj_clip_param1
.type = TestOperandType::FLOAT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // input_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {0},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // forget_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // cell_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // output_layer_norm_weights1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::TEMPORARY_VARIABLE,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({})
}, { // scratch_buffer1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 12},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // output_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = true,
.data = TestBuffer::createFromVector<float>({0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f})
}, { // cell_state_out1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5736622f, 0.5952501f, 0.129295f, 0.711027f, -0.5323033f, 0.5556133f, 0.1800992f, 0.7845056f})
}, { // output1
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 0,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_OUTPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.0123688057f, 0.165790111f, 0.0893077999f, -0.0103429332f, 0.173016444f, 0.0720508844f})
}, { // input1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.7f, 0.7f, 0.1f, 0.7f, 0.6f, 0.9f, 0.2f, 0.5f, 0.7f})
}, { // placeholder105
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param105
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.6f, -0.1f, 0.3f, 0.2f, 0.9f, -0.5f, -0.2f, -0.4f, 0.3f, -0.8f, -0.4f, 0.3f, -0.5f, -0.4f, -0.6f, 0.3f, -0.4f, -0.6f, -0.5f, -0.5f})
}, { // placeholder106
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param106
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_cell_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.4f, -0.3f, -0.2f, -0.1f, -0.5f, 0.5f, -0.2f, -0.3f, -0.2f, -0.6f, 0.6f, -0.1f, -0.4f, -0.3f, -0.7f, 0.7f, -0.9f, -0.5f, 0.8f, 0.6f})
}, { // placeholder107
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param107
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // input_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 5},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.8f, -0.4f, -0.2f, -0.9f, -0.1f, -0.7f, 0.3f, -0.3f, -0.8f, -0.2f, 0.6f, -0.2f, 0.4f, -0.7f, -0.3f, -0.5f, 0.1f, 0.5f, -0.6f, -0.4f})
}, { // placeholder108
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param108
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5f, -0.3f, -0.5f, -0.2f, 0.6f, 0.4f, 0.9f, 0.3f, -0.1f, 0.2f, 0.5f, 0.2f})
}, { // placeholder109
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param109
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_cell_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.3f, 0.2f, 0.1f, -0.3f, 0.8f, -0.08f, -0.2f, 0.3f, 0.8f, -0.6f, -0.1f, 0.2f})
}, { // placeholder110
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param110
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // recurrent_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.3f, -0.1f, 0.1f, -0.2f, -0.5f, -0.7f, -0.2f, -0.6f, -0.1f, -0.4f, -0.7f, -0.2f})
}, { // placeholder111
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param111
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_forget_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.02f, -0.15f, -0.25f, -0.03f})
}, { // placeholder112
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param112
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_to_output_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.1f, -0.5f, 0.05f})
}, { // placeholder113
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param113
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.1f, -0.3f, -0.2f, 0.1f})
}, { // placeholder114
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param114
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.05f, 0.72f, 0.25f, 0.08f})
}, { // placeholder115
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param115
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_gate_bias1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.05f, -0.01f, 0.2f, 0.1f})
}, { // placeholder116
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param116
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // projection_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {3, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.1f, 0.2f, 0.01f, -0.2f, 0.1f, 0.5f, 0.3f, 0.08f, 0.07f, 0.2f, -0.4f, 0.2f})
}, { // placeholder117
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param117
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_state_in1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 3},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0132302344f, 0.152308047f, 0.0346313119f, -0.0269966982f, 0.149707705f, 0.094149217f})
}, { // placeholder118
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param118
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_state_in1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {2, 4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({-0.5069088f, 0.5386363f, 0.1980069f, 0.5355753f, -0.3866257f, 0.4749442f, 0.1074765f, 0.7124508f})
}, { // placeholder119
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param119
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // forget_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.2f, 0.2f, 0.4f, 0.3f})
}, { // placeholder120
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param120
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // cell_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.7f, 0.2f, 0.3f, 0.8f})
}, { // placeholder121
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param121
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}, { // output_layer_norm_weights1_new
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {4},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::SUBGRAPH_INPUT,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.6f, 0.2f, 0.2f, 0.5f})
}, { // placeholder122
.type = TestOperandType::TENSOR_FLOAT32,
.dimensions = {1},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<float>({0.0f})
}, { // param122
.type = TestOperandType::INT32,
.dimensions = {},
.numberOfConsumers = 1,
.scale = 0.0f,
.zeroPoint = 0,
.lifetime = TestOperandLifeTime::CONSTANT_COPY,
.channelQuant = {},
.isIgnored = false,
.data = TestBuffer::createFromVector<int32_t>({0})
}},
.operations = {{
.type = TestOperationType::ADD,
.inputs = {31, 32, 33},
.outputs = {0}
}, {
.type = TestOperationType::ADD,
.inputs = {34, 35, 36},
.outputs = {2}
}, {
.type = TestOperationType::ADD,
.inputs = {37, 38, 39},
.outputs = {3}
}, {
.type = TestOperationType::ADD,
.inputs = {40, 41, 42},
.outputs = {4}
}, {
.type = TestOperationType::ADD,
.inputs = {43, 44, 45},
.outputs = {6}
}, {
.type = TestOperationType::ADD,
.inputs = {46, 47, 48},
.outputs = {7}
}, {
.type = TestOperationType::ADD,
.inputs = {49, 50, 51},
.outputs = {8}
}, {
.type = TestOperationType::ADD,
.inputs = {52, 53, 54},
.outputs = {10}
}, {
.type = TestOperationType::ADD,
.inputs = {55, 56, 57},
.outputs = {11}
}, {
.type = TestOperationType::ADD,
.inputs = {58, 59, 60},
.outputs = {13}
}, {
.type = TestOperationType::ADD,
.inputs = {61, 62, 63},
.outputs = {14}
}, {
.type = TestOperationType::ADD,
.inputs = {64, 65, 66},
.outputs = {15}
}, {
.type = TestOperationType::ADD,
.inputs = {67, 68, 69},
.outputs = {16}
}, {
.type = TestOperationType::ADD,
.inputs = {70, 71, 72},
.outputs = {18}
}, {
.type = TestOperationType::ADD,
.inputs = {73, 74, 75},
.outputs = {19}
}, {
.type = TestOperationType::ADD,
.inputs = {76, 77, 78},
.outputs = {24}
}, {
.type = TestOperationType::ADD,
.inputs = {79, 80, 81},
.outputs = {25}
}, {
.type = TestOperationType::ADD,
.inputs = {82, 83, 84},
.outputs = {26}
}, {
.type = TestOperationType::LSTM,
.inputs = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
.outputs = {27, 28, 29, 30}
}},
.inputIndexes = {1, 5, 9, 12, 17, 23, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82},
.outputIndexes = {27, 28, 29, 30}
},
.referenced = {},
.isRelaxed = false,
.expectedMultinomialDistributionTolerance = 0,
.expectFailure = false,
.minSupportedVersion = TestHalVersion::V1_2
};
return model;
}
const auto dummy_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3 = TestModelManager::get().add("layer_norm_lstm_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3", get_test_model_CifgPeepholeProjectionNoClippingLayerNormLstm_all_inputs_as_internal_3());
} // namespace generated_tests::layer_norm_lstm
| 57.115875 | 314 | 0.3703 | [
"model"
] |
f52d6e2a3b99c0080f99ef09eddce36a3f463443 | 2,833 | cpp | C++ | Leetcode/2001-3000/2056. Number of Valid Move Combinations On Chessboard/2056.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/2001-3000/2056. Number of Valid Move Combinations On Chessboard/2056.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/2001-3000/2056. Number of Valid Move Combinations On Chessboard/2056.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int countCombinations(vector<string>& pieces,
vector<vector<int>>& positions) {
const int n = pieces.size();
unordered_set<unsigned long long> ans;
vector<vector<pair<int, int>>> combMoves;
vector<pair<int, int>> board;
getCombMoves(pieces, 0, {}, combMoves);
for (const auto& pos : positions)
board.emplace_back(pos[0], pos[1]);
for (const auto& combMove : combMoves)
dfs(board, n, combMove, (1 << n) - 1, ans);
return ans.size();
}
private:
const unordered_map<string, vector<pair<int, int>>> moves{
{"rook", {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}},
{"bishop", {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}},
{"queen",
{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}}};
void getCombMoves(const vector<string>& pieces, int ithPiece,
vector<pair<int, int>>&& path,
vector<vector<pair<int, int>>>& combMoves) {
if (ithPiece == pieces.size()) {
combMoves.push_back(path);
return;
}
for (const auto& move : moves.at(pieces[ithPiece])) {
path.push_back(move);
getCombMoves(pieces, ithPiece + 1, std::move(path), combMoves);
path.pop_back();
}
}
void dfs(const vector<pair<int, int>>& board, int n,
const vector<pair<int, int>>& combMove, int activeMask,
unordered_set<unsigned long long>& ans) {
if (activeMask == 0)
return;
ans.insert(hash(board));
for (int nextActiveMask = 1; nextActiveMask < 1 << n; ++nextActiveMask) {
if ((activeMask & nextActiveMask) != nextActiveMask)
continue;
// make sure to copy the board
auto nextBoard(board);
// move pieces that are active in this turn
for (int i = 0; i < n; ++i)
if ((nextActiveMask >> i) & 1) {
nextBoard[i].first += combMove[i].first;
nextBoard[i].second += combMove[i].second;
}
// check no two or more pieces occupy the same square
if (getUniqueSize(nextBoard) < n)
continue;
// check if all in boundary
if (all_of(begin(nextBoard), end(nextBoard), [](const auto& piece) {
const int x = piece.first;
const int y = piece.second;
return 1 <= x && x <= 8 && 1 <= y && y <= 8;
}))
dfs(nextBoard, n, combMove, nextActiveMask, ans);
}
}
unsigned long long hash(const vector<pair<int, int>>& board) {
unsigned long long hashed;
for (const auto& [x, y] : board)
hashed = (hashed * 64) + (x - 1 << 3) + (y - 1);
return hashed;
}
int getUniqueSize(const vector<pair<int, int>>& board) {
unordered_set<int> unique;
for (const auto& [x, y] : board)
unique.insert(x * 8 + y);
return unique.size();
}
};
| 30.793478 | 80 | 0.551006 | [
"vector"
] |
f530013c1cfc35edc1fe19916b7a9f3e94a000a9 | 1,386 | cpp | C++ | src/common/error.cpp | shucheng-ai/WDA-core | b1d952aef01537439db13e845e60b8bf77c1c10d | [
"Apache-2.0"
] | null | null | null | src/common/error.cpp | shucheng-ai/WDA-core | b1d952aef01537439db13e845e60b8bf77c1c10d | [
"Apache-2.0"
] | null | null | null | src/common/error.cpp | shucheng-ai/WDA-core | b1d952aef01537439db13e845e60b8bf77c1c10d | [
"Apache-2.0"
] | null | null | null | #include <pybind11/pybind11.h>
#include "error.h"
namespace layout{
void errorDef(py::module m){
py::register_exception<UnknownError>(m, "UnknownError");
py::class_<UnknownError>(m, "UnknownWarning").def("__repr__", &UnknownError::what);
py::register_exception<StorageError>(m, "StorageError");
py::class_<StorageError, UnknownError>(m, "StorageWarning").def("__repr__", &StorageError::what);
py::register_exception<ParameterError>(m, "ParameterError");
py::class_<ParameterError, UnknownError>(m, "ParameterWarning").def("__repr__", &ParameterError::what);
py::register_exception<MethodError>(m, "MethodError");
py::class_<MethodError, UnknownError>(m, "MethodWarning").def("__repr__", &MethodError::what);
py::register_exception<InterfaceError>(m, "InterfaceError");
py::class_<InterfaceError, UnknownError>(m, "InterfaceWarning").def("__repr__", &InterfaceError::what);
m.def("warning_list", [](bool clear){
py::list ret;
for (auto &warning : warning_list) ret.append(*warning.get());
if (clear) warning_list.clear();
return ret;
},
"clear"_a = 1
);
m.def("clear_warning_list", []{
warning_list.clear();
});
}
vector<unique_ptr<UnknownError>> warning_list;
}
| 38.5 | 111 | 0.627706 | [
"vector"
] |
f5324a45011bf92af025ad8e4947c656257e8b38 | 8,306 | cc | C++ | src/breakpad/src/tools/linux/symupload/sym_upload.cc | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 46 | 2015-01-08T14:32:34.000Z | 2022-02-05T16:48:26.000Z | src/breakpad/src/tools/linux/symupload/sym_upload.cc | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 7 | 2015-01-20T14:28:12.000Z | 2017-01-18T17:21:44.000Z | src/breakpad/src/tools/linux/symupload/sym_upload.cc | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 14 | 2015-10-27T06:17:48.000Z | 2020-03-03T06:15:50.000Z | // Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
// symupload.cc: Upload a symbol file to a HTTP server. The upload is sent as
// a multipart/form-data POST request with the following parameters:
// code_file: the basename of the module, e.g. "app"
// debug_file: the basename of the debugging file, e.g. "app"
// debug_identifier: the debug file's identifier, usually consisting of
// the guid and age embedded in the pdb, e.g.
// "11111111BBBB3333DDDD555555555555F"
// version: the file version of the module, e.g. "1.2.3.4"
// os: the operating system that the module was built for
// cpu: the CPU that the module was built for
// symbol_file: the contents of the breakpad-format symbol file
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
#include "common/linux/http_upload.h"
using google_breakpad::HTTPUpload;
typedef struct {
std::string symbolsPath;
std::string uploadURLStr;
std::string proxy;
std::string proxy_user_pwd;
std::string version;
bool success;
} Options;
static void TokenizeByChar(const std::string &source_string,
int c, std::vector<std::string> *results) {
assert(results);
std::string::size_type cur_pos = 0, next_pos = 0;
while ((next_pos = source_string.find(c, cur_pos)) != std::string::npos) {
if (next_pos != cur_pos)
results->push_back(source_string.substr(cur_pos, next_pos - cur_pos));
cur_pos = next_pos + 1;
}
if (cur_pos < source_string.size() && next_pos != cur_pos)
results->push_back(source_string.substr(cur_pos));
}
//=============================================================================
// Parse out the module line which have 5 parts.
// MODULE <os> <cpu> <uuid> <module-name>
static bool ModuleDataForSymbolFile(const std::string &file,
std::vector<std::string> *module_parts) {
assert(module_parts);
const size_t kModulePartNumber = 5;
FILE *fp = fopen(file.c_str(), "r");
if (fp) {
char buffer[1024];
if (fgets(buffer, sizeof(buffer), fp)) {
std::string line(buffer);
std::string::size_type line_break_pos = line.find_first_of('\n');
if (line_break_pos == std::string::npos) {
assert(!"The file is invalid!");
fclose(fp);
return false;
}
line.resize(line_break_pos);
const char kDelimiter = ' ';
TokenizeByChar(line, kDelimiter, module_parts);
if (module_parts->size() != kModulePartNumber)
module_parts->clear();
}
fclose(fp);
}
return module_parts->size() == kModulePartNumber;
}
//=============================================================================
static std::string CompactIdentifier(const std::string &uuid) {
std::vector<std::string> components;
TokenizeByChar(uuid, '-', &components);
std::string result;
for (size_t i = 0; i < components.size(); ++i)
result += components[i];
return result;
}
//=============================================================================
static void Start(Options *options) {
std::map<std::string, std::string> parameters;
options->success = false;
std::vector<std::string> module_parts;
if (!ModuleDataForSymbolFile(options->symbolsPath, &module_parts)) {
fprintf(stderr, "Failed to parse symbol file!\n");
return;
}
std::string compacted_id = CompactIdentifier(module_parts[3]);
// Add parameters
if (!options->version.empty())
parameters["version"] = options->version;
// MODULE <os> <cpu> <uuid> <module-name>
// 0 1 2 3 4
parameters["os"] = module_parts[1];
parameters["cpu"] = module_parts[2];
parameters["debug_file"] = module_parts[4];
parameters["code_file"] = module_parts[4];
parameters["debug_identifier"] = compacted_id;
std::string response, error;
long response_code;
bool success = HTTPUpload::SendRequest(options->uploadURLStr,
parameters,
options->symbolsPath,
"symbol_file",
options->proxy,
options->proxy_user_pwd,
"",
&response,
&response_code,
&error);
if (!success) {
printf("Failed to send symbol file: %s\n", error.c_str());
printf("Response:\n");
printf("%s\n", response.c_str());
} else if (response_code == 0) {
printf("Failed to send symbol file: No response code\n");
} else if (response_code != 200) {
printf("Failed to send symbol file: Response code %ld\n", response_code);
printf("Response:\n");
printf("%s\n", response.c_str());
} else {
printf("Successfully sent the symbol file.\n");
}
options->success = success;
}
//=============================================================================
static void
Usage(int argc, const char *argv[]) {
fprintf(stderr, "Submit symbol information.\n");
fprintf(stderr, "Usage: %s [options...] <symbols> <upload-URL>\n", argv[0]);
fprintf(stderr, "Options:\n");
fprintf(stderr, "<symbols> should be created by using the dump_syms tool.\n");
fprintf(stderr, "<upload-URL> is the destination for the upload\n");
fprintf(stderr, "-v:\t Version information (e.g., 1.2.3.4)\n");
fprintf(stderr, "-x:\t <host[:port]> Use HTTP proxy on given port\n");
fprintf(stderr, "-u:\t <user[:password]> Set proxy user and password\n");
fprintf(stderr, "-h:\t Usage\n");
fprintf(stderr, "-?:\t Usage\n");
}
//=============================================================================
static void
SetupOptions(int argc, const char *argv[], Options *options) {
extern int optind;
char ch;
while ((ch = getopt(argc, (char * const *)argv, "u:v:x:h?")) != -1) {
switch (ch) {
case 'u':
options->proxy_user_pwd = optarg;
break;
case 'v':
options->version = optarg;
break;
case 'x':
options->proxy = optarg;
break;
default:
Usage(argc, argv);
exit(0);
break;
}
}
if ((argc - optind) != 2) {
fprintf(stderr, "%s: Missing symbols file and/or upload-URL\n", argv[0]);
Usage(argc, argv);
exit(1);
}
options->symbolsPath = argv[optind];
options->uploadURLStr = argv[optind + 1];
}
//=============================================================================
int main (int argc, const char * argv[]) {
Options options;
SetupOptions(argc, argv, &options);
Start(&options);
return options.success ? 0 : 1;
}
| 36.590308 | 80 | 0.604382 | [
"vector"
] |
f5346ac37cae337cc5bc4f27a19d1553f1429f77 | 22,771 | cc | C++ | chrome/browser/ui/commander/commander_controller_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/ui/commander/commander_controller_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/ui/commander/commander_controller_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // 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 "chrome/browser/ui/commander/commander_controller.h"
#include <string>
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "chrome/browser/ui/commander/command_source.h"
#include "chrome/browser/ui/commander/commander_view_model.h"
#include "chrome/test/base/browser_with_test_window_test.h"
namespace commander {
namespace {
class TestCommandSource : public CommandSource {
public:
using GetCommandsHandler =
base::RepeatingCallback<CommandResults(const std::u16string&,
Browser* browser)>;
explicit TestCommandSource(GetCommandsHandler handler)
: handler_(std::move(handler)) {}
~TestCommandSource() override = default;
CommandResults GetCommands(const std::u16string& input,
Browser* browser) const override {
invocations_.push_back(input);
return handler_.Run(input, browser);
}
const std::vector<std::u16string>& invocations() const {
return invocations_;
}
private:
mutable std::vector<std::u16string> invocations_;
GetCommandsHandler handler_;
};
std::unique_ptr<TestCommandSource> CreateNoOpCommandSource() {
return std::make_unique<TestCommandSource>(base::BindRepeating(
[](const std::u16string&,
Browser* browser) -> CommandSource::CommandResults { return {}; }));
}
std::unique_ptr<CommandItem> CreateNoOpCommandItem(const std::u16string& title,
double score) {
std::vector<gfx::Range> ranges{{0, static_cast<uint32_t>(title.size())}};
auto item = std::make_unique<CommandItem>(title, score, ranges);
item->command = base::DoNothing();
return item;
}
TestCommandSource* AddSource(
std::vector<std::unique_ptr<CommandSource>>* sources,
std::unique_ptr<TestCommandSource> source) {
TestCommandSource* bare_ptr = source.get();
sources->push_back(std::move(source));
return bare_ptr;
}
} // namespace
class CommanderControllerTest : public BrowserWithTestWindowTest {
public:
void SetUp() override {
BrowserWithTestWindowTest::SetUp();
expected_count_ = 0;
}
void ExpectViewModelCallbackCalls(int expected_count) {
expected_count_ += expected_count;
}
void WaitForExpectedCallbacks() {
if (expected_count_ <= 0)
return;
if (!run_loop_.get() || !run_loop_->running()) {
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
}
void OnViewModelUpdated(CommanderViewModel view_model) {
received_view_models_.push_back(view_model);
if (expected_count_ > 0) {
expected_count_--;
if (run_loop_.get() && expected_count_ == 0)
run_loop_->Quit();
}
}
protected:
std::unique_ptr<base::RunLoop> run_loop_;
int expected_count_;
std::vector<CommanderViewModel> received_view_models_;
};
class ViewModelCallbackWaiter {
public:
explicit ViewModelCallbackWaiter(CommanderControllerTest* test, int count = 1)
: test_(test) {
test_->ExpectViewModelCallbackCalls(count);
}
~ViewModelCallbackWaiter() { test_->WaitForExpectedCallbacks(); }
private:
CommanderControllerTest* test_;
};
TEST_F(CommanderControllerTest, PassesInputToCommandSourcesOnTextChanged) {
std::vector<std::unique_ptr<CommandSource>> sources;
TestCommandSource* first = AddSource(&sources, CreateNoOpCommandSource());
TestCommandSource* second = AddSource(&sources, CreateNoOpCommandSource());
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
EXPECT_EQ(first->invocations().size(), 0u);
EXPECT_EQ(second->invocations().size(), 0u);
std::u16string input = u"foobar";
controller->OnTextChanged(input, browser());
EXPECT_EQ(first->invocations().size(), 1u);
EXPECT_EQ(second->invocations().size(), 1u);
EXPECT_EQ(first->invocations().back(), input);
EXPECT_EQ(second->invocations().back(), input);
}
TEST_F(CommanderControllerTest, ResultSetIdsDifferAcrossCalls) {
std::vector<std::unique_ptr<CommandSource>> sources;
ignore_result(AddSource(&sources, CreateNoOpCommandSource()));
base::RunLoop run_loop;
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
// Assert since we're accessing an element.
ASSERT_EQ(received_view_models_.size(), 1u);
int first_id = received_view_models_.back().result_set_id;
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"barfoo", browser());
}
EXPECT_EQ(received_view_models_.size(), 2u);
EXPECT_NE(received_view_models_.back().result_set_id, first_id);
}
TEST_F(CommanderControllerTest, ViewModelAggregatesResults) {
std::vector<std::unique_ptr<CommandSource>> sources;
auto first = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
CommandSource::CommandResults result;
result.push_back(CreateNoOpCommandItem(u"first", 100));
return result;
}));
auto second = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
CommandSource::CommandResults result;
auto item = CreateNoOpCommandItem(u"second", 99);
item->annotation = u"2nd";
item->entity_type = CommandItem::Entity::kBookmark;
result.push_back(std::move(item));
return result;
}));
sources.push_back(std::move(first));
sources.push_back(std::move(second));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
ASSERT_EQ(model.items.size(), 2u);
EXPECT_EQ(model.items[0].title, u"first");
EXPECT_EQ(model.items[0].annotation, std::u16string());
EXPECT_EQ(model.items[0].entity_type, CommandItem::Entity::kCommand);
EXPECT_EQ(model.items[1].title, u"second");
EXPECT_EQ(model.items[1].annotation, u"2nd");
EXPECT_EQ(model.items[1].entity_type, CommandItem::Entity::kBookmark);
}
// TODO(lgrey): This will need to change when scoring gets more sophisticated
// than a simple sort.
TEST_F(CommanderControllerTest, ViewModelSortsResults) {
std::vector<std::unique_ptr<CommandSource>> sources;
auto first = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
CommandSource::CommandResults result;
result.push_back(CreateNoOpCommandItem(u"third", 98));
result.push_back(CreateNoOpCommandItem(u"first", 100));
result.push_back(CreateNoOpCommandItem(u"fourth", 90));
return result;
}));
auto second = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
CommandSource::CommandResults result;
result.push_back(CreateNoOpCommandItem(u"second", 99));
result.push_back(CreateNoOpCommandItem(u"fifth", 1));
return result;
}));
sources.push_back(std::move(first));
sources.push_back(std::move(second));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
ASSERT_EQ(model.items.size(), 5u);
EXPECT_EQ(model.items[0].title, u"first");
EXPECT_EQ(model.items[1].title, u"second");
EXPECT_EQ(model.items[2].title, u"third");
EXPECT_EQ(model.items[3].title, u"fourth");
EXPECT_EQ(model.items[4].title, u"fifth");
}
TEST_F(CommanderControllerTest, ViewModelSortsSameScoreAlphabetically) {
std::vector<std::unique_ptr<CommandSource>> sources;
auto source = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
CommandSource::CommandResults result;
result.push_back(CreateNoOpCommandItem(u"clementine", 100));
result.push_back(CreateNoOpCommandItem(u"apple", 100));
result.push_back(CreateNoOpCommandItem(u"banana", 100));
return result;
}));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
ASSERT_EQ(model.items.size(), 3u);
EXPECT_EQ(model.items[0].title, u"apple");
EXPECT_EQ(model.items[1].title, u"banana");
EXPECT_EQ(model.items[2].title, u"clementine");
}
TEST_F(CommanderControllerTest, ViewModelRetainsBoldRanges) {
std::vector<std::unique_ptr<CommandSource>> sources;
auto source = std::make_unique<TestCommandSource>(
base::BindRepeating([=](const std::u16string&, Browser* browser) {
auto first = CreateNoOpCommandItem(u"first", 100);
auto second = CreateNoOpCommandItem(u"second", 99);
first->matched_ranges.clear();
first->matched_ranges.emplace_back(0, 2);
first->matched_ranges.emplace_back(4, 1);
second->matched_ranges.clear();
second->matched_ranges.emplace_back(1, 4);
CommandSource::CommandResults result;
result.push_back(std::move(first));
result.push_back(std::move(second));
return result;
}));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
// Ensure |first| is at index 0;
EXPECT_EQ(model.items[0].title, u"first");
std::vector<gfx::Range> first_ranges = {gfx::Range(0, 2), gfx::Range(4, 1)};
std::vector<gfx::Range> second_ranges = {gfx::Range(1, 4)};
EXPECT_EQ(model.items[0].matched_ranges, first_ranges);
EXPECT_EQ(model.items[1].matched_ranges, second_ranges);
}
TEST_F(CommanderControllerTest, OnCommandSelectedInvokesOneShotCommand) {
std::vector<std::unique_ptr<CommandSource>> sources;
bool first_called = false;
bool second_called = false;
auto source = std::make_unique<TestCommandSource>(base::BindRepeating(
[](bool* first_called_ptr, bool* second_called_ptr, const std::u16string&,
Browser* browser) {
auto first = CreateNoOpCommandItem(u"first", 100);
auto second = CreateNoOpCommandItem(u"second", 99);
first->command = base::BindOnce([](bool* called) { *called = true; },
first_called_ptr);
second->command = base::BindOnce([](bool* called) { *called = true; },
second_called_ptr);
CommandSource::CommandResults result;
result.push_back(std::move(first));
result.push_back(std::move(second));
return result;
},
&first_called, &second_called));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
// Ensure |first| is at index 0;
EXPECT_EQ(model.items[0].title, u"first");
{
ViewModelCallbackWaiter waiter(this);
controller->OnCommandSelected(0, model.result_set_id);
}
EXPECT_TRUE(first_called);
EXPECT_FALSE(second_called);
EXPECT_EQ(received_view_models_.size(), 2u);
EXPECT_EQ(received_view_models_.back().action,
CommanderViewModel::Action::kClose);
}
TEST_F(CommanderControllerTest, NoActionOnIncorrectResultId) {
std::vector<std::unique_ptr<CommandSource>> sources;
bool item_called = false;
auto source = std::make_unique<TestCommandSource>(base::BindRepeating(
[](bool* called_ptr, const std::u16string&, Browser* browser) {
auto item = CreateNoOpCommandItem(u"first", 100);
item->command =
base::BindOnce([](bool* called) { *called = true; }, called_ptr);
CommandSource::CommandResults result;
result.push_back(std::move(item));
return result;
},
&item_called));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
controller->OnCommandSelected(0, model.result_set_id - 1);
EXPECT_FALSE(item_called);
}
TEST_F(CommanderControllerTest, NoActionOnOOBIndex) {
std::vector<std::unique_ptr<CommandSource>> sources;
bool item_called = false;
auto source = std::make_unique<TestCommandSource>(base::BindRepeating(
[](bool* called_ptr, const std::u16string&, Browser* browser) {
auto item = CreateNoOpCommandItem(u"first", 100);
item->command =
base::BindOnce([](bool* called) { *called = true; }, called_ptr);
CommandSource::CommandResults result;
result.push_back(std::move(item));
return result;
},
&item_called));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"foobar", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
CommanderViewModel model = received_view_models_.back();
controller->OnCommandSelected(1, model.result_set_id);
EXPECT_FALSE(item_called);
}
TEST_F(CommanderControllerTest, InvokingCompositeCommandSendsPrompt) {
std::vector<std::unique_ptr<CommandSource>> sources;
auto source = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
auto item = CreateNoOpCommandItem(u"first", 100);
CommandItem::CompositeCommandProvider noop =
base::BindRepeating([](const std::u16string&) {
return CommandSource::CommandResults();
});
item->command = std::make_pair(u"Do stuff", noop);
CommandSource::CommandResults result;
result.push_back(std::move(item));
return result;
}));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"abracadabra", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
{
ViewModelCallbackWaiter waiter(this);
controller->OnCommandSelected(0,
received_view_models_.back().result_set_id);
}
EXPECT_EQ(received_view_models_.back().action,
CommanderViewModel::Action::kPrompt);
EXPECT_EQ(received_view_models_.back().prompt_text, u"Do stuff");
}
TEST_F(CommanderControllerTest, OnTextChangedPassedToCompositeCommandProvider) {
std::vector<std::unique_ptr<CommandSource>> sources;
std::u16string received_string;
auto source = std::make_unique<TestCommandSource>(base::BindRepeating(
[](std::u16string* passthrough_string, const std::u16string& string,
Browser* browser) {
auto item = CreateNoOpCommandItem(u"first", 100);
CommandItem::CompositeCommandProvider provider = base::BindRepeating(
[](std::u16string* out_string, const std::u16string& string) {
*out_string = string;
return CommandSource::CommandResults();
},
passthrough_string);
item->command = std::make_pair(u"Do stuff", provider);
CommandSource::CommandResults result;
result.push_back(std::move(item));
return result;
},
&received_string));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"abracadabra", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
{
ViewModelCallbackWaiter waiter(this);
controller->OnCommandSelected(0,
received_view_models_.back().result_set_id);
}
controller->OnTextChanged(u"hocus pocus", browser());
EXPECT_EQ(received_string, u"hocus pocus");
}
TEST_F(CommanderControllerTest,
CompositeProviderCommandsArePresentedAndExecuted) {
std::vector<std::unique_ptr<CommandSource>> sources;
auto source = std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
auto outer = CreateNoOpCommandItem(u"outer", 100);
CommandItem::CompositeCommandProvider provider =
base::BindRepeating([](const std::u16string&) {
CommandSource::CommandResults results;
auto inner = CreateNoOpCommandItem(u"inner", 100);
inner->command = base::MakeExpectedRunClosure(FROM_HERE);
results.push_back(std::move(inner));
return results;
});
outer->command = std::make_pair(u"Do stuff", provider);
CommandSource::CommandResults result;
result.push_back(std::move(outer));
return result;
}));
sources.push_back(std::move(source));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"abracadabra", browser());
}
ASSERT_EQ(received_view_models_.size(), 1u);
// Select composite command.
{
ViewModelCallbackWaiter waiter(this);
controller->OnCommandSelected(0,
received_view_models_.back().result_set_id);
}
// Query again. Controller should pull results from the composite provider
// this time.
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"hocus pocus", browser());
}
ASSERT_EQ(received_view_models_.size(), 3u);
EXPECT_EQ(received_view_models_.back().items[0].title, u"inner");
controller->OnCommandSelected(0, received_view_models_.back().result_set_id);
// Inner command is an ExpectedRunClosure, so we will fail here if it wasn't
// called, without needing to assert anything.
}
TEST_F(CommanderControllerTest, OnCompositeCommandCancelledRemovesProvider) {
std::vector<std::unique_ptr<CommandSource>> sources;
TestCommandSource* source = AddSource(
&sources,
std::make_unique<TestCommandSource>(
base::BindRepeating([](const std::u16string&, Browser* browser) {
auto item = CreateNoOpCommandItem(u"first", 100);
CommandItem::CompositeCommandProvider noop =
base::BindRepeating([](const std::u16string&) {
return CommandSource::CommandResults();
});
item->command = std::make_pair(u"Do stuff", noop);
CommandSource::CommandResults result;
result.push_back(std::move(item));
return result;
})));
auto controller =
CommanderController::CreateWithSourcesForTesting(std::move(sources));
controller->SetUpdateCallback(base::BindRepeating(
&CommanderControllerTest::OnViewModelUpdated, base::Unretained(this)));
// Prime the sources so we can select an item.
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"abracadabra", browser());
}
EXPECT_EQ(source->invocations().size(), 1u);
// Selecting
{
ViewModelCallbackWaiter waiter(this);
controller->OnCommandSelected(0,
received_view_models_.back().result_set_id);
}
ASSERT_EQ(received_view_models_.size(), 2u);
EXPECT_EQ(received_view_models_.back().action,
CommanderViewModel::Action::kPrompt);
// This should go to the provider and not be seen by the source.
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"alakazam", browser());
}
EXPECT_EQ(source->invocations().size(), 1u);
controller->OnCompositeCommandCancelled();
// Composite command was cancelled, so the source should see this one.
{
ViewModelCallbackWaiter waiter(this);
controller->OnTextChanged(u"hocus pocus", browser());
}
EXPECT_EQ(source->invocations().size(), 2u);
EXPECT_EQ(source->invocations().back(), u"hocus pocus");
}
} // namespace commander
| 38.015025 | 80 | 0.701418 | [
"vector",
"model"
] |
f53478df5c510c2245ea33417ed764e44531d970 | 5,354 | cpp | C++ | Framework/Platforms/Source/WhistleSimulator/main.cpp | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 15 | 2015-01-12T10:46:29.000Z | 2022-03-28T05:13:14.000Z | Framework/Platforms/Source/WhistleSimulator/main.cpp | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-01-20T21:07:50.000Z | 2020-01-22T14:00:28.000Z | Framework/Platforms/Source/WhistleSimulator/main.cpp | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2018-02-07T18:18:10.000Z | 2019-10-15T17:01:41.000Z | /*
* File: main.cpp
* Author: schlottb[at]informatik.hu-berlin.de
*
* Created on 2017.05.21
*/
#include <glib.h>
#include <glib-object.h>
#include <PlatformInterface/Platform.h>
//#include <Tools/Debug/Stopwatch.h>
#include <ModuleFramework/ModuleManager.h>
#include <ModuleFramework/ModuleCreator.h>
#include <cstring>
#include "WhistleSimulator.h"
using namespace std;
using namespace naoth;
// kind of a HACK, needed by the logsimulator
extern ModuleManager* getModuleManager(Cognition* c);
extern ModuleManager* getModuleManager(Motion* m);
#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)
void print_info() {
std::cout << "==========================================" << std::endl;
std::cout << "WhistleSimulator compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;
#ifdef REVISION
std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
#endif
#ifdef USER_NAME
std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
#endif
#ifdef BRANCH_PATH
std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
#endif
std::cout << "==========================================\n" << std::endl;
}
int main(int argc, char** argv) {
print_info();
g_type_init();
bool backendMode = false;
bool realTime = false;
unsigned short port = 5401;
unsigned short rate = 0;
unsigned short channels = 0;
unsigned short samples = 1024;
unsigned short overlap = 0;
bool start = false;
char* logpath = getenv("NAOTH_AUDIOFILE");
if (logpath == NULL && argc > 1) {
logpath = argv[argc - 1];
}
// search for parameters
for (int i = 1; i <= argc - 1; i++) {
if (strcmp(argv[i], "-h") == 0) {
std::cout << "syntax: (-h)? (-p <port number>)? <logfile>" << std::endl;
std::cout << "\"--port\" debug port number, range of valid values: [1,65535]" << std::endl;
std::cout << "\"-a\" autoplay the audio file immediately" << std::endl;
std::cout << "\"--rate\" sample rate of raw audio file (8000, 22050, 32000, 44100, 48000)" << std::endl;
std::cout << "\"--channels\" channel count of raw audio file (1, 2, 3, 4)" << std::endl;
std::cout << "\"--samples\" amount of samples to provide audio file" << std::endl;
std::cout << "\"--overlap\" amount of samples overlap" << std::endl;
std::cout << "\"-h\" help" << std::endl;
return (EXIT_SUCCESS);
}
if (strcmp(argv[i], "--port") == 0) {
port = (unsigned short)strtol(argv[++i], 0, 10);
if (port == 0) {
cerr << "invalid port number" << endl;
return (EXIT_FAILURE);
}
}
if (strcmp(argv[i], "--rate") == 0) {
rate = (unsigned short)strtol(argv[++i], 0, 10);
if (!(rate == 8000 || rate == 32000 || rate == 44100 || rate == 22050 || rate == 48000)) {
cerr << "invalid sample rate " << endl;
return (EXIT_FAILURE);
}
}
if (strcmp(argv[i], "--channels") == 0) {
channels = (unsigned short)strtol(argv[++i], 0, 10);
if (channels < 1 || channels > 4) {
cerr << "invalid channel count" << endl;
return (EXIT_FAILURE);
}
}
if (strcmp(argv[i], "--samples") == 0) {
samples = (unsigned short)strtol(argv[++i], 0, 10);
if (samples == 0) {
cerr << "invalid samples count" << endl;
return (EXIT_FAILURE);
}
}
if (strcmp(argv[i], "--overlap") == 0) {
overlap = (unsigned short)strtol(argv[++i], 0, 10);
if (overlap == 0 || overlap > samples) {
cerr << "invalid overlap count" << endl;
return (EXIT_FAILURE);
}
}
if (strcmp(argv[i], "-a") == 0) {
start = true;
}
}
if (logpath == NULL) {
cerr << "You need to give the path to the logfile as argument" << endl;
cerr << "arguments: (-h)? (-p <port number>)? <logfile>" << endl;
cerr << "\"--port\" debug port number, range of valid values: [1,65535]" << std::endl;
cerr << "\"-a\" starts playing the log file immediatly" << std::endl;
cerr << "\"-h\" help" << endl;
return (EXIT_FAILURE);
}
// create the simulator instance
WhistleSimulator sim(logpath, backendMode, realTime, port);
sim.setParams(channels, rate, samples, overlap);
// init the platform
Platform::getInstance().init(&sim);
//init_agent(sim);
Cognition* theCognition = createCognition();
Motion* theMotion = createMotion(); // crashes at inverse kinematics
// ACHTUNG: C-Cast (!)
ModuleManager* theCognitionManager = getModuleManager(theCognition);
if (!theCognitionManager) {
std::cerr << "ERROR: theCognition is not of type ModuleManager" << std::endl;
return (EXIT_FAILURE);
}
// register processes
sim.registerCognition((naoth::Callable*)(theCognition));
sim.registerMotion((naoth::Callable*)(theMotion));
// start the execution
sim.main();
deleteCognition(theCognition);
deleteMotion(theMotion);
return (EXIT_SUCCESS);
}
| 32.646341 | 116 | 0.546321 | [
"object"
] |
f534fe3d70ea4a3f13a51cb78dcb1ea34444ffcf | 635 | cpp | C++ | Arrays/8. PlusOne.cpp | jatinbharadwaj/FAANGPath | 4f42a66331c4478ed95348419ba89b6d7ba27d42 | [
"MIT"
] | 1 | 2021-08-03T10:22:08.000Z | 2021-08-03T10:22:08.000Z | Arrays/8. PlusOne.cpp | jatinbharadwaj/FAANGPath | 4f42a66331c4478ed95348419ba89b6d7ba27d42 | [
"MIT"
] | null | null | null | Arrays/8. PlusOne.cpp | jatinbharadwaj/FAANGPath | 4f42a66331c4478ed95348419ba89b6d7ba27d42 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/plus-one/
class Solution
{
public:
vector<int> plusOne(vector<int> &digits)
{
int n = digits.size();
// vector<int> ans;
int carry = 1, sum = 0;
for (int i = n - 1; i >= 0; --i)
{
sum = carry + digits[i];
// ans.push_back(sum%10);
digits[i] = sum % 10;
carry = sum / 10;
}
if (carry)
{
// ans.push_back(carry);
digits.insert(digits.begin(), carry);
}
// reverse(ans.begin(),ans.end());
// return ans;
return digits;
}
}; | 22.678571 | 49 | 0.440945 | [
"vector"
] |
f5352cbf1d2d97f5f22aac5bf08a6a0637029e60 | 2,197 | cpp | C++ | 208-implement-trie-prefix-tree/implement-trie-prefix-tree.cpp | TJUSsr/leetcodesolution | 8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee | [
"MIT"
] | null | null | null | 208-implement-trie-prefix-tree/implement-trie-prefix-tree.cpp | TJUSsr/leetcodesolution | 8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee | [
"MIT"
] | 2 | 2021-03-31T19:10:41.000Z | 2021-12-13T19:58:15.000Z | 208-implement-trie-prefix-tree/implement-trie-prefix-tree.cpp | TJUSsr/leetcodesolution | 8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee | [
"MIT"
] | null | null | null | // Implement a trie with insert, search, and startsWith methods.
//
// Example:
//
//
// Trie trie = new Trie();
//
// trie.insert("apple");
// trie.search("apple"); // returns true
// trie.search("app"); // returns false
// trie.startsWith("app"); // returns true
// trie.insert("app");
// trie.search("app"); // returns true
//
//
// Note:
//
//
// You may assume that all inputs are consist of lowercase letters a-z.
// All inputs are guaranteed to be non-empty strings.
//
//
static const auto _=[](){
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
struct Dic{
vector<Dic*> dic;
char c;
bool finish;
//Dic():c('#'),finish(false),dic(vector<Dic*>(26,nullptr)){}
Dic(char c_='#', bool finish_=false, vector<Dic*> dic_=vector<Dic*>(26,nullptr)):c(c_),finish(finish_),dic(dic_){}
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root=new Dic();
}
/** Inserts a word into the trie. */
void insert(string word) {
auto temp=root;
for(int i=0;i<word.size();++i){
if(temp->dic[word[i]-'a']==nullptr)
temp->dic[word[i]-'a']=new Dic(word[i],false);
temp=temp->dic[word[i]-'a'];
}
temp->finish=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
auto temp=root;
for(int i=0;i<word.size();++i){
if(temp->dic[word[i]-'a']==nullptr)
return false;
temp=temp->dic[word[i]-'a'];
}
return temp->finish;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
auto temp=root;
for(int i=0;i<prefix.size();++i){
if(temp->dic[prefix[i]-'a']==nullptr)
return false;
temp=temp->dic[prefix[i]-'a'];
}
return true;
}
private:
Dic* root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* bool param_2 = obj.search(word);
* bool param_3 = obj.startsWith(prefix);
*/
| 24.411111 | 118 | 0.54802 | [
"object",
"vector"
] |
f5352f6e1990176221c149eaedd74bd7b52993c5 | 5,813 | cpp | C++ | Samples/SensorVisualization/SensorVisualization/Content/GyroRenderer.cpp | akihiro0105/HoloLens2ForCV | 28762fc79dc1a86e7be4891b295a107e116636d1 | [
"MIT"
] | null | null | null | Samples/SensorVisualization/SensorVisualization/Content/GyroRenderer.cpp | akihiro0105/HoloLens2ForCV | 28762fc79dc1a86e7be4891b295a107e116636d1 | [
"MIT"
] | null | null | null | Samples/SensorVisualization/SensorVisualization/Content/GyroRenderer.cpp | akihiro0105/HoloLens2ForCV | 28762fc79dc1a86e7be4891b295a107e116636d1 | [
"MIT"
] | 1 | 2021-04-20T09:52:51.000Z | 2021-04-20T09:52:51.000Z | #include "pch.h"
#include "GyroRenderer.h"
#include "Common\DirectXHelper.h"
#include <mutex>
using namespace BasicHologram;
using namespace DirectX;
using namespace winrt::Windows::Foundation::Numerics;
using namespace winrt::Windows::UI::Input::Spatial;
void GyroRenderer::GyroUpdateLoop()
{
uint64_t lastSocTick = 0;
uint64_t lastHupTick = 0;
LARGE_INTEGER qpf;
uint64_t lastQpcNow = 0;
// Cache the QueryPerformanceFrequency
QueryPerformanceFrequency(&qpf);
winrt::check_hresult(m_pGyroSensor->OpenStream());
while (!m_fExit)
{
char printString[1000];
IResearchModeSensorFrame* pSensorFrame = nullptr;
ResearchModeSensorTimestamp timeStamp;
size_t BufferOutLength;
IResearchModeGyroFrame* pSensorGyroFrame = nullptr;
const GyroDataStruct* pGyroBuffer = nullptr;
winrt::check_hresult(m_pGyroSensor->GetNextBuffer(&pSensorFrame));
winrt::check_hresult(pSensorFrame->QueryInterface(IID_PPV_ARGS(&pSensorGyroFrame)));
{
std::lock_guard<std::mutex> guard(m_sampleMutex);
winrt::check_hresult(pSensorGyroFrame->GetCalibratedGyro(&m_gyroSample));
}
winrt::check_hresult(pSensorGyroFrame->GetCalibratedGyroSamples(
&pGyroBuffer,
&BufferOutLength));
lastHupTick = 0;
std::string hupTimeDeltas = "";
for (UINT i = 0; i < BufferOutLength; i++)
{
pSensorFrame->GetTimeStamp(&timeStamp);
if (lastHupTick != 0)
{
if (pGyroBuffer[i].VinylHupTicks < lastHupTick)
{
sprintf(printString, "####Gyro BAD HUP ORDERING\n");
OutputDebugStringA(printString);
DebugBreak();
}
sprintf(printString, " %I64d", (pGyroBuffer[i].VinylHupTicks - lastHupTick) / 1000); // Microseconds
hupTimeDeltas = hupTimeDeltas + printString;
}
lastHupTick = pGyroBuffer[i].VinylHupTicks;
}
hupTimeDeltas = hupTimeDeltas + "\n";
//OutputDebugStringA(hupTimeDeltas.c_str());
pSensorFrame->GetTimeStamp(&timeStamp);
LARGE_INTEGER qpcNow;
uint64_t uqpcNow;
QueryPerformanceCounter(&qpcNow);
uqpcNow = qpcNow.QuadPart;
if (lastSocTick != 0)
{
uint64_t timeInMilliseconds =
(1000 *
(uqpcNow - lastQpcNow)) /
qpf.QuadPart;
if (timeStamp.HostTicks < lastSocTick)
{
DebugBreak();
}
sprintf(printString, "####Gyro: % 3.4f % 3.4f % 3.4f %f %I64d %I64d\n",
m_gyroSample.x,
m_gyroSample.y,
m_gyroSample.z,
sqrt(m_gyroSample.x * m_gyroSample.x + m_gyroSample.y * m_gyroSample.y + m_gyroSample.z * m_gyroSample.z),
(((timeStamp.HostTicks - lastSocTick) * 1000) / timeStamp.HostTicksPerSecond), // Milliseconds
timeInMilliseconds);
//OutputDebugStringA(printString);
}
lastSocTick = timeStamp.HostTicks;
lastQpcNow = uqpcNow;
if (pSensorFrame)
{
pSensorFrame->Release();
}
if (pSensorGyroFrame)
{
pSensorGyroFrame->Release();
}
}
winrt::check_hresult(m_pGyroSensor->CloseStream());
}
void GyroRenderer::GetGyroSample(DirectX::XMFLOAT3* pGyroSample)
{
std::lock_guard<std::mutex> guard(m_sampleMutex);
*pGyroSample = m_gyroSample;
}
// This function uses a SpatialPointerPose to position the world-locked hologram
// two meters in front of the user's heading.
void GyroRenderer::PositionHologram(SpatialPointerPose const& pointerPose)
{
}
// Called once per frame. Rotates the cube, and calculates and sets the model matrix
// relative to the position transform indicated by hologramPositionTransform.
void GyroRenderer::Update(DX::StepTimer const& timer)
{
}
void GyroRenderer::SetSensorFrame(IResearchModeSensorFrame* pSensorFrame)
{
}
void GyroRenderer::GyroUpdateThread(GyroRenderer* pGyroRenderer, HANDLE hasData, ResearchModeSensorConsent* pCamAccessConsent)
{
HRESULT hr = S_OK;
if (hasData != nullptr)
{
DWORD waitResult = WaitForSingleObject(hasData, INFINITE);
if (waitResult == WAIT_OBJECT_0)
{
switch (*pCamAccessConsent)
{
case ResearchModeSensorConsent::Allowed:
OutputDebugString(L"Access is granted");
break;
case ResearchModeSensorConsent::DeniedBySystem:
OutputDebugString(L"Access is denied by the system");
hr = E_ACCESSDENIED;
break;
case ResearchModeSensorConsent::DeniedByUser:
OutputDebugString(L"Access is denied by the user");
hr = E_ACCESSDENIED;
break;
case ResearchModeSensorConsent::NotDeclaredByApp:
OutputDebugString(L"Capability is not declared in the app manifest");
hr = E_ACCESSDENIED;
break;
case ResearchModeSensorConsent::UserPromptRequired:
OutputDebugString(L"Capability user prompt required");
hr = E_ACCESSDENIED;
break;
default:
OutputDebugString(L"Access is denied by the system");
hr = E_ACCESSDENIED;
break;
}
}
else
{
hr = E_UNEXPECTED;
}
}
if (FAILED(hr))
{
return;
}
pGyroRenderer->GyroUpdateLoop();
}
void GyroRenderer::UpdateSample()
{
HRESULT hr = S_OK;
}
| 29.358586 | 126 | 0.601411 | [
"model",
"transform"
] |
f53a8fe36ec4c4960a13ea487f72c14356fc2897 | 35,685 | cc | C++ | chromium/ipc/ipc_channel_posix.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | chromium/ipc/ipc_channel_posix.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | chromium/ipc/ipc_channel_posix.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ipc/ipc_channel_posix.h"
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#if defined(OS_OPENBSD)
#include <sys/uio.h>
#endif
#if !defined(OS_NACL_NONSFI)
#include <sys/un.h>
#endif
#include <algorithm>
#include <map>
#include <string>
#include <utility>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/global_descriptors.h"
#include "base/process/process_handle.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/synchronization/lock.h"
#include "build/build_config.h"
#include "ipc/attachment_broker.h"
#include "ipc/ipc_descriptors.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_logging.h"
#include "ipc/ipc_message_attachment_set.h"
#include "ipc/ipc_message_utils.h"
#include "ipc/ipc_platform_file_attachment_posix.h"
#include "ipc/ipc_switches.h"
#include "ipc/unix_domain_socket_util.h"
namespace IPC {
// IPC channels on Windows use named pipes (CreateNamedPipe()) with
// channel ids as the pipe names. Channels on POSIX use sockets as
// pipes These don't quite line up.
//
// When creating a child subprocess we use a socket pair and the parent side of
// the fork arranges it such that the initial control channel ends up on the
// magic file descriptor kPrimaryIPCChannel in the child. Future
// connections (file descriptors) can then be passed via that
// connection via sendmsg().
//
// A POSIX IPC channel can also be set up as a server for a bound UNIX domain
// socket, and will handle multiple connect and disconnect sequences. Currently
// it is limited to one connection at a time.
//------------------------------------------------------------------------------
namespace {
// The PipeMap class works around this quirk related to unit tests:
//
// When running as a server, we install the client socket in a
// specific file descriptor number (@kPrimaryIPCChannel). However, we
// also have to support the case where we are running unittests in the
// same process. (We do not support forking without execing.)
//
// Case 1: normal running
// The IPC server object will install a mapping in PipeMap from the
// name which it was given to the client pipe. When forking the client, the
// GetClientFileDescriptorMapping will ensure that the socket is installed in
// the magic slot (@kPrimaryIPCChannel). The client will search for the
// mapping, but it won't find any since we are in a new process. Thus the
// magic fd number is returned. Once the client connects, the server will
// close its copy of the client socket and remove the mapping.
//
// Case 2: unittests - client and server in the same process
// The IPC server will install a mapping as before. The client will search
// for a mapping and find out. It duplicates the file descriptor and
// connects. Once the client connects, the server will close the original
// copy of the client socket and remove the mapping. Thus, when the client
// object closes, it will close the only remaining copy of the client socket
// in the fd table and the server will see EOF on its side.
//
// TODO(port): a client process cannot connect to multiple IPC channels with
// this scheme.
class PipeMap {
public:
static PipeMap* GetInstance() { return base::Singleton<PipeMap>::get(); }
~PipeMap() {
// Shouldn't have left over pipes.
DCHECK(map_.empty());
}
// Lookup a given channel id. Return -1 if not found.
int Lookup(const std::string& channel_id) {
base::AutoLock locked(lock_);
ChannelToFDMap::const_iterator i = map_.find(channel_id);
if (i == map_.end())
return -1;
return i->second;
}
// Remove the mapping for the given channel id. No error is signaled if the
// channel_id doesn't exist
void Remove(const std::string& channel_id) {
base::AutoLock locked(lock_);
map_.erase(channel_id);
}
// Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
// mapping if one already exists for the given channel_id
void Insert(const std::string& channel_id, int fd) {
base::AutoLock locked(lock_);
DCHECK_NE(-1, fd);
ChannelToFDMap::const_iterator i = map_.find(channel_id);
CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
<< "for '" << channel_id << "' while first "
<< "(fd " << i->second << ") still exists";
map_[channel_id] = fd;
}
private:
base::Lock lock_;
typedef std::map<std::string, int> ChannelToFDMap;
ChannelToFDMap map_;
friend struct base::DefaultSingletonTraits<PipeMap>;
#if defined(OS_ANDROID)
friend void ::IPC::Channel::NotifyProcessForkedForTesting();
#endif
};
//------------------------------------------------------------------------------
bool SocketWriteErrorIsRecoverable() {
#if defined(OS_MACOSX)
// On OS X if sendmsg() is trying to send fds between processes and there
// isn't enough room in the output buffer to send the fd structure over
// atomically then EMSGSIZE is returned.
//
// EMSGSIZE presents a problem since the system APIs can only call us when
// there's room in the socket buffer and not when there is "enough" room.
//
// The current behavior is to return to the event loop when EMSGSIZE is
// received and hopefull service another FD. This is however still
// technically a busy wait since the event loop will call us right back until
// the receiver has read enough data to allow passing the FD over atomically.
return errno == EAGAIN || errno == EMSGSIZE;
#else
return errno == EAGAIN;
#endif // OS_MACOSX
}
} // namespace
#if defined(OS_ANDROID)
// When we fork for simple tests on Android, we can't 'exec', so we need to
// reset these entries manually to get the expected testing behavior.
void Channel::NotifyProcessForkedForTesting() {
PipeMap::GetInstance()->map_.clear();
}
#endif
//------------------------------------------------------------------------------
#if defined(OS_LINUX)
int ChannelPosix::global_pid_ = 0;
#endif // OS_LINUX
ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
Mode mode,
Listener* listener)
: ChannelReader(listener),
mode_(mode),
peer_pid_(base::kNullProcessId),
is_blocked_on_write_(false),
waiting_connect_(true),
message_send_bytes_written_(0),
pipe_name_(channel_handle.name),
in_dtor_(false),
must_unlink_(false) {
if (!CreatePipe(channel_handle)) {
// The pipe may have been closed already.
const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
<< "\" in " << modestr << " mode";
}
}
ChannelPosix::~ChannelPosix() {
in_dtor_ = true;
CleanUp();
Close();
}
bool SocketPair(int* fd1, int* fd2) {
int pipe_fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
PLOG(ERROR) << "socketpair()";
return false;
}
// Set both ends to be non-blocking.
if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
PLOG(ERROR) << "fcntl(O_NONBLOCK)";
if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
PLOG(ERROR) << "close";
if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
PLOG(ERROR) << "close";
return false;
}
*fd1 = pipe_fds[0];
*fd2 = pipe_fds[1];
return true;
}
bool ChannelPosix::CreatePipe(
const IPC::ChannelHandle& channel_handle) {
DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
// Four possible cases:
// 1) It's a channel wrapping a pipe that is given to us.
// 2) It's for a named channel, so we create it.
// 3) It's for a client that we implement ourself. This is used
// in single-process unittesting.
// 4) It's the initial IPC channel:
// 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
// 4b) Server side: create the pipe.
base::ScopedFD local_pipe;
if (channel_handle.socket.fd != -1) {
// Case 1 from comment above.
local_pipe.reset(channel_handle.socket.fd);
} else if (mode_ & MODE_NAMED_FLAG) {
#if defined(OS_NACL_NONSFI)
LOG(FATAL)
<< "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
#else
// Case 2 from comment above.
int local_pipe_fd = -1;
if (mode_ & MODE_SERVER_FLAG) {
if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
&local_pipe_fd)) {
return false;
}
must_unlink_ = true;
} else if (mode_ & MODE_CLIENT_FLAG) {
if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
&local_pipe_fd)) {
return false;
}
} else {
LOG(ERROR) << "Bad mode: " << mode_;
return false;
}
local_pipe.reset(local_pipe_fd);
#endif // !defined(OS_NACL_NONSFI)
} else {
local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
if (mode_ & MODE_CLIENT_FLAG) {
if (local_pipe.is_valid()) {
// Case 3 from comment above.
// We only allow one connection.
local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
PipeMap::GetInstance()->Remove(pipe_name_);
} else {
// Case 4a from comment above.
// Guard against inappropriate reuse of the initial IPC channel. If
// an IPC channel closes and someone attempts to reuse it by name, the
// initial channel must not be recycled here. http://crbug.com/26754.
static bool used_initial_channel = false;
if (used_initial_channel) {
LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
<< pipe_name_;
return false;
}
used_initial_channel = true;
local_pipe.reset(
base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
}
} else if (mode_ & MODE_SERVER_FLAG) {
// Case 4b from comment above.
if (local_pipe.is_valid()) {
LOG(ERROR) << "Server already exists for " << pipe_name_;
// This is a client side pipe registered by other server and
// shouldn't be closed.
ignore_result(local_pipe.release());
return false;
}
base::AutoLock lock(client_pipe_lock_);
int local_pipe_fd = -1, client_pipe_fd = -1;
if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
return false;
local_pipe.reset(local_pipe_fd);
client_pipe_.reset(client_pipe_fd);
PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
} else {
LOG(ERROR) << "Bad mode: " << mode_;
return false;
}
}
if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
#if defined(OS_NACL_NONSFI)
LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
<< "should not be in NAMED or SERVER mode.";
#else
server_listen_pipe_.reset(local_pipe.release());
#endif
} else {
pipe_.reset(local_pipe.release());
}
return true;
}
bool ChannelPosix::Connect() {
if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
return false;
}
bool did_connect = true;
if (server_listen_pipe_.is_valid()) {
#if defined(OS_NACL_NONSFI)
LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
<< "should always be in client mode.";
#else
// Watch the pipe for connections, and turn any connections into
// active sockets.
base::MessageLoopForIO::current()->WatchFileDescriptor(
server_listen_pipe_.get(),
true,
base::MessageLoopForIO::WATCH_READ,
&server_listen_connection_watcher_,
this);
#endif
} else {
did_connect = AcceptConnection();
}
return did_connect;
}
void ChannelPosix::CloseFileDescriptors(Message* msg) {
#if defined(OS_MACOSX)
// There is a bug on OSX which makes it dangerous to close
// a file descriptor while it is in transit. So instead we
// store the file descriptor in a set and send a message to
// the recipient, which is queued AFTER the message that
// sent the FD. The recipient will reply to the message,
// letting us know that it is now safe to close the file
// descriptor. For more information, see:
// http://crbug.com/298276
std::vector<int> to_close;
msg->attachment_set()->ReleaseFDsToClose(&to_close);
for (size_t i = 0; i < to_close.size(); i++) {
fds_to_close_.insert(to_close[i]);
QueueCloseFDMessage(to_close[i], 2);
}
#else
msg->attachment_set()->CommitAllDescriptors();
#endif
}
bool ChannelPosix::ProcessOutgoingMessages() {
if (waiting_connect_)
return true;
if (is_blocked_on_write_)
return true;
if (output_queue_.empty())
return true;
if (!pipe_.is_valid())
return false;
// Write out all the messages we can till the write blocks or there are no
// more outgoing messages.
while (!output_queue_.empty()) {
OutputElement* element = output_queue_.front();
size_t amt_to_write = element->size() - message_send_bytes_written_;
DCHECK_NE(0U, amt_to_write);
const char* out_bytes = reinterpret_cast<const char*>(element->data()) +
message_send_bytes_written_;
struct msghdr msgh = {0};
struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
msgh.msg_iov = &iov;
msgh.msg_iovlen = 1;
char buf[CMSG_SPACE(sizeof(int) *
MessageAttachmentSet::kMaxDescriptorsPerMessage)];
ssize_t bytes_written = 1;
int fd_written = -1;
Message* msg = element->get_message();
if (message_send_bytes_written_ == 0 && msg &&
msg->attachment_set()->num_non_brokerable_attachments()) {
// This is the first chunk of a message which has descriptors to send
struct cmsghdr *cmsg;
const unsigned num_fds =
msg->attachment_set()->num_non_brokerable_attachments();
DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
" IPC. Aborting to maintain sandbox isolation.";
// If you have hit this then something tried to send a file descriptor
// to a directory over an IPC channel. Since IPC channels span
// sandboxes this is very bad: the receiving process can use openat
// with ".." elements in the path in order to reach the real
// filesystem.
}
msgh.msg_control = buf;
msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
cmsg = CMSG_FIRSTHDR(&msgh);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
msg->attachment_set()->PeekDescriptors(
reinterpret_cast<int*>(CMSG_DATA(cmsg)));
msgh.msg_controllen = cmsg->cmsg_len;
// DCHECK_LE above already checks that
// num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
msg->header()->num_fds = static_cast<uint16_t>(num_fds);
}
if (bytes_written == 1) {
fd_written = pipe_.get();
bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
}
if (bytes_written > 0 && msg)
CloseFileDescriptors(msg);
if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
// We can't close the pipe here, because calling OnChannelError
// may destroy this object, and that would be bad if we are
// called from Send(). Instead, we return false and hope the
// caller will close the pipe. If they do not, the pipe will
// still be closed next time OnFileCanReadWithoutBlocking is
// called.
#if defined(OS_MACOSX)
// On OSX writing to a pipe with no listener returns EPERM.
if (errno == EPERM) {
return false;
}
#endif // OS_MACOSX
if (errno == EPIPE) {
return false;
}
PLOG(ERROR) << "pipe error on "
<< fd_written
<< " Currently writing message of size: "
<< element->size();
return false;
}
if (static_cast<size_t>(bytes_written) != amt_to_write) {
if (bytes_written > 0) {
// If write() fails with EAGAIN then bytes_written will be -1.
message_send_bytes_written_ += bytes_written;
}
// Tell libevent to call us back once things are unblocked.
is_blocked_on_write_ = true;
base::MessageLoopForIO::current()->WatchFileDescriptor(
pipe_.get(),
false, // One shot
base::MessageLoopForIO::WATCH_WRITE,
&write_watcher_,
this);
return true;
} else {
message_send_bytes_written_ = 0;
// Message sent OK!
if (msg) {
DVLOG(2) << "sent message @" << msg << " on channel @" << this
<< " with type " << msg->type() << " on fd " << pipe_.get();
} else {
DVLOG(2) << "sent buffer @" << element->data() << " on channel @"
<< this << " on fd " << pipe_.get();
}
delete output_queue_.front();
output_queue_.pop();
}
}
return true;
}
bool ChannelPosix::Send(Message* message) {
DCHECK(!message->HasMojoHandles());
DVLOG(2) << "sending message @" << message << " on channel @" << this
<< " with type " << message->type()
<< " (" << output_queue_.size() << " in queue)";
if (!prelim_queue_.empty()) {
prelim_queue_.push(message);
return true;
}
if (message->HasBrokerableAttachments() &&
peer_pid_ == base::kNullProcessId) {
prelim_queue_.push(message);
return true;
}
return ProcessMessageForDelivery(message);
}
AttachmentBroker* ChannelPosix::GetAttachmentBroker() {
return AttachmentBroker::GetGlobal();
}
int ChannelPosix::GetClientFileDescriptor() const {
base::AutoLock lock(client_pipe_lock_);
return client_pipe_.get();
}
base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
base::AutoLock lock(client_pipe_lock_);
if (!client_pipe_.is_valid())
return base::ScopedFD();
PipeMap::GetInstance()->Remove(pipe_name_);
return std::move(client_pipe_);
}
void ChannelPosix::CloseClientFileDescriptor() {
base::AutoLock lock(client_pipe_lock_);
if (!client_pipe_.is_valid())
return;
PipeMap::GetInstance()->Remove(pipe_name_);
client_pipe_.reset();
}
bool ChannelPosix::AcceptsConnections() const {
return server_listen_pipe_.is_valid();
}
bool ChannelPosix::HasAcceptedConnection() const {
return AcceptsConnections() && pipe_.is_valid();
}
#if !defined(OS_NACL_NONSFI)
// GetPeerEuid is not supported in nacl_helper_nonsfi.
bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
return IPC::GetPeerEuid(pipe_.get(), peer_euid);
}
#endif
void ChannelPosix::ResetToAcceptingConnectionState() {
// Unregister libevent for the unix domain socket and close it.
read_watcher_.StopWatchingFileDescriptor();
write_watcher_.StopWatchingFileDescriptor();
ResetSafely(&pipe_);
while (!output_queue_.empty()) {
OutputElement* element = output_queue_.front();
output_queue_.pop();
if (element->get_message())
CloseFileDescriptors(element->get_message());
delete element;
}
// Close any outstanding, received file descriptors.
ClearInputFDs();
#if defined(OS_MACOSX)
// Clear any outstanding, sent file descriptors.
for (std::set<int>::iterator i = fds_to_close_.begin();
i != fds_to_close_.end();
++i) {
if (IGNORE_EINTR(close(*i)) < 0)
PLOG(ERROR) << "close";
}
fds_to_close_.clear();
#endif
}
// static
bool ChannelPosix::IsNamedServerInitialized(
const std::string& channel_id) {
return base::PathExists(base::FilePath(channel_id));
}
#if defined(OS_LINUX)
// static
void ChannelPosix::SetGlobalPid(int pid) {
global_pid_ = pid;
}
#endif // OS_LINUX
// Called by libevent when we can read from the pipe without blocking.
void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
if (fd == server_listen_pipe_.get()) {
#if defined(OS_NACL_NONSFI)
LOG(FATAL)
<< "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
#else
int new_pipe = 0;
if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
new_pipe < 0) {
Close();
listener()->OnChannelListenError();
}
if (pipe_.is_valid()) {
// We already have a connection. We only handle one at a time.
// close our new descriptor.
if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
DPLOG(ERROR) << "shutdown " << pipe_name_;
if (IGNORE_EINTR(close(new_pipe)) < 0)
DPLOG(ERROR) << "close " << pipe_name_;
listener()->OnChannelDenied();
return;
}
pipe_.reset(new_pipe);
if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
// Verify that the IPC channel peer is running as the same user.
uid_t client_euid;
if (!GetPeerEuid(&client_euid)) {
DLOG(ERROR) << "Unable to query client euid";
ResetToAcceptingConnectionState();
return;
}
if (client_euid != geteuid()) {
DLOG(WARNING) << "Client euid is not authorised";
ResetToAcceptingConnectionState();
return;
}
}
if (!AcceptConnection()) {
NOTREACHED() << "AcceptConnection should not fail on server";
}
waiting_connect_ = false;
#endif
} else if (fd == pipe_) {
if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
waiting_connect_ = false;
}
if (ProcessIncomingMessages() == DISPATCH_ERROR) {
// ClosePipeOnError may delete this object, so we mustn't call
// ProcessOutgoingMessages.
ClosePipeOnError();
return;
}
} else {
NOTREACHED() << "Unknown pipe " << fd;
}
// If we're a server and handshaking, then we want to make sure that we
// only send our handshake message after we've processed the client's.
// This gives us a chance to kill the client if the incoming handshake
// is invalid. This also flushes any closefd messages.
if (!ProcessOutgoingMessages()) {
ClosePipeOnError();
}
}
// Called by libevent when we can write to the pipe without blocking.
void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
DCHECK_EQ(pipe_.get(), fd);
is_blocked_on_write_ = false;
if (!ProcessOutgoingMessages()) {
ClosePipeOnError();
}
}
bool ChannelPosix::ProcessMessageForDelivery(Message* message) {
// Sending a brokerable attachment requires a call to Channel::Send(), so
// Send() may be re-entrant.
if (message->HasBrokerableAttachments()) {
DCHECK(GetAttachmentBroker());
DCHECK(peer_pid_ != base::kNullProcessId);
for (const scoped_refptr<IPC::BrokerableAttachment>& attachment :
message->attachment_set()->GetBrokerableAttachments()) {
if (!GetAttachmentBroker()->SendAttachmentToProcess(attachment,
peer_pid_)) {
delete message;
return false;
}
}
}
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::GetInstance()->OnSendMessage(message, "");
#endif // IPC_MESSAGE_LOG_ENABLED
TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
"ChannelPosix::Send",
message->flags(),
TRACE_EVENT_FLAG_FLOW_OUT);
// |output_queue_| takes ownership of |message|.
OutputElement* element = new OutputElement(message);
output_queue_.push(element);
if (message->HasBrokerableAttachments()) {
// |output_queue_| takes ownership of |ids.buffer|.
Message::SerializedAttachmentIds ids =
message->SerializedIdsOfBrokerableAttachments();
output_queue_.push(new OutputElement(ids.buffer, ids.size));
}
return ProcessOutgoingMessages();
}
bool ChannelPosix::FlushPrelimQueue() {
DCHECK_NE(peer_pid_, base::kNullProcessId);
// Due to the possibly re-entrant nature of ProcessMessageForDelivery(),
// |prelim_queue_| should appear empty.
std::queue<Message*> prelim_queue;
std::swap(prelim_queue_, prelim_queue);
bool processing_error = false;
while (!prelim_queue.empty()) {
Message* m = prelim_queue.front();
processing_error = !ProcessMessageForDelivery(m);
prelim_queue.pop();
if (processing_error)
break;
}
// Delete any unprocessed messages.
while (!prelim_queue.empty()) {
Message* m = prelim_queue.front();
delete m;
prelim_queue.pop();
}
return !processing_error;
}
bool ChannelPosix::AcceptConnection() {
base::MessageLoopForIO::current()->WatchFileDescriptor(
pipe_.get(),
true,
base::MessageLoopForIO::WATCH_READ,
&read_watcher_,
this);
QueueHelloMessage();
if (mode_ & MODE_CLIENT_FLAG) {
// If we are a client we want to send a hello message out immediately.
// In server mode we will send a hello message when we receive one from a
// client.
waiting_connect_ = false;
return ProcessOutgoingMessages();
} else if (mode_ & MODE_SERVER_FLAG) {
waiting_connect_ = true;
return true;
} else {
NOTREACHED();
return false;
}
}
void ChannelPosix::ClosePipeOnError() {
if (HasAcceptedConnection()) {
ResetToAcceptingConnectionState();
listener()->OnChannelError();
} else {
Close();
if (AcceptsConnections()) {
listener()->OnChannelListenError();
} else {
listener()->OnChannelError();
}
}
}
int ChannelPosix::GetHelloMessageProcId() const {
#if defined(OS_NACL_NONSFI)
// In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
// allowed and would cause a SIGSYS crash because of the seccomp sandbox.
return -1;
#else
int pid = base::GetCurrentProcId();
#if defined(OS_LINUX)
// Our process may be in a sandbox with a separate PID namespace.
if (global_pid_) {
pid = global_pid_;
}
#endif // defined(OS_LINUX)
return pid;
#endif // defined(OS_NACL_NONSFI)
}
void ChannelPosix::QueueHelloMessage() {
// Create the Hello message
scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
HELLO_MESSAGE_TYPE,
IPC::Message::PRIORITY_NORMAL));
if (!msg->WriteInt(GetHelloMessageProcId())) {
NOTREACHED() << "Unable to pickle hello message proc id";
}
OutputElement* element = new OutputElement(msg.release());
output_queue_.push(element);
}
ChannelPosix::ReadState ChannelPosix::ReadData(
char* buffer,
int buffer_len,
int* bytes_read) {
if (!pipe_.is_valid())
return READ_FAILED;
struct msghdr msg = {0};
struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char input_cmsg_buf[kMaxReadFDBuffer];
msg.msg_control = input_cmsg_buf;
// recvmsg() returns 0 if the connection has closed or EAGAIN if no data
// is waiting on the pipe.
msg.msg_controllen = sizeof(input_cmsg_buf);
*bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
if (*bytes_read < 0) {
if (errno == EAGAIN) {
return READ_PENDING;
#if defined(OS_MACOSX)
} else if (errno == EPERM) {
// On OSX, reading from a pipe with no listener returns EPERM
// treat this as a special case to prevent spurious error messages
// to the console.
return READ_FAILED;
#endif // OS_MACOSX
} else if (errno == ECONNRESET || errno == EPIPE) {
return READ_FAILED;
} else {
PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
return READ_FAILED;
}
} else if (*bytes_read == 0) {
// The pipe has closed...
return READ_FAILED;
}
DCHECK(*bytes_read);
CloseClientFileDescriptor();
// Read any file descriptors from the message.
if (!ExtractFileDescriptorsFromMsghdr(&msg))
return READ_FAILED;
return READ_SUCCEEDED;
}
bool ChannelPosix::ShouldDispatchInputMessage(Message* msg) {
return true;
}
// On Posix, we need to fix up the file descriptors before the input message
// is dispatched.
//
// This will read from the input_fds_ (READWRITE mode only) and read more
// handles from the FD pipe if necessary.
bool ChannelPosix::GetNonBrokeredAttachments(Message* msg) {
uint16_t header_fds = msg->header()->num_fds;
if (!header_fds)
return true; // Nothing to do.
// The message has file descriptors.
const char* error = NULL;
if (header_fds > input_fds_.size()) {
// The message has been completely received, but we didn't get
// enough file descriptors.
error = "Message needs unreceived descriptors";
}
if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
error = "Message requires an excessive number of descriptors";
if (error) {
LOG(WARNING) << error
<< " channel:" << this
<< " message-type:" << msg->type()
<< " header()->num_fds:" << header_fds;
// Abort the connection.
ClearInputFDs();
return false;
}
// The shenaniganery below with &foo.front() requires input_fds_ to have
// contiguous underlying storage (such as a simple array or a std::vector).
// This is why the header warns not to make input_fds_ a deque<>.
msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
return true;
}
bool ChannelPosix::DidEmptyInputBuffers() {
// When the input data buffer is empty, the fds should be too. If this is
// not the case, we probably have a rogue renderer which is trying to fill
// our descriptor table.
return input_fds_.empty();
}
bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
// Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
// return an invalid non-NULL pointer in the case that controllen == 0.
if (msg->msg_controllen == 0)
return true;
for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
cmsg;
cmsg = CMSG_NXTHDR(msg, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
DCHECK_EQ(0U, payload_len % sizeof(int));
const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
unsigned num_file_descriptors = payload_len / 4;
input_fds_.insert(input_fds_.end(),
file_descriptors,
file_descriptors + num_file_descriptors);
// Check this after adding the FDs so we don't leak them.
if (msg->msg_flags & MSG_CTRUNC) {
ClearInputFDs();
return false;
}
return true;
}
}
// No file descriptors found, but that's OK.
return true;
}
void ChannelPosix::ClearInputFDs() {
for (size_t i = 0; i < input_fds_.size(); ++i) {
if (IGNORE_EINTR(close(input_fds_[i])) < 0)
PLOG(ERROR) << "close ";
}
input_fds_.clear();
}
void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
switch (hops) {
case 1:
case 2: {
// Create the message
scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
CLOSE_FD_MESSAGE_TYPE,
IPC::Message::PRIORITY_NORMAL));
if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
NOTREACHED() << "Unable to pickle close fd.";
}
OutputElement* element = new OutputElement(msg.release());
output_queue_.push(element);
break;
}
default:
NOTREACHED();
break;
}
}
void ChannelPosix::HandleInternalMessage(const Message& msg) {
// The Hello message contains only the process id.
base::PickleIterator iter(msg);
switch (msg.type()) {
default:
NOTREACHED();
break;
case Channel::HELLO_MESSAGE_TYPE:
int pid;
if (!iter.ReadInt(&pid))
NOTREACHED();
peer_pid_ = pid;
listener()->OnChannelConnected(pid);
if (!FlushPrelimQueue())
ClosePipeOnError();
break;
#if defined(OS_MACOSX)
case Channel::CLOSE_FD_MESSAGE_TYPE:
int fd, hops;
if (!iter.ReadInt(&hops))
NOTREACHED();
if (!iter.ReadInt(&fd))
NOTREACHED();
if (hops == 0) {
if (fds_to_close_.erase(fd) > 0) {
if (IGNORE_EINTR(close(fd)) < 0)
PLOG(ERROR) << "close";
} else {
NOTREACHED();
}
} else {
QueueCloseFDMessage(fd, hops);
}
break;
#endif
}
}
base::ProcessId ChannelPosix::GetSenderPID() {
return GetPeerPID();
}
bool ChannelPosix::IsAttachmentBrokerEndpoint() {
return is_attachment_broker_endpoint();
}
void ChannelPosix::Close() {
// Close can be called multiple time, so we need to make sure we're
// idempotent.
ResetToAcceptingConnectionState();
if (must_unlink_) {
unlink(pipe_name_.c_str());
must_unlink_ = false;
}
if (server_listen_pipe_.is_valid()) {
#if defined(OS_NACL_NONSFI)
LOG(FATAL)
<< "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
#else
server_listen_pipe_.reset();
// Unregister libevent for the listening socket and close it.
server_listen_connection_watcher_.StopWatchingFileDescriptor();
#endif
}
CloseClientFileDescriptor();
}
base::ProcessId ChannelPosix::GetPeerPID() const {
return peer_pid_;
}
base::ProcessId ChannelPosix::GetSelfPID() const {
return GetHelloMessageProcId();
}
void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
if (!in_dtor_) {
fd->reset();
return;
}
// crbug.com/449233
// The CL [1] tightened the error check for closing FDs, but it turned
// out that there are existing cases that hit the newly added check.
// ResetSafely() is the workaround for that crash, turning it from
// from PCHECK() to DPCHECK() so that it doesn't crash in production.
// [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
int fd_to_close = fd->release();
if (-1 != fd_to_close) {
int rv = IGNORE_EINTR(close(fd_to_close));
DPCHECK(0 == rv);
}
}
//------------------------------------------------------------------------------
// Channel's methods
// static
scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
Mode mode,
Listener* listener) {
return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
}
// static
std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
// A random name is sufficient validation on posix systems, so we don't need
// an additional shared secret.
std::string id = prefix;
if (!id.empty())
id.append(".");
return id.append(GenerateUniqueRandomChannelID());
}
bool Channel::IsNamedServerInitialized(
const std::string& channel_id) {
return ChannelPosix::IsNamedServerInitialized(channel_id);
}
#if defined(OS_LINUX)
// static
void Channel::SetGlobalPid(int pid) {
ChannelPosix::SetGlobalPid(pid);
}
#endif // OS_LINUX
} // namespace IPC
| 31.551724 | 80 | 0.655429 | [
"object",
"vector"
] |
f53b65fe7aa9c93a37973f1d3a0f825ccf7886ea | 657 | cpp | C++ | main.cpp | rightson/des-barbershop | 0b06f1db85383f6dce97780b45f8392d462a48c3 | [
"MIT"
] | null | null | null | main.cpp | rightson/des-barbershop | 0b06f1db85383f6dce97780b45f8392d462a48c3 | [
"MIT"
] | null | null | null | main.cpp | rightson/des-barbershop | 0b06f1db85383f6dce97780b45f8392d462a48c3 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "barberShopSimulation.h"
#include "arrivalEvent.h"
barberShopSimulation barberShop;
long randnum(int max) {
return rand() % max;
}
void scheduleRandomEvents(bool random = true) {
if (random) srand(time(NULL));
for (unsigned t = 0; t < 20; t += randnum(6)) {
barberShop.scheduleEvent(new arrivalEvent(t));
printf("scheduling random arrival events: %u\n", t);
}
}
int main(int argc, char* argv[]) {
bool random = true;
if (argc == 2) random = atoi(argv[1]);
scheduleRandomEvents(random);
barberShop.run();
return 0;
}
| 21.9 | 60 | 0.64688 | [
"vector"
] |
f540c15250d9b2af3d9437bba327d5bef83faca3 | 6,568 | hpp | C++ | src/oatpp-postgresql/Executor.hpp | freeman-23/oatpp-postgresql | 79a1e0dce44747fcd8c72a7cc068082324a2afd4 | [
"Apache-2.0"
] | null | null | null | src/oatpp-postgresql/Executor.hpp | freeman-23/oatpp-postgresql | 79a1e0dce44747fcd8c72a7cc068082324a2afd4 | [
"Apache-2.0"
] | null | null | null | src/oatpp-postgresql/Executor.hpp | freeman-23/oatpp-postgresql | 79a1e0dce44747fcd8c72a7cc068082324a2afd4 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef oatpp_postgresql_Executor_hpp
#define oatpp_postgresql_Executor_hpp
#include "ConnectionProvider.hpp"
#include "QueryResult.hpp"
#include "mapping/Serializer.hpp"
#include "mapping/ResultMapper.hpp"
#include "Types.hpp"
#include "oatpp/orm/Executor.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include <vector>
namespace oatpp { namespace postgresql {
/**
* Implementation of &id:oatpp::orm::Executor;. for PostgreSQL.
*/
class Executor : public orm::Executor {
private:
struct QueryParameter {
oatpp::String name;
std::vector<std::string> propertyPath;
};
static QueryParameter parseQueryParameter(const oatpp::String& paramName);
private:
class QueryParams {
private:
std::vector<mapping::Serializer::OutputData> outData;
public:
QueryParams(const StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const mapping::Serializer& serializer,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver);
int count;
const char* query;
const char* queryName;
std::vector<Oid> paramOids;
std::vector<const char*> paramValues;
std::vector<int> paramLengths;
std::vector<int> paramFormats;
};
private:
std::shared_ptr<orm::QueryResult> exec(const oatpp::String& statement,
const std::shared_ptr<orm::Connection>& connection,
bool useExecParams = false);
oatpp::String getSchemaVersionTableName(const oatpp::String& suffix);
std::shared_ptr<orm::QueryResult> updateSchemaVersion(v_int64 newVersion,
const oatpp::String& suffix,
const std::shared_ptr<orm::Connection>& connection);
private:
std::unique_ptr<Oid[]> getParamTypes(const StringTemplate& queryTemplate,
const ParamsTypeMap& paramsTypeMap,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver);
std::shared_ptr<QueryResult> prepareQuery(const StringTemplate& queryTemplate,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver,
const std::shared_ptr<postgresql::Connection>& connection);
std::shared_ptr<QueryResult> executeQueryPrepared(const StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver,
const std::shared_ptr<postgresql::Connection>& connection);
std::shared_ptr<QueryResult> executeQuery(const StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver,
const std::shared_ptr<postgresql::Connection>& connection);
std::shared_ptr<QueryResult> expandAndExecuteQuery(const StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver,
const std::shared_ptr<postgresql::Connection>& connection);
private:
std::shared_ptr<provider::Provider<Connection>> m_connectionProvider;
std::shared_ptr<mapping::ResultMapper> m_resultMapper;
mapping::Serializer m_serializer;
public:
Executor(const std::shared_ptr<provider::Provider<Connection>>& connectionProvider);
std::shared_ptr<data::mapping::TypeResolver> createTypeResolver() override;
StringTemplate parseQueryTemplate(const oatpp::String& name,
const oatpp::String& text,
const ParamsTypeMap& paramsTypeMap,
bool prepare) override;
std::shared_ptr<orm::Connection> getConnection() override;
std::shared_ptr<orm::QueryResult> execute(const StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver,
const std::shared_ptr<orm::Connection>& connection) override;
std::shared_ptr<orm::QueryResult> begin(const std::shared_ptr<orm::Connection>& connection = nullptr) override;
std::shared_ptr<orm::QueryResult> commit(const std::shared_ptr<orm::Connection>& connection) override;
std::shared_ptr<orm::QueryResult> rollback(const std::shared_ptr<orm::Connection>& connection) override;
v_int64 getSchemaVersion(const oatpp::String& suffix = nullptr,
const std::shared_ptr<orm::Connection>& connection = nullptr) override;
void migrateSchema(const oatpp::String& script,
v_int64 newVersion,
const oatpp::String& suffix = nullptr,
const std::shared_ptr<orm::Connection>& connection = nullptr) override;
};
}}
#endif // oatpp_postgresql_Executor_hpp
| 41.834395 | 123 | 0.600944 | [
"vector"
] |
f5411b5dc0db1d946737907541a7e9b4df9a913c | 16,845 | cpp | C++ | ext/Log4Qt/src/helpers/factory.cpp | sailfish-os-apps/log4qt-demo-sailfish | 1cf612af479635de18bbdd42421120ac9f7c1ffe | [
"Unlicense"
] | 1 | 2015-11-26T14:03:52.000Z | 2015-11-26T14:03:52.000Z | ext/Log4Qt/src/helpers/factory.cpp | sailfish-os-apps/log4qt-demo-sailfish | 1cf612af479635de18bbdd42421120ac9f7c1ffe | [
"Unlicense"
] | null | null | null | ext/Log4Qt/src/helpers/factory.cpp | sailfish-os-apps/log4qt-demo-sailfish | 1cf612af479635de18bbdd42421120ac9f7c1ffe | [
"Unlicense"
] | 2 | 2017-08-09T13:26:20.000Z | 2019-07-05T08:49:30.000Z | /******************************************************************************
*
* package: Log4Qt
* file: factory.cpp
* created: September 2007
* author: Martin Heinrich
*
*
* Copyright 2007 Martin Heinrich
*
* 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.
*
******************************************************************************/
/******************************************************************************
* Dependencies
******************************************************************************/
#include "helpers/factory.h"
#include <QtCore/QDebug>
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include "consoleappender.h"
#include "colorconsoleappender.h"
#include "dailyrollingfileappender.h"
#include "fileappender.h"
#include "helpers/logerror.h"
#include "helpers/initialisationhelper.h"
#include "helpers/optionconverter.h"
#include "patternlayout.h"
#include "rollingfileappender.h"
#include "signalappender.h"
#include "simplelayout.h"
#include "simpletimelayout.h"
#include "ttcclayout.h"
#if defined(QT_NETWORK_LIB)
#include "telnetappender.h"
#endif
#if defined(QT_SQL_LIB)
#include "databaseappender.h"
#include "databaselayout.h"
#endif //#ifdef QT_SQL_LIB
#include "varia/debugappender.h"
#include "varia/denyallfilter.h"
#include "varia/levelmatchfilter.h"
#include "varia/levelrangefilter.h"
#include "varia/listappender.h"
#include "varia/nullappender.h"
#include "varia/stringmatchfilter.h"
namespace Log4Qt
{
/**************************************************************************
* Declarations
**************************************************************************/
/**************************************************************************
* C helper functions
**************************************************************************/
LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::Factory)
// Appenders
Appender *console_file_appender()
{ return new ConsoleAppender; }
Appender *create_daily_rolling_file_appender()
{ return new DailyRollingFileAppender; }
Appender *create_debug_appender()
{ return new DebugAppender; }
Appender *create_file_appender()
{ return new FileAppender; }
Appender *create_list_appender()
{ return new ListAppender; }
Appender *create_null_appender()
{ return new NullAppender; }
Appender *create_rolling_file_appender()
{ return new RollingFileAppender; }
Appender *create_signal_appender()
{ return new SignalAppender; }
Appender *create_color_console_appender()
{ return new ColorConsoleAppender;}
#if defined(QT_SQL_LIB)
Appender *create_database_appender()
{ return new DatabaseAppender; }
#endif //#if defined(QT_SQL_LIB)
#if defined(QT_NETWORK_LIB)
Appender *create_telnet_appender()
{ return new TelnetAppender; }
#endif
// Filters
Filter *create_deny_all_filter()
{ return new DenyAllFilter; }
Filter *create_level_match_filter()
{ return new LevelMatchFilter; }
Filter *create_level_range_filter()
{ return new LevelRangeFilter; }
Filter *create_string_match_filter()
{ return new StringMatchFilter; }
// Layouts
Layout *create_pattern_layout()
{ return new PatternLayout; }
Layout *create_simple_layout()
{ return new SimpleLayout; }
Layout *create_simple_time_layout()
{ return new SimpleTimeLayout; }
#if defined(QT_SQL_LIB)
Layout *create_database_layout()
{ return new DatabaseLayout; }
#endif //#if defined(QT_SQL_LIB)
Layout *create_ttcc_layout()
{ return new TTCCLayout; }
/**************************************************************************
* Class implementation: Factory
**************************************************************************/
Factory::Factory() :
mObjectGuard(),
mAppenderRegistry(),
mFilterRegistry(),
mLayoutRegistry()
{
registerDefaultAppenders();
registerDefaultFilters();
registerDefaultLayouts();
}
LOG4QT_IMPLEMENT_INSTANCE(Factory)
Appender *Factory::doCreateAppender(const QString &rAppenderClassName)
{
QMutexLocker locker(&mObjectGuard);
if (!mAppenderRegistry.contains(rAppenderClassName))
{
logger()->warn("Request for the creation of Appender with class '%1', which is not registered", rAppenderClassName);
return 0;
}
return mAppenderRegistry.value(rAppenderClassName)();
}
Filter *Factory::doCreateFilter(const QString &rFilterClassName)
{
QMutexLocker locker(&mObjectGuard);
if (!mFilterRegistry.contains(rFilterClassName))
{
logger()->warn("Request for the creation of Filter with class '%1', which is not registered", rFilterClassName);
return 0;
}
return mFilterRegistry.value(rFilterClassName)();
}
Layout *Factory::doCreateLayout(const QString &rLayoutClassName)
{
QMutexLocker locker(&mObjectGuard);
if (!mLayoutRegistry.contains(rLayoutClassName))
{
logger()->warn("Request for the creation of Layout with class '%1', which is not registered", rLayoutClassName);
return 0;
}
return mLayoutRegistry.value(rLayoutClassName)();
}
void Factory::doRegisterAppender(const QString &rAppenderClassName,
AppenderFactoryFunc pAppenderFactoryFunc)
{
QMutexLocker locker(&mObjectGuard);
if(rAppenderClassName.isEmpty())
{
logger()->warn("Registering Appender factory function with empty class name");
return;
}
mAppenderRegistry.insert(rAppenderClassName, pAppenderFactoryFunc);
}
void Factory::doRegisterFilter(const QString &rFilterClassName,
FilterFactoryFunc pFilterFactoryFunc)
{
QMutexLocker locker(&mObjectGuard);
if(rFilterClassName.isEmpty())
{
logger()->warn("Registering Filter factory function with empty class name");
return;
}
mFilterRegistry.insert(rFilterClassName, pFilterFactoryFunc);
}
void Factory::doRegisterLayout(const QString &rLayoutClassName,
LayoutFactoryFunc pLayoutFactoryFunc)
{
QMutexLocker locker(&mObjectGuard);
if(rLayoutClassName.isEmpty())
{
logger()->warn("Registering Layout factory function with empty class name");
return;
}
mLayoutRegistry.insert(rLayoutClassName, pLayoutFactoryFunc);
}
void Factory::doSetObjectProperty(QObject *pObject,
const QString &rProperty,
const QString &rValue)
{
// - Validate property
// - Get correct property name from meta object
// - Find specific property setter
// - If no specfifc propery setter can be found,
// find general property setter
// - Call property setter
QMetaProperty meta_property;
if (!validateObjectProperty(meta_property, rProperty, pObject))
return;
QString property = QLatin1String(meta_property.name());
QString type = QLatin1String(meta_property.typeName());
logger()->debug("Setting property '%1' on object of class '%2' to value '%3'",
property,
QLatin1String(pObject->metaObject()->className()),
rValue);
QVariant value;
bool ok = true;
if (type == QLatin1String("bool"))
value = OptionConverter::toBoolean(rValue, &ok);
else if (type == QLatin1String("int"))
value = OptionConverter::toInt(rValue, &ok);
else if (type == QLatin1String("Log4Qt::Level"))
value = QVariant::fromValue(OptionConverter::toLevel(rValue, &ok));
else if (type == QLatin1String("QString"))
value = rValue;
else
{
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Cannot convert to type '%1' for property '%2' on object of class '%3'"),
CONFIGURATOR_UNKNOWN_TYPE_ERROR,
"Log4Qt::Factory");
e << type
<< property
<< QString::fromLatin1(pObject->metaObject()->className());
logger()->error(e);
return;
}
if (!ok)
return;
// Everything is checked and the type is the one of the property.
// Write should never return false
if (!meta_property.write(pObject, value))
logger()->warn("Unxpected error result from QMetaProperty.write()");
}
void Factory::doUnregisterAppender(const QString &rAppenderClassName)
{
QMutexLocker locker(&mObjectGuard);
if (!mAppenderRegistry.contains(rAppenderClassName))
{
logger()->warn("Request to unregister not registered Appender factory function for class '%1'", rAppenderClassName);
return;
}
mAppenderRegistry.remove(rAppenderClassName);
}
void Factory::doUnregisterFilter(const QString &rFilterClassName)
{
QMutexLocker locker(&mObjectGuard);
if (!mFilterRegistry.contains(rFilterClassName))
{
logger()->warn("Request to unregister not registered Filter factory function for class '%1'", rFilterClassName);
return;
}
mFilterRegistry.remove(rFilterClassName);
}
void Factory::doUnregisterLayout(const QString &rLayoutClassName)
{
QMutexLocker locker(&mObjectGuard);
if (!mLayoutRegistry.contains(rLayoutClassName))
{
logger()->warn("Request to unregister not registered Layout factory function for class '%1'", rLayoutClassName);
return;
}
mLayoutRegistry.remove(rLayoutClassName);
}
void Factory::registerDefaultAppenders()
{
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.ConsoleAppender"), console_file_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::ConsoleAppender"), console_file_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.DailyRollingFileAppender"), create_daily_rolling_file_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::DailyRollingFileAppender"), create_daily_rolling_file_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.varia.DebugAppender"), create_debug_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::DebugAppender"), create_debug_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.FileAppender"), create_file_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::FileAppender"), create_file_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.varia.ListAppender"), create_list_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::ListAppender"), create_list_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.varia.NullAppender"), create_null_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::NullAppender"), create_null_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.RollingFileAppender"), create_rolling_file_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::RollingFileAppender"), create_rolling_file_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.SignalAppender"), create_signal_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::SignalAppender"), create_signal_appender);
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.ColorConsoleAppender"), create_color_console_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::ColorConsoleAppender"), create_color_console_appender);
#if defined(QT_SQL_LIB)
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.DatabaseAppender"), create_database_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::DatabaseAppender"), create_database_appender);
#endif //#ifdef QT_SQL_LIB
#if defined(QT_NETWORK_LIB)
mAppenderRegistry.insert(QLatin1String("org.apache.log4j.TelnetAppender"), create_telnet_appender);
mAppenderRegistry.insert(QLatin1String("Log4Qt::TelnetAppender"), create_telnet_appender);
#endif
}
void Factory::registerDefaultFilters()
{
mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.DenyAllFilter"), create_deny_all_filter);
mFilterRegistry.insert(QLatin1String("Log4Qt::DenyAllFilter"), create_deny_all_filter);
mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.LevelMatchFilter"), create_level_match_filter);
mFilterRegistry.insert(QLatin1String("Log4Qt::LevelMatchFilter"), create_level_match_filter);
mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.LevelRangeFilter"), create_level_range_filter);
mFilterRegistry.insert(QLatin1String("Log4Qt::LevelRangeFilter"), create_level_range_filter);
mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.StringMatchFilter"), create_string_match_filter);
mFilterRegistry.insert(QLatin1String("Log4Qt::StringMatchFilter"), create_string_match_filter);
}
void Factory::registerDefaultLayouts()
{
mLayoutRegistry.insert(QLatin1String("org.apache.log4j.PatternLayout"), create_pattern_layout);
mLayoutRegistry.insert(QLatin1String("Log4Qt::PatternLayout"), create_pattern_layout);
mLayoutRegistry.insert(QLatin1String("org.apache.log4j.SimpleLayout"), create_simple_layout);
mLayoutRegistry.insert(QLatin1String("Log4Qt::SimpleLayout"), create_simple_layout);
mLayoutRegistry.insert(QLatin1String("org.apache.log4j.TTCCLayout"), create_ttcc_layout);
mLayoutRegistry.insert(QLatin1String("Log4Qt::TTCCLayout"), create_ttcc_layout);
mLayoutRegistry.insert(QLatin1String("org.apache.log4j.SimpleTimeLayout"), create_simple_time_layout);
mLayoutRegistry.insert(QLatin1String("Log4Qt::SimpleTimeLayout"), create_simple_time_layout);
#if defined(QT_SQL_LIB)
mLayoutRegistry.insert(QLatin1String("org.apache.log4j.DatabaseLayout"), create_database_layout);
mLayoutRegistry.insert(QLatin1String("Log4Qt::DatabaseLayout"), create_database_layout);
#endif //#ifdef (QT_SQL_LIB)
}
bool Factory::validateObjectProperty(QMetaProperty &rMetaProperty,
const QString &rProperty,
QObject *pObject)
{
// Validate:
// - No null object pointer
// - No empty property name
// - Property exists on the object (QT or Java name)
// - Property is readable
// - Property is writable
const char *p_context = "Log4Qt::Factory";
LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to set property value on object"),
CONFIGURATOR_PROPERTY_ERROR,
p_context);
if (!pObject)
{
LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Invalid null object pointer"),
0,
p_context);
e.addCausingError(ce);
logger()->error(e);
return false;
}
if (rProperty.isEmpty())
{
LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Invalid empty property name"),
0,
p_context);
e.addCausingError(ce);
logger()->error(e);
return false;
}
const QMetaObject *p_meta_object = pObject->metaObject();
QString property = rProperty;
int i = p_meta_object->indexOfProperty(property.toLatin1());
if (i < 0)
{
// Try name with lower case first character. Java properties names
// start upper case
property[0] = property[0].toLower();
i = p_meta_object->indexOfProperty(property.toLatin1());
if (i < 0)
{
LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Property '%1' does not exist in class '%2'"),
0,
p_context);
ce << property
<< QString::fromLatin1(pObject->metaObject()->className());
e.addCausingError(ce);
logger()->error(e);
return false;
}
}
rMetaProperty = p_meta_object->property(i);
if (!rMetaProperty.isWritable())
{
LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Property '%1' is not writable in class '%2'"),
0,
p_context);
ce << property
<< QString::fromLatin1(pObject->metaObject()->className());
e.addCausingError(ce);
logger()->error(e);
return false;
}
return true;
}
/**************************************************************************
* Implementation: Operators, Helper
**************************************************************************/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug,
const Factory &rFactory)
{
debug.nospace() << "Factory("
<< "appenderfactories:" << rFactory.registeredAppenders()
<< "filterfactories:" << rFactory.registeredFilters()
<< "layoutfactories:" << rFactory.registeredLayouts()
<< ")";
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
} // namespace Log4Qt
| 32.645349 | 124 | 0.679905 | [
"object"
] |
f542b7a4c41fd96ceb9c5b9be8fe28b605c64974 | 250,338 | cpp | C++ | RoomTest/Build6/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_17Table.cpp | spacebirdrise/Holo-History-holo_dev | 41d3219d89e4c04570f87e42d6f7a7e583a3f872 | [
"MIT"
] | null | null | null | RoomTest/Build6/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_17Table.cpp | spacebirdrise/Holo-History-holo_dev | 41d3219d89e4c04570f87e42d6f7a7e583a3f872 | [
"MIT"
] | null | null | null | RoomTest/Build6/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_17Table.cpp | spacebirdrise/Holo-History-holo_dev | 41d3219d89e4c04570f87e42d6f7a7e583a3f872 | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// Mono.Security.X509.X509Certificate
struct X509Certificate_t592E2574612B2C554C7B707754AEC3B66A4B476B;
// System.AsyncCallback
struct AsyncCallback_t3F3DA3BEDAEE81DD1D24125DF8EB30E85EE14DA4;
// System.Byte[]
struct ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821;
// System.Char[]
struct CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2;
// System.Collections.ArrayList
struct ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4;
// System.Collections.Generic.Dictionary`2<System.Int32,System.String>
struct Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C;
// System.Collections.Generic.List`1<System.Security.Cryptography.X509Certificates.X509CertificateImpl>
struct List_1_t37E424CC2C8529EE0DCF9C6ACACB7F4CA9534033;
// System.Collections.Hashtable
struct Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9;
// System.Collections.ICollection
struct ICollection_tA3BAB2482E28132A7CA9E0E21393027353C28B54;
// System.Collections.IDictionary
struct IDictionary_t1BD5C1546718A374EA8122FBD6C6EE45331E8CE7;
// System.Collections.IEnumerator
struct IEnumerator_t8789118187258CC88B77AFAC6315B5AF87D3E18A;
// System.ComponentModel.Component
struct Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473;
// System.ComponentModel.EventHandlerList
struct EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4;
// System.ComponentModel.EventHandlerList/ListEntry
struct ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D;
// System.ComponentModel.ISite
struct ISite_t6804B48BC23ABB5F4141903F878589BCEF6097A2;
// System.ComponentModel.PropertyChangedEventArgs
struct PropertyChangedEventArgs_t90CF85B82F87D594F73F03364494C77592B11F46;
// System.ComponentModel.TypeConverter/StandardValuesCollection
struct StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3;
// System.Delegate
struct Delegate_t;
// System.DelegateData
struct DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE;
// System.Delegate[]
struct DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86;
// System.Diagnostics.StackTrace[]
struct StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196;
// System.IAsyncResult
struct IAsyncResult_t8E194308510B375B42432981AE5E7488C458D598;
// System.IO.Compression.DeflateStream
struct DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE;
// System.IO.Compression.DeflateStreamNative
struct DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB;
// System.IO.Compression.DeflateStreamNative/SafeDeflateStreamHandle
struct SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959;
// System.IO.Compression.DeflateStreamNative/UnmanagedReadOrWrite
struct UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0;
// System.IO.Stream
struct Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7;
// System.IO.Stream/ReadWriteTask
struct ReadWriteTask_tFA17EEE8BC5C4C83EAEFCC3662A30DE351ABAA80;
// System.Int32[]
struct Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83;
// System.IntPtr[]
struct IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD;
// System.Net.CredentialCache
struct CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D;
// System.Net.ICredentials[]
struct ICredentialsU5BU5D_t9392DAC5D43E13A7142056D21759B362C7C29864;
// System.Reflection.MethodInfo
struct MethodInfo_t;
// System.Runtime.Serialization.SafeSerializationManager
struct SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770;
// System.Security.Cryptography.AsnEncodedData
struct AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65;
// System.Security.Cryptography.AsymmetricAlgorithm
struct AsymmetricAlgorithm_t9F811260245370BD8786A849DBF9F8054F97F4CB;
// System.Security.Cryptography.Oid
struct Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137;
// System.Security.Cryptography.OidCollection
struct OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E;
// System.Security.Cryptography.X509Certificates.PublicKey
struct PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620;
// System.Security.Cryptography.X509Certificates.X500DistinguishedName
struct X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199;
// System.Security.Cryptography.X509Certificates.X509Certificate2Collection
struct X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D;
// System.Security.Cryptography.X509Certificates.X509CertificateCollection
struct X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833;
// System.Security.Cryptography.X509Certificates.X509CertificateImpl
struct X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313;
// System.Security.Cryptography.X509Certificates.X509CertificateImplCollection
struct X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242;
// System.Security.Cryptography.X509Certificates.X509ChainElementCollection
struct X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4;
// System.Security.Cryptography.X509Certificates.X509ChainImpl
struct X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67;
// System.Security.Cryptography.X509Certificates.X509ChainPolicy
struct X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD;
// System.Security.Cryptography.X509Certificates.X509ChainStatus[]
struct X509ChainStatusU5BU5D_tA8CCC33D50C4BCF6F657063CD1DACCC3B9A7BFBB;
// System.Security.Cryptography.X509Certificates.X509ExtensionCollection
struct X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F;
// System.String
struct String_t;
// System.String[]
struct StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E;
// System.Threading.SemaphoreSlim
struct SemaphoreSlim_t2E2888D1C0C8FAB80823C76F1602E4434B8FA048;
// System.Type
struct Type_t;
// System.Void
struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017;
struct Delegate_t_marshaled_com;
struct Delegate_t_marshaled_pinvoke;
struct Exception_t_marshaled_com;
struct Exception_t_marshaled_pinvoke;
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
#ifndef ATTRIBUTE_TF048C13FB3C8CFCC53F82290E4A3F621089F9A74_H
#define ATTRIBUTE_TF048C13FB3C8CFCC53F82290E4A3F621089F9A74_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Attribute
struct Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ATTRIBUTE_TF048C13FB3C8CFCC53F82290E4A3F621089F9A74_H
#ifndef COLLECTIONBASE_TF5D4583FF325726066A9803839A04E9C0084ED01_H
#define COLLECTIONBASE_TF5D4583FF325726066A9803839A04E9C0084ED01_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.CollectionBase
struct CollectionBase_tF5D4583FF325726066A9803839A04E9C0084ED01 : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Collections.CollectionBase::list
ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * ___list_0;
public:
inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(CollectionBase_tF5D4583FF325726066A9803839A04E9C0084ED01, ___list_0)); }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * get_list_0() const { return ___list_0; }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 ** get_address_of_list_0() { return &___list_0; }
inline void set_list_0(ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * value)
{
___list_0 = value;
Il2CppCodeGenWriteBarrier((&___list_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COLLECTIONBASE_TF5D4583FF325726066A9803839A04E9C0084ED01_H
#ifndef EVENTHANDLERLIST_TFE9EF79E85419EBB2C206CF475E29A9960699BE4_H
#define EVENTHANDLERLIST_TFE9EF79E85419EBB2C206CF475E29A9960699BE4_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EventHandlerList
struct EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4 : public RuntimeObject
{
public:
// System.ComponentModel.EventHandlerList_ListEntry System.ComponentModel.EventHandlerList::head
ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D * ___head_0;
// System.ComponentModel.Component System.ComponentModel.EventHandlerList::parent
Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473 * ___parent_1;
public:
inline static int32_t get_offset_of_head_0() { return static_cast<int32_t>(offsetof(EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4, ___head_0)); }
inline ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D * get_head_0() const { return ___head_0; }
inline ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D ** get_address_of_head_0() { return &___head_0; }
inline void set_head_0(ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D * value)
{
___head_0 = value;
Il2CppCodeGenWriteBarrier((&___head_0), value);
}
inline static int32_t get_offset_of_parent_1() { return static_cast<int32_t>(offsetof(EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4, ___parent_1)); }
inline Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473 * get_parent_1() const { return ___parent_1; }
inline Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473 ** get_address_of_parent_1() { return &___parent_1; }
inline void set_parent_1(Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473 * value)
{
___parent_1 = value;
Il2CppCodeGenWriteBarrier((&___parent_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EVENTHANDLERLIST_TFE9EF79E85419EBB2C206CF475E29A9960699BE4_H
#ifndef LISTENTRY_T32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D_H
#define LISTENTRY_T32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EventHandlerList_ListEntry
struct ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D : public RuntimeObject
{
public:
// System.ComponentModel.EventHandlerList_ListEntry System.ComponentModel.EventHandlerList_ListEntry::next
ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D * ___next_0;
// System.Object System.ComponentModel.EventHandlerList_ListEntry::key
RuntimeObject * ___key_1;
// System.Delegate System.ComponentModel.EventHandlerList_ListEntry::handler
Delegate_t * ___handler_2;
public:
inline static int32_t get_offset_of_next_0() { return static_cast<int32_t>(offsetof(ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D, ___next_0)); }
inline ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D * get_next_0() const { return ___next_0; }
inline ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D ** get_address_of_next_0() { return &___next_0; }
inline void set_next_0(ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D * value)
{
___next_0 = value;
Il2CppCodeGenWriteBarrier((&___next_0), value);
}
inline static int32_t get_offset_of_key_1() { return static_cast<int32_t>(offsetof(ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D, ___key_1)); }
inline RuntimeObject * get_key_1() const { return ___key_1; }
inline RuntimeObject ** get_address_of_key_1() { return &___key_1; }
inline void set_key_1(RuntimeObject * value)
{
___key_1 = value;
Il2CppCodeGenWriteBarrier((&___key_1), value);
}
inline static int32_t get_offset_of_handler_2() { return static_cast<int32_t>(offsetof(ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D, ___handler_2)); }
inline Delegate_t * get_handler_2() const { return ___handler_2; }
inline Delegate_t ** get_address_of_handler_2() { return &___handler_2; }
inline void set_handler_2(Delegate_t * value)
{
___handler_2 = value;
Il2CppCodeGenWriteBarrier((&___handler_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LISTENTRY_T32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D_H
#ifndef STANDARDVALUESCOLLECTION_T929677712574EF02F5C4CF4C38E070841C20BDA3_H
#define STANDARDVALUESCOLLECTION_T929677712574EF02F5C4CF4C38E070841C20BDA3_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverter_StandardValuesCollection
struct StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 : public RuntimeObject
{
public:
// System.Collections.ICollection System.ComponentModel.TypeConverter_StandardValuesCollection::values
RuntimeObject* ___values_0;
// System.Array System.ComponentModel.TypeConverter_StandardValuesCollection::valueArray
RuntimeArray * ___valueArray_1;
public:
inline static int32_t get_offset_of_values_0() { return static_cast<int32_t>(offsetof(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3, ___values_0)); }
inline RuntimeObject* get_values_0() const { return ___values_0; }
inline RuntimeObject** get_address_of_values_0() { return &___values_0; }
inline void set_values_0(RuntimeObject* value)
{
___values_0 = value;
Il2CppCodeGenWriteBarrier((&___values_0), value);
}
inline static int32_t get_offset_of_valueArray_1() { return static_cast<int32_t>(offsetof(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3, ___valueArray_1)); }
inline RuntimeArray * get_valueArray_1() const { return ___valueArray_1; }
inline RuntimeArray ** get_address_of_valueArray_1() { return &___valueArray_1; }
inline void set_valueArray_1(RuntimeArray * value)
{
___valueArray_1 = value;
Il2CppCodeGenWriteBarrier((&___valueArray_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STANDARDVALUESCOLLECTION_T929677712574EF02F5C4CF4C38E070841C20BDA3_H
#ifndef EVENTARGS_T8E6CA180BE0E56674C6407011A94BAF7C757352E_H
#define EVENTARGS_T8E6CA180BE0E56674C6407011A94BAF7C757352E_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.EventArgs
struct EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E : public RuntimeObject
{
public:
public:
};
struct EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E_StaticFields
{
public:
// System.EventArgs System.EventArgs::Empty
EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E * ___Empty_0;
public:
inline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E_StaticFields, ___Empty_0)); }
inline EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E * get_Empty_0() const { return ___Empty_0; }
inline EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E ** get_address_of_Empty_0() { return &___Empty_0; }
inline void set_Empty_0(EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E * value)
{
___Empty_0 = value;
Il2CppCodeGenWriteBarrier((&___Empty_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EVENTARGS_T8E6CA180BE0E56674C6407011A94BAF7C757352E_H
#ifndef EXCEPTION_T_H
#define EXCEPTION_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Exception
struct Exception_t : public RuntimeObject
{
public:
// System.String System.Exception::_className
String_t* ____className_1;
// System.String System.Exception::_message
String_t* ____message_2;
// System.Collections.IDictionary System.Exception::_data
RuntimeObject* ____data_3;
// System.Exception System.Exception::_innerException
Exception_t * ____innerException_4;
// System.String System.Exception::_helpURL
String_t* ____helpURL_5;
// System.Object System.Exception::_stackTrace
RuntimeObject * ____stackTrace_6;
// System.String System.Exception::_stackTraceString
String_t* ____stackTraceString_7;
// System.String System.Exception::_remoteStackTraceString
String_t* ____remoteStackTraceString_8;
// System.Int32 System.Exception::_remoteStackIndex
int32_t ____remoteStackIndex_9;
// System.Object System.Exception::_dynamicMethods
RuntimeObject * ____dynamicMethods_10;
// System.Int32 System.Exception::_HResult
int32_t ____HResult_11;
// System.String System.Exception::_source
String_t* ____source_12;
// System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager
SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13;
// System.Diagnostics.StackTrace[] System.Exception::captured_traces
StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14;
// System.IntPtr[] System.Exception::native_trace_ips
IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* ___native_trace_ips_15;
public:
inline static int32_t get_offset_of__className_1() { return static_cast<int32_t>(offsetof(Exception_t, ____className_1)); }
inline String_t* get__className_1() const { return ____className_1; }
inline String_t** get_address_of__className_1() { return &____className_1; }
inline void set__className_1(String_t* value)
{
____className_1 = value;
Il2CppCodeGenWriteBarrier((&____className_1), value);
}
inline static int32_t get_offset_of__message_2() { return static_cast<int32_t>(offsetof(Exception_t, ____message_2)); }
inline String_t* get__message_2() const { return ____message_2; }
inline String_t** get_address_of__message_2() { return &____message_2; }
inline void set__message_2(String_t* value)
{
____message_2 = value;
Il2CppCodeGenWriteBarrier((&____message_2), value);
}
inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(Exception_t, ____data_3)); }
inline RuntimeObject* get__data_3() const { return ____data_3; }
inline RuntimeObject** get_address_of__data_3() { return &____data_3; }
inline void set__data_3(RuntimeObject* value)
{
____data_3 = value;
Il2CppCodeGenWriteBarrier((&____data_3), value);
}
inline static int32_t get_offset_of__innerException_4() { return static_cast<int32_t>(offsetof(Exception_t, ____innerException_4)); }
inline Exception_t * get__innerException_4() const { return ____innerException_4; }
inline Exception_t ** get_address_of__innerException_4() { return &____innerException_4; }
inline void set__innerException_4(Exception_t * value)
{
____innerException_4 = value;
Il2CppCodeGenWriteBarrier((&____innerException_4), value);
}
inline static int32_t get_offset_of__helpURL_5() { return static_cast<int32_t>(offsetof(Exception_t, ____helpURL_5)); }
inline String_t* get__helpURL_5() const { return ____helpURL_5; }
inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; }
inline void set__helpURL_5(String_t* value)
{
____helpURL_5 = value;
Il2CppCodeGenWriteBarrier((&____helpURL_5), value);
}
inline static int32_t get_offset_of__stackTrace_6() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTrace_6)); }
inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; }
inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; }
inline void set__stackTrace_6(RuntimeObject * value)
{
____stackTrace_6 = value;
Il2CppCodeGenWriteBarrier((&____stackTrace_6), value);
}
inline static int32_t get_offset_of__stackTraceString_7() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTraceString_7)); }
inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; }
inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; }
inline void set__stackTraceString_7(String_t* value)
{
____stackTraceString_7 = value;
Il2CppCodeGenWriteBarrier((&____stackTraceString_7), value);
}
inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_8)); }
inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; }
inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; }
inline void set__remoteStackTraceString_8(String_t* value)
{
____remoteStackTraceString_8 = value;
Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_8), value);
}
inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackIndex_9)); }
inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; }
inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; }
inline void set__remoteStackIndex_9(int32_t value)
{
____remoteStackIndex_9 = value;
}
inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast<int32_t>(offsetof(Exception_t, ____dynamicMethods_10)); }
inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; }
inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; }
inline void set__dynamicMethods_10(RuntimeObject * value)
{
____dynamicMethods_10 = value;
Il2CppCodeGenWriteBarrier((&____dynamicMethods_10), value);
}
inline static int32_t get_offset_of__HResult_11() { return static_cast<int32_t>(offsetof(Exception_t, ____HResult_11)); }
inline int32_t get__HResult_11() const { return ____HResult_11; }
inline int32_t* get_address_of__HResult_11() { return &____HResult_11; }
inline void set__HResult_11(int32_t value)
{
____HResult_11 = value;
}
inline static int32_t get_offset_of__source_12() { return static_cast<int32_t>(offsetof(Exception_t, ____source_12)); }
inline String_t* get__source_12() const { return ____source_12; }
inline String_t** get_address_of__source_12() { return &____source_12; }
inline void set__source_12(String_t* value)
{
____source_12 = value;
Il2CppCodeGenWriteBarrier((&____source_12), value);
}
inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast<int32_t>(offsetof(Exception_t, ____safeSerializationManager_13)); }
inline SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; }
inline SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; }
inline void set__safeSerializationManager_13(SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * value)
{
____safeSerializationManager_13 = value;
Il2CppCodeGenWriteBarrier((&____safeSerializationManager_13), value);
}
inline static int32_t get_offset_of_captured_traces_14() { return static_cast<int32_t>(offsetof(Exception_t, ___captured_traces_14)); }
inline StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* get_captured_traces_14() const { return ___captured_traces_14; }
inline StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196** get_address_of_captured_traces_14() { return &___captured_traces_14; }
inline void set_captured_traces_14(StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* value)
{
___captured_traces_14 = value;
Il2CppCodeGenWriteBarrier((&___captured_traces_14), value);
}
inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast<int32_t>(offsetof(Exception_t, ___native_trace_ips_15)); }
inline IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* get_native_trace_ips_15() const { return ___native_trace_ips_15; }
inline IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; }
inline void set_native_trace_ips_15(IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* value)
{
___native_trace_ips_15 = value;
Il2CppCodeGenWriteBarrier((&___native_trace_ips_15), value);
}
};
struct Exception_t_StaticFields
{
public:
// System.Object System.Exception::s_EDILock
RuntimeObject * ___s_EDILock_0;
public:
inline static int32_t get_offset_of_s_EDILock_0() { return static_cast<int32_t>(offsetof(Exception_t_StaticFields, ___s_EDILock_0)); }
inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; }
inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; }
inline void set_s_EDILock_0(RuntimeObject * value)
{
___s_EDILock_0 = value;
Il2CppCodeGenWriteBarrier((&___s_EDILock_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Exception
struct Exception_t_marshaled_pinvoke
{
char* ____className_1;
char* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_pinvoke* ____innerException_4;
char* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
char* ____stackTraceString_7;
char* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
char* ____source_12;
SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13;
StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
// Native definition for COM marshalling of System.Exception
struct Exception_t_marshaled_com
{
Il2CppChar* ____className_1;
Il2CppChar* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_com* ____innerException_4;
Il2CppChar* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
Il2CppChar* ____stackTraceString_7;
Il2CppChar* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
Il2CppChar* ____source_12;
SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13;
StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
#endif // EXCEPTION_T_H
#ifndef MARSHALBYREFOBJECT_TC4577953D0A44D0AB8597CFA868E01C858B1C9AF_H
#define MARSHALBYREFOBJECT_TC4577953D0A44D0AB8597CFA868E01C858B1C9AF_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.MarshalByRefObject
struct MarshalByRefObject_tC4577953D0A44D0AB8597CFA868E01C858B1C9AF : public RuntimeObject
{
public:
// System.Object System.MarshalByRefObject::_identity
RuntimeObject * ____identity_0;
public:
inline static int32_t get_offset_of__identity_0() { return static_cast<int32_t>(offsetof(MarshalByRefObject_tC4577953D0A44D0AB8597CFA868E01C858B1C9AF, ____identity_0)); }
inline RuntimeObject * get__identity_0() const { return ____identity_0; }
inline RuntimeObject ** get_address_of__identity_0() { return &____identity_0; }
inline void set__identity_0(RuntimeObject * value)
{
____identity_0 = value;
Il2CppCodeGenWriteBarrier((&____identity_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.MarshalByRefObject
struct MarshalByRefObject_tC4577953D0A44D0AB8597CFA868E01C858B1C9AF_marshaled_pinvoke
{
Il2CppIUnknown* ____identity_0;
};
// Native definition for COM marshalling of System.MarshalByRefObject
struct MarshalByRefObject_tC4577953D0A44D0AB8597CFA868E01C858B1C9AF_marshaled_com
{
Il2CppIUnknown* ____identity_0;
};
#endif // MARSHALBYREFOBJECT_TC4577953D0A44D0AB8597CFA868E01C858B1C9AF_H
#ifndef AUTHORIZATION_T6AA17F42B60530EEB99AABAF32E48F292BE2125B_H
#define AUTHORIZATION_T6AA17F42B60530EEB99AABAF32E48F292BE2125B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Net.Authorization
struct Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B : public RuntimeObject
{
public:
// System.String System.Net.Authorization::m_Message
String_t* ___m_Message_0;
// System.Boolean System.Net.Authorization::m_Complete
bool ___m_Complete_1;
// System.String System.Net.Authorization::ModuleAuthenticationType
String_t* ___ModuleAuthenticationType_2;
public:
inline static int32_t get_offset_of_m_Message_0() { return static_cast<int32_t>(offsetof(Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B, ___m_Message_0)); }
inline String_t* get_m_Message_0() const { return ___m_Message_0; }
inline String_t** get_address_of_m_Message_0() { return &___m_Message_0; }
inline void set_m_Message_0(String_t* value)
{
___m_Message_0 = value;
Il2CppCodeGenWriteBarrier((&___m_Message_0), value);
}
inline static int32_t get_offset_of_m_Complete_1() { return static_cast<int32_t>(offsetof(Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B, ___m_Complete_1)); }
inline bool get_m_Complete_1() const { return ___m_Complete_1; }
inline bool* get_address_of_m_Complete_1() { return &___m_Complete_1; }
inline void set_m_Complete_1(bool value)
{
___m_Complete_1 = value;
}
inline static int32_t get_offset_of_ModuleAuthenticationType_2() { return static_cast<int32_t>(offsetof(Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B, ___ModuleAuthenticationType_2)); }
inline String_t* get_ModuleAuthenticationType_2() const { return ___ModuleAuthenticationType_2; }
inline String_t** get_address_of_ModuleAuthenticationType_2() { return &___ModuleAuthenticationType_2; }
inline void set_ModuleAuthenticationType_2(String_t* value)
{
___ModuleAuthenticationType_2 = value;
Il2CppCodeGenWriteBarrier((&___ModuleAuthenticationType_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AUTHORIZATION_T6AA17F42B60530EEB99AABAF32E48F292BE2125B_H
#ifndef CREDENTIALCACHE_T5AB6054A54B30F44BC5746C09E6524F947E7904D_H
#define CREDENTIALCACHE_T5AB6054A54B30F44BC5746C09E6524F947E7904D_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Net.CredentialCache
struct CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D : public RuntimeObject
{
public:
// System.Collections.Hashtable System.Net.CredentialCache::cache
Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ___cache_0;
// System.Collections.Hashtable System.Net.CredentialCache::cacheForHosts
Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * ___cacheForHosts_1;
// System.Int32 System.Net.CredentialCache::m_version
int32_t ___m_version_2;
public:
inline static int32_t get_offset_of_cache_0() { return static_cast<int32_t>(offsetof(CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D, ___cache_0)); }
inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get_cache_0() const { return ___cache_0; }
inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of_cache_0() { return &___cache_0; }
inline void set_cache_0(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value)
{
___cache_0 = value;
Il2CppCodeGenWriteBarrier((&___cache_0), value);
}
inline static int32_t get_offset_of_cacheForHosts_1() { return static_cast<int32_t>(offsetof(CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D, ___cacheForHosts_1)); }
inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * get_cacheForHosts_1() const { return ___cacheForHosts_1; }
inline Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 ** get_address_of_cacheForHosts_1() { return &___cacheForHosts_1; }
inline void set_cacheForHosts_1(Hashtable_t978F65B8006C8F5504B286526AEC6608FF983FC9 * value)
{
___cacheForHosts_1 = value;
Il2CppCodeGenWriteBarrier((&___cacheForHosts_1), value);
}
inline static int32_t get_offset_of_m_version_2() { return static_cast<int32_t>(offsetof(CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D, ___m_version_2)); }
inline int32_t get_m_version_2() const { return ___m_version_2; }
inline int32_t* get_address_of_m_version_2() { return &___m_version_2; }
inline void set_m_version_2(int32_t value)
{
___m_version_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CREDENTIALCACHE_T5AB6054A54B30F44BC5746C09E6524F947E7904D_H
#ifndef CREDENTIALENUMERATOR_T49CCE6816AB3062B27C0640100310C75F881F8D4_H
#define CREDENTIALENUMERATOR_T49CCE6816AB3062B27C0640100310C75F881F8D4_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Net.CredentialCache_CredentialEnumerator
struct CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4 : public RuntimeObject
{
public:
// System.Net.CredentialCache System.Net.CredentialCache_CredentialEnumerator::m_cache
CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D * ___m_cache_0;
// System.Net.ICredentials[] System.Net.CredentialCache_CredentialEnumerator::m_array
ICredentialsU5BU5D_t9392DAC5D43E13A7142056D21759B362C7C29864* ___m_array_1;
// System.Int32 System.Net.CredentialCache_CredentialEnumerator::m_index
int32_t ___m_index_2;
// System.Int32 System.Net.CredentialCache_CredentialEnumerator::m_version
int32_t ___m_version_3;
public:
inline static int32_t get_offset_of_m_cache_0() { return static_cast<int32_t>(offsetof(CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4, ___m_cache_0)); }
inline CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D * get_m_cache_0() const { return ___m_cache_0; }
inline CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D ** get_address_of_m_cache_0() { return &___m_cache_0; }
inline void set_m_cache_0(CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D * value)
{
___m_cache_0 = value;
Il2CppCodeGenWriteBarrier((&___m_cache_0), value);
}
inline static int32_t get_offset_of_m_array_1() { return static_cast<int32_t>(offsetof(CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4, ___m_array_1)); }
inline ICredentialsU5BU5D_t9392DAC5D43E13A7142056D21759B362C7C29864* get_m_array_1() const { return ___m_array_1; }
inline ICredentialsU5BU5D_t9392DAC5D43E13A7142056D21759B362C7C29864** get_address_of_m_array_1() { return &___m_array_1; }
inline void set_m_array_1(ICredentialsU5BU5D_t9392DAC5D43E13A7142056D21759B362C7C29864* value)
{
___m_array_1 = value;
Il2CppCodeGenWriteBarrier((&___m_array_1), value);
}
inline static int32_t get_offset_of_m_index_2() { return static_cast<int32_t>(offsetof(CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4, ___m_index_2)); }
inline int32_t get_m_index_2() const { return ___m_index_2; }
inline int32_t* get_address_of_m_index_2() { return &___m_index_2; }
inline void set_m_index_2(int32_t value)
{
___m_index_2 = value;
}
inline static int32_t get_offset_of_m_version_3() { return static_cast<int32_t>(offsetof(CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4, ___m_version_3)); }
inline int32_t get_m_version_3() const { return ___m_version_3; }
inline int32_t* get_address_of_m_version_3() { return &___m_version_3; }
inline void set_m_version_3(int32_t value)
{
___m_version_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CREDENTIALENUMERATOR_T49CCE6816AB3062B27C0640100310C75F881F8D4_H
#ifndef CRITICALFINALIZEROBJECT_T8B006E1DEE084E781F5C0F3283E9226E28894DD9_H
#define CRITICALFINALIZEROBJECT_T8B006E1DEE084E781F5C0F3283E9226E28894DD9_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.ConstrainedExecution.CriticalFinalizerObject
struct CriticalFinalizerObject_t8B006E1DEE084E781F5C0F3283E9226E28894DD9 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CRITICALFINALIZEROBJECT_T8B006E1DEE084E781F5C0F3283E9226E28894DD9_H
#ifndef ASNENCODEDDATA_T7D5EF5337DCAF507CAD7D750552C943F037A9D65_H
#define ASNENCODEDDATA_T7D5EF5337DCAF507CAD7D750552C943F037A9D65_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AsnEncodedData
struct AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 : public RuntimeObject
{
public:
// System.Security.Cryptography.Oid System.Security.Cryptography.AsnEncodedData::_oid
Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * ____oid_0;
// System.Byte[] System.Security.Cryptography.AsnEncodedData::_raw
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ____raw_1;
public:
inline static int32_t get_offset_of__oid_0() { return static_cast<int32_t>(offsetof(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65, ____oid_0)); }
inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * get__oid_0() const { return ____oid_0; }
inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 ** get_address_of__oid_0() { return &____oid_0; }
inline void set__oid_0(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * value)
{
____oid_0 = value;
Il2CppCodeGenWriteBarrier((&____oid_0), value);
}
inline static int32_t get_offset_of__raw_1() { return static_cast<int32_t>(offsetof(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65, ____raw_1)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get__raw_1() const { return ____raw_1; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of__raw_1() { return &____raw_1; }
inline void set__raw_1(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
____raw_1 = value;
Il2CppCodeGenWriteBarrier((&____raw_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ASNENCODEDDATA_T7D5EF5337DCAF507CAD7D750552C943F037A9D65_H
#ifndef CAPI_TEA68010AC3470FFEBC91FC9D3C13E7D7064C3267_H
#define CAPI_TEA68010AC3470FFEBC91FC9D3C13E7D7064C3267_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.CAPI
struct CAPI_tEA68010AC3470FFEBC91FC9D3C13E7D7064C3267 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CAPI_TEA68010AC3470FFEBC91FC9D3C13E7D7064C3267_H
#ifndef OIDCOLLECTION_TEB423F1150E53DCF513BF5A699F911586A31B94E_H
#define OIDCOLLECTION_TEB423F1150E53DCF513BF5A699F911586A31B94E_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.OidCollection
struct OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Security.Cryptography.OidCollection::m_list
ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * ___m_list_0;
public:
inline static int32_t get_offset_of_m_list_0() { return static_cast<int32_t>(offsetof(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E, ___m_list_0)); }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * get_m_list_0() const { return ___m_list_0; }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 ** get_address_of_m_list_0() { return &___m_list_0; }
inline void set_m_list_0(ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * value)
{
___m_list_0 = value;
Il2CppCodeGenWriteBarrier((&___m_list_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OIDCOLLECTION_TEB423F1150E53DCF513BF5A699F911586A31B94E_H
#ifndef OIDENUMERATOR_TC2DB288576C575B69F7934274DDD8A5868CEF97C_H
#define OIDENUMERATOR_TC2DB288576C575B69F7934274DDD8A5868CEF97C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.OidEnumerator
struct OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C : public RuntimeObject
{
public:
// System.Security.Cryptography.OidCollection System.Security.Cryptography.OidEnumerator::m_oids
OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * ___m_oids_0;
// System.Int32 System.Security.Cryptography.OidEnumerator::m_current
int32_t ___m_current_1;
public:
inline static int32_t get_offset_of_m_oids_0() { return static_cast<int32_t>(offsetof(OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C, ___m_oids_0)); }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * get_m_oids_0() const { return ___m_oids_0; }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E ** get_address_of_m_oids_0() { return &___m_oids_0; }
inline void set_m_oids_0(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * value)
{
___m_oids_0 = value;
Il2CppCodeGenWriteBarrier((&___m_oids_0), value);
}
inline static int32_t get_offset_of_m_current_1() { return static_cast<int32_t>(offsetof(OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C, ___m_current_1)); }
inline int32_t get_m_current_1() const { return ___m_current_1; }
inline int32_t* get_address_of_m_current_1() { return &___m_current_1; }
inline void set_m_current_1(int32_t value)
{
___m_current_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OIDENUMERATOR_TC2DB288576C575B69F7934274DDD8A5868CEF97C_H
#ifndef PUBLICKEY_TBA8234EB603A903FCBBBE67D8247393D4CC8D620_H
#define PUBLICKEY_TBA8234EB603A903FCBBBE67D8247393D4CC8D620_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.PublicKey
struct PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620 : public RuntimeObject
{
public:
// System.Security.Cryptography.AsymmetricAlgorithm System.Security.Cryptography.X509Certificates.PublicKey::_key
AsymmetricAlgorithm_t9F811260245370BD8786A849DBF9F8054F97F4CB * ____key_0;
// System.Security.Cryptography.AsnEncodedData System.Security.Cryptography.X509Certificates.PublicKey::_keyValue
AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * ____keyValue_1;
// System.Security.Cryptography.AsnEncodedData System.Security.Cryptography.X509Certificates.PublicKey::_params
AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * ____params_2;
// System.Security.Cryptography.Oid System.Security.Cryptography.X509Certificates.PublicKey::_oid
Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * ____oid_3;
public:
inline static int32_t get_offset_of__key_0() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____key_0)); }
inline AsymmetricAlgorithm_t9F811260245370BD8786A849DBF9F8054F97F4CB * get__key_0() const { return ____key_0; }
inline AsymmetricAlgorithm_t9F811260245370BD8786A849DBF9F8054F97F4CB ** get_address_of__key_0() { return &____key_0; }
inline void set__key_0(AsymmetricAlgorithm_t9F811260245370BD8786A849DBF9F8054F97F4CB * value)
{
____key_0 = value;
Il2CppCodeGenWriteBarrier((&____key_0), value);
}
inline static int32_t get_offset_of__keyValue_1() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____keyValue_1)); }
inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * get__keyValue_1() const { return ____keyValue_1; }
inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 ** get_address_of__keyValue_1() { return &____keyValue_1; }
inline void set__keyValue_1(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * value)
{
____keyValue_1 = value;
Il2CppCodeGenWriteBarrier((&____keyValue_1), value);
}
inline static int32_t get_offset_of__params_2() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____params_2)); }
inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * get__params_2() const { return ____params_2; }
inline AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 ** get_address_of__params_2() { return &____params_2; }
inline void set__params_2(AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65 * value)
{
____params_2 = value;
Il2CppCodeGenWriteBarrier((&____params_2), value);
}
inline static int32_t get_offset_of__oid_3() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620, ____oid_3)); }
inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * get__oid_3() const { return ____oid_3; }
inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 ** get_address_of__oid_3() { return &____oid_3; }
inline void set__oid_3(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * value)
{
____oid_3 = value;
Il2CppCodeGenWriteBarrier((&____oid_3), value);
}
};
struct PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields
{
public:
// System.Byte[] System.Security.Cryptography.X509Certificates.PublicKey::Empty
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___Empty_4;
public:
inline static int32_t get_offset_of_Empty_4() { return static_cast<int32_t>(offsetof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields, ___Empty_4)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_Empty_4() const { return ___Empty_4; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_Empty_4() { return &___Empty_4; }
inline void set_Empty_4(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___Empty_4 = value;
Il2CppCodeGenWriteBarrier((&___Empty_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PUBLICKEY_TBA8234EB603A903FCBBBE67D8247393D4CC8D620_H
#ifndef X509CERTIFICATE_T6859B8914E252B6831D6F59A2A720CD23F7FA7B2_H
#define X509CERTIFICATE_T6859B8914E252B6831D6F59A2A720CD23F7FA7B2_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Certificate
struct X509Certificate_t6859B8914E252B6831D6F59A2A720CD23F7FA7B2 : public RuntimeObject
{
public:
// System.Security.Cryptography.X509Certificates.X509CertificateImpl System.Security.Cryptography.X509Certificates.X509Certificate::impl
X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313 * ___impl_0;
// System.Boolean System.Security.Cryptography.X509Certificates.X509Certificate::hideDates
bool ___hideDates_1;
// System.String System.Security.Cryptography.X509Certificates.X509Certificate::issuer_name
String_t* ___issuer_name_2;
// System.String System.Security.Cryptography.X509Certificates.X509Certificate::subject_name
String_t* ___subject_name_3;
public:
inline static int32_t get_offset_of_impl_0() { return static_cast<int32_t>(offsetof(X509Certificate_t6859B8914E252B6831D6F59A2A720CD23F7FA7B2, ___impl_0)); }
inline X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313 * get_impl_0() const { return ___impl_0; }
inline X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313 ** get_address_of_impl_0() { return &___impl_0; }
inline void set_impl_0(X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313 * value)
{
___impl_0 = value;
Il2CppCodeGenWriteBarrier((&___impl_0), value);
}
inline static int32_t get_offset_of_hideDates_1() { return static_cast<int32_t>(offsetof(X509Certificate_t6859B8914E252B6831D6F59A2A720CD23F7FA7B2, ___hideDates_1)); }
inline bool get_hideDates_1() const { return ___hideDates_1; }
inline bool* get_address_of_hideDates_1() { return &___hideDates_1; }
inline void set_hideDates_1(bool value)
{
___hideDates_1 = value;
}
inline static int32_t get_offset_of_issuer_name_2() { return static_cast<int32_t>(offsetof(X509Certificate_t6859B8914E252B6831D6F59A2A720CD23F7FA7B2, ___issuer_name_2)); }
inline String_t* get_issuer_name_2() const { return ___issuer_name_2; }
inline String_t** get_address_of_issuer_name_2() { return &___issuer_name_2; }
inline void set_issuer_name_2(String_t* value)
{
___issuer_name_2 = value;
Il2CppCodeGenWriteBarrier((&___issuer_name_2), value);
}
inline static int32_t get_offset_of_subject_name_3() { return static_cast<int32_t>(offsetof(X509Certificate_t6859B8914E252B6831D6F59A2A720CD23F7FA7B2, ___subject_name_3)); }
inline String_t* get_subject_name_3() const { return ___subject_name_3; }
inline String_t** get_address_of_subject_name_3() { return &___subject_name_3; }
inline void set_subject_name_3(String_t* value)
{
___subject_name_3 = value;
Il2CppCodeGenWriteBarrier((&___subject_name_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATE_T6859B8914E252B6831D6F59A2A720CD23F7FA7B2_H
#ifndef X509CERTIFICATEENUMERATOR_T99AEDECD77BFC6083D8C98F9760BF7876D5B886B_H
#define X509CERTIFICATEENUMERATOR_T99AEDECD77BFC6083D8C98F9760BF7876D5B886B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509CertificateCollection_X509CertificateEnumerator
struct X509CertificateEnumerator_t99AEDECD77BFC6083D8C98F9760BF7876D5B886B : public RuntimeObject
{
public:
// System.Collections.IEnumerator System.Security.Cryptography.X509Certificates.X509CertificateCollection_X509CertificateEnumerator::enumerator
RuntimeObject* ___enumerator_0;
public:
inline static int32_t get_offset_of_enumerator_0() { return static_cast<int32_t>(offsetof(X509CertificateEnumerator_t99AEDECD77BFC6083D8C98F9760BF7876D5B886B, ___enumerator_0)); }
inline RuntimeObject* get_enumerator_0() const { return ___enumerator_0; }
inline RuntimeObject** get_address_of_enumerator_0() { return &___enumerator_0; }
inline void set_enumerator_0(RuntimeObject* value)
{
___enumerator_0 = value;
Il2CppCodeGenWriteBarrier((&___enumerator_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATEENUMERATOR_T99AEDECD77BFC6083D8C98F9760BF7876D5B886B_H
#ifndef X509CERTIFICATEIMPL_T89610BFDE87B872143A4623CFC7F17275EB48313_H
#define X509CERTIFICATEIMPL_T89610BFDE87B872143A4623CFC7F17275EB48313_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509CertificateImpl
struct X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313 : public RuntimeObject
{
public:
// System.Byte[] System.Security.Cryptography.X509Certificates.X509CertificateImpl::cachedCertificateHash
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___cachedCertificateHash_0;
public:
inline static int32_t get_offset_of_cachedCertificateHash_0() { return static_cast<int32_t>(offsetof(X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313, ___cachedCertificateHash_0)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_cachedCertificateHash_0() const { return ___cachedCertificateHash_0; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_cachedCertificateHash_0() { return &___cachedCertificateHash_0; }
inline void set_cachedCertificateHash_0(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___cachedCertificateHash_0 = value;
Il2CppCodeGenWriteBarrier((&___cachedCertificateHash_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATEIMPL_T89610BFDE87B872143A4623CFC7F17275EB48313_H
#ifndef X509CERTIFICATEIMPLCOLLECTION_T2F7A6E9F160116CE64224D56187C92ECD7FA7242_H
#define X509CERTIFICATEIMPLCOLLECTION_T2F7A6E9F160116CE64224D56187C92ECD7FA7242_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509CertificateImplCollection
struct X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242 : public RuntimeObject
{
public:
// System.Collections.Generic.List`1<System.Security.Cryptography.X509Certificates.X509CertificateImpl> System.Security.Cryptography.X509Certificates.X509CertificateImplCollection::list
List_1_t37E424CC2C8529EE0DCF9C6ACACB7F4CA9534033 * ___list_0;
public:
inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242, ___list_0)); }
inline List_1_t37E424CC2C8529EE0DCF9C6ACACB7F4CA9534033 * get_list_0() const { return ___list_0; }
inline List_1_t37E424CC2C8529EE0DCF9C6ACACB7F4CA9534033 ** get_address_of_list_0() { return &___list_0; }
inline void set_list_0(List_1_t37E424CC2C8529EE0DCF9C6ACACB7F4CA9534033 * value)
{
___list_0 = value;
Il2CppCodeGenWriteBarrier((&___list_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATEIMPLCOLLECTION_T2F7A6E9F160116CE64224D56187C92ECD7FA7242_H
#ifndef X509CHAIN_T4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538_H
#define X509CHAIN_T4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Chain
struct X509Chain_t4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538 : public RuntimeObject
{
public:
// System.Security.Cryptography.X509Certificates.X509ChainImpl System.Security.Cryptography.X509Certificates.X509Chain::impl
X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67 * ___impl_0;
public:
inline static int32_t get_offset_of_impl_0() { return static_cast<int32_t>(offsetof(X509Chain_t4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538, ___impl_0)); }
inline X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67 * get_impl_0() const { return ___impl_0; }
inline X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67 ** get_address_of_impl_0() { return &___impl_0; }
inline void set_impl_0(X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67 * value)
{
___impl_0 = value;
Il2CppCodeGenWriteBarrier((&___impl_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAIN_T4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538_H
#ifndef X509CHAINELEMENTCOLLECTION_T7098FB9D22CA34D461370C124E598C629BCADBF4_H
#define X509CHAINELEMENTCOLLECTION_T7098FB9D22CA34D461370C124E598C629BCADBF4_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainElementCollection
struct X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4 : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Security.Cryptography.X509Certificates.X509ChainElementCollection::_list
ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * ____list_0;
public:
inline static int32_t get_offset_of__list_0() { return static_cast<int32_t>(offsetof(X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4, ____list_0)); }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * get__list_0() const { return ____list_0; }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 ** get_address_of__list_0() { return &____list_0; }
inline void set__list_0(ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * value)
{
____list_0 = value;
Il2CppCodeGenWriteBarrier((&____list_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINELEMENTCOLLECTION_T7098FB9D22CA34D461370C124E598C629BCADBF4_H
#ifndef X509CHAINELEMENTENUMERATOR_TEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20_H
#define X509CHAINELEMENTENUMERATOR_TEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator
struct X509ChainElementEnumerator_tEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20 : public RuntimeObject
{
public:
// System.Collections.IEnumerator System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator::enumerator
RuntimeObject* ___enumerator_0;
public:
inline static int32_t get_offset_of_enumerator_0() { return static_cast<int32_t>(offsetof(X509ChainElementEnumerator_tEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20, ___enumerator_0)); }
inline RuntimeObject* get_enumerator_0() const { return ___enumerator_0; }
inline RuntimeObject** get_address_of_enumerator_0() { return &___enumerator_0; }
inline void set_enumerator_0(RuntimeObject* value)
{
___enumerator_0 = value;
Il2CppCodeGenWriteBarrier((&___enumerator_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINELEMENTENUMERATOR_TEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20_H
#ifndef X509CHAINIMPL_T34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67_H
#define X509CHAINIMPL_T34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainImpl
struct X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINIMPL_T34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67_H
#ifndef X509EXTENSIONCOLLECTION_T83492D3C69B75EE35B0029F87F9E46CABE49248F_H
#define X509EXTENSIONCOLLECTION_T83492D3C69B75EE35B0029F87F9E46CABE49248F_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ExtensionCollection
struct X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Security.Cryptography.X509Certificates.X509ExtensionCollection::_list
ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * ____list_1;
public:
inline static int32_t get_offset_of__list_1() { return static_cast<int32_t>(offsetof(X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F, ____list_1)); }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * get__list_1() const { return ____list_1; }
inline ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 ** get_address_of__list_1() { return &____list_1; }
inline void set__list_1(ArrayList_t4131E0C29C7E1B9BC9DFE37BEC41A5EB1481ADF4 * value)
{
____list_1 = value;
Il2CppCodeGenWriteBarrier((&____list_1), value);
}
};
struct X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F_StaticFields
{
public:
// System.Byte[] System.Security.Cryptography.X509Certificates.X509ExtensionCollection::Empty
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___Empty_0;
public:
inline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F_StaticFields, ___Empty_0)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_Empty_0() const { return ___Empty_0; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_Empty_0() { return &___Empty_0; }
inline void set_Empty_0(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___Empty_0 = value;
Il2CppCodeGenWriteBarrier((&___Empty_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509EXTENSIONCOLLECTION_T83492D3C69B75EE35B0029F87F9E46CABE49248F_H
#ifndef X509EXTENSIONENUMERATOR_TD857681A1E92F6D18ADCA3710A0176A221D151D8_H
#define X509EXTENSIONENUMERATOR_TD857681A1E92F6D18ADCA3710A0176A221D151D8_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator
struct X509ExtensionEnumerator_tD857681A1E92F6D18ADCA3710A0176A221D151D8 : public RuntimeObject
{
public:
// System.Collections.IEnumerator System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator::enumerator
RuntimeObject* ___enumerator_0;
public:
inline static int32_t get_offset_of_enumerator_0() { return static_cast<int32_t>(offsetof(X509ExtensionEnumerator_tD857681A1E92F6D18ADCA3710A0176A221D151D8, ___enumerator_0)); }
inline RuntimeObject* get_enumerator_0() const { return ___enumerator_0; }
inline RuntimeObject** get_address_of_enumerator_0() { return &___enumerator_0; }
inline void set_enumerator_0(RuntimeObject* value)
{
___enumerator_0 = value;
Il2CppCodeGenWriteBarrier((&___enumerator_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509EXTENSIONENUMERATOR_TD857681A1E92F6D18ADCA3710A0176A221D151D8_H
#ifndef X509HELPER2_TD0B65FDE6197798D9719F42AAEA8D9063A8916C7_H
#define X509HELPER2_TD0B65FDE6197798D9719F42AAEA8D9063A8916C7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Helper2
struct X509Helper2_tD0B65FDE6197798D9719F42AAEA8D9063A8916C7 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509HELPER2_TD0B65FDE6197798D9719F42AAEA8D9063A8916C7_H
#ifndef MYNATIVEHELPER_T045BCDC42DCE7A83A80C98AC77C835142040F7B0_H
#define MYNATIVEHELPER_T045BCDC42DCE7A83A80C98AC77C835142040F7B0_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Helper2_MyNativeHelper
struct MyNativeHelper_t045BCDC42DCE7A83A80C98AC77C835142040F7B0 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MYNATIVEHELPER_T045BCDC42DCE7A83A80C98AC77C835142040F7B0_H
#ifndef X509UTILS_T596E1974703C7988010495E60F15BE9680FC71B8_H
#define X509UTILS_T596E1974703C7988010495E60F15BE9680FC71B8_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Utils
struct X509Utils_t596E1974703C7988010495E60F15BE9680FC71B8 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509UTILS_T596E1974703C7988010495E60F15BE9680FC71B8_H
#ifndef VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H
#define VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com
{
};
#endif // VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H
#ifndef BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H
#define BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_5), value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_6), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H
#ifndef BROWSABLEATTRIBUTE_T8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_H
#define BROWSABLEATTRIBUTE_T8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.BrowsableAttribute
struct BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.Boolean System.ComponentModel.BrowsableAttribute::browsable
bool ___browsable_3;
public:
inline static int32_t get_offset_of_browsable_3() { return static_cast<int32_t>(offsetof(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1, ___browsable_3)); }
inline bool get_browsable_3() const { return ___browsable_3; }
inline bool* get_address_of_browsable_3() { return &___browsable_3; }
inline void set_browsable_3(bool value)
{
___browsable_3 = value;
}
};
struct BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields
{
public:
// System.ComponentModel.BrowsableAttribute System.ComponentModel.BrowsableAttribute::Yes
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * ___Yes_0;
// System.ComponentModel.BrowsableAttribute System.ComponentModel.BrowsableAttribute::No
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * ___No_1;
// System.ComponentModel.BrowsableAttribute System.ComponentModel.BrowsableAttribute::Default
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * ___Default_2;
public:
inline static int32_t get_offset_of_Yes_0() { return static_cast<int32_t>(offsetof(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields, ___Yes_0)); }
inline BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * get_Yes_0() const { return ___Yes_0; }
inline BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 ** get_address_of_Yes_0() { return &___Yes_0; }
inline void set_Yes_0(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * value)
{
___Yes_0 = value;
Il2CppCodeGenWriteBarrier((&___Yes_0), value);
}
inline static int32_t get_offset_of_No_1() { return static_cast<int32_t>(offsetof(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields, ___No_1)); }
inline BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * get_No_1() const { return ___No_1; }
inline BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 ** get_address_of_No_1() { return &___No_1; }
inline void set_No_1(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * value)
{
___No_1 = value;
Il2CppCodeGenWriteBarrier((&___No_1), value);
}
inline static int32_t get_offset_of_Default_2() { return static_cast<int32_t>(offsetof(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields, ___Default_2)); }
inline BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * get_Default_2() const { return ___Default_2; }
inline BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 ** get_address_of_Default_2() { return &___Default_2; }
inline void set_Default_2(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1 * value)
{
___Default_2 = value;
Il2CppCodeGenWriteBarrier((&___Default_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BROWSABLEATTRIBUTE_T8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_H
#ifndef CATEGORYATTRIBUTE_T89C58D266A4A65CD58E04FF63344AA3E0AF57B80_H
#define CATEGORYATTRIBUTE_T89C58D266A4A65CD58E04FF63344AA3E0AF57B80_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.CategoryAttribute
struct CategoryAttribute_t89C58D266A4A65CD58E04FF63344AA3E0AF57B80 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.Boolean System.ComponentModel.CategoryAttribute::localized
bool ___localized_0;
// System.String System.ComponentModel.CategoryAttribute::categoryValue
String_t* ___categoryValue_1;
public:
inline static int32_t get_offset_of_localized_0() { return static_cast<int32_t>(offsetof(CategoryAttribute_t89C58D266A4A65CD58E04FF63344AA3E0AF57B80, ___localized_0)); }
inline bool get_localized_0() const { return ___localized_0; }
inline bool* get_address_of_localized_0() { return &___localized_0; }
inline void set_localized_0(bool value)
{
___localized_0 = value;
}
inline static int32_t get_offset_of_categoryValue_1() { return static_cast<int32_t>(offsetof(CategoryAttribute_t89C58D266A4A65CD58E04FF63344AA3E0AF57B80, ___categoryValue_1)); }
inline String_t* get_categoryValue_1() const { return ___categoryValue_1; }
inline String_t** get_address_of_categoryValue_1() { return &___categoryValue_1; }
inline void set_categoryValue_1(String_t* value)
{
___categoryValue_1 = value;
Il2CppCodeGenWriteBarrier((&___categoryValue_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CATEGORYATTRIBUTE_T89C58D266A4A65CD58E04FF63344AA3E0AF57B80_H
#ifndef COMPONENT_T7AEFE153F6778CF52E1981BC3E811A9604B29473_H
#define COMPONENT_T7AEFE153F6778CF52E1981BC3E811A9604B29473_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Component
struct Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473 : public MarshalByRefObject_tC4577953D0A44D0AB8597CFA868E01C858B1C9AF
{
public:
// System.ComponentModel.ISite System.ComponentModel.Component::site
RuntimeObject* ___site_2;
// System.ComponentModel.EventHandlerList System.ComponentModel.Component::events
EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4 * ___events_3;
public:
inline static int32_t get_offset_of_site_2() { return static_cast<int32_t>(offsetof(Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473, ___site_2)); }
inline RuntimeObject* get_site_2() const { return ___site_2; }
inline RuntimeObject** get_address_of_site_2() { return &___site_2; }
inline void set_site_2(RuntimeObject* value)
{
___site_2 = value;
Il2CppCodeGenWriteBarrier((&___site_2), value);
}
inline static int32_t get_offset_of_events_3() { return static_cast<int32_t>(offsetof(Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473, ___events_3)); }
inline EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4 * get_events_3() const { return ___events_3; }
inline EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4 ** get_address_of_events_3() { return &___events_3; }
inline void set_events_3(EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4 * value)
{
___events_3 = value;
Il2CppCodeGenWriteBarrier((&___events_3), value);
}
};
struct Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473_StaticFields
{
public:
// System.Object System.ComponentModel.Component::EventDisposed
RuntimeObject * ___EventDisposed_1;
public:
inline static int32_t get_offset_of_EventDisposed_1() { return static_cast<int32_t>(offsetof(Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473_StaticFields, ___EventDisposed_1)); }
inline RuntimeObject * get_EventDisposed_1() const { return ___EventDisposed_1; }
inline RuntimeObject ** get_address_of_EventDisposed_1() { return &___EventDisposed_1; }
inline void set_EventDisposed_1(RuntimeObject * value)
{
___EventDisposed_1 = value;
Il2CppCodeGenWriteBarrier((&___EventDisposed_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COMPONENT_T7AEFE153F6778CF52E1981BC3E811A9604B29473_H
#ifndef DEFAULTEVENTATTRIBUTE_TD1A10417C052CE865C43023F6DCC33CF54D3D846_H
#define DEFAULTEVENTATTRIBUTE_TD1A10417C052CE865C43023F6DCC33CF54D3D846_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DefaultEventAttribute
struct DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.String System.ComponentModel.DefaultEventAttribute::name
String_t* ___name_0;
public:
inline static int32_t get_offset_of_name_0() { return static_cast<int32_t>(offsetof(DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846, ___name_0)); }
inline String_t* get_name_0() const { return ___name_0; }
inline String_t** get_address_of_name_0() { return &___name_0; }
inline void set_name_0(String_t* value)
{
___name_0 = value;
Il2CppCodeGenWriteBarrier((&___name_0), value);
}
};
struct DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846_StaticFields
{
public:
// System.ComponentModel.DefaultEventAttribute System.ComponentModel.DefaultEventAttribute::Default
DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846 * ___Default_1;
public:
inline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846_StaticFields, ___Default_1)); }
inline DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846 * get_Default_1() const { return ___Default_1; }
inline DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846 ** get_address_of_Default_1() { return &___Default_1; }
inline void set_Default_1(DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846 * value)
{
___Default_1 = value;
Il2CppCodeGenWriteBarrier((&___Default_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFAULTEVENTATTRIBUTE_TD1A10417C052CE865C43023F6DCC33CF54D3D846_H
#ifndef DEFAULTPROPERTYATTRIBUTE_T4C049F2905F3ABDE9B9592627B6133AE49050AA7_H
#define DEFAULTPROPERTYATTRIBUTE_T4C049F2905F3ABDE9B9592627B6133AE49050AA7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DefaultPropertyAttribute
struct DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.String System.ComponentModel.DefaultPropertyAttribute::name
String_t* ___name_0;
public:
inline static int32_t get_offset_of_name_0() { return static_cast<int32_t>(offsetof(DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7, ___name_0)); }
inline String_t* get_name_0() const { return ___name_0; }
inline String_t** get_address_of_name_0() { return &___name_0; }
inline void set_name_0(String_t* value)
{
___name_0 = value;
Il2CppCodeGenWriteBarrier((&___name_0), value);
}
};
struct DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7_StaticFields
{
public:
// System.ComponentModel.DefaultPropertyAttribute System.ComponentModel.DefaultPropertyAttribute::Default
DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7 * ___Default_1;
public:
inline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7_StaticFields, ___Default_1)); }
inline DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7 * get_Default_1() const { return ___Default_1; }
inline DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7 ** get_address_of_Default_1() { return &___Default_1; }
inline void set_Default_1(DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7 * value)
{
___Default_1 = value;
Il2CppCodeGenWriteBarrier((&___Default_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFAULTPROPERTYATTRIBUTE_T4C049F2905F3ABDE9B9592627B6133AE49050AA7_H
#ifndef DEFAULTVALUEATTRIBUTE_T03B1F51B35271D50779D31234C9C6845BC9626EC_H
#define DEFAULTVALUEATTRIBUTE_T03B1F51B35271D50779D31234C9C6845BC9626EC_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DefaultValueAttribute
struct DefaultValueAttribute_t03B1F51B35271D50779D31234C9C6845BC9626EC : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.Object System.ComponentModel.DefaultValueAttribute::value
RuntimeObject * ___value_0;
public:
inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(DefaultValueAttribute_t03B1F51B35271D50779D31234C9C6845BC9626EC, ___value_0)); }
inline RuntimeObject * get_value_0() const { return ___value_0; }
inline RuntimeObject ** get_address_of_value_0() { return &___value_0; }
inline void set_value_0(RuntimeObject * value)
{
___value_0 = value;
Il2CppCodeGenWriteBarrier((&___value_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFAULTVALUEATTRIBUTE_T03B1F51B35271D50779D31234C9C6845BC9626EC_H
#ifndef DESCRIPTIONATTRIBUTE_T112C5FEAA03342D05BF40C1713ABF1C1848DEE75_H
#define DESCRIPTIONATTRIBUTE_T112C5FEAA03342D05BF40C1713ABF1C1848DEE75_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DescriptionAttribute
struct DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.String System.ComponentModel.DescriptionAttribute::description
String_t* ___description_1;
public:
inline static int32_t get_offset_of_description_1() { return static_cast<int32_t>(offsetof(DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75, ___description_1)); }
inline String_t* get_description_1() const { return ___description_1; }
inline String_t** get_address_of_description_1() { return &___description_1; }
inline void set_description_1(String_t* value)
{
___description_1 = value;
Il2CppCodeGenWriteBarrier((&___description_1), value);
}
};
struct DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75_StaticFields
{
public:
// System.ComponentModel.DescriptionAttribute System.ComponentModel.DescriptionAttribute::Default
DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75 * ___Default_0;
public:
inline static int32_t get_offset_of_Default_0() { return static_cast<int32_t>(offsetof(DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75_StaticFields, ___Default_0)); }
inline DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75 * get_Default_0() const { return ___Default_0; }
inline DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75 ** get_address_of_Default_0() { return &___Default_0; }
inline void set_Default_0(DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75 * value)
{
___Default_0 = value;
Il2CppCodeGenWriteBarrier((&___Default_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESCRIPTIONATTRIBUTE_T112C5FEAA03342D05BF40C1713ABF1C1848DEE75_H
#ifndef ROOTDESIGNERSERIALIZERATTRIBUTE_TD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA_H
#define ROOTDESIGNERSERIALIZERATTRIBUTE_TD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute
struct RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.Boolean System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::reloadable
bool ___reloadable_0;
// System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::serializerTypeName
String_t* ___serializerTypeName_1;
// System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::serializerBaseTypeName
String_t* ___serializerBaseTypeName_2;
public:
inline static int32_t get_offset_of_reloadable_0() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA, ___reloadable_0)); }
inline bool get_reloadable_0() const { return ___reloadable_0; }
inline bool* get_address_of_reloadable_0() { return &___reloadable_0; }
inline void set_reloadable_0(bool value)
{
___reloadable_0 = value;
}
inline static int32_t get_offset_of_serializerTypeName_1() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA, ___serializerTypeName_1)); }
inline String_t* get_serializerTypeName_1() const { return ___serializerTypeName_1; }
inline String_t** get_address_of_serializerTypeName_1() { return &___serializerTypeName_1; }
inline void set_serializerTypeName_1(String_t* value)
{
___serializerTypeName_1 = value;
Il2CppCodeGenWriteBarrier((&___serializerTypeName_1), value);
}
inline static int32_t get_offset_of_serializerBaseTypeName_2() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA, ___serializerBaseTypeName_2)); }
inline String_t* get_serializerBaseTypeName_2() const { return ___serializerBaseTypeName_2; }
inline String_t** get_address_of_serializerBaseTypeName_2() { return &___serializerBaseTypeName_2; }
inline void set_serializerBaseTypeName_2(String_t* value)
{
___serializerBaseTypeName_2 = value;
Il2CppCodeGenWriteBarrier((&___serializerBaseTypeName_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ROOTDESIGNERSERIALIZERATTRIBUTE_TD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA_H
#ifndef DESIGNERATTRIBUTE_T55268910CFC6D82065C1A2F68D05DCD3858933D0_H
#define DESIGNERATTRIBUTE_T55268910CFC6D82065C1A2F68D05DCD3858933D0_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerAttribute
struct DesignerAttribute_t55268910CFC6D82065C1A2F68D05DCD3858933D0 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.String System.ComponentModel.DesignerAttribute::designerTypeName
String_t* ___designerTypeName_0;
// System.String System.ComponentModel.DesignerAttribute::designerBaseTypeName
String_t* ___designerBaseTypeName_1;
public:
inline static int32_t get_offset_of_designerTypeName_0() { return static_cast<int32_t>(offsetof(DesignerAttribute_t55268910CFC6D82065C1A2F68D05DCD3858933D0, ___designerTypeName_0)); }
inline String_t* get_designerTypeName_0() const { return ___designerTypeName_0; }
inline String_t** get_address_of_designerTypeName_0() { return &___designerTypeName_0; }
inline void set_designerTypeName_0(String_t* value)
{
___designerTypeName_0 = value;
Il2CppCodeGenWriteBarrier((&___designerTypeName_0), value);
}
inline static int32_t get_offset_of_designerBaseTypeName_1() { return static_cast<int32_t>(offsetof(DesignerAttribute_t55268910CFC6D82065C1A2F68D05DCD3858933D0, ___designerBaseTypeName_1)); }
inline String_t* get_designerBaseTypeName_1() const { return ___designerBaseTypeName_1; }
inline String_t** get_address_of_designerBaseTypeName_1() { return &___designerBaseTypeName_1; }
inline void set_designerBaseTypeName_1(String_t* value)
{
___designerBaseTypeName_1 = value;
Il2CppCodeGenWriteBarrier((&___designerBaseTypeName_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERATTRIBUTE_T55268910CFC6D82065C1A2F68D05DCD3858933D0_H
#ifndef DESIGNERCATEGORYATTRIBUTE_TE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_H
#define DESIGNERCATEGORYATTRIBUTE_TE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerCategoryAttribute
struct DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.String System.ComponentModel.DesignerCategoryAttribute::category
String_t* ___category_0;
public:
inline static int32_t get_offset_of_category_0() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA, ___category_0)); }
inline String_t* get_category_0() const { return ___category_0; }
inline String_t** get_address_of_category_0() { return &___category_0; }
inline void set_category_0(String_t* value)
{
___category_0 = value;
Il2CppCodeGenWriteBarrier((&___category_0), value);
}
};
struct DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields
{
public:
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Component
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * ___Component_1;
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Default
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * ___Default_2;
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Form
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * ___Form_3;
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Generic
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * ___Generic_4;
public:
inline static int32_t get_offset_of_Component_1() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields, ___Component_1)); }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * get_Component_1() const { return ___Component_1; }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA ** get_address_of_Component_1() { return &___Component_1; }
inline void set_Component_1(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * value)
{
___Component_1 = value;
Il2CppCodeGenWriteBarrier((&___Component_1), value);
}
inline static int32_t get_offset_of_Default_2() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields, ___Default_2)); }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * get_Default_2() const { return ___Default_2; }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA ** get_address_of_Default_2() { return &___Default_2; }
inline void set_Default_2(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * value)
{
___Default_2 = value;
Il2CppCodeGenWriteBarrier((&___Default_2), value);
}
inline static int32_t get_offset_of_Form_3() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields, ___Form_3)); }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * get_Form_3() const { return ___Form_3; }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA ** get_address_of_Form_3() { return &___Form_3; }
inline void set_Form_3(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * value)
{
___Form_3 = value;
Il2CppCodeGenWriteBarrier((&___Form_3), value);
}
inline static int32_t get_offset_of_Generic_4() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields, ___Generic_4)); }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * get_Generic_4() const { return ___Generic_4; }
inline DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA ** get_address_of_Generic_4() { return &___Generic_4; }
inline void set_Generic_4(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA * value)
{
___Generic_4 = value;
Il2CppCodeGenWriteBarrier((&___Generic_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERCATEGORYATTRIBUTE_TE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_H
#ifndef PROPERTYCHANGEDEVENTARGS_T90CF85B82F87D594F73F03364494C77592B11F46_H
#define PROPERTYCHANGEDEVENTARGS_T90CF85B82F87D594F73F03364494C77592B11F46_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyChangedEventArgs
struct PropertyChangedEventArgs_t90CF85B82F87D594F73F03364494C77592B11F46 : public EventArgs_t8E6CA180BE0E56674C6407011A94BAF7C757352E
{
public:
// System.String System.ComponentModel.PropertyChangedEventArgs::propertyName
String_t* ___propertyName_1;
public:
inline static int32_t get_offset_of_propertyName_1() { return static_cast<int32_t>(offsetof(PropertyChangedEventArgs_t90CF85B82F87D594F73F03364494C77592B11F46, ___propertyName_1)); }
inline String_t* get_propertyName_1() const { return ___propertyName_1; }
inline String_t** get_address_of_propertyName_1() { return &___propertyName_1; }
inline void set_propertyName_1(String_t* value)
{
___propertyName_1 = value;
Il2CppCodeGenWriteBarrier((&___propertyName_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYCHANGEDEVENTARGS_T90CF85B82F87D594F73F03364494C77592B11F46_H
#ifndef TYPECONVERTERATTRIBUTE_TA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_H
#define TYPECONVERTERATTRIBUTE_TA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverterAttribute
struct TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.String System.ComponentModel.TypeConverterAttribute::typeName
String_t* ___typeName_0;
public:
inline static int32_t get_offset_of_typeName_0() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8, ___typeName_0)); }
inline String_t* get_typeName_0() const { return ___typeName_0; }
inline String_t** get_address_of_typeName_0() { return &___typeName_0; }
inline void set_typeName_0(String_t* value)
{
___typeName_0 = value;
Il2CppCodeGenWriteBarrier((&___typeName_0), value);
}
};
struct TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields
{
public:
// System.ComponentModel.TypeConverterAttribute System.ComponentModel.TypeConverterAttribute::Default
TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 * ___Default_1;
public:
inline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields, ___Default_1)); }
inline TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 * get_Default_1() const { return ___Default_1; }
inline TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 ** get_address_of_Default_1() { return &___Default_1; }
inline void set_Default_1(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8 * value)
{
___Default_1 = value;
Il2CppCodeGenWriteBarrier((&___Default_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPECONVERTERATTRIBUTE_TA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_H
#ifndef DATETIME_T349B7449FBAAFF4192636E2B7A07694DA9236132_H
#define DATETIME_T349B7449FBAAFF4192636E2B7A07694DA9236132_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.DateTime
struct DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132
{
public:
// System.UInt64 System.DateTime::dateData
uint64_t ___dateData_44;
public:
inline static int32_t get_offset_of_dateData_44() { return static_cast<int32_t>(offsetof(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132, ___dateData_44)); }
inline uint64_t get_dateData_44() const { return ___dateData_44; }
inline uint64_t* get_address_of_dateData_44() { return &___dateData_44; }
inline void set_dateData_44(uint64_t value)
{
___dateData_44 = value;
}
};
struct DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132_StaticFields
{
public:
// System.Int32[] System.DateTime::DaysToMonth365
Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ___DaysToMonth365_29;
// System.Int32[] System.DateTime::DaysToMonth366
Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* ___DaysToMonth366_30;
// System.DateTime System.DateTime::MinValue
DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 ___MinValue_31;
// System.DateTime System.DateTime::MaxValue
DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 ___MaxValue_32;
public:
inline static int32_t get_offset_of_DaysToMonth365_29() { return static_cast<int32_t>(offsetof(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132_StaticFields, ___DaysToMonth365_29)); }
inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get_DaysToMonth365_29() const { return ___DaysToMonth365_29; }
inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of_DaysToMonth365_29() { return &___DaysToMonth365_29; }
inline void set_DaysToMonth365_29(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value)
{
___DaysToMonth365_29 = value;
Il2CppCodeGenWriteBarrier((&___DaysToMonth365_29), value);
}
inline static int32_t get_offset_of_DaysToMonth366_30() { return static_cast<int32_t>(offsetof(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132_StaticFields, ___DaysToMonth366_30)); }
inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* get_DaysToMonth366_30() const { return ___DaysToMonth366_30; }
inline Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83** get_address_of_DaysToMonth366_30() { return &___DaysToMonth366_30; }
inline void set_DaysToMonth366_30(Int32U5BU5D_t2B9E4FDDDB9F0A00EC0AC631BA2DA915EB1ECF83* value)
{
___DaysToMonth366_30 = value;
Il2CppCodeGenWriteBarrier((&___DaysToMonth366_30), value);
}
inline static int32_t get_offset_of_MinValue_31() { return static_cast<int32_t>(offsetof(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132_StaticFields, ___MinValue_31)); }
inline DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 get_MinValue_31() const { return ___MinValue_31; }
inline DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 * get_address_of_MinValue_31() { return &___MinValue_31; }
inline void set_MinValue_31(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 value)
{
___MinValue_31 = value;
}
inline static int32_t get_offset_of_MaxValue_32() { return static_cast<int32_t>(offsetof(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132_StaticFields, ___MaxValue_32)); }
inline DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 get_MaxValue_32() const { return ___MaxValue_32; }
inline DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 * get_address_of_MaxValue_32() { return &___MaxValue_32; }
inline void set_MaxValue_32(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 value)
{
___MaxValue_32 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DATETIME_T349B7449FBAAFF4192636E2B7A07694DA9236132_H
#ifndef ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H
#define ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521 : public ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF
{
public:
public:
};
struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_com
{
};
#endif // ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H
#ifndef STREAM_TFC50657DD5AAB87770987F9179D934A51D99D5E7_H
#define STREAM_TFC50657DD5AAB87770987F9179D934A51D99D5E7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Stream
struct Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 : public MarshalByRefObject_tC4577953D0A44D0AB8597CFA868E01C858B1C9AF
{
public:
// System.IO.Stream_ReadWriteTask System.IO.Stream::_activeReadWriteTask
ReadWriteTask_tFA17EEE8BC5C4C83EAEFCC3662A30DE351ABAA80 * ____activeReadWriteTask_2;
// System.Threading.SemaphoreSlim System.IO.Stream::_asyncActiveSemaphore
SemaphoreSlim_t2E2888D1C0C8FAB80823C76F1602E4434B8FA048 * ____asyncActiveSemaphore_3;
public:
inline static int32_t get_offset_of__activeReadWriteTask_2() { return static_cast<int32_t>(offsetof(Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7, ____activeReadWriteTask_2)); }
inline ReadWriteTask_tFA17EEE8BC5C4C83EAEFCC3662A30DE351ABAA80 * get__activeReadWriteTask_2() const { return ____activeReadWriteTask_2; }
inline ReadWriteTask_tFA17EEE8BC5C4C83EAEFCC3662A30DE351ABAA80 ** get_address_of__activeReadWriteTask_2() { return &____activeReadWriteTask_2; }
inline void set__activeReadWriteTask_2(ReadWriteTask_tFA17EEE8BC5C4C83EAEFCC3662A30DE351ABAA80 * value)
{
____activeReadWriteTask_2 = value;
Il2CppCodeGenWriteBarrier((&____activeReadWriteTask_2), value);
}
inline static int32_t get_offset_of__asyncActiveSemaphore_3() { return static_cast<int32_t>(offsetof(Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7, ____asyncActiveSemaphore_3)); }
inline SemaphoreSlim_t2E2888D1C0C8FAB80823C76F1602E4434B8FA048 * get__asyncActiveSemaphore_3() const { return ____asyncActiveSemaphore_3; }
inline SemaphoreSlim_t2E2888D1C0C8FAB80823C76F1602E4434B8FA048 ** get_address_of__asyncActiveSemaphore_3() { return &____asyncActiveSemaphore_3; }
inline void set__asyncActiveSemaphore_3(SemaphoreSlim_t2E2888D1C0C8FAB80823C76F1602E4434B8FA048 * value)
{
____asyncActiveSemaphore_3 = value;
Il2CppCodeGenWriteBarrier((&____asyncActiveSemaphore_3), value);
}
};
struct Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7_StaticFields
{
public:
// System.IO.Stream System.IO.Stream::Null
Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * ___Null_1;
public:
inline static int32_t get_offset_of_Null_1() { return static_cast<int32_t>(offsetof(Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7_StaticFields, ___Null_1)); }
inline Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * get_Null_1() const { return ___Null_1; }
inline Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 ** get_address_of_Null_1() { return &___Null_1; }
inline void set_Null_1(Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * value)
{
___Null_1 = value;
Il2CppCodeGenWriteBarrier((&___Null_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STREAM_TFC50657DD5AAB87770987F9179D934A51D99D5E7_H
#ifndef INT32_T585191389E07734F19F3156FF88FB3EF4800D102_H
#define INT32_T585191389E07734F19F3156FF88FB3EF4800D102_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t585191389E07734F19F3156FF88FB3EF4800D102, ___m_value_0)); }
inline int32_t get_m_value_0() const { return ___m_value_0; }
inline int32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int32_t value)
{
___m_value_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T585191389E07734F19F3156FF88FB3EF4800D102_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef GCHANDLE_T39FAEE3EA592432C93B574A31DD83B87F1847DE3_H
#define GCHANDLE_T39FAEE3EA592432C93B574A31DD83B87F1847DE3_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.InteropServices.GCHandle
struct GCHandle_t39FAEE3EA592432C93B574A31DD83B87F1847DE3
{
public:
// System.Int32 System.Runtime.InteropServices.GCHandle::handle
int32_t ___handle_0;
public:
inline static int32_t get_offset_of_handle_0() { return static_cast<int32_t>(offsetof(GCHandle_t39FAEE3EA592432C93B574A31DD83B87F1847DE3, ___handle_0)); }
inline int32_t get_handle_0() const { return ___handle_0; }
inline int32_t* get_address_of_handle_0() { return &___handle_0; }
inline void set_handle_0(int32_t value)
{
___handle_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GCHANDLE_T39FAEE3EA592432C93B574A31DD83B87F1847DE3_H
#ifndef X500DISTINGUISHEDNAME_T848C6BCD1C0923D5FF85BCA3804AC3D256DF8199_H
#define X500DISTINGUISHEDNAME_T848C6BCD1C0923D5FF85BCA3804AC3D256DF8199_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X500DistinguishedName
struct X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 : public AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X500DISTINGUISHEDNAME_T848C6BCD1C0923D5FF85BCA3804AC3D256DF8199_H
#ifndef X509CERTIFICATE2_TC1C49EB4CFD571C2FFDE940C24BC69651A058F73_H
#define X509CERTIFICATE2_TC1C49EB4CFD571C2FFDE940C24BC69651A058F73_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Certificate2
struct X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73 : public X509Certificate_t6859B8914E252B6831D6F59A2A720CD23F7FA7B2
{
public:
// System.String System.Security.Cryptography.X509Certificates.X509Certificate2::friendlyName
String_t* ___friendlyName_4;
public:
inline static int32_t get_offset_of_friendlyName_4() { return static_cast<int32_t>(offsetof(X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73, ___friendlyName_4)); }
inline String_t* get_friendlyName_4() const { return ___friendlyName_4; }
inline String_t** get_address_of_friendlyName_4() { return &___friendlyName_4; }
inline void set_friendlyName_4(String_t* value)
{
___friendlyName_4 = value;
Il2CppCodeGenWriteBarrier((&___friendlyName_4), value);
}
};
struct X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73_StaticFields
{
public:
// System.Byte[] System.Security.Cryptography.X509Certificates.X509Certificate2::signedData
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___signedData_5;
public:
inline static int32_t get_offset_of_signedData_5() { return static_cast<int32_t>(offsetof(X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73_StaticFields, ___signedData_5)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_signedData_5() const { return ___signedData_5; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_signedData_5() { return &___signedData_5; }
inline void set_signedData_5(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___signedData_5 = value;
Il2CppCodeGenWriteBarrier((&___signedData_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATE2_TC1C49EB4CFD571C2FFDE940C24BC69651A058F73_H
#ifndef X509CERTIFICATE2IMPL_T645108014422F6408EB87390317CD10710F129E7_H
#define X509CERTIFICATE2IMPL_T645108014422F6408EB87390317CD10710F129E7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Certificate2Impl
struct X509Certificate2Impl_t645108014422F6408EB87390317CD10710F129E7 : public X509CertificateImpl_t89610BFDE87B872143A4623CFC7F17275EB48313
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATE2IMPL_T645108014422F6408EB87390317CD10710F129E7_H
#ifndef X509CERTIFICATECOLLECTION_T824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833_H
#define X509CERTIFICATECOLLECTION_T824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509CertificateCollection
struct X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833 : public CollectionBase_tF5D4583FF325726066A9803839A04E9C0084ED01
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATECOLLECTION_T824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833_H
#ifndef X509EXTENSION_T223237DF0C323CC455D3A2634D977773D2F3818A_H
#define X509EXTENSION_T223237DF0C323CC455D3A2634D977773D2F3818A_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Extension
struct X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A : public AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65
{
public:
// System.Boolean System.Security.Cryptography.X509Certificates.X509Extension::_critical
bool ____critical_2;
public:
inline static int32_t get_offset_of__critical_2() { return static_cast<int32_t>(offsetof(X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A, ____critical_2)); }
inline bool get__critical_2() const { return ____critical_2; }
inline bool* get_address_of__critical_2() { return &____critical_2; }
inline void set__critical_2(bool value)
{
____critical_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509EXTENSION_T223237DF0C323CC455D3A2634D977773D2F3818A_H
#ifndef SYSTEMEXCEPTION_T5380468142AA850BE4A341D7AF3EAB9C78746782_H
#define SYSTEMEXCEPTION_T5380468142AA850BE4A341D7AF3EAB9C78746782_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.SystemException
struct SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 : public Exception_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYSTEMEXCEPTION_T5380468142AA850BE4A341D7AF3EAB9C78746782_H
#ifndef VOID_T22962CB4C05B1D89B55A6E1139F0E87A90987017_H
#define VOID_T22962CB4C05B1D89B55A6E1139F0E87A90987017_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017
{
public:
union
{
struct
{
};
uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T22962CB4C05B1D89B55A6E1139F0E87A90987017_H
#ifndef DESIGNERSERIALIZATIONVISIBILITY_TCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A_H
#define DESIGNERSERIALIZATIONVISIBILITY_TCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerSerializationVisibility
struct DesignerSerializationVisibility_tCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A
{
public:
// System.Int32 System.ComponentModel.DesignerSerializationVisibility::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibility_tCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERSERIALIZATIONVISIBILITY_TCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A_H
#ifndef EDITORBROWSABLESTATE_T8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B_H
#define EDITORBROWSABLESTATE_T8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EditorBrowsableState
struct EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B
{
public:
// System.Int32 System.ComponentModel.EditorBrowsableState::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EDITORBROWSABLESTATE_T8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B_H
#ifndef TYPECONVERTER_T8306AE03734853B551DDF089C1F17836A7764DBB_H
#define TYPECONVERTER_T8306AE03734853B551DDF089C1F17836A7764DBB_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverter
struct TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB : public RuntimeObject
{
public:
public:
};
struct TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields
{
public:
// System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.TypeConverter::useCompatibleTypeConversion
bool ___useCompatibleTypeConversion_1;
public:
inline static int32_t get_offset_of_useCompatibleTypeConversion_1() { return static_cast<int32_t>(offsetof(TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields, ___useCompatibleTypeConversion_1)); }
inline bool get_useCompatibleTypeConversion_1() const { return ___useCompatibleTypeConversion_1; }
inline bool* get_address_of_useCompatibleTypeConversion_1() { return &___useCompatibleTypeConversion_1; }
inline void set_useCompatibleTypeConversion_1(bool value)
{
___useCompatibleTypeConversion_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPECONVERTER_T8306AE03734853B551DDF089C1F17836A7764DBB_H
#ifndef DELEGATE_T_H
#define DELEGATE_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Delegate
struct Delegate_t : public RuntimeObject
{
public:
// System.IntPtr System.Delegate::method_ptr
Il2CppMethodPointer ___method_ptr_0;
// System.IntPtr System.Delegate::invoke_impl
intptr_t ___invoke_impl_1;
// System.Object System.Delegate::m_target
RuntimeObject * ___m_target_2;
// System.IntPtr System.Delegate::method
intptr_t ___method_3;
// System.IntPtr System.Delegate::delegate_trampoline
intptr_t ___delegate_trampoline_4;
// System.IntPtr System.Delegate::extra_arg
intptr_t ___extra_arg_5;
// System.IntPtr System.Delegate::method_code
intptr_t ___method_code_6;
// System.Reflection.MethodInfo System.Delegate::method_info
MethodInfo_t * ___method_info_7;
// System.Reflection.MethodInfo System.Delegate::original_method_info
MethodInfo_t * ___original_method_info_8;
// System.DelegateData System.Delegate::data
DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * ___data_9;
// System.Boolean System.Delegate::method_is_virtual
bool ___method_is_virtual_10;
public:
inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_ptr_0)); }
inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }
inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }
inline void set_method_ptr_0(Il2CppMethodPointer value)
{
___method_ptr_0 = value;
}
inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t, ___invoke_impl_1)); }
inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }
inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }
inline void set_invoke_impl_1(intptr_t value)
{
___invoke_impl_1 = value;
}
inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t, ___m_target_2)); }
inline RuntimeObject * get_m_target_2() const { return ___m_target_2; }
inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }
inline void set_m_target_2(RuntimeObject * value)
{
___m_target_2 = value;
Il2CppCodeGenWriteBarrier((&___m_target_2), value);
}
inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_3)); }
inline intptr_t get_method_3() const { return ___method_3; }
inline intptr_t* get_address_of_method_3() { return &___method_3; }
inline void set_method_3(intptr_t value)
{
___method_3 = value;
}
inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t, ___delegate_trampoline_4)); }
inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }
inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }
inline void set_delegate_trampoline_4(intptr_t value)
{
___delegate_trampoline_4 = value;
}
inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t, ___extra_arg_5)); }
inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; }
inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; }
inline void set_extra_arg_5(intptr_t value)
{
___extra_arg_5 = value;
}
inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_code_6)); }
inline intptr_t get_method_code_6() const { return ___method_code_6; }
inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; }
inline void set_method_code_6(intptr_t value)
{
___method_code_6 = value;
}
inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_info_7)); }
inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; }
inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; }
inline void set_method_info_7(MethodInfo_t * value)
{
___method_info_7 = value;
Il2CppCodeGenWriteBarrier((&___method_info_7), value);
}
inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t, ___original_method_info_8)); }
inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; }
inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; }
inline void set_original_method_info_8(MethodInfo_t * value)
{
___original_method_info_8 = value;
Il2CppCodeGenWriteBarrier((&___original_method_info_8), value);
}
inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t, ___data_9)); }
inline DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * get_data_9() const { return ___data_9; }
inline DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE ** get_address_of_data_9() { return &___data_9; }
inline void set_data_9(DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * value)
{
___data_9 = value;
Il2CppCodeGenWriteBarrier((&___data_9), value);
}
inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_is_virtual_10)); }
inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; }
inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; }
inline void set_method_is_virtual_10(bool value)
{
___method_is_virtual_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Delegate
struct Delegate_t_marshaled_pinvoke
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
MethodInfo_t * ___method_info_7;
MethodInfo_t * ___original_method_info_8;
DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * ___data_9;
int32_t ___method_is_virtual_10;
};
// Native definition for COM marshalling of System.Delegate
struct Delegate_t_marshaled_com
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
MethodInfo_t * ___method_info_7;
MethodInfo_t * ___original_method_info_8;
DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * ___data_9;
int32_t ___method_is_virtual_10;
};
#endif // DELEGATE_T_H
#ifndef COMPRESSIONMODE_TA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C_H
#define COMPRESSIONMODE_TA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.CompressionMode
struct CompressionMode_tA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C
{
public:
// System.Int32 System.IO.Compression.CompressionMode::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(CompressionMode_tA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COMPRESSIONMODE_TA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C_H
#ifndef DEFLATESTREAMNATIVE_T7370A3BA77DBD70CCF3355B3862D101135D0F1DB_H
#define DEFLATESTREAMNATIVE_T7370A3BA77DBD70CCF3355B3862D101135D0F1DB_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.DeflateStreamNative
struct DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB : public RuntimeObject
{
public:
// System.IO.Compression.DeflateStreamNative_UnmanagedReadOrWrite System.IO.Compression.DeflateStreamNative::feeder
UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0 * ___feeder_0;
// System.IO.Stream System.IO.Compression.DeflateStreamNative::base_stream
Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * ___base_stream_1;
// System.IO.Compression.DeflateStreamNative_SafeDeflateStreamHandle System.IO.Compression.DeflateStreamNative::z_stream
SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959 * ___z_stream_2;
// System.Runtime.InteropServices.GCHandle System.IO.Compression.DeflateStreamNative::data
GCHandle_t39FAEE3EA592432C93B574A31DD83B87F1847DE3 ___data_3;
// System.Boolean System.IO.Compression.DeflateStreamNative::disposed
bool ___disposed_4;
// System.Byte[] System.IO.Compression.DeflateStreamNative::io_buffer
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___io_buffer_5;
public:
inline static int32_t get_offset_of_feeder_0() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB, ___feeder_0)); }
inline UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0 * get_feeder_0() const { return ___feeder_0; }
inline UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0 ** get_address_of_feeder_0() { return &___feeder_0; }
inline void set_feeder_0(UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0 * value)
{
___feeder_0 = value;
Il2CppCodeGenWriteBarrier((&___feeder_0), value);
}
inline static int32_t get_offset_of_base_stream_1() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB, ___base_stream_1)); }
inline Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * get_base_stream_1() const { return ___base_stream_1; }
inline Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 ** get_address_of_base_stream_1() { return &___base_stream_1; }
inline void set_base_stream_1(Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * value)
{
___base_stream_1 = value;
Il2CppCodeGenWriteBarrier((&___base_stream_1), value);
}
inline static int32_t get_offset_of_z_stream_2() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB, ___z_stream_2)); }
inline SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959 * get_z_stream_2() const { return ___z_stream_2; }
inline SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959 ** get_address_of_z_stream_2() { return &___z_stream_2; }
inline void set_z_stream_2(SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959 * value)
{
___z_stream_2 = value;
Il2CppCodeGenWriteBarrier((&___z_stream_2), value);
}
inline static int32_t get_offset_of_data_3() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB, ___data_3)); }
inline GCHandle_t39FAEE3EA592432C93B574A31DD83B87F1847DE3 get_data_3() const { return ___data_3; }
inline GCHandle_t39FAEE3EA592432C93B574A31DD83B87F1847DE3 * get_address_of_data_3() { return &___data_3; }
inline void set_data_3(GCHandle_t39FAEE3EA592432C93B574A31DD83B87F1847DE3 value)
{
___data_3 = value;
}
inline static int32_t get_offset_of_disposed_4() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB, ___disposed_4)); }
inline bool get_disposed_4() const { return ___disposed_4; }
inline bool* get_address_of_disposed_4() { return &___disposed_4; }
inline void set_disposed_4(bool value)
{
___disposed_4 = value;
}
inline static int32_t get_offset_of_io_buffer_5() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB, ___io_buffer_5)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_io_buffer_5() const { return ___io_buffer_5; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_io_buffer_5() { return &___io_buffer_5; }
inline void set_io_buffer_5(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___io_buffer_5 = value;
Il2CppCodeGenWriteBarrier((&___io_buffer_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFLATESTREAMNATIVE_T7370A3BA77DBD70CCF3355B3862D101135D0F1DB_H
#ifndef GZIPSTREAM_T8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588_H
#define GZIPSTREAM_T8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.GZipStream
struct GZipStream_t8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588 : public Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7
{
public:
// System.IO.Compression.DeflateStream System.IO.Compression.GZipStream::_deflateStream
DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE * ____deflateStream_4;
public:
inline static int32_t get_offset_of__deflateStream_4() { return static_cast<int32_t>(offsetof(GZipStream_t8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588, ____deflateStream_4)); }
inline DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE * get__deflateStream_4() const { return ____deflateStream_4; }
inline DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE ** get_address_of__deflateStream_4() { return &____deflateStream_4; }
inline void set__deflateStream_4(DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE * value)
{
____deflateStream_4 = value;
Il2CppCodeGenWriteBarrier((&____deflateStream_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GZIPSTREAM_T8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588_H
#ifndef SECURITYPROTOCOLTYPE_T5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941_H
#define SECURITYPROTOCOLTYPE_T5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Net.SecurityProtocolType
struct SecurityProtocolType_t5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941
{
public:
// System.Int32 System.Net.SecurityProtocolType::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SecurityProtocolType_t5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SECURITYPROTOCOLTYPE_T5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941_H
#ifndef EXTERNALEXCEPTION_T68841FD169C0CB00CC950EDA7E2A59540D65B1CE_H
#define EXTERNALEXCEPTION_T68841FD169C0CB00CC950EDA7E2A59540D65B1CE_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.InteropServices.ExternalException
struct ExternalException_t68841FD169C0CB00CC950EDA7E2A59540D65B1CE : public SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXTERNALEXCEPTION_T68841FD169C0CB00CC950EDA7E2A59540D65B1CE_H
#ifndef SAFEHANDLE_T1E326D75E23FD5BB6D40BA322298FDC6526CC383_H
#define SAFEHANDLE_T1E326D75E23FD5BB6D40BA322298FDC6526CC383_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.InteropServices.SafeHandle
struct SafeHandle_t1E326D75E23FD5BB6D40BA322298FDC6526CC383 : public CriticalFinalizerObject_t8B006E1DEE084E781F5C0F3283E9226E28894DD9
{
public:
// System.IntPtr System.Runtime.InteropServices.SafeHandle::handle
intptr_t ___handle_0;
// System.Int32 System.Runtime.InteropServices.SafeHandle::_state
int32_t ____state_1;
// System.Boolean System.Runtime.InteropServices.SafeHandle::_ownsHandle
bool ____ownsHandle_2;
// System.Boolean System.Runtime.InteropServices.SafeHandle::_fullyInitialized
bool ____fullyInitialized_3;
public:
inline static int32_t get_offset_of_handle_0() { return static_cast<int32_t>(offsetof(SafeHandle_t1E326D75E23FD5BB6D40BA322298FDC6526CC383, ___handle_0)); }
inline intptr_t get_handle_0() const { return ___handle_0; }
inline intptr_t* get_address_of_handle_0() { return &___handle_0; }
inline void set_handle_0(intptr_t value)
{
___handle_0 = value;
}
inline static int32_t get_offset_of__state_1() { return static_cast<int32_t>(offsetof(SafeHandle_t1E326D75E23FD5BB6D40BA322298FDC6526CC383, ____state_1)); }
inline int32_t get__state_1() const { return ____state_1; }
inline int32_t* get_address_of__state_1() { return &____state_1; }
inline void set__state_1(int32_t value)
{
____state_1 = value;
}
inline static int32_t get_offset_of__ownsHandle_2() { return static_cast<int32_t>(offsetof(SafeHandle_t1E326D75E23FD5BB6D40BA322298FDC6526CC383, ____ownsHandle_2)); }
inline bool get__ownsHandle_2() const { return ____ownsHandle_2; }
inline bool* get_address_of__ownsHandle_2() { return &____ownsHandle_2; }
inline void set__ownsHandle_2(bool value)
{
____ownsHandle_2 = value;
}
inline static int32_t get_offset_of__fullyInitialized_3() { return static_cast<int32_t>(offsetof(SafeHandle_t1E326D75E23FD5BB6D40BA322298FDC6526CC383, ____fullyInitialized_3)); }
inline bool get__fullyInitialized_3() const { return ____fullyInitialized_3; }
inline bool* get_address_of__fullyInitialized_3() { return &____fullyInitialized_3; }
inline void set__fullyInitialized_3(bool value)
{
____fullyInitialized_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SAFEHANDLE_T1E326D75E23FD5BB6D40BA322298FDC6526CC383_H
#ifndef AUTHENTICATIONEXCEPTION_TE24BF2E2AD351F0C9586A59191F01918659A7516_H
#define AUTHENTICATIONEXCEPTION_TE24BF2E2AD351F0C9586A59191F01918659A7516_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Authentication.AuthenticationException
struct AuthenticationException_tE24BF2E2AD351F0C9586A59191F01918659A7516 : public SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AUTHENTICATIONEXCEPTION_TE24BF2E2AD351F0C9586A59191F01918659A7516_H
#ifndef SSLPROTOCOLS_TDD37F8F06AD19BDAF27AEA484EC06820FE3107AE_H
#define SSLPROTOCOLS_TDD37F8F06AD19BDAF27AEA484EC06820FE3107AE_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Authentication.SslProtocols
struct SslProtocols_tDD37F8F06AD19BDAF27AEA484EC06820FE3107AE
{
public:
// System.Int32 System.Security.Authentication.SslProtocols::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SslProtocols_tDD37F8F06AD19BDAF27AEA484EC06820FE3107AE, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SSLPROTOCOLS_TDD37F8F06AD19BDAF27AEA484EC06820FE3107AE_H
#ifndef ASNDECODESTATUS_T83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB_H
#define ASNDECODESTATUS_T83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AsnDecodeStatus
struct AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB
{
public:
// System.Int32 System.Security.Cryptography.AsnDecodeStatus::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ASNDECODESTATUS_T83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB_H
#ifndef OIDGROUP_T9A99D3013C1B94CB060656F30C39E893E75FAD6B_H
#define OIDGROUP_T9A99D3013C1B94CB060656F30C39E893E75FAD6B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.OidGroup
struct OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B
{
public:
// System.Int32 System.Security.Cryptography.OidGroup::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OIDGROUP_T9A99D3013C1B94CB060656F30C39E893E75FAD6B_H
#ifndef STORELOCATION_T5610361F4E31C5B2B42EE424C3E136BE2CA4C830_H
#define STORELOCATION_T5610361F4E31C5B2B42EE424C3E136BE2CA4C830_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.StoreLocation
struct StoreLocation_t5610361F4E31C5B2B42EE424C3E136BE2CA4C830
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.StoreLocation::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(StoreLocation_t5610361F4E31C5B2B42EE424C3E136BE2CA4C830, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STORELOCATION_T5610361F4E31C5B2B42EE424C3E136BE2CA4C830_H
#ifndef X509CERTIFICATE2COLLECTION_T14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_H
#define X509CERTIFICATE2COLLECTION_T14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Certificate2Collection
struct X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D : public X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833
{
public:
public:
};
struct X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_StaticFields
{
public:
// System.String[] System.Security.Cryptography.X509Certificates.X509Certificate2Collection::newline_split
StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* ___newline_split_1;
public:
inline static int32_t get_offset_of_newline_split_1() { return static_cast<int32_t>(offsetof(X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_StaticFields, ___newline_split_1)); }
inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* get_newline_split_1() const { return ___newline_split_1; }
inline StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E** get_address_of_newline_split_1() { return &___newline_split_1; }
inline void set_newline_split_1(StringU5BU5D_t933FB07893230EA91C40FF900D5400665E87B14E* value)
{
___newline_split_1 = value;
Il2CppCodeGenWriteBarrier((&___newline_split_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATE2COLLECTION_T14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_H
#ifndef X509CERTIFICATE2IMPLMONO_T3A65BD83268B651BCBE65CFB3691FB85401A91A5_H
#define X509CERTIFICATE2IMPLMONO_T3A65BD83268B651BCBE65CFB3691FB85401A91A5_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono
struct X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5 : public X509Certificate2Impl_t645108014422F6408EB87390317CD10710F129E7
{
public:
// System.Boolean System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::_archived
bool ____archived_1;
// System.Security.Cryptography.X509Certificates.X509ExtensionCollection System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::_extensions
X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F * ____extensions_2;
// System.Security.Cryptography.X509Certificates.PublicKey System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::_publicKey
PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620 * ____publicKey_3;
// System.Security.Cryptography.X509Certificates.X500DistinguishedName System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::issuer_name
X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 * ___issuer_name_4;
// System.Security.Cryptography.X509Certificates.X500DistinguishedName System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::subject_name
X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 * ___subject_name_5;
// System.Security.Cryptography.Oid System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::signature_algorithm
Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * ___signature_algorithm_6;
// System.Security.Cryptography.X509Certificates.X509CertificateImplCollection System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::intermediateCerts
X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242 * ___intermediateCerts_7;
// Mono.Security.X509.X509Certificate System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::_cert
X509Certificate_t592E2574612B2C554C7B707754AEC3B66A4B476B * ____cert_8;
public:
inline static int32_t get_offset_of__archived_1() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ____archived_1)); }
inline bool get__archived_1() const { return ____archived_1; }
inline bool* get_address_of__archived_1() { return &____archived_1; }
inline void set__archived_1(bool value)
{
____archived_1 = value;
}
inline static int32_t get_offset_of__extensions_2() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ____extensions_2)); }
inline X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F * get__extensions_2() const { return ____extensions_2; }
inline X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F ** get_address_of__extensions_2() { return &____extensions_2; }
inline void set__extensions_2(X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F * value)
{
____extensions_2 = value;
Il2CppCodeGenWriteBarrier((&____extensions_2), value);
}
inline static int32_t get_offset_of__publicKey_3() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ____publicKey_3)); }
inline PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620 * get__publicKey_3() const { return ____publicKey_3; }
inline PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620 ** get_address_of__publicKey_3() { return &____publicKey_3; }
inline void set__publicKey_3(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620 * value)
{
____publicKey_3 = value;
Il2CppCodeGenWriteBarrier((&____publicKey_3), value);
}
inline static int32_t get_offset_of_issuer_name_4() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ___issuer_name_4)); }
inline X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 * get_issuer_name_4() const { return ___issuer_name_4; }
inline X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 ** get_address_of_issuer_name_4() { return &___issuer_name_4; }
inline void set_issuer_name_4(X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 * value)
{
___issuer_name_4 = value;
Il2CppCodeGenWriteBarrier((&___issuer_name_4), value);
}
inline static int32_t get_offset_of_subject_name_5() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ___subject_name_5)); }
inline X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 * get_subject_name_5() const { return ___subject_name_5; }
inline X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 ** get_address_of_subject_name_5() { return &___subject_name_5; }
inline void set_subject_name_5(X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199 * value)
{
___subject_name_5 = value;
Il2CppCodeGenWriteBarrier((&___subject_name_5), value);
}
inline static int32_t get_offset_of_signature_algorithm_6() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ___signature_algorithm_6)); }
inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * get_signature_algorithm_6() const { return ___signature_algorithm_6; }
inline Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 ** get_address_of_signature_algorithm_6() { return &___signature_algorithm_6; }
inline void set_signature_algorithm_6(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 * value)
{
___signature_algorithm_6 = value;
Il2CppCodeGenWriteBarrier((&___signature_algorithm_6), value);
}
inline static int32_t get_offset_of_intermediateCerts_7() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ___intermediateCerts_7)); }
inline X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242 * get_intermediateCerts_7() const { return ___intermediateCerts_7; }
inline X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242 ** get_address_of_intermediateCerts_7() { return &___intermediateCerts_7; }
inline void set_intermediateCerts_7(X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242 * value)
{
___intermediateCerts_7 = value;
Il2CppCodeGenWriteBarrier((&___intermediateCerts_7), value);
}
inline static int32_t get_offset_of__cert_8() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5, ____cert_8)); }
inline X509Certificate_t592E2574612B2C554C7B707754AEC3B66A4B476B * get__cert_8() const { return ____cert_8; }
inline X509Certificate_t592E2574612B2C554C7B707754AEC3B66A4B476B ** get_address_of__cert_8() { return &____cert_8; }
inline void set__cert_8(X509Certificate_t592E2574612B2C554C7B707754AEC3B66A4B476B * value)
{
____cert_8 = value;
Il2CppCodeGenWriteBarrier((&____cert_8), value);
}
};
struct X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields
{
public:
// System.String System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::empty_error
String_t* ___empty_error_9;
// System.Byte[] System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::commonName
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___commonName_10;
// System.Byte[] System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::email
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___email_11;
// System.Byte[] System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono::signedData
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ___signedData_12;
public:
inline static int32_t get_offset_of_empty_error_9() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields, ___empty_error_9)); }
inline String_t* get_empty_error_9() const { return ___empty_error_9; }
inline String_t** get_address_of_empty_error_9() { return &___empty_error_9; }
inline void set_empty_error_9(String_t* value)
{
___empty_error_9 = value;
Il2CppCodeGenWriteBarrier((&___empty_error_9), value);
}
inline static int32_t get_offset_of_commonName_10() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields, ___commonName_10)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_commonName_10() const { return ___commonName_10; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_commonName_10() { return &___commonName_10; }
inline void set_commonName_10(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___commonName_10 = value;
Il2CppCodeGenWriteBarrier((&___commonName_10), value);
}
inline static int32_t get_offset_of_email_11() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields, ___email_11)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_email_11() const { return ___email_11; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_email_11() { return &___email_11; }
inline void set_email_11(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___email_11 = value;
Il2CppCodeGenWriteBarrier((&___email_11), value);
}
inline static int32_t get_offset_of_signedData_12() { return static_cast<int32_t>(offsetof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields, ___signedData_12)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get_signedData_12() const { return ___signedData_12; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of_signedData_12() { return &___signedData_12; }
inline void set_signedData_12(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
___signedData_12 = value;
Il2CppCodeGenWriteBarrier((&___signedData_12), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CERTIFICATE2IMPLMONO_T3A65BD83268B651BCBE65CFB3691FB85401A91A5_H
#ifndef X509CHAINSTATUSFLAGS_T208E1E90A6014521B09653B6B237D045A8573E5B_H
#define X509CHAINSTATUSFLAGS_T208E1E90A6014521B09653B6B237D045A8573E5B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainStatusFlags
struct X509ChainStatusFlags_t208E1E90A6014521B09653B6B237D045A8573E5B
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509ChainStatusFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509ChainStatusFlags_t208E1E90A6014521B09653B6B237D045A8573E5B, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINSTATUSFLAGS_T208E1E90A6014521B09653B6B237D045A8573E5B_H
#ifndef X509KEYUSAGEFLAGS_TAD6560EDDEB746BA983AE4E7ABC237A6178D6437_H
#define X509KEYUSAGEFLAGS_TAD6560EDDEB746BA983AE4E7ABC237A6178D6437_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509KeyUsageFlags
struct X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509KeyUsageFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509KEYUSAGEFLAGS_TAD6560EDDEB746BA983AE4E7ABC237A6178D6437_H
#ifndef X509REVOCATIONFLAG_T8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A_H
#define X509REVOCATIONFLAG_T8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509RevocationFlag
struct X509RevocationFlag_t8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509RevocationFlag::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509RevocationFlag_t8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509REVOCATIONFLAG_T8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A_H
#ifndef X509REVOCATIONMODE_TEFEA8C7147423CC3363A4AF504853BD054A33BE7_H
#define X509REVOCATIONMODE_TEFEA8C7147423CC3363A4AF504853BD054A33BE7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509RevocationMode
struct X509RevocationMode_tEFEA8C7147423CC3363A4AF504853BD054A33BE7
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509RevocationMode::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509RevocationMode_tEFEA8C7147423CC3363A4AF504853BD054A33BE7, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509REVOCATIONMODE_TEFEA8C7147423CC3363A4AF504853BD054A33BE7_H
#ifndef X509SUBJECTKEYIDENTIFIERHASHALGORITHM_T7928324BFDBB7B255970D50D0D8972FDFC981A0C_H
#define X509SUBJECTKEYIDENTIFIERHASHALGORITHM_T7928324BFDBB7B255970D50D0D8972FDFC981A0C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm
struct X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509SUBJECTKEYIDENTIFIERHASHALGORITHM_T7928324BFDBB7B255970D50D0D8972FDFC981A0C_H
#ifndef X509VERIFICATIONFLAGS_T145010CF6C45EE6563E0874B82C2555025F7A20B_H
#define X509VERIFICATIONFLAGS_T145010CF6C45EE6563E0874B82C2555025F7A20B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509VerificationFlags
struct X509VerificationFlags_t145010CF6C45EE6563E0874B82C2555025F7A20B
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509VerificationFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509VerificationFlags_t145010CF6C45EE6563E0874B82C2555025F7A20B, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509VERIFICATIONFLAGS_T145010CF6C45EE6563E0874B82C2555025F7A20B_H
#ifndef TIMESPAN_TA8069278ACE8A74D6DF7D514A9CD4432433F64C4_H
#define TIMESPAN_TA8069278ACE8A74D6DF7D514A9CD4432433F64C4_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.TimeSpan
struct TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4
{
public:
// System.Int64 System.TimeSpan::_ticks
int64_t ____ticks_3;
public:
inline static int32_t get_offset_of__ticks_3() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4, ____ticks_3)); }
inline int64_t get__ticks_3() const { return ____ticks_3; }
inline int64_t* get_address_of__ticks_3() { return &____ticks_3; }
inline void set__ticks_3(int64_t value)
{
____ticks_3 = value;
}
};
struct TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields
{
public:
// System.TimeSpan System.TimeSpan::Zero
TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___Zero_0;
// System.TimeSpan System.TimeSpan::MaxValue
TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___MaxValue_1;
// System.TimeSpan System.TimeSpan::MinValue
TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___MinValue_2;
// System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyConfigChecked
bool ____legacyConfigChecked_4;
// System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyMode
bool ____legacyMode_5;
public:
inline static int32_t get_offset_of_Zero_0() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ___Zero_0)); }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_Zero_0() const { return ___Zero_0; }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_Zero_0() { return &___Zero_0; }
inline void set_Zero_0(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value)
{
___Zero_0 = value;
}
inline static int32_t get_offset_of_MaxValue_1() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ___MaxValue_1)); }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_MaxValue_1() const { return ___MaxValue_1; }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_MaxValue_1() { return &___MaxValue_1; }
inline void set_MaxValue_1(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value)
{
___MaxValue_1 = value;
}
inline static int32_t get_offset_of_MinValue_2() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ___MinValue_2)); }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_MinValue_2() const { return ___MinValue_2; }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_MinValue_2() { return &___MinValue_2; }
inline void set_MinValue_2(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value)
{
___MinValue_2 = value;
}
inline static int32_t get_offset_of__legacyConfigChecked_4() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ____legacyConfigChecked_4)); }
inline bool get__legacyConfigChecked_4() const { return ____legacyConfigChecked_4; }
inline bool* get_address_of__legacyConfigChecked_4() { return &____legacyConfigChecked_4; }
inline void set__legacyConfigChecked_4(bool value)
{
____legacyConfigChecked_4 = value;
}
inline static int32_t get_offset_of__legacyMode_5() { return static_cast<int32_t>(offsetof(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4_StaticFields, ____legacyMode_5)); }
inline bool get__legacyMode_5() const { return ____legacyMode_5; }
inline bool* get_address_of__legacyMode_5() { return &____legacyMode_5; }
inline void set__legacyMode_5(bool value)
{
____legacyMode_5 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TIMESPAN_TA8069278ACE8A74D6DF7D514A9CD4432433F64C4_H
#ifndef BASENUMBERCONVERTER_T6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63_H
#define BASENUMBERCONVERTER_T6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.BaseNumberConverter
struct BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BASENUMBERCONVERTER_T6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63_H
#ifndef BOOLEANCONVERTER_TD0D177A9F577915FAA9F6749229672CE8EBAA94C_H
#define BOOLEANCONVERTER_TD0D177A9F577915FAA9F6749229672CE8EBAA94C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.BooleanConverter
struct BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
public:
};
struct BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields
{
public:
// System.ComponentModel.TypeConverter_StandardValuesCollection modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.BooleanConverter::values
StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * ___values_2;
public:
inline static int32_t get_offset_of_values_2() { return static_cast<int32_t>(offsetof(BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields, ___values_2)); }
inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * get_values_2() const { return ___values_2; }
inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 ** get_address_of_values_2() { return &___values_2; }
inline void set_values_2(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * value)
{
___values_2 = value;
Il2CppCodeGenWriteBarrier((&___values_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEANCONVERTER_TD0D177A9F577915FAA9F6749229672CE8EBAA94C_H
#ifndef COLLECTIONCONVERTER_T039E15C433996B0F0F0EB78BEE81F6DE0705F184_H
#define COLLECTIONCONVERTER_T039E15C433996B0F0F0EB78BEE81F6DE0705F184_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.CollectionConverter
struct CollectionConverter_t039E15C433996B0F0F0EB78BEE81F6DE0705F184 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COLLECTIONCONVERTER_T039E15C433996B0F0F0EB78BEE81F6DE0705F184_H
#ifndef DESIGNERSERIALIZATIONVISIBILITYATTRIBUTE_TC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_H
#define DESIGNERSERIALIZATIONVISIBILITYATTRIBUTE_TC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerSerializationVisibilityAttribute
struct DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.ComponentModel.DesignerSerializationVisibility System.ComponentModel.DesignerSerializationVisibilityAttribute::visibility
int32_t ___visibility_4;
public:
inline static int32_t get_offset_of_visibility_4() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA, ___visibility_4)); }
inline int32_t get_visibility_4() const { return ___visibility_4; }
inline int32_t* get_address_of_visibility_4() { return &___visibility_4; }
inline void set_visibility_4(int32_t value)
{
___visibility_4 = value;
}
};
struct DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields
{
public:
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Content
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * ___Content_0;
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Hidden
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * ___Hidden_1;
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Visible
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * ___Visible_2;
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Default
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * ___Default_3;
public:
inline static int32_t get_offset_of_Content_0() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields, ___Content_0)); }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * get_Content_0() const { return ___Content_0; }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA ** get_address_of_Content_0() { return &___Content_0; }
inline void set_Content_0(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * value)
{
___Content_0 = value;
Il2CppCodeGenWriteBarrier((&___Content_0), value);
}
inline static int32_t get_offset_of_Hidden_1() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields, ___Hidden_1)); }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * get_Hidden_1() const { return ___Hidden_1; }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA ** get_address_of_Hidden_1() { return &___Hidden_1; }
inline void set_Hidden_1(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * value)
{
___Hidden_1 = value;
Il2CppCodeGenWriteBarrier((&___Hidden_1), value);
}
inline static int32_t get_offset_of_Visible_2() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields, ___Visible_2)); }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * get_Visible_2() const { return ___Visible_2; }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA ** get_address_of_Visible_2() { return &___Visible_2; }
inline void set_Visible_2(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * value)
{
___Visible_2 = value;
Il2CppCodeGenWriteBarrier((&___Visible_2), value);
}
inline static int32_t get_offset_of_Default_3() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields, ___Default_3)); }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * get_Default_3() const { return ___Default_3; }
inline DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA ** get_address_of_Default_3() { return &___Default_3; }
inline void set_Default_3(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA * value)
{
___Default_3 = value;
Il2CppCodeGenWriteBarrier((&___Default_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERSERIALIZATIONVISIBILITYATTRIBUTE_TC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_H
#ifndef EDITORBROWSABLEATTRIBUTE_TF3507DF0AB82A8D54C70D6F7FB4D363DF729D516_H
#define EDITORBROWSABLEATTRIBUTE_TF3507DF0AB82A8D54C70D6F7FB4D363DF729D516_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EditorBrowsableAttribute
struct EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516 : public Attribute_tF048C13FB3C8CFCC53F82290E4A3F621089F9A74
{
public:
// System.ComponentModel.EditorBrowsableState System.ComponentModel.EditorBrowsableAttribute::browsableState
int32_t ___browsableState_0;
public:
inline static int32_t get_offset_of_browsableState_0() { return static_cast<int32_t>(offsetof(EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516, ___browsableState_0)); }
inline int32_t get_browsableState_0() const { return ___browsableState_0; }
inline int32_t* get_address_of_browsableState_0() { return &___browsableState_0; }
inline void set_browsableState_0(int32_t value)
{
___browsableState_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EDITORBROWSABLEATTRIBUTE_TF3507DF0AB82A8D54C70D6F7FB4D363DF729D516_H
#ifndef ENUMCONVERTER_T5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12_H
#define ENUMCONVERTER_T5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EnumConverter
struct EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
// System.ComponentModel.TypeConverter_StandardValuesCollection System.ComponentModel.EnumConverter::values
StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * ___values_2;
// System.Type System.ComponentModel.EnumConverter::type
Type_t * ___type_3;
public:
inline static int32_t get_offset_of_values_2() { return static_cast<int32_t>(offsetof(EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12, ___values_2)); }
inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * get_values_2() const { return ___values_2; }
inline StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 ** get_address_of_values_2() { return &___values_2; }
inline void set_values_2(StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3 * value)
{
___values_2 = value;
Il2CppCodeGenWriteBarrier((&___values_2), value);
}
inline static int32_t get_offset_of_type_3() { return static_cast<int32_t>(offsetof(EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12, ___type_3)); }
inline Type_t * get_type_3() const { return ___type_3; }
inline Type_t ** get_address_of_type_3() { return &___type_3; }
inline void set_type_3(Type_t * value)
{
___type_3 = value;
Il2CppCodeGenWriteBarrier((&___type_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ENUMCONVERTER_T5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12_H
#ifndef REFERENCECONVERTER_T5080472EE999A1F00721E6C5C97013762C85C7E4_H
#define REFERENCECONVERTER_T5080472EE999A1F00721E6C5C97013762C85C7E4_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ReferenceConverter
struct ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
public:
};
struct ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4_StaticFields
{
public:
// System.String System.ComponentModel.ReferenceConverter::none
String_t* ___none_2;
public:
inline static int32_t get_offset_of_none_2() { return static_cast<int32_t>(offsetof(ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4_StaticFields, ___none_2)); }
inline String_t* get_none_2() const { return ___none_2; }
inline String_t** get_address_of_none_2() { return &___none_2; }
inline void set_none_2(String_t* value)
{
___none_2 = value;
Il2CppCodeGenWriteBarrier((&___none_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFERENCECONVERTER_T5080472EE999A1F00721E6C5C97013762C85C7E4_H
#ifndef STRINGCONVERTER_T054FA0796F4C8E951208AFA052D99BCB8E68BED7_H
#define STRINGCONVERTER_T054FA0796F4C8E951208AFA052D99BCB8E68BED7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.StringConverter
struct StringConverter_t054FA0796F4C8E951208AFA052D99BCB8E68BED7 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRINGCONVERTER_T054FA0796F4C8E951208AFA052D99BCB8E68BED7_H
#ifndef TIMESPANCONVERTER_T4025A0861C52420BC73D837729E5EFA6ECDE07C7_H
#define TIMESPANCONVERTER_T4025A0861C52420BC73D837729E5EFA6ECDE07C7_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TimeSpanConverter
struct TimeSpanConverter_t4025A0861C52420BC73D837729E5EFA6ECDE07C7 : public TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TIMESPANCONVERTER_T4025A0861C52420BC73D837729E5EFA6ECDE07C7_H
#ifndef WIN32EXCEPTION_TB05BE97AB4CADD54DF96C0109689F0ECA7517668_H
#define WIN32EXCEPTION_TB05BE97AB4CADD54DF96C0109689F0ECA7517668_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Win32Exception
struct Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668 : public ExternalException_t68841FD169C0CB00CC950EDA7E2A59540D65B1CE
{
public:
// System.Int32 System.ComponentModel.Win32Exception::nativeErrorCode
int32_t ___nativeErrorCode_17;
public:
inline static int32_t get_offset_of_nativeErrorCode_17() { return static_cast<int32_t>(offsetof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668, ___nativeErrorCode_17)); }
inline int32_t get_nativeErrorCode_17() const { return ___nativeErrorCode_17; }
inline int32_t* get_address_of_nativeErrorCode_17() { return &___nativeErrorCode_17; }
inline void set_nativeErrorCode_17(int32_t value)
{
___nativeErrorCode_17 = value;
}
};
struct Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields
{
public:
// System.Boolean System.ComponentModel.Win32Exception::s_ErrorMessagesInitialized
bool ___s_ErrorMessagesInitialized_18;
// System.Collections.Generic.Dictionary`2<System.Int32,System.String> System.ComponentModel.Win32Exception::s_ErrorMessage
Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C * ___s_ErrorMessage_19;
public:
inline static int32_t get_offset_of_s_ErrorMessagesInitialized_18() { return static_cast<int32_t>(offsetof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields, ___s_ErrorMessagesInitialized_18)); }
inline bool get_s_ErrorMessagesInitialized_18() const { return ___s_ErrorMessagesInitialized_18; }
inline bool* get_address_of_s_ErrorMessagesInitialized_18() { return &___s_ErrorMessagesInitialized_18; }
inline void set_s_ErrorMessagesInitialized_18(bool value)
{
___s_ErrorMessagesInitialized_18 = value;
}
inline static int32_t get_offset_of_s_ErrorMessage_19() { return static_cast<int32_t>(offsetof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields, ___s_ErrorMessage_19)); }
inline Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C * get_s_ErrorMessage_19() const { return ___s_ErrorMessage_19; }
inline Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C ** get_address_of_s_ErrorMessage_19() { return &___s_ErrorMessage_19; }
inline void set_s_ErrorMessage_19(Dictionary_2_t4EFE6A1D6502662B911688316C6920444A18CF0C * value)
{
___s_ErrorMessage_19 = value;
Il2CppCodeGenWriteBarrier((&___s_ErrorMessage_19), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WIN32EXCEPTION_TB05BE97AB4CADD54DF96C0109689F0ECA7517668_H
#ifndef DEFLATESTREAM_T31630A254BA2F3626DA55B570FE488DFF4A227FE_H
#define DEFLATESTREAM_T31630A254BA2F3626DA55B570FE488DFF4A227FE_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.DeflateStream
struct DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE : public Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7
{
public:
// System.IO.Stream System.IO.Compression.DeflateStream::base_stream
Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * ___base_stream_4;
// System.IO.Compression.CompressionMode System.IO.Compression.DeflateStream::mode
int32_t ___mode_5;
// System.Boolean System.IO.Compression.DeflateStream::leaveOpen
bool ___leaveOpen_6;
// System.Boolean System.IO.Compression.DeflateStream::disposed
bool ___disposed_7;
// System.IO.Compression.DeflateStreamNative System.IO.Compression.DeflateStream::native
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB * ___native_8;
public:
inline static int32_t get_offset_of_base_stream_4() { return static_cast<int32_t>(offsetof(DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE, ___base_stream_4)); }
inline Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * get_base_stream_4() const { return ___base_stream_4; }
inline Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 ** get_address_of_base_stream_4() { return &___base_stream_4; }
inline void set_base_stream_4(Stream_tFC50657DD5AAB87770987F9179D934A51D99D5E7 * value)
{
___base_stream_4 = value;
Il2CppCodeGenWriteBarrier((&___base_stream_4), value);
}
inline static int32_t get_offset_of_mode_5() { return static_cast<int32_t>(offsetof(DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE, ___mode_5)); }
inline int32_t get_mode_5() const { return ___mode_5; }
inline int32_t* get_address_of_mode_5() { return &___mode_5; }
inline void set_mode_5(int32_t value)
{
___mode_5 = value;
}
inline static int32_t get_offset_of_leaveOpen_6() { return static_cast<int32_t>(offsetof(DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE, ___leaveOpen_6)); }
inline bool get_leaveOpen_6() const { return ___leaveOpen_6; }
inline bool* get_address_of_leaveOpen_6() { return &___leaveOpen_6; }
inline void set_leaveOpen_6(bool value)
{
___leaveOpen_6 = value;
}
inline static int32_t get_offset_of_disposed_7() { return static_cast<int32_t>(offsetof(DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE, ___disposed_7)); }
inline bool get_disposed_7() const { return ___disposed_7; }
inline bool* get_address_of_disposed_7() { return &___disposed_7; }
inline void set_disposed_7(bool value)
{
___disposed_7 = value;
}
inline static int32_t get_offset_of_native_8() { return static_cast<int32_t>(offsetof(DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE, ___native_8)); }
inline DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB * get_native_8() const { return ___native_8; }
inline DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB ** get_address_of_native_8() { return &___native_8; }
inline void set_native_8(DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB * value)
{
___native_8 = value;
Il2CppCodeGenWriteBarrier((&___native_8), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFLATESTREAM_T31630A254BA2F3626DA55B570FE488DFF4A227FE_H
#ifndef SAFEDEFLATESTREAMHANDLE_TE4BC64B6A6597FD38FC9B774F01C4D1EC7464959_H
#define SAFEDEFLATESTREAMHANDLE_TE4BC64B6A6597FD38FC9B774F01C4D1EC7464959_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.DeflateStreamNative_SafeDeflateStreamHandle
struct SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959 : public SafeHandle_t1E326D75E23FD5BB6D40BA322298FDC6526CC383
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SAFEDEFLATESTREAMHANDLE_TE4BC64B6A6597FD38FC9B774F01C4D1EC7464959_H
#ifndef MULTICASTDELEGATE_T_H
#define MULTICASTDELEGATE_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.MulticastDelegate
struct MulticastDelegate_t : public Delegate_t
{
public:
// System.Delegate[] System.MulticastDelegate::delegates
DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* ___delegates_11;
public:
inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); }
inline DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* get_delegates_11() const { return ___delegates_11; }
inline DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86** get_address_of_delegates_11() { return &___delegates_11; }
inline void set_delegates_11(DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* value)
{
___delegates_11 = value;
Il2CppCodeGenWriteBarrier((&___delegates_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.MulticastDelegate
struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t_marshaled_pinvoke
{
Delegate_t_marshaled_pinvoke** ___delegates_11;
};
// Native definition for COM marshalling of System.MulticastDelegate
struct MulticastDelegate_t_marshaled_com : public Delegate_t_marshaled_com
{
Delegate_t_marshaled_com** ___delegates_11;
};
#endif // MULTICASTDELEGATE_T_H
#ifndef OID_TC00A10270EAF16BBF0F2619B9AEC883E0CFE6137_H
#define OID_TC00A10270EAF16BBF0F2619B9AEC883E0CFE6137_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.Oid
struct Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137 : public RuntimeObject
{
public:
// System.String System.Security.Cryptography.Oid::m_value
String_t* ___m_value_0;
// System.String System.Security.Cryptography.Oid::m_friendlyName
String_t* ___m_friendlyName_1;
// System.Security.Cryptography.OidGroup System.Security.Cryptography.Oid::m_group
int32_t ___m_group_2;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137, ___m_value_0)); }
inline String_t* get_m_value_0() const { return ___m_value_0; }
inline String_t** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(String_t* value)
{
___m_value_0 = value;
Il2CppCodeGenWriteBarrier((&___m_value_0), value);
}
inline static int32_t get_offset_of_m_friendlyName_1() { return static_cast<int32_t>(offsetof(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137, ___m_friendlyName_1)); }
inline String_t* get_m_friendlyName_1() const { return ___m_friendlyName_1; }
inline String_t** get_address_of_m_friendlyName_1() { return &___m_friendlyName_1; }
inline void set_m_friendlyName_1(String_t* value)
{
___m_friendlyName_1 = value;
Il2CppCodeGenWriteBarrier((&___m_friendlyName_1), value);
}
inline static int32_t get_offset_of_m_group_2() { return static_cast<int32_t>(offsetof(Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137, ___m_group_2)); }
inline int32_t get_m_group_2() const { return ___m_group_2; }
inline int32_t* get_address_of_m_group_2() { return &___m_group_2; }
inline void set_m_group_2(int32_t value)
{
___m_group_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OID_TC00A10270EAF16BBF0F2619B9AEC883E0CFE6137_H
#ifndef X509BASICCONSTRAINTSEXTENSION_T091983B3CDCB686781B4853177610A22483B532C_H
#define X509BASICCONSTRAINTSEXTENSION_T091983B3CDCB686781B4853177610A22483B532C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension
struct X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A
{
public:
// System.Boolean System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_certificateAuthority
bool ____certificateAuthority_5;
// System.Boolean System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_hasPathLengthConstraint
bool ____hasPathLengthConstraint_6;
// System.Int32 System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_pathLengthConstraint
int32_t ____pathLengthConstraint_7;
// System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension::_status
int32_t ____status_8;
public:
inline static int32_t get_offset_of__certificateAuthority_5() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____certificateAuthority_5)); }
inline bool get__certificateAuthority_5() const { return ____certificateAuthority_5; }
inline bool* get_address_of__certificateAuthority_5() { return &____certificateAuthority_5; }
inline void set__certificateAuthority_5(bool value)
{
____certificateAuthority_5 = value;
}
inline static int32_t get_offset_of__hasPathLengthConstraint_6() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____hasPathLengthConstraint_6)); }
inline bool get__hasPathLengthConstraint_6() const { return ____hasPathLengthConstraint_6; }
inline bool* get_address_of__hasPathLengthConstraint_6() { return &____hasPathLengthConstraint_6; }
inline void set__hasPathLengthConstraint_6(bool value)
{
____hasPathLengthConstraint_6 = value;
}
inline static int32_t get_offset_of__pathLengthConstraint_7() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____pathLengthConstraint_7)); }
inline int32_t get__pathLengthConstraint_7() const { return ____pathLengthConstraint_7; }
inline int32_t* get_address_of__pathLengthConstraint_7() { return &____pathLengthConstraint_7; }
inline void set__pathLengthConstraint_7(int32_t value)
{
____pathLengthConstraint_7 = value;
}
inline static int32_t get_offset_of__status_8() { return static_cast<int32_t>(offsetof(X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C, ____status_8)); }
inline int32_t get__status_8() const { return ____status_8; }
inline int32_t* get_address_of__status_8() { return &____status_8; }
inline void set__status_8(int32_t value)
{
____status_8 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509BASICCONSTRAINTSEXTENSION_T091983B3CDCB686781B4853177610A22483B532C_H
#ifndef X509CHAINIMPLMONO_T38D97B22EAE940C6D941DB58282503264F19FA9D_H
#define X509CHAINIMPLMONO_T38D97B22EAE940C6D941DB58282503264F19FA9D_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainImplMono
struct X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D : public X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67
{
public:
// System.Security.Cryptography.X509Certificates.StoreLocation System.Security.Cryptography.X509Certificates.X509ChainImplMono::location
int32_t ___location_0;
// System.Security.Cryptography.X509Certificates.X509ChainElementCollection System.Security.Cryptography.X509Certificates.X509ChainImplMono::elements
X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4 * ___elements_1;
// System.Security.Cryptography.X509Certificates.X509ChainPolicy System.Security.Cryptography.X509Certificates.X509ChainImplMono::policy
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD * ___policy_2;
public:
inline static int32_t get_offset_of_location_0() { return static_cast<int32_t>(offsetof(X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D, ___location_0)); }
inline int32_t get_location_0() const { return ___location_0; }
inline int32_t* get_address_of_location_0() { return &___location_0; }
inline void set_location_0(int32_t value)
{
___location_0 = value;
}
inline static int32_t get_offset_of_elements_1() { return static_cast<int32_t>(offsetof(X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D, ___elements_1)); }
inline X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4 * get_elements_1() const { return ___elements_1; }
inline X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4 ** get_address_of_elements_1() { return &___elements_1; }
inline void set_elements_1(X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4 * value)
{
___elements_1 = value;
Il2CppCodeGenWriteBarrier((&___elements_1), value);
}
inline static int32_t get_offset_of_policy_2() { return static_cast<int32_t>(offsetof(X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D, ___policy_2)); }
inline X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD * get_policy_2() const { return ___policy_2; }
inline X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD ** get_address_of_policy_2() { return &___policy_2; }
inline void set_policy_2(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD * value)
{
___policy_2 = value;
Il2CppCodeGenWriteBarrier((&___policy_2), value);
}
};
struct X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D_StaticFields
{
public:
// System.Security.Cryptography.X509Certificates.X509ChainStatus[] System.Security.Cryptography.X509Certificates.X509ChainImplMono::Empty
X509ChainStatusU5BU5D_tA8CCC33D50C4BCF6F657063CD1DACCC3B9A7BFBB* ___Empty_3;
public:
inline static int32_t get_offset_of_Empty_3() { return static_cast<int32_t>(offsetof(X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D_StaticFields, ___Empty_3)); }
inline X509ChainStatusU5BU5D_tA8CCC33D50C4BCF6F657063CD1DACCC3B9A7BFBB* get_Empty_3() const { return ___Empty_3; }
inline X509ChainStatusU5BU5D_tA8CCC33D50C4BCF6F657063CD1DACCC3B9A7BFBB** get_address_of_Empty_3() { return &___Empty_3; }
inline void set_Empty_3(X509ChainStatusU5BU5D_tA8CCC33D50C4BCF6F657063CD1DACCC3B9A7BFBB* value)
{
___Empty_3 = value;
Il2CppCodeGenWriteBarrier((&___Empty_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINIMPLMONO_T38D97B22EAE940C6D941DB58282503264F19FA9D_H
#ifndef X509CHAINPOLICY_TCA1D9E9842A16ACD71D35E9C36659E3E861D74DD_H
#define X509CHAINPOLICY_TCA1D9E9842A16ACD71D35E9C36659E3E861D74DD_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainPolicy
struct X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD : public RuntimeObject
{
public:
// System.Security.Cryptography.OidCollection System.Security.Cryptography.X509Certificates.X509ChainPolicy::apps
OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * ___apps_0;
// System.Security.Cryptography.OidCollection System.Security.Cryptography.X509Certificates.X509ChainPolicy::cert
OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * ___cert_1;
// System.Security.Cryptography.X509Certificates.X509CertificateCollection System.Security.Cryptography.X509Certificates.X509ChainPolicy::store
X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833 * ___store_2;
// System.Security.Cryptography.X509Certificates.X509Certificate2Collection System.Security.Cryptography.X509Certificates.X509ChainPolicy::store2
X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D * ___store2_3;
// System.Security.Cryptography.X509Certificates.X509RevocationFlag System.Security.Cryptography.X509Certificates.X509ChainPolicy::rflag
int32_t ___rflag_4;
// System.Security.Cryptography.X509Certificates.X509RevocationMode System.Security.Cryptography.X509Certificates.X509ChainPolicy::mode
int32_t ___mode_5;
// System.TimeSpan System.Security.Cryptography.X509Certificates.X509ChainPolicy::timeout
TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 ___timeout_6;
// System.Security.Cryptography.X509Certificates.X509VerificationFlags System.Security.Cryptography.X509Certificates.X509ChainPolicy::vflags
int32_t ___vflags_7;
// System.DateTime System.Security.Cryptography.X509Certificates.X509ChainPolicy::vtime
DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 ___vtime_8;
public:
inline static int32_t get_offset_of_apps_0() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___apps_0)); }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * get_apps_0() const { return ___apps_0; }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E ** get_address_of_apps_0() { return &___apps_0; }
inline void set_apps_0(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * value)
{
___apps_0 = value;
Il2CppCodeGenWriteBarrier((&___apps_0), value);
}
inline static int32_t get_offset_of_cert_1() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___cert_1)); }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * get_cert_1() const { return ___cert_1; }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E ** get_address_of_cert_1() { return &___cert_1; }
inline void set_cert_1(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * value)
{
___cert_1 = value;
Il2CppCodeGenWriteBarrier((&___cert_1), value);
}
inline static int32_t get_offset_of_store_2() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___store_2)); }
inline X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833 * get_store_2() const { return ___store_2; }
inline X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833 ** get_address_of_store_2() { return &___store_2; }
inline void set_store_2(X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833 * value)
{
___store_2 = value;
Il2CppCodeGenWriteBarrier((&___store_2), value);
}
inline static int32_t get_offset_of_store2_3() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___store2_3)); }
inline X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D * get_store2_3() const { return ___store2_3; }
inline X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D ** get_address_of_store2_3() { return &___store2_3; }
inline void set_store2_3(X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D * value)
{
___store2_3 = value;
Il2CppCodeGenWriteBarrier((&___store2_3), value);
}
inline static int32_t get_offset_of_rflag_4() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___rflag_4)); }
inline int32_t get_rflag_4() const { return ___rflag_4; }
inline int32_t* get_address_of_rflag_4() { return &___rflag_4; }
inline void set_rflag_4(int32_t value)
{
___rflag_4 = value;
}
inline static int32_t get_offset_of_mode_5() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___mode_5)); }
inline int32_t get_mode_5() const { return ___mode_5; }
inline int32_t* get_address_of_mode_5() { return &___mode_5; }
inline void set_mode_5(int32_t value)
{
___mode_5 = value;
}
inline static int32_t get_offset_of_timeout_6() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___timeout_6)); }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 get_timeout_6() const { return ___timeout_6; }
inline TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 * get_address_of_timeout_6() { return &___timeout_6; }
inline void set_timeout_6(TimeSpan_tA8069278ACE8A74D6DF7D514A9CD4432433F64C4 value)
{
___timeout_6 = value;
}
inline static int32_t get_offset_of_vflags_7() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___vflags_7)); }
inline int32_t get_vflags_7() const { return ___vflags_7; }
inline int32_t* get_address_of_vflags_7() { return &___vflags_7; }
inline void set_vflags_7(int32_t value)
{
___vflags_7 = value;
}
inline static int32_t get_offset_of_vtime_8() { return static_cast<int32_t>(offsetof(X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD, ___vtime_8)); }
inline DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 get_vtime_8() const { return ___vtime_8; }
inline DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 * get_address_of_vtime_8() { return &___vtime_8; }
inline void set_vtime_8(DateTime_t349B7449FBAAFF4192636E2B7A07694DA9236132 value)
{
___vtime_8 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINPOLICY_TCA1D9E9842A16ACD71D35E9C36659E3E861D74DD_H
#ifndef X509CHAINSTATUS_T9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C_H
#define X509CHAINSTATUS_T9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainStatus
struct X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C
{
public:
// System.Security.Cryptography.X509Certificates.X509ChainStatusFlags System.Security.Cryptography.X509Certificates.X509ChainStatus::status
int32_t ___status_0;
// System.String System.Security.Cryptography.X509Certificates.X509ChainStatus::info
String_t* ___info_1;
public:
inline static int32_t get_offset_of_status_0() { return static_cast<int32_t>(offsetof(X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C, ___status_0)); }
inline int32_t get_status_0() const { return ___status_0; }
inline int32_t* get_address_of_status_0() { return &___status_0; }
inline void set_status_0(int32_t value)
{
___status_0 = value;
}
inline static int32_t get_offset_of_info_1() { return static_cast<int32_t>(offsetof(X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C, ___info_1)); }
inline String_t* get_info_1() const { return ___info_1; }
inline String_t** get_address_of_info_1() { return &___info_1; }
inline void set_info_1(String_t* value)
{
___info_1 = value;
Il2CppCodeGenWriteBarrier((&___info_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Security.Cryptography.X509Certificates.X509ChainStatus
struct X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C_marshaled_pinvoke
{
int32_t ___status_0;
char* ___info_1;
};
// Native definition for COM marshalling of System.Security.Cryptography.X509Certificates.X509ChainStatus
struct X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C_marshaled_com
{
int32_t ___status_0;
Il2CppChar* ___info_1;
};
#endif // X509CHAINSTATUS_T9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C_H
#ifndef X509ENHANCEDKEYUSAGEEXTENSION_T8B1FEC5814799207635A97EA878EA64688437254_H
#define X509ENHANCEDKEYUSAGEEXTENSION_T8B1FEC5814799207635A97EA878EA64688437254_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension
struct X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254 : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A
{
public:
// System.Security.Cryptography.OidCollection System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension::_enhKeyUsage
OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * ____enhKeyUsage_3;
// System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension::_status
int32_t ____status_4;
public:
inline static int32_t get_offset_of__enhKeyUsage_3() { return static_cast<int32_t>(offsetof(X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254, ____enhKeyUsage_3)); }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * get__enhKeyUsage_3() const { return ____enhKeyUsage_3; }
inline OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E ** get_address_of__enhKeyUsage_3() { return &____enhKeyUsage_3; }
inline void set__enhKeyUsage_3(OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E * value)
{
____enhKeyUsage_3 = value;
Il2CppCodeGenWriteBarrier((&____enhKeyUsage_3), value);
}
inline static int32_t get_offset_of__status_4() { return static_cast<int32_t>(offsetof(X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254, ____status_4)); }
inline int32_t get__status_4() const { return ____status_4; }
inline int32_t* get_address_of__status_4() { return &____status_4; }
inline void set__status_4(int32_t value)
{
____status_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509ENHANCEDKEYUSAGEEXTENSION_T8B1FEC5814799207635A97EA878EA64688437254_H
#ifndef X509KEYUSAGEEXTENSION_T9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E_H
#define X509KEYUSAGEEXTENSION_T9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509KeyUsageExtension
struct X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A
{
public:
// System.Security.Cryptography.X509Certificates.X509KeyUsageFlags System.Security.Cryptography.X509Certificates.X509KeyUsageExtension::_keyUsages
int32_t ____keyUsages_6;
// System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509KeyUsageExtension::_status
int32_t ____status_7;
public:
inline static int32_t get_offset_of__keyUsages_6() { return static_cast<int32_t>(offsetof(X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E, ____keyUsages_6)); }
inline int32_t get__keyUsages_6() const { return ____keyUsages_6; }
inline int32_t* get_address_of__keyUsages_6() { return &____keyUsages_6; }
inline void set__keyUsages_6(int32_t value)
{
____keyUsages_6 = value;
}
inline static int32_t get_offset_of__status_7() { return static_cast<int32_t>(offsetof(X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E, ____status_7)); }
inline int32_t get__status_7() const { return ____status_7; }
inline int32_t* get_address_of__status_7() { return &____status_7; }
inline void set__status_7(int32_t value)
{
____status_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509KEYUSAGEEXTENSION_T9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E_H
#ifndef X509SUBJECTKEYIDENTIFIEREXTENSION_T200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E_H
#define X509SUBJECTKEYIDENTIFIEREXTENSION_T200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension
struct X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E : public X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A
{
public:
// System.Byte[] System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension::_subjectKeyIdentifier
ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* ____subjectKeyIdentifier_5;
// System.String System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension::_ski
String_t* ____ski_6;
// System.Security.Cryptography.AsnDecodeStatus System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension::_status
int32_t ____status_7;
public:
inline static int32_t get_offset_of__subjectKeyIdentifier_5() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E, ____subjectKeyIdentifier_5)); }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* get__subjectKeyIdentifier_5() const { return ____subjectKeyIdentifier_5; }
inline ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821** get_address_of__subjectKeyIdentifier_5() { return &____subjectKeyIdentifier_5; }
inline void set__subjectKeyIdentifier_5(ByteU5BU5D_tD06FDBE8142446525DF1C40351D523A228373821* value)
{
____subjectKeyIdentifier_5 = value;
Il2CppCodeGenWriteBarrier((&____subjectKeyIdentifier_5), value);
}
inline static int32_t get_offset_of__ski_6() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E, ____ski_6)); }
inline String_t* get__ski_6() const { return ____ski_6; }
inline String_t** get_address_of__ski_6() { return &____ski_6; }
inline void set__ski_6(String_t* value)
{
____ski_6 = value;
Il2CppCodeGenWriteBarrier((&____ski_6), value);
}
inline static int32_t get_offset_of__status_7() { return static_cast<int32_t>(offsetof(X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E, ____status_7)); }
inline int32_t get__status_7() const { return ____status_7; }
inline int32_t* get_address_of__status_7() { return &____status_7; }
inline void set__status_7(int32_t value)
{
____status_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509SUBJECTKEYIDENTIFIEREXTENSION_T200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E_H
#ifndef COMPONENTCONVERTER_TAFCE49784F59197CB5E92C8ED566B069D1A5766E_H
#define COMPONENTCONVERTER_TAFCE49784F59197CB5E92C8ED566B069D1A5766E_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ComponentConverter
struct ComponentConverter_tAFCE49784F59197CB5E92C8ED566B069D1A5766E : public ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COMPONENTCONVERTER_TAFCE49784F59197CB5E92C8ED566B069D1A5766E_H
#ifndef DECIMALCONVERTER_T10232B897580B6DE599BB375BE8C0F4E1C30B0C1_H
#define DECIMALCONVERTER_T10232B897580B6DE599BB375BE8C0F4E1C30B0C1_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DecimalConverter
struct DecimalConverter_t10232B897580B6DE599BB375BE8C0F4E1C30B0C1 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DECIMALCONVERTER_T10232B897580B6DE599BB375BE8C0F4E1C30B0C1_H
#ifndef DOUBLECONVERTER_T65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75_H
#define DOUBLECONVERTER_T65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DoubleConverter
struct DoubleConverter_t65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DOUBLECONVERTER_T65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75_H
#ifndef INT16CONVERTER_TA2223DDF2BE99AD79AD836FCEC90F2C12705433B_H
#define INT16CONVERTER_TA2223DDF2BE99AD79AD836FCEC90F2C12705433B_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Int16Converter
struct Int16Converter_tA2223DDF2BE99AD79AD836FCEC90F2C12705433B : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT16CONVERTER_TA2223DDF2BE99AD79AD836FCEC90F2C12705433B_H
#ifndef INT32CONVERTER_T73A6E403EBE01B56528CB227509954397A46BA22_H
#define INT32CONVERTER_T73A6E403EBE01B56528CB227509954397A46BA22_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Int32Converter
struct Int32Converter_t73A6E403EBE01B56528CB227509954397A46BA22 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32CONVERTER_T73A6E403EBE01B56528CB227509954397A46BA22_H
#ifndef INT64CONVERTER_TED09C98C409F894484943F8D4F9C6468A97F1447_H
#define INT64CONVERTER_TED09C98C409F894484943F8D4F9C6468A97F1447_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Int64Converter
struct Int64Converter_tED09C98C409F894484943F8D4F9C6468A97F1447 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT64CONVERTER_TED09C98C409F894484943F8D4F9C6468A97F1447_H
#ifndef PROPERTYCHANGEDEVENTHANDLER_T617E98E1876A8EB394D2B329340CE02D21FFFC82_H
#define PROPERTYCHANGEDEVENTHANDLER_T617E98E1876A8EB394D2B329340CE02D21FFFC82_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyChangedEventHandler
struct PropertyChangedEventHandler_t617E98E1876A8EB394D2B329340CE02D21FFFC82 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// COM Callable Wrapper interface definition for System.ComponentModel.PropertyChangedEventHandler
struct IPropertyChangedEventHandler_t617E98E1876A8EB394D2B329340CE02D21FFFC82_ComCallableWrapper : Il2CppIUnknown
{
static const Il2CppGuid IID;
virtual il2cpp_hresult_t STDCALL Invoke(Il2CppIInspectable* ___sender0, PropertyChangedEventArgs_t90CF85B82F87D594F73F03364494C77592B11F46 * ___e1) = 0;
};
#endif // PROPERTYCHANGEDEVENTHANDLER_T617E98E1876A8EB394D2B329340CE02D21FFFC82_H
#ifndef SINGLECONVERTER_T86A24FBD46D753B99344470E9566584F15538902_H
#define SINGLECONVERTER_T86A24FBD46D753B99344470E9566584F15538902_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.SingleConverter
struct SingleConverter_t86A24FBD46D753B99344470E9566584F15538902 : public BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SINGLECONVERTER_T86A24FBD46D753B99344470E9566584F15538902_H
#ifndef READMETHOD_T6D92A091070756743232D28A30A05FFCFB7928C4_H
#define READMETHOD_T6D92A091070756743232D28A30A05FFCFB7928C4_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.DeflateStream_ReadMethod
struct ReadMethod_t6D92A091070756743232D28A30A05FFCFB7928C4 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // READMETHOD_T6D92A091070756743232D28A30A05FFCFB7928C4_H
#ifndef WRITEMETHOD_TA5073EA0B599530C5CB5FF202832E16DD4C48397_H
#define WRITEMETHOD_TA5073EA0B599530C5CB5FF202832E16DD4C48397_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.DeflateStream_WriteMethod
struct WriteMethod_tA5073EA0B599530C5CB5FF202832E16DD4C48397 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WRITEMETHOD_TA5073EA0B599530C5CB5FF202832E16DD4C48397_H
#ifndef UNMANAGEDREADORWRITE_TE27F26A26800EB8FA74A54956323F29F04E055B0_H
#define UNMANAGEDREADORWRITE_TE27F26A26800EB8FA74A54956323F29F04E055B0_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IO.Compression.DeflateStreamNative_UnmanagedReadOrWrite
struct UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UNMANAGEDREADORWRITE_TE27F26A26800EB8FA74A54956323F29F04E055B0_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1700 = { sizeof (BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C), -1, sizeof(BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1700[1] =
{
BooleanConverter_tD0D177A9F577915FAA9F6749229672CE8EBAA94C_StaticFields::get_offset_of_values_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1701 = { sizeof (BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1), -1, sizeof(BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1701[4] =
{
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields::get_offset_of_Yes_0(),
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields::get_offset_of_No_1(),
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1_StaticFields::get_offset_of_Default_2(),
BrowsableAttribute_t8A1A514FEE5735ADED64CCFE6E06A42E5CD872D1::get_offset_of_browsable_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1702 = { sizeof (CategoryAttribute_t89C58D266A4A65CD58E04FF63344AA3E0AF57B80), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1702[2] =
{
CategoryAttribute_t89C58D266A4A65CD58E04FF63344AA3E0AF57B80::get_offset_of_localized_0(),
CategoryAttribute_t89C58D266A4A65CD58E04FF63344AA3E0AF57B80::get_offset_of_categoryValue_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1703 = { sizeof (CollectionConverter_t039E15C433996B0F0F0EB78BEE81F6DE0705F184), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1704 = { sizeof (Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473), -1, sizeof(Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1704[3] =
{
Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473_StaticFields::get_offset_of_EventDisposed_1(),
Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473::get_offset_of_site_2(),
Component_t7AEFE153F6778CF52E1981BC3E811A9604B29473::get_offset_of_events_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1705 = { sizeof (ComponentConverter_tAFCE49784F59197CB5E92C8ED566B069D1A5766E), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1706 = { sizeof (DecimalConverter_t10232B897580B6DE599BB375BE8C0F4E1C30B0C1), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1707 = { sizeof (DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846), -1, sizeof(DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1707[2] =
{
DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846::get_offset_of_name_0(),
DefaultEventAttribute_tD1A10417C052CE865C43023F6DCC33CF54D3D846_StaticFields::get_offset_of_Default_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1708 = { sizeof (DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7), -1, sizeof(DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1708[2] =
{
DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7::get_offset_of_name_0(),
DefaultPropertyAttribute_t4C049F2905F3ABDE9B9592627B6133AE49050AA7_StaticFields::get_offset_of_Default_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1709 = { sizeof (DefaultValueAttribute_t03B1F51B35271D50779D31234C9C6845BC9626EC), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1709[1] =
{
DefaultValueAttribute_t03B1F51B35271D50779D31234C9C6845BC9626EC::get_offset_of_value_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1710 = { sizeof (DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75), -1, sizeof(DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1710[2] =
{
DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75_StaticFields::get_offset_of_Default_0(),
DescriptionAttribute_t112C5FEAA03342D05BF40C1713ABF1C1848DEE75::get_offset_of_description_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1711 = { sizeof (DesignerAttribute_t55268910CFC6D82065C1A2F68D05DCD3858933D0), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1711[2] =
{
DesignerAttribute_t55268910CFC6D82065C1A2F68D05DCD3858933D0::get_offset_of_designerTypeName_0(),
DesignerAttribute_t55268910CFC6D82065C1A2F68D05DCD3858933D0::get_offset_of_designerBaseTypeName_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1712 = { sizeof (DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA), -1, sizeof(DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1712[5] =
{
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA::get_offset_of_category_0(),
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields::get_offset_of_Component_1(),
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields::get_offset_of_Default_2(),
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields::get_offset_of_Form_3(),
DesignerCategoryAttribute_tE79E5894EFE62D19C0CD24911AB16B9E996BA7FA_StaticFields::get_offset_of_Generic_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1713 = { sizeof (DesignerSerializationVisibility_tCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1713[4] =
{
DesignerSerializationVisibility_tCD99EB7FAAE0F69CABCFCE53E16C39DDCB2FFC5A::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1714 = { sizeof (DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA), -1, sizeof(DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1714[5] =
{
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields::get_offset_of_Content_0(),
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields::get_offset_of_Hidden_1(),
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields::get_offset_of_Visible_2(),
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA_StaticFields::get_offset_of_Default_3(),
DesignerSerializationVisibilityAttribute_tC50BBA28AF86896B3F34ECB9D56CB0A15BB4CBFA::get_offset_of_visibility_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1715 = { sizeof (DoubleConverter_t65A5D8B0C2736FC5469CE5DFA468D371DD5F9F75), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1716 = { sizeof (EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1716[1] =
{
EditorBrowsableAttribute_tF3507DF0AB82A8D54C70D6F7FB4D363DF729D516::get_offset_of_browsableState_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1717 = { sizeof (EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1717[4] =
{
EditorBrowsableState_t8EAF9BADAAE7DA735C235280DF4B8974EAA39C1B::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1718 = { sizeof (EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1718[2] =
{
EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12::get_offset_of_values_2(),
EnumConverter_t5DA4CB27C27A8C37C31B2A4DE0C4C37820638E12::get_offset_of_type_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1719 = { sizeof (EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1719[2] =
{
EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4::get_offset_of_head_0(),
EventHandlerList_tFE9EF79E85419EBB2C206CF475E29A9960699BE4::get_offset_of_parent_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1720 = { sizeof (ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1720[3] =
{
ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D::get_offset_of_next_0(),
ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D::get_offset_of_key_1(),
ListEntry_t32989B38CAC0D49C6A5AC5BA1622A62088BA6E6D::get_offset_of_handler_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1721 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1722 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1723 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1724 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1725 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1726 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1727 = { sizeof (Int16Converter_tA2223DDF2BE99AD79AD836FCEC90F2C12705433B), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1728 = { sizeof (Int32Converter_t73A6E403EBE01B56528CB227509954397A46BA22), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1729 = { sizeof (Int64Converter_tED09C98C409F894484943F8D4F9C6468A97F1447), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1730 = { sizeof (PropertyChangedEventArgs_t90CF85B82F87D594F73F03364494C77592B11F46), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1730[1] =
{
PropertyChangedEventArgs_t90CF85B82F87D594F73F03364494C77592B11F46::get_offset_of_propertyName_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1731 = { sizeof (PropertyChangedEventHandler_t617E98E1876A8EB394D2B329340CE02D21FFFC82), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1732 = { sizeof (ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4), -1, sizeof(ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1732[1] =
{
ReferenceConverter_t5080472EE999A1F00721E6C5C97013762C85C7E4_StaticFields::get_offset_of_none_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1733 = { sizeof (SingleConverter_t86A24FBD46D753B99344470E9566584F15538902), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1734 = { sizeof (StringConverter_t054FA0796F4C8E951208AFA052D99BCB8E68BED7), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1735 = { sizeof (TimeSpanConverter_t4025A0861C52420BC73D837729E5EFA6ECDE07C7), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1736 = { sizeof (TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB), -1, sizeof(TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1736[2] =
{
0,
TypeConverter_t8306AE03734853B551DDF089C1F17836A7764DBB_StaticFields::get_offset_of_useCompatibleTypeConversion_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1737 = { sizeof (StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1737[2] =
{
StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3::get_offset_of_values_0(),
StandardValuesCollection_t929677712574EF02F5C4CF4C38E070841C20BDA3::get_offset_of_valueArray_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1738 = { sizeof (TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8), -1, sizeof(TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1738[2] =
{
TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8::get_offset_of_typeName_0(),
TypeConverterAttribute_tA0B22E1BE9471741D2CD2A078A2C9A5FF882C2F8_StaticFields::get_offset_of_Default_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1739 = { sizeof (Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668), -1, sizeof(Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1739[3] =
{
Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668::get_offset_of_nativeErrorCode_17(),
Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields::get_offset_of_s_ErrorMessagesInitialized_18(),
Win32Exception_tB05BE97AB4CADD54DF96C0109689F0ECA7517668_StaticFields::get_offset_of_s_ErrorMessage_19(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1740 = { sizeof (BaseNumberConverter_t6AF36A2503E7BABF7FB9A8EC05DF8B828491AC63), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1741 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1742 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1743 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1744 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1745 = { sizeof (RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1745[3] =
{
RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA::get_offset_of_reloadable_0(),
RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA::get_offset_of_serializerTypeName_1(),
RootDesignerSerializerAttribute_tD5A87C7E5CB002D859780E1BEF96D7E1214CC0AA::get_offset_of_serializerBaseTypeName_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1746 = { sizeof (AuthenticationException_tE24BF2E2AD351F0C9586A59191F01918659A7516), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1747 = { sizeof (SslProtocols_tDD37F8F06AD19BDAF27AEA484EC06820FE3107AE)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1747[8] =
{
SslProtocols_tDD37F8F06AD19BDAF27AEA484EC06820FE3107AE::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1748 = { sizeof (OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1748[12] =
{
OidGroup_t9A99D3013C1B94CB060656F30C39E893E75FAD6B::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1749 = { sizeof (Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1749[3] =
{
Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137::get_offset_of_m_value_0(),
Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137::get_offset_of_m_friendlyName_1(),
Oid_tC00A10270EAF16BBF0F2619B9AEC883E0CFE6137::get_offset_of_m_group_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1750 = { sizeof (OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1750[1] =
{
OidCollection_tEB423F1150E53DCF513BF5A699F911586A31B94E::get_offset_of_m_list_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1751 = { sizeof (OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1751[2] =
{
OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C::get_offset_of_m_oids_0(),
OidEnumerator_tC2DB288576C575B69F7934274DDD8A5868CEF97C::get_offset_of_m_current_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1752 = { sizeof (CAPI_tEA68010AC3470FFEBC91FC9D3C13E7D7064C3267), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1753 = { sizeof (AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1753[7] =
{
AsnDecodeStatus_t83139F58FFE08CE7DBCB990C9F30D2F2CA5BC0BB::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1754 = { sizeof (AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1754[2] =
{
AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65::get_offset_of__oid_0(),
AsnEncodedData_t7D5EF5337DCAF507CAD7D750552C943F037A9D65::get_offset_of__raw_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1755 = { sizeof (StoreLocation_t5610361F4E31C5B2B42EE424C3E136BE2CA4C830)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1755[3] =
{
StoreLocation_t5610361F4E31C5B2B42EE424C3E136BE2CA4C830::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1756 = { sizeof (X509ChainStatusFlags_t208E1E90A6014521B09653B6B237D045A8573E5B)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1756[27] =
{
X509ChainStatusFlags_t208E1E90A6014521B09653B6B237D045A8573E5B::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1757 = { sizeof (X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1757[11] =
{
X509KeyUsageFlags_tAD6560EDDEB746BA983AE4E7ABC237A6178D6437::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1758 = { sizeof (X509RevocationFlag_t8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1758[4] =
{
X509RevocationFlag_t8BF7FE53641A7A3C406E86857F3C80F0E25C3F4A::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1759 = { sizeof (X509RevocationMode_tEFEA8C7147423CC3363A4AF504853BD054A33BE7)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1759[4] =
{
X509RevocationMode_tEFEA8C7147423CC3363A4AF504853BD054A33BE7::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1760 = { sizeof (X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1760[4] =
{
X509SubjectKeyIdentifierHashAlgorithm_t7928324BFDBB7B255970D50D0D8972FDFC981A0C::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1761 = { sizeof (X509VerificationFlags_t145010CF6C45EE6563E0874B82C2555025F7A20B)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1761[15] =
{
X509VerificationFlags_t145010CF6C45EE6563E0874B82C2555025F7A20B::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1762 = { sizeof (X509Utils_t596E1974703C7988010495E60F15BE9680FC71B8), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1763 = { sizeof (PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620), -1, sizeof(PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1763[5] =
{
PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__key_0(),
PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__keyValue_1(),
PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__params_2(),
PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620::get_offset_of__oid_3(),
PublicKey_tBA8234EB603A903FCBBBE67D8247393D4CC8D620_StaticFields::get_offset_of_Empty_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1764 = { sizeof (X500DistinguishedName_t848C6BCD1C0923D5FF85BCA3804AC3D256DF8199), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1765 = { sizeof (X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1765[6] =
{
0,
0,
X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__certificateAuthority_5(),
X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__hasPathLengthConstraint_6(),
X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__pathLengthConstraint_7(),
X509BasicConstraintsExtension_t091983B3CDCB686781B4853177610A22483B532C::get_offset_of__status_8(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1766 = { sizeof (X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73), -1, sizeof(X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1766[2] =
{
X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73::get_offset_of_friendlyName_4(),
X509Certificate2_tC1C49EB4CFD571C2FFDE940C24BC69651A058F73_StaticFields::get_offset_of_signedData_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1767 = { sizeof (X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D), -1, sizeof(X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1767[1] =
{
X509Certificate2Collection_t14D64A5A2CFE4EA1782A417F975C2AB85BDA190D_StaticFields::get_offset_of_newline_split_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1768 = { sizeof (X509Certificate2Impl_t645108014422F6408EB87390317CD10710F129E7), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1769 = { sizeof (X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5), -1, sizeof(X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1769[12] =
{
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of__archived_1(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of__extensions_2(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of__publicKey_3(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of_issuer_name_4(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of_subject_name_5(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of_signature_algorithm_6(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of_intermediateCerts_7(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5::get_offset_of__cert_8(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields::get_offset_of_empty_error_9(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields::get_offset_of_commonName_10(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields::get_offset_of_email_11(),
X509Certificate2ImplMono_t3A65BD83268B651BCBE65CFB3691FB85401A91A5_StaticFields::get_offset_of_signedData_12(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1770 = { sizeof (X509CertificateCollection_t824A6C58D0D1B4A7CAE30F26CE8EE4B23A8A1833), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1771 = { sizeof (X509CertificateEnumerator_t99AEDECD77BFC6083D8C98F9760BF7876D5B886B), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1771[1] =
{
X509CertificateEnumerator_t99AEDECD77BFC6083D8C98F9760BF7876D5B886B::get_offset_of_enumerator_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1772 = { sizeof (X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1772[1] =
{
X509CertificateImplCollection_t2F7A6E9F160116CE64224D56187C92ECD7FA7242::get_offset_of_list_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1773 = { sizeof (X509Chain_t4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1773[1] =
{
X509Chain_t4A28E9A30CBB331C9B68AE4AFCB30625C6C8B538::get_offset_of_impl_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1774 = { sizeof (X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1774[1] =
{
X509ChainElementCollection_t7098FB9D22CA34D461370C124E598C629BCADBF4::get_offset_of__list_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1775 = { sizeof (X509ChainElementEnumerator_tEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1775[1] =
{
X509ChainElementEnumerator_tEF7D4F9F87BAAF9A067923B6D4686C2AA4DB5B20::get_offset_of_enumerator_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1776 = { sizeof (X509ChainImpl_t34FABF07BEA0CFB6D88717BCDDE0607D9DA13A67), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1777 = { sizeof (X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D), -1, sizeof(X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1777[4] =
{
X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D::get_offset_of_location_0(),
X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D::get_offset_of_elements_1(),
X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D::get_offset_of_policy_2(),
X509ChainImplMono_t38D97B22EAE940C6D941DB58282503264F19FA9D_StaticFields::get_offset_of_Empty_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1778 = { sizeof (X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1778[9] =
{
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_apps_0(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_cert_1(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_store_2(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_store2_3(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_rflag_4(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_mode_5(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_timeout_6(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_vflags_7(),
X509ChainPolicy_tCA1D9E9842A16ACD71D35E9C36659E3E861D74DD::get_offset_of_vtime_8(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1779 = { sizeof (X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C)+ sizeof (RuntimeObject), sizeof(X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C_marshaled_pinvoke), 0, 0 };
extern const int32_t g_FieldOffsetTable1779[2] =
{
X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C::get_offset_of_status_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
X509ChainStatus_t9E05BD8700EA6158AC82F71CBE53AD20F6B99B0C::get_offset_of_info_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1780 = { sizeof (X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1780[2] =
{
X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254::get_offset_of__enhKeyUsage_3(),
X509EnhancedKeyUsageExtension_t8B1FEC5814799207635A97EA878EA64688437254::get_offset_of__status_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1781 = { sizeof (X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1781[1] =
{
X509Extension_t223237DF0C323CC455D3A2634D977773D2F3818A::get_offset_of__critical_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1782 = { sizeof (X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F), -1, sizeof(X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable1782[2] =
{
X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F_StaticFields::get_offset_of_Empty_0(),
X509ExtensionCollection_t83492D3C69B75EE35B0029F87F9E46CABE49248F::get_offset_of__list_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1783 = { sizeof (X509ExtensionEnumerator_tD857681A1E92F6D18ADCA3710A0176A221D151D8), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1783[1] =
{
X509ExtensionEnumerator_tD857681A1E92F6D18ADCA3710A0176A221D151D8::get_offset_of_enumerator_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1784 = { sizeof (X509Helper2_tD0B65FDE6197798D9719F42AAEA8D9063A8916C7), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1785 = { sizeof (MyNativeHelper_t045BCDC42DCE7A83A80C98AC77C835142040F7B0), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1786 = { sizeof (X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1786[5] =
{
0,
0,
0,
X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E::get_offset_of__keyUsages_6(),
X509KeyUsageExtension_t9F740A60AD6DBEF9B09E946D4D8D67DB882C6E6E::get_offset_of__status_7(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1787 = { sizeof (X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1787[5] =
{
0,
0,
X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E::get_offset_of__subjectKeyIdentifier_5(),
X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E::get_offset_of__ski_6(),
X509SubjectKeyIdentifierExtension_t200DBBEB1229862DAA5F56EA352B03D2EDAC4D8E::get_offset_of__status_7(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1788 = { sizeof (CompressionMode_tA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1788[3] =
{
CompressionMode_tA81E7327FA16C35AE7E4DF2C914F7FA17BD5CA5C::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1789 = { sizeof (GZipStream_t8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1789[1] =
{
GZipStream_t8CA9DD3FABD2B2C7B568D3CA1AEFBA9801D6C588::get_offset_of__deflateStream_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1790 = { sizeof (DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1790[5] =
{
DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE::get_offset_of_base_stream_4(),
DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE::get_offset_of_mode_5(),
DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE::get_offset_of_leaveOpen_6(),
DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE::get_offset_of_disposed_7(),
DeflateStream_t31630A254BA2F3626DA55B570FE488DFF4A227FE::get_offset_of_native_8(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1791 = { sizeof (ReadMethod_t6D92A091070756743232D28A30A05FFCFB7928C4), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1792 = { sizeof (WriteMethod_tA5073EA0B599530C5CB5FF202832E16DD4C48397), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1793 = { sizeof (DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1793[6] =
{
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB::get_offset_of_feeder_0(),
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB::get_offset_of_base_stream_1(),
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB::get_offset_of_z_stream_2(),
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB::get_offset_of_data_3(),
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB::get_offset_of_disposed_4(),
DeflateStreamNative_t7370A3BA77DBD70CCF3355B3862D101135D0F1DB::get_offset_of_io_buffer_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1794 = { sizeof (UnmanagedReadOrWrite_tE27F26A26800EB8FA74A54956323F29F04E055B0), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1795 = { sizeof (SafeDeflateStreamHandle_tE4BC64B6A6597FD38FC9B774F01C4D1EC7464959), sizeof(void*), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1796 = { sizeof (SecurityProtocolType_t5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable1796[6] =
{
SecurityProtocolType_t5A4A36AC58D7FE75545BAB63E4FACE97C7FFE941::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1797 = { sizeof (Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1797[3] =
{
Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B::get_offset_of_m_Message_0(),
Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B::get_offset_of_m_Complete_1(),
Authorization_t6AA17F42B60530EEB99AABAF32E48F292BE2125B::get_offset_of_ModuleAuthenticationType_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1798 = { sizeof (CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1798[3] =
{
CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D::get_offset_of_cache_0(),
CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D::get_offset_of_cacheForHosts_1(),
CredentialCache_t5AB6054A54B30F44BC5746C09E6524F947E7904D::get_offset_of_m_version_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1799 = { sizeof (CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable1799[4] =
{
CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4::get_offset_of_m_cache_0(),
CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4::get_offset_of_m_array_1(),
CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4::get_offset_of_m_index_2(),
CredentialEnumerator_t49CCE6816AB3062B27C0640100310C75F881F8D4::get_offset_of_m_version_3(),
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 46.111254 | 274 | 0.855388 | [
"object"
] |
f550a5ee77c16ccef3518e8b3e29beec883494f4 | 5,614 | cpp | C++ | src/lib/motion_planning/PositionSmoothingTest.cpp | lgarciaos/Firmware | 26dba1407bd1fbc65c23870a22fed904afba6347 | [
"BSD-3-Clause"
] | 4,224 | 2015-01-02T11:51:02.000Z | 2020-10-27T23:42:28.000Z | src/lib/motion_planning/PositionSmoothingTest.cpp | lgarciaos/Firmware | 26dba1407bd1fbc65c23870a22fed904afba6347 | [
"BSD-3-Clause"
] | 11,736 | 2015-01-01T11:59:16.000Z | 2020-10-28T17:13:38.000Z | src/lib/motion_planning/PositionSmoothingTest.cpp | lgarciaos/Firmware | 26dba1407bd1fbc65c23870a22fed904afba6347 | [
"BSD-3-Clause"
] | 11,850 | 2015-01-02T14:54:47.000Z | 2020-10-28T16:42:47.000Z | #include <gtest/gtest.h>
#include <motion_planning/PositionSmoothing.hpp>
static constexpr float MAX_JERK = 4.f;
static constexpr float MAX_ACCELERATION = 3.f;
static constexpr float MAX_ALLOWED_HOR_ERR = 2.f;
static constexpr float VERTICAL_ACCEPTANCE_RADIUS = 0.8f;
static constexpr float CRUISE_SPEED = 5.f;
static constexpr float MAX_VELOCITY = CRUISE_SPEED;
static constexpr float HORIZONTAL_TRAJECTORY_GAIN = 0.5f;
static constexpr float TARGET_ACCEPTANCE_RADIUS = 0.5f;
class PositionSmoothingTest : public ::testing::Test
{
public:
PositionSmoothing _position_smoothing;
PositionSmoothingTest()
{
_position_smoothing.setMaxJerk({MAX_JERK, MAX_JERK, MAX_JERK});
_position_smoothing.setMaxAcceleration({MAX_ACCELERATION, MAX_ACCELERATION, MAX_ACCELERATION});
_position_smoothing.setMaxVelocity({MAX_VELOCITY, MAX_VELOCITY, MAX_VELOCITY});
_position_smoothing.setMaxAllowedHorizontalError(MAX_ALLOWED_HOR_ERR);
_position_smoothing.setVerticalAcceptanceRadius(VERTICAL_ACCEPTANCE_RADIUS);
_position_smoothing.setCruiseSpeed(CRUISE_SPEED);
_position_smoothing.setHorizontalTrajectoryGain(HORIZONTAL_TRAJECTORY_GAIN);
_position_smoothing.setTargetAcceptanceRadius(TARGET_ACCEPTANCE_RADIUS);
_position_smoothing.reset({0.f, 0.f, 0.f}, {0.f, 0.f, 0.f}, {0.f, 0.f, 0.f});
}
static bool _vectorNear(const Vector3f &a, const Vector3f &b, float EPS = 1e-4f)
{
return (fabsf(a(0) - b(0)) < EPS) && (fabsf(a(1) - b(1)) < EPS) && (fabsf(a(2) - b(2)) < EPS);
}
static void expectVectorEqual(const Vector3f &expected, const Vector3f &value, const char *name, float EPS)
{
EXPECT_TRUE(_vectorNear(expected, value, EPS)) <<
"Vector \"" << name << "\" expected [" <<
expected(0) << ", " <<
expected(1) << ", " <<
expected(2) << "] has value [" <<
value(0) << ", " <<
value(1) << ", " <<
value(2) << "]\n";
}
static void expectDynamicsLimitsRespected(const PositionSmoothing::PositionSmoothingSetpoints &setpoints)
{
EXPECT_LE(fabsf(setpoints.velocity(0)), MAX_VELOCITY) << "Velocity in x too high\n";
EXPECT_LE(fabsf(setpoints.velocity(1)), MAX_VELOCITY) << "Velocity in y too high\n";
EXPECT_LE(fabsf(setpoints.velocity(2)), MAX_VELOCITY) << "Velocity in z too high\n";
EXPECT_LE(fabsf(setpoints.acceleration(0)), MAX_ACCELERATION) << "Acceleration in x too high\n";
EXPECT_LE(fabsf(setpoints.acceleration(1)), MAX_ACCELERATION) << "Acceleration in y too high\n";
EXPECT_LE(fabsf(setpoints.acceleration(2)), MAX_ACCELERATION) << "Acceleration in z too high\n";
EXPECT_LE(fabsf(setpoints.jerk(0)), MAX_JERK) << "Jerk in x too high\n";
EXPECT_LE(fabsf(setpoints.jerk(1)), MAX_JERK) << "Jerk in y too high\n";
EXPECT_LE(fabsf(setpoints.jerk(2)), MAX_JERK) << "Jerk in z too high\n";
}
};
TEST_F(PositionSmoothingTest, reachesTargetPositionSetpoint)
{
const float EPS = 1e-4;
const int N_ITER = 2000;
const float DELTA_T = 0.02f;
const Vector3f INITIAL_POSITION{0.f, 0.f, 0.f};
const Vector3f FF_VELOCITY{0.f, 0.f, 0.f};
const Vector3f TARGET{12.f, 17.f, 8.f};
Vector3f waypoints[3] = {INITIAL_POSITION, TARGET, TARGET};
Vector3f position{0.f, 0.f, 0.f};
PositionSmoothing::PositionSmoothingSetpoints out;
int iteration = 0;
for (; iteration < N_ITER; iteration++) {
_position_smoothing.generateSetpoints(
position,
waypoints,
FF_VELOCITY,
DELTA_T,
false,
out
);
position = out.position;
expectDynamicsLimitsRespected(out);
if ((position - TARGET).length() < EPS) {
printf("Converged in %d iterations\n", iteration);
break;
}
}
expectVectorEqual(TARGET, position, "position", EPS);
EXPECT_LT(iteration, N_ITER) << "Took too long to converge\n";
}
TEST_F(PositionSmoothingTest, reachesTargetVelocityIntegration)
{
const float EPS = 1e-4;
const int N_ITER = 2000;
const float DELTA_T = 0.02f;
const Vector3f INITIAL_POSITION{0.f, 0.f, 0.f};
const Vector3f FF_VELOCITY{0.f, 0.f, 0.f};
const Vector3f TARGET{12.f, 17.f, 8.f};
Vector3f waypoints[3] = {INITIAL_POSITION, TARGET, TARGET};
Vector3f position{0.f, 0.f, 0.f};
PositionSmoothing::PositionSmoothingSetpoints out;
int iteration = 0;
for (; iteration < N_ITER; iteration++) {
_position_smoothing.generateSetpoints(
position,
waypoints,
FF_VELOCITY,
DELTA_T,
false,
out
);
position += out.velocity * DELTA_T;
expectDynamicsLimitsRespected(out);
if ((position - TARGET).length() < EPS) {
printf("Converged in %d iterations\n", iteration);
break;
}
}
expectVectorEqual(TARGET, position, "position", EPS);
EXPECT_LT(iteration, N_ITER) << "Took too long to converge\n";
}
TEST_F(PositionSmoothingTest, reachesTargetInitialVelocity)
{
const float EPS = 1e-4;
const int N_ITER = 2000;
const float DELTA_T = 0.02f;
const Vector3f INITIAL_POSITION{0.f, 0.f, 0.f};
const Vector3f TARGET{12.f, 17.f, 8.f};
const Vector3f NEXT_TARGET{8.f, 12.f, 80.f};
Vector3f waypoints[3] = {INITIAL_POSITION, TARGET, NEXT_TARGET};
Vector3f ff_velocity{1.f, 0.1f, 0.3f};
Vector3f position{0.f, 0.f, 0.f};
PositionSmoothing::PositionSmoothingSetpoints out;
int iteration = 0;
for (; iteration < N_ITER; iteration++) {
_position_smoothing.generateSetpoints(
position,
waypoints,
ff_velocity,
DELTA_T,
false,
out
);
position = out.position;
ff_velocity = {0.f, 0.f, 0.f};
expectDynamicsLimitsRespected(out);
if ((position - TARGET).length() < EPS) {
printf("Converged in %d iterations\n", iteration);
break;
}
}
expectVectorEqual(TARGET, position, "position", EPS);
EXPECT_LT(iteration, N_ITER) << "Took too long to converge\n";
}
| 29.239583 | 108 | 0.716423 | [
"vector"
] |
f55145ccfc7826ca92104fe6fad4e1b7f3016d44 | 7,370 | cpp | C++ | src/Storages/System/StorageSystemGrants.cpp | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 5 | 2019-07-29T02:09:56.000Z | 2020-03-19T19:05:44.000Z | src/Storages/System/StorageSystemGrants.cpp | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 30 | 2021-10-01T00:08:14.000Z | 2021-12-06T13:13:12.000Z | src/Storages/System/StorageSystemGrants.cpp | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 1 | 2022-03-19T17:31:29.000Z | 2022-03-19T17:31:29.000Z | #include <Storages/System/StorageSystemGrants.h>
#include <Storages/System/StorageSystemPrivileges.h>
#include <DataTypes/DataTypeEnum.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypesNumber.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnsNumber.h>
#include <Access/AccessControl.h>
#include <Access/Common/AccessRightsElement.h>
#include <Access/Role.h>
#include <Access/User.h>
#include <Interpreters/Context.h>
#include <boost/range/algorithm_ext/push_back.hpp>
namespace DB
{
NamesAndTypesList StorageSystemGrants::getNamesAndTypes()
{
NamesAndTypesList names_and_types{
{"user_name", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>())},
{"role_name", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>())},
{"access_type", std::make_shared<DataTypeEnum8>(StorageSystemPrivileges::getAccessTypeEnumValues())},
{"database", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>())},
{"table", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>())},
{"column", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeString>())},
{"is_partial_revoke", std::make_shared<DataTypeUInt8>()},
{"grant_option", std::make_shared<DataTypeUInt8>()},
};
return names_and_types;
}
void StorageSystemGrants::fillData(MutableColumns & res_columns, ContextPtr context, const SelectQueryInfo &) const
{
context->checkAccess(AccessType::SHOW_USERS | AccessType::SHOW_ROLES);
const auto & access_control = context->getAccessControl();
std::vector<UUID> ids = access_control.findAll<User>();
boost::range::push_back(ids, access_control.findAll<Role>());
size_t column_index = 0;
auto & column_user_name = assert_cast<ColumnString &>(assert_cast<ColumnNullable &>(*res_columns[column_index]).getNestedColumn());
auto & column_user_name_null_map = assert_cast<ColumnNullable &>(*res_columns[column_index++]).getNullMapData();
auto & column_role_name = assert_cast<ColumnString &>(assert_cast<ColumnNullable &>(*res_columns[column_index]).getNestedColumn());
auto & column_role_name_null_map = assert_cast<ColumnNullable &>(*res_columns[column_index++]).getNullMapData();
auto & column_access_type = assert_cast<ColumnInt8 &>(*res_columns[column_index++]).getData();
auto & column_database = assert_cast<ColumnString &>(assert_cast<ColumnNullable &>(*res_columns[column_index]).getNestedColumn());
auto & column_database_null_map = assert_cast<ColumnNullable &>(*res_columns[column_index++]).getNullMapData();
auto & column_table = assert_cast<ColumnString &>(assert_cast<ColumnNullable &>(*res_columns[column_index]).getNestedColumn());
auto & column_table_null_map = assert_cast<ColumnNullable &>(*res_columns[column_index++]).getNullMapData();
auto & column_column = assert_cast<ColumnString &>(assert_cast<ColumnNullable &>(*res_columns[column_index]).getNestedColumn());
auto & column_column_null_map = assert_cast<ColumnNullable &>(*res_columns[column_index++]).getNullMapData();
auto & column_is_partial_revoke = assert_cast<ColumnUInt8 &>(*res_columns[column_index++]).getData();
auto & column_grant_option = assert_cast<ColumnUInt8 &>(*res_columns[column_index++]).getData();
auto add_row = [&](const String & grantee_name,
AccessEntityType grantee_type,
AccessType access_type,
const String * database,
const String * table,
const String * column,
bool is_partial_revoke,
bool grant_option)
{
if (grantee_type == AccessEntityType::USER)
{
column_user_name.insertData(grantee_name.data(), grantee_name.length());
column_user_name_null_map.push_back(false);
column_role_name.insertDefault();
column_role_name_null_map.push_back(true);
}
else if (grantee_type == AccessEntityType::ROLE)
{
column_user_name.insertDefault();
column_user_name_null_map.push_back(true);
column_role_name.insertData(grantee_name.data(), grantee_name.length());
column_role_name_null_map.push_back(false);
}
else
assert(false);
column_access_type.push_back(static_cast<Int8>(access_type));
if (database)
{
column_database.insertData(database->data(), database->length());
column_database_null_map.push_back(false);
}
else
{
column_database.insertDefault();
column_database_null_map.push_back(true);
}
if (table)
{
column_table.insertData(table->data(), table->length());
column_table_null_map.push_back(false);
}
else
{
column_table.insertDefault();
column_table_null_map.push_back(true);
}
if (column)
{
column_column.insertData(column->data(), column->length());
column_column_null_map.push_back(false);
}
else
{
column_column.insertDefault();
column_column_null_map.push_back(true);
}
column_is_partial_revoke.push_back(is_partial_revoke);
column_grant_option.push_back(grant_option);
};
auto add_rows = [&](const String & grantee_name,
AccessEntityType grantee_type,
const AccessRightsElements & elements)
{
for (const auto & element : elements)
{
auto access_types = element.access_flags.toAccessTypes();
if (access_types.empty() || (!element.any_column && element.columns.empty()))
continue;
const auto * database = element.any_database ? nullptr : &element.database;
const auto * table = element.any_table ? nullptr : &element.table;
if (element.any_column)
{
for (const auto & access_type : access_types)
add_row(grantee_name, grantee_type, access_type, database, table, nullptr, element.is_partial_revoke, element.grant_option);
}
else
{
for (const auto & access_type : access_types)
for (const auto & column : element.columns)
add_row(grantee_name, grantee_type, access_type, database, table, &column, element.is_partial_revoke, element.grant_option);
}
}
};
for (const auto & id : ids)
{
auto entity = access_control.tryRead(id);
if (!entity)
continue;
const AccessRights * access = nullptr;
if (auto role = typeid_cast<RolePtr>(entity))
access = &role->access;
else if (auto user = typeid_cast<UserPtr>(entity))
access = &user->access;
else
continue;
const String & grantee_name = entity->getName();
const auto grantee_type = entity->getType();
auto elements = access->getElements();
add_rows(grantee_name, grantee_type, elements);
}
}
}
| 42.601156 | 148 | 0.652782 | [
"vector"
] |
f553a7502b42a23834d36cb610cc4e829b07f39b | 51,934 | cpp | C++ | be/test/runtime/buffered_block_mgr2_test.cpp | kuolei/incubator-doris | b14678c0021896f11efdfdaa3e2dad15b2d4868d | [
"Apache-2.0"
] | 2 | 2022-01-26T15:24:34.000Z | 2022-02-10T09:07:33.000Z | be/test/runtime/buffered_block_mgr2_test.cpp | kuolei/incubator-doris | b14678c0021896f11efdfdaa3e2dad15b2d4868d | [
"Apache-2.0"
] | 2 | 2018-08-27T07:42:21.000Z | 2018-08-29T06:37:41.000Z | be/test/runtime/buffered_block_mgr2_test.cpp | kuolei/incubator-doris | b14678c0021896f11efdfdaa3e2dad15b2d4868d | [
"Apache-2.0"
] | 1 | 2022-02-28T09:53:30.000Z | 2022-02-28T09:53:30.000Z | // 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 "runtime/buffered_block_mgr2.h"
#include <gtest/gtest.h>
#include <sys/stat.h>
#include <filesystem>
#include <functional>
#include <thread>
#include "runtime/disk_io_mgr.h"
#include "runtime/exec_env.h"
#include "runtime/runtime_state.h"
#include "runtime/test_env.h"
#include "runtime/tmp_file_mgr.h"
#include "util/cpu_info.h"
#include "util/disk_info.h"
#include "util/filesystem_util.h"
#include "util/logging.h"
#include "util/monotime.h"
#include "util/thread_group.h"
using std::filesystem::directory_iterator;
using std::filesystem::remove;
using std::unique_ptr;
using std::unordered_map;
using std::thread;
using std::string;
using std::stringstream;
using std::vector;
// Note: This is the default scratch dir created by doris.
// config::query_scratch_dirs + TmpFileMgr::_s_tmp_sub_dir_name.
const static string SCRATCH_DIR = "/tmp/doris-scratch";
// This suffix is appended to a tmp dir
const static string SCRATCH_SUFFIX = "/doris-scratch";
// Number of milliseconds to wait to ensure write completes
const static int WRITE_WAIT_MILLIS = 500;
// How often to check for write completion
const static int WRITE_CHECK_INTERVAL_MILLIS = 10;
namespace doris {
class BufferedBlockMgrTest : public ::testing::Test {
protected:
const static int _block_size = 1024;
virtual void SetUp() {
_test_env.reset(new TestEnv());
_client_tracker.reset(new MemTracker(-1));
}
virtual void TearDown() {
TearDownMgrs();
_test_env.reset();
_client_tracker.reset();
// Tests modify permissions, so make sure we can delete if they didn't clean up.
for (int i = 0; i < _created_tmp_dirs.size(); ++i) {
chmod((_created_tmp_dirs[i] + SCRATCH_SUFFIX).c_str(), S_IRWXU);
}
FileSystemUtil::remove_paths(_created_tmp_dirs);
_created_tmp_dirs.clear();
}
// Reinitialize _test_env to have multiple temporary directories.
std::vector<string> InitMultipleTmpDirs(int num_dirs) {
std::vector<string> tmp_dirs;
for (int i = 0; i < num_dirs; ++i) {
std::stringstream dir_str;
dir_str << "/tmp/buffered-block-mgr-test." << i;
const string& dir = dir_str.str();
// Fix permissions in case old directories were left from previous runs of test.
chmod((dir + SCRATCH_SUFFIX).c_str(), S_IRWXU);
EXPECT_TRUE(FileSystemUtil::create_directory(dir).ok());
tmp_dirs.push_back(dir);
_created_tmp_dirs.push_back(dir);
}
_test_env->init_tmp_file_mgr(tmp_dirs, false);
EXPECT_EQ(num_dirs, _test_env->tmp_file_mgr()->num_active_tmp_devices());
return tmp_dirs;
}
static void ValidateBlock(BufferedBlockMgr2::Block* block, int32_t data) {
EXPECT_TRUE(block->valid_data_len() == sizeof(int32_t));
EXPECT_TRUE(*reinterpret_cast<int32_t*>(block->buffer()) == data);
}
static int32_t* MakeRandomSizeData(BufferedBlockMgr2::Block* block) {
// Format is int32_t size, followed by size bytes of data
int32_t size = (rand() % 252) + 4; // So blocks have 4-256 bytes of data
uint8_t* data = block->allocate<uint8_t>(size);
*(reinterpret_cast<int32_t*>(data)) = size;
int i = 0;
for (i = 4; i < size - 5; ++i) {
data[i] = i;
}
for (; i < size; ++i) { // End marker of at least 5 0xff's
data[i] = 0xff;
}
return reinterpret_cast<int32_t*>(data); // Really returns a pointer to size
}
static void ValidateRandomSizeData(BufferedBlockMgr2::Block* block, int32_t size) {
int32_t bsize = *(reinterpret_cast<int32_t*>(block->buffer()));
uint8_t* data = reinterpret_cast<uint8_t*>(block->buffer());
int i = 0;
EXPECT_EQ(block->valid_data_len(), size);
EXPECT_EQ(size, bsize);
for (i = 4; i < size - 5; ++i) {
EXPECT_EQ(data[i], i);
}
for (; i < size; ++i) {
EXPECT_EQ(data[i], 0xff);
}
}
/// Helper to create a simple block manager.
BufferedBlockMgr2* CreateMgr(int64_t query_id, int max_buffers, int block_size,
RuntimeState** query_state = nullptr) {
RuntimeState* state = nullptr;
EXPECT_TRUE(_test_env->create_query_state(query_id, max_buffers, block_size, &state).ok());
if (query_state != nullptr) {
*query_state = state;
}
return state->block_mgr2();
}
BufferedBlockMgr2* CreateMgrAndClient(int64_t query_id, int max_buffers, int block_size,
int reserved_blocks,
const std::shared_ptr<MemTracker>& tracker,
BufferedBlockMgr2::Client** client) {
RuntimeState* state = nullptr;
BufferedBlockMgr2* mgr = CreateMgr(query_id, max_buffers, block_size, &state);
EXPECT_TRUE(mgr->register_client(reserved_blocks, tracker, state, client).ok());
EXPECT_TRUE(client != nullptr);
return mgr;
}
void CreateMgrsAndClients(int64_t start_query_id, int num_mgrs, int buffers_per_mgr,
int block_size, int reserved_blocks_per_client,
const std::shared_ptr<MemTracker>& tracker,
std::vector<BufferedBlockMgr2*>* mgrs,
std::vector<BufferedBlockMgr2::Client*>* clients) {
for (int i = 0; i < num_mgrs; ++i) {
BufferedBlockMgr2::Client* client;
BufferedBlockMgr2* mgr =
CreateMgrAndClient(start_query_id + i, buffers_per_mgr, _block_size,
reserved_blocks_per_client, tracker, &client);
mgrs->push_back(mgr);
clients->push_back(client);
}
}
// Destroy all created query states and associated block managers.
void TearDownMgrs() {
// Freeing all block managers should clean up all consumed memory.
_test_env->tear_down_query_states();
EXPECT_EQ(_test_env->block_mgr_parent_tracker()->consumption(), 0);
}
void AllocateBlocks(BufferedBlockMgr2* block_mgr, BufferedBlockMgr2::Client* client,
int num_blocks, std::vector<BufferedBlockMgr2::Block*>* blocks) {
int32_t* data = nullptr;
Status status;
BufferedBlockMgr2::Block* new_block;
for (int i = 0; i < num_blocks; ++i) {
status = block_mgr->get_new_block(client, nullptr, &new_block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(new_block != nullptr);
data = new_block->allocate<int32_t>(sizeof(int32_t));
*data = blocks->size();
blocks->push_back(new_block);
}
}
// Pin all blocks, expecting they are pinned successfully.
void PinBlocks(const std::vector<BufferedBlockMgr2::Block*>& blocks) {
for (int i = 0; i < blocks.size(); ++i) {
bool pinned = false;
EXPECT_TRUE(blocks[i]->pin(&pinned).ok());
EXPECT_TRUE(pinned);
}
}
// Pin all blocks, expecting no errors from unpin() calls.
void UnpinBlocks(const std::vector<BufferedBlockMgr2::Block*>& blocks) {
for (int i = 0; i < blocks.size(); ++i) {
EXPECT_TRUE(blocks[i]->unpin().ok());
}
}
static void WaitForWrites(BufferedBlockMgr2* block_mgr) {
std::vector<BufferedBlockMgr2*> block_mgrs;
block_mgrs.push_back(block_mgr);
WaitForWrites(block_mgrs);
}
// Wait for writes issued through block managers to complete.
static void WaitForWrites(const std::vector<BufferedBlockMgr2*>& block_mgrs) {
int max_attempts = WRITE_WAIT_MILLIS / WRITE_CHECK_INTERVAL_MILLIS;
for (int i = 0; i < max_attempts; ++i) {
SleepFor(MonoDelta::FromMilliseconds(WRITE_CHECK_INTERVAL_MILLIS));
if (AllWritesComplete(block_mgrs)) {
return;
}
}
EXPECT_TRUE(false) << "Writes did not complete after " << WRITE_WAIT_MILLIS << "ms";
}
static bool AllWritesComplete(const std::vector<BufferedBlockMgr2*>& block_mgrs) {
for (int i = 0; i < block_mgrs.size(); ++i) {
RuntimeProfile::Counter* writes_outstanding =
block_mgrs[i]->profile()->get_counter("BlockWritesOutstanding");
if (writes_outstanding->value() != 0) {
return false;
}
}
return true;
}
// Delete the temporary file backing a block - all subsequent writes to the file
// should fail. Expects backing file has already been allocated.
static void DeleteBackingFile(BufferedBlockMgr2::Block* block) {
const string& path = block->tmp_file_path();
EXPECT_GT(path.size(), 0);
EXPECT_TRUE(remove(path));
LOG(INFO) << "Injected fault by deleting file " << path;
}
// Check that the file backing the block has dir as a prefix of its path.
static bool BlockInDir(BufferedBlockMgr2::Block* block, const string& dir) {
return block->tmp_file_path().find(dir) == 0;
}
// Find a block in the list that is backed by a file with the given directory as prefix
// of its path.
static BufferedBlockMgr2::Block* FindBlockForDir(
const std::vector<BufferedBlockMgr2::Block*>& blocks, const string& dir) {
for (int i = 0; i < blocks.size(); ++i) {
if (BlockInDir(blocks[i], dir)) {
return blocks[i];
}
}
return nullptr;
}
void TestGetNewBlockImpl(int block_size) {
Status status;
int max_num_blocks = 5;
BufferedBlockMgr2* block_mgr = nullptr;
BufferedBlockMgr2::Client* client;
block_mgr = CreateMgrAndClient(0, max_num_blocks, block_size, 0, _client_tracker, &client);
EXPECT_EQ(_test_env->block_mgr_parent_tracker()->consumption(), 0);
// Allocate blocks until max_num_blocks, they should all succeed and memory
// usage should go up.
BufferedBlockMgr2::Block* new_block;
BufferedBlockMgr2::Block* first_block = nullptr;
for (int i = 0; i < max_num_blocks; ++i) {
status = block_mgr->get_new_block(client, nullptr, &new_block);
EXPECT_TRUE(new_block != nullptr);
EXPECT_EQ(block_mgr->bytes_allocated(), (i + 1) * block_size);
if (first_block == nullptr) {
first_block = new_block;
}
}
// Trying to allocate a new one should fail.
status = block_mgr->get_new_block(client, nullptr, &new_block);
EXPECT_TRUE(new_block == nullptr);
EXPECT_EQ(block_mgr->bytes_allocated(), max_num_blocks * block_size);
// We can allocate a new block by transferring an already allocated one.
uint8_t* old_buffer = first_block->buffer();
status = block_mgr->get_new_block(client, first_block, &new_block);
EXPECT_TRUE(new_block != nullptr);
EXPECT_TRUE(old_buffer == new_block->buffer());
EXPECT_EQ(block_mgr->bytes_allocated(), max_num_blocks * block_size);
EXPECT_TRUE(!first_block->is_pinned());
// Trying to allocate a new one should still fail.
status = block_mgr->get_new_block(client, nullptr, &new_block);
EXPECT_TRUE(new_block == nullptr);
EXPECT_EQ(block_mgr->bytes_allocated(), max_num_blocks * block_size);
EXPECT_EQ(block_mgr->writes_issued(), 1);
TearDownMgrs();
}
void TestEvictionImpl(int block_size) {
Status status;
DCHECK_GT(block_size, 0);
int max_num_buffers = 5;
BufferedBlockMgr2* block_mgr = nullptr;
BufferedBlockMgr2::Client* client = nullptr;
block_mgr = CreateMgrAndClient(0, max_num_buffers, block_size, 0, _client_tracker, &client);
// Check counters.
RuntimeProfile* profile = block_mgr->profile();
RuntimeProfile::Counter* buffered_pin = profile->get_counter("BufferedPins");
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
EXPECT_EQ(block_mgr->bytes_allocated(), max_num_buffers * block_size);
for (BufferedBlockMgr2::Block* block : blocks) {
block->unpin();
}
// Re-pinning all blocks
for (int i = 0; i < blocks.size(); ++i) {
bool pinned = false;
status = blocks[i]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
ValidateBlock(blocks[i], i);
}
int buffered_pins_expected = blocks.size();
EXPECT_EQ(buffered_pin->value(), buffered_pins_expected);
// Unpin all blocks
for (BufferedBlockMgr2::Block* block : blocks) {
block->unpin();
}
// Get two new blocks.
AllocateBlocks(block_mgr, client, 2, &blocks);
// At least two writes must be issued. The first (num_blocks - 2) must be in memory.
EXPECT_GE(block_mgr->writes_issued(), 2);
for (int i = 0; i < (max_num_buffers - 2); ++i) {
bool pinned = false;
status = blocks[i]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
ValidateBlock(blocks[i], i);
}
EXPECT_GE(buffered_pin->value(), buffered_pins_expected);
// can not pin any more
for (int i = (max_num_buffers - 2); i < max_num_buffers; ++i) {
bool pinned = true;
status = blocks[i]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_FALSE(pinned);
}
// the last 2 block has already been pinned
for (int i = max_num_buffers; i < blocks.size(); ++i) {
bool pinned = false;
status = blocks[i]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
ValidateBlock(blocks[i], i);
}
TearDownMgrs();
}
// Test that randomly issues GetFreeBlock(), pin(), unpin(), del() and Close()
// calls. All calls made are legal - error conditions are not expected until the first
// call to Close(). This is called 2 times with encryption+integrity on/off.
// When executed in single-threaded mode 'tid' should be SINGLE_THREADED_TID.
static const int SINGLE_THREADED_TID = -1;
void TestRandomInternalImpl(RuntimeState* state, BufferedBlockMgr2* block_mgr, int num_buffers,
int tid) {
DCHECK(block_mgr != nullptr);
const int num_iterations = 100000;
const int iters_before_close = num_iterations - 5000;
bool close_called = false;
unordered_map<BufferedBlockMgr2::Block*, int> pinned_block_map;
std::vector<std::pair<BufferedBlockMgr2::Block*, int32_t>> pinned_blocks;
unordered_map<BufferedBlockMgr2::Block*, int> unpinned_block_map;
std::vector<std::pair<BufferedBlockMgr2::Block*, int32_t>> unpinned_blocks;
typedef enum { Pin, New, Unpin, Delete, Close } ApiFunction;
ApiFunction api_function;
BufferedBlockMgr2::Client* client;
Status status = block_mgr->register_client(0, _client_tracker, state, &client);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client != nullptr);
pinned_blocks.reserve(num_buffers);
BufferedBlockMgr2::Block* new_block;
for (int i = 0; i < num_iterations; ++i) {
if ((i % 20000) == 0) {
LOG(ERROR) << " Iteration " << i << std::endl;
}
if (i > iters_before_close && (rand() % 5 == 0)) {
api_function = Close;
} else if (pinned_blocks.size() == 0 && unpinned_blocks.size() == 0) {
api_function = New;
} else if (pinned_blocks.size() == 0) {
// Pin or New. Can't unpin or delete.
api_function = static_cast<ApiFunction>(rand() % 2);
} else if (pinned_blocks.size() >= num_buffers) {
// Unpin or delete. Can't pin or get new.
api_function = static_cast<ApiFunction>(2 + (rand() % 2));
} else if (unpinned_blocks.size() == 0) {
// Can't pin. Unpin, new or delete.
api_function = static_cast<ApiFunction>(1 + (rand() % 3));
} else {
// Any api function.
api_function = static_cast<ApiFunction>(rand() % 4);
}
std::pair<BufferedBlockMgr2::Block*, int32_t> block_data;
int rand_pick = 0;
int32_t* data = nullptr;
bool pinned = false;
switch (api_function) {
case New:
status = block_mgr->get_new_block(client, nullptr, &new_block);
if (close_called || (tid != SINGLE_THREADED_TID && status.is_cancelled())) {
EXPECT_TRUE(new_block == nullptr);
EXPECT_TRUE(status.is_cancelled());
continue;
}
EXPECT_TRUE(status.ok());
EXPECT_TRUE(new_block != nullptr);
data = MakeRandomSizeData(new_block);
block_data = std::make_pair(new_block, *data);
pinned_blocks.push_back(block_data);
pinned_block_map.insert(std::make_pair(block_data.first, pinned_blocks.size() - 1));
break;
case Pin:
rand_pick = rand() % unpinned_blocks.size();
block_data = unpinned_blocks[rand_pick];
status = block_data.first->pin(&pinned);
if (close_called || (tid != SINGLE_THREADED_TID && status.is_cancelled())) {
EXPECT_TRUE(status.is_cancelled());
// In single-threaded runs the block should not have been pinned.
// In multi-threaded runs pin() may return the block pinned but the status to
// be cancelled. In this case we could move the block from unpinned_blocks
// to pinned_blocks. We do not do that because after is_cancelled() no actual
// block operations should take place.
// reason: when block_mgr is cancelled in one thread, the same block_mgr
// is waiting for scan-range to be ready.
if (tid == SINGLE_THREADED_TID) {
EXPECT_FALSE(pinned);
}
continue;
}
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
ValidateRandomSizeData(block_data.first, block_data.second);
unpinned_blocks[rand_pick] = unpinned_blocks.back();
unpinned_blocks.pop_back();
unpinned_block_map[unpinned_blocks[rand_pick].first] = rand_pick;
pinned_blocks.push_back(block_data);
pinned_block_map.insert(std::make_pair(block_data.first, pinned_blocks.size() - 1));
break;
case Unpin:
rand_pick = rand() % pinned_blocks.size();
block_data = pinned_blocks[rand_pick];
status = block_data.first->unpin();
if (close_called || (tid != SINGLE_THREADED_TID && status.is_cancelled())) {
EXPECT_TRUE(status.is_cancelled());
continue;
}
EXPECT_TRUE(status.ok());
pinned_blocks[rand_pick] = pinned_blocks.back();
pinned_blocks.pop_back();
pinned_block_map[pinned_blocks[rand_pick].first] = rand_pick;
unpinned_blocks.push_back(block_data);
unpinned_block_map.insert(
std::make_pair(block_data.first, unpinned_blocks.size() - 1));
break;
case Delete:
rand_pick = rand() % pinned_blocks.size();
block_data = pinned_blocks[rand_pick];
block_data.first->del();
pinned_blocks[rand_pick] = pinned_blocks.back();
pinned_blocks.pop_back();
pinned_block_map[pinned_blocks[rand_pick].first] = rand_pick;
break;
case Close:
block_mgr->cancel();
close_called = true;
break;
} // end switch (apiFunction)
} // end for ()
}
// Single-threaded execution of the TestRandomInternalImpl.
void TestRandomInternalSingle(int block_size) {
DCHECK_GT(block_size, 0);
DCHECK(_test_env.get() != nullptr);
const int max_num_buffers = 100;
RuntimeState* state = nullptr;
BufferedBlockMgr2* block_mgr = CreateMgr(0, max_num_buffers, block_size, &state);
TestRandomInternalImpl(state, block_mgr, max_num_buffers, SINGLE_THREADED_TID);
TearDownMgrs();
}
// Multi-threaded execution of the TestRandomInternalImpl.
void TestRandomInternalMulti(int num_threads, int block_size) {
DCHECK_GT(num_threads, 0);
DCHECK_GT(block_size, 0);
DCHECK(_test_env.get() != nullptr);
const int max_num_buffers = 100;
RuntimeState* state = nullptr;
BufferedBlockMgr2* block_mgr =
CreateMgr(0, num_threads * max_num_buffers, block_size, &state);
ThreadGroup workers;
for (int i = 0; i < num_threads; ++i) {
thread* t = new thread(std::bind(&BufferedBlockMgrTest::TestRandomInternalImpl, this,
state, block_mgr, max_num_buffers, i));
workers.add_thread(t);
}
workers.join_all();
TearDownMgrs();
}
// Repeatedly call BufferedBlockMgr2::Create() and BufferedBlockMgr2::~BufferedBlockMgr2().
void CreateDestroyThread(int index, RuntimeState* state) {
const int num_buffers = 10;
const int iters = 100;
for (int i = 0; i < iters; ++i) {
LOG(WARNING) << "CreateDestroyThread thread " << index << " begin " << i << std::endl;
std::shared_ptr<BufferedBlockMgr2> mgr;
Status status = BufferedBlockMgr2::create(
state, _test_env->block_mgr_parent_tracker(), state->runtime_profile(),
_test_env->tmp_file_mgr(), _block_size * num_buffers, _block_size, &mgr);
LOG(WARNING) << "CreateDestroyThread thread " << index << " end " << i << std::endl;
}
}
// IMPALA-2286: Test for races between BufferedBlockMgr2::Create() and
// BufferedBlockMgr2::~BufferedBlockMgr2().
void CreateDestroyMulti() {
const int num_threads = 4;
ThreadGroup workers;
// Create a shared RuntimeState with no BufferedBlockMgr2.
RuntimeState* shared_state = new RuntimeState(TUniqueId(), TQueryOptions(), TQueryGlobals(),
_test_env->exec_env());
for (int i = 0; i < num_threads; ++i) {
thread* t = new thread(
std::bind(&BufferedBlockMgrTest::CreateDestroyThread, this, i, shared_state));
workers.add_thread(t);
}
workers.join_all();
}
std::unique_ptr<TestEnv> _test_env;
std::shared_ptr<MemTracker> _client_tracker;
std::vector<string> _created_tmp_dirs;
};
TEST_F(BufferedBlockMgrTest, get_new_block) {
TestGetNewBlockImpl(1024);
TestGetNewBlockImpl(8 * 1024);
TestGetNewBlockImpl(8 * 1024 * 1024);
LOG(WARNING) << "finish test get_new_block." << std::endl;
}
TEST_F(BufferedBlockMgrTest, GetNewBlockSmallBlocks) {
const int block_size = 1024;
int max_num_blocks = 3;
BufferedBlockMgr2* block_mgr;
BufferedBlockMgr2::Client* client;
block_mgr = CreateMgrAndClient(0, max_num_blocks, block_size, 0, _client_tracker, &client);
EXPECT_EQ(0, _test_env->block_mgr_parent_tracker()->consumption());
std::vector<BufferedBlockMgr2::Block*> blocks;
// Allocate a small block.
BufferedBlockMgr2::Block* new_block = nullptr;
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block, 128).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_EQ(block_mgr->bytes_allocated(), 0);
EXPECT_EQ(_test_env->block_mgr_parent_tracker()->consumption(), 0);
EXPECT_EQ(_client_tracker->consumption(), 128);
EXPECT_TRUE(new_block->is_pinned());
EXPECT_EQ(new_block->bytes_remaining(), 128);
EXPECT_TRUE(new_block->buffer() != nullptr);
blocks.push_back(new_block);
// Allocate a normal block
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_EQ(block_mgr->bytes_allocated(), block_mgr->max_block_size());
EXPECT_EQ(_test_env->block_mgr_parent_tracker()->consumption(), block_mgr->max_block_size());
EXPECT_EQ(_client_tracker->consumption(), 128 + block_mgr->max_block_size());
EXPECT_TRUE(new_block->is_pinned());
EXPECT_EQ(new_block->bytes_remaining(), block_mgr->max_block_size());
EXPECT_TRUE(new_block->buffer() != nullptr);
blocks.push_back(new_block);
// Allocate another small block.
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block, 512).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_EQ(block_mgr->bytes_allocated(), block_mgr->max_block_size());
EXPECT_EQ(_test_env->block_mgr_parent_tracker()->consumption(), block_mgr->max_block_size());
EXPECT_EQ(_client_tracker->consumption(), 128 + 512 + block_mgr->max_block_size());
EXPECT_TRUE(new_block->is_pinned());
EXPECT_EQ(new_block->bytes_remaining(), 512);
EXPECT_TRUE(new_block->buffer() != nullptr);
blocks.push_back(new_block);
// Should be able to unpin and pin the middle block
EXPECT_TRUE(blocks[1]->unpin().ok());
bool pinned;
EXPECT_TRUE(blocks[1]->pin(&pinned).ok());
EXPECT_TRUE(pinned);
for (int i = 0; i < blocks.size(); ++i) {
blocks[i]->del();
}
TearDownMgrs();
}
// Test that pinning more blocks than the max available buffers.
TEST_F(BufferedBlockMgrTest, Pin) {
Status status;
int max_num_blocks = 5;
const int block_size = 1024;
BufferedBlockMgr2* block_mgr;
BufferedBlockMgr2::Client* client;
block_mgr = CreateMgrAndClient(0, max_num_blocks, block_size, 0, _client_tracker, &client);
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_blocks, &blocks);
// Unpin them all.
for (int i = 0; i < blocks.size(); ++i) {
status = blocks[i]->unpin();
EXPECT_TRUE(status.ok());
}
// Allocate more, this should work since we just unpinned some blocks.
AllocateBlocks(block_mgr, client, max_num_blocks, &blocks);
// Try to pin a unpinned block, this should not be possible.
bool pinned;
status = blocks[0]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_FALSE(pinned);
// Unpin all blocks.
for (int i = 0; i < blocks.size(); ++i) {
status = blocks[i]->unpin();
EXPECT_TRUE(status.ok());
}
// Should be able to pin max_num_blocks blocks.
for (int i = 0; i < max_num_blocks; ++i) {
status = blocks[i]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
}
// Can't pin any more though.
status = blocks[max_num_blocks]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_FALSE(pinned);
TearDownMgrs();
}
// Test the eviction policy of the block mgr. No writes issued until more than
// the max available buffers are allocated. Writes must be issued in LIFO order.
TEST_F(BufferedBlockMgrTest, Eviction) {
TestEvictionImpl(1024);
TestEvictionImpl(8 * 1024 * 1024);
}
// Test deletion and reuse of blocks.
TEST_F(BufferedBlockMgrTest, Deletion) {
int max_num_buffers = 5;
const int block_size = 1024;
BufferedBlockMgr2* block_mgr;
BufferedBlockMgr2::Client* client;
block_mgr = CreateMgrAndClient(0, max_num_buffers, block_size, 0, _client_tracker, &client);
// Check counters.
RuntimeProfile* profile = block_mgr->profile();
RuntimeProfile::Counter* recycled_cnt = profile->get_counter("BlocksRecycled");
RuntimeProfile::Counter* created_cnt = profile->get_counter("BlocksCreated");
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
EXPECT_TRUE(created_cnt->value() == max_num_buffers);
for (BufferedBlockMgr2::Block* block : blocks) {
block->del();
}
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
EXPECT_TRUE(created_cnt->value() == max_num_buffers);
EXPECT_TRUE(recycled_cnt->value() == max_num_buffers);
TearDownMgrs();
}
// Delete blocks of various sizes and statuses to exercise the different code paths.
// This relies on internal validation in block manager to detect many errors.
TEST_F(BufferedBlockMgrTest, DeleteSingleBlocks) {
int max_num_buffers = 16;
BufferedBlockMgr2::Client* client;
BufferedBlockMgr2* block_mgr =
CreateMgrAndClient(0, max_num_buffers, _block_size, 0, _client_tracker, &client);
// Pinned I/O block.
BufferedBlockMgr2::Block* new_block;
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_TRUE(new_block->is_pinned());
EXPECT_TRUE(new_block->is_max_size());
new_block->del();
EXPECT_TRUE(_client_tracker->consumption() == 0);
// Pinned non-I/O block.
int small_block_size = 128;
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block, small_block_size).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_TRUE(new_block->is_pinned());
EXPECT_EQ(small_block_size, _client_tracker->consumption());
new_block->del();
EXPECT_EQ(0, _client_tracker->consumption());
// Unpinned I/O block - delete after written to disk.
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_TRUE(new_block->is_pinned());
EXPECT_TRUE(new_block->is_max_size());
new_block->unpin();
EXPECT_FALSE(new_block->is_pinned());
WaitForWrites(block_mgr);
new_block->del();
EXPECT_TRUE(_client_tracker->consumption() == 0);
// Unpinned I/O block - delete before written to disk.
EXPECT_TRUE(block_mgr->get_new_block(client, nullptr, &new_block).ok());
EXPECT_TRUE(new_block != nullptr);
EXPECT_TRUE(new_block->is_pinned());
EXPECT_TRUE(new_block->is_max_size());
new_block->unpin();
EXPECT_FALSE(new_block->is_pinned());
new_block->del();
WaitForWrites(block_mgr);
EXPECT_TRUE(_client_tracker->consumption() == 0);
TearDownMgrs();
}
// Test that all APIs return cancelled after close.
TEST_F(BufferedBlockMgrTest, Close) {
int max_num_buffers = 5;
const int block_size = 1024;
BufferedBlockMgr2* block_mgr;
BufferedBlockMgr2::Client* client;
block_mgr = CreateMgrAndClient(0, max_num_buffers, block_size, 0, _client_tracker, &client);
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
block_mgr->cancel();
BufferedBlockMgr2::Block* new_block;
Status status = block_mgr->get_new_block(client, nullptr, &new_block);
EXPECT_TRUE(status.is_cancelled());
EXPECT_TRUE(new_block == nullptr);
status = blocks[0]->unpin();
EXPECT_TRUE(status.is_cancelled());
bool pinned;
status = blocks[0]->pin(&pinned);
EXPECT_TRUE(status.is_cancelled());
blocks[1]->del();
TearDownMgrs();
}
// Clear scratch directory. Return # of files deleted.
static int clear_scratch_dir() {
int num_files = 0;
directory_iterator dir_it(SCRATCH_DIR);
for (; dir_it != directory_iterator(); ++dir_it) {
++num_files;
remove_all(dir_it->path());
}
return num_files;
}
// Test that the block manager behaves correctly after a write error. Delete the scratch
// directory before an operation that would cause a write and test that subsequent API
// calls return 'CANCELLED' correctly.
TEST_F(BufferedBlockMgrTest, WriteError) {
Status status;
int max_num_buffers = 2;
const int block_size = 1024;
BufferedBlockMgr2* block_mgr;
BufferedBlockMgr2::Client* client;
block_mgr = CreateMgrAndClient(0, max_num_buffers, block_size, 0, _client_tracker, &client);
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
// Unpin two blocks here, to ensure that backing storage is allocated in tmp file.
for (int i = 0; i < 2; ++i) {
status = blocks[i]->unpin();
EXPECT_TRUE(status.ok());
}
WaitForWrites(block_mgr);
// Repin the blocks
for (int i = 0; i < 2; ++i) {
bool pinned;
status = blocks[i]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
}
// Remove the backing storage so that future writes will fail
int num_files = clear_scratch_dir();
EXPECT_TRUE(num_files > 0);
for (int i = 0; i < 2; ++i) {
status = blocks[i]->unpin();
EXPECT_TRUE(status.ok());
}
WaitForWrites(block_mgr);
// Subsequent calls should fail.
for (int i = 0; i < 2; ++i) {
blocks[i]->del();
}
BufferedBlockMgr2::Block* new_block;
status = block_mgr->get_new_block(client, nullptr, &new_block);
EXPECT_TRUE(status.is_cancelled());
EXPECT_TRUE(new_block == nullptr);
TearDownMgrs();
}
// Test block manager error handling when temporary file space cannot be allocated to
// back an unpinned buffer.
TEST_F(BufferedBlockMgrTest, TmpFileAllocateError) {
Status status;
int max_num_buffers = 2;
BufferedBlockMgr2::Client* client;
BufferedBlockMgr2* block_mgr =
CreateMgrAndClient(0, max_num_buffers, _block_size, 0, _client_tracker, &client);
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
// Unpin a block, forcing a write.
status = blocks[0]->unpin();
EXPECT_TRUE(status.ok());
WaitForWrites(block_mgr);
// Remove temporary files - subsequent operations will fail.
int num_files = clear_scratch_dir();
EXPECT_TRUE(num_files > 0);
// Current implementation will fail here because it tries to expand the tmp file
// immediately. This behavior is not contractual but we want to know if it changes
// accidentally.
status = blocks[1]->unpin();
EXPECT_FALSE(status.ok());
TearDownMgrs();
}
// Test that the block manager is able to blacklist a temporary device correctly after a
// write error. We should not allocate more blocks on that device, but existing blocks
// on the device will remain in use.
/// Disabled because blacklisting was disabled as workaround for IMPALA-2305.
TEST_F(BufferedBlockMgrTest, DISABLED_WriteErrorBlacklist) {
// TEST_F(BufferedBlockMgrTest, WriteErrorBlacklist) {
// Set up two buffered block managers with two temporary dirs.
std::vector<string> tmp_dirs = InitMultipleTmpDirs(2);
// Simulate two concurrent queries.
const int NUM_BLOCK_MGRS = 2;
const int MAX_NUM_BLOCKS = 4;
int blocks_per_mgr = MAX_NUM_BLOCKS / NUM_BLOCK_MGRS;
std::vector<BufferedBlockMgr2*> block_mgrs;
std::vector<BufferedBlockMgr2::Client*> clients;
CreateMgrsAndClients(0, NUM_BLOCK_MGRS, blocks_per_mgr, _block_size, 0, _client_tracker,
&block_mgrs, &clients);
// Allocate files for all 2x2 combinations by unpinning blocks.
std::vector<vector<BufferedBlockMgr2::Block*>> blocks;
std::vector<BufferedBlockMgr2::Block*> all_blocks;
for (int i = 0; i < NUM_BLOCK_MGRS; ++i) {
std::vector<BufferedBlockMgr2::Block*> mgr_blocks;
AllocateBlocks(block_mgrs[i], clients[i], blocks_per_mgr, &mgr_blocks);
UnpinBlocks(mgr_blocks);
for (int j = 0; j < blocks_per_mgr; ++j) {
LOG(INFO) << "Manager " << i << " Block " << j << " backed by file "
<< mgr_blocks[j]->tmp_file_path();
}
blocks.push_back(mgr_blocks);
all_blocks.insert(all_blocks.end(), mgr_blocks.begin(), mgr_blocks.end());
}
WaitForWrites(block_mgrs);
int error_mgr = 0;
int no_error_mgr = 1;
const string& error_dir = tmp_dirs[0];
const string& good_dir = tmp_dirs[1];
// Delete one file from first scratch dir for first block manager.
BufferedBlockMgr2::Block* error_block = FindBlockForDir(blocks[error_mgr], error_dir);
EXPECT_TRUE(error_block != nullptr) << "Expected a tmp file in dir " << error_dir;
PinBlocks(all_blocks);
DeleteBackingFile(error_block);
UnpinBlocks(all_blocks); // Should succeed since tmp file space was already allocated.
WaitForWrites(block_mgrs);
EXPECT_TRUE(block_mgrs[error_mgr]->is_cancelled());
EXPECT_FALSE(block_mgrs[no_error_mgr]->is_cancelled());
// Temporary device with error should no longer be active.
std::vector<TmpFileMgr::DeviceId> active_tmp_devices =
_test_env->tmp_file_mgr()->active_tmp_devices();
EXPECT_EQ(tmp_dirs.size() - 1, active_tmp_devices.size());
for (int i = 0; i < active_tmp_devices.size(); ++i) {
const string& device_path =
_test_env->tmp_file_mgr()->get_tmp_dir_path(active_tmp_devices[i]);
EXPECT_EQ(string::npos, error_dir.find(device_path));
}
// The second block manager should continue using allocated scratch space, since it
// didn't encounter a write error itself. In future this could change but for now it is
// the intended behaviour.
PinBlocks(blocks[no_error_mgr]);
UnpinBlocks(blocks[no_error_mgr]);
EXPECT_TRUE(FindBlockForDir(blocks[no_error_mgr], good_dir) != nullptr);
EXPECT_TRUE(FindBlockForDir(blocks[no_error_mgr], error_dir) != nullptr);
// The second block manager should avoid using bad directory for new blocks.
std::vector<BufferedBlockMgr2::Block*> no_error_new_blocks;
AllocateBlocks(block_mgrs[no_error_mgr], clients[no_error_mgr], blocks_per_mgr,
&no_error_new_blocks);
UnpinBlocks(no_error_new_blocks);
for (int i = 0; i < no_error_new_blocks.size(); ++i) {
LOG(INFO) << "Newly created block backed by file "
<< no_error_new_blocks[i]->tmp_file_path();
EXPECT_TRUE(BlockInDir(no_error_new_blocks[i], good_dir));
}
// A new block manager should only use the good dir for backing storage.
BufferedBlockMgr2::Client* new_client;
BufferedBlockMgr2* new_block_mgr =
CreateMgrAndClient(9999, blocks_per_mgr, _block_size, 0, _client_tracker, &new_client);
std::vector<BufferedBlockMgr2::Block*> new_mgr_blocks;
AllocateBlocks(new_block_mgr, new_client, blocks_per_mgr, &new_mgr_blocks);
UnpinBlocks(new_mgr_blocks);
for (int i = 0; i < blocks_per_mgr; ++i) {
LOG(INFO) << "New manager Block " << i << " backed by file "
<< new_mgr_blocks[i]->tmp_file_path();
EXPECT_TRUE(BlockInDir(new_mgr_blocks[i], good_dir));
}
}
// Check that allocation error resulting from removal of directory results in blocks
/// being allocated in other directories.
TEST_F(BufferedBlockMgrTest, AllocationErrorHandling) {
// Set up two buffered block managers with two temporary dirs.
std::vector<string> tmp_dirs = InitMultipleTmpDirs(2);
// Simulate two concurrent queries.
int num_block_mgrs = 2;
int max_num_blocks = 4;
int blocks_per_mgr = max_num_blocks / num_block_mgrs;
// std::vector<RuntimeState*> runtime_states;
std::vector<BufferedBlockMgr2*> block_mgrs;
std::vector<BufferedBlockMgr2::Client*> clients;
CreateMgrsAndClients(0, num_block_mgrs, blocks_per_mgr, _block_size, 0, _client_tracker,
&block_mgrs, &clients);
// Allocate files for all 2x2 combinations by unpinning blocks.
std::vector<vector<BufferedBlockMgr2::Block*>> blocks;
for (int i = 0; i < num_block_mgrs; ++i) {
std::vector<BufferedBlockMgr2::Block*> mgr_blocks;
LOG(INFO) << "Iter " << i;
AllocateBlocks(block_mgrs[i], clients[i], blocks_per_mgr, &mgr_blocks);
blocks.push_back(mgr_blocks);
}
const string& bad_dir = tmp_dirs[0];
const string& bad_scratch_subdir = bad_dir + SCRATCH_SUFFIX;
// const string& good_dir = tmp_dirs[1];
// const string& good_scratch_subdir = good_dir + SCRATCH_SUFFIX;
chmod(bad_scratch_subdir.c_str(), 0);
// The block mgr should attempt to allocate space in bad dir for one block, which will
// cause an error when it tries to create/expand the file. It should recover and just
// use the good dir.
UnpinBlocks(blocks[0]);
// Directories remain on active list even when they experience errors.
EXPECT_EQ(2, _test_env->tmp_file_mgr()->num_active_tmp_devices());
// Blocks should not be written to bad dir even if it remains non-writable.
UnpinBlocks(blocks[1]);
// All writes should succeed.
WaitForWrites(block_mgrs);
for (int i = 0; i < blocks.size(); ++i) {
for (int j = 0; j < blocks[i].size(); ++j) {
blocks[i][j]->del();
}
}
}
// Test that block manager fails cleanly when all directories are inaccessible at runtime.
TEST_F(BufferedBlockMgrTest, NoDirsAllocationError) {
std::vector<string> tmp_dirs = InitMultipleTmpDirs(2);
int max_num_buffers = 2;
BufferedBlockMgr2::Client* client;
BufferedBlockMgr2* block_mgr =
CreateMgrAndClient(0, max_num_buffers, _block_size, 0, _client_tracker, &client);
std::vector<BufferedBlockMgr2::Block*> blocks;
AllocateBlocks(block_mgr, client, max_num_buffers, &blocks);
for (int i = 0; i < tmp_dirs.size(); ++i) {
const string& tmp_scratch_subdir = tmp_dirs[i] + SCRATCH_SUFFIX;
chmod(tmp_scratch_subdir.c_str(), 0);
}
for (int i = 0; i < blocks.size(); ++i) {
EXPECT_FALSE(blocks[i]->unpin().ok());
}
}
// Create two clients with different number of reserved buffers.
TEST_F(BufferedBlockMgrTest, MultipleClients) {
Status status;
int client1_buffers = 3;
int client2_buffers = 5;
int max_num_buffers = client1_buffers + client2_buffers;
const int block_size = 1024;
RuntimeState* runtime_state;
BufferedBlockMgr2* block_mgr = CreateMgr(0, max_num_buffers, block_size, &runtime_state);
BufferedBlockMgr2::Client* client1 = nullptr;
BufferedBlockMgr2::Client* client2 = nullptr;
status = block_mgr->register_client(client1_buffers, _client_tracker, runtime_state, &client1);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client1 != nullptr);
status = block_mgr->register_client(client2_buffers, _client_tracker, runtime_state, &client2);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client2 != nullptr);
// Reserve client 1's and 2's buffers. They should succeed.
bool reserved = block_mgr->try_acquire_tmp_reservation(client1, 1);
EXPECT_TRUE(reserved);
reserved = block_mgr->try_acquire_tmp_reservation(client2, 1);
EXPECT_TRUE(reserved);
std::vector<BufferedBlockMgr2::Block*> client1_blocks;
// Allocate all of client1's reserved blocks, they should all succeed.
AllocateBlocks(block_mgr, client1, client1_buffers, &client1_blocks);
// Try allocating one more, that should fail.
BufferedBlockMgr2::Block* block;
status = block_mgr->get_new_block(client1, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block == nullptr);
// Trying to reserve should also fail.
reserved = block_mgr->try_acquire_tmp_reservation(client1, 1);
EXPECT_FALSE(reserved);
// Allocate all of client2's reserved blocks, these should succeed.
std::vector<BufferedBlockMgr2::Block*> client2_blocks;
AllocateBlocks(block_mgr, client2, client2_buffers, &client2_blocks);
// Try allocating one more from client 2, that should fail.
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block == nullptr);
// Unpin one block from client 1.
status = client1_blocks[0]->unpin();
EXPECT_TRUE(status.ok());
// Client 2 should still not be able to allocate.
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block == nullptr);
// Client 2 should still not be able to reserve.
reserved = block_mgr->try_acquire_tmp_reservation(client2, 1);
EXPECT_FALSE(reserved);
// Client 1 should be able to though.
status = block_mgr->get_new_block(client1, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block != nullptr);
// Unpin two of client 1's blocks (client 1 should have 3 unpinned blocks now).
status = client1_blocks[1]->unpin();
EXPECT_TRUE(status.ok());
status = client1_blocks[2]->unpin();
EXPECT_TRUE(status.ok());
// Clear client 1's reservation
block_mgr->clear_reservations(client1);
// Client 2 should be able to reserve 1 buffers now (there are 2 left);
reserved = block_mgr->try_acquire_tmp_reservation(client2, 1);
EXPECT_TRUE(reserved);
// Client one can only pin 1.
bool pinned;
status = client1_blocks[0]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
// Can't get this one.
status = client1_blocks[1]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_FALSE(pinned);
// Client 2 can pick up the one reserved buffer
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block != nullptr);
// But not a second
BufferedBlockMgr2::Block* block2;
status = block_mgr->get_new_block(client2, nullptr, &block2);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block2 == nullptr);
// Unpin client 2's block it got from the reservation. Sine this is a tmp
// reservation, client 1 can pick it up again (it is not longer reserved).
status = block->unpin();
EXPECT_TRUE(status.ok());
status = client1_blocks[1]->pin(&pinned);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(pinned);
TearDownMgrs();
}
// Create two clients with different number of reserved buffers and some additional.
TEST_F(BufferedBlockMgrTest, MultipleClientsExtraBuffers) {
Status status;
int client1_buffers = 1;
int client2_buffers = 1;
int max_num_buffers = client1_buffers + client2_buffers + 2;
const int block_size = 1024;
RuntimeState* runtime_state;
BufferedBlockMgr2* block_mgr = CreateMgr(0, max_num_buffers, block_size, &runtime_state);
BufferedBlockMgr2::Client* client1 = nullptr;
BufferedBlockMgr2::Client* client2 = nullptr;
BufferedBlockMgr2::Block* block = nullptr;
status = block_mgr->register_client(client1_buffers, _client_tracker, runtime_state, &client1);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client1 != nullptr);
status = block_mgr->register_client(client2_buffers, _client_tracker, runtime_state, &client2);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client2 != nullptr);
std::vector<BufferedBlockMgr2::Block*> client1_blocks;
// Allocate all of client1's reserved blocks, they should all succeed.
AllocateBlocks(block_mgr, client1, client1_buffers, &client1_blocks);
// Allocate all of client2's reserved blocks, these should succeed.
std::vector<BufferedBlockMgr2::Block*> client2_blocks;
AllocateBlocks(block_mgr, client2, client2_buffers, &client2_blocks);
// We have two spare buffers now. Each client should be able to allocate it.
status = block_mgr->get_new_block(client1, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block != nullptr);
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block != nullptr);
// Now we are completely full, no one should be able to allocate a new block.
status = block_mgr->get_new_block(client1, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block == nullptr);
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block == nullptr);
TearDownMgrs();
}
// Create two clients causing oversubscription.
TEST_F(BufferedBlockMgrTest, ClientOversubscription) {
Status status;
int client1_buffers = 1;
int client2_buffers = 2;
int max_num_buffers = 2;
const int block_size = 1024;
RuntimeState* runtime_state;
BufferedBlockMgr2* block_mgr = CreateMgr(0, max_num_buffers, block_size, &runtime_state);
BufferedBlockMgr2::Client* client1 = nullptr;
BufferedBlockMgr2::Client* client2 = nullptr;
BufferedBlockMgr2::Block* block = nullptr;
status = block_mgr->register_client(client1_buffers, _client_tracker, runtime_state, &client1);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client1 != nullptr);
status = block_mgr->register_client(client2_buffers, _client_tracker, runtime_state, &client2);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(client2 != nullptr);
// Client one allocates first block, should work.
status = block_mgr->get_new_block(client1, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block != nullptr);
// Client two allocates first block, should work.
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block != nullptr);
// At this point we've used both buffers. Client one reserved one so subsequent
// calls should fail with no error (but returns no block).
status = block_mgr->get_new_block(client1, nullptr, &block);
EXPECT_TRUE(status.ok());
EXPECT_TRUE(block == nullptr);
// Allocate with client two. Since client two reserved 2 buffers, this should fail
// with MEM_LIMIT_EXCEEDED.
status = block_mgr->get_new_block(client2, nullptr, &block);
EXPECT_TRUE(status.is_mem_limit_exceeded());
TearDownMgrs();
}
TEST_F(BufferedBlockMgrTest, SingleRandom_plain) {
TestRandomInternalSingle(1024);
TestRandomInternalSingle(8 * 1024);
TestRandomInternalSingle(8 * 1024 * 1024);
}
TEST_F(BufferedBlockMgrTest, Multi2Random_plain) {
TestRandomInternalMulti(2, 1024);
TestRandomInternalMulti(2, 8 * 1024);
TestRandomInternalMulti(2, 8 * 1024 * 1024);
}
TEST_F(BufferedBlockMgrTest, Multi4Random_plain) {
TestRandomInternalMulti(4, 1024);
TestRandomInternalMulti(4, 8 * 1024);
TestRandomInternalMulti(4, 8 * 1024 * 1024);
}
// TODO: Enable when we improve concurrency/scalability of block mgr.
TEST_F(BufferedBlockMgrTest, DISABLED_Multi8Random_plain) {
TestRandomInternalMulti(8, 1024);
}
TEST_F(BufferedBlockMgrTest, CreateDestroyMulti) {
CreateDestroyMulti();
}
} // end namespace doris
| 41.21746 | 100 | 0.652694 | [
"vector"
] |
f555ede478a7edcad797ed33627fef0a286d6be6 | 42,917 | cpp | C++ | src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp | FrenchCORE/OLD_FrenchCORE | edf1a2859246493c0667b44497c4bbb0fe718cbd | [
"OpenSSL"
] | 1 | 2019-12-03T18:41:39.000Z | 2019-12-03T18:41:39.000Z | src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp | FrenchCORE/OLD_FrenchCORE | edf1a2859246493c0667b44497c4bbb0fe718cbd | [
"OpenSSL"
] | null | null | null | src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp | FrenchCORE/OLD_FrenchCORE | edf1a2859246493c0667b44497c4bbb0fe718cbd | [
"OpenSSL"
] | null | null | null | /*
* Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gamePCH.h"
#include "ObjectMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "BattlegroundMgr.h"
#include "Battleground.h"
#include "BattlegroundEY.h"
#include "Creature.h"
#include "Language.h"
#include "Object.h"
#include "Player.h"
#include "Util.h"
// these variables aren't used outside of this file, so declare them only here
uint32 BG_EY_HonorScoreTicks[BG_HONOR_MODE_NUM] = {
330, // normal honor
200 // holiday
};
BattlegroundEY::BattlegroundEY()
{
m_BuffChange = true;
m_BgObjects.resize(BG_EY_OBJECT_MAX);
m_BgCreatures.resize(BG_EY_CREATURES_MAX);
m_Points_Trigger[FEL_REAVER] = TR_FEL_REAVER_BUFF;
m_Points_Trigger[BLOOD_ELF] = TR_BLOOD_ELF_BUFF;
m_Points_Trigger[DRAENEI_RUINS] = TR_DRAENEI_RUINS_BUFF;
m_Points_Trigger[MAGE_TOWER] = TR_MAGE_TOWER_BUFF;
m_StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_BG_EY_START_TWO_MINUTES;
m_StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_BG_EY_START_ONE_MINUTE;
m_StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_BG_EY_START_HALF_MINUTE;
m_StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_BG_EY_HAS_BEGUN;
}
BattlegroundEY::~BattlegroundEY()
{
}
void BattlegroundEY::Update(uint32 diff)
{
Battleground::Update(diff);
if (GetStatus() == STATUS_IN_PROGRESS)
{
m_PointAddingTimer -= diff;
if (m_PointAddingTimer <= 0)
{
m_PointAddingTimer = BG_EY_FPOINTS_TICK_TIME;
if (m_TeamPointsCount[BG_TEAM_ALLIANCE] > 0)
AddPoints(ALLIANCE, BG_EY_TickPoints[m_TeamPointsCount[BG_TEAM_ALLIANCE] - 1]);
if (m_TeamPointsCount[BG_TEAM_HORDE] > 0)
AddPoints(HORDE, BG_EY_TickPoints[m_TeamPointsCount[BG_TEAM_HORDE] - 1]);
}
if (m_FlagState == BG_EY_FLAG_STATE_WAIT_RESPAWN || m_FlagState == BG_EY_FLAG_STATE_ON_GROUND)
{
m_FlagsTimer -= diff;
if (m_FlagsTimer < 0)
{
m_FlagsTimer = 0;
if (m_FlagState == BG_EY_FLAG_STATE_WAIT_RESPAWN)
RespawnFlag(true);
else
RespawnFlagAfterDrop();
}
}
m_TowerCapCheckTimer -= diff;
if (m_TowerCapCheckTimer <= 0)
{
//check if player joined point
/*I used this order of calls, because although we will check if one player is in gameobject's distance 2 times
but we can count of players on current point in CheckSomeoneLeftPoint
*/
this->CheckSomeoneJoinedPoint();
//check if player left point
this->CheckSomeoneLeftPoint();
this->UpdatePointStatuses();
m_TowerCapCheckTimer = BG_EY_FPOINTS_TICK_TIME;
}
}
}
void BattlegroundEY::StartingEventCloseDoors()
{
SpawnBGObject(BG_EY_OBJECT_DOOR_A, RESPAWN_IMMEDIATELY);
SpawnBGObject(BG_EY_OBJECT_DOOR_H, RESPAWN_IMMEDIATELY);
for (uint32 i = BG_EY_OBJECT_A_BANNER_FEL_REAVER_CENTER; i < BG_EY_OBJECT_MAX; ++i)
SpawnBGObject(i, RESPAWN_ONE_DAY);
}
void BattlegroundEY::StartingEventOpenDoors()
{
SpawnBGObject(BG_EY_OBJECT_DOOR_A, RESPAWN_ONE_DAY);
SpawnBGObject(BG_EY_OBJECT_DOOR_H, RESPAWN_ONE_DAY);
for (uint32 i = BG_EY_OBJECT_N_BANNER_FEL_REAVER_CENTER; i <= BG_EY_OBJECT_FLAG_NETHERSTORM; ++i)
SpawnBGObject(i, RESPAWN_IMMEDIATELY);
for (uint32 i = 0; i < EY_POINTS_MAX; ++i)
{
//randomly spawn buff
uint8 buff = urand(0, 2);
SpawnBGObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + buff + i * 3, RESPAWN_IMMEDIATELY);
}
// Achievement: Flurry
StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EY_EVENT_START_BATTLE);
}
void BattlegroundEY::AddPoints(uint32 Team, uint32 Points)
{
BattlegroundTeamId team_index = GetTeamIndexByTeamId(Team);
m_TeamScores[team_index] += Points;
m_HonorScoreTics[team_index] += Points;
if (m_HonorScoreTics[team_index] >= m_HonorTics)
{
RewardHonorToTeam(GetBonusHonorFromKill(1), Team);
m_HonorScoreTics[team_index] -= m_HonorTics;
}
UpdateTeamScore(Team);
}
void BattlegroundEY::CheckSomeoneJoinedPoint()
{
GameObject *obj = NULL;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
obj = HashMapHolder<GameObject>::Find(m_BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]);
if (obj)
{
uint8 j = 0;
while (j < m_PlayersNearPoint[EY_POINTS_MAX].size())
{
Player *plr = sObjectMgr->GetPlayer(m_PlayersNearPoint[EY_POINTS_MAX][j]);
if (!plr)
{
sLog->outError("BattlegroundEY:CheckSomeoneJoinedPoint: Player (GUID: %u) not found!", GUID_LOPART(m_PlayersNearPoint[EY_POINTS_MAX][j]));
++j;
continue;
}
if (plr->CanCaptureTowerPoint() && plr->IsWithinDistInMap(obj, BG_EY_POINT_RADIUS))
{
//player joined point!
//show progress bar
UpdateWorldStateForPlayer(PROGRESS_BAR_PERCENT_GREY, BG_EY_PROGRESS_BAR_PERCENT_GREY, plr);
UpdateWorldStateForPlayer(PROGRESS_BAR_STATUS, m_PointBarStatus[i], plr);
UpdateWorldStateForPlayer(PROGRESS_BAR_SHOW, BG_EY_PROGRESS_BAR_SHOW, plr);
//add player to point
m_PlayersNearPoint[i].push_back(m_PlayersNearPoint[EY_POINTS_MAX][j]);
//remove player from "free space"
m_PlayersNearPoint[EY_POINTS_MAX].erase(m_PlayersNearPoint[EY_POINTS_MAX].begin() + j);
}
else
++j;
}
}
}
}
void BattlegroundEY::CheckSomeoneLeftPoint()
{
//reset current point counts
for (uint8 i = 0; i < 2*EY_POINTS_MAX; ++i)
m_CurrentPointPlayersCount[i] = 0;
GameObject *obj = NULL;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
obj = HashMapHolder<GameObject>::Find(m_BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]);
if (obj)
{
uint8 j = 0;
while (j < m_PlayersNearPoint[i].size())
{
Player *plr = sObjectMgr->GetPlayer(m_PlayersNearPoint[i][j]);
if (!plr)
{
sLog->outError("BattlegroundEY:CheckSomeoneLeftPoint Player (GUID: %u) not found!", GUID_LOPART(m_PlayersNearPoint[i][j]));
//move not existed player to "free space" - this will cause many error showing in log, but it is a very important bug
m_PlayersNearPoint[EY_POINTS_MAX].push_back(m_PlayersNearPoint[i][j]);
m_PlayersNearPoint[i].erase(m_PlayersNearPoint[i].begin() + j);
++j;
continue;
}
if (!plr->CanCaptureTowerPoint() || !plr->IsWithinDistInMap(obj, BG_EY_POINT_RADIUS))
//move player out of point (add him to players that are out of points
{
m_PlayersNearPoint[EY_POINTS_MAX].push_back(m_PlayersNearPoint[i][j]);
m_PlayersNearPoint[i].erase(m_PlayersNearPoint[i].begin() + j);
this->UpdateWorldStateForPlayer(PROGRESS_BAR_SHOW, BG_EY_PROGRESS_BAR_DONT_SHOW, plr);
}
else
{
//player is neat flag, so update count:
m_CurrentPointPlayersCount[2 * i + GetTeamIndexByTeamId(plr->GetTeam())]++;
++j;
}
}
}
}
}
void BattlegroundEY::UpdatePointStatuses()
{
for (uint8 point = 0; point < EY_POINTS_MAX; ++point)
{
if (m_PlayersNearPoint[point].empty())
continue;
//count new point bar status:
m_PointBarStatus[point] += (m_CurrentPointPlayersCount[2 * point] - m_CurrentPointPlayersCount[2 * point + 1] < BG_EY_POINT_MAX_CAPTURERS_COUNT) ? m_CurrentPointPlayersCount[2 * point] - m_CurrentPointPlayersCount[2 * point + 1] : BG_EY_POINT_MAX_CAPTURERS_COUNT;
if (m_PointBarStatus[point] > BG_EY_PROGRESS_BAR_ALI_CONTROLLED)
//point is fully alliance's
m_PointBarStatus[point] = BG_EY_PROGRESS_BAR_ALI_CONTROLLED;
if (m_PointBarStatus[point] < BG_EY_PROGRESS_BAR_HORDE_CONTROLLED)
//point is fully horde's
m_PointBarStatus[point] = BG_EY_PROGRESS_BAR_HORDE_CONTROLLED;
uint32 pointOwnerTeamId = 0;
//find which team should own this point
if (m_PointBarStatus[point] <= BG_EY_PROGRESS_BAR_NEUTRAL_LOW)
pointOwnerTeamId = HORDE;
else if (m_PointBarStatus[point] >= BG_EY_PROGRESS_BAR_NEUTRAL_HIGH)
pointOwnerTeamId = ALLIANCE;
else
pointOwnerTeamId = EY_POINT_NO_OWNER;
for (uint8 i = 0; i < m_PlayersNearPoint[point].size(); ++i)
{
Player *plr = sObjectMgr->GetPlayer(m_PlayersNearPoint[point][i]);
if (plr)
{
this->UpdateWorldStateForPlayer(PROGRESS_BAR_STATUS, m_PointBarStatus[point], plr);
//if point owner changed we must evoke event!
if (pointOwnerTeamId != m_PointOwnedByTeam[point])
{
//point was uncontrolled and player is from team which captured point
if (m_PointState[point] == EY_POINT_STATE_UNCONTROLLED && plr->GetTeam() == pointOwnerTeamId)
this->EventTeamCapturedPoint(plr, point);
//point was under control and player isn't from team which controlled it
if (m_PointState[point] == EY_POINT_UNDER_CONTROL && plr->GetTeam() != m_PointOwnedByTeam[point])
this->EventTeamLostPoint(plr, point);
}
}
}
}
}
void BattlegroundEY::UpdateTeamScore(uint32 Team)
{
uint32 score = GetTeamScore(Team);
//TODO there should be some sound played when one team is near victory!! - and define variables
/*if (!m_IsInformedNearVictory && score >= BG_EY_WARNING_NEAR_VICTORY_SCORE)
{
if (Team == ALLIANCE)
SendMessageToAll(LANG_BG_EY_A_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL);
else
SendMessageToAll(LANG_BG_EY_H_NEAR_VICTORY, CHAT_MSG_BG_SYSTEM_NEUTRAL);
PlaySoundToAll(BG_EY_SOUND_NEAR_VICTORY);
m_IsInformedNearVictory = true;
}*/
if (score >= BG_EY_MAX_TEAM_SCORE)
{
score = BG_EY_MAX_TEAM_SCORE;
EndBattleground(Team);
}
if (Team == ALLIANCE)
UpdateWorldState(EY_ALLIANCE_RESOURCES, score);
else
UpdateWorldState(EY_HORDE_RESOURCES, score);
}
void BattlegroundEY::EndBattleground(uint32 winner)
{
//win reward
if (winner == ALLIANCE)
RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE);
if (winner == HORDE)
RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE);
//complete map reward
RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE);
RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE);
Battleground::EndBattleground(winner);
}
void BattlegroundEY::UpdatePointsCount(uint32 Team)
{
if (Team == ALLIANCE)
UpdateWorldState(EY_ALLIANCE_BASE, m_TeamPointsCount[BG_TEAM_ALLIANCE]);
else
UpdateWorldState(EY_HORDE_BASE, m_TeamPointsCount[BG_TEAM_HORDE]);
}
void BattlegroundEY::UpdatePointsIcons(uint32 Team, uint32 Point)
{
//we MUST firstly send 0, after that we can send 1!!!
if (m_PointState[Point] == EY_POINT_UNDER_CONTROL)
{
UpdateWorldState(m_PointsIconStruct[Point].WorldStateControlIndex, 0);
if (Team == ALLIANCE)
UpdateWorldState(m_PointsIconStruct[Point].WorldStateAllianceControlledIndex, 1);
else
UpdateWorldState(m_PointsIconStruct[Point].WorldStateHordeControlledIndex, 1);
}
else
{
if (Team == ALLIANCE)
UpdateWorldState(m_PointsIconStruct[Point].WorldStateAllianceControlledIndex, 0);
else
UpdateWorldState(m_PointsIconStruct[Point].WorldStateHordeControlledIndex, 0);
UpdateWorldState(m_PointsIconStruct[Point].WorldStateControlIndex, 1);
}
}
void BattlegroundEY::AddPlayer(Player *plr)
{
Battleground::AddPlayer(plr);
//create score and add it to map
BattlegroundEYScore* sc = new BattlegroundEYScore;
m_PlayersNearPoint[EY_POINTS_MAX].push_back(plr->GetGUID());
m_PlayerScores[plr->GetGUID()] = sc;
}
void BattlegroundEY::RemovePlayer(Player *plr, uint64 guid)
{
// sometimes flag aura not removed :(
for (int j = EY_POINTS_MAX; j >= 0; --j)
{
for (size_t i = 0; i < m_PlayersNearPoint[j].size(); ++i)
if (m_PlayersNearPoint[j][i] == guid)
m_PlayersNearPoint[j].erase(m_PlayersNearPoint[j].begin() + i);
}
if (IsFlagPickedup())
{
if (m_FlagKeeper == guid)
{
if (plr)
EventPlayerDroppedFlag(plr);
else
{
SetFlagPicker(0);
RespawnFlag(true);
}
}
}
}
void BattlegroundEY::HandleAreaTrigger(Player *Source, uint32 Trigger)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
if (!Source->isAlive()) //hack code, must be removed later
return;
switch(Trigger)
{
case TR_BLOOD_ELF_POINT:
if (m_PointState[BLOOD_ELF] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[BLOOD_ELF] == Source->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == Source->GetGUID())
EventPlayerCapturedFlag(Source, BG_EY_OBJECT_FLAG_BLOOD_ELF);
break;
case TR_FEL_REAVER_POINT:
if (m_PointState[FEL_REAVER] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[FEL_REAVER] == Source->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == Source->GetGUID())
EventPlayerCapturedFlag(Source, BG_EY_OBJECT_FLAG_FEL_REAVER);
break;
case TR_MAGE_TOWER_POINT:
if (m_PointState[MAGE_TOWER] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[MAGE_TOWER] == Source->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == Source->GetGUID())
EventPlayerCapturedFlag(Source, BG_EY_OBJECT_FLAG_MAGE_TOWER);
break;
case TR_DRAENEI_RUINS_POINT:
if (m_PointState[DRAENEI_RUINS] == EY_POINT_UNDER_CONTROL && m_PointOwnedByTeam[DRAENEI_RUINS] == Source->GetTeam())
if (m_FlagState && GetFlagPickerGUID() == Source->GetGUID())
EventPlayerCapturedFlag(Source, BG_EY_OBJECT_FLAG_DRAENEI_RUINS);
break;
case 4512:
case 4515:
case 4517:
case 4519:
case 4530:
case 4531:
case 4568:
case 4569:
case 4570:
case 4571:
case 5866:
break;
default:
sLog->outError("WARNING: Unhandled AreaTrigger in Battleground: %u", Trigger);
Source->GetSession()->SendAreaTriggerMessage("Warning: Unhandled AreaTrigger in Battleground: %u", Trigger);
break;
}
}
bool BattlegroundEY::SetupBattleground()
{
// doors
if (!AddObject(BG_EY_OBJECT_DOOR_A, BG_OBJECT_A_DOOR_EY_ENTRY, 2527.6f, 1596.91f, 1262.13f, -3.12414f, -0.173642f, -0.001515f, 0.98477f, -0.008594f, RESPAWN_IMMEDIATELY)
|| !AddObject(BG_EY_OBJECT_DOOR_H, BG_OBJECT_H_DOOR_EY_ENTRY, 1803.21f, 1539.49f, 1261.09f, 3.14159f, 0.173648f, 0, 0.984808f, 0, RESPAWN_IMMEDIATELY)
// banners (alliance)
|| !AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_BLOOD_ELF_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2047.19f, 1349.19f, 1189.0f, -1.62316f, 0, 0, 0.725374f, -0.688354f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_BLOOD_ELF_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2074.32f, 1385.78f, 1194.72f, 0.488692f, 0, 0, 0.241922f, 0.970296f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_BLOOD_ELF_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2025.13f, 1386.12f, 1192.74f, 2.3911f, 0, 0, 0.930418f, 0.366501f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_DRAENEI_RUINS_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2276.8f, 1400.41f, 1196.33f, 2.44346f, 0, 0, 0.939693f, 0.34202f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_DRAENEI_RUINS_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2305.78f, 1404.56f, 1199.38f, 1.74533f, 0, 0, 0.766044f, 0.642788f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_DRAENEI_RUINS_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2245.4f, 1366.41f, 1195.28f, 2.21657f, 0, 0, 0.894934f, 0.446198f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_A_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_A_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_A_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_A_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY)
// banners (horde)
|| !AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_BLOOD_ELF_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2047.19f, 1349.19f, 1189.0f, -1.62316f, 0, 0, 0.725374f, -0.688354f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_BLOOD_ELF_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2074.32f, 1385.78f, 1194.72f, 0.488692f, 0, 0, 0.241922f, 0.970296f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_BLOOD_ELF_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2025.13f, 1386.12f, 1192.74f, 2.3911f, 0, 0, 0.930418f, 0.366501f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_DRAENEI_RUINS_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2276.8f, 1400.41f, 1196.33f, 2.44346f, 0, 0, 0.939693f, 0.34202f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_DRAENEI_RUINS_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2305.78f, 1404.56f, 1199.38f, 1.74533f, 0, 0, 0.766044f, 0.642788f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_DRAENEI_RUINS_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2245.4f, 1366.41f, 1195.28f, 2.21657f, 0, 0, 0.894934f, 0.446198f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_H_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_H_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_H_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_H_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY)
// banners (natural)
|| !AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2057.46f, 1735.07f, 1187.91f, -0.925024f, 0, 0, 0.446198f, -0.894934f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2032.25f, 1729.53f, 1190.33f, 1.8675f, 0, 0, 0.803857f, 0.594823f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_FEL_REAVER_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2092.35f, 1775.46f, 1187.08f, -0.401426f, 0, 0, 0.199368f, -0.979925f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_BLOOD_ELF_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2047.19f, 1349.19f, 1189.0f, -1.62316f, 0, 0, 0.725374f, -0.688354f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_BLOOD_ELF_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2074.32f, 1385.78f, 1194.72f, 0.488692f, 0, 0, 0.241922f, 0.970296f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_BLOOD_ELF_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2025.13f, 1386.12f, 1192.74f, 2.3911f, 0, 0, 0.930418f, 0.366501f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_DRAENEI_RUINS_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2276.8f, 1400.41f, 1196.33f, 2.44346f, 0, 0, 0.939693f, 0.34202f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_DRAENEI_RUINS_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2305.78f, 1404.56f, 1199.38f, 1.74533f, 0, 0, 0.766044f, 0.642788f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_DRAENEI_RUINS_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2245.4f, 1366.41f, 1195.28f, 2.21657f, 0, 0, 0.894934f, 0.446198f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_CENTER, BG_OBJECT_N_BANNER_EY_ENTRY, 2270.84f, 1784.08f, 1186.76f, 2.42601f, 0, 0, 0.936672f, 0.350207f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_LEFT, BG_OBJECT_N_BANNER_EY_ENTRY, 2269.13f, 1737.7f, 1186.66f, 0.994838f, 0, 0, 0.477159f, 0.878817f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_N_BANNER_MAGE_TOWER_RIGHT, BG_OBJECT_N_BANNER_EY_ENTRY, 2300.86f, 1741.25f, 1187.7f, -0.785398f, 0, 0, 0.382683f, -0.92388f, RESPAWN_ONE_DAY)
// flags
|| !AddObject(BG_EY_OBJECT_FLAG_NETHERSTORM, BG_OBJECT_FLAG2_EY_ENTRY, 2174.782227f, 1569.054688f, 1160.361938f, -1.448624f, 0, 0, 0.662620f, -0.748956f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_FEL_REAVER, BG_OBJECT_FLAG1_EY_ENTRY, 2044.28f, 1729.68f, 1189.96f, -0.017453f, 0, 0, 0.008727f, -0.999962f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_BLOOD_ELF, BG_OBJECT_FLAG1_EY_ENTRY, 2048.83f, 1393.65f, 1194.49f, 0.20944f, 0, 0, 0.104528f, 0.994522f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_DRAENEI_RUINS, BG_OBJECT_FLAG1_EY_ENTRY, 2286.56f, 1402.36f, 1197.11f, 3.72381f, 0, 0, 0.957926f, -0.287016f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_FLAG_MAGE_TOWER, BG_OBJECT_FLAG1_EY_ENTRY, 2284.48f, 1731.23f, 1189.99f, 2.89725f, 0, 0, 0.992546f, 0.121869f, RESPAWN_ONE_DAY)
// tower cap
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_FEL_REAVER, BG_OBJECT_FR_TOWER_CAP_EY_ENTRY, 2024.600708f, 1742.819580f, 1195.157715f, 2.443461f, 0, 0, 0.939693f, 0.342020f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_BLOOD_ELF, BG_OBJECT_BE_TOWER_CAP_EY_ENTRY, 2050.493164f, 1372.235962f, 1194.563477f, 1.710423f, 0, 0, 0.754710f, 0.656059f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_DRAENEI_RUINS, BG_OBJECT_DR_TOWER_CAP_EY_ENTRY, 2301.010498f, 1386.931641f, 1197.183472f, 1.570796f, 0, 0, 0.707107f, 0.707107f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_TOWER_CAP_MAGE_TOWER, BG_OBJECT_HU_TOWER_CAP_EY_ENTRY, 2282.121582f, 1760.006958f, 1189.707153f, 1.919862f, 0, 0, 0.819152f, 0.573576f, RESPAWN_ONE_DAY)
)
{
sLog->outErrorDb("BatteGroundEY: Failed to spawn some object Battleground not created!");
return false;
}
//buffs
for (int i = 0; i < EY_POINTS_MAX; ++i)
{
AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(m_Points_Trigger[i]);
if (!at)
{
sLog->outError("BattlegroundEY: Unknown trigger: %u", m_Points_Trigger[i]);
continue;
}
if (!AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3, Buff_Entries[0], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + 1, Buff_Entries[1], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY)
|| !AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + 2, Buff_Entries[2], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY)
)
sLog->outError("BattlegroundEY: Cannot spawn buff");
}
WorldSafeLocsEntry const *sg = NULL;
sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_ALLIANCE);
if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_ALLIANCE, sg->x, sg->y, sg->z, 3.124139f, ALLIANCE))
{
sLog->outErrorDb("BatteGroundEY: Failed to spawn spirit guide! Battleground not created!");
return false;
}
sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_HORDE);
if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_HORDE, sg->x, sg->y, sg->z, 3.193953f, HORDE))
{
sLog->outErrorDb("BatteGroundEY: Failed to spawn spirit guide! Battleground not created!");
return false;
}
return true;
}
void BattlegroundEY::Reset()
{
//call parent's class reset
Battleground::Reset();
m_TeamScores[BG_TEAM_ALLIANCE] = 0;
m_TeamScores[BG_TEAM_HORDE] = 0;
m_TeamPointsCount[BG_TEAM_ALLIANCE] = 0;
m_TeamPointsCount[BG_TEAM_HORDE] = 0;
m_HonorScoreTics[BG_TEAM_ALLIANCE] = 0;
m_HonorScoreTics[BG_TEAM_HORDE] = 0;
m_FlagState = BG_EY_FLAG_STATE_ON_BASE;
m_FlagCapturedBgObjectType = 0;
m_FlagKeeper = 0;
m_DroppedFlagGUID = 0;
m_PointAddingTimer = 0;
m_TowerCapCheckTimer = 0;
bool isBGWeekend = sBattlegroundMgr->IsBGWeekend(GetTypeID());
m_HonorTics = (isBGWeekend) ? BG_EY_EYWeekendHonorTicks : BG_EY_NotEYWeekendHonorTicks;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
m_PointOwnedByTeam[i] = EY_POINT_NO_OWNER;
m_PointState[i] = EY_POINT_STATE_UNCONTROLLED;
m_PointBarStatus[i] = BG_EY_PROGRESS_BAR_STATE_MIDDLE;
m_PlayersNearPoint[i].clear();
m_PlayersNearPoint[i].reserve(15); //tip size
}
m_PlayersNearPoint[EY_PLAYERS_OUT_OF_POINTS].clear();
m_PlayersNearPoint[EY_PLAYERS_OUT_OF_POINTS].reserve(30);
}
void BattlegroundEY::RespawnFlag(bool send_message)
{
if (m_FlagCapturedBgObjectType > 0)
SpawnBGObject(m_FlagCapturedBgObjectType, RESPAWN_ONE_DAY);
m_FlagCapturedBgObjectType = 0;
m_FlagState = BG_EY_FLAG_STATE_ON_BASE;
SpawnBGObject(BG_EY_OBJECT_FLAG_NETHERSTORM, RESPAWN_IMMEDIATELY);
if (send_message)
{
SendMessageToAll(LANG_BG_EY_RESETED_FLAG, CHAT_MSG_BG_SYSTEM_NEUTRAL);
PlaySoundToAll(BG_EY_SOUND_FLAG_RESET); // flags respawned sound...
}
UpdateWorldState(NETHERSTORM_FLAG, 1);
}
void BattlegroundEY::RespawnFlagAfterDrop()
{
RespawnFlag(true);
GameObject *obj = HashMapHolder<GameObject>::Find(GetDroppedFlagGUID());
if (obj)
obj->Delete();
else
sLog->outError("BattlegroundEY: Unknown dropped flag guid: %u", GUID_LOPART(GetDroppedFlagGUID()));
SetDroppedFlagGUID(0);
}
void BattlegroundEY::HandleKillPlayer(Player *player, Player *killer)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
Battleground::HandleKillPlayer(player, killer);
EventPlayerDroppedFlag(player);
}
void BattlegroundEY::EventPlayerDroppedFlag(Player *Source)
{
if (GetStatus() != STATUS_IN_PROGRESS)
{
// if not running, do not cast things at the dropper player, neither send unnecessary messages
// just take off the aura
if (IsFlagPickedup() && GetFlagPickerGUID() == Source->GetGUID())
{
SetFlagPicker(0);
Source->RemoveAurasDueToSpell(BG_EY_NETHERSTORM_FLAG_SPELL);
}
return;
}
if (!IsFlagPickedup())
return;
if (GetFlagPickerGUID() != Source->GetGUID())
return;
SetFlagPicker(0);
Source->RemoveAurasDueToSpell(BG_EY_NETHERSTORM_FLAG_SPELL);
m_FlagState = BG_EY_FLAG_STATE_ON_GROUND;
m_FlagsTimer = BG_EY_FLAG_RESPAWN_TIME;
Source->CastSpell(Source, SPELL_RECENTLY_DROPPED_FLAG, true);
Source->CastSpell(Source, BG_EY_PLAYER_DROPPED_FLAG_SPELL, true);
//this does not work correctly :((it should remove flag carrier name)
UpdateWorldState(NETHERSTORM_FLAG_STATE_HORDE, BG_EY_FLAG_STATE_WAIT_RESPAWN);
UpdateWorldState(NETHERSTORM_FLAG_STATE_ALLIANCE, BG_EY_FLAG_STATE_WAIT_RESPAWN);
if (Source->GetTeam() == ALLIANCE)
SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL);
else
SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL);
}
void BattlegroundEY::EventPlayerClickedOnFlag(Player *Source, GameObject* target_obj)
{
if (GetStatus() != STATUS_IN_PROGRESS || IsFlagPickedup() || !Source->IsWithinDistInMap(target_obj, 10))
return;
if (Source->GetTeam() == ALLIANCE)
{
UpdateWorldState(NETHERSTORM_FLAG_STATE_ALLIANCE, BG_EY_FLAG_STATE_ON_PLAYER);
PlaySoundToAll(BG_EY_SOUND_FLAG_PICKED_UP_ALLIANCE);
}
else
{
UpdateWorldState(NETHERSTORM_FLAG_STATE_HORDE, BG_EY_FLAG_STATE_ON_PLAYER);
PlaySoundToAll(BG_EY_SOUND_FLAG_PICKED_UP_HORDE);
}
if (m_FlagState == BG_EY_FLAG_STATE_ON_BASE)
UpdateWorldState(NETHERSTORM_FLAG, 0);
m_FlagState = BG_EY_FLAG_STATE_ON_PLAYER;
SpawnBGObject(BG_EY_OBJECT_FLAG_NETHERSTORM, RESPAWN_ONE_DAY);
SetFlagPicker(Source->GetGUID());
//get flag aura on player
Source->CastSpell(Source, BG_EY_NETHERSTORM_FLAG_SPELL, true);
Source->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
if (Source->GetTeam() == ALLIANCE)
PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, Source->GetName());
else
PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL, Source->GetName());
}
void BattlegroundEY::EventTeamLostPoint(Player *Source, uint32 Point)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
//Natural point
uint32 Team = m_PointOwnedByTeam[Point];
if (!Team)
return;
if (Team == ALLIANCE)
{
m_TeamPointsCount[BG_TEAM_ALLIANCE]--;
SpawnBGObject(m_LoosingPointTypes[Point].DespawnObjectTypeAlliance, RESPAWN_ONE_DAY);
SpawnBGObject(m_LoosingPointTypes[Point].DespawnObjectTypeAlliance + 1, RESPAWN_ONE_DAY);
SpawnBGObject(m_LoosingPointTypes[Point].DespawnObjectTypeAlliance + 2, RESPAWN_ONE_DAY);
}
else
{
m_TeamPointsCount[BG_TEAM_HORDE]--;
SpawnBGObject(m_LoosingPointTypes[Point].DespawnObjectTypeHorde, RESPAWN_ONE_DAY);
SpawnBGObject(m_LoosingPointTypes[Point].DespawnObjectTypeHorde + 1, RESPAWN_ONE_DAY);
SpawnBGObject(m_LoosingPointTypes[Point].DespawnObjectTypeHorde + 2, RESPAWN_ONE_DAY);
}
SpawnBGObject(m_LoosingPointTypes[Point].SpawnNeutralObjectType, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_LoosingPointTypes[Point].SpawnNeutralObjectType + 1, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_LoosingPointTypes[Point].SpawnNeutralObjectType + 2, RESPAWN_IMMEDIATELY);
//buff isn't despawned
m_PointOwnedByTeam[Point] = EY_POINT_NO_OWNER;
m_PointState[Point] = EY_POINT_NO_OWNER;
if (Team == ALLIANCE)
SendMessageToAll(m_LoosingPointTypes[Point].MessageIdAlliance, CHAT_MSG_BG_SYSTEM_ALLIANCE, Source);
else
SendMessageToAll(m_LoosingPointTypes[Point].MessageIdHorde, CHAT_MSG_BG_SYSTEM_HORDE, Source);
UpdatePointsIcons(Team, Point);
UpdatePointsCount(Team);
//remove bonus honor aura trigger creature when node is lost
if (Point < EY_POINTS_MAX)
DelCreature(Point + 6);//NULL checks are in DelCreature! 0-5 spirit guides
}
void BattlegroundEY::EventTeamCapturedPoint(Player *Source, uint32 Point)
{
if (GetStatus() != STATUS_IN_PROGRESS)
return;
uint32 Team = Source->GetTeam();
SpawnBGObject(m_CapturingPointTypes[Point].DespawnNeutralObjectType, RESPAWN_ONE_DAY);
SpawnBGObject(m_CapturingPointTypes[Point].DespawnNeutralObjectType + 1, RESPAWN_ONE_DAY);
SpawnBGObject(m_CapturingPointTypes[Point].DespawnNeutralObjectType + 2, RESPAWN_ONE_DAY);
if (Team == ALLIANCE)
{
m_TeamPointsCount[BG_TEAM_ALLIANCE]++;
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeAlliance, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeAlliance + 1, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeAlliance + 2, RESPAWN_IMMEDIATELY);
}
else
{
m_TeamPointsCount[BG_TEAM_HORDE]++;
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeHorde, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeHorde + 1, RESPAWN_IMMEDIATELY);
SpawnBGObject(m_CapturingPointTypes[Point].SpawnObjectTypeHorde + 2, RESPAWN_IMMEDIATELY);
}
//buff isn't respawned
m_PointOwnedByTeam[Point] = Team;
m_PointState[Point] = EY_POINT_UNDER_CONTROL;
if (Team == ALLIANCE)
SendMessageToAll(m_CapturingPointTypes[Point].MessageIdAlliance, CHAT_MSG_BG_SYSTEM_ALLIANCE, Source);
else
SendMessageToAll(m_CapturingPointTypes[Point].MessageIdHorde, CHAT_MSG_BG_SYSTEM_HORDE, Source);
if (m_BgCreatures[Point])
DelCreature(Point);
WorldSafeLocsEntry const *sg = NULL;
sg = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[Point].GraveYardId);
if (!sg || !AddSpiritGuide(Point, sg->x, sg->y, sg->z, 3.124139f, Team))
sLog->outError("BatteGroundEY: Failed to spawn spirit guide! point: %u, team: %u, graveyard_id: %u",
Point, Team, m_CapturingPointTypes[Point].GraveYardId);
// SpawnBGCreature(Point, RESPAWN_IMMEDIATELY);
UpdatePointsIcons(Team, Point);
UpdatePointsCount(Team);
if (Point >= EY_POINTS_MAX)
return;
Creature* trigger = GetBGCreature(Point + 6);//0-5 spirit guides
if (!trigger)
trigger = AddCreature(WORLD_TRIGGER, Point+6, Team, BG_EY_TriggerPositions[Point][0], BG_EY_TriggerPositions[Point][1], BG_EY_TriggerPositions[Point][2], BG_EY_TriggerPositions[Point][3]);
//add bonus honor aura trigger creature when node is accupied
//cast bonus aura (+50% honor in 25yards)
//aura should only apply to players who have accupied the node, set correct faction for trigger
if (trigger)
{
trigger->setFaction(Team == ALLIANCE ? 84 : 83);
trigger->CastSpell(trigger, SPELL_HONORABLE_DEFENDER_25Y, false);
}
}
void BattlegroundEY::EventPlayerCapturedFlag(Player *Source, uint32 BgObjectType)
{
if (GetStatus() != STATUS_IN_PROGRESS || GetFlagPickerGUID() != Source->GetGUID())
return;
SetFlagPicker(0);
m_FlagState = BG_EY_FLAG_STATE_WAIT_RESPAWN;
Source->RemoveAurasDueToSpell(BG_EY_NETHERSTORM_FLAG_SPELL);
Source->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
if (Source->GetTeam() == ALLIANCE)
PlaySoundToAll(BG_EY_SOUND_FLAG_CAPTURED_ALLIANCE);
else
PlaySoundToAll(BG_EY_SOUND_FLAG_CAPTURED_HORDE);
SpawnBGObject(BgObjectType, RESPAWN_IMMEDIATELY);
m_FlagsTimer = BG_EY_FLAG_RESPAWN_TIME;
m_FlagCapturedBgObjectType = BgObjectType;
uint8 team_id = 0;
if (Source->GetTeam() == ALLIANCE)
{
team_id = BG_TEAM_ALLIANCE;
SendMessageToAll(LANG_BG_EY_CAPTURED_FLAG_A, CHAT_MSG_BG_SYSTEM_ALLIANCE, Source);
}
else
{
team_id = BG_TEAM_HORDE;
SendMessageToAll(LANG_BG_EY_CAPTURED_FLAG_H, CHAT_MSG_BG_SYSTEM_HORDE, Source);
}
if (m_TeamPointsCount[team_id] > 0)
AddPoints(Source->GetTeam(), BG_EY_FlagPoints[m_TeamPointsCount[team_id] - 1]);
UpdatePlayerScore(Source, SCORE_FLAG_CAPTURES, 1);
}
void BattlegroundEY::UpdatePlayerScore(Player *Source, uint32 type, uint32 value, bool doAddHonor)
{
BattlegroundScoreMap::iterator itr = m_PlayerScores.find(Source->GetGUID());
if (itr == m_PlayerScores.end()) // player not found
return;
switch(type)
{
case SCORE_FLAG_CAPTURES: // flags captured
((BattlegroundEYScore*)itr->second)->FlagCaptures += value;
Source->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, EY_OBJECTIVE_CAPTURE_FLAG);
break;
default:
Battleground::UpdatePlayerScore(Source, type, value, doAddHonor);
break;
}
}
void BattlegroundEY::FillInitialWorldStates(WorldPacket& data)
{
data << uint32(EY_HORDE_BASE) << uint32(m_TeamPointsCount[BG_TEAM_HORDE]);
data << uint32(EY_ALLIANCE_BASE) << uint32(m_TeamPointsCount[BG_TEAM_ALLIANCE]);
data << uint32(0xab6) << uint32(0x0);
data << uint32(0xab5) << uint32(0x0);
data << uint32(0xab4) << uint32(0x0);
data << uint32(0xab3) << uint32(0x0);
data << uint32(0xab2) << uint32(0x0);
data << uint32(0xab1) << uint32(0x0);
data << uint32(0xab0) << uint32(0x0);
data << uint32(0xaaf) << uint32(0x0);
data << uint32(DRAENEI_RUINS_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[DRAENEI_RUINS] == HORDE && m_PointState[DRAENEI_RUINS] == EY_POINT_UNDER_CONTROL);
data << uint32(DRAENEI_RUINS_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[DRAENEI_RUINS] == ALLIANCE && m_PointState[DRAENEI_RUINS] == EY_POINT_UNDER_CONTROL);
data << uint32(DRAENEI_RUINS_UNCONTROL) << uint32(m_PointState[DRAENEI_RUINS] != EY_POINT_UNDER_CONTROL);
data << uint32(MAGE_TOWER_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[MAGE_TOWER] == ALLIANCE && m_PointState[MAGE_TOWER] == EY_POINT_UNDER_CONTROL);
data << uint32(MAGE_TOWER_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[MAGE_TOWER] == HORDE && m_PointState[MAGE_TOWER] == EY_POINT_UNDER_CONTROL);
data << uint32(MAGE_TOWER_UNCONTROL) << uint32(m_PointState[MAGE_TOWER] != EY_POINT_UNDER_CONTROL);
data << uint32(FEL_REAVER_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[FEL_REAVER] == HORDE && m_PointState[FEL_REAVER] == EY_POINT_UNDER_CONTROL);
data << uint32(FEL_REAVER_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[FEL_REAVER] == ALLIANCE && m_PointState[FEL_REAVER] == EY_POINT_UNDER_CONTROL);
data << uint32(FEL_REAVER_UNCONTROL) << uint32(m_PointState[FEL_REAVER] != EY_POINT_UNDER_CONTROL);
data << uint32(BLOOD_ELF_HORDE_CONTROL) << uint32(m_PointOwnedByTeam[BLOOD_ELF] == HORDE && m_PointState[BLOOD_ELF] == EY_POINT_UNDER_CONTROL);
data << uint32(BLOOD_ELF_ALLIANCE_CONTROL) << uint32(m_PointOwnedByTeam[BLOOD_ELF] == ALLIANCE && m_PointState[BLOOD_ELF] == EY_POINT_UNDER_CONTROL);
data << uint32(BLOOD_ELF_UNCONTROL) << uint32(m_PointState[BLOOD_ELF] != EY_POINT_UNDER_CONTROL);
data << uint32(NETHERSTORM_FLAG) << uint32(m_FlagState == BG_EY_FLAG_STATE_ON_BASE);
data << uint32(0xad2) << uint32(0x1);
data << uint32(0xad1) << uint32(0x1);
data << uint32(0xabe) << uint32(GetTeamScore(HORDE));
data << uint32(0xabd) << uint32(GetTeamScore(ALLIANCE));
data << uint32(0xa05) << uint32(0x8e);
data << uint32(0xaa0) << uint32(0x0);
data << uint32(0xa9f) << uint32(0x0);
data << uint32(0xa9e) << uint32(0x0);
data << uint32(0xc0d) << uint32(0x17b);
}
WorldSafeLocsEntry const *BattlegroundEY::GetClosestGraveYard(Player* player)
{
uint32 g_id = 0;
switch(player->GetTeam())
{
case ALLIANCE: g_id = EY_GRAVEYARD_MAIN_ALLIANCE; break;
case HORDE: g_id = EY_GRAVEYARD_MAIN_HORDE; break;
default: return NULL;
}
float distance, nearestDistance;
WorldSafeLocsEntry const* entry = NULL;
WorldSafeLocsEntry const* nearestEntry = NULL;
entry = sWorldSafeLocsStore.LookupEntry(g_id);
nearestEntry = entry;
if (!entry)
{
sLog->outError("BattlegroundEY: Not found the main team graveyard. Graveyard system isn't working!");
return NULL;
}
float plr_x = player->GetPositionX();
float plr_y = player->GetPositionY();
float plr_z = player->GetPositionZ();
distance = (entry->x - plr_x)*(entry->x - plr_x) + (entry->y - plr_y)*(entry->y - plr_y) + (entry->z - plr_z)*(entry->z - plr_z);
nearestDistance = distance;
for (uint8 i = 0; i < EY_POINTS_MAX; ++i)
{
if (m_PointOwnedByTeam[i] == player->GetTeam() && m_PointState[i] == EY_POINT_UNDER_CONTROL)
{
entry = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[i].GraveYardId);
if (!entry)
sLog->outError("BattlegroundEY: Not found graveyard: %u", m_CapturingPointTypes[i].GraveYardId);
else
{
distance = (entry->x - plr_x)*(entry->x - plr_x) + (entry->y - plr_y)*(entry->y - plr_y) + (entry->z - plr_z)*(entry->z - plr_z);
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestEntry = entry;
}
}
}
}
return nearestEntry;
}
bool BattlegroundEY::IsAllNodesConrolledByTeam(uint32 team) const
{
uint32 count = 0;
for (int i = 0; i < EY_POINTS_MAX; ++i)
if (m_PointOwnedByTeam[i] == team && m_PointState[i] == EY_POINT_UNDER_CONTROL)
++count;
return count == EY_POINTS_MAX;
} | 45.414815 | 271 | 0.684903 | [
"object"
] |
f5568fb0dd851f58ead661e5bc320aee0e482148 | 5,192 | cpp | C++ | TelemetrySourcererDriver/TelemetrySourcererDriver.cpp | fengjixuchui/TelemetrySourcerer | 908c96b3ce08c4f806545ab611977d355cae0b44 | [
"Apache-2.0"
] | 1 | 2021-06-15T16:51:21.000Z | 2021-06-15T16:51:21.000Z | TelemetrySourcererDriver/TelemetrySourcererDriver.cpp | L1ves/TelemetrySourcerer | 72fd542305ee9fdfe75cdeca3f75b37787514c87 | [
"Apache-2.0"
] | null | null | null | TelemetrySourcererDriver/TelemetrySourcererDriver.cpp | L1ves/TelemetrySourcerer | 72fd542305ee9fdfe75cdeca3f75b37787514c87 | [
"Apache-2.0"
] | 1 | 2020-10-23T04:04:16.000Z | 2020-10-23T04:04:16.000Z | #include <ntddk.h>
#include "TelemetrySourcererDriver.h"
#include "Common.h"
#include "Memory.h"
#include "Modules.h"
#include "Callbacks.h"
extern "C" NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
NTSTATUS Status = STATUS_SUCCESS;
UNREFERENCED_PARAMETER(RegistryPath);
DriverObject->DriverUnload = UnloadDriver;
DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreateClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchCreateClose;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchDeviceControl;
// Create device.
PDEVICE_OBJECT DeviceObject;
UNICODE_STRING DeviceName = RTL_CONSTANT_STRING(LR"(\Device\TelemetrySourcererDriver)");
Status = IoCreateDevice(DriverObject, 0, &DeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &DeviceObject);
if (NT_SUCCESS(Status))
{
DeviceObject->Flags |= DO_BUFFERED_IO;
}
else
{
DbgPrint("> TelemetrySourcererDriver: Failed to create device (0x%08X).\n", Status);
return Status;
}
// Create symbolic link for device.
UNICODE_STRING SymbolicLink = RTL_CONSTANT_STRING(LR"(\??\TelemetrySourcererDriver)");
Status = IoCreateSymbolicLink(&SymbolicLink, &DeviceName);
if (!NT_SUCCESS(Status))
{
DbgPrint("> TelemetrySourcererDriver: Failed to create symbolic link (0x%08X).\n", Status);
IoDeleteDevice(DeviceObject);
return Status;
}
DbgPrint("> TelemetrySourcererDriver: Compiled on %s %s.\n", __DATE__, __TIME__);
DbgPrint("> TelemetrySourcererDriver: Initialized successfully.\n");
return Status;
}
void UnloadDriver(_In_ PDRIVER_OBJECT DriverObject)
{
// Delete symbolic link and device.
UNICODE_STRING SymbolicLink = RTL_CONSTANT_STRING(LR"(\??\TelemetrySourcererDriver)");
IoDeleteSymbolicLink(&SymbolicLink);
IoDeleteDevice(DriverObject->DeviceObject);
DbgPrint("> TelemetrySourcererDriver: Unloaded successfully.\n");
}
_Use_decl_annotations_
NTSTATUS DispatchCreateClose(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
UNREFERENCED_PARAMETER(DeviceObject);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
_Use_decl_annotations_
NTSTATUS DispatchDeviceControl(PDEVICE_OBJECT, PIRP Irp)
{
NTSTATUS Status = STATUS_SUCCESS;
ULONG OutBufferSize = 0;
PIO_STACK_LOCATION Stack = IoGetCurrentIrpStackLocation(Irp);
switch (Stack->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_SANDBOX:
{
DbgPrint("> TelemetrySourcererDriver: Hello, world!\n");
break;
}
case IOCTL_GET_MODULES:
{
DbgPrint("> TelemetrySourcererDriver: Getting modules...\n");
OutBufferSize = Stack->Parameters.DeviceIoControl.InputBufferLength;
MODULE_INFO* Modules = (MODULE_INFO*)Irp->AssociatedIrp.SystemBuffer;
Status = GetModules(Modules);
break;
}
case IOCTL_GET_CALLBACKS:
{
ULONG i = 0;
ULONG n = 0;
CALLBACK_INFO* Callbacks = (CALLBACK_INFO*)Irp->AssociatedIrp.SystemBuffer;
OutBufferSize = Stack->Parameters.DeviceIoControl.InputBufferLength;
// Get load image notification callbacks and update the output index.
DbgPrint("> TelemetrySourcererDriver: Getting load image notification callbacks...\n");
if (NT_SUCCESS(GetLoadImageNotifyCallbacks(&Callbacks[i], &n)))
i += n;
// Get create process notification callbacks and update the output index.
DbgPrint("> TelemetrySourcererDriver: Getting create process notification callbacks...\n");
if (NT_SUCCESS(GetCreateProcessNotifyCallbacks(&Callbacks[i], &n)))
i += n;
// Get create thread notification callbacks and update the output index.
DbgPrint("> TelemetrySourcererDriver: Getting create thread notification callbacks...\n");
if (NT_SUCCESS(GetCreateThreadNotifyCallbacks(&Callbacks[i], &n)))
i += n;
// Get registry callbacks and and update the output index.
DbgPrint("> TelemetrySourcererDriver: Getting registry notification callbacks...\n");
if (NT_SUCCESS(GetRegistryCallbacks(&Callbacks[i], &n)))
i += n;
// Get object callbacks and and update the output index.
DbgPrint("> TelemetrySourcererDriver: Getting object notification callbacks...\n");
if (NT_SUCCESS(GetObjectCallbacks(&Callbacks[i], &n)))
i += n;
// Get minifilter callbacks and and update the output index.
DbgPrint("> TelemetrySourcererDriver: Getting minifilter notification callbacks...\n");
if (NT_SUCCESS(GetMinifilterCallbacks(&Callbacks[i], &n)))
i += n;
break;
}
case IOCTL_GET_QWORD:
{
OutBufferSize = Stack->Parameters.DeviceIoControl.InputBufferLength;
QWORD_INFO* Buffer = (QWORD_INFO*)Irp->AssociatedIrp.SystemBuffer;
KdPrint(("> TelemetrySourcererDriver: Getting QWORD at 0x%p...\n", Buffer->Address));
Buffer->Value = *Buffer->Address;
break;
}
case IOCTL_SET_QWORD:
{
QWORD_INFO* Buffer = (QWORD_INFO*)Irp->AssociatedIrp.SystemBuffer;
KdPrint(("> TelemetrySourcererDriver: Setting QWORD at 0x%p...\n", Buffer->Address));
WriteVirtualMemory(Buffer->Address, &Buffer->Value, sizeof(ULONG64));
break;
}
default:
{
Status = STATUS_INVALID_DEVICE_REQUEST;
break;
}
}
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = OutBufferSize;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Status;
} | 33.070064 | 101 | 0.761941 | [
"object"
] |
f559bfa6ace57c7986b4d0d37d07e7f095a1668c | 6,937 | cpp | C++ | Systems/Physics/PhysicsEvents.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | Systems/Physics/PhysicsEvents.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | Systems/Physics/PhysicsEvents.cpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Claeys, Joshua Davis
/// Copyright 2010-2017, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
namespace Events
{
DefineEvent(RigidBodySlept);
DefineEvent(RigidBodyAwoke);
DefineEvent(CollisionStarted);
DefineEvent(CollisionPersisted);
DefineEvent(CollisionEnded);
DefineEvent(GroupCollisionStarted);
DefineEvent(GroupCollisionPersisted);
DefineEvent(GroupCollisionEnded);
DefineEvent(GroupCollisionPreSolve);
DefineEvent(PhysicsUpdateFinished);
}//namespace Events
//-------------------------------------------------------------------BaseCollisionEvent
ZilchDefineType(BaseCollisionEvent, builder, type)
{
ZeroBindDocumented();
ZilchBindGetterProperty(Object);
ZilchBindGetterProperty(OtherObject);
ZilchBindGetterProperty(ContactPointCount);
ZilchBindGetterProperty(IsGhost);
ZilchBindGetterProperty(ContactPoints);
}
BaseCollisionEvent::BaseCollisionEvent()
{
mManifold = nullptr;
mObjectIndex = 0;
}
void BaseCollisionEvent::Set(Physics::Manifold* manifold, StringParam eventType)
{
mManifold = manifold;
mEventType = eventType;
}
Cog* BaseCollisionEvent::GetObject()
{
return mManifold->Objects[mObjectIndex]->GetOwner();
}
Cog* BaseCollisionEvent::GetOtherObject()
{
return mManifold->Objects[(mObjectIndex + 1) % 2]->GetOwner();
}
bool BaseCollisionEvent::GetIsGhost()
{
bool aGhost = false;
bool bGhost = false;
aGhost = GetCollider()->NotCollideable();
bGhost = GetOtherCollider()->NotCollideable();
return aGhost || bGhost;
}
uint BaseCollisionEvent::GetContactPointCount()
{
return mManifold->ContactCount;
}
ContactPointRange BaseCollisionEvent::GetContactPoints()
{
ContactPointRange range;
range.Set(mManifold, mObjectIndex);
return range;
}
ContactPoint BaseCollisionEvent::GetFirstPoint()
{
ContactPoint point;
point.Set(mManifold, &mManifold->Contacts[0], mObjectIndex);
return point;
}
Collider* BaseCollisionEvent::GetCollider()
{
return mManifold->Objects[mObjectIndex];
}
Collider* BaseCollisionEvent::GetOtherCollider()
{
return mManifold->Objects[(mObjectIndex + 1) % 2];
}
void BaseCollisionEvent::MatchCollisionFilterOrder(CollisionFilter* filter)
{
// To help make SendToA and SendToB make more sense, flip the event's order to match the same as the filter.
// This means SendToA will send to the collider with the same collision group as the first one in the filter.
// If both collision groups are the same then no flip happens but there's no logical order then anyways.
Collider* firstCollider = GetCollider();
ResourceId firstGroupId = firstCollider->mCollisionGroupInstance->mResource->mResourceId;
if(firstGroupId != filter->first())
mObjectIndex = !mObjectIndex;
}
const Physics::ManifoldPoint& BaseCollisionEvent::GetPoint(uint index)
{
ErrorIf(index >= GetContactPointCount(), "Point index is greater than the number of contact points.");
return mManifold->Contacts[index];
}
//-------------------------------------------------------------------CollisionEvent
ZilchDefineType(CollisionEvent, builder, type)
{
ZeroBindDocumented();
ZilchBindGetterProperty(FirstPoint);
ZeroBindTag(Tags::Physics);
}
CollisionEvent::CollisionEvent()
{
mContactIndex = 0;
}
void CollisionEvent::Set(Physics::Manifold* manifold, StringParam eventType)
{
BaseCollisionEvent::Set(manifold, eventType);
mContactIndex = 0;
UpdatePoint();
}
void CollisionEvent::Set(Physics::Manifold* manifold, const Physics::ManifoldPoint& point, StringParam eventType)
{
BaseCollisionEvent::Set(manifold, eventType);
mContactPoint = point;
}
ContactPoint CollisionEvent::GetFirstPoint()
{
ContactPoint point;
point.Set(mManifold, &mContactPoint, mObjectIndex);
return point;
}
void CollisionEvent::UpdatePoint()
{
if(mCollisionType == CollisionStarted || mCollisionType == CollisionPersisted)
mContactPoint = mManifold->Contacts[mContactIndex];
}
String CollisionEvent::GetEventName(BaseCollisionEvent::CollisionType type)
{
if(type == BaseCollisionEvent::CollisionStarted)
return Events::CollisionStarted;
else if(type == BaseCollisionEvent::CollisionPersisted)
return Events::CollisionPersisted;
else
return Events::CollisionEnded;
}
//-------------------------------------------------------------------CollisionGroupEvent
ZilchDefineType(CollisionGroupEvent, builder, type)
{
ZeroBindDocumented();
ZilchBindGetterProperty(TypeAName);
ZilchBindGetterProperty(TypeBName);
ZilchBindGetterProperty(FirstPoint);
ZeroBindTag(Tags::Physics);
}
CollisionGroupEvent::CollisionGroupEvent()
{
}
void CollisionGroupEvent::Set(Physics::Manifold* manifold, const CollisionFilter& pair, CollisionFilterBlock* block, StringParam eventType)
{
BaseCollisionEvent::Set(manifold,eventType);
mBlock = block;
mTypeAName = pair.GetTypeAName();
mTypeBName = pair.GetTypeBName();
// Put the objects in the same ordering as the pair
if(manifold->Objects[0]->mCollisionGroupInstance->mResource->mResourceId != pair.TypeA)
mObjectIndex = !mObjectIndex;
}
String CollisionGroupEvent::GetTypeAName()
{
return mTypeAName;
}
String CollisionGroupEvent::GetTypeBName()
{
return mTypeBName;
}
String CollisionGroupEvent::GetEventName(BaseCollisionEvent::CollisionType type)
{
if(type == BaseCollisionEvent::CollisionStarted)
return Events::GroupCollisionStarted;
else if(type == BaseCollisionEvent::CollisionPersisted)
return Events::GroupCollisionPersisted;
else
return Events::GroupCollisionEnded;
}
//-------------------------------------------------------------------PreSolveEvent
ZilchDefineType(PreSolveEvent, builder, type)
{
ZeroBindDocumented();
ZilchBindGetterSetter(Restitution);
ZilchBindGetterSetter(Friction);
ZeroBindTag(Tags::Physics);
}
PreSolveEvent::PreSolveEvent()
{
mBlock = nullptr;
}
void PreSolveEvent::Set(Physics::Manifold* manifold, CollisionFilterBlock* preSolveBlock)
{
BaseCollisionEvent::Set(manifold, String());
mBlock = preSolveBlock;
if(!mBlock->mEventOverride.Empty())
EventId = mBlock->mEventOverride;
else
EventId = Events::GroupCollisionPreSolve;
}
real PreSolveEvent::GetRestitution()
{
return mManifold->Restitution;
}
void PreSolveEvent::SetRestitution(real restitution)
{
mManifold->Restitution = restitution;
}
real PreSolveEvent::GetFriction()
{
return mManifold->DynamicFriction;
}
void PreSolveEvent::SetFriction(real friction)
{
mManifold->DynamicFriction = friction;
}
}//namespace Zero
| 25.981273 | 140 | 0.695257 | [
"object"
] |
f55e0812bf4ad93caad90bedd0afd531156e1b38 | 26,640 | cpp | C++ | external/vulkancts/modules/vulkan/api/vktApiBufferViewAccessTests.cpp | karolherbst/VK-GL-CTS | bb088fddd8673dc4f37e5956c42890645ab31577 | [
"Apache-2.0"
] | null | null | null | external/vulkancts/modules/vulkan/api/vktApiBufferViewAccessTests.cpp | karolherbst/VK-GL-CTS | bb088fddd8673dc4f37e5956c42890645ab31577 | [
"Apache-2.0"
] | null | null | null | external/vulkancts/modules/vulkan/api/vktApiBufferViewAccessTests.cpp | karolherbst/VK-GL-CTS | bb088fddd8673dc4f37e5956c42890645ab31577 | [
"Apache-2.0"
] | null | null | null | /*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2015 The Khronos Group Inc.
* Copyright (c) 2015 Samsung Electronics 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.
*
*//*!
* \file
* \brief Vulkan Buffer View Memory Tests
*//*--------------------------------------------------------------------*/
#include "vktApiBufferViewAccessTests.hpp"
#include "vktApiBufferAndImageAllocationUtil.hpp"
#include "deStringUtil.hpp"
#include "deUniquePtr.hpp"
#include "vktTestCase.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkPrograms.hpp"
#include "vkQueryUtil.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"
#include "tcuImageCompare.hpp"
#include "tcuTexture.hpp"
#include "tcuTextureUtil.hpp"
#include "deSharedPtr.hpp"
namespace vkt
{
namespace api
{
using namespace vk;
namespace
{
enum AllocationKind
{
ALLOCATION_KIND_SUBALLOCATION = 0,
ALLOCATION_KIND_DEDICATED = 1,
ALLOCATION_KIND_LAST
};
struct BufferViewCaseParams
{
deUint32 bufferSize;
deUint32 bufferViewSize;
deUint32 elementOffset;
AllocationKind bufferAllocationKind;
AllocationKind imageAllocationKind;
};
class BufferViewTestInstance : public vkt::TestInstance
{
public:
BufferViewTestInstance (Context& context,
BufferViewCaseParams testCase);
virtual ~BufferViewTestInstance (void);
virtual tcu::TestStatus iterate (void);
private:
void createQuad (void);
tcu::TestStatus checkResult (deInt8 factor);
private:
BufferViewCaseParams m_testCase;
const tcu::IVec2 m_renderSize;
const VkFormat m_colorFormat;
const VkDeviceSize m_pixelDataSize;
Move<VkImage> m_colorImage;
de::MovePtr<Allocation> m_colorImageAlloc;
Move<VkImageView> m_colorAttachmentView;
Move<VkRenderPass> m_renderPass;
Move<VkFramebuffer> m_framebuffer;
Move<VkDescriptorSetLayout> m_descriptorSetLayout;
Move<VkDescriptorPool> m_descriptorPool;
Move<VkDescriptorSet> m_descriptorSet;
Move<VkBuffer> m_uniformBuffer;
de::MovePtr<vk::Allocation> m_uniformBufferAlloc;
Move<VkBufferView> m_uniformBufferView;
Move<VkShaderModule> m_vertexShaderModule;
Move<VkShaderModule> m_fragmentShaderModule;
Move<VkBuffer> m_vertexBuffer;
std::vector<tcu::Vec4> m_vertices;
de::MovePtr<Allocation> m_vertexBufferAlloc;
Move<VkPipelineLayout> m_pipelineLayout;
Move<VkPipeline> m_graphicsPipelines;
Move<VkCommandPool> m_cmdPool;
Move<VkCommandBuffer> m_cmdBuffer;
Move<VkBuffer> m_resultBuffer;
de::MovePtr<Allocation> m_resultBufferAlloc;
};
static void generateBuffer (std::vector<deUint32>& uniformData,
deUint32 bufferSize,
deInt8 factor)
{
for (deUint32 i = 0; i < bufferSize; ++i)
uniformData.push_back(factor * i);
}
void BufferViewTestInstance::createQuad (void)
{
tcu::Vec4 a(-1.0, -1.0, 0.0, 1.0);
tcu::Vec4 b(1.0, -1.0, 0.0, 1.0);
tcu::Vec4 c(1.0, 1.0, 0.0, 1.0);
tcu::Vec4 d(-1.0, 1.0, 0.0, 1.0);
// Triangle 1
m_vertices.push_back(a);
m_vertices.push_back(c);
m_vertices.push_back(b);
// Triangle 2
m_vertices.push_back(c);
m_vertices.push_back(a);
m_vertices.push_back(d);
}
BufferViewTestInstance::~BufferViewTestInstance (void)
{
}
BufferViewTestInstance::BufferViewTestInstance (Context& context,
BufferViewCaseParams testCase)
: vkt::TestInstance (context)
, m_testCase (testCase)
, m_renderSize (testCase.bufferViewSize, testCase.bufferViewSize)
, m_colorFormat (VK_FORMAT_R32_UINT)
, m_pixelDataSize (m_renderSize.x() * m_renderSize.y() * mapVkFormat(m_colorFormat).getPixelSize())
{
const DeviceInterface& vk = context.getDeviceInterface();
const VkDevice vkDevice = context.getDevice();
const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex();
SimpleAllocator memAlloc (vk, vkDevice, getPhysicalDeviceMemoryProperties(context.getInstanceInterface(), context.getPhysicalDevice()));
const VkComponentMapping channelMappingRGBA = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A };
// Create color image
if (m_testCase.imageAllocationKind == ALLOCATION_KIND_DEDICATED)
{
ImageDedicatedAllocation().createTestImage(m_renderSize, m_colorFormat, context, memAlloc, m_colorImage, MemoryRequirement::Any, m_colorImageAlloc);
}
else
{
ImageSuballocation().createTestImage(m_renderSize, m_colorFormat, context, memAlloc, m_colorImage, MemoryRequirement::Any, m_colorImageAlloc);
}
// Create destination buffer
if (m_testCase.bufferAllocationKind == ALLOCATION_KIND_DEDICATED)
{
BufferDedicatedAllocation().createTestBuffer(m_pixelDataSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT, m_context, memAlloc, m_resultBuffer, MemoryRequirement::HostVisible, m_resultBufferAlloc);
}
else
{
BufferSuballocation().createTestBuffer(m_pixelDataSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT, m_context, memAlloc, m_resultBuffer, MemoryRequirement::HostVisible, m_resultBufferAlloc);
}
// Create color attachment view
{
const VkImageViewCreateInfo colorAttachmentViewParams =
{
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkImageViewCreateFlags flags;
*m_colorImage, // VkImage image;
VK_IMAGE_VIEW_TYPE_2D, // VkImageViewType viewType;
m_colorFormat, // VkFormat format;
channelMappingRGBA, // VkChannelMapping channels;
{ VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u }, // VkImageSubresourceRange subresourceRange;
};
m_colorAttachmentView = createImageView(vk, vkDevice, &colorAttachmentViewParams);
}
// Create render pass
m_renderPass = makeRenderPass(vk, vkDevice, m_colorFormat);
// Create framebuffer
{
const VkImageView attachmentBindInfos[1] =
{
*m_colorAttachmentView,
};
const VkFramebufferCreateInfo framebufferParams =
{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkFramebufferCreateFlags)0,
*m_renderPass, // VkRenderPass renderPass;
1u, // deUint32 attachmentCount;
attachmentBindInfos, // const VkImageView* pAttachments;
(deUint32)m_renderSize.x(), // deUint32 width;
(deUint32)m_renderSize.y(), // deUint32 height;
1u // deUint32 layers;
};
m_framebuffer = createFramebuffer(vk, vkDevice, &framebufferParams);
}
// Create descriptors
{
const VkDescriptorSetLayoutBinding
layoutBindings[1] =
{
{
0u, // deUint32 binding;
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, // VkDescriptorType descriptorType;
1u, // deUint32 arraySize;
VK_SHADER_STAGE_ALL, // VkShaderStageFlags stageFlags;
DE_NULL // const VkSampler* pImmutableSamplers;
},
};
const VkDescriptorSetLayoutCreateInfo
descriptorLayoutParams =
{
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, // VkStructureType sType;
DE_NULL, // cost void* pNexŧ;
(VkDescriptorSetLayoutCreateFlags)0,
DE_LENGTH_OF_ARRAY(layoutBindings), // deUint32 count;
layoutBindings // const VkDescriptorSetLayoutBinding pBinding;
};
m_descriptorSetLayout = createDescriptorSetLayout(vk, vkDevice, &descriptorLayoutParams);
// Generate buffer
std::vector<deUint32> uniformData;
generateBuffer(uniformData, testCase.bufferSize, 1);
const VkDeviceSize uniformSize = testCase.bufferSize * sizeof(deUint32);
BufferSuballocation().createTestBuffer(uniformSize, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, m_context, memAlloc, m_uniformBuffer, MemoryRequirement::HostVisible, m_uniformBufferAlloc);
deMemcpy(m_uniformBufferAlloc->getHostPtr(), uniformData.data(), (size_t)uniformSize);
flushMappedMemoryRange(vk, vkDevice, m_uniformBufferAlloc->getMemory(), m_uniformBufferAlloc->getOffset(), uniformSize);
const VkBufferViewCreateInfo viewInfo =
{
VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO, // VkStructureType sType;
DE_NULL, // void* pNext;
(VkBufferViewCreateFlags)0,
*m_uniformBuffer, // VkBuffer buffer;
m_colorFormat, // VkFormat format;
m_testCase.elementOffset * sizeof(deUint32), // VkDeviceSize offset;
m_testCase.bufferViewSize * sizeof(deUint32) // VkDeviceSize range;
};
m_uniformBufferView = createBufferView(vk, vkDevice, &viewInfo);
const VkDescriptorPoolSize descriptorTypes[1] =
{
{
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, // VkDescriptorType type;
1 // deUint32 count;
}
};
const VkDescriptorPoolCreateInfo
descriptorPoolParams =
{
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, // VkStructureType sType;
DE_NULL, // void* pNext;
VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, // VkDescriptorPoolCreateFlags flags;
1u, // uint32_t maxSets;
DE_LENGTH_OF_ARRAY(descriptorTypes), // deUint32 count;
descriptorTypes // const VkDescriptorTypeCount* pTypeCount
};
m_descriptorPool = createDescriptorPool(vk, vkDevice, &descriptorPoolParams);
const VkDescriptorSetAllocateInfo
descriptorSetParams =
{
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
DE_NULL,
*m_descriptorPool,
1u,
&m_descriptorSetLayout.get(),
};
m_descriptorSet = allocateDescriptorSet(vk, vkDevice, &descriptorSetParams);
const VkWriteDescriptorSet writeDescritporSets[] =
{
{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // VkStructureType sType;
DE_NULL, // const void* pNext;
*m_descriptorSet, // VkDescriptorSet destSet;
0, // deUint32 destBinding;
0, // deUint32 destArrayElement;
1u, // deUint32 count;
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, // VkDescriptorType descriptorType;
(const VkDescriptorImageInfo*)DE_NULL,
(const VkDescriptorBufferInfo*)DE_NULL,
&m_uniformBufferView.get(),
}
};
vk.updateDescriptorSets(vkDevice, DE_LENGTH_OF_ARRAY(writeDescritporSets), writeDescritporSets, 0u, DE_NULL);
}
// Create pipeline layout
{
const VkPipelineLayoutCreateInfo
pipelineLayoutParams =
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineLayoutCreateFlags)0,
1u, // deUint32 descriptorSetCount;
&*m_descriptorSetLayout, // const VkDescriptorSetLayout* pSetLayouts;
0u, // deUint32 pushConstantRangeCount;
DE_NULL // const VkPushConstantRange* pPushConstantRanges;
};
m_pipelineLayout = createPipelineLayout(vk, vkDevice, &pipelineLayoutParams);
}
// Create shaders
{
m_vertexShaderModule = createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("vert"), 0);
m_fragmentShaderModule = createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("frag"), 0);
}
// Create pipeline
{
const std::vector<VkViewport> viewports (1, makeViewport(m_renderSize));
const std::vector<VkRect2D> scissors (1, makeRect2D(m_renderSize));
m_graphicsPipelines = makeGraphicsPipeline(vk, // const DeviceInterface& vk
vkDevice, // const VkDevice device
*m_pipelineLayout, // const VkPipelineLayout pipelineLayout
*m_vertexShaderModule, // const VkShaderModule vertexShaderModule
DE_NULL, // const VkShaderModule tessellationControlModule
DE_NULL, // const VkShaderModule tessellationEvalModule
DE_NULL, // const VkShaderModule geometryShaderModule
*m_fragmentShaderModule, // const VkShaderModule fragmentShaderModule
*m_renderPass, // const VkRenderPass renderPass
viewports, // const std::vector<VkViewport>& viewports
scissors); // const std::vector<VkRect2D>& scissors
}
// Create vertex buffer
{
createQuad();
const VkDeviceSize vertexDataSize = m_vertices.size() * sizeof(tcu::Vec4);
BufferSuballocation().createTestBuffer(vertexDataSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, m_context, memAlloc, m_vertexBuffer, MemoryRequirement::HostVisible, m_vertexBufferAlloc);
// Load vertices into vertex buffer
deMemcpy(m_vertexBufferAlloc->getHostPtr(), m_vertices.data(), (size_t)vertexDataSize);
flushMappedMemoryRange(vk, vkDevice, m_vertexBufferAlloc->getMemory(), m_vertexBufferAlloc->getOffset(), vertexDataSize);
}
// Create command pool
m_cmdPool = createCommandPool(vk, vkDevice, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex);
// Create command buffer
{
m_cmdBuffer = allocateCommandBuffer(vk, vkDevice, *m_cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
beginCommandBuffer(vk, *m_cmdBuffer, 0u);
const VkImageMemoryBarrier initialImageBarrier =
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType;
DE_NULL, // const void* pNext;
0, // VkAccessFlags srcAccessMask;
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags dstAccessMask;
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout oldLayout;
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, // deUint32 destQueueFamilyIndex;
*m_colorImage, // VkImage image;
{ // VkImageSubresourceRange subresourceRange;
VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask;
0u, // deUint32 baseMipLevel;
1u, // deUint32 mipLevels;
0u, // deUint32 baseArraySlice;
1u // deUint32 arraySize;
}
};
vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &initialImageBarrier);
beginRenderPass(vk, *m_cmdBuffer, *m_renderPass, *m_framebuffer, makeRect2D(0, 0, m_renderSize.x(), m_renderSize.y()), tcu::Vec4(0.0f));
const VkDeviceSize vertexBufferOffset[1] = { 0 };
vk.cmdBindPipeline(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_graphicsPipelines);
vk.cmdBindDescriptorSets(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_pipelineLayout, 0u, 1, &*m_descriptorSet, 0u, DE_NULL);
vk.cmdBindVertexBuffers(*m_cmdBuffer, 0, 1, &m_vertexBuffer.get(), vertexBufferOffset);
vk.cmdDraw(*m_cmdBuffer, (deUint32)m_vertices.size(), 1, 0, 0);
endRenderPass(vk, *m_cmdBuffer);
const VkImageMemoryBarrier imageBarrier =
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType;
DE_NULL, // const void* pNext;
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask;
VK_ACCESS_TRANSFER_READ_BIT, // VkAccessFlags dstAccessMask;
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout oldLayout;
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, // VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, // deUint32 destQueueFamilyIndex;
*m_colorImage, // VkImage image;
{ // VkImageSubresourceRange subresourceRange;
VK_IMAGE_ASPECT_COLOR_BIT, // VkImageAspectFlags aspectMask;
0u, // deUint32 baseMipLevel;
1u, // deUint32 mipLevels;
0u, // deUint32 baseArraySlice;
1u // deUint32 arraySize;
}
};
const VkBufferMemoryBarrier bufferBarrier =
{
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // VkStructureType sType;
DE_NULL, // const void* pNext;
VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags srcAccessMask;
VK_ACCESS_HOST_READ_BIT, // VkAccessFlags dstAccessMask;
VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, // deUint32 destQueueFamilyIndex;
*m_resultBuffer, // VkBuffer buffer;
0u, // VkDeviceSize offset;
m_pixelDataSize // VkDeviceSize size;
};
const VkBufferImageCopy copyRegion =
{
0u, // VkDeviceSize bufferOffset;
(deUint32)m_renderSize.x(), // deUint32 bufferRowLength;
(deUint32)m_renderSize.y(), // deUint32 bufferImageHeight;
{ VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, 1u }, // VkImageSubresourceCopy imageSubresource;
{ 0, 0, 0 }, // VkOffset3D imageOffset;
{
(deUint32)m_renderSize.x(),
(deUint32)m_renderSize.y(),
1u
} // VkExtent3D imageExtent;
};
vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &imageBarrier);
vk.cmdCopyImageToBuffer(*m_cmdBuffer, *m_colorImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *m_resultBuffer, 1, ©Region);
vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &bufferBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
endCommandBuffer(vk, *m_cmdBuffer);
}
}
tcu::TestStatus BufferViewTestInstance::checkResult (deInt8 factor)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const tcu::TextureFormat tcuFormat = mapVkFormat(m_colorFormat);
de::MovePtr<tcu::TextureLevel> resultLevel (new tcu::TextureLevel(tcuFormat, m_renderSize.x(), m_renderSize.y()));
invalidateMappedMemoryRange(vk, vkDevice, m_resultBufferAlloc->getMemory(), m_resultBufferAlloc->getOffset(), m_pixelDataSize);
tcu::copy(*resultLevel, tcu::ConstPixelBufferAccess(resultLevel->getFormat(), resultLevel->getSize(), m_resultBufferAlloc->getHostPtr()));
tcu::ConstPixelBufferAccess pixelBuffer = resultLevel->getAccess();
for (deInt32 i = 0; i < (deInt32) m_renderSize.x(); ++i)
{
tcu::IVec4 pixel = pixelBuffer.getPixelInt(i, i);
deInt32 expected = factor * (m_testCase.elementOffset + i);
deInt32 actual = pixel[0];
if (expected != actual)
{
std::ostringstream errorMessage;
errorMessage << "BufferView test failed. expected: " << expected << " actual: " << actual;
return tcu::TestStatus::fail(errorMessage.str());
}
}
return tcu::TestStatus::pass("BufferView test");
}
tcu::TestStatus BufferViewTestInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const VkQueue queue = m_context.getUniversalQueue();
submitCommandsAndWait(vk, vkDevice, queue, m_cmdBuffer.get());
tcu::TestStatus testStatus = checkResult(1);
if (testStatus.getCode() != QP_TEST_RESULT_PASS)
return testStatus;
// Generate and bind another buffer
std::vector<deUint32> uniformData;
const VkDeviceSize uniformSize = m_testCase.bufferSize * sizeof(deUint32);
const deInt8 factor = 2;
generateBuffer(uniformData, m_testCase.bufferSize, factor);
deMemcpy(m_uniformBufferAlloc->getHostPtr(), uniformData.data(), (size_t)uniformSize);
flushMappedMemoryRange(vk, vkDevice, m_uniformBufferAlloc->getMemory(), m_uniformBufferAlloc->getOffset(), uniformSize);
submitCommandsAndWait(vk, vkDevice, queue, m_cmdBuffer.get());
return checkResult(factor);
}
class BufferViewTestCase : public vkt::TestCase
{
public:
BufferViewTestCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
BufferViewCaseParams bufferViewTestInfo)
: vkt::TestCase (testCtx, name, description)
, m_bufferViewTestInfo (bufferViewTestInfo)
{}
virtual ~BufferViewTestCase (void)
{}
virtual void initPrograms (SourceCollections& programCollection) const;
virtual TestInstance* createInstance (Context& context) const
{
return new BufferViewTestInstance(context, m_bufferViewTestInfo);
}
private:
BufferViewCaseParams m_bufferViewTestInfo;
};
void BufferViewTestCase::initPrograms (SourceCollections& programCollection) const
{
programCollection.glslSources.add("vert") << glu::VertexSource(
"#version 310 es\n"
"layout (location = 0) in highp vec4 a_position;\n"
"void main()\n"
"{\n"
" gl_Position = a_position;\n"
"}\n");
programCollection.glslSources.add("frag") << glu::FragmentSource(
"#version 310 es\n"
"#extension GL_EXT_texture_buffer : enable\n"
"layout (set=0, binding=0) uniform highp usamplerBuffer u_buffer;\n"
"layout (location = 0) out highp uint o_color;\n"
"void main()\n"
"{\n"
" o_color = texelFetch(u_buffer, int(gl_FragCoord.x)).x;\n"
"}\n");
}
} // anonymous
tcu::TestCaseGroup* createBufferViewAccessTests (tcu::TestContext& testCtx)
{
const char* const bufferTexts[ALLOCATION_KIND_LAST] =
{
"buffer_suballocated",
"buffer_dedicated_alloc"
};
const char* const imageTexts[ALLOCATION_KIND_LAST] =
{
"image_suballocated",
"image_dedicated_alloc"
};
de::MovePtr<tcu::TestCaseGroup> bufferViewTests (new tcu::TestCaseGroup(testCtx, "access", "BufferView Access Tests"));
de::MovePtr<tcu::TestCaseGroup> bufferViewAllocationGroupTests[] =
{
de::MovePtr<tcu::TestCaseGroup>(new tcu::TestCaseGroup(testCtx, "suballocation", "BufferView Access Tests for Suballocated Objects")),
de::MovePtr<tcu::TestCaseGroup>(new tcu::TestCaseGroup(testCtx, "dedicated_alloc", "BufferView Access Tests for Dedicatedly Allocated Objects"))
};
for (deUint32 buffersAllocationNdx = 0u; buffersAllocationNdx < ALLOCATION_KIND_LAST; ++buffersAllocationNdx)
for (deUint32 imageAllocationNdx = 0u; imageAllocationNdx < ALLOCATION_KIND_LAST; ++imageAllocationNdx)
{
const deUint32 testCaseGroupNdx = (buffersAllocationNdx == 0u && imageAllocationNdx == 0u) ? 0u : 1u;
de::MovePtr<tcu::TestCaseGroup>&
currentTestsGroup = bufferViewAllocationGroupTests[testCaseGroupNdx];
{
const BufferViewCaseParams info =
{
512, // deUint32 bufferSize
512, // deUint32 bufferViewSize
0, // deUint32 elementOffset
static_cast<AllocationKind>(buffersAllocationNdx),
static_cast<AllocationKind>(imageAllocationNdx)
};
std::ostringstream name;
name << "buffer_view_memory_test_complete";
if (testCaseGroupNdx != 0)
name << "_with_" << bufferTexts[buffersAllocationNdx] << "_" << imageTexts[imageAllocationNdx];
std::ostringstream description;
description << "bufferSize: " << info.bufferSize << " bufferViewSize: " << info.bufferViewSize << " bufferView element offset: " << info.elementOffset;
currentTestsGroup->addChild(new BufferViewTestCase(testCtx, name.str(), description.str(), info));
}
{
const BufferViewCaseParams info =
{
4096, // deUint32 bufferSize
512, // deUint32 bufferViewSize
0, // deUint32 elementOffset
static_cast<AllocationKind>(buffersAllocationNdx),
static_cast<AllocationKind>(imageAllocationNdx)
};
std::ostringstream name;
name << "buffer_view_memory_test_partial_offset0";
if (testCaseGroupNdx != 0)
name << "_with_" << bufferTexts[buffersAllocationNdx] << "_" << imageTexts[imageAllocationNdx];
std::ostringstream description;
description << "bufferSize: " << info.bufferSize << " bufferViewSize: " << info.bufferViewSize << " bufferView element offset: " << info.elementOffset;
currentTestsGroup->addChild(new BufferViewTestCase(testCtx, name.str(), description.str(), info));
}
{
const BufferViewCaseParams info =
{
4096, // deUint32 bufferSize
512, // deUint32 bufferViewSize
128, // deUint32 elementOffset
static_cast<AllocationKind>(buffersAllocationNdx),
static_cast<AllocationKind>(imageAllocationNdx)
};
std::ostringstream name;
name << "buffer_view_memory_test_partial_offset1";
if (testCaseGroupNdx != 0)
name << "_with_" << bufferTexts[buffersAllocationNdx] << "_" << imageTexts[imageAllocationNdx];
std::ostringstream description;
description << "bufferSize: " << info.bufferSize << " bufferViewSize: " << info.bufferViewSize << " bufferView element offset: " << info.elementOffset;
currentTestsGroup->addChild(new BufferViewTestCase(testCtx, name.str(), description.str(), info));
}
}
for (deUint32 subgroupNdx = 0u; subgroupNdx < DE_LENGTH_OF_ARRAY(bufferViewAllocationGroupTests); ++subgroupNdx)
{
bufferViewTests->addChild(bufferViewAllocationGroupTests[subgroupNdx].release());
}
return bufferViewTests.release();
}
} // api
} // vkt
| 39.701937 | 245 | 0.6878 | [
"render",
"vector"
] |
f55f8f68796c11054d5abf0bb19431b08fa418d9 | 2,476 | cpp | C++ | Hanicam/OpenCV/opencv-3.1.0/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp | ArianeFire/HaniCam | 8a940486a613d680a0b556209a596cdf3eb71f53 | [
"MIT"
] | 144 | 2015-01-15T03:38:44.000Z | 2022-02-17T09:07:52.000Z | Hanicam/OpenCV/opencv-3.1.0/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp | ArianeFire/HaniCam | 8a940486a613d680a0b556209a596cdf3eb71f53 | [
"MIT"
] | 9 | 2015-09-09T06:51:46.000Z | 2020-06-17T14:10:10.000Z | Hanicam/OpenCV/opencv-3.1.0/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp | ArianeFire/HaniCam | 8a940486a613d680a0b556209a596cdf3eb71f53 | [
"MIT"
] | 58 | 2015-01-14T23:43:49.000Z | 2021-11-15T05:19:08.000Z | /**
* @function pointPolygonTest_demo.cpp
* @brief Demo code to use the pointPolygonTest function...fairly easy
* @author OpenCV team
*/
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
/**
* @function main
*/
int main( void )
{
/// Create an image
const int r = 100;
Mat src = Mat::zeros( Size( 4*r, 4*r ), CV_8UC1 );
/// Create a sequence of points to make a contour:
vector<Point2f> vert(6);
vert[0] = Point( 3*r/2, static_cast<int>(1.34*r) );
vert[1] = Point( 1*r, 2*r );
vert[2] = Point( 3*r/2, static_cast<int>(2.866*r) );
vert[3] = Point( 5*r/2, static_cast<int>(2.866*r) );
vert[4] = Point( 3*r, 2*r );
vert[5] = Point( 5*r/2, static_cast<int>(1.34*r) );
/// Draw it in src
for( int j = 0; j < 6; j++ )
{ line( src, vert[j], vert[(j+1)%6], Scalar( 255 ), 3, 8 ); }
/// Get the contours
vector<vector<Point> > contours; vector<Vec4i> hierarchy;
Mat src_copy = src.clone();
findContours( src_copy, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
/// Calculate the distances to the contour
Mat raw_dist( src.size(), CV_32FC1 );
for( int j = 0; j < src.rows; j++ )
{ for( int i = 0; i < src.cols; i++ )
{ raw_dist.at<float>(j,i) = (float)pointPolygonTest( contours[0], Point2f((float)i,(float)j), true ); }
}
double minVal; double maxVal;
minMaxLoc( raw_dist, &minVal, &maxVal, 0, 0, Mat() );
minVal = abs(minVal); maxVal = abs(maxVal);
/// Depicting the distances graphically
Mat drawing = Mat::zeros( src.size(), CV_8UC3 );
for( int j = 0; j < src.rows; j++ )
{ for( int i = 0; i < src.cols; i++ )
{
if( raw_dist.at<float>(j,i) < 0 )
{ drawing.at<Vec3b>(j,i)[0] = (uchar)(255 - abs(raw_dist.at<float>(j,i))*255/minVal); }
else if( raw_dist.at<float>(j,i) > 0 )
{ drawing.at<Vec3b>(j,i)[2] = (uchar)(255 - raw_dist.at<float>(j,i)*255/maxVal); }
else
{ drawing.at<Vec3b>(j,i)[0] = 255; drawing.at<Vec3b>(j,i)[1] = 255; drawing.at<Vec3b>(j,i)[2] = 255; }
}
}
/// Create Window and show your results
const char* source_window = "Source";
namedWindow( source_window, WINDOW_AUTOSIZE );
imshow( source_window, src );
namedWindow( "Distance", WINDOW_AUTOSIZE );
imshow( "Distance", drawing );
waitKey(0);
return(0);
}
| 30.195122 | 116 | 0.594507 | [
"vector"
] |
f5622ef64b72e72448e4c774a006e6bffe74b4e6 | 10,906 | cpp | C++ | iteration.cpp | yketa/coll_dyn_activem | 7d72a258aa16fbb1dab5e49c811f38f381d51b28 | [
"MIT"
] | 1 | 2021-12-19T06:48:25.000Z | 2021-12-19T06:48:25.000Z | iteration.cpp | yketa/coll_dyn_activem | 7d72a258aa16fbb1dab5e49c811f38f381d51b28 | [
"MIT"
] | null | null | null | iteration.cpp | yketa/coll_dyn_activem | 7d72a258aa16fbb1dab5e49c811f38f381d51b28 | [
"MIT"
] | null | null | null | #include <cmath>
#include <math.h>
#include <vector>
#include "iteration.hpp"
#include "particle.hpp"
///////////////////////////////
// ACTIVE BROWNIAN PARTICLES //
///////////////////////////////
template<> void iterate_ABP_WCA(
System* system, int Niter) {
// Updates system to next step according to the dynamics of active Brownian
// particles with WCA potential, using custom dimensionless parameters
// relations.
Parameters* parameters = system->getParameters();
bool const considerTorque = ( system->getTorqueParameter() != 0 );
std::vector<Particle> newParticles(parameters->getNumberParticles());
double selfPropulsion; // self-propulsion force
double noise; // noise realisation
#if HEUN // HEUN'S SCHEME
double selfPropulsionCorrection; // correction to the self-propulsion force
std::vector<double> positions (2*parameters->getNumberParticles(), 0.0); // positions backup
std::vector<double> forces (2*parameters->getNumberParticles(), 0.0); // forces backup
std::vector<double> orientations; // orientations backup
std::vector<double> torques; // torques backup
if ( considerTorque ) { // only need to use this memory when torque parameter is not 0
orientations.assign(parameters->getNumberParticles(), 0.0);
torques.assign(parameters->getNumberParticles(), 0.0);
}
#endif
for (int iter=0; iter < Niter; iter++) {
// COMPUTATION
for (int i=0; i < parameters->getNumberParticles(); i++) {
// POSITIONS
for (int dim=0; dim < 2; dim++) {
// initialise velocity
(system->getParticle(i))->velocity()[dim] = 0.0;
// initialise new positions with previous ones
newParticles[i].position()[dim] =
(system->getParticle(i))->position()[dim];
// add self-propulsion
selfPropulsion =
#if CONTROLLED_DYNAMICS
(1.0 - 2.0*system->getBiasingParameter()
/3.0/parameters->getPersistenceLength())*
#endif
cos((system->getParticle(i))->orientation()[0] - dim*M_PI/2);
(system->getParticle(i))->velocity()[dim] += selfPropulsion;
newParticles[i].position()[dim] +=
parameters->getTimeStep()*selfPropulsion;
// add noise
noise = (system->getRandomGenerator())->gauss_cutoff();
(system->getParticle(i))->velocity()[dim] +=
sqrt(2.0/3.0/parameters->getPersistenceLength())
*noise;
newParticles[i].position()[dim] +=
sqrt(parameters->getTimeStep()
*2.0/3.0/parameters->getPersistenceLength())
*noise;
// initialise force
(system->getParticle(i))->force()[dim] = 0.0;
}
// ORIENTATIONS
// initialise new orientation with previous one
newParticles[i].orientation()[0] =
(system->getParticle(i))->orientation()[0];
// add noise
newParticles[i].orientation()[0] +=
sqrt(parameters->getTimeStep()*2.0/parameters->getPersistenceLength())
*(system->getRandomGenerator())->gauss_cutoff();
if ( considerTorque ) {
// initialise torque
(system->getParticle(i))->torque()[0] = 0.0;
}
}
// FORCES AND ALIGNING TORQUES
system_WCA<System>(system); // compute forces
if ( considerTorque ) {
aligningTorque<System>(system,
[&system](int index) {
return (system->getParticle(index))->orientation(); },
[&system](int index) {
return (system->getParticle(index))->torque(); }); // compute torques
}
for (int i=0; i < parameters->getNumberParticles(); i++) {
for (int dim=0; dim < 2; dim++) {
(system->getParticle(i))->velocity()[dim] +=
(system->getParticle(i))->force()[dim]
/3.0/parameters->getPersistenceLength(); // add force
newParticles[i].position()[dim] +=
(system->getParticle(i))->force()[dim]
*parameters->getTimeStep()/3.0/parameters->getPersistenceLength(); // add force displacement
}
if ( considerTorque ) {
newParticles[i].orientation()[0] +=
(system->getParticle(i))->torque()[0]*parameters->getTimeStep(); // add torque rotation
}
}
// HEUN'S SCHEME
#if HEUN
for (int i=0; i < parameters->getNumberParticles(); i++) {
for (int dim=0; dim < 2; dim++) {
// POSITIONS
positions[2*i + dim] = (system->getParticle(i))->position()[dim]; // save initial position
(system->getParticle(i))->position()[dim] =
newParticles[i].position()[dim]; // integrate position as if using Euler's scheme
// FORCES
forces[2*i + dim] = (system->getParticle(i))->force()[dim]; // save computed force at initial position
(system->getParticle(i))->force()[dim] = 0.0; // re-initialise force
}
if ( considerTorque ) {
// ORIENTATIONS
orientations[i] = (system->getParticle(i))->orientation()[0]; // save initial orientation
(system->getParticle(i))->orientation()[0] =
newParticles[i].orientation()[0]; // integrate position as if using Euler's scheme
// TORQUES
torques[i] = (system->getParticle(i))->torque()[0]; // save computed force at initial position
(system->getParticle(i))->torque()[0] = 0.0; // re-initialise torque
}
}
// FORCES AND ALIGNING TORQUES
system_WCA<System>(system); // re-compute forces
if ( considerTorque ) {
aligningTorque<System>(system,
[&system](int index) {
return (system->getParticle(index))->orientation(); },
[&system](int index) {
return (system->getParticle(index))->torque(); }); // re-compute torques
}
for (int i=0; i < parameters->getNumberParticles(); i++) {
// CORRECTION TO INTERPARTICLE FORCE
for (int dim=0; dim < 2; dim++) {
(system->getParticle(i))->velocity()[dim] +=
((system->getParticle(i))->force()[dim] - forces[2*i + dim])
/3.0/parameters->getPersistenceLength()/2; // velocity
newParticles[i].position()[dim] +=
((system->getParticle(i))->force()[dim] - forces[2*i + dim])
*parameters->getTimeStep()/3.0/parameters->getPersistenceLength()/2; // position
(system->getParticle(i))->force()[dim] =
((system->getParticle(i))->force()[dim] + forces[2*i + dim])/2; // force
}
// CORRECTION TO SELF-PROPULSION FORCE
for (int dim=0; dim < 2; dim++) {
selfPropulsionCorrection = 1.0;
#if CONTROLLED_DYNAMICS
selfPropulsionCorrection *=
(1.0 - 2.0*system->getBiasingParameter()
/3.0/parameters->getPersistenceLength());
#endif
if ( considerTorque ) {
selfPropulsionCorrection *=
(cos(newParticles[i].orientation()[0] - dim*M_PI/2)
- cos(orientations[2*i + dim] - dim*M_PI/2));
}
else {
selfPropulsionCorrection *=
(cos(newParticles[i].orientation()[0] - dim*M_PI/2)
- cos((system->getParticle(i))->orientation()[0] - dim*M_PI/2));
}
selfPropulsionCorrection /= 2;
(system->getParticle(i))->velocity()[dim] +=
selfPropulsionCorrection; // velocity
newParticles[i].position()[dim] +=
parameters->getTimeStep()*selfPropulsionCorrection; // position
}
// CORRECTION TO TORQUE
if ( considerTorque ) {
newParticles[i].orientation()[0] +=
((system->getParticle(i))->torque()[0] - torques[i])
*parameters->getTimeStep()/2; // orientation
(system->getParticle(i))->torque()[0] =
((system->getParticle(i))->torque()[0] + torques[i])/2; // torque
}
// RESET INITIAL POSITIONS AND ORIENTATION
for (int dim=0; dim < 2; dim++) {
(system->getParticle(i))->position()[dim] = positions[2*i + dim]; // position
}
if ( considerTorque ) {
(system->getParticle(i))->orientation()[0] = orientations[i]; // orientation
}
}
#endif
// SAVE AND COPY
system->saveNewState(newParticles);
}
}
/////////////////////////////////
// INTERACTING BROWNIAN ROTORS //
/////////////////////////////////
void iterate_rotors(Rotors* rotors, int Niter) {
// Updates system to next step according to the dynamics of interacting
// Brownian rotors.
bool const considerTorque = ( rotors->getTorqueParameter() != 0 );
std::vector<double> newOrientations(rotors->getNumberParticles());
#if HEUN // HEUN'S SCHEME
std::vector<double> orientations(rotors->getNumberParticles(), 0.0); // orientations backup
std::vector<double> torques(rotors->getNumberParticles(), 0.0); // torques backup
#endif
for (int iter=0; iter < Niter; iter++) {
// COMPUTATION
for (int i=0; i < rotors->getNumberParticles(); i++) {
// initialise new orientations with previous ones
newOrientations[i] = rotors->getOrientation(i)[0];
// reset torques
rotors->getTorque(i)[0] = 0.0;
// add noise
newOrientations[i] +=
sqrt(2.0*rotors->getRotDiffusivity()*rotors->getTimeStep())
*(rotors->getRandomGenerator())->gauss_cutoff();
}
// compute aligning torques
if ( considerTorque ) {
aligningTorque<Rotors>(rotors,
[&rotors](int index) {
return rotors->getOrientation(index); },
[&rotors](int index) {
return rotors->getTorque(index); }); // compute torques
}
// add torque
for (int i=0; i < rotors->getNumberParticles(); i++) {
newOrientations[i] +=
rotors->getTorque(i)[0]*rotors->getTimeStep();
}
// HEUN'S SCHEME
#if HEUN
for (int i=0; i < rotors->getNumberParticles(); i++) {
// ORIENTATIONS
orientations[i] = rotors->getOrientation(i)[0]; // save initial orientation
rotors->getOrientation(i)[0] = newOrientations[i]; // integration orientation as if using Euler's scheme
// TORQUES
torques[i] = rotors->getTorque(i)[0]; // save computed torque at initial orientation
rotors->getTorque(i)[0] = 0; // re-initialise torques
}
// re-compute aligning torques
if ( considerTorque ) {
aligningTorque<Rotors>(rotors,
[&rotors](int index) {
return rotors->getOrientation(index); },
[&rotors](int index) {
return rotors->getTorque(index); }); // compute torques
}
for (int i=0; i < rotors->getNumberParticles(); i++) {
// correction to orientations
newOrientations[i] +=
(rotors->getTorque(i)[0] - torques[i])*rotors->getTimeStep()
/2;
// correction to torques
rotors->getTorque(i)[0] =
(rotors->getTorque(i)[0] + torques[i])
/2;
// reset initial orientations
rotors->getOrientation(i)[0] = orientations[i];
}
#endif
// SAVE
rotors->saveNewState(newOrientations);
}
}
| 36.969492 | 110 | 0.595085 | [
"vector"
] |
f5672146cbcdf3cbe33a85c47790c8918b62eb5f | 5,890 | hh | C++ | src/arch/arm/kvm/arm_cpu.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 135 | 2016-10-21T03:31:49.000Z | 2022-03-25T01:22:20.000Z | src/arch/arm/kvm/arm_cpu.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 35 | 2017-03-10T17:57:46.000Z | 2022-02-18T17:34:16.000Z | src/arch/arm/kvm/arm_cpu.hh | qianlong4526888/haha | 01baf923693873c11ae072ce4dde3d8f1d7b6239 | [
"BSD-3-Clause"
] | 48 | 2016-12-08T12:03:13.000Z | 2022-02-16T09:16:13.000Z | /*
* Copyright (c) 2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andreas Sandberg
*/
#ifndef __ARCH_ARM_KVM_ARM_CPU_HH__
#define __ARCH_ARM_KVM_ARM_CPU_HH__
#include <set>
#include <vector>
#include "cpu/kvm/base.hh"
#include "params/ArmKvmCPU.hh"
/**
* ARM implementation of a KVM-based hardware virtualized CPU.
* Architecture specific limitations:
* * LPAE is currently not supported by gem5. We therefore panic if LPAE
* is enabled when returning to gem5.
* * The co-processor based interface to the architected timer is
* unsupported. We can't support this due to limitations in the KVM
* API on ARM.
* * M5 ops are currently not supported. This requires either a kernel
* hack or a memory mapped device that handles the guest<->m5
* interface.
*/
class ArmKvmCPU : public BaseKvmCPU
{
public:
ArmKvmCPU(ArmKvmCPUParams *params);
virtual ~ArmKvmCPU();
void startup();
void dump();
protected:
struct KvmIntRegInfo {
/** KVM ID */
const uint64_t id;
/** gem5 index */
const IntRegIndex idx;
/** Name in debug output */
const char *name;
};
struct KvmCoreMiscRegInfo {
/** KVM ID */
const uint64_t id;
/** gem5 index */
const MiscRegIndex idx;
/** Name in debug output */
const char *name;
};
typedef std::vector<uint64_t> RegIndexVector;
Tick kvmRun(Tick ticks);
void updateKvmState();
void updateThreadContext();
Tick onKvmExitHypercall();
/**
* Get a list of registers supported by getOneReg() and setOneReg().
*/
const RegIndexVector &getRegList() const;
void kvmArmVCpuInit(uint32_t target);
void kvmArmVCpuInit(const struct kvm_vcpu_init &init);
ArmISA::MiscRegIndex decodeCoProcReg(uint64_t id) const;
ArmISA::MiscRegIndex decodeVFPCtrlReg(uint64_t id) const;
/**
* Determine if a register is invariant.
*
* Some registers must have the same value in both the host and
* the guest. Such registers are referred to as "invariant"
* registers in KVM. This is a restriction imposed by KVM as
* having different values in ID registers (e.g., the cache
* identification registers) would confuse the guest kernel.
*/
bool isInvariantReg(uint64_t id);
static KvmIntRegInfo kvmIntRegs[];
static KvmCoreMiscRegInfo kvmCoreMiscRegs[];
private:
/**
* Get a list of registers supported by getOneReg() and setOneReg().
*
* @return False if the number of elements allocated in the list
* is too small to hold the complete register list (the required
* value is written into n in this case). True on success.
*/
bool getRegList(struct kvm_reg_list ®s) const;
void dumpKvmStateCore();
void dumpKvmStateMisc();
void dumpKvmStateCoProc(uint64_t id);
void dumpKvmStateVFP(uint64_t id);
void updateKvmStateCore();
void updateKvmStateMisc();
void updateKvmStateCoProc(uint64_t id, bool show_warnings);
void updateKvmStateVFP(uint64_t id, bool show_warnings);
void updateTCStateCore();
void updateTCStateMisc();
void updateTCStateCoProc(uint64_t id, bool show_warnings);
void updateTCStateVFP(uint64_t id, bool show_warnings);
/** Cached state of the IRQ line */
bool irqAsserted;
/** Cached state of the FIQ line */
bool fiqAsserted;
/**
* Cached copy of the list of co-processor registers supported by
* KVM
*/
mutable RegIndexVector _regIndexList;
/**
* List of co-processor registers that KVM requires to be
* identical on both the host and the guest. KVM does not allow
* writes to these registers.
*/
static const std::set<uint64_t> invariant_regs;
};
#endif // __ARCH_ARM_KVM_ARM_CPU_HH__
| 34.444444 | 73 | 0.71562 | [
"vector"
] |
f5684aeb3619021d07aa9cc740d45e98744da41c | 13,488 | cc | C++ | chrome/browser/renderer_host/web_cache_manager.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/browser/renderer_host/web_cache_manager.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/renderer_host/web_cache_manager.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include <algorithm>
#include "base/compiler_specific.h"
#include "base/singleton.h"
#include "base/sys_info.h"
#include "base/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/render_messages.h"
using base::Time;
using base::TimeDelta;
using WebKit::WebCache;
static const unsigned int kReviseAllocationDelayMS = 200 /* milliseconds */;
// The default size limit of the in-memory cache is 8 MB
static const int kDefaultMemoryCacheSize = 8 * 1024 * 1024;
namespace {
int GetDefaultCacheSize() {
// Start off with a modest default
int default_cache_size = kDefaultMemoryCacheSize;
// Check how much physical memory the OS has
int mem_size_mb = base::SysInfo::AmountOfPhysicalMemoryMB();
if (mem_size_mb >= 1000) // If we have a GB of memory, set a larger default.
default_cache_size *= 4;
else if (mem_size_mb >= 512) // With 512 MB, set a slightly larger default.
default_cache_size *= 2;
return default_cache_size;
}
} // anonymous namespace
// static
void WebCacheManager::RegisterPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kMemoryCacheSize, GetDefaultCacheSize());
}
// static
WebCacheManager* WebCacheManager::GetInstance() {
return Singleton<WebCacheManager>::get();
}
WebCacheManager::WebCacheManager()
: global_size_limit_(GetDefaultGlobalSizeLimit()),
ALLOW_THIS_IN_INITIALIZER_LIST(revise_allocation_factory_(this)) {
}
WebCacheManager::~WebCacheManager() {
}
void WebCacheManager::Add(int renderer_id) {
DCHECK(inactive_renderers_.count(renderer_id) == 0);
// It is tempting to make the following DCHECK here, but it fails when a new
// tab is created as we observe activity from that tab because the
// RenderProcessHost is recreated and adds itself.
//
// DCHECK(active_renderers_.count(renderer_id) == 0);
//
// However, there doesn't seem to be much harm in receiving the calls in this
// order.
active_renderers_.insert(renderer_id);
RendererInfo* stats = &(stats_[renderer_id]);
memset(stats, 0, sizeof(*stats));
stats->access = Time::Now();
// Revise our allocation strategy to account for this new renderer.
ReviseAllocationStrategyLater();
}
void WebCacheManager::Remove(int renderer_id) {
// Erase all knowledge of this renderer
active_renderers_.erase(renderer_id);
inactive_renderers_.erase(renderer_id);
stats_.erase(renderer_id);
// Reallocate the resources used by this renderer
ReviseAllocationStrategyLater();
}
void WebCacheManager::ObserveActivity(int renderer_id) {
StatsMap::iterator item = stats_.find(renderer_id);
if (item == stats_.end())
return; // We might see stats for a renderer that has been destroyed.
// Record activity.
active_renderers_.insert(renderer_id);
item->second.access = Time::Now();
std::set<int>::iterator elmt = inactive_renderers_.find(renderer_id);
if (elmt != inactive_renderers_.end()) {
inactive_renderers_.erase(elmt);
// A renderer that was inactive, just became active. We should make sure
// it is given a fair cache allocation, but we defer this for a bit in
// order to make this function call cheap.
ReviseAllocationStrategyLater();
}
}
void WebCacheManager::ObserveStats(int renderer_id,
const WebCache::UsageStats& stats) {
StatsMap::iterator entry = stats_.find(renderer_id);
if (entry == stats_.end())
return; // We might see stats for a renderer that has been destroyed.
// Record the updated stats.
entry->second.capacity = stats.capacity;
entry->second.deadSize = stats.deadSize;
entry->second.liveSize = stats.liveSize;
entry->second.maxDeadCapacity = stats.maxDeadCapacity;
entry->second.minDeadCapacity = stats.minDeadCapacity;
// trigger notification
WebCache::UsageStats stats_details(stats);
// &stats_details is only valid during the notification.
// See notification_types.h.
NotificationService::current()->Notify(
NotificationType::WEB_CACHE_STATS_OBSERVED,
Source<RenderProcessHost>(RenderProcessHost::FromID(renderer_id)),
Details<WebCache::UsageStats>(&stats_details));
}
void WebCacheManager::SetGlobalSizeLimit(size_t bytes) {
global_size_limit_ = bytes;
ReviseAllocationStrategyLater();
}
// static
size_t WebCacheManager::GetDefaultGlobalSizeLimit() {
PrefService* perf_service = g_browser_process->local_state();
if (perf_service)
return perf_service->GetInteger(prefs::kMemoryCacheSize);
return GetDefaultCacheSize();
}
void WebCacheManager::GatherStats(const std::set<int>& renderers,
WebCache::UsageStats* stats) {
DCHECK(stats);
memset(stats, 0, sizeof(WebCache::UsageStats));
std::set<int>::const_iterator iter = renderers.begin();
while (iter != renderers.end()) {
StatsMap::iterator elmt = stats_.find(*iter);
if (elmt != stats_.end()) {
stats->minDeadCapacity += elmt->second.minDeadCapacity;
stats->maxDeadCapacity += elmt->second.maxDeadCapacity;
stats->capacity += elmt->second.capacity;
stats->liveSize += elmt->second.liveSize;
stats->deadSize += elmt->second.deadSize;
}
++iter;
}
}
// static
size_t WebCacheManager::GetSize(AllocationTactic tactic,
const WebCache::UsageStats& stats) {
switch (tactic) {
case DIVIDE_EVENLY:
// We aren't going to reserve any space for existing objects.
return 0;
case KEEP_CURRENT_WITH_HEADROOM:
// We need enough space for our current objects, plus some headroom.
return 3 * GetSize(KEEP_CURRENT, stats) / 2;
case KEEP_CURRENT:
// We need enough space to keep our current objects.
return stats.liveSize + stats.deadSize;
case KEEP_LIVE_WITH_HEADROOM:
// We need enough space to keep out live resources, plus some headroom.
return 3 * GetSize(KEEP_LIVE, stats) / 2;
case KEEP_LIVE:
// We need enough space to keep our live resources.
return stats.liveSize;
default:
NOTREACHED() << "Unknown cache allocation tactic";
return 0;
}
}
bool WebCacheManager::AttemptTactic(
AllocationTactic active_tactic,
const WebCache::UsageStats& active_stats,
AllocationTactic inactive_tactic,
const WebCache::UsageStats& inactive_stats,
AllocationStrategy* strategy) {
DCHECK(strategy);
size_t active_size = GetSize(active_tactic, active_stats);
size_t inactive_size = GetSize(inactive_tactic, inactive_stats);
// Give up if we don't have enough space to use this tactic.
if (global_size_limit_ < active_size + inactive_size)
return false;
// Compute the unreserved space available.
size_t total_extra = global_size_limit_ - (active_size + inactive_size);
// The plan for the extra space is to divide it evenly amoung the active
// renderers.
size_t shares = active_renderers_.size();
// The inactive renderers get one share of the extra memory to be divided
// among themselves.
size_t inactive_extra = 0;
if (inactive_renderers_.size() > 0) {
++shares;
inactive_extra = total_extra / shares;
}
// The remaining memory is allocated to the active renderers.
size_t active_extra = total_extra - inactive_extra;
// Actually compute the allocations for each renderer.
AddToStrategy(active_renderers_, active_tactic, active_extra, strategy);
AddToStrategy(inactive_renderers_, inactive_tactic, inactive_extra, strategy);
// We succeeded in computing an allocation strategy.
return true;
}
void WebCacheManager::AddToStrategy(std::set<int> renderers,
AllocationTactic tactic,
size_t extra_bytes_to_allocate,
AllocationStrategy* strategy) {
DCHECK(strategy);
// Nothing to do if there are no renderers. It is common for there to be no
// inactive renderers if there is a single active tab.
if (renderers.size() == 0)
return;
// Divide the extra memory evenly among the renderers.
size_t extra_each = extra_bytes_to_allocate / renderers.size();
std::set<int>::const_iterator iter = renderers.begin();
while (iter != renderers.end()) {
size_t cache_size = extra_each;
// Add in the space required to implement |tactic|.
StatsMap::iterator elmt = stats_.find(*iter);
if (elmt != stats_.end())
cache_size += GetSize(tactic, elmt->second);
// Record the allocation in our strategy.
strategy->push_back(Allocation(*iter, cache_size));
++iter;
}
}
void WebCacheManager::EnactStrategy(const AllocationStrategy& strategy) {
// Inform each render process of its cache allocation.
AllocationStrategy::const_iterator allocation = strategy.begin();
while (allocation != strategy.end()) {
RenderProcessHost* host = RenderProcessHost::FromID(allocation->first);
if (host) {
// This is the capacity this renderer has been allocated.
size_t capacity = allocation->second;
// We don't reserve any space for dead objects in the cache. Instead, we
// prefer to keep live objects around. There is probably some performance
// tuning to be done here.
size_t min_dead_capacity = 0;
// We allow the dead objects to consume all of the cache, if the renderer
// so desires. If we wanted this memory, we would have set the total
// capacity lower.
size_t max_dead_capacity = capacity;
host->Send(new ViewMsg_SetCacheCapacities(min_dead_capacity,
max_dead_capacity,
capacity));
}
++allocation;
}
}
void WebCacheManager::ReviseAllocationStrategy() {
DCHECK(stats_.size() <=
active_renderers_.size() + inactive_renderers_.size());
// Check if renderers have gone inactive.
FindInactiveRenderers();
// Gather statistics
WebCache::UsageStats active;
WebCache::UsageStats inactive;
GatherStats(active_renderers_, &active);
GatherStats(inactive_renderers_, &inactive);
// Compute an allocation strategy.
//
// We attempt various tactics in order of preference. Our first preference
// is not to evict any objects. If we don't have enough resources, we'll
// first try to evict dead data only. If that fails, we'll just divide the
// resources we have evenly.
//
// We always try to give the active renderers some head room in their
// allocations so they can take memory away from an inactive renderer with
// a large cache allocation.
//
// Notice the early exit will prevent attempting less desirable tactics once
// we've found a workable strategy.
AllocationStrategy strategy;
if ( // Ideally, we'd like to give the active renderers some headroom and
// keep all our current objects.
AttemptTactic(KEEP_CURRENT_WITH_HEADROOM, active,
KEEP_CURRENT, inactive, &strategy) ||
// If we can't have that, then we first try to evict the dead objects in
// the caches of inactive renderers.
AttemptTactic(KEEP_CURRENT_WITH_HEADROOM, active,
KEEP_LIVE, inactive, &strategy) ||
// Next, we try to keep the live objects in the active renders (with some
// room for new objects) and give whatever is left to the inactive
// renderers.
AttemptTactic(KEEP_LIVE_WITH_HEADROOM, active,
DIVIDE_EVENLY, inactive, &strategy) ||
// If we've gotten this far, then we are very tight on memory. Let's try
// to at least keep around the live objects for the active renderers.
AttemptTactic(KEEP_LIVE, active, DIVIDE_EVENLY, inactive, &strategy) ||
// We're basically out of memory. The best we can do is just divide up
// what we have and soldier on.
AttemptTactic(DIVIDE_EVENLY, active, DIVIDE_EVENLY, inactive,
&strategy)) {
// Having found a workable strategy, we enact it.
EnactStrategy(strategy);
} else {
// DIVIDE_EVENLY / DIVIDE_EVENLY should always succeed.
NOTREACHED() << "Unable to find a cache allocation";
}
}
void WebCacheManager::ReviseAllocationStrategyLater() {
// Ask to be called back in a few milliseconds to actually recompute our
// allocation.
MessageLoop::current()->PostDelayedTask(FROM_HERE,
revise_allocation_factory_.NewRunnableMethod(
&WebCacheManager::ReviseAllocationStrategy),
kReviseAllocationDelayMS);
}
void WebCacheManager::FindInactiveRenderers() {
std::set<int>::const_iterator iter = active_renderers_.begin();
while (iter != active_renderers_.end()) {
StatsMap::iterator elmt = stats_.find(*iter);
DCHECK(elmt != stats_.end());
TimeDelta idle = Time::Now() - elmt->second.access;
if (idle >= TimeDelta::FromMinutes(kRendererInactiveThresholdMinutes)) {
// Moved to inactive status. This invalidates our iterator.
inactive_renderers_.insert(*iter);
active_renderers_.erase(*iter);
iter = active_renderers_.begin();
continue;
}
++iter;
}
}
| 35.777188 | 80 | 0.706628 | [
"render"
] |
f5685a97194249086f159bf36ae160ce075053a7 | 4,552 | hpp | C++ | Source/AllProjects/CQCKit/CQCKit_PowerStateMon.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CQCKit/CQCKit_PowerStateMon.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CQCKit/CQCKit_PowerStateMon.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCKit_PowerStateMon.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/03/2014
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This class is used when a client needs to wait for some arbitrary set of V2
// drivers (which implement the Power class) to reach a particular power state.
// When it's required to power on a set of drivers, it's necessary to check which
// ones are not in the required state and ask them to transition, then to wait for
// them to get there.
//
// It's also possible that some of them might be heading towards the opposite state,
// in which case we have to wait for those to get to that other state, and then
// ask for the transition to the desired state.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $Log$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TCQCPwrStateMon
// PREFIX: cpsm
// ---------------------------------------------------------------------------
class CQCKITEXPORT TCQCPwrStateMon : public TObject
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TCQCPwrStateMon() = delete;
TCQCPwrStateMon
(
const TString& strName
);
TCQCPwrStateMon(const TCQCPwrStateMon&) = default;
TCQCPwrStateMon(TCQCPwrStateMon&&) = default;
~TCQCPwrStateMon();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TCQCPwrStateMon& operator=(const TCQCPwrStateMon&) = default;
TCQCPwrStateMon& operator=(TCQCPwrStateMon&&) = default;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::EAsyncWaitRes eCheckResult();
tCIDLib::TVoid Cleanup();
tCIDLib::TVoid Start
(
const tCIDLib::TKVPCollect& colDrivers
, const tCIDLib::TBoolean bNewState
);
private :
// -------------------------------------------------------------------
// Private data types
//
// We need an overall state
// -------------------------------------------------------------------
enum class EStates
{
Idle
, Waiting
, Complete
, Timeout
};
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::EExitCodes ePollThread
(
TThread& thrThis
, tCIDLib::TVoid* pData
);
// -------------------------------------------------------------------
// Private data members
//
// m_eCurState
// Our current state, which is initialized by the Start() and
// Cleanup() methods, and the polling thread when active.
//
// m_eTarPwrState
// The new target status we are going for
//
// m_colDrivers
// The key/value list (driver/sub-unit) that we are to wait on.
//
// m_thrPoll
// The thread that does the waiting in the background.
//
// m_strName
// A name given to this object by the client code.
// -------------------------------------------------------------------
EStates m_eCurState;
tCQCKit::EPowerStatus m_eTarPwrState;
tCIDLib::TKVPList m_colDrivers;
TThread m_thrPoll;
TString m_strName;
// -------------------------------------------------------------------
// Magic Macros
// -------------------------------------------------------------------
RTTIDefs(TCQCPwrStateMon,TObject)
};
#pragma CIDLIB_POPPACK
| 32.056338 | 85 | 0.417399 | [
"object"
] |
f5694b7fb4dff264583ab746086838321c2cd88e | 38,101 | cpp | C++ | B2G/gecko/xpcom/base/nsTraceRefcntImpl.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/xpcom/base/nsTraceRefcntImpl.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/xpcom/base/nsTraceRefcntImpl.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsTraceRefcntImpl.h"
#include "nsXPCOMPrivate.h"
#include "nscore.h"
#include "nsISupports.h"
#include "nsTArray.h"
#include "prenv.h"
#include "prprf.h"
#include "prlog.h"
#include "plstr.h"
#include "prlink.h"
#include <stdlib.h>
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include <math.h>
#include "nsStackWalkPrivate.h"
#include "nsStackWalk.h"
#include "nsString.h"
#include "nsXULAppAPI.h"
#ifdef XP_WIN
#include <process.h>
#define getpid _getpid
#else
#include <unistd.h>
#endif
#ifdef NS_TRACE_MALLOC
#include "nsTraceMalloc.h"
#endif
#include "mozilla/BlockingResourceBase.h"
#include "mozilla/mozPoisonWrite.h"
#ifdef HAVE_DLOPEN
#include <dlfcn.h>
#endif
////////////////////////////////////////////////////////////////////////////////
void
NS_MeanAndStdDev(double n, double sumOfValues, double sumOfSquaredValues,
double *meanResult, double *stdDevResult)
{
double mean = 0.0, var = 0.0, stdDev = 0.0;
if (n > 0.0 && sumOfValues >= 0) {
mean = sumOfValues / n;
double temp = (n * sumOfSquaredValues) - (sumOfValues * sumOfValues);
if (temp < 0.0 || n <= 1)
var = 0.0;
else
var = temp / (n * (n - 1));
// for some reason, Windows says sqrt(0.0) is "-1.#J" (?!) so do this:
stdDev = var != 0.0 ? sqrt(var) : 0.0;
}
*meanResult = mean;
*stdDevResult = stdDev;
}
////////////////////////////////////////////////////////////////////////////////
#define NS_IMPL_REFCNT_LOGGING
#ifdef NS_IMPL_REFCNT_LOGGING
#include "plhash.h"
#include "prmem.h"
#include "prlock.h"
// TraceRefcnt has to use bare PRLock instead of mozilla::Mutex
// because TraceRefcnt can be used very early in startup.
static PRLock* gTraceLock;
#define LOCK_TRACELOG() PR_Lock(gTraceLock)
#define UNLOCK_TRACELOG() PR_Unlock(gTraceLock)
static PLHashTable* gBloatView;
static PLHashTable* gTypesToLog;
static PLHashTable* gObjectsToLog;
static PLHashTable* gSerialNumbers;
static int32_t gNextSerialNumber;
static bool gLogging;
static bool gLogToLeaky;
static bool gLogLeaksOnly;
static void (*leakyLogAddRef)(void* p, int oldrc, int newrc);
static void (*leakyLogRelease)(void* p, int oldrc, int newrc);
#define BAD_TLS_INDEX ((unsigned) -1)
// if gActivityTLS == BAD_TLS_INDEX, then we're
// unitialized... otherwise this points to a NSPR TLS thread index
// indicating whether addref activity is legal. If the PTR_TO_INT32 is 0 then
// activity is ok, otherwise not!
static unsigned gActivityTLS = BAD_TLS_INDEX;
static bool gInitialized;
static nsrefcnt gInitCount;
static FILE *gBloatLog = nullptr;
static FILE *gRefcntsLog = nullptr;
static FILE *gAllocLog = nullptr;
static FILE *gLeakyLog = nullptr;
static FILE *gCOMPtrLog = nullptr;
struct serialNumberRecord {
int32_t serialNumber;
int32_t refCount;
int32_t COMPtrCount;
};
struct nsTraceRefcntStats {
uint64_t mAddRefs;
uint64_t mReleases;
uint64_t mCreates;
uint64_t mDestroys;
double mRefsOutstandingTotal;
double mRefsOutstandingSquared;
double mObjsOutstandingTotal;
double mObjsOutstandingSquared;
};
// I hope to turn this on for everybody once we hit it a little less.
#ifdef DEBUG
static const char kStaticCtorDtorWarning[] =
"XPCOM objects created/destroyed from static ctor/dtor";
static void
AssertActivityIsLegal()
{
if (gActivityTLS == BAD_TLS_INDEX ||
NS_PTR_TO_INT32(PR_GetThreadPrivate(gActivityTLS)) != 0) {
if (PR_GetEnv("MOZ_FATAL_STATIC_XPCOM_CTORS_DTORS")) {
NS_RUNTIMEABORT(kStaticCtorDtorWarning);
} else {
NS_WARNING(kStaticCtorDtorWarning);
}
}
}
# define ASSERT_ACTIVITY_IS_LEGAL \
PR_BEGIN_MACRO \
AssertActivityIsLegal(); \
PR_END_MACRO
#else
# define ASSERT_ACTIVITY_IS_LEGAL PR_BEGIN_MACRO PR_END_MACRO
#endif // DEBUG
// These functions are copied from nsprpub/lib/ds/plhash.c, with changes
// to the functions not called Default* to free the serialNumberRecord or
// the BloatEntry.
static void *
DefaultAllocTable(void *pool, size_t size)
{
return PR_MALLOC(size);
}
static void
DefaultFreeTable(void *pool, void *item)
{
PR_Free(item);
}
static PLHashEntry *
DefaultAllocEntry(void *pool, const void *key)
{
return PR_NEW(PLHashEntry);
}
static void
SerialNumberFreeEntry(void *pool, PLHashEntry *he, unsigned flag)
{
if (flag == HT_FREE_ENTRY) {
PR_Free(reinterpret_cast<serialNumberRecord*>(he->value));
PR_Free(he);
}
}
static void
TypesToLogFreeEntry(void *pool, PLHashEntry *he, unsigned flag)
{
if (flag == HT_FREE_ENTRY) {
nsCRT::free(const_cast<char*>
(reinterpret_cast<const char*>(he->key)));
PR_Free(he);
}
}
static const PLHashAllocOps serialNumberHashAllocOps = {
DefaultAllocTable, DefaultFreeTable,
DefaultAllocEntry, SerialNumberFreeEntry
};
static const PLHashAllocOps typesToLogHashAllocOps = {
DefaultAllocTable, DefaultFreeTable,
DefaultAllocEntry, TypesToLogFreeEntry
};
////////////////////////////////////////////////////////////////////////////////
class BloatEntry {
public:
BloatEntry(const char* className, uint32_t classSize)
: mClassSize(classSize) {
mClassName = PL_strdup(className);
Clear(&mNewStats);
Clear(&mAllStats);
mTotalLeaked = 0;
}
~BloatEntry() {
PL_strfree(mClassName);
}
uint32_t GetClassSize() { return (uint32_t)mClassSize; }
const char* GetClassName() { return mClassName; }
static void Clear(nsTraceRefcntStats* stats) {
stats->mAddRefs = 0;
stats->mReleases = 0;
stats->mCreates = 0;
stats->mDestroys = 0;
stats->mRefsOutstandingTotal = 0;
stats->mRefsOutstandingSquared = 0;
stats->mObjsOutstandingTotal = 0;
stats->mObjsOutstandingSquared = 0;
}
void Accumulate() {
mAllStats.mAddRefs += mNewStats.mAddRefs;
mAllStats.mReleases += mNewStats.mReleases;
mAllStats.mCreates += mNewStats.mCreates;
mAllStats.mDestroys += mNewStats.mDestroys;
mAllStats.mRefsOutstandingTotal += mNewStats.mRefsOutstandingTotal;
mAllStats.mRefsOutstandingSquared += mNewStats.mRefsOutstandingSquared;
mAllStats.mObjsOutstandingTotal += mNewStats.mObjsOutstandingTotal;
mAllStats.mObjsOutstandingSquared += mNewStats.mObjsOutstandingSquared;
Clear(&mNewStats);
}
void AddRef(nsrefcnt refcnt) {
mNewStats.mAddRefs++;
if (refcnt == 1) {
Ctor();
}
AccountRefs();
}
void Release(nsrefcnt refcnt) {
mNewStats.mReleases++;
if (refcnt == 0) {
Dtor();
}
AccountRefs();
}
void Ctor() {
mNewStats.mCreates++;
AccountObjs();
}
void Dtor() {
mNewStats.mDestroys++;
AccountObjs();
}
void AccountRefs() {
uint64_t cnt = (mNewStats.mAddRefs - mNewStats.mReleases);
mNewStats.mRefsOutstandingTotal += cnt;
mNewStats.mRefsOutstandingSquared += cnt * cnt;
}
void AccountObjs() {
uint64_t cnt = (mNewStats.mCreates - mNewStats.mDestroys);
mNewStats.mObjsOutstandingTotal += cnt;
mNewStats.mObjsOutstandingSquared += cnt * cnt;
}
static int DumpEntry(PLHashEntry *he, int i, void *arg) {
BloatEntry* entry = (BloatEntry*)he->value;
if (entry) {
entry->Accumulate();
static_cast<nsTArray<BloatEntry*>*>(arg)->AppendElement(entry);
}
return HT_ENUMERATE_NEXT;
}
static int TotalEntries(PLHashEntry *he, int i, void *arg) {
BloatEntry* entry = (BloatEntry*)he->value;
if (entry && nsCRT::strcmp(entry->mClassName, "TOTAL") != 0) {
entry->Total((BloatEntry*)arg);
}
return HT_ENUMERATE_NEXT;
}
void Total(BloatEntry* total) {
total->mAllStats.mAddRefs += mNewStats.mAddRefs + mAllStats.mAddRefs;
total->mAllStats.mReleases += mNewStats.mReleases + mAllStats.mReleases;
total->mAllStats.mCreates += mNewStats.mCreates + mAllStats.mCreates;
total->mAllStats.mDestroys += mNewStats.mDestroys + mAllStats.mDestroys;
total->mAllStats.mRefsOutstandingTotal += mNewStats.mRefsOutstandingTotal + mAllStats.mRefsOutstandingTotal;
total->mAllStats.mRefsOutstandingSquared += mNewStats.mRefsOutstandingSquared + mAllStats.mRefsOutstandingSquared;
total->mAllStats.mObjsOutstandingTotal += mNewStats.mObjsOutstandingTotal + mAllStats.mObjsOutstandingTotal;
total->mAllStats.mObjsOutstandingSquared += mNewStats.mObjsOutstandingSquared + mAllStats.mObjsOutstandingSquared;
uint64_t count = (mNewStats.mCreates + mAllStats.mCreates);
total->mClassSize += mClassSize * count; // adjust for average in DumpTotal
total->mTotalLeaked += (uint64_t)(mClassSize *
((mNewStats.mCreates + mAllStats.mCreates)
-(mNewStats.mDestroys + mAllStats.mDestroys)));
}
void DumpTotal(FILE* out) {
mClassSize /= mAllStats.mCreates;
Dump(-1, out, nsTraceRefcntImpl::ALL_STATS);
}
static bool HaveLeaks(nsTraceRefcntStats* stats) {
return ((stats->mAddRefs != stats->mReleases) ||
(stats->mCreates != stats->mDestroys));
}
bool PrintDumpHeader(FILE* out, const char* msg, nsTraceRefcntImpl::StatisticsType type) {
fprintf(out, "\n== BloatView: %s, %s process %d\n", msg,
XRE_ChildProcessTypeToString(XRE_GetProcessType()), getpid());
nsTraceRefcntStats& stats =
(type == nsTraceRefcntImpl::NEW_STATS) ? mNewStats : mAllStats;
if (gLogLeaksOnly && !HaveLeaks(&stats))
return false;
fprintf(out,
"\n" \
" |<----------------Class--------------->|<-----Bytes------>|<----------------Objects---------------->|<--------------References-------------->|\n" \
" Per-Inst Leaked Total Rem Mean StdDev Total Rem Mean StdDev\n");
this->DumpTotal(out);
return true;
}
void Dump(int i, FILE* out, nsTraceRefcntImpl::StatisticsType type) {
nsTraceRefcntStats* stats = (type == nsTraceRefcntImpl::NEW_STATS) ? &mNewStats : &mAllStats;
if (gLogLeaksOnly && !HaveLeaks(stats)) {
return;
}
double meanRefs, stddevRefs;
NS_MeanAndStdDev(stats->mAddRefs + stats->mReleases,
stats->mRefsOutstandingTotal,
stats->mRefsOutstandingSquared,
&meanRefs, &stddevRefs);
double meanObjs, stddevObjs;
NS_MeanAndStdDev(stats->mCreates + stats->mDestroys,
stats->mObjsOutstandingTotal,
stats->mObjsOutstandingSquared,
&meanObjs, &stddevObjs);
if ((stats->mAddRefs - stats->mReleases) != 0 ||
stats->mAddRefs != 0 ||
meanRefs != 0 ||
stddevRefs != 0 ||
(stats->mCreates - stats->mDestroys) != 0 ||
stats->mCreates != 0 ||
meanObjs != 0 ||
stddevObjs != 0) {
fprintf(out, "%4d %-40.40s %8d %8llu %8llu %8llu (%8.2f +/- %8.2f) %8llu %8llu (%8.2f +/- %8.2f)\n",
i+1, mClassName,
(int32_t)mClassSize,
(nsCRT::strcmp(mClassName, "TOTAL"))
?(uint64_t)((stats->mCreates - stats->mDestroys) * mClassSize)
:mTotalLeaked,
stats->mCreates,
(stats->mCreates - stats->mDestroys),
meanObjs,
stddevObjs,
stats->mAddRefs,
(stats->mAddRefs - stats->mReleases),
meanRefs,
stddevRefs);
}
}
protected:
char* mClassName;
double mClassSize; // this is stored as a double because of the way we compute the avg class size for total bloat
uint64_t mTotalLeaked; // used only for TOTAL entry
nsTraceRefcntStats mNewStats;
nsTraceRefcntStats mAllStats;
};
static void
BloatViewFreeEntry(void *pool, PLHashEntry *he, unsigned flag)
{
if (flag == HT_FREE_ENTRY) {
BloatEntry* entry = reinterpret_cast<BloatEntry*>(he->value);
delete entry;
PR_Free(he);
}
}
const static PLHashAllocOps bloatViewHashAllocOps = {
DefaultAllocTable, DefaultFreeTable,
DefaultAllocEntry, BloatViewFreeEntry
};
static void
RecreateBloatView()
{
gBloatView = PL_NewHashTable(256,
PL_HashString,
PL_CompareStrings,
PL_CompareValues,
&bloatViewHashAllocOps, NULL);
}
static BloatEntry*
GetBloatEntry(const char* aTypeName, uint32_t aInstanceSize)
{
if (!gBloatView) {
RecreateBloatView();
}
BloatEntry* entry = NULL;
if (gBloatView) {
entry = (BloatEntry*)PL_HashTableLookup(gBloatView, aTypeName);
if (entry == NULL && aInstanceSize > 0) {
entry = new BloatEntry(aTypeName, aInstanceSize);
PLHashEntry* e = PL_HashTableAdd(gBloatView, aTypeName, entry);
if (e == NULL) {
delete entry;
entry = NULL;
}
} else {
NS_ASSERTION(aInstanceSize == 0 ||
entry->GetClassSize() == aInstanceSize,
"bad size recorded");
}
}
return entry;
}
static int DumpSerialNumbers(PLHashEntry* aHashEntry, int aIndex, void* aClosure)
{
serialNumberRecord* record = reinterpret_cast<serialNumberRecord *>(aHashEntry->value);
#ifdef HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR
fprintf((FILE*) aClosure, "%d @%p (%d references; %d from COMPtrs)\n",
record->serialNumber,
NS_INT32_TO_PTR(aHashEntry->key),
record->refCount,
record->COMPtrCount);
#else
fprintf((FILE*) aClosure, "%d @%p (%d references)\n",
record->serialNumber,
NS_INT32_TO_PTR(aHashEntry->key),
record->refCount);
#endif
return HT_ENUMERATE_NEXT;
}
template <>
class nsDefaultComparator <BloatEntry*, BloatEntry*> {
public:
bool Equals(BloatEntry* const& aA, BloatEntry* const& aB) const {
return PL_strcmp(aA->GetClassName(), aB->GetClassName()) == 0;
}
bool LessThan(BloatEntry* const& aA, BloatEntry* const& aB) const {
return PL_strcmp(aA->GetClassName(), aB->GetClassName()) < 0;
}
};
#endif /* NS_IMPL_REFCNT_LOGGING */
nsresult
nsTraceRefcntImpl::DumpStatistics(StatisticsType type, FILE* out)
{
#ifdef NS_IMPL_REFCNT_LOGGING
if (gBloatLog == nullptr || gBloatView == nullptr) {
return NS_ERROR_FAILURE;
}
if (out == nullptr) {
out = gBloatLog;
}
LOCK_TRACELOG();
bool wasLogging = gLogging;
gLogging = false; // turn off logging for this method
BloatEntry total("TOTAL", 0);
PL_HashTableEnumerateEntries(gBloatView, BloatEntry::TotalEntries, &total);
const char* msg;
if (type == NEW_STATS) {
if (gLogLeaksOnly)
msg = "NEW (incremental) LEAK STATISTICS";
else
msg = "NEW (incremental) LEAK AND BLOAT STATISTICS";
}
else {
if (gLogLeaksOnly)
msg = "ALL (cumulative) LEAK STATISTICS";
else
msg = "ALL (cumulative) LEAK AND BLOAT STATISTICS";
}
const bool leaked = total.PrintDumpHeader(out, msg, type);
nsTArray<BloatEntry*> entries;
PL_HashTableEnumerateEntries(gBloatView, BloatEntry::DumpEntry, &entries);
const uint32_t count = entries.Length();
if (!gLogLeaksOnly || leaked) {
// Sort the entries alphabetically by classname.
entries.Sort();
for (uint32_t i = 0; i < count; ++i) {
BloatEntry* entry = entries[i];
entry->Dump(i, out, type);
}
fprintf(out, "\n");
}
fprintf(out, "nsTraceRefcntImpl::DumpStatistics: %d entries\n", count);
if (gSerialNumbers) {
fprintf(out, "\nSerial Numbers of Leaked Objects:\n");
PL_HashTableEnumerateEntries(gSerialNumbers, DumpSerialNumbers, out);
}
gLogging = wasLogging;
UNLOCK_TRACELOG();
#endif
return NS_OK;
}
void
nsTraceRefcntImpl::ResetStatistics()
{
#ifdef NS_IMPL_REFCNT_LOGGING
LOCK_TRACELOG();
if (gBloatView) {
PL_HashTableDestroy(gBloatView);
gBloatView = nullptr;
}
UNLOCK_TRACELOG();
#endif
}
#ifdef NS_IMPL_REFCNT_LOGGING
static bool LogThisType(const char* aTypeName)
{
void* he = PL_HashTableLookup(gTypesToLog, aTypeName);
return nullptr != he;
}
static int32_t GetSerialNumber(void* aPtr, bool aCreate)
{
PLHashEntry** hep = PL_HashTableRawLookup(gSerialNumbers, PLHashNumber(NS_PTR_TO_INT32(aPtr)), aPtr);
if (hep && *hep) {
return int32_t((reinterpret_cast<serialNumberRecord*>((*hep)->value))->serialNumber);
}
else if (aCreate) {
serialNumberRecord *record = PR_NEW(serialNumberRecord);
record->serialNumber = ++gNextSerialNumber;
record->refCount = 0;
record->COMPtrCount = 0;
PL_HashTableRawAdd(gSerialNumbers, hep, PLHashNumber(NS_PTR_TO_INT32(aPtr)), aPtr, reinterpret_cast<void*>(record));
return gNextSerialNumber;
}
else {
return 0;
}
}
static int32_t* GetRefCount(void* aPtr)
{
PLHashEntry** hep = PL_HashTableRawLookup(gSerialNumbers, PLHashNumber(NS_PTR_TO_INT32(aPtr)), aPtr);
if (hep && *hep) {
return &((reinterpret_cast<serialNumberRecord*>((*hep)->value))->refCount);
} else {
return nullptr;
}
}
#if defined(NS_IMPL_REFCNT_LOGGING) && defined(HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR)
static int32_t* GetCOMPtrCount(void* aPtr)
{
PLHashEntry** hep = PL_HashTableRawLookup(gSerialNumbers, PLHashNumber(NS_PTR_TO_INT32(aPtr)), aPtr);
if (hep && *hep) {
return &((reinterpret_cast<serialNumberRecord*>((*hep)->value))->COMPtrCount);
} else {
return nullptr;
}
}
#endif
static void RecycleSerialNumberPtr(void* aPtr)
{
PL_HashTableRemove(gSerialNumbers, aPtr);
}
static bool LogThisObj(int32_t aSerialNumber)
{
return nullptr != PL_HashTableLookup(gObjectsToLog, (const void*)(aSerialNumber));
}
#ifdef XP_WIN
#define FOPEN_NO_INHERIT "N"
#else
#define FOPEN_NO_INHERIT
#endif
static bool InitLog(const char* envVar, const char* msg, FILE* *result)
{
const char* value = getenv(envVar);
if (value) {
if (nsCRT::strcmp(value, "1") == 0) {
*result = stdout;
fprintf(stdout, "### %s defined -- logging %s to stdout\n",
envVar, msg);
return true;
}
else if (nsCRT::strcmp(value, "2") == 0) {
*result = stderr;
fprintf(stdout, "### %s defined -- logging %s to stderr\n",
envVar, msg);
return true;
}
else {
FILE *stream;
nsAutoCString fname(value);
if (XRE_GetProcessType() != GeckoProcessType_Default) {
bool hasLogExtension =
fname.RFind(".log", true, -1, 4) == kNotFound ? false : true;
if (hasLogExtension)
fname.Cut(fname.Length() - 4, 4);
fname.AppendLiteral("_");
fname.Append((char*)XRE_ChildProcessTypeToString(XRE_GetProcessType()));
fname.AppendLiteral("_pid");
fname.AppendInt((uint32_t)getpid());
if (hasLogExtension)
fname.AppendLiteral(".log");
}
stream = ::fopen(fname.get(), "w" FOPEN_NO_INHERIT);
if (stream != NULL) {
MozillaRegisterDebugFD(fileno(stream));
*result = stream;
fprintf(stdout, "### %s defined -- logging %s to %s\n",
envVar, msg, fname.get());
}
else {
fprintf(stdout, "### %s defined -- unable to log %s to %s\n",
envVar, msg, fname.get());
}
return stream != NULL;
}
}
return false;
}
static PLHashNumber HashNumber(const void* aKey)
{
return PLHashNumber(NS_PTR_TO_INT32(aKey));
}
static void InitTraceLog(void)
{
if (gInitialized) return;
gInitialized = true;
bool defined;
defined = InitLog("XPCOM_MEM_BLOAT_LOG", "bloat/leaks", &gBloatLog);
if (!defined)
gLogLeaksOnly = InitLog("XPCOM_MEM_LEAK_LOG", "leaks", &gBloatLog);
if (defined || gLogLeaksOnly) {
RecreateBloatView();
if (!gBloatView) {
NS_WARNING("out of memory");
gBloatLog = nullptr;
gLogLeaksOnly = false;
}
}
(void)InitLog("XPCOM_MEM_REFCNT_LOG", "refcounts", &gRefcntsLog);
(void)InitLog("XPCOM_MEM_ALLOC_LOG", "new/delete", &gAllocLog);
defined = InitLog("XPCOM_MEM_LEAKY_LOG", "for leaky", &gLeakyLog);
if (defined) {
gLogToLeaky = true;
PRFuncPtr p = nullptr, q = nullptr;
#ifdef HAVE_DLOPEN
{
PRLibrary *lib = nullptr;
p = PR_FindFunctionSymbolAndLibrary("__log_addref", &lib);
if (lib) {
PR_UnloadLibrary(lib);
lib = nullptr;
}
q = PR_FindFunctionSymbolAndLibrary("__log_release", &lib);
if (lib) {
PR_UnloadLibrary(lib);
}
}
#endif
if (p && q) {
leakyLogAddRef = (void (*)(void*,int,int)) p;
leakyLogRelease = (void (*)(void*,int,int)) q;
}
else {
gLogToLeaky = false;
fprintf(stdout, "### ERROR: XPCOM_MEM_LEAKY_LOG defined, but can't locate __log_addref and __log_release symbols\n");
fflush(stdout);
}
}
const char* classes = getenv("XPCOM_MEM_LOG_CLASSES");
#ifdef HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR
if (classes) {
(void)InitLog("XPCOM_MEM_COMPTR_LOG", "nsCOMPtr", &gCOMPtrLog);
} else {
if (getenv("XPCOM_MEM_COMPTR_LOG")) {
fprintf(stdout, "### XPCOM_MEM_COMPTR_LOG defined -- but XPCOM_MEM_LOG_CLASSES is not defined\n");
}
}
#else
const char* comptr_log = getenv("XPCOM_MEM_COMPTR_LOG");
if (comptr_log) {
fprintf(stdout, "### XPCOM_MEM_COMPTR_LOG defined -- but it will not work without dynamic_cast\n");
}
#endif
if (classes) {
// if XPCOM_MEM_LOG_CLASSES was set to some value, the value is interpreted
// as a list of class names to track
gTypesToLog = PL_NewHashTable(256,
PL_HashString,
PL_CompareStrings,
PL_CompareValues,
&typesToLogHashAllocOps, NULL);
if (!gTypesToLog) {
NS_WARNING("out of memory");
fprintf(stdout, "### XPCOM_MEM_LOG_CLASSES defined -- unable to log specific classes\n");
}
else {
fprintf(stdout, "### XPCOM_MEM_LOG_CLASSES defined -- only logging these classes: ");
const char* cp = classes;
for (;;) {
char* cm = (char*) strchr(cp, ',');
if (cm) {
*cm = '\0';
}
PL_HashTableAdd(gTypesToLog, nsCRT::strdup(cp), (void*)1);
fprintf(stdout, "%s ", cp);
if (!cm) break;
*cm = ',';
cp = cm + 1;
}
fprintf(stdout, "\n");
}
gSerialNumbers = PL_NewHashTable(256,
HashNumber,
PL_CompareValues,
PL_CompareValues,
&serialNumberHashAllocOps, NULL);
}
const char* objects = getenv("XPCOM_MEM_LOG_OBJECTS");
if (objects) {
gObjectsToLog = PL_NewHashTable(256,
HashNumber,
PL_CompareValues,
PL_CompareValues,
NULL, NULL);
if (!gObjectsToLog) {
NS_WARNING("out of memory");
fprintf(stdout, "### XPCOM_MEM_LOG_OBJECTS defined -- unable to log specific objects\n");
}
else if (! (gRefcntsLog || gAllocLog || gCOMPtrLog)) {
fprintf(stdout, "### XPCOM_MEM_LOG_OBJECTS defined -- but none of XPCOM_MEM_(REFCNT|ALLOC|COMPTR)_LOG is defined\n");
}
else {
fprintf(stdout, "### XPCOM_MEM_LOG_OBJECTS defined -- only logging these objects: ");
const char* cp = objects;
for (;;) {
char* cm = (char*) strchr(cp, ',');
if (cm) {
*cm = '\0';
}
int32_t top = 0;
int32_t bottom = 0;
while (*cp) {
if (*cp == '-') {
bottom = top;
top = 0;
++cp;
}
top *= 10;
top += *cp - '0';
++cp;
}
if (!bottom) {
bottom = top;
}
for(int32_t serialno = bottom; serialno <= top; serialno++) {
PL_HashTableAdd(gObjectsToLog, (const void*)serialno, (void*)1);
fprintf(stdout, "%d ", serialno);
}
if (!cm) break;
*cm = ',';
cp = cm + 1;
}
fprintf(stdout, "\n");
}
}
if (gBloatLog || gRefcntsLog || gAllocLog || gLeakyLog || gCOMPtrLog) {
gLogging = true;
}
gTraceLock = PR_NewLock();
}
#endif
extern "C" {
static void PrintStackFrame(void *aPC, void *aSP, void *aClosure)
{
FILE *stream = (FILE*)aClosure;
nsCodeAddressDetails details;
char buf[1024];
NS_DescribeCodeAddress(aPC, &details);
NS_FormatCodeAddressDetails(aPC, &details, buf, sizeof(buf));
fputs(buf, stream);
}
}
void
nsTraceRefcntImpl::WalkTheStack(FILE* aStream)
{
NS_StackWalk(PrintStackFrame, 2, aStream, 0);
}
//----------------------------------------------------------------------
// This thing is exported by libstdc++
// Yes, this is a gcc only hack
#if defined(MOZ_DEMANGLE_SYMBOLS)
#include <cxxabi.h>
#include <stdlib.h> // for free()
#endif // MOZ_DEMANGLE_SYMBOLS
void
nsTraceRefcntImpl::DemangleSymbol(const char * aSymbol,
char * aBuffer,
int aBufLen)
{
NS_ASSERTION(nullptr != aSymbol,"null symbol");
NS_ASSERTION(nullptr != aBuffer,"null buffer");
NS_ASSERTION(aBufLen >= 32 ,"pulled 32 out of you know where");
aBuffer[0] = '\0';
#if defined(MOZ_DEMANGLE_SYMBOLS)
/* See demangle.h in the gcc source for the voodoo */
char * demangled = abi::__cxa_demangle(aSymbol,0,0,0);
if (demangled)
{
strncpy(aBuffer,demangled,aBufLen);
free(demangled);
}
#endif // MOZ_DEMANGLE_SYMBOLS
}
//----------------------------------------------------------------------
EXPORT_XPCOM_API(void)
NS_LogInit()
{
// FIXME: This is called multiple times, we should probably not allow that.
StackWalkInitCriticalAddress();
#ifdef NS_IMPL_REFCNT_LOGGING
if (++gInitCount)
nsTraceRefcntImpl::SetActivityIsLegal(true);
#endif
#ifdef NS_TRACE_MALLOC
// XXX we don't have to worry about shutting down trace-malloc; it
// handles this itself, through an atexit() callback.
if (!NS_TraceMallocHasStarted())
NS_TraceMallocStartup(-1); // -1 == no logging
#endif
}
EXPORT_XPCOM_API(void)
NS_LogTerm()
{
mozilla::LogTerm();
}
namespace mozilla {
void
LogTerm()
{
NS_ASSERTION(gInitCount > 0,
"NS_LogTerm without matching NS_LogInit");
if (--gInitCount == 0) {
#ifdef DEBUG
/* FIXME bug 491977: This is only going to operate on the
* BlockingResourceBase which is compiled into
* libxul/libxpcom_core.so. Anyone using external linkage will
* have their own copy of BlockingResourceBase statics which will
* not be freed by this method.
*
* It sounds like what we really want is to be able to register a
* callback function to call at XPCOM shutdown. Note that with
* this solution, however, we need to guarantee that
* BlockingResourceBase::Shutdown() runs after all other shutdown
* functions.
*/
BlockingResourceBase::Shutdown();
#endif
if (gInitialized) {
nsTraceRefcntImpl::DumpStatistics();
nsTraceRefcntImpl::ResetStatistics();
}
nsTraceRefcntImpl::Shutdown();
#ifdef NS_IMPL_REFCNT_LOGGING
nsTraceRefcntImpl::SetActivityIsLegal(false);
gActivityTLS = BAD_TLS_INDEX;
#endif
}
}
} // namespace mozilla
EXPORT_XPCOM_API(void)
NS_LogAddRef(void* aPtr, nsrefcnt aRefcnt,
const char* aClazz, uint32_t classSize)
{
#ifdef NS_IMPL_REFCNT_LOGGING
ASSERT_ACTIVITY_IS_LEGAL;
if (!gInitialized)
InitTraceLog();
if (gLogging) {
LOCK_TRACELOG();
if (gBloatLog) {
BloatEntry* entry = GetBloatEntry(aClazz, classSize);
if (entry) {
entry->AddRef(aRefcnt);
}
}
// Here's the case where MOZ_COUNT_CTOR was not used,
// yet we still want to see creation information:
bool loggingThisType = (!gTypesToLog || LogThisType(aClazz));
int32_t serialno = 0;
if (gSerialNumbers && loggingThisType) {
serialno = GetSerialNumber(aPtr, aRefcnt == 1);
NS_ASSERTION(serialno != 0,
"Serial number requested for unrecognized pointer! "
"Are you memmoving a refcounted object?");
int32_t* count = GetRefCount(aPtr);
if(count)
(*count)++;
}
bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno));
if (aRefcnt == 1 && gAllocLog && loggingThisType && loggingThisObject) {
fprintf(gAllocLog, "\n<%s> 0x%08X %d Create\n",
aClazz, NS_PTR_TO_INT32(aPtr), serialno);
nsTraceRefcntImpl::WalkTheStack(gAllocLog);
}
if (gRefcntsLog && loggingThisType && loggingThisObject) {
if (gLogToLeaky) {
(*leakyLogAddRef)(aPtr, aRefcnt - 1, aRefcnt);
}
else {
// Can't use PR_LOG(), b/c it truncates the line
fprintf(gRefcntsLog,
"\n<%s> 0x%08X %d AddRef %d\n", aClazz, NS_PTR_TO_INT32(aPtr), serialno, aRefcnt);
nsTraceRefcntImpl::WalkTheStack(gRefcntsLog);
fflush(gRefcntsLog);
}
}
UNLOCK_TRACELOG();
}
#endif
}
EXPORT_XPCOM_API(void)
NS_LogRelease(void* aPtr, nsrefcnt aRefcnt, const char* aClazz)
{
#ifdef NS_IMPL_REFCNT_LOGGING
ASSERT_ACTIVITY_IS_LEGAL;
if (!gInitialized)
InitTraceLog();
if (gLogging) {
LOCK_TRACELOG();
if (gBloatLog) {
BloatEntry* entry = GetBloatEntry(aClazz, 0);
if (entry) {
entry->Release(aRefcnt);
}
}
bool loggingThisType = (!gTypesToLog || LogThisType(aClazz));
int32_t serialno = 0;
if (gSerialNumbers && loggingThisType) {
serialno = GetSerialNumber(aPtr, false);
NS_ASSERTION(serialno != 0,
"Serial number requested for unrecognized pointer! "
"Are you memmoving a refcounted object?");
int32_t* count = GetRefCount(aPtr);
if(count)
(*count)--;
}
bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno));
if (gRefcntsLog && loggingThisType && loggingThisObject) {
if (gLogToLeaky) {
(*leakyLogRelease)(aPtr, aRefcnt + 1, aRefcnt);
}
else {
// Can't use PR_LOG(), b/c it truncates the line
fprintf(gRefcntsLog,
"\n<%s> 0x%08X %d Release %d\n", aClazz, NS_PTR_TO_INT32(aPtr), serialno, aRefcnt);
nsTraceRefcntImpl::WalkTheStack(gRefcntsLog);
fflush(gRefcntsLog);
}
}
// Here's the case where MOZ_COUNT_DTOR was not used,
// yet we still want to see deletion information:
if (aRefcnt == 0 && gAllocLog && loggingThisType && loggingThisObject) {
fprintf(gAllocLog,
"\n<%s> 0x%08X %d Destroy\n",
aClazz, NS_PTR_TO_INT32(aPtr), serialno);
nsTraceRefcntImpl::WalkTheStack(gAllocLog);
}
if (aRefcnt == 0 && gSerialNumbers && loggingThisType) {
RecycleSerialNumberPtr(aPtr);
}
UNLOCK_TRACELOG();
}
#endif
}
EXPORT_XPCOM_API(void)
NS_LogCtor(void* aPtr, const char* aType, uint32_t aInstanceSize)
{
#ifdef NS_IMPL_REFCNT_LOGGING
ASSERT_ACTIVITY_IS_LEGAL;
if (!gInitialized)
InitTraceLog();
if (gLogging) {
LOCK_TRACELOG();
if (gBloatLog) {
BloatEntry* entry = GetBloatEntry(aType, aInstanceSize);
if (entry) {
entry->Ctor();
}
}
bool loggingThisType = (!gTypesToLog || LogThisType(aType));
int32_t serialno = 0;
if (gSerialNumbers && loggingThisType) {
serialno = GetSerialNumber(aPtr, true);
}
bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno));
if (gAllocLog && loggingThisType && loggingThisObject) {
fprintf(gAllocLog, "\n<%s> 0x%08X %d Ctor (%d)\n",
aType, NS_PTR_TO_INT32(aPtr), serialno, aInstanceSize);
nsTraceRefcntImpl::WalkTheStack(gAllocLog);
}
UNLOCK_TRACELOG();
}
#endif
}
EXPORT_XPCOM_API(void)
NS_LogDtor(void* aPtr, const char* aType, uint32_t aInstanceSize)
{
#ifdef NS_IMPL_REFCNT_LOGGING
ASSERT_ACTIVITY_IS_LEGAL;
if (!gInitialized)
InitTraceLog();
if (gLogging) {
LOCK_TRACELOG();
if (gBloatLog) {
BloatEntry* entry = GetBloatEntry(aType, aInstanceSize);
if (entry) {
entry->Dtor();
}
}
bool loggingThisType = (!gTypesToLog || LogThisType(aType));
int32_t serialno = 0;
if (gSerialNumbers && loggingThisType) {
serialno = GetSerialNumber(aPtr, false);
RecycleSerialNumberPtr(aPtr);
}
bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno));
// (If we're on a losing architecture, don't do this because we'll be
// using LogDeleteXPCOM instead to get file and line numbers.)
if (gAllocLog && loggingThisType && loggingThisObject) {
fprintf(gAllocLog, "\n<%s> 0x%08X %d Dtor (%d)\n",
aType, NS_PTR_TO_INT32(aPtr), serialno, aInstanceSize);
nsTraceRefcntImpl::WalkTheStack(gAllocLog);
}
UNLOCK_TRACELOG();
}
#endif
}
EXPORT_XPCOM_API(void)
NS_LogCOMPtrAddRef(void* aCOMPtr, nsISupports* aObject)
{
#if defined(NS_IMPL_REFCNT_LOGGING) && defined(HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR)
// Get the most-derived object.
void *object = dynamic_cast<void *>(aObject);
// This is a very indirect way of finding out what the class is
// of the object being logged. If we're logging a specific type,
// then
if (!gTypesToLog || !gSerialNumbers) {
return;
}
int32_t serialno = GetSerialNumber(object, false);
if (serialno == 0) {
return;
}
if (!gInitialized)
InitTraceLog();
if (gLogging) {
LOCK_TRACELOG();
int32_t* count = GetCOMPtrCount(object);
if(count)
(*count)++;
bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno));
if (gCOMPtrLog && loggingThisObject) {
fprintf(gCOMPtrLog, "\n<?> 0x%08X %d nsCOMPtrAddRef %d 0x%08X\n",
NS_PTR_TO_INT32(object), serialno, count?(*count):-1, NS_PTR_TO_INT32(aCOMPtr));
nsTraceRefcntImpl::WalkTheStack(gCOMPtrLog);
}
UNLOCK_TRACELOG();
}
#endif
}
EXPORT_XPCOM_API(void)
NS_LogCOMPtrRelease(void* aCOMPtr, nsISupports* aObject)
{
#if defined(NS_IMPL_REFCNT_LOGGING) && defined(HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR)
// Get the most-derived object.
void *object = dynamic_cast<void *>(aObject);
// This is a very indirect way of finding out what the class is
// of the object being logged. If we're logging a specific type,
// then
if (!gTypesToLog || !gSerialNumbers) {
return;
}
int32_t serialno = GetSerialNumber(object, false);
if (serialno == 0) {
return;
}
if (!gInitialized)
InitTraceLog();
if (gLogging) {
LOCK_TRACELOG();
int32_t* count = GetCOMPtrCount(object);
if(count)
(*count)--;
bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno));
if (gCOMPtrLog && loggingThisObject) {
fprintf(gCOMPtrLog, "\n<?> 0x%08X %d nsCOMPtrRelease %d 0x%08X\n",
NS_PTR_TO_INT32(object), serialno, count?(*count):-1, NS_PTR_TO_INT32(aCOMPtr));
nsTraceRefcntImpl::WalkTheStack(gCOMPtrLog);
}
UNLOCK_TRACELOG();
}
#endif
}
void
nsTraceRefcntImpl::Startup()
{
}
static void maybeUnregisterAndCloseFile(FILE *&f) {
if (!f)
return;
MozillaUnRegisterDebugFILE(f);
fclose(f);
f = nullptr;
}
void
nsTraceRefcntImpl::Shutdown()
{
#ifdef NS_IMPL_REFCNT_LOGGING
if (gBloatView) {
PL_HashTableDestroy(gBloatView);
gBloatView = nullptr;
}
if (gTypesToLog) {
PL_HashTableDestroy(gTypesToLog);
gTypesToLog = nullptr;
}
if (gObjectsToLog) {
PL_HashTableDestroy(gObjectsToLog);
gObjectsToLog = nullptr;
}
if (gSerialNumbers) {
PL_HashTableDestroy(gSerialNumbers);
gSerialNumbers = nullptr;
}
maybeUnregisterAndCloseFile(gBloatLog);
maybeUnregisterAndCloseFile(gRefcntsLog);
maybeUnregisterAndCloseFile(gAllocLog);
maybeUnregisterAndCloseFile(gLeakyLog);
maybeUnregisterAndCloseFile(gCOMPtrLog);
#endif
}
void
nsTraceRefcntImpl::SetActivityIsLegal(bool aLegal)
{
#ifdef NS_IMPL_REFCNT_LOGGING
if (gActivityTLS == BAD_TLS_INDEX)
PR_NewThreadPrivateIndex(&gActivityTLS, nullptr);
PR_SetThreadPrivate(gActivityTLS, NS_INT32_TO_PTR(!aLegal));
#endif
}
NS_IMPL_QUERY_INTERFACE1(nsTraceRefcntImpl, nsITraceRefcnt)
NS_IMETHODIMP_(nsrefcnt) nsTraceRefcntImpl::AddRef(void)
{
return 2;
}
NS_IMETHODIMP_(nsrefcnt) nsTraceRefcntImpl::Release(void)
{
return 1;
}
NS_IMETHODIMP
nsTraceRefcntImpl::LogAddRef(void *aPtr, nsrefcnt aNewRefcnt,
const char *aTypeName, uint32_t aSize)
{
NS_LogAddRef(aPtr, aNewRefcnt, aTypeName, aSize);
return NS_OK;
}
NS_IMETHODIMP
nsTraceRefcntImpl::LogRelease(void *aPtr, nsrefcnt aNewRefcnt,
const char *aTypeName)
{
NS_LogRelease(aPtr, aNewRefcnt, aTypeName);
return NS_OK;
}
NS_IMETHODIMP
nsTraceRefcntImpl::LogCtor(void *aPtr, const char *aTypeName, uint32_t aSize)
{
NS_LogCtor(aPtr, aTypeName, aSize);
return NS_OK;
}
NS_IMETHODIMP
nsTraceRefcntImpl::LogDtor(void *aPtr, const char *aTypeName, uint32_t aSize)
{
NS_LogDtor(aPtr, aTypeName, aSize);
return NS_OK;
}
NS_IMETHODIMP
nsTraceRefcntImpl::LogAddCOMPtr(void *aCOMPtr, nsISupports* aObject)
{
NS_LogCOMPtrAddRef(aCOMPtr, aObject);
return NS_OK;
}
NS_IMETHODIMP
nsTraceRefcntImpl::LogReleaseCOMPtr(void *aCOMPtr, nsISupports* aObject)
{
NS_LogCOMPtrRelease(aCOMPtr, aObject);
return NS_OK;
}
static const nsTraceRefcntImpl kTraceRefcntImpl;
NS_METHOD
nsTraceRefcntImpl::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr)
{
return const_cast<nsTraceRefcntImpl*>(&kTraceRefcntImpl)->
QueryInterface(aIID, aInstancePtr);
}
| 28.118819 | 161 | 0.639773 | [
"object"
] |
f56bf35b2b421b4621d725652117f01d35d1369e | 1,298 | hpp | C++ | src/lib/bamrc/BasicStat.hpp | matnguyen/bam-readcount | 3a60b29688d8a5de1a1e99338a9530b5a7441a14 | [
"MIT"
] | null | null | null | src/lib/bamrc/BasicStat.hpp | matnguyen/bam-readcount | 3a60b29688d8a5de1a1e99338a9530b5a7441a14 | [
"MIT"
] | null | null | null | src/lib/bamrc/BasicStat.hpp | matnguyen/bam-readcount | 3a60b29688d8a5de1a1e99338a9530b5a7441a14 | [
"MIT"
] | null | null | null | #pragma once
#include <ostream>
#include <vector>
#include "sam.h"
class BasicStat {
public:
BasicStat(bool is_indel = false);
void process_read(bam_pileup1_t const* base); //may want other things here like clipping.
mutable unsigned int read_count; //number of reads containing the indel
mutable unsigned int sum_map_qualities; //sum of the mapping qualities of reads containing the indel
mutable unsigned int sum_single_ended_map_qualities; //sum of the single ended mapping qualities;
mutable unsigned int num_plus_strand;
mutable unsigned int num_minus_strand;
mutable float sum_event_location;
mutable float sum_q2_distance;
mutable unsigned int num_q2_reads;
mutable float sum_number_of_mismatches;
mutable unsigned int sum_of_mismatch_qualities;
mutable unsigned int sum_of_clipped_lengths;
mutable float sum_3p_distance;
mutable float sum_5p_distance;
mutable unsigned int sum_base_qualities;
mutable std::vector<unsigned int> mapping_qualities;
mutable std::vector<float> distances_to_3p;
mutable std::vector<float> distances_to_5p;
bool is_indel;
};
std::ostream& operator<<(std::ostream& s, const BasicStat& stat);
| 39.333333 | 108 | 0.716487 | [
"vector"
] |
f570fd99ca0527c1db7730dc6e08e941a14e42a9 | 12,217 | cpp | C++ | Libs/mitkCore/src/mitkCoreActivator.cpp | al-sabr/CTK-MotionBox | 002afb789b3d33a42a1ceae45637bb5467c11eb3 | [
"Apache-2.0"
] | null | null | null | Libs/mitkCore/src/mitkCoreActivator.cpp | al-sabr/CTK-MotionBox | 002afb789b3d33a42a1ceae45637bb5467c11eb3 | [
"Apache-2.0"
] | null | null | null | Libs/mitkCore/src/mitkCoreActivator.cpp | al-sabr/CTK-MotionBox | 002afb789b3d33a42a1ceae45637bb5467c11eb3 | [
"Apache-2.0"
] | null | null | null | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkCoreActivator.h"
#include <mitkCoreServices.h>
#include <mitkPropertyPersistenceInfo.h>
// File IO
#include <mitkIOMetaInformationPropertyConstants.h>
#include <mitkGeometryDataReaderService.h>
#include <mitkGeometryDataWriterService.h>
#include <mitkIOMimeTypes.h>
#include <mitkIOUtil.h>
#include <mitkImageVtkLegacyIO.h>
#include <mitkImageVtkXmlIO.h>
#include <mitkItkImageIO.h>
#include <mitkMimeTypeProvider.h>
#include <mitkPointSetReaderService.h>
#include <mitkPointSetWriterService.h>
#include <mitkRawImageFileReader.h>
#include <mitkSurfaceStlIO.h>
#include <mitkSurfaceVtkLegacyIO.h>
#include <mitkSurfaceVtkXmlIO.h>
#include "mitkLegacyFileWriterService.h"
#include <mitkFileWriter.h>
#include <itkGDCMImageIO.h>
#include <itkNiftiImageIO.h>
// PropertyRelationRules
#include <mitkPropertyRelationRuleBase.h>
// Micro Services
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleActivator.h>
#include <usModuleContext.h>
#include <usModuleEvent.h>
#include <usModuleInitialization.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
#include <usModuleSettings.h>
#include <usServiceTracker.h>
// ITK "injects" static initialization code for IO factories
// via the itkImageIOFactoryRegisterManager.h header (which
// is generated in the application library build directory).
// To ensure that the code is called *before* the CppMicroServices
// static initialization code (which triggers the Activator::Start
// method), we include the ITK header here.
#include <itkImageIOFactoryRegisterManager.h>
void HandleMicroServicesMessages(us::MsgType type, const char *msg)
{
switch (type)
{
case us::DebugMsg:
MITK_DEBUG << msg;
break;
case us::InfoMsg:
MITK_INFO << msg;
break;
case us::WarningMsg:
MITK_WARN << msg;
break;
case us::ErrorMsg:
MITK_ERROR << msg;
break;
}
}
void AddMitkAutoLoadPaths(const std::string &programPath)
{
us::ModuleSettings::AddAutoLoadPath(programPath);
#ifdef __APPLE__
// Walk up three directories since that is where the .dylib files are located
// for build trees.
std::string additionalPath = programPath;
bool addPath = true;
for (int i = 0; i < 3; ++i)
{
std::size_t index = additionalPath.find_last_of('/');
if (index != std::string::npos)
{
additionalPath = additionalPath.substr(0, index);
}
else
{
addPath = false;
break;
}
}
if (addPath)
{
us::ModuleSettings::AddAutoLoadPath(additionalPath);
}
#endif
}
void AddPropertyPersistence(const mitk::PropertyKeyPath& propPath)
{
mitk::CoreServicePointer<mitk::IPropertyPersistence> persistenceService(mitk::CoreServices::GetPropertyPersistence());
auto info = mitk::PropertyPersistenceInfo::New();
if (propPath.IsExplicit())
{
std::string name = mitk::PropertyKeyPathToPropertyName(propPath);
std::string key = name;
std::replace(key.begin(), key.end(), '.', '_');
info->SetNameAndKey(name, key);
}
else
{
std::string key = mitk::PropertyKeyPathToPersistenceKeyRegEx(propPath);
std::string keyTemplate = mitk::PropertyKeyPathToPersistenceKeyTemplate(propPath);
std::string propRegEx = mitk::PropertyKeyPathToPropertyRegEx(propPath);
std::string propTemplate = mitk::PropertyKeyPathToPersistenceNameTemplate(propPath);
info->UseRegEx(propRegEx, propTemplate, key, keyTemplate);
}
persistenceService->AddInfo(info);
}
class FixedNiftiImageIO : public itk::NiftiImageIO
{
public:
/** Standard class typedefs. */
typedef FixedNiftiImageIO Self;
typedef itk::NiftiImageIO Superclass;
typedef itk::SmartPointer<Self> Pointer;
/** Method for creation through the object factory. */
itkNewMacro(Self)
/** Run-time type information (and related methods). */
itkTypeMacro(FixedNiftiImageIO, Superclass)
bool SupportsDimension(unsigned long dim) override
{
return dim > 1 && dim < 5;
}
};
void MitkCoreActivator::Load(us::ModuleContext *context)
{
// Handle messages from CppMicroServices
us::installMsgHandler(HandleMicroServicesMessages);
this->m_Context = context;
// Add the current application directory to the auto-load paths.
// This is useful for third-party executables.
std::string programPath = mitk::IOUtil::GetProgramPath();
if (programPath.empty())
{
MITK_WARN << "Could not get the program path.";
}
else
{
AddMitkAutoLoadPaths(programPath);
}
// m_RenderingManager = mitk::RenderingManager::New();
// context->RegisterService<mitk::RenderingManager>(renderingManager.GetPointer());
m_PlanePositionManager.reset(new mitk::PlanePositionManagerService);
context->RegisterService<mitk::PlanePositionManagerService>(m_PlanePositionManager.get());
m_PropertyAliases.reset(new mitk::PropertyAliases);
context->RegisterService<mitk::IPropertyAliases>(m_PropertyAliases.get());
m_PropertyDescriptions.reset(new mitk::PropertyDescriptions);
context->RegisterService<mitk::IPropertyDescriptions>(m_PropertyDescriptions.get());
m_PropertyExtensions.reset(new mitk::PropertyExtensions);
context->RegisterService<mitk::IPropertyExtensions>(m_PropertyExtensions.get());
m_PropertyFilters.reset(new mitk::PropertyFilters);
context->RegisterService<mitk::IPropertyFilters>(m_PropertyFilters.get());
m_PropertyPersistence.reset(new mitk::PropertyPersistence);
context->RegisterService<mitk::IPropertyPersistence>(m_PropertyPersistence.get());
m_PropertyRelations.reset(new mitk::PropertyRelations);
context->RegisterService<mitk::IPropertyRelations>(m_PropertyRelations.get());
m_MimeTypeProvider.reset(new mitk::MimeTypeProvider);
m_MimeTypeProvider->Start();
m_MimeTypeProviderReg = context->RegisterService<mitk::IMimeTypeProvider>(m_MimeTypeProvider.get());
this->RegisterDefaultMimeTypes();
this->RegisterItkReaderWriter();
this->RegisterVtkReaderWriter();
// Add custom Reader / Writer Services
m_FileReaders.push_back(new mitk::PointSetReaderService());
m_FileWriters.push_back(new mitk::PointSetWriterService());
m_FileReaders.push_back(new mitk::GeometryDataReaderService());
m_FileWriters.push_back(new mitk::GeometryDataWriterService());
m_FileReaders.push_back(new mitk::RawImageFileReaderService());
//add properties that should be persistent (if possible/supported by the writer)
AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_DESCRIPTION());
AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_INPUTLOCATION());
AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_MIME_CATEGORY());
AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_MIME_NAME());
AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_VERSION());
AddPropertyPersistence(mitk::IOMetaInformationPropertyConstants::READER_OPTIONS_ANY());
AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIDestinationUIDPropertyKeyPath());
AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIRelationUIDPropertyKeyPath());
AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIRuleIDPropertyKeyPath());
AddPropertyPersistence(mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath("","").AddAnyElement());
/*
There IS an option to exchange ALL vtkTexture instances against vtkNeverTranslucentTextureFactory.
This code is left here as a reminder, just in case we might need to do that some time.
vtkNeverTranslucentTextureFactory* textureFactory = vtkNeverTranslucentTextureFactory::New();
vtkObjectFactory::RegisterFactory( textureFactory );
textureFactory->Delete();
*/
this->RegisterLegacyWriter();
}
void MitkCoreActivator::Unload(us::ModuleContext *)
{
for (auto &elem : m_FileReaders)
{
delete elem;
}
for (auto &elem : m_FileWriters)
{
delete elem;
}
for (auto &elem : m_FileIOs)
{
delete elem;
}
for (auto &elem : m_LegacyWriters)
{
delete elem;
}
// The mitk::ModuleContext* argument of the Unload() method
// will always be 0 for the Mitk library. It makes no sense
// to use it at this stage anyway, since all libraries which
// know about the module system have already been unloaded.
// we need to close the internal service tracker of the
// MimeTypeProvider class here. Otherwise it
// would hold on to the ModuleContext longer than it is
// actually valid.
m_MimeTypeProviderReg.Unregister();
m_MimeTypeProvider->Stop();
for (std::vector<mitk::CustomMimeType *>::const_iterator mimeTypeIter = m_DefaultMimeTypes.begin(),
iterEnd = m_DefaultMimeTypes.end();
mimeTypeIter != iterEnd;
++mimeTypeIter)
{
delete *mimeTypeIter;
}
}
void MitkCoreActivator::RegisterDefaultMimeTypes()
{
// Register some default mime-types
std::vector<mitk::CustomMimeType *> mimeTypes = mitk::IOMimeTypes::Get();
for (std::vector<mitk::CustomMimeType *>::const_iterator mimeTypeIter = mimeTypes.begin(), iterEnd = mimeTypes.end();
mimeTypeIter != iterEnd;
++mimeTypeIter)
{
m_DefaultMimeTypes.push_back(*mimeTypeIter);
m_Context->RegisterService(m_DefaultMimeTypes.back());
}
}
void MitkCoreActivator::RegisterItkReaderWriter()
{
std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase");
for (auto &allobject : allobjects)
{
auto *io = dynamic_cast<itk::ImageIOBase *>(allobject.GetPointer());
// NiftiImageIO does not provide a correct "SupportsDimension()" methods
// and the supported read/write extensions are not ordered correctly
if (dynamic_cast<itk::NiftiImageIO *>(io))
continue;
// Use a custom mime-type for GDCMImageIO below
if (dynamic_cast<itk::GDCMImageIO *>(allobject.GetPointer()))
{
// MITK provides its own DICOM reader (which internally uses GDCMImageIO).
continue;
}
if (io)
{
m_FileIOs.push_back(new mitk::ItkImageIO(io));
}
else
{
MITK_WARN << "Error ImageIO factory did not return an ImageIOBase: " << (allobject)->GetNameOfClass();
}
}
FixedNiftiImageIO::Pointer itkNiftiIO = FixedNiftiImageIO::New();
mitk::ItkImageIO *niftiIO = new mitk::ItkImageIO(mitk::IOMimeTypes::NIFTI_MIMETYPE(), itkNiftiIO.GetPointer(), 0);
m_FileIOs.push_back(niftiIO);
}
void MitkCoreActivator::RegisterVtkReaderWriter()
{
m_FileIOs.push_back(new mitk::SurfaceVtkXmlIO());
m_FileIOs.push_back(new mitk::SurfaceStlIO());
m_FileIOs.push_back(new mitk::SurfaceVtkLegacyIO());
m_FileIOs.push_back(new mitk::ImageVtkXmlIO());
m_FileIOs.push_back(new mitk::ImageVtkLegacyIO());
}
void MitkCoreActivator::RegisterLegacyWriter()
{
std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("IOWriter");
for (auto i = allobjects.begin(); i != allobjects.end(); ++i)
{
mitk::FileWriter::Pointer io = dynamic_cast<mitk::FileWriter *>(i->GetPointer());
if (io)
{
std::string description = std::string("Legacy ") + io->GetNameOfClass() + " Writer";
mitk::IFileWriter *writer = new mitk::LegacyFileWriterService(io, description);
m_LegacyWriters.push_back(writer);
}
else
{
MITK_ERROR << "Error IOWriter override is not of type mitk::FileWriter: " << (*i)->GetNameOfClass() << std::endl;
}
}
}
US_EXPORT_MODULE_ACTIVATOR(mitkCore, MitkCoreActivator)
// Call CppMicroservices initialization code at the end of the file.
// This especially ensures that VTK object factories have already
// been registered (VTK initialization code is injected by implicitly
// include VTK header files at the top of this file).
US_INITIALIZE_MODULE("Port of Core module from MITK", "CTKmitkCore")
| 33.379781 | 120 | 0.733077 | [
"object",
"vector"
] |
f571e5c1e9a0caacba13e421def1c6841e6bc440 | 7,397 | cpp | C++ | act_map/tests/test_act_map.cpp | debugCVML/rpg_information_field | 56f9ffba83aaee796502116e1cf651c5bc405bf6 | [
"MIT"
] | 149 | 2020-06-23T12:08:47.000Z | 2022-03-31T08:18:52.000Z | act_map/tests/test_act_map.cpp | debugCVML/rpg_information_field | 56f9ffba83aaee796502116e1cf651c5bc405bf6 | [
"MIT"
] | 4 | 2020-08-28T07:51:15.000Z | 2021-04-09T13:18:49.000Z | act_map/tests/test_act_map.cpp | debugCVML/rpg_information_field | 56f9ffba83aaee796502116e1cf651c5bc405bf6 | [
"MIT"
] | 34 | 2020-06-26T14:50:34.000Z | 2022-03-04T06:45:55.000Z | #include "act_map/act_map.h"
#include <rpg_common/test_main.h>
#include <rpg_common/fs.h>
#include <vi_utils/map.h>
#include <vi_utils/states.h>
#include <vi_utils/cam_min.h>
using namespace act_map;
template <typename T>
class ActMapTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
std::string dir;
std::string fn;
rpg::fs::splitPathAndFilename(__FILE__, &dir, &fn);
abs_map_ = dir + "/test_data/test_map_100.txt";
abs_traj_ = dir + "/test_data/test_traj.csv";
std::string vis_dir = dir + "/test_data/fov45_fs30_lm1000_k10_fast";
setGPVisiblityFromFolder(vis_dir);
map_.reset(new vi::Map());
map_->load(abs_map_, std::string());
vi::States::load(abs_traj_, &states_, ',', true);
ranges_ = std::vector<double>{ -this->xrange_ / 2, this->xrange_ / 2,
-this->yrange_ / 2, this->yrange_ / 2,
-this->zrange_ / 2, this->zrange_ / 2 };
options_.pos_factor_layer_options_.vox_size = 0.3;
options_.occ_layer_options_.vox_size = 0.01;
options_.vis_options_.resize(1);
setQuadPolyVisiblity(options_.vis_options_[0]);
}
std::string abs_map_;
std::string abs_traj_;
vi::MapPtr map_;
vi::StatesVec states_;
double xrange_ = 1.0;
double yrange_ = 1.0;
double zrange_ = 1.0;
std::vector<double> ranges_;
ActMapOptions options_;
};
using PosFactorVoxelTypes =
::testing::Types<QuadInfoVoxel, QuadTraceVoxel, GPInfoVoxel, GPTraceVoxel,
QuadPolyInfoVoxel, QuadPolyTraceVoxel>;
TYPED_TEST_CASE(ActMapTest, PosFactorVoxelTypes);
TYPED_TEST(ActMapTest, testInitPrint)
{
ActMap<TypeParam> am(this->options_);
std::cout << am;
}
TYPED_TEST(ActMapTest, testOccupancyIntegrate)
{
ActMap<TypeParam> am(this->options_);
EXPECT_EQ(0u, am.occLayerCRef().getNumberOfAllocatedBlocks());
std::cout << "Occ Memory at the beginning: "
<< am.occLayerCRef().getMemorySize() << std::endl;
rpg::Pose cam_pose;
cam_pose.setIdentity(); // at origin
am.integratePointCloudOccupancy(cam_pose, this->map_->points_);
EXPECT_EQ(0, am.getLastAddedOccPoints().size());
EXPECT_EQ(0, am.getLastDeletedOccPoints().size());
for (int i = 0; i < 10; i++)
{
am.integratePointCloudOccupancy(cam_pose, this->map_->points_);
if (am.getLastAddedOccPoints().size() > 0)
{
break;
}
}
size_t n_pts = 0;
for (const auto& pair : am.getLastAddedOccPoints())
{
n_pts += pair.second.size();
}
EXPECT_EQ(this->map_->points_.cols(), n_pts);
EXPECT_EQ(0, am.getLastDeletedOccPoints().size());
EXPECT_GT(am.occLayerCRef().getNumberOfAllocatedBlocks(), 0u);
std::cout << "Occ Memory after integration (KB): "
<< am.occLayerCRef().getMemorySize() << std::endl;
std::cout << "Number of occ blocks after integration: "
<< am.occLayerCRef().getNumberOfAllocatedBlocks() << std::endl;
}
TYPED_TEST(ActMapTest, testAllocationKernelLayer)
{
ActMap<TypeParam> am(this->options_);
EXPECT_EQ(0, am.kerLayerCRef().getNumberOfAllocatedBlocks());
am.allocateFactorLayerUniform(this->ranges_);
EXPECT_GT(am.kerLayerCRef().getNumberOfAllocatedBlocks(), 0);
am.kerLayerPtr()->removeAllBlocks();
EXPECT_EQ(0, am.kerLayerCRef().getNumberOfAllocatedBlocks());
std::vector<double> ranges2{ this->xrange_, this->yrange_, this->zrange_ };
am.allocateFactorLayerUniform(ranges2);
EXPECT_GT(am.kerLayerCRef().getNumberOfAllocatedBlocks(), 0);
}
TYPED_TEST(ActMapTest, testKernelIntegrationBatch)
{
ActMap<TypeParam> am(this->options_);
// set occupancy
EXPECT_EQ(0, am.numOccupiedVoxels());
am.setOccupancyWorldPoints(this->map_->points_);
EXPECT_EQ(this->map_->n_points_, am.numOccupiedVoxels());
// allocate
EXPECT_DOUBLE_EQ(0.0, am.accumulatedUpdatedBlkRatioFactorLayer());
std::vector<double> ranges{ this->xrange_, this->yrange_, this->zrange_ };
am.allocateFactorLayerUniform(ranges);
EXPECT_DOUBLE_EQ(0.0, am.updatedBlkRatioFactorLayer());
EXPECT_DOUBLE_EQ(0.0, am.accumulatedUpdatedBlkRatioFactorLayer());
voxblox::BlockIndexList updated_blk_idxs;
const voxblox::Layer<TypeParam>& tl = am.kerLayerCRef();
tl.getAllUpdatedBlocks(&updated_blk_idxs);
EXPECT_TRUE(updated_blk_idxs.empty());
am.recomputeFactorLayer();
tl.getAllUpdatedBlocks(&updated_blk_idxs);
EXPECT_FALSE(updated_blk_idxs.empty());
EXPECT_EQ(tl.getNumberOfAllocatedBlocks(), updated_blk_idxs.size());
EXPECT_DOUBLE_EQ(1.0, am.updatedBlkRatioFactorLayer());
EXPECT_DOUBLE_EQ(1.0, am.accumulatedUpdatedBlkRatioFactorLayer());
const voxblox::BlockIndexList& last_updated_kblk_idxs =
am.getAccumulatedUpdatedFactorBlocksIndices();
EXPECT_EQ(utils::getNumOfUpdatedBlocks(tl), last_updated_kblk_idxs.size());
}
TYPED_TEST(ActMapTest, testKernelUpdateIncremental)
{
ActMap<TypeParam> am_batch(this->options_);
ActMap<TypeParam> am_inc(this->options_);
std::vector<double> ranges{ this->xrange_, this->yrange_, this->zrange_ };
am_batch.allocateFactorLayerUniform(ranges);
am_inc.allocateFactorLayerUniform(ranges);
EXPECT_TRUE(voxblox::utils::isSameLayer(am_batch.kerLayerCRef(),
am_inc.kerLayerCRef()));
// batch
utils::setPointsInOccupancyLayer(this->map_->points_,
am_batch.occLayerPtr().get());
am_batch.recomputeFactorLayer();
// incremental
rpg::Pose cam_pose;
cam_pose.setIdentity(); // at origin
for (size_t i = 0; i < 10; i++)
{
am_inc.integratePointCloudOccupancy(cam_pose, this->map_->points_);
am_inc.updateFactorLayerIncremental();
}
//
EXPECT_TRUE(voxblox::utils::isSameLayer(am_batch.occLayerCRef(),
am_inc.occLayerCRef()));
EXPECT_TRUE(voxblox::utils::isSameLayer(am_batch.kerLayerCRef(),
am_inc.kerLayerCRef()));
}
TYPED_TEST(ActMapTest, testAddLocationInterface)
{
ActMap<TypeParam> am(this->options_);
utils::setPointsInOccupancyLayer(this->map_->points_, am.occLayerPtr().get());
rpg::Pose Twb;
Twb.setIdentity();
const std::vector<double> ranges{ 1, 1, 1 };
am.addRegionToFactorLayer(Twb, ranges);
EXPECT_GT(am.getNewlyAllocatedFactorBlockIndices().size(), 0);
am.updateFactorLayerIncremental();
EXPECT_EQ(am.getNewlyAllocatedFactorBlockIndices().size(), 0);
}
TYPED_TEST(ActMapTest, testGetInfoMetric)
{
ActMap<TypeParam> am(this->options_);
Eigen::Matrix3Xd views;
views.resize(Eigen::NoChange, 0);
am.setOccupancyWorldPoints(this->map_->points_, views);
am.allocateFactorLayerUniform(this->ranges_);
am.recomputeFactorLayer();
am.prepareInfoFromPointCloud();
rpg::Pose Twc;
Twc.setIdentity();
InfoMetricType info_t = InfoMetricType::kTrace;
double val_ker;
Eigen::Vector3d dpos_ker, drot_g_ker;
am.getInfoMetricAt(Twc, info_t, &val_ker, &dpos_ker, &drot_g_ker);
double val_pc;
Eigen::Vector3d dpos_pc, drot_g_pc;
am.getInfoMetricFromPC(Twc, info_t, &val_pc, &dpos_pc, &drot_g_pc);
std::cout << "Kernel vs. pc:" << std::endl;
std::cout << "- " << val_ker << " <-> " << val_pc << std::endl;
std::cout << "- " << dpos_ker.transpose() << " <-> " << dpos_pc.transpose()
<< std::endl;
std::cout << "- " << drot_g_ker.transpose() << " <-> "
<< drot_g_pc.transpose() << std::endl;
}
RPG_COMMON_TEST_MAIN
{
}
| 32.16087 | 80 | 0.69366 | [
"vector"
] |
f577eb6744c08b05a458757430cbadae8880d27e | 4,319 | hpp | C++ | bindings/python/crocoddyl/core/activations/quadratic-barrier.hpp | jcarpent/crocoddyl | 155999999f1fbd0c5760875584c540e2bc13645b | [
"BSD-3-Clause"
] | 1 | 2019-12-21T12:11:15.000Z | 2019-12-21T12:11:15.000Z | bindings/python/crocoddyl/core/activations/quadratic-barrier.hpp | boyali/crocoddyl | 155999999f1fbd0c5760875584c540e2bc13645b | [
"BSD-3-Clause"
] | null | null | null | bindings/python/crocoddyl/core/activations/quadratic-barrier.hpp | boyali/crocoddyl | 155999999f1fbd0c5760875584c540e2bc13645b | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2018-2019, LAAS-CNRS
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef BINDINGS_PYTHON_CROCODDYL_CORE_ACTIVATIONS_QUADRATIC_BARRIER_HPP_
#define BINDINGS_PYTHON_CROCODDYL_CORE_ACTIVATIONS_QUADRATIC_BARRIER_HPP_
#include "crocoddyl/core/activations/quadratic-barrier.hpp"
namespace crocoddyl {
namespace python {
namespace bp = boost::python;
void exposeActivationQuadraticBarrier() {
bp::class_<ActivationBounds>(
"ActivationBounds",
"Activation bounds.\n\n"
"The activation bounds describes the lower and upper vector plus it activation range\n"
"(between 0 and 1), its default value is 1.",
bp::init<Eigen::VectorXd, Eigen::VectorXd, double>(bp::args(" self", " lb", " ub", " beta=1."),
"Initialize the activation model.\n\n"
":param lb: lower bounds\n"
":param ub: upper bounds\n"
":param beta: range of activation (between 0 to 1)"))
.add_property("lb", bp::make_getter(&ActivationBounds::lb, bp::return_value_policy<bp::return_by_value>()),
"lower bounds")
.add_property("ub", bp::make_getter(&ActivationBounds::ub, bp::return_value_policy<bp::return_by_value>()),
"upper bounds")
.add_property("beta", &ActivationBounds::beta, "beta");
bp::class_<ActivationModelQuadraticBarrier, bp::bases<ActivationModelAbstract> >(
"ActivationModelQuadraticBarrier",
"Inequality activation model.\n\n"
"The activation is zero when r is between the lower (lb) and upper (ub) bounds, beta\n"
"determines how much of the total range is not activated (default 0.9). This is the\n"
"activation equations:\n"
"a(r) = 0.5 * ||r||^2 for lb < r < ub\n"
"a(r) = 0. for lb >= r >= ub.",
bp::init<ActivationBounds>(bp::args(" self", " bounds"),
"Initialize the activation model.\n\n"
":param bounds: activation bounds\n"
":param ub: upper bounds\n"
":param beta: range of activation (between 0 to 1)"))
.def("calc", &ActivationModelQuadraticBarrier::calc_wrap, bp::args(" self", " data", " r"),
"Compute the inequality activation.\n\n"
":param data: activation data\n"
":param r: residual vector")
.def<void (ActivationModelQuadraticBarrier::*)(const boost::shared_ptr<ActivationDataAbstract>&,
const Eigen::VectorXd&, const bool&)>(
"calcDiff", &ActivationModelQuadraticBarrier::calcDiff_wrap,
bp::args(" self", " data", " r", " recalc=True"),
"Compute the derivatives of inequality activation.\n\n"
":param data: activation data\n"
"Note that the Hessian is constant, so we don't write again this value.\n"
":param r: residual vector \n"
":param recalc: If true, it updates the residual value.")
.def<void (ActivationModelQuadraticBarrier::*)(const boost::shared_ptr<ActivationDataAbstract>&,
const Eigen::VectorXd&)>(
"calcDiff", &ActivationModelQuadraticBarrier::calcDiff_wrap, bp::args(" self", " data", " r"))
.def("createData", &ActivationModelQuadraticBarrier::createData, bp::args(" self"),
"Create the weighted quadratic action data.")
.add_property("bounds",
bp::make_function(&ActivationModelQuadraticBarrier::get_bounds,
bp::return_value_policy<bp::return_by_value>()),
bp::make_function(&ActivationModelQuadraticBarrier::set_bounds),
"bounds (beta, lower and upper bounds)");
}
} // namespace python
} // namespace crocoddyl
#endif // BINDINGS_PYTHON_CROCODDYL_CORE_ACTIVATIONS_QUADRATIC_BARRIER_HPP_
| 55.371795 | 113 | 0.573744 | [
"vector",
"model"
] |
f57abcec27ee1954573933c48ee819a9db41e080 | 33,973 | hpp | C++ | fem/tmop.hpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | fem/tmop.hpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | fem/tmop.hpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_TMOP_HPP
#define MFEM_TMOP_HPP
#include "../linalg/invariants.hpp"
#include "nonlininteg.hpp"
namespace mfem
{
/** @brief Abstract class for local mesh quality metrics in the target-matrix
optimization paradigm (TMOP) by P. Knupp et al. */
class TMOP_QualityMetric : public HyperelasticModel
{
protected:
const DenseMatrix *Jtr; /**< Jacobian of the reference-element to
target-element transformation. */
/** @brief The method SetTransformation() is hidden for TMOP_QualityMetric%s,
because it is not used. */
void SetTransformation(ElementTransformation &) { }
public:
TMOP_QualityMetric() : Jtr(NULL) { }
virtual ~TMOP_QualityMetric() { }
/** @brief Specify the reference-element -> target-element Jacobian matrix
for the point of interest.
The specified Jacobian matrix, #Jtr, can be used by metrics that cannot
be written just as a function of the target->physical Jacobian matrix,
Jpt. */
void SetTargetJacobian(const DenseMatrix &_Jtr) { Jtr = &_Jtr; }
/** @brief Evaluate the strain energy density function, W = W(Jpt).
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix. */
virtual double EvalW(const DenseMatrix &Jpt) const = 0;
/** @brief Evaluate the 1st Piola-Kirchhoff stress tensor, P = P(Jpt).
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix.
@param[out] P The evaluated 1st Piola-Kirchhoff stress tensor. */
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const = 0;
/** @brief Evaluate the derivative of the 1st Piola-Kirchhoff stress tensor
and assemble its contribution to the local gradient matrix 'A'.
@param[in] Jpt Represents the target->physical transformation
Jacobian matrix.
@param[in] DS Gradient of the basis matrix (dof x dim).
@param[in] weight Quadrature weight coefficient for the point.
@param[in,out] A Local gradient matrix where the contribution from this
point will be added.
Computes weight * d(dW_dxi)_d(xj) at the current point, for all i and j,
where x1 ... xn are the FE dofs. This function is usually defined using
the matrix invariants and their derivatives.
*/
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const = 0;
};
/// Metric without a type, 2D
class TMOP_Metric_001 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = |J|^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Skew metric, 2D.
class TMOP_Metric_skew2D : public TMOP_QualityMetric
{
public:
// W = 0.5 (1 - cos(angle_Jpr - angle_Jtr)).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const
{ MFEM_ABORT("Not implemented"); }
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const
{ MFEM_ABORT("Not implemented"); }
};
/// Skew metric, 3D.
class TMOP_Metric_skew3D : public TMOP_QualityMetric
{
public:
// W = 1/6 (3 - sum_i cos(angle_Jpr_i - angle_Jtr_i)), i = 1..3.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const
{ MFEM_ABORT("Not implemented"); }
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const
{ MFEM_ABORT("Not implemented"); }
};
/// Aspect ratio metric, 2D.
class TMOP_Metric_aspratio2D : public TMOP_QualityMetric
{
public:
// W = 0.5 (ar_Jpr/ar_Jtr + ar_Jtr/ar_Jpr) - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const
{ MFEM_ABORT("Not implemented"); }
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const
{ MFEM_ABORT("Not implemented"); }
};
/// Aspect ratio metric, 3D.
class TMOP_Metric_aspratio3D : public TMOP_QualityMetric
{
public:
// W = 1/3 sum [0.5 (ar_Jpr_i/ar_Jtr_i + ar_Jtr_i/ar_Jpr_i) - 1], i = 1..3.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const
{ MFEM_ABORT("Not implemented"); }
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const
{ MFEM_ABORT("Not implemented"); }
};
/// Shape+Size+Orientation metric, 2D.
class TMOP_Metric_SSA2D : public TMOP_QualityMetric
{
public:
// W = 0.5 (1 - cos(theta_Jpr - theta_Jtr)).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const
{ MFEM_ABORT("Not implemented"); }
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const
{ MFEM_ABORT("Not implemented"); }
};
/// Shape+Size metric, 2D.
class TMOP_Metric_SS2D : public TMOP_QualityMetric
{
public:
// W = 0.5 (1 - cos(theta_Jpr - theta_Jtr)).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const
{ MFEM_ABORT("Not implemented"); }
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const
{ MFEM_ABORT("Not implemented"); }
};
/// Shape, ideal barrier metric, 2D
class TMOP_Metric_002 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = 0.5|J|^2 / det(J) - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape & area, ideal barrier metric, 2D
class TMOP_Metric_007 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = |J - J^-t|^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape & area metric, 2D
class TMOP_Metric_009 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = det(J) * |J - J^-t|^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shifted barrier form of metric 2 (shape, ideal barrier metric), 2D
class TMOP_Metric_022 : public TMOP_QualityMetric
{
protected:
double &tau0;
mutable InvariantsEvaluator2D<double> ie;
public:
TMOP_Metric_022(double &t0): tau0(t0) {}
// W = 0.5(|J|^2 - 2det(J)) / (det(J) - tau0).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape, ideal barrier metric, 2D
class TMOP_Metric_050 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = 0.5|J^t J|^2 / det(J)^2 - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Area metric, 2D
class TMOP_Metric_055 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = (det(J) - 1)^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Area, ideal barrier metric, 2D
class TMOP_Metric_056 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = 0.5( sqrt(det(J)) - 1 / sqrt(det(J)) )^2
// = 0.5( det(J) - 1 )^2 / det(J)
// = 0.5( det(J) + 1/det(J) ) - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape, ideal barrier metric, 2D
class TMOP_Metric_058 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = |J^t J|^2 / det(J)^2 - 2|J|^2 / det(J) + 2
// = I1b (I1b - 2).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Area, ideal barrier metric, 2D
class TMOP_Metric_077 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator2D<double> ie;
public:
// W = 0.5(det(J) - 1 / det(J))^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Untangling metric, 2D
class TMOP_Metric_211 : public TMOP_QualityMetric
{
protected:
const double eps;
mutable InvariantsEvaluator2D<double> ie;
public:
TMOP_Metric_211(double epsilon = 1e-4) : eps(epsilon) { }
// W = (det(J) - 1)^2 - det(J) + sqrt(det(J)^2 + eps).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shifted barrier form of metric 56 (area, ideal barrier metric), 2D
class TMOP_Metric_252 : public TMOP_QualityMetric
{
protected:
double &tau0;
mutable InvariantsEvaluator2D<double> ie;
public:
/// Note that @a t0 is stored by reference
TMOP_Metric_252(double &t0): tau0(t0) {}
// W = 0.5(det(J) - 1)^2 / (det(J) - tau0).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape, ideal barrier metric, 3D
class TMOP_Metric_301 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator3D<double> ie;
public:
// W = |J| |J^-1| / 3 - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape, ideal barrier metric, 3D
class TMOP_Metric_302 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator3D<double> ie;
public:
// W = |J|^2 |J^-1|^2 / 9 - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape, ideal barrier metric, 3D
class TMOP_Metric_303 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator3D<double> ie;
public:
// W = |J|^2 / 3 * det(J)^(2/3) - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Volume metric, 3D
class TMOP_Metric_315 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator3D<double> ie;
public:
// W = (det(J) - 1)^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Volume, ideal barrier metric, 3D
class TMOP_Metric_316 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator3D<double> ie;
public:
// W = 0.5( sqrt(det(J)) - 1 / sqrt(det(J)) )^2
// = 0.5( det(J) - 1 )^2 / det(J)
// = 0.5( det(J) + 1/det(J) ) - 1.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shape & volume, ideal barrier metric, 3D
class TMOP_Metric_321 : public TMOP_QualityMetric
{
protected:
mutable InvariantsEvaluator3D<double> ie;
public:
// W = |J - J^-t|^2.
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Shifted barrier form of 3D metric 16 (volume, ideal barrier metric), 3D
class TMOP_Metric_352 : public TMOP_QualityMetric
{
protected:
double &tau0;
mutable InvariantsEvaluator3D<double> ie;
public:
TMOP_Metric_352(double &t0): tau0(t0) {}
// W = 0.5(det(J) - 1)^2 / (det(J) - tau0).
virtual double EvalW(const DenseMatrix &Jpt) const;
virtual void EvalP(const DenseMatrix &Jpt, DenseMatrix &P) const;
virtual void AssembleH(const DenseMatrix &Jpt, const DenseMatrix &DS,
const double weight, DenseMatrix &A) const;
};
/// Base class for limiting functions to be used in class TMOP_Integrator.
/** This class represents a scalar function f(x, x0, d), where x and x0 are
positions in physical space, and d is a reference physical distance
associated with the point x0. */
class TMOP_LimiterFunction
{
public:
/// Returns the limiting function, f(x, x0, d).
virtual double Eval(const Vector &x, const Vector &x0, double d) const = 0;
/** @brief Returns the gradient of the limiting function f(x, x0, d) with
respect to x. */
virtual void Eval_d1(const Vector &x, const Vector &x0, double dist,
Vector &d1) const = 0;
/** @brief Returns the Hessian of the limiting function f(x, x0, d) with
respect to x. */
virtual void Eval_d2(const Vector &x, const Vector &x0, double dist,
DenseMatrix &d2) const = 0;
/// Virtual destructor.
virtual ~TMOP_LimiterFunction() { }
};
/// Default limiter function in TMOP_Integrator.
class TMOP_QuadraticLimiter : public TMOP_LimiterFunction
{
public:
virtual double Eval(const Vector &x, const Vector &x0, double dist) const
{
MFEM_ASSERT(x.Size() == x0.Size(), "Bad input.");
return 0.5 * x.DistanceSquaredTo(x0) / (dist * dist);
}
virtual void Eval_d1(const Vector &x, const Vector &x0, double dist,
Vector &d1) const
{
MFEM_ASSERT(x.Size() == x0.Size(), "Bad input.");
d1.SetSize(x.Size());
subtract(1.0 / (dist * dist), x, x0, d1);
}
virtual void Eval_d2(const Vector &x, const Vector &x0, double dist,
DenseMatrix &d2) const
{
MFEM_ASSERT(x.Size() == x0.Size(), "Bad input.");
d2.Diag(1.0 / (dist * dist), x.Size());
}
virtual ~TMOP_QuadraticLimiter() { }
};
class FiniteElementCollection;
class FiniteElementSpace;
class ParFiniteElementSpace;
class AdaptivityEvaluator
{
protected:
// Owned.
Mesh *mesh;
FiniteElementSpace *fes;
#ifdef MFEM_USE_MPI
// Owned.
ParMesh *pmesh;
ParFiniteElementSpace *pfes;
#endif
public:
AdaptivityEvaluator() : mesh(NULL), fes(NULL)
{
#ifdef MFEM_USE_MPI
pmesh = NULL;
pfes = NULL;
#endif
}
virtual ~AdaptivityEvaluator();
/** Specifies the Mesh and FiniteElementCollection of the solution that will
be evaluated. The given mesh will be copied into the internal object. */
void SetSerialMetaInfo(const Mesh &m,
const FiniteElementCollection &fec, int num_comp);
#ifdef MFEM_USE_MPI
/// Parallel version of SetSerialMetaInfo.
void SetParMetaInfo(const ParMesh &m,
const FiniteElementCollection &fec, int num_comp);
#endif
// TODO use GridFunctions to make clear it's on the ldofs?
virtual void SetInitialField(const Vector &init_nodes,
const Vector &init_field) = 0;
virtual void ComputeAtNewPosition(const Vector &new_nodes,
Vector &new_field) = 0;
};
/** @brief Base class representing target-matrix construction algorithms for
mesh optimization via the target-matrix optimization paradigm (TMOP). */
/** This class is used by class TMOP_Integrator to construct the target Jacobian
matrices (reference-element to target-element) at quadrature points. It
supports a set of algorithms chosen by the #TargetType enumeration.
New target-matrix construction algorithms can be defined by deriving new
classes and overriding the method ComputeElementTargets(). */
class TargetConstructor
{
public:
/// Target-matrix construction algorithms supported by this class.
enum TargetType
{
IDEAL_SHAPE_UNIT_SIZE, /**<
Ideal shape, unit size; the nodes are not used. */
IDEAL_SHAPE_EQUAL_SIZE, /**<
Ideal shape, equal size/volume; the given nodes define the total target
volume; for each mesh element, the target volume is the average volume
multiplied by the volume scale, set with SetVolumeScale(). */
IDEAL_SHAPE_GIVEN_SIZE, /**<
Ideal shape, given size/volume; the given nodes define the target
volume at all quadrature points. */
GIVEN_SHAPE_AND_SIZE, /**<
Given shape, given size/volume; the given nodes define the exact target
Jacobian matrix at all quadrature points. */
GIVEN_FULL /**<
Full target tensor is specified at every quadrature point. */
};
protected:
// Nodes that are used in ComputeElementTargets(), depending on target_type.
const GridFunction *nodes; // not owned
mutable double avg_volume;
double volume_scale;
const TargetType target_type;
#ifdef MFEM_USE_MPI
MPI_Comm comm;
bool Parallel() const { return (comm != MPI_COMM_NULL); }
#else
bool Parallel() const { return false; }
#endif
// should be called only if avg_volume == 0.0, i.e. avg_volume is not
// computed yet
void ComputeAvgVolume() const;
public:
/// Constructor for use in serial
TargetConstructor(TargetType ttype)
: nodes(NULL), avg_volume(), volume_scale(1.0), target_type(ttype)
{
#ifdef MFEM_USE_MPI
comm = MPI_COMM_NULL;
#endif
}
#ifdef MFEM_USE_MPI
/// Constructor for use in parallel
TargetConstructor(TargetType ttype, MPI_Comm mpicomm)
: nodes(NULL), avg_volume(), volume_scale(1.0), target_type(ttype),
comm(mpicomm) { }
#endif
virtual ~TargetConstructor() { }
/** @brief Set the nodes to be used in the target-matrix construction.
This method should be called every time the target nodes are updated
externally and recomputation of the target average volume is needed. The
nodes are used by all target types except IDEAL_SHAPE_UNIT_SIZE. */
void SetNodes(const GridFunction &n) { nodes = &n; avg_volume = 0.0; }
/// Used by target type IDEAL_SHAPE_EQUAL_SIZE. The default volume scale is 1.
void SetVolumeScale(double vol_scale) { volume_scale = vol_scale; }
/** @brief Given an element and quadrature rule, computes ref->target
transformation Jacobians for each quadrature point in the element.
The physical positions of the element's nodes are given by @a elfun. */
virtual void ComputeElementTargets(int e_id, const FiniteElement &fe,
const IntegrationRule &ir,
const Vector &elfun,
DenseTensor &Jtr) const;
};
class AnalyticAdaptTC : public TargetConstructor
{
protected:
// Analytic target specification.
Coefficient *scalar_tspec;
VectorCoefficient *vector_tspec;
MatrixCoefficient *matrix_tspec;
public:
AnalyticAdaptTC(TargetType ttype)
: TargetConstructor(ttype),
scalar_tspec(NULL), vector_tspec(NULL), matrix_tspec(NULL) { }
virtual void SetAnalyticTargetSpec(Coefficient *sspec,
VectorCoefficient *vspec,
MatrixCoefficient *mspec);
/** @brief Given an element and quadrature rule, computes ref->target
transformation Jacobians for each quadrature point in the element.
The physical positions of the element's nodes are given by @a elfun. */
virtual void ComputeElementTargets(int e_id, const FiniteElement &fe,
const IntegrationRule &ir,
const Vector &elfun,
DenseTensor &Jtr) const;
};
#ifdef MFEM_USE_MPI
class ParGridFunction;
#endif
class DiscreteAdaptTC : public TargetConstructor
{
protected:
// Discrete target specification.
// Data is owned, updated by UpdateTargetSpecification.
Vector tspec; //eta(x)
Vector tspec_sav;
Vector tspec_perth; //eta(x+h)
Vector tspec_pert2h; //eta(x+2*h)
Vector tspec_pertmix; //eta(x+h,y+h)
// Note: do not use the Nodes of this space as they may not be on the
// positions corresponding to the values of tspec.
const FiniteElementSpace *tspec_fes;
// Evaluation of the discrete target specification on different meshes.
// Owned.
AdaptivityEvaluator *adapt_eval;
public:
DiscreteAdaptTC(TargetType ttype)
: TargetConstructor(ttype),
tspec(), tspec_fes(NULL), adapt_eval(NULL) { }
virtual ~DiscreteAdaptTC() { delete adapt_eval; }
virtual void SetSerialDiscreteTargetSpec(GridFunction &tspec_);
#ifdef MFEM_USE_MPI
virtual void SetParDiscreteTargetSpec(ParGridFunction &tspec_);
#endif
/** Used to update the target specification after the mesh has changed. The
new mesh positions are given by new_x. */
void UpdateTargetSpecification(const Vector &new_x);
void UpdateTargetSpecification(Vector &new_x, Vector &IntData);
void UpdateTargetSpecificationAtNode(const FiniteElement &el,
ElementTransformation &T,
int nodenum, int idir,
const Vector &IntData);
void RestoreTargetSpecificationAtNode(ElementTransformation &T, int nodenum);
/** Used for finite-difference based computations. Computes the target
specifications after a mesh perturbation in x or y direction. */
void UpdateGradientTargetSpecification(const Vector &x, const double dx);
/** Used for finite-difference based computations. Computes the target
specifications after two mesh perturbations in x and/or y direction. */
void UpdateHessianTargetSpecification(const Vector &x, const double dx);
void SetAdaptivityEvaluator(AdaptivityEvaluator *ae)
{
if (adapt_eval) { delete adapt_eval; }
adapt_eval = ae;
}
const Vector &GetTspecPert1H() { return tspec_perth; }
const Vector &GetTspecPert2H() { return tspec_pert2h; }
const Vector &GetTspecPertMixH() { return tspec_pertmix; }
/** @brief Given an element and quadrature rule, computes ref->target
transformation Jacobians for each quadrature point in the element.
The physical positions of the element's nodes are given by @a elfun.
Note that this function assumes that UpdateTargetSpecification() has
been called with the position vector corresponding to @a elfun. */
virtual void ComputeElementTargets(int e_id, const FiniteElement &fe,
const IntegrationRule &ir,
const Vector &elfun,
DenseTensor &Jtr) const;
};
class TMOPNewtonSolver;
class TMOPDescentNewtonSolver;
/** @brief A TMOP integrator class based on any given TMOP_QualityMetric and
TargetConstructor.
Represents @f$ \int W(Jpt) dx @f$ over a target zone, where W is the
metric's strain energy density function, and Jpt is the Jacobian of the
target->physical coordinates transformation. The virtual target zone is
defined by the TargetConstructor. */
class TMOP_Integrator : public NonlinearFormIntegrator
{
protected:
friend class TMOPNewtonSolver;
friend class TMOPDescentNewtonSolver;
TMOP_QualityMetric *metric; // not owned
const TargetConstructor *targetC; // not owned
// Weight Coefficient multiplying the quality metric term.
Coefficient *coeff1; // not owned, if NULL -> coeff1 is 1.
// Normalization factor for the metric term.
double metric_normal;
// Nodes and weight Coefficient used for "limiting" the TMOP_Integrator.
// These are both NULL when there is no limiting.
// The class doesn't own nodes0 and coeff0.
const GridFunction *nodes0;
Coefficient *coeff0;
// Limiting reference distance. Not owned.
const GridFunction *lim_dist;
// Limiting function. Owned.
TMOP_LimiterFunction *lim_func;
// Normalization factor for the limiting term.
double lim_normal;
DiscreteAdaptTC *discr_tc;
// Parameters for FD-based Gradient & Hessian calculation.
bool fdflag;
double dx;
double dxscale;
Array <Vector *> ElemDer; //f'(x)
Array <Vector *> ElemPertEnergy; //f(x+h)
// Jrt: the inverse of the ref->target Jacobian, Jrt = Jtr^{-1}.
// Jpr: the ref->physical transformation Jacobian, Jpr = PMatI^t DS.
// Jpt: the target->physical transformation Jacobian, Jpt = Jpr Jrt.
// P: represents dW_d(Jtp) (dim x dim).
// DSh: gradients of reference shape functions (dof x dim).
// DS: gradients of the shape functions in the target configuration,
// DS = DSh Jrt (dof x dim).
// PMatI: current coordinates of the nodes (dof x dim).
// PMat0: reshaped view into the local element contribution to the operator
// output - the result of AssembleElementVector() (dof x dim).
DenseMatrix DSh, DS, Jrt, Jpr, Jpt, P, PMatI, PMatO;
void ComputeNormalizationEnergies(const GridFunction &x,
double &metric_energy, double &lim_energy);
void AssembleElementVectorExact(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun, Vector &elvect);
void AssembleElementGradExact(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun, DenseMatrix &elmat);
void AssembleElementVectorFD(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun, Vector &elvect);
/** Assumes that AssembleElementVectorFD has been called. */
void AssembleElementGradFD(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun, DenseMatrix &elmat);
double GetFDDerivative(const FiniteElement &el,
ElementTransformation &T,
Vector &elfun, const int nodenum,const int idir,
const double baseenergy, bool update_stored);
/** @brief Determines the perturbation, h, for FD-based approximation. */
void ComputeFDh(const Vector &x, const FiniteElementSpace &fes);
#ifdef MFEM_USE_MPI
void ComputeFDh(const Vector &x, const ParFiniteElementSpace &pfes);
#endif
void ComputeMinJac(const Vector &x, const FiniteElementSpace &fes);
public:
/** @param[in] m TMOP_QualityMetric that will be integrated (not owned).
@param[in] tc Target-matrix construction algorithm to use (not owned). */
TMOP_Integrator(TMOP_QualityMetric *m, TargetConstructor *tc)
: metric(m), targetC(tc),
coeff1(NULL), metric_normal(1.0),
nodes0(NULL), coeff0(NULL),
lim_dist(NULL), lim_func(NULL), lim_normal(1.0),
discr_tc(dynamic_cast<DiscreteAdaptTC *>(tc)),
fdflag(false), dxscale(1.0e3)
{ }
~TMOP_Integrator()
{
delete lim_func;
for (int i = 0; i < ElemDer.Size(); i++)
{
delete ElemDer[i];
delete ElemPertEnergy[i];
}
}
/// Sets a scaling Coefficient for the quality metric term of the integrator.
/** With this addition, the integrator becomes
@f$ \int w1 W(Jpt) dx @f$.
Note that the Coefficient is evaluated in the physical configuration and
not in the target configuration which may be undefined. */
void SetCoefficient(Coefficient &w1) { coeff1 = &w1; }
/// Adds a limiting term to the integrator (general version).
/** With this addition, the integrator becomes
@f$ \int w1 W(Jpt) + w0 f(x, x_0, d) dx @f$,
where the second term measures the change with respect to the original
physical positions, @a n0.
@param[in] n0 Original mesh node coordinates.
@param[in] dist Limiting physical distances.
@param[in] w0 Coefficient scaling the limiting term.
@param[in] lfunc TMOP_LimiterFunction defining the limiting term f. If
NULL, a TMOP_QuadraticLimiter will be used. The
TMOP_Integrator assumes ownership of this pointer. */
void EnableLimiting(const GridFunction &n0, const GridFunction &dist,
Coefficient &w0, TMOP_LimiterFunction *lfunc = NULL);
/** @brief Adds a limiting term to the integrator with limiting distance
function (@a dist in the general version of the method) equal to 1. */
void EnableLimiting(const GridFunction &n0,
Coefficient &w0, TMOP_LimiterFunction *lfunc = NULL);
/// Update the original/reference nodes used for limiting.
void SetLimitingNodes(const GridFunction &n0) { nodes0 = &n0; }
/** @brief Computes the integral of W(Jacobian(Trt)) over a target zone.
@param[in] el Type of FiniteElement.
@param[in] T Mesh element transformation.
@param[in] elfun Physical coordinates of the zone. */
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun);
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun, Vector &elvect);
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &T,
const Vector &elfun, DenseMatrix &elmat);
DiscreteAdaptTC *GetDiscreteAdaptTC() { return discr_tc; }
/** @brief Computes the normalization factors of the metric and limiting
integrals using the mesh position given by @a x. */
void EnableNormalization(const GridFunction &x);
#ifdef MFEM_USE_MPI
void ParEnableNormalization(const ParGridFunction &x);
#endif
/** @brief Enables FD-based approximation and computes dx. */
void EnableFiniteDifferences(const GridFunction &x);
#ifdef MFEM_USE_MPI
void EnableFiniteDifferences(const ParGridFunction &x);
#endif
void SetFDhScale(double _dxscale) { dxscale = _dxscale; }
bool GetFDFlag() const { return fdflag; }
double GetFDh() const { return dx; }
};
/// Interpolates the @a metric's values at the nodes of @a metric_gf.
/** Assumes that @a metric_gf's FiniteElementSpace is initialized. */
void InterpolateTMOP_QualityMetric(TMOP_QualityMetric &metric,
const TargetConstructor &tc,
const Mesh &mesh, GridFunction &metric_gf);
}
#endif
| 35.168737 | 81 | 0.666206 | [
"mesh",
"object",
"shape",
"vector",
"3d"
] |
f57e8a07535f11fc14fceae7c0e23521af281e30 | 3,096 | cpp | C++ | mdc/src/v20200828/model/CreateInputRTPSettings.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | mdc/src/v20200828/model/CreateInputRTPSettings.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | mdc/src/v20200828/model/CreateInputRTPSettings.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/mdc/v20200828/model/CreateInputRTPSettings.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Mdc::V20200828::Model;
using namespace std;
CreateInputRTPSettings::CreateInputRTPSettings() :
m_fECHasBeenSet(false),
m_idleTimeoutHasBeenSet(false)
{
}
CoreInternalOutcome CreateInputRTPSettings::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("FEC") && !value["FEC"].IsNull())
{
if (!value["FEC"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CreateInputRTPSettings.FEC` IsString=false incorrectly").SetRequestId(requestId));
}
m_fEC = string(value["FEC"].GetString());
m_fECHasBeenSet = true;
}
if (value.HasMember("IdleTimeout") && !value["IdleTimeout"].IsNull())
{
if (!value["IdleTimeout"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `CreateInputRTPSettings.IdleTimeout` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_idleTimeout = value["IdleTimeout"].GetInt64();
m_idleTimeoutHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void CreateInputRTPSettings::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_fECHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FEC";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_fEC.c_str(), allocator).Move(), allocator);
}
if (m_idleTimeoutHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IdleTimeout";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_idleTimeout, allocator);
}
}
string CreateInputRTPSettings::GetFEC() const
{
return m_fEC;
}
void CreateInputRTPSettings::SetFEC(const string& _fEC)
{
m_fEC = _fEC;
m_fECHasBeenSet = true;
}
bool CreateInputRTPSettings::FECHasBeenSet() const
{
return m_fECHasBeenSet;
}
int64_t CreateInputRTPSettings::GetIdleTimeout() const
{
return m_idleTimeout;
}
void CreateInputRTPSettings::SetIdleTimeout(const int64_t& _idleTimeout)
{
m_idleTimeout = _idleTimeout;
m_idleTimeoutHasBeenSet = true;
}
bool CreateInputRTPSettings::IdleTimeoutHasBeenSet() const
{
return m_idleTimeoutHasBeenSet;
}
| 27.642857 | 151 | 0.70478 | [
"model"
] |
f57ea79d2aadda0bbf95fcceb22aaf6eee058e0a | 904 | cpp | C++ | code/LeetCode_22.cpp | Aden-Q/LeetCode | 4bbf772c886f42ce3d72d01fd737929b99df3eb3 | [
"MIT"
] | 1 | 2019-09-22T03:08:14.000Z | 2019-09-22T03:08:14.000Z | code/LeetCode_22.cpp | Aden-Q/leetcode | ebd4804edd4f172b9981b22c18d9ff654cf20762 | [
"Apache-2.0"
] | null | null | null | code/LeetCode_22.cpp | Aden-Q/leetcode | ebd4804edd4f172b9981b22c18d9ff654cf20762 | [
"Apache-2.0"
] | null | null | null | // Generate Parentheses
// 这个brute force还是算了。。。
// 深搜100%
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
DFS(res, "", n, n);
return res;
}
void DFS(vector<string>& res, string out, int left, int right){
if(left>right) // string里面的左括号少于右括号,剪枝
return;
if(left == 0 && right == 0) // 都已经加入到out里
res.push_back(out);
else{
if(left>0)
DFS(res, out+'(', left-1, right);
if(right>0)
DFS(res, out+')', left, right-1);
}
}
};
int main(){
Solution test;
vector<string> res;
vector<string>::iterator iter;
res = test.generateParenthesis(3);
for(iter=res.begin();iter!=res.end();iter++)
cout << *iter << endl;
return 0;
}
| 21.52381 | 67 | 0.53208 | [
"vector"
] |
f580a3e47667a94fc5e4764bf85c6ff66d38a704 | 7,121 | hpp | C++ | ze_vi_simulation/include/ze/vi_simulation/evaluation_tools.hpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 30 | 2016-09-27T07:41:28.000Z | 2021-12-03T20:44:28.000Z | ze_vi_simulation/include/ze/vi_simulation/evaluation_tools.hpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 1 | 2018-12-18T15:53:06.000Z | 2018-12-21T03:10:06.000Z | ze_vi_simulation/include/ze/vi_simulation/evaluation_tools.hpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 12 | 2016-11-05T07:51:29.000Z | 2020-07-13T02:26:08.000Z | // Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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.
#pragma once
#include <ze/vi_simulation/imu_bias_simulator.hpp>
#include <ze/matplotlib/matplotlibcpp.hpp>
#include <ze/splines/bspline_pose_minimal.hpp>
//! A couple of useful functions to evaluation simulation results with IMUs.
namespace ze {
// -----------------------------------------------------------------------------
//! Takes the accel / gyro bias noise density in the continuous-case and
//! a constant vector valued bias otherwise.
ImuBiasSimulator::Ptr generateImuBias(real_t start,
real_t end,
const std::string& type,
Vector3 imu_acc_bias,
Vector3 imu_gyr_bias)
{
//! continuous bias model
if (type == "continuous")
{
return std::make_shared<ContinuousBiasSimulator>(
imu_acc_bias,
imu_gyr_bias,
start,
end,
100); // This is an arbitrary value.
}
//! a simple constant bias
else
{
return std::make_shared<ConstantBiasSimulator>(imu_acc_bias, imu_gyr_bias);
}
}
//-----------------------------------------------------------------------------
void plotOrientation(
const std::vector<real_t>& times,
const Eigen::Matrix<real_t, 3, Eigen::Dynamic>& points,
const std::string& label,
const Eigen::Matrix<real_t, 3, Eigen::Dynamic>* ref_points = nullptr)
{
plt::figure("orientation");
plt::subplot(3, 1, 1);
plt::title("Orientation");
plt::labelPlot(label, times, points.row(0));
if(ref_points)
{
plt::labelPlot("reference", times, ref_points->row(0));
}
plt::legend();
plt::subplot(3, 1, 2);
plt::labelPlot(label, times, points.row(1));
if(ref_points)
{
plt::labelPlot("reference", times, ref_points->row(1));
}
plt::subplot(3, 1, 3);
plt::labelPlot(label, times, points.row(2));
if(ref_points)
{
plt::labelPlot("reference", times, ref_points->row(2));
}
plt::show(false);
}
//-----------------------------------------------------------------------------
void plotOrientation(
const std::vector<real_t>& times,
const QuaternionVector& orientation,
const std::string& label,
const BSplinePoseMinimalRotationVector::Ptr reference = nullptr)
{
CHECK_EQ(times.size(), orientation.size());
Eigen::Matrix<real_t, 3, Eigen::Dynamic> points(3, orientation.size());
Eigen::Matrix<real_t, 3, Eigen::Dynamic> ref_points(3, orientation.size());
for (size_t i = 0; i < orientation.size(); ++i)
{
ze::sm::RotationVector rv(Matrix3(orientation[i].getRotationMatrix()));
points.col(i) = rv.getParameters();
// Hanlde sign flips in the rotation vector.
if (i > 0 && (points.col(i-1) - points.col(i)).norm() >
(points.col(i-1) + points.col(i)).norm())
{
points.col(i) = -points.col(i);
}
if (reference)
{
ref_points.col(i) = reference->eval(times[i]).tail<3>();
}
}
if (reference)
{
plotOrientation(times, points, label, &ref_points);
}
else
{
plotOrientation(times, points, label);
}
}
//-----------------------------------------------------------------------------
void plotOrientation(
const std::vector<real_t>& times,
const std::vector<Matrix3>& orientation,
const std::string& label,
const BSplinePoseMinimalRotationVector::Ptr& trajectory = nullptr)
{
CHECK_EQ(times.size(), orientation.size());
Eigen::Matrix<real_t, 3, Eigen::Dynamic> points(3, orientation.size());
Eigen::Matrix<real_t, 3, Eigen::Dynamic> ref_points(3, orientation.size());
for (size_t i = 0; i < orientation.size(); ++i)
{
ze::sm::RotationVector rv(orientation[i]);
points.col(i) = rv.getParameters();
if (trajectory)
{
ref_points.col(i) = trajectory->eval(times[i]).tail<3>();
}
}
if (trajectory)
{
plotOrientation(times, points, label, &ref_points);
}
else
{
plotOrientation(times, points, label);
}
}
//-----------------------------------------------------------------------------
void plotOrientationError(
const std::vector<real_t>& times,
const std::vector<Matrix3>& est,
const std::string& label,
const BSplinePoseMinimalRotationVector::Ptr trajectory)
{
CHECK_EQ(times.size(), est.size());
Eigen::Matrix<real_t, 1, Eigen::Dynamic> err(1, est.size());
for (size_t i = 0; i < est.size(); ++i)
{
Quaternion q1(est[i]);
Quaternion q2(trajectory->orientation(times[i]));
err(i) = q1.getDisparityAngle(q2);
}
plt::figure("orientation_offset");
plt::title("Orientation Offset");
plt::labelPlot(label, times, err.row(0));
plt::legend();
plt::show(false);
}
//-----------------------------------------------------------------------------
void plotImuMeasurements(
const std::vector<real_t>& times,
const ImuAccGyrContainer& measurements)
{
CHECK_EQ(static_cast<int>(times.size()), measurements.cols());
plt::figure("imu_measurements");
plt::subplot(3, 1, 1);
plt::title("Imu Measurements (Accel)");
plt::plot(times, measurements.row(0));
plt::subplot(3, 1, 2);
plt::plot(times, measurements.row(1));
plt::subplot(3, 1, 3);
plt::plot(times, measurements.row(2));
plt::show(false);
plt::figure();
plt::subplot(3, 1, 1);
plt::title("Imu Measurements (Gyro)");
plt::plot(times, measurements.row(3));
plt::subplot(3, 1, 2);
plt::plot(times, measurements.row(4));
plt::subplot(3, 1, 3);
plt::plot(times, measurements.row(5));
plt::show(false);
}
} // namespace ze
| 31.790179 | 86 | 0.622946 | [
"vector",
"model"
] |
f580c254ae832e65f316d64a7a457c29ba5f1a07 | 5,764 | cpp | C++ | model/mosesdecoder/moses/Syntax/S2T/Parsers/Scope3Parser/PatternApplicationTrie.cpp | saeedesm/UNMT_AH | cc171bf66933b5c0ad8a0ab87e57f7364312a7df | [
"Apache-2.0"
] | 3 | 2020-02-28T21:42:44.000Z | 2021-03-12T13:56:16.000Z | tools/mosesdecoder-master/moses/Syntax/S2T/Parsers/Scope3Parser/PatternApplicationTrie.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-11-06T14:40:10.000Z | 2020-12-29T19:03:11.000Z | tools/mosesdecoder-master/moses/Syntax/S2T/Parsers/Scope3Parser/PatternApplicationTrie.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-03-26T16:05:11.000Z | 2020-08-06T16:35:39.000Z | #include "PatternApplicationTrie.h"
#include "moses/Syntax/PVertex.h"
namespace Moses
{
namespace Syntax
{
namespace S2T
{
int PatternApplicationTrie::Depth() const
{
if (m_parent) {
return m_parent->Depth() + 1;
}
return 0;
}
const PatternApplicationTrie *
PatternApplicationTrie::GetHighestTerminalNode() const
{
// Check if result has been cached.
if (m_highestTerminalNode) {
return m_highestTerminalNode;
}
// It doesn't really make sense to call this on the root node. Just return 0.
if (!m_parent) {
return 0;
}
// Is this the highest non-root node?
if (!m_parent->m_parent) {
if (IsTerminalNode()) {
m_highestTerminalNode = this;
return this;
} else {
return 0;
}
}
// This is not the highest non-root node, so ask parent node.
if (const PatternApplicationTrie *p = m_parent->GetHighestTerminalNode()) {
m_highestTerminalNode = p;
return p;
}
// There are no terminal nodes higher than this node.
if (IsTerminalNode()) {
m_highestTerminalNode = this;
}
return m_highestTerminalNode;
}
const PatternApplicationTrie *
PatternApplicationTrie::GetLowestTerminalNode() const
{
// Check if result has been cached.
if (m_lowestTerminalNode) {
return m_lowestTerminalNode;
}
// It doesn't really make sense to call this on the root node. Just return 0.
if (!m_parent) {
return 0;
}
// Is this a terminal node?
if (IsTerminalNode()) {
m_lowestTerminalNode = this;
return this;
}
// Is this the highest non-root node?
if (!m_parent->m_parent) {
return 0;
}
// Ask parent node.
return m_parent->GetLowestTerminalNode();
}
// A node corresponds to a rule pattern that has been partially applied to a
// sentence (the terminals have fixed positions, but the spans of gap symbols
// may be unknown). This function determines the range of possible start
// values for the partially-applied pattern.
void PatternApplicationTrie::DetermineStartRange(int sentenceLength,
int &minStart,
int &maxStart) const
{
// Find the leftmost terminal symbol, if any.
const PatternApplicationTrie *n = GetHighestTerminalNode();
if (!n) {
// The pattern contains only gap symbols.
minStart = 0;
maxStart = sentenceLength-Depth();
return;
}
assert(n->m_parent);
if (!n->m_parent->m_parent) {
// The pattern begins with a terminal symbol so the start position is
// fixed.
minStart = n->m_start;
maxStart = n->m_start;
} else {
// The pattern begins with a gap symbol but it contains at least one
// terminal symbol. The maximum start position is the start position of
// the leftmost terminal minus one position for each leading gap symbol.
minStart = 0;
maxStart = n->m_start - (n->Depth()-1);
}
}
// A node corresponds to a rule pattern that has been partially applied to a
// sentence (the terminals have fixed positions, but the spans of gap symbols
// may be unknown). This function determines the range of possible end values
// for the partially-applied pattern.
void PatternApplicationTrie::DetermineEndRange(int sentenceLength,
int &minEnd,
int &maxEnd) const
{
// Find the rightmost terminal symbol, if any.
const PatternApplicationTrie *n = GetLowestTerminalNode();
if (!n) {
// The pattern contains only gap symbols.
minEnd = Depth()-1;
maxEnd = sentenceLength-1;
return;
}
if (n == this) {
// The pattern ends with a terminal symbol so the end position is fixed.
minEnd = m_end;
maxEnd = m_end;
} else {
// The pattern ends with a gap symbol but it contains at least one terminal
// symbol. The minimum end position is the end position of the rightmost
// terminal + one position for each trailing gap symbol.
minEnd = n->m_end + (Depth()-n->Depth());
maxEnd = sentenceLength-1;
}
}
void PatternApplicationTrie::Extend(const RuleTrieScope3::Node &node,
int minPos, const SentenceMap &sentMap,
bool followsGap)
{
const RuleTrieScope3::Node::TerminalMap &termMap = node.GetTerminalMap();
for (RuleTrieScope3::Node::TerminalMap::const_iterator p = termMap.begin();
p != termMap.end(); ++p) {
const Word &word = p->first;
const RuleTrieScope3::Node &child = p->second;
SentenceMap::const_iterator q = sentMap.find(word);
if (q == sentMap.end()) {
continue;
}
for (std::vector<const PVertex *>::const_iterator r = q->second.begin();
r != q->second.end(); ++r) {
const PVertex *v = *r;
std::size_t start = v->span.GetStartPos();
std::size_t end = v->span.GetEndPos();
if (start == (std::size_t)minPos ||
(followsGap && start > (std::size_t)minPos) ||
minPos == -1) {
PatternApplicationTrie *subTrie =
new PatternApplicationTrie(start, end, child, v, this);
subTrie->Extend(child, end+1, sentMap, false);
m_children.push_back(subTrie);
}
}
}
const RuleTrieScope3::Node *child = node.GetNonTerminalChild();
if (!child) {
return;
}
int start = followsGap ? -1 : minPos;
PatternApplicationTrie *subTrie =
new PatternApplicationTrie(start, -1, *child, 0, this);
int newMinPos = (minPos == -1 ? 1 : minPos+1);
subTrie->Extend(*child, newMinPos, sentMap, true);
m_children.push_back(subTrie);
}
void PatternApplicationTrie::ReadOffPatternApplicationKey(
PatternApplicationKey &key) const
{
const int depth = Depth();
key.resize(depth);
const PatternApplicationTrie *p = this;
std::size_t i = depth-1;
while (p->m_parent != 0) {
key[i--] = p;
p = p->m_parent;
}
}
} // namespace S2T
} // namespace Moses
} // namespace Syntax
| 29.865285 | 80 | 0.66499 | [
"vector"
] |
f581ba0c799ea98cff46ed53d5419b2bc1b4c1d8 | 2,885 | cpp | C++ | SVEngine/src/node/SVBGRAInstreamNode.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 34 | 2018-09-28T08:28:27.000Z | 2022-01-15T10:31:41.000Z | SVEngine/src/node/SVBGRAInstreamNode.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | null | null | null | SVEngine/src/node/SVBGRAInstreamNode.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 8 | 2018-10-11T13:36:35.000Z | 2021-04-01T09:29:34.000Z | //
// SVBGRAInstreamNode.cpp
// SVEngine
// Copyright 2017-2020
// yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li
//
#include "SVBGRAInstreamNode.h"
#include "SVScene.h"
#include "SVCameraNode.h"
#include "../mtl/SVMtlCore.h"
#include "../rendercore/SVRenderMesh.h"
#include "../core/SVGeoGen.h"
#include "../basesys/SVConfig.h"
#include "../mtl/SVTexture.h"
#include "../mtl/SVTexMgr.h"
#include "../app/SVInst.h"
#include "../rendercore/SVRenderObject.h"
#include "../rendercore/SVRenderMgr.h"
#include "../rendercore/SVRenderer.h"
#include "../basesys/SVStaticData.h"
//
SVBGRAInstreamNode::SVBGRAInstreamNode(SVInst *_app)
:SVNode(_app) {
SVBGRAInstreamNode(_app,100,100);
}
SVBGRAInstreamNode::SVBGRAInstreamNode(SVInst *_app,f32 _w,f32 _h)
:SVNode(_app) {
ntype = "SVBGRAInstreamNode";
m_rsType = RST_SOLID_3D;
m_pRenderObj = MakeSharedPtr<SVRenderObject>();
m_canSelect = false;
m_pMesh = nullptr;
setSpriteSize(_w,_h);
}
SVBGRAInstreamNode::~SVBGRAInstreamNode() {
m_pMesh = nullptr;
m_pRenderObj = nullptr;
m_pMtl = nullptr;
m_pTex = nullptr;
}
//
void SVBGRAInstreamNode::setSpriteSize(f32 _w,f32 _h) {
m_width = _w;
m_height = _h;
m_pMesh = SVGeoGen::genRect(mApp, m_width, m_height, 0, 0, m_width, m_height,m_aabbBox);
}
void SVBGRAInstreamNode::setMaterial(SVMtlCorePtr _mtl){
m_pMtl = _mtl;
}
void SVBGRAInstreamNode::setTexture(SVTexturePtr _tex){
m_pTex = _tex;
}
void SVBGRAInstreamNode::update(f32 dt) {
SVNode::update(dt);
if (m_pRenderObj && m_pMesh) {
if(m_pMtl){
m_pMtl->setBlendEnable(true);
m_pMtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
m_pMtl->setModelMatrix(m_absolutMat.get());
m_pMtl->setTexcoordFlip(1.0f, -1.0f);
m_pMtl->update(dt);
m_pRenderObj->setMesh(m_pMesh);
m_pRenderObj->setMtl(m_pMtl);
}else{
//创建新的材质
SVMtlCorePtr t_mtl = MakeSharedPtr<SVMtlCore>(mApp, "normal2dBGRA");
t_mtl->setBlendEnable(false);
t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA);
t_mtl->setModelMatrix(m_absolutMat.get());
t_mtl->setTexcoordFlip(1.0f, -1.0f);
t_mtl->setTexture(0,m_pTex);
t_mtl->setBlendEnable(true);
t_mtl->setBlendState(MTL_BLEND_SRC_ALPHA,MTL_BLEND_ONE_MINUS_SRC_ALPHA);
t_mtl->update(dt);
m_pRenderObj->setMesh(m_pMesh);
m_pRenderObj->setMtl(t_mtl);
}
}
}
void SVBGRAInstreamNode::render() {
if (mApp->m_pGlobalParam->m_curScene && m_visible ){
SVRenderScenePtr t_rs = mApp->getRenderMgr()->getRenderScene();
if (m_pRenderObj) {
m_pRenderObj->pushCmd(t_rs, m_rsType, "SVBGRAInstreamNode");
}
}
SVNode::render();
}
| 29.141414 | 92 | 0.659619 | [
"render"
] |
f581bc616cc3b97ed3a12ed7117ae6b07fcc9c7e | 12,211 | cpp | C++ | source/LibFgBase/src/FgGuiApi3d.cpp | MikhailGorobets/FaceGenBaseLibrary | 3ea688f9e3811943adb18e23e7bb2addc5f688a5 | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgGuiApi3d.cpp | MikhailGorobets/FaceGenBaseLibrary | 3ea688f9e3811943adb18e23e7bb2addc5f688a5 | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgGuiApi3d.cpp | MikhailGorobets/FaceGenBaseLibrary | 3ea688f9e3811943adb18e23e7bb2addc5f688a5 | [
"MIT"
] | 1 | 2020-05-27T17:23:50.000Z | 2020-05-27T17:23:50.000Z | //
// Coypright (c) 2020 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
#include "stdafx.h"
#include "FgGuiApi.hpp"
#include "Fg3dMeshIo.hpp"
#include "Fg3dTopology.hpp"
#include "FgAffineCwC.hpp"
#include "FgGeometry.hpp"
using namespace std;
namespace Fg {
Ustrings
cAlbedoModeLabels()
{
return {
"albedo map",
"none",
"by mesh",
"by surf",
};
}
Opt<MeshesIntersect>
intersectMeshes(
Vec2UI winSize,
Vec2I pos,
Mat44F worldToD3ps,
RendMeshes const & rendMeshes)
{
MeshesIntersect ret;
Valid<float> minDepth;
Vec2D pnt {pos};
Mat32F d3ps {-1,1,1,-1,0,1};
Mat32F rcs {-0.5f,winSize[0]-0.5f,-0.5f,winSize[1]-0.5f,0,1};
AffineEw3F d3psToRcs {d3ps,rcs};
Mat44F invXform = asHomogMat(d3psToRcs.asAffine()) * worldToD3ps;
for (size_t mm=0; mm<rendMeshes.size(); ++mm) {
RendMesh const & rendMesh = rendMeshes[mm];
Mesh const & mesh = rendMesh.origMeshN.cref();
Vec3Fs const & verts = rendMesh.posedVertsN.cref();
Vec3Fs pvs(verts.size());
for (size_t ii=0; ii<pvs.size(); ++ii) {
Vec4F v = invXform * asHomogVec(verts[ii]);
pvs[ii] = v.subMatrix<3,1>(0,0) / v[3];
}
for (size_t ss=0; ss<mesh.surfaces.size(); ++ss) {
Surf const & surf = mesh.surfaces[ss];
size_t numTriEquivs = surf.numTriEquivs();
for (size_t tt=0; tt<numTriEquivs; ++tt) {
Vec3UI tri = surf.getTriEquivPosInds(tt);
Vec3F t0 = pvs[tri[0]],
t1 = pvs[tri[1]],
t2 = pvs[tri[2]];
Vec2D v0 = Vec2D(t0.subMatrix<2,1>(0,0)),
v1 = Vec2D(t1.subMatrix<2,1>(0,0)),
v2 = Vec2D(t2.subMatrix<2,1>(0,0));
if (pointInTriangle(pnt,v0,v1,v2) == -1) { // CC winding
Opt<Vec3D> vbc = barycentricCoord(pnt,v0,v1,v2);
if (vbc.valid()) {
Vec3D bc = vbc.val();
// Depth value range for unclipped polys is [-1,1]. These correspond to the
// negative inverse depth values of the frustum.
// Only an approximation to the depth value but who cares:
double dep = cDot(bc,Vec3D(t0[2],t1[2],t2[2]));
if (!minDepth.valid() || (dep < minDepth.val())) { // OGL prj inverts depth
minDepth = dep;
ret.meshIdx = mm;
ret.surfIdx = ss;
ret.surfPnt.triEquivIdx = uint(tt);
ret.surfPnt.weights = Vec3F(bc);
}
}
}
}
}
}
if (minDepth.valid())
return Opt<MeshesIntersect>(ret);
return Opt<MeshesIntersect>();
}
void
Gui3d::panTilt(Vec2I delta)
{
size_t mode = panTiltMode.val();
if (mode == 0) {
Vec2D panTilt;
panTilt[0] = panDegrees.val();
panTilt[1] = tiltDegrees.val();
panTilt += Vec2D(delta) / 3.0;
if (panTiltLimits) {
for (uint dd=0; dd<2; ++dd)
panTilt[dd] = clampBounds(panTilt[dd],-90.0,90.0);
}
else {
for (uint dd=0; dd<2; ++dd) {
if (panTilt[dd] < -180)
panTilt[dd] += 360;
if (panTilt[dd] > 180)
panTilt[dd] -= 360;
}
}
panDegrees.set(panTilt[0]);
tiltDegrees.set(panTilt[1]);
}
else {
// Convert from pixels to half the tangent rotation in radians:
Vec2D del = Vec2D(delta) * 0.005;
QuaternionD poseVal = pose.val();
poseVal = QuaternionD(1.0,del[1],del[0],0.0) * poseVal;
pose.set(poseVal);
}
}
void
Gui3d::roll(int delta)
{
size_t mode = panTiltMode.val();
if (mode == 1) {
// Convert from pixels to half the tangent rotation in radians:
double del = double(delta) * 0.005;
QuaternionD poseVal = pose.val();
poseVal = QuaternionD(1.0,0,0,del) * poseVal;
pose.set(poseVal);
}
}
void
Gui3d::scale(int delta)
{
double rs = logRelSize.val();
rs += double(delta)/200.0;
static double rsMin = std::log(0.05);
// The effective limit is due to avoiding clipping in creation of the MVM and projection matrices,
// not due to this value which well exceeds it:
static double rsMax = std::log(20.0);
if (rs < rsMin)
rs = rsMin;
if (rs > rsMax)
rs = rsMax;
logRelSize.set(rs);
}
void
Gui3d::translate(Vec2I delta)
{
delta[1] *= -1;
Vec2D tr = trans.val();
double scale = std::exp(logRelSize.val());
tr += Vec2D(delta) / (400.0 * scale);
trans.set(tr);
}
void
Gui3d::markSurfPoint(
Vec2UI winSize,
Vec2I pos,
Mat44F worldToD3ps) // Transforms frustum to [-1,1] cube (depth & y inverted)
{
RendMeshes const & rms = rendMeshesN.cref();
Opt<MeshesIntersect> vpt = intersectMeshes(winSize,pos,worldToD3ps,rms);
if (vpt.valid() && pointLabel.ptr) {
MeshesIntersect pt = vpt.val();
RendMesh const & rm = rms[pt.meshIdx];
Mesh * origMeshPtr = rm.origMeshN.valPtr();
fgout << fgnl << "Surf point placed at mesh coord: "
<< cSurfPointPos(pt.surfPnt,origMeshPtr->getTriEquivs(),Quads(),origMeshPtr->verts);
if (origMeshPtr) { // If original mesh is an input node (ie. modifiable):
SurfPoints & surfPoints = origMeshPtr->surfaces[pt.surfIdx].surfPoints;
pt.surfPnt.label = pointLabel.cref().as_ascii();
if (!pt.surfPnt.label.empty()) {
for (size_t ii=0; ii<surfPoints.size(); ++ii) {
if (surfPoints[ii].label == pt.surfPnt.label) { // Replace SPs of same name:
surfPoints[ii] = pt.surfPnt;
return;
}
}
}
// Add new SP:
surfPoints.push_back(pt.surfPnt);
}
}
}
void
Gui3d::markVertex(
Vec2UI winSize,
Vec2I pos,
Mat44F worldToD3ps) // Transforms frustum to [-1,1] cube (depth & y inverted)
{
RendMeshes const & rms = rendMeshesN.cref();
Opt<MeshesIntersect> vpt = intersectMeshes(winSize,pos,worldToD3ps,rms);
if (vpt.valid() && vertMarkModeN.ptr) {
MeshesIntersect pt = vpt.val();
RendMesh const & rm = rms[pt.meshIdx];
Mesh * origMeshPtr = rm.origMeshN.valPtr();
if (origMeshPtr) {
Mesh & meshIn = *origMeshPtr;
Surf const & surf = meshIn.surfaces[pt.surfIdx];
uint facetIdx = cMaxIdx(pt.surfPnt.weights);
uint vertIdx = cTriEquivPosInds(surf.tris,surf.quads,pt.surfPnt.triEquivIdx)[facetIdx];
size_t vertMarkMode = vertMarkModeN.val();
if (vertMarkMode == 0) {
if (!contains(meshIn.markedVerts,vertIdx))
meshIn.markedVerts.push_back(MarkedVert(vertIdx));
}
else if (vertMarkMode < 4) {
Vec3UIs tris = surf.getTriEquivs().posInds;
MeshTopology topo(meshIn.verts.size(),tris);
set<uint> seam;
if (vertMarkMode == 1)
seam = topo.seamContaining(vertIdx);
else if (vertMarkMode == 2) {
Surf tmpSurf;
tmpSurf.tris.posInds = tris;
vector<FgBool> done(meshIn.verts.size(),false);
seam = topo.traceFold(cNormals(svec(tmpSurf),meshIn.verts),done,vertIdx);
}
else if (vertMarkMode == 3)
seam = cFillMarkedVertRegion(meshIn,topo,vertIdx);
for (uint idx : seam)
if (!contains(meshIn.markedVerts,idx))
meshIn.markedVerts.push_back(MarkedVert{idx});
}
}
}
}
void
Gui3d::ctlClick(Vec2UI winSize,Vec2I pos,Mat44F worldToD3ps)
{
RendMeshes const & rms = rendMeshesN.cref();
Opt<MeshesIntersect> vpt = intersectMeshes(winSize,pos,worldToD3ps,rms);
if (vpt.valid()) {
MeshesIntersect pt = vpt.val();
uint mi = cMaxIdx(pt.surfPnt.weights);
RendMesh const & rm = rms[pt.meshIdx];
Mesh const & mesh = rm.origMeshN.cref();
Surf const & surf = mesh.surfaces[pt.surfIdx];
lastCtlClick.meshIdx = pt.meshIdx;
lastCtlClick.vertIdx = cTriEquivPosInds(surf.tris,surf.quads,pt.surfPnt.triEquivIdx)[mi];
lastCtlClick.valid = true;
}
else
lastCtlClick.valid = false;
}
void
Gui3d::ctlDrag(bool left, Vec2UI winSize,Vec2I delta,Mat44F worldToD3ps)
{
if (lastCtlClick.valid) {
// Interestingly, the concept of a delta vector doesn't work in projective space;
// a homogeneous component equal to zero is a direction. Conceptually, we can't
// transform a delta in D3PS to FHCS without knowing it's absolute position since. Hence
// we transform the end point back into FHCS and take the difference:
RendMeshes const & rms = rendMeshesN.cref();
Vec3Fs const & verts = rms[lastCtlClick.meshIdx].posedVertsN.cref();
Vec3F vertPos0Hcs = verts[lastCtlClick.vertIdx];
Vec4F vertPos0d3ps = worldToD3ps * asHomogVec(vertPos0Hcs);
// Convert delta to D3PS. Y inverted and Viewport aspect (compensated for in frustum)
// is ratio to largest dimension:
Vec2F delD3ps2 = 2.0f * Vec2F(delta) / float(cMaxElem(winSize));
Vec4F delD3ps(delD3ps2[0],-delD3ps2[1],0,0),
// Normalize vector for valid addition of delta:
vertPos1d3ps = vertPos0d3ps / vertPos0d3ps[3] + delD3ps,
// We don't expect worldToD3ps to be singular:
vertPos1HcsH = solveLinear(worldToD3ps,vertPos1d3ps).val();
Vec3F vertPos1Hcs = vertPos1HcsH.subMatrix<3,1>(0,0) / vertPos1HcsH[3],
delHcs = vertPos1Hcs - vertPos0Hcs;
ctlDragAction(left,lastCtlClick,delHcs);
}
}
void
Gui3d::ctrlShiftLeftDrag(Vec2UI winSize,Vec2I delta)
{
if (bgImg.imgN.ptr) {
ImgC4UC const & img = bgImg.imgN.cref();
if (!img.empty()) {
Vec2F del = mapDiv(Vec2F(delta),Vec2F(winSize));
Vec2F & offset = bgImg.offset.ref();
offset += del;
}
}
}
void
Gui3d::ctrlShiftRightDrag(Vec2UI winSize,Vec2I delta)
{
if (bgImg.imgN.ptr) {
ImgC4UC const & img = bgImg.imgN.cref();
if (!img.empty()) {
double lnScale = bgImg.lnScale.val();
lnScale += double(delta[1]) / double(winSize[1]);
bgImg.lnScale.set(lnScale);
}
}
}
}
// */
| 39.263666 | 119 | 0.502662 | [
"mesh",
"vector",
"transform"
] |
f5874057568071175b33c9a179a04858a383dd33 | 2,638 | cpp | C++ | keyinfo.cpp | majorpakhom/i2pd-tools | c9408c61215dc1b9f22842b000b9084e7f7be107 | [
"BSD-3-Clause"
] | null | null | null | keyinfo.cpp | majorpakhom/i2pd-tools | c9408c61215dc1b9f22842b000b9084e7f7be107 | [
"BSD-3-Clause"
] | null | null | null | keyinfo.cpp | majorpakhom/i2pd-tools | c9408c61215dc1b9f22842b000b9084e7f7be107 | [
"BSD-3-Clause"
] | null | null | null | #include "Identity.h"
#include "I2PEndian.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include "common/key.hpp"
static int printHelp(const char * exe, int exitcode)
{
std::cout << "usage: " << exe << " [-v] [-d] privatekey.dat" << std::endl;
return exitcode;
}
std::string ConvertTime (time_t t)
{
struct tm *tm = localtime(&t);
char date[128];
snprintf(date, sizeof(date), "%02d/%02d/%d %02d:%02d:%02d", tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec);
return date;
}
int main(int argc, char * argv[])
{
if(argc == 1) {
return printHelp(argv[0], -1);
}
int opt;
bool print_full = false;
bool verbose = false;
while((opt = getopt(argc, argv, "hvd")) != -1) {
switch(opt){
case 'h':
return printHelp(argv[0], 0);
case 'v':
verbose = true;
break;
case 'd':
print_full = true;
break;
default:
return printHelp(argv[0], -1);
}
}
std::string fname(argv[optind]);
i2p::data::PrivateKeys keys;
{
std::vector<uint8_t> buff;
std::ifstream inf;
inf.open(fname);
if (!inf.is_open()) {
std::cout << "cannot open private key file " << fname << std::endl;
return 2;
}
inf.seekg(0, std::ios::end);
const std::size_t len = inf.tellg();
inf.seekg(0, std::ios::beg);
buff.resize(len);
inf.read((char*)buff.data(), buff.size());
if (!keys.FromBuffer(buff.data(), buff.size())) {
std::cout << "bad key file format" << std::endl;
return 3;
}
}
auto dest = keys.GetPublic();
if(!dest) {
std::cout << "failed to extract public key" << std::endl;
return 3;
}
const auto & ident = dest->GetIdentHash();
if (verbose) {
std::cout << "Destination: " << dest->ToBase64() << std::endl;
std::cout << "Destination Hash: " << ident.ToBase64() << std::endl;
std::cout << "B32 Address: " << ident.ToBase32() << ".b32.i2p" << std::endl;
std::cout << "Signature Type: " << SigTypeToName(dest->GetSigningKeyType()) << std::endl;
std::cout << "Encryption Type: " << (int) dest->GetCryptoKeyType() << std::endl;
if (keys.IsOfflineSignature ())
{
std::cout << "Offline signature" << std::endl;
const auto& offlineSignature = keys.GetOfflineSignature ();
std::cout << "Expires: " << ConvertTime (bufbe32toh(offlineSignature.data ())) << std::endl;
std::cout << "Transient Signature Type: " << SigTypeToName(bufbe16toh(offlineSignature.data () + 4)) << std::endl;
}
} else {
if(print_full) {
std::cout << dest->ToBase64() << std::endl;
} else {
std::cout << ident.ToBase32() << ".b32.i2p" << std::endl;
}
}
}
| 26.646465 | 147 | 0.612964 | [
"vector"
] |
f589005c74f295e86132b7d3f986c4cfb4ab7c69 | 13,762 | hxx | C++ | windows/core/ntgdi/gre/textobj.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/core/ntgdi/gre/textobj.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/core/ntgdi/gre/textobj.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /******************************Module*Header*******************************\
* Module Name: textobj.hxx *
* *
* Supporting routines for text output, mostly computation of text *
* positioning and text extent. *
* *
* Created: 16-Jan-1991 13:44:27 *
* Author: Bodin Dresevic [BodinD] *
* *
* Copyright (c) 1992-1999 Microsoft Corporation *
\**************************************************************************/
/*********************************Class************************************\
* class ESTROBJ; *
* *
* The global aspects of the text positioning and text size computation. *
* *
* Public Interface: *
* *
* History: *
* Fri 13-Mar-1992 02:10:27 -by- Charles Whitmer [chuckwh] *
* Simplified all the work and put it into the vInit call. Deleted lots of *
* methods. *
* *
* 21-Jan-1991 -by- Bodin Dresevic [BodinD] *
* Wrote it. *
\**************************************************************************/
// The flTO flags. Leave room for the TSIM flags.
#define TO_MEM_ALLOCATED 0x0001L //Memory was allocated.
#define TO_ALL_PTRS_VALID 0x0002L //All pointers to cache locked.
#define TO_VALID 0x0004L //ESTROBJ constructor succeeded.
#define TO_ESC_NOT_ORIENT 0x0008L //Escapement not equal to orientation.
#define TO_PWSZ_ALLOCATED 0x0010L //pwszOrg needs to be released
#define TO_HIGHRESTEXT 0x0100L //Printer driver wants 28.4 text coords.
#define TO_BITMAPS 0x0200L //pgdf contains GLYPHBITS pointer
#ifdef FE_SB
#define TO_PARTITION_INIT 0x0400L //The partitioning info has been initialized.
#define TO_ALLOC_FACENAME 0x0800L //FaceName glyphs array was allocated.
#define TO_SYS_PARTITION 0x1000L //System glyphs partition initialized
#endif
#define POINTS_PER_INCH 72
#define DEFAULT_SCALABLE_FONT_HEIGHT_IN_POINTS 24
#ifndef GDIFLAGS_ONLY // used for gdikdx
class ESTROBJ : public _STROBJ // so
{
public:
// The following five fields are inherited from the STROBJ.
// ULONG cGlyphs; // Number of glyphs.
// FLONG flAccel; // Accelerator flags exposed to the driver.
// ULONG ulCharInc; // Non-zero if constant character increment.
// RECTL rclBkGround; // Background rect of the string.
// GLYPHPOS *pgp; // Accelerator if all GLYPHPOS's are valid.
// PWSTR pwszOrg; // pointer to original unicode string.
ULONG cgposCopied; // For enumeration.
ULONG cgposPositionsEnumerated; // only used for enumerating positions in linked strings
RFONTOBJ *prfo; // Remember our RFONTOBJ.
FLONG flTO; // flags
EGLYPHPOS *pgpos; // Pointer to the GLYPHPOS structures.
POINTFIX ptfxRef; // Reference point.
POINTFIX ptfxUpdate; // CP advancement for the string.
POINTFIX ptfxEscapement; // The total escapement vector.
RECTFX rcfx; // The TextBox, projected onto the base and ascent.
FIX fxExtent; // The Windows compatible text extent.
FIX xExtra; // computed in H3, G2,3 cases
FIX xBreakExtra; // computed in H3, G2,3 cases
DWORD dwCodePage; // accelerator for ps driver
ULONG cExtraRects; // Rectangles for underline
RECTL arclExtra[3]; // and strikeout.
#ifdef FE_SB
RECTL rclBkGroundSave; // used to save a copy of BkGroundRect
WCHAR *pwcPartition; // For partitioning
LONG *plPartition; // Points to partitioning information
LONG *plNext; // Next glyph in font
GLYPHPOS *pgpNext; // For enumeration
LONG lCurrentFont; // For enumeration
POINTL ptlBaseLineAdjust; // Used to adjust SysEUDC baseline
ULONG cTTSysGlyphs; // Number of TT system font glyphs in a string
ULONG cSysGlyphs; // Number of system eudc glyphs in a string.
ULONG cDefGlyphs; // Number of default eudc glyphs in a string.
ULONG cNumFaceNameLinks; // Number of linked face name eudc in a string .
ULONG *pacFaceNameGlyphs; // Pointer to array of number of face name glyphs.
ULONG acFaceNameGlyphs[QUICK_FACE_NAME_LINKS]; // Number of face name glyphs
// in a string.
#endif
public:
VOID vInit // TEXTOBJ.CXX
(
PWSZ pwsz,
LONG cwc,
XDCOBJ& dco,
RFONTOBJ& rfo,
EXFORMOBJ& xo,
LONG *pdx,
BOOL bPdy,
LONG lEsc,
LONG lExtra,
LONG lBreakExtra,
LONG cBreak,
FIX xRef,
FIX yRef,
FLONG flControl,
LONG *pdxOut,
PVOID pvBuffer,
DWORD dwCodePage
);
VOID vInitSimple // TEXTOBJ.CXX
(
PWSZ pwsz,
LONG cwc,
XDCOBJ& dco,
RFONTOBJ& rfo,
LONG xRef,
LONG yRef,
PVOID pvBuffer
);
ESTROBJ() {flTO = 0;}
// constructor -- initialize the object on the frame
ESTROBJ
(
PWSZ pwsz,
LONG cwc,
XDCOBJ& dco,
RFONTOBJ& rfo,
EXFORMOBJ& xo,
LONG *pdx,
BOOL bPdy,
LONG lEsc,
LONG lExtra,
LONG lBExtra,
LONG cBreak,
FIX x,
FIX y,
FLONG fl,
LONG *pdxOut
)
{
vInit(pwsz,
cwc,
dco,
rfo,xo,pdx,bPdy,lEsc,lExtra,lBExtra,cBreak,x,y,fl,pdxOut,NULL,0);
}
// destructor -- Frees the memory pointed to by pgpos.
~ESTROBJ()
{
#ifdef FE_SB
if (flTO & (TO_MEM_ALLOCATED|TO_ALLOC_FACENAME))
{
if (flTO & TO_MEM_ALLOCATED)
FREEALLOCTEMPBUFFER((PVOID) pgpos);
if (flTO & TO_ALLOC_FACENAME)
VFREEMEM((PVOID) pacFaceNameGlyphs);
}
#else
if (flTO & TO_MEM_ALLOCATED)
{
//
// NOTE:
// Use this macro because allocation of the ESTROBJ goes through
// The fast allocator.
//
FREEALLOCTEMPBUFFER((PVOID) pgpos);
}
#endif
}
// bValid -- Checks if memory allocation in the constructor has failed.
BOOL bValid() {return(flTO & TO_VALID);}
// bOpaqueArea -- Computes the area that would need opaquing behind the text.
// Returns TRUE if the result is complex.
BOOL bOpaqueArea(POINTFIX *pptfx,RECTL *prcl);
// prclExtraRects -- Returns the rectangles that simulate underlines.
RECTL *prclExtraRects()
{
return((cExtraRects == 0) ? NULL : arclExtra);
}
// bTextExtent -- Transform the TextBox extents back to logical coordinates.
#ifdef FE_SB
BOOL bTextExtent(RFONTOBJ& rfo,LONG lEsc,PSIZE pSize);
#else
BOOL bTextExtent(PSIZE pSize);
#endif
// ptfxAdvance -- Returns the amount that the current position should be offset.
POINTFIX& ptfxAdvance() {return(ptfxUpdate);}
// bTextToPath -- Draws the string into the given path.
BOOL bTextToPath( EPATHOBJ& po, XDCOBJ& dco, BOOL bNeedUnflattend = FALSE);
BOOL bLinkedTextToPath( EPATHOBJ& po, XDCOBJ& dco, BOOL bNeedUnflattend = FALSE);
BOOL bTextToPathWorkhorse( EPATHOBJ& po, BOOL bNeedUnflattend = FALSE);
// bExtraRectsToPath -- Draws underlines and strikeouts into a path.
BOOL bExtraRectsToPath(EPATHOBJ& po, BOOL bNeedUnflattend = FALSE);
VOID vEnumStart()
{
cgposCopied = 0;
cgposPositionsEnumerated = 0;
}
// vCharPos -- Special case character positioning routines.
VOID vCharPos_H1
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG *pdx,
EFLOAT efScale
);
VOID ESTROBJ::vCharPos_H2
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef
#ifdef FE_SB
,EFLOAT efScale
#endif
);
VOID vCharPos_H3
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG lExtra,
LONG lBreakExtra,
LONG cBreak,
EFLOAT efScale
#ifdef FE_SB
,PBOOL pAccel = NULL
#endif
);
VOID ESTROBJ::vCharPos_H4
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG *pdxdy,
EFLOAT efXScale,
EFLOAT efYScale
);
VOID vCharPos_G1
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG *pdx,
LONG *pdxOut
);
VOID vCharPos_G2
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG lExtra,
LONG lBreakExtra,
LONG cBreak,
LONG *pdxOut
);
VOID vCharPos_G3
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG lExtra,
LONG lBreakExtra,
LONG cBreak,
LONG *pdx,
LONG *pdxOut
);
VOID vCharPos_G4
(
XDCOBJ& dco,
RFONTOBJ& rfo,
FIX xRef,
FIX yRef,
LONG *pdxdy
);
VOID vEudcOpaqueArea(POINTFIX *pptfx, BOOL bComplexBackGround);
PGLYPHPOS pgpGet() {return(pgpos); }
ULONG cGlyphsGet() {return(cGlyphs); }
PWSZ pwszGet() {return(pwszOrg); }
#ifdef FE_SB
// methods for EUDC functionality
VOID vFontSet( LONG _lCurrentFont )
{ lCurrentFont = _lCurrentFont; cgposCopied = 0;}
FLONG flAccelGet() { return( flAccel ); }
VOID flAccelSet( FLONG _flAccel ) { flAccel = _flAccel ;}
VOID vClearCharInc() { ulCharInc = 0; }
VOID pgpSet( GLYPHPOS *_pgp ) { pgp = _pgp; }
VOID prfntSet( PRFONTOBJ _prfnt ) { prfo = _prfnt; }
VOID pwszSet( PWSZ _pwszOrg ) { pwszOrg = _pwszOrg; }
BOOL bLinkedGlyphs()
{
return((flTO & (TO_SYS_PARTITION|TO_PARTITION_INIT )) ? TRUE : FALSE);
}
VOID cGlyphsSet( LONG _cGlyphs ) { cGlyphs = _cGlyphs; }
ULONG cFaceNameGlyphsGet( ULONG ul )
{
return( pacFaceNameGlyphs ? pacFaceNameGlyphs[ul] : 0);
}
VOID vFaceNameInc( ULONG ul ) { (pacFaceNameGlyphs[ul]) += 1; }
ULONG cTTSysGlyphsGet() { return( cTTSysGlyphs ); }
ULONG cSysGlyphsGet() { return( cSysGlyphs ); }
VOID vSysGlyphsInc() { cSysGlyphs += 1; }
VOID vTTSysGlyphsInc() { cTTSysGlyphs += 1; }
ULONG cDefGlyphsGet() { return( cDefGlyphs ); }
VOID vDefGlyphsInc() { cDefGlyphs += 1; }
VOID vInflateTextRect(ERECTL _rclInflate) { (ERECTL)rclBkGround += _rclInflate; }
VOID ptlBaseLineAdjustSet( POINTL& _ptlBaseLineAdjust );
BOOL bPartitionInit() { return(flTO & TO_PARTITION_INIT ); }
BOOL bSystemPartitionInit(){ return(flTO & TO_SYS_PARTITION);}
BOOL bPartitionInit(COUNT c, UINT uiNumLinks, BOOL bEUDCInit);
LONG *plPartitionGet() { return( plPartition ); }
WCHAR *pwcPartitionGet() { return( pwcPartition ); }
VOID vSaveBkGroundRect() {rclBkGroundSave = rclBkGround;}
VOID vRestoreBkGroundRect() {rclBkGround = rclBkGroundSave;}
#endif
#if DBG
void vCorrectBackGround();
void vCorrectBackGroundError( GLYPHPOS *pgp );
#endif
};
BOOL
GreExtTextOutWLocked(
XDCOBJ &dco,
int x,
int y,
UINT flOpts,
LPRECT prcl,
LPWSTR pwsz,
int cwc,
LPINT pdx,
ULONG ulBkMode,
PVOID pvBuffer,
DWORD dwCodePage
);
BOOL
ExtTextOutRect(
XDCOBJ &dcoDst,
LPRECT prcl
);
BOOL
GreBatchTextOut(
XDCOBJ &dcoDst,
PBATCHTEXTOUT pbText,
ULONG cjBatchLength
);
#endif // GDIFLAGS_ONLY used for gdikdx
| 33.002398 | 100 | 0.496439 | [
"object",
"vector",
"transform"
] |
f58c4142a450a54cb8797720b923d39409c85c94 | 2,857 | cpp | C++ | tests/vector_copy.cpp | skn123/vexcl | 8e80910f9bacf34b786f9538cfd74662653b731f | [
"MIT"
] | 531 | 2015-01-05T11:56:07.000Z | 2022-03-20T10:21:25.000Z | tests/vector_copy.cpp | skn123/vexcl | 8e80910f9bacf34b786f9538cfd74662653b731f | [
"MIT"
] | 130 | 2015-01-29T11:19:38.000Z | 2021-11-14T06:56:07.000Z | tests/vector_copy.cpp | skn123/vexcl | 8e80910f9bacf34b786f9538cfd74662653b731f | [
"MIT"
] | 85 | 2015-01-10T13:09:35.000Z | 2022-03-11T13:31:03.000Z | #define BOOST_TEST_MODULE VectorCopy
#include <boost/test/unit_test.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/gather.hpp>
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(iterate_over_vector)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
x = 42;
BOOST_CHECK(42 == *std::min_element(x.begin(), x.end()));
}
BOOST_AUTO_TEST_CASE(element_access)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
for(size_t i = 0; i < N; i++)
x[i] = 42;
check_sample(x, [](size_t, double a) { BOOST_CHECK(a == 42); });
}
BOOST_AUTO_TEST_CASE(copy_to_std_vector)
{
const size_t N = 1024;
vex::vector<double> X(ctx, N);
std::vector<double> x(N);
X = 42;
copy(X, x);
check_sample(x, [](size_t, double a) { BOOST_CHECK(a == 42); });
X = 67;
vex::copy(X.begin(), X.end(), x.begin());
check_sample(x, [](size_t, double a) { BOOST_CHECK(a == 67); });
}
BOOST_AUTO_TEST_CASE(copy_from_std_vector)
{
const size_t N = 1024;
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(ctx, N);
copy(x, X);
check_sample(X, x, [](size_t, double a, double b) { BOOST_CHECK(a == b); });
std::fill(x.begin(), x.end(), 42);
vex::copy(x.begin(), x.end(), X.begin());
check_sample(X, [](size_t, double a) { BOOST_CHECK(a == 42); });
}
BOOST_AUTO_TEST_CASE(map_buffer)
{
const size_t N = 1 << 20;
vex::vector<size_t> x(ctx, N);
for(unsigned d = 0; d < ctx.size(); ++d) {
auto ptr = x.map(d);
for(size_t i = 0; i < x.part_size(d); ++i)
ptr[i] = i + x.part_start(d);
}
check_sample(x, [](size_t idx, size_t a) { BOOST_CHECK(a == idx); });
}
BOOST_AUTO_TEST_CASE(gather)
{
const size_t n = 1 << 20;
const size_t m = 100;
std::vector<double> x = random_vector<double>(n);
vex::vector<double> X(ctx, x);
std::vector<size_t> i(m);
std::generate(i.begin(), i.end(), [n](){ return rand() % n; });
for (int sorted = 0; sorted < 2; ++sorted) {
if (sorted) {
std::sort(i.begin(), i.end());
i.resize( std::unique(i.begin(), i.end()) - i.begin() );
}
std::vector<double> data(i.size());
vex::gather get(ctx, x.size(), i);
vex::scatter put(ctx, x.size(), i);
get(X, data);
for(size_t p = 0; p < i.size(); ++p)
BOOST_CHECK(data[p] == x[i[p]]);
vex::vector<double> Y(ctx, n);
Y = 0;
put(data, Y);
for(size_t p = 0; p < i.size(); ++p)
BOOST_CHECK(Y[i[p]] == x[i[p]]);
}
}
BOOST_AUTO_TEST_CASE(std_sort_vex_vector)
{
const size_t n = 1 << 10;
vex::vector<double> x(ctx, random_vector<double>(n));
std::sort(x.begin(), x.end());
BOOST_CHECK(std::is_sorted(x.begin(), x.end()));
}
BOOST_AUTO_TEST_SUITE_END()
| 24.008403 | 80 | 0.558628 | [
"vector"
] |
f58cb9a5ac6eac122d198a12350124ece1f28086 | 11,056 | cpp | C++ | src/mongo/db/commands/cleanup_orphaned_cmd.cpp | EshaMaharishi/pubsub-1 | 13cb194078ed39b00ea623db0d87df8e153e7981 | [
"Apache-2.0"
] | 2 | 2015-04-16T02:40:53.000Z | 2016-11-04T09:38:56.000Z | src/mongo/db/commands/cleanup_orphaned_cmd.cpp | EshaMaharishi/pubsub-1 | 13cb194078ed39b00ea623db0d87df8e153e7981 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/commands/cleanup_orphaned_cmd.cpp | EshaMaharishi/pubsub-1 | 13cb194078ed39b00ea623db0d87df8e153e7981 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include <string>
#include <vector>
#include "mongo/base/init.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/commands.h"
#include "mongo/db/field_parser.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/range_deleter_service.h"
#include "mongo/s/collection_metadata.h"
#include "mongo/s/d_logic.h"
#include "mongo/s/range_arithmetic.h"
namespace mongo {
using mongoutils::str::stream;
enum CleanupResult {
CleanupResult_Done, CleanupResult_Continue, CleanupResult_Error
};
/**
* Cleans up one range of orphaned data starting from a range that overlaps or starts at
* 'startingFromKey'. If empty, startingFromKey is the minimum key of the sharded range.
*
* @return CleanupResult_Continue and 'stoppedAtKey' if orphaned range was found and cleaned
* @return CleanupResult_Done if no orphaned ranges remain
* @return CleanupResult_Error and 'errMsg' if an error occurred
*
* If the collection is not sharded, returns CleanupResult_Done.
*/
CleanupResult cleanupOrphanedData( const NamespaceString& ns,
const BSONObj& startingFromKeyConst,
bool secondaryThrottle,
BSONObj* stoppedAtKey,
string* errMsg ) {
BSONObj startingFromKey = startingFromKeyConst;
CollectionMetadataPtr metadata = shardingState.getCollectionMetadata( ns.toString() );
if ( !metadata || metadata->getKeyPattern().isEmpty() ) {
warning() << "skipping orphaned data cleanup for " << ns.toString()
<< ", collection is not sharded" << endl;
return CleanupResult_Done;
}
BSONObj keyPattern = metadata->getKeyPattern();
if ( !startingFromKey.isEmpty() ) {
if ( !metadata->isValidKey( startingFromKey ) ) {
*errMsg = stream() << "could not cleanup orphaned data, start key "
<< startingFromKey
<< " does not match shard key pattern " << keyPattern;
warning() << *errMsg << endl;
return CleanupResult_Error;
}
}
else {
startingFromKey = metadata->getMinKey();
}
KeyRange orphanRange;
if ( !metadata->getNextOrphanRange( startingFromKey, &orphanRange ) ) {
LOG( 1 ) << "orphaned data cleanup requested for " << ns.toString()
<< " starting from " << startingFromKey
<< ", no orphan ranges remain" << endl;
return CleanupResult_Done;
}
*stoppedAtKey = orphanRange.maxKey;
// We're done with this metadata now, no matter what happens
metadata.reset();
LOG( 1 ) << "orphaned data cleanup requested for " << ns.toString()
<< " starting from " << startingFromKey
<< ", removing next orphan range"
<< " [" << orphanRange.minKey << "," << orphanRange.maxKey << ")"
<< endl;
// Metadata snapshot may be stale now, but deleter checks metadata again in write lock
// before delete.
if ( !getDeleter()->deleteNow( ns.toString(),
orphanRange.minKey,
orphanRange.maxKey,
keyPattern,
secondaryThrottle,
errMsg ) ) {
warning() << *errMsg << endl;
return CleanupResult_Error;
}
return CleanupResult_Continue;
}
/**
* Cleanup orphaned data command. Called on a particular namespace, and if the collection
* is sharded will clean up a single orphaned data range which overlaps or starts after a
* passed-in 'startingFromKey'. Returns true and a 'stoppedAtKey' (which will start a
* search for the next orphaned range if the command is called again) or no key if there
* are no more orphaned ranges in the collection.
*
* If the collection is not sharded, returns true but no 'stoppedAtKey'.
* On failure, returns false and an error message.
*
* Calling this command repeatedly until no 'stoppedAtKey' is returned ensures that the
* full collection range is searched for orphaned documents, but since sharding state may
* change between calls there is no guarantee that all orphaned documents were found unless
* the balancer is off.
*
* Safe to call with the balancer on.
*/
class CleanupOrphanedCommand : public Command {
public:
CleanupOrphanedCommand() :
Command( "cleanupOrphaned" ) {}
virtual bool slaveOk() const { return false; }
virtual bool adminOnly() const { return true; }
virtual bool localHostOnlyIfNoAuth( const BSONObj& cmdObj ) { return false; }
virtual Status checkAuthForCommand( ClientBasic* client,
const std::string& dbname,
const BSONObj& cmdObj ) {
if (!client->getAuthorizationSession()->isAuthorizedForActionsOnResource(
ResourcePattern::forClusterResource(), ActionType::cleanupOrphaned)) {
return Status(ErrorCodes::Unauthorized,
"Not authorized for cleanupOrphaned command.");
}
return Status::OK();
}
virtual LockType locktype() const { return NONE; }
// Input
static BSONField<string> nsField;
static BSONField<BSONObj> startingFromKeyField;
static BSONField<bool> secondaryThrottleField;
// Output
static BSONField<BSONObj> stoppedAtKeyField;
bool run( string const &db,
BSONObj &cmdObj,
int,
string &errmsg,
BSONObjBuilder &result,
bool ) {
string ns;
if ( !FieldParser::extract( cmdObj, nsField, &ns, &errmsg ) ) {
return false;
}
if ( ns == "" ) {
errmsg = "no collection name specified";
return false;
}
BSONObj startingFromKey;
if ( !FieldParser::extract( cmdObj,
startingFromKeyField,
&startingFromKey,
&errmsg ) ) {
return false;
}
bool secondaryThrottle = true;
if ( !FieldParser::extract( cmdObj,
secondaryThrottleField,
&secondaryThrottle,
&errmsg ) ) {
return false;
}
if (!shardingState.enabled()) {
errmsg = str::stream() << "server is not part of a sharded cluster or "
<< "the sharding metadata is not yet initialized.";
return false;
}
ChunkVersion shardVersion;
Status status = shardingState.refreshMetadataNow( ns, &shardVersion );
if ( !status.isOK() ) {
if ( status.code() == ErrorCodes::RemoteChangeDetected ) {
warning() << "Shard version in transition detected while refreshing "
<< "metadata for " << ns << " at version " << shardVersion << endl;
}
else {
errmsg = str::stream() << "failed to refresh shard metadata: "
<< status.reason();
return false;
}
}
BSONObj stoppedAtKey;
CleanupResult cleanupResult = cleanupOrphanedData( NamespaceString( ns ),
startingFromKey,
secondaryThrottle,
&stoppedAtKey,
&errmsg );
if ( cleanupResult == CleanupResult_Error ) {
return false;
}
if ( cleanupResult == CleanupResult_Continue ) {
result.append( stoppedAtKeyField(), stoppedAtKey );
}
else {
dassert( cleanupResult == CleanupResult_Done );
}
return true;
}
};
BSONField<string> CleanupOrphanedCommand::nsField( "cleanupOrphaned" );
BSONField<BSONObj> CleanupOrphanedCommand::startingFromKeyField( "startingFromKey" );
BSONField<bool> CleanupOrphanedCommand::secondaryThrottleField( "secondaryThrottle" );
BSONField<BSONObj> CleanupOrphanedCommand::stoppedAtKeyField( "stoppedAtKey" );
MONGO_INITIALIZER(RegisterCleanupOrphanedCommand)(InitializerContext* context) {
// Leaked intentionally: a Command registers itself when constructed.
new CleanupOrphanedCommand();
return Status::OK();
}
} // namespace mongo
| 41.253731 | 97 | 0.565033 | [
"vector"
] |
f58d659c4b9b6af8ae37dd50bb2348be8af06681 | 795 | cpp | C++ | main.cpp | dkhelwig/sb-massive-patch | 0d0e62af3f2e2ff01f0b21827d56e139b370a820 | [
"MIT"
] | null | null | null | main.cpp | dkhelwig/sb-massive-patch | 0d0e62af3f2e2ff01f0b21827d56e139b370a820 | [
"MIT"
] | null | null | null | main.cpp | dkhelwig/sb-massive-patch | 0d0e62af3f2e2ff01f0b21827d56e139b370a820 | [
"MIT"
] | null | null | null |
int utf8_main(int, char*[]);
#ifdef _WIN32
#include <Windows.h>
#include <vector>
#include <string>
#include <iostream>
int wmain(int argc, wchar_t* argv[])
{
std::vector<std::string> args(argc);
std::vector<char*> arg_p(argc);
for (int i = 0; i < argc; ++i)
{
args[i].resize(::WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr));
if (!args[i].size())
{
std::cerr << "Failed to get length of argument" << std::endl;
return -1;
}
args[i].resize(::WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, &args[i][0], static_cast<int>(args[i].size()), nullptr, nullptr));
arg_p[i] = &args[i][0];
}
return utf8_main(argc, &arg_p[0]);
}
#else
int main(int argc, char* argv[])
{
return utf8_main(argc, argv);
}
#endif
| 21.486486 | 131 | 0.6 | [
"vector"
] |
f59233d9ad0a742f9765debab879f249ff41bd2e | 1,582 | hpp | C++ | include/atl/detail/fomula_automaton/parse.hpp | LoringHe/fml | fe4e5341b0f07ffd4d04207b3039cf4157ef3cba | [
"MIT"
] | 2 | 2020-09-02T05:04:52.000Z | 2020-09-04T05:26:33.000Z | include/atl/detail/fomula_automaton/parse.hpp | Jinlong-He/fml | fe4e5341b0f07ffd4d04207b3039cf4157ef3cba | [
"MIT"
] | null | null | null | include/atl/detail/fomula_automaton/parse.hpp | Jinlong-He/fml | fe4e5341b0f07ffd4d04207b3039cf4157ef3cba | [
"MIT"
] | null | null | null | //
// parse.hpp
// atl
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2020 Jinlong He.
//
#ifndef atl_detail_fomula_automaton_parse_hpp
#define atl_detail_fomula_automaton_parse_hpp
#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <atl/detail/fomula_automaton/fomula_automaton.hpp>
using std::endl;
namespace atl::detail {
struct parse_trace_nuxmv_impl {
template <FOA_PARAMS>
static void
apply(const FOA& foa,
const string& trace_file,
unordered_map<string, vector<string> >& trace_table) {
std::ifstream in(trace_file);
string line = "";
vector<string> vars;
while (getline(in, line)) {
vars.clear();
boost::split(vars, line, boost::is_any_of(" "));
if (vars[0] == "Step") continue;
auto& trace = trace_table[vars[0]];
for (ID i = 1; i < vars.size(); i++) {
if (vars[i] != "-") trace.emplace_back(vars[i]);
}
}
in.close();
}
};
};
namespace atl {
template <FOA_PARAMS>
inline void
parse_trace_nuxmv(const FOA& foa,
const string& trace_file,
unordered_map<string, vector<string> >& trace_table) {
return detail::parse_trace_nuxmv_impl::apply(foa, trace_file, trace_table);
}
}
#endif /* atl_detail_fomula_automaton_parse_hpp */
| 29.296296 | 83 | 0.57775 | [
"vector"
] |
f594b30ddbb98e42d2476fc94dea452c3c7450a6 | 7,769 | cc | C++ | components/arc/timer/arc_timer_bridge.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-16T13:10:29.000Z | 2021-11-16T13:10:29.000Z | components/arc/timer/arc_timer_bridge.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/arc/timer/arc_timer_bridge.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include "base/bind.h"
#include "base/containers/flat_set.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/task/task_runner_util.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "components/arc/arc_browser_context_keyed_service_factory_base.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/session/arc_service_manager.h"
#include "components/arc/timer/arc_timer_bridge.h"
#include "components/arc/timer/arc_timer_mojom_traits.h"
#include "mojo/public/cpp/system/handle.h"
#include "mojo/public/cpp/system/platform_handle.h"
namespace arc {
namespace {
// Tag to be used with the powerd timer API.
constexpr char kTag[] = "ARC";
mojom::ArcTimerResult ConvertBoolResultToMojo(bool result) {
return result ? mojom::ArcTimerResult::SUCCESS
: mojom::ArcTimerResult::FAILURE;
}
// Callback for powerd API called in |StartTimer|.
void OnStartTimer(mojom::TimerHost::StartTimerCallback callback, bool result) {
std::move(callback).Run(ConvertBoolResultToMojo(result));
}
// Unwraps a mojo handle to a file descriptor on the system.
base::ScopedFD UnwrapScopedHandle(mojo::ScopedHandle handle) {
base::ScopedPlatformFile platform_file;
if (mojo::UnwrapPlatformFile(std::move(handle), &platform_file) !=
MOJO_RESULT_OK) {
LOG(ERROR) << "Failed to unwrap mojo handle";
}
return platform_file;
}
// Returns true iff |arc_timer_requests| contains duplicate clock id values.
bool ContainsDuplicateClocks(
const std::vector<arc::mojom::CreateTimerRequestPtr>& arc_timer_requests) {
std::set<clockid_t> seen_clock_ids;
for (const auto& request : arc_timer_requests) {
if (!seen_clock_ids.emplace(request->clock_id).second)
return true;
}
return false;
}
// Singleton factory for ArcTimerBridge.
class ArcTimerBridgeFactory
: public internal::ArcBrowserContextKeyedServiceFactoryBase<
ArcTimerBridge,
ArcTimerBridgeFactory> {
public:
// Factory name used by ArcBrowserContextKeyedServiceFactoryBase.
static constexpr const char* kName = "ArcTimerBridgeFactory";
static ArcTimerBridgeFactory* GetInstance() {
return base::Singleton<ArcTimerBridgeFactory>::get();
}
private:
friend base::DefaultSingletonTraits<ArcTimerBridgeFactory>;
ArcTimerBridgeFactory() = default;
~ArcTimerBridgeFactory() override = default;
};
} // namespace
// static
BrowserContextKeyedServiceFactory* ArcTimerBridge::GetFactory() {
return ArcTimerBridgeFactory::GetInstance();
}
// static
ArcTimerBridge* ArcTimerBridge::GetForBrowserContext(
content::BrowserContext* context) {
return ArcTimerBridgeFactory::GetForBrowserContext(context);
}
// static
ArcTimerBridge* ArcTimerBridge::GetForBrowserContextForTesting(
content::BrowserContext* context) {
return ArcTimerBridgeFactory::GetForBrowserContextForTesting(context);
}
ArcTimerBridge::ArcTimerBridge(content::BrowserContext* context,
ArcBridgeService* bridge_service)
: arc_bridge_service_(bridge_service) {
arc_bridge_service_->timer()->SetHost(this);
arc_bridge_service_->timer()->AddObserver(this);
}
ArcTimerBridge::~ArcTimerBridge() {
arc_bridge_service_->timer()->RemoveObserver(this);
arc_bridge_service_->timer()->SetHost(nullptr);
}
void ArcTimerBridge::OnConnectionClosed() {
DeleteArcTimers();
}
void ArcTimerBridge::CreateTimers(
std::vector<arc::mojom::CreateTimerRequestPtr> arc_timer_requests,
CreateTimersCallback callback) {
// Duplicate clocks are not allowed.
if (ContainsDuplicateClocks(arc_timer_requests)) {
std::move(callback).Run(mojom::ArcTimerResult::FAILURE);
return;
}
// Convert mojo arguments to D-Bus arguments required by powerd to create
// timers.
std::vector<std::pair<clockid_t, base::ScopedFD>> requests;
std::vector<clockid_t> clock_ids;
for (auto& request : arc_timer_requests) {
clockid_t clock_id = request->clock_id;
base::ScopedFD expiration_fd =
UnwrapScopedHandle(std::move(request->expiration_fd));
if (!expiration_fd.is_valid()) {
LOG(ERROR) << "Unwrapped expiration fd is invalid for clock=" << clock_id;
std::move(callback).Run(mojom::ArcTimerResult::FAILURE);
return;
}
requests.emplace_back(clock_id, std::move(expiration_fd));
clock_ids.emplace_back(clock_id);
}
chromeos::PowerManagerClient::Get()->CreateArcTimers(
kTag, std::move(requests),
base::BindOnce(&ArcTimerBridge::OnCreateArcTimers,
weak_ptr_factory_.GetWeakPtr(), std::move(clock_ids),
std::move(callback)));
}
void ArcTimerBridge::StartTimer(clockid_t clock_id,
base::TimeTicks absolute_expiration_time,
StartTimerCallback callback) {
auto timer_id = GetTimerId(clock_id);
if (!timer_id.has_value()) {
LOG(ERROR) << "Timer for clock=" << clock_id << " not created";
std::move(callback).Run(mojom::ArcTimerResult::FAILURE);
return;
}
chromeos::PowerManagerClient::Get()->StartArcTimer(
timer_id.value(), absolute_expiration_time,
base::BindOnce(&OnStartTimer, std::move(callback)));
}
void ArcTimerBridge::DeleteArcTimers() {
chromeos::PowerManagerClient::Get()->DeleteArcTimers(
kTag, base::BindOnce(&ArcTimerBridge::OnDeleteArcTimers,
weak_ptr_factory_.GetWeakPtr()));
}
void ArcTimerBridge::OnDeleteArcTimers(bool result) {
if (!result) {
LOG(ERROR) << "Delete timers failed";
return;
}
// If the delete call succeeded then delete any timer ids stored and make a
// create timers call.
DVLOG(1) << "Delete timers succeeded";
timer_ids_.clear();
}
void ArcTimerBridge::OnCreateArcTimers(
std::vector<clockid_t> clock_ids,
CreateTimersCallback callback,
absl::optional<std::vector<TimerId>> timer_ids) {
// Any old timers associated with the same tag are always cleared by the API
// regardless of the new timers being created successfully or not. Clear the
// cached timer ids in that case.
timer_ids_.clear();
// The API returns a list of timer ids corresponding to each clock in
// |clock_ids|.
if (!timer_ids.has_value()) {
LOG(ERROR) << "Create timers failed";
std::move(callback).Run(mojom::ArcTimerResult::FAILURE);
return;
}
std::vector<TimerId> result = timer_ids.value();
if (result.size() != clock_ids.size()) {
std::move(callback).Run(mojom::ArcTimerResult::FAILURE);
return;
}
// Map clock id values to timer ids.
auto timer_id_iter = result.begin();
for (clockid_t clock_id : clock_ids) {
DVLOG(1) << "Storing clock=" << clock_id << " timer id=" << *timer_id_iter;
if (!timer_ids_.emplace(clock_id, *timer_id_iter).second) {
// This should never happen as any collision should have been detected on
// the powerd side and it should have returned an error.
LOG(ERROR) << "Can't store clock=" << clock_id;
timer_ids_.clear();
std::move(callback).Run(mojom::ArcTimerResult::FAILURE);
return;
}
timer_id_iter++;
}
std::move(callback).Run(mojom::ArcTimerResult::SUCCESS);
}
absl::optional<ArcTimerBridge::TimerId> ArcTimerBridge::GetTimerId(
clockid_t clock_id) const {
auto it = timer_ids_.find(clock_id);
return (it == timer_ids_.end()) ? absl::nullopt
: absl::make_optional<TimerId>(it->second);
}
} // namespace arc
| 34.22467 | 80 | 0.716437 | [
"vector"
] |
60d80c0f4ef61e5da914d8ba923353ca4ecc33bf | 4,621 | cpp | C++ | test/geometry/convex_hull_test.cpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 25 | 2016-05-03T02:08:58.000Z | 2022-01-11T03:49:28.000Z | test/geometry/convex_hull_test.cpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 22 | 2016-04-26T04:46:17.000Z | 2016-12-06T03:53:32.000Z | test/geometry/convex_hull_test.cpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 5 | 2017-04-04T16:10:42.000Z | 2019-12-05T08:22:30.000Z | // Copyright Jorge Aguirre 2015
// 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 <cpl/geometry/convex_hull.hpp>
#include <gtest/gtest.h>
#include <cpl/geometry/point_2d.hpp> // point
#include <cpl/geometry/point_order.hpp> // ccw_less
#include <algorithm> // sort, is_sorted
#include <cstddef> // size_t
#include <cstdint> // int32_t
#include <iterator> // begin, end
#include <vector> // vector
using cpl::convex_hull;
using cpl::convex_hull_partition;
using cpl::point;
using std::size_t;
using std::int32_t;
// TODO(Jorge) make_convex_set should be tested or should be internal.
template <class ForwardIt, class Point>
static bool is_ccw_sorted(const Point& center, ForwardIt first,
ForwardIt last) {
if (first == last)
return true;
const auto start = *first - center;
return std::is_sorted(first, last,
[center, start](const Point& lhs, const Point& rhs) {
using cpl::ccw_less;
return ccw_less(center, start, lhs, rhs);
});
}
TEST(ConvexHullTest, SortsPointsInCounterClockwiseOrder) {
using scalar_t = int32_t;
using point_t = point<scalar_t>;
using vector_t = std::vector<point_t>;
vector_t points = {{1, 1}, {1, -1}, {-1, -1}, {-1, 1}};
std::sort(begin(points), end(points));
auto hull = convex_hull(begin(points), end(points), true);
EXPECT_TRUE(is_ccw_sorted(hull.front(), begin(hull), end(hull)));
points.erase(begin(points),
convex_hull_partition(begin(points), end(points), true));
EXPECT_EQ(hull.size(), points.size());
for (size_t i = 0; i < points.size(); ++i) {
EXPECT_EQ(hull[i].x, points[i].x);
EXPECT_EQ(hull[i].y, points[i].y);
}
EXPECT_TRUE(is_ccw_sorted(hull.front(), begin(points), end(points)));
}
TEST(ConvexHullTest, WithCollinearPoints) {
using scalar_t = int32_t;
using point_t = point<scalar_t>;
using vector_t = std::vector<point_t>;
vector_t points = {// Square
{0, 0},
{0, 5},
{5, 5},
{5, 0},
// Collinear points
{0, 2},
{2, 0},
{2, 5},
{5, 2},
// Inner points
{1, 1},
{2, 2},
{3, 3},
{4, 4},
{1, 2},
{3, 2}};
std::sort(begin(points), end(points));
auto hull = convex_hull(begin(points), end(points), true);
points.erase(begin(points),
convex_hull_partition(begin(points), end(points), true));
const size_t expected_len = 8;
EXPECT_EQ(expected_len, hull.size());
EXPECT_EQ(expected_len, points.size());
vector_t result = {{0, 0}, {2, 0}, {5, 0}, {5, 2},
{5, 5}, {2, 5}, {0, 5}, {0, 2}};
for (size_t i = 0; i < expected_len; ++i) {
EXPECT_EQ(result[i].x, points[i].x);
EXPECT_EQ(result[i].y, points[i].y);
EXPECT_EQ(result[i].x, hull[i].x);
EXPECT_EQ(result[i].y, hull[i].y);
}
}
TEST(ConvexHullTest, WithoutCollinearPoints) {
using scalar_t = int32_t;
using point_t = point<scalar_t>;
using vector_t = std::vector<point_t>;
vector_t points = {// Square
{0, 0},
{0, 5},
{5, 5},
{5, 0},
// Collinear points
{0, 2},
{2, 0},
{2, 5},
{5, 2},
// Inner points
{1, 1},
{2, 2},
{3, 3},
{4, 4},
{1, 2},
{3, 2}};
std::sort(begin(points), end(points));
auto hull = convex_hull(begin(points), end(points));
points.erase(begin(points),
convex_hull_partition(begin(points), end(points)));
const size_t expected_len = 4;
EXPECT_EQ(expected_len, hull.size());
EXPECT_EQ(expected_len, points.size());
vector_t result = {{0, 0}, {5, 0}, {5, 5}, {0, 5}};
for (size_t i = 0; i < expected_len; ++i) {
EXPECT_EQ(result[i].x, points[i].x);
EXPECT_EQ(result[i].y, points[i].y);
EXPECT_EQ(result[i].x, hull[i].x);
EXPECT_EQ(result[i].y, hull[i].y);
}
}
| 30.401316 | 77 | 0.511578 | [
"geometry",
"vector"
] |
60db949109b4e7a0bc04ccdd07f47eeebc50efe9 | 22,264 | cpp | C++ | deps/mozjs/js/ipc/ObjectWrapperParent.cpp | zpao/spidernode | 843d5b5e9be55ce447fd03127aeeb2c7728ae168 | [
"MIT"
] | 48 | 2015-01-09T20:39:35.000Z | 2021-12-21T21:17:52.000Z | deps/mozjs/js/ipc/ObjectWrapperParent.cpp | ninja1002/spidernode | ada8fc559bd2c047a6e52c78af9d27ab273c87d5 | [
"MIT"
] | 2 | 2016-02-05T10:27:37.000Z | 2019-01-22T16:22:51.000Z | deps/mozjs/js/ipc/ObjectWrapperParent.cpp | ninja1002/spidernode | ada8fc559bd2c047a6e52c78af9d27ab273c87d5 | [
"MIT"
] | 8 | 2015-01-12T17:14:36.000Z | 2018-09-15T14:10:27.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=80:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* The Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ben Newman <b{enjam,newma}n@mozilla.com> (original author)
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "mozilla/jsipc/ObjectWrapperParent.h"
#include "mozilla/jsipc/ContextWrapperParent.h"
#include "mozilla/jsipc/CPOWTypes.h"
#include "mozilla/unused.h"
#include "nsJSUtils.h"
#include "jsutil.h"
#include "jsfriendapi.h"
using namespace mozilla::jsipc;
namespace {
// Only need one reserved slot because the ObjectWrapperParent* is
// stored in the private slot.
static const uintN sFlagsSlot = 0;
static const uintN sNumSlots = 1;
static const uintN CPOW_FLAG_RESOLVING = 1 << 0;
class AutoResolveFlag
{
JSObject* mObj;
uintN mOldFlags;
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
static uintN GetFlags(JSObject* obj) {
jsval v = JS_GetReservedSlot(obj, sFlagsSlot);
return JSVAL_TO_INT(v);
}
static uintN SetFlags(JSObject* obj, uintN flags) {
uintN oldFlags = GetFlags(obj);
if (oldFlags != flags)
JS_SetReservedSlot(obj, sFlagsSlot, INT_TO_JSVAL(flags));
return oldFlags;
}
public:
AutoResolveFlag(JSObject* obj
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: mObj(obj)
, mOldFlags(SetFlags(obj, GetFlags(obj) | CPOW_FLAG_RESOLVING))
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
~AutoResolveFlag() {
SetFlags(mObj, mOldFlags);
}
static JSBool IsSet(JSObject* obj) {
return GetFlags(obj) & CPOW_FLAG_RESOLVING;
}
};
class StatusMemberOwner
{
OperationStatus mStatus;
public:
StatusMemberOwner() : mStatus(JS_FALSE) {}
OperationStatus* StatusPtr() {
return &mStatus;
}
};
typedef AutoCheckOperationBase<StatusMemberOwner> ACOBase;
class AutoCheckOperation : public ACOBase
{
JS_DECL_USE_GUARD_OBJECT_NOTIFIER
public:
AutoCheckOperation(JSContext* cx,
ObjectWrapperParent* owp
JS_GUARD_OBJECT_NOTIFIER_PARAM)
: ACOBase(cx, owp)
{
JS_GUARD_OBJECT_NOTIFIER_INIT;
}
};
}
void
ObjectWrapperParent::CheckOperation(JSContext* cx,
OperationStatus* status)
{
NS_PRECONDITION(status->type() != OperationStatus::T__None,
"Checking an uninitialized operation.");
switch (status->type()) {
case OperationStatus::TJSVariant:
{
jsval thrown;
if (jsval_from_JSVariant(cx, status->get_JSVariant(), &thrown))
JS_SetPendingException(cx, thrown);
*status = JS_FALSE;
}
break;
case OperationStatus::TJSBool:
if (!status->get_JSBool() && !JS_IsExceptionPending(cx)) {
NS_WARNING("CPOW operation failed without setting an exception.");
}
break;
default:
NS_NOTREACHED("Invalid or uninitialized OperationStatus type.");
break;
}
}
template <typename RType>
static RType
with_error(JSContext* cx,
RType rval,
const char* error = NULL)
{
if (!JS_IsExceptionPending(cx))
JS_ReportError(cx, error ? error : "Unspecified CPOW error");
return rval;
}
const js::Class ObjectWrapperParent::sCPOW_JSClass = {
"CrossProcessObjectWrapper",
JSCLASS_NEW_RESOLVE | JSCLASS_NEW_ENUMERATE |
JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(sNumSlots),
ObjectWrapperParent::CPOW_AddProperty,
ObjectWrapperParent::CPOW_DelProperty,
ObjectWrapperParent::CPOW_GetProperty,
ObjectWrapperParent::CPOW_SetProperty,
(JSEnumerateOp) ObjectWrapperParent::CPOW_NewEnumerate,
(JSResolveOp) ObjectWrapperParent::CPOW_NewResolve,
ObjectWrapperParent::CPOW_Convert,
ObjectWrapperParent::CPOW_Finalize,
nsnull, // reserved1
nsnull, // checkAccess
ObjectWrapperParent::CPOW_Call,
ObjectWrapperParent::CPOW_Construct,
nsnull, // xdrObject
ObjectWrapperParent::CPOW_HasInstance,
nsnull, // mark
{
ObjectWrapperParent::CPOW_Equality,
nsnull, // outerObject
nsnull, // innerObject
nsnull, // iteratorObject
nsnull, // wrappedObject
}
};
void
ObjectWrapperParent::ActorDestroy(ActorDestroyReason)
{
if (mObj) {
JS_SetPrivate(mObj, NULL);
mObj = NULL;
}
}
ContextWrapperParent*
ObjectWrapperParent::Manager()
{
PContextWrapperParent* pcwp = PObjectWrapperParent::Manager();
return static_cast<ContextWrapperParent*>(pcwp);
}
JSObject*
ObjectWrapperParent::GetJSObject(JSContext* cx) const
{
if (!mObj) {
js::Class *clasp = const_cast<js::Class *>(&ObjectWrapperParent::sCPOW_JSClass);
mObj = JS_NewObject(cx, js::Jsvalify(clasp), NULL, NULL);
if (mObj) {
JS_SetPrivate(mObj, (void*)this);
JS_SetReservedSlot(mObj, sFlagsSlot, JSVAL_ZERO);
}
}
return mObj;
}
static ObjectWrapperParent*
Unwrap(JSObject* obj)
{
while (js::GetObjectClass(obj) != &ObjectWrapperParent::sCPOW_JSClass)
if (!(obj = js::GetObjectProto(obj)))
return NULL;
ObjectWrapperParent* self =
static_cast<ObjectWrapperParent*>(JS_GetPrivate(obj));
NS_ASSERTION(!self || self->GetJSObjectOrNull() == obj,
"Wrapper and wrapped object disagree?");
return self;
}
/*static*/ bool
ObjectWrapperParent::jsval_to_JSVariant(JSContext* cx, jsval from,
JSVariant* to)
{
switch (JS_TypeOfValue(cx, from)) {
case JSTYPE_VOID:
*to = void_t();
return true;
case JSTYPE_NULL:
if (from != JSVAL_NULL)
return false;
// fall through
case JSTYPE_FUNCTION:
// CPOWs can fool JS_TypeOfValue into returning JSTYPE_FUNCTION
// because they have a call hook, but CPOWs are really objects, so
// fall through to the JSTYPE_OBJECT case:
case JSTYPE_OBJECT:
{
PObjectWrapperParent* powp;
if (!JSObject_to_PObjectWrapperParent(JSVAL_TO_OBJECT(from), &powp))
return with_error(cx, false, "Cannot pass parent-created object to child");
*to = powp;
}
return true;
case JSTYPE_STRING:
{
nsDependentJSString depStr;
if (!depStr.init(cx, from))
return false;
*to = depStr;
}
return true;
case JSTYPE_NUMBER:
if (JSVAL_IS_INT(from))
*to = JSVAL_TO_INT(from);
else if (JSVAL_IS_DOUBLE(from))
*to = JSVAL_TO_DOUBLE(from);
else return false;
return true;
case JSTYPE_BOOLEAN:
*to = !!JSVAL_TO_BOOLEAN(from);
return true;
case JSTYPE_XML:
return with_error(cx, false, "CPOWs currently cannot handle JSTYPE_XML");
default:
return with_error(cx, false, "Bad jsval type");
}
}
/*static*/ bool
ObjectWrapperParent::jsval_from_JSVariant(JSContext* cx, const JSVariant& from,
jsval* to)
{
switch (from.type()) {
case JSVariant::Tvoid_t:
*to = JSVAL_VOID;
return true;
case JSVariant::TPObjectWrapperParent:
return jsval_from_PObjectWrapperParent(cx, from.get_PObjectWrapperParent(), to);
case JSVariant::TnsString:
{
JSString* str = JS_NewUCStringCopyZ(cx, from.get_nsString().BeginReading());
if (!str)
return false;
*to = STRING_TO_JSVAL(str);
return true;
}
case JSVariant::Tint:
*to = INT_TO_JSVAL(from.get_int());
return true;
case JSVariant::Tdouble:
return !!JS_NewNumberValue(cx, from.get_double(), to);
case JSVariant::Tbool:
*to = BOOLEAN_TO_JSVAL(from.get_bool());
return true;
default:
return false;
}
}
/*static*/ bool
ObjectWrapperParent::
JSObject_to_PObjectWrapperParent(JSObject* from, PObjectWrapperParent** to)
{
if (!from) {
*to = NULL;
return true;
}
ObjectWrapperParent* owp = Unwrap(from);
if (!owp)
return false;
*to = owp;
return true;
}
/*static*/ bool
ObjectWrapperParent::
JSObject_from_PObjectWrapperParent(JSContext* cx,
const PObjectWrapperParent* from,
JSObject** to)
{
const ObjectWrapperParent* owp =
static_cast<const ObjectWrapperParent*>(from);
*to = owp
? owp->GetJSObject(cx)
: JSVAL_TO_OBJECT(JSVAL_NULL);
return true;
}
/*static*/ bool
ObjectWrapperParent::
jsval_from_PObjectWrapperParent(JSContext* cx,
const PObjectWrapperParent* from,
jsval* to)
{
JSObject* obj;
if (!JSObject_from_PObjectWrapperParent(cx, from, &obj))
return false;
*to = OBJECT_TO_JSVAL(obj);
return true;
}
static bool
jsid_from_int(JSContext* cx, int from, jsid* to)
{
jsval v = INT_TO_JSVAL(from);
return JS_ValueToId(cx, v, to);
}
static bool
jsid_from_nsString(JSContext* cx, const nsString& from, jsid* to)
{
JSString* str = JS_NewUCStringCopyZ(cx, from.BeginReading());
if (!str)
return false;
return JS_ValueToId(cx, STRING_TO_JSVAL(str), to);
}
static bool
jsval_to_nsString(JSContext* cx, jsid from, nsString* to)
{
JSString* str;
const jschar* chars;
jsval idval;
if (JS_IdToValue(cx, from, &idval) &&
(str = JS_ValueToString(cx, idval)) &&
(chars = JS_GetStringCharsZ(cx, str))) {
*to = chars;
return true;
}
return false;
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_AddProperty(JSContext *cx, JSObject *obj, jsid id,
jsval *vp)
{
CPOW_LOG(("Calling CPOW_AddProperty (%s)...",
JSVAL_TO_CSTR(cx, id)));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_AddProperty");
if (AutoResolveFlag::IsSet(obj))
return JS_TRUE;
AutoCheckOperation aco(cx, self);
nsString in_id;
if (!jsval_to_nsString(cx, id, &in_id))
return JS_FALSE;
return (self->Manager()->RequestRunToCompletion() &&
self->CallAddProperty(in_id,
aco.StatusPtr()) &&
aco.Ok());
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_GetProperty(JSContext *cx, JSObject *obj, jsid id,
jsval *vp)
{
CPOW_LOG(("Calling CPOW_GetProperty (%s)...",
JSVAL_TO_CSTR(cx, id)));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_GetProperty");
AutoCheckOperation aco(cx, self);
nsString in_id;
if (!jsval_to_nsString(cx, id, &in_id))
return JS_FALSE;
JSVariant out_v;
return (self->Manager()->RequestRunToCompletion() &&
self->CallGetProperty(in_id,
aco.StatusPtr(), &out_v) &&
aco.Ok() &&
self->jsval_from_JSVariant(cx, out_v, vp));
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_SetProperty(JSContext *cx, JSObject *obj, jsid id,
JSBool strict, jsval *vp)
{
CPOW_LOG(("Calling CPOW_SetProperty (%s)...",
JSVAL_TO_CSTR(cx, id)));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_SetProperty");
AutoCheckOperation aco(cx, self);
nsString in_id;
JSVariant in_v;
if (!jsval_to_nsString(cx, id, &in_id) ||
!self->jsval_to_JSVariant(cx, *vp, &in_v))
return JS_FALSE;
JSVariant out_v;
return (self->Manager()->RequestRunToCompletion() &&
self->CallSetProperty(in_id, in_v,
aco.StatusPtr(), &out_v) &&
aco.Ok() &&
self->jsval_from_JSVariant(cx, out_v, vp));
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_DelProperty(JSContext *cx, JSObject *obj, jsid id,
jsval *vp)
{
CPOW_LOG(("Calling CPOW_DelProperty (%s)...",
JSVAL_TO_CSTR(cx, id)));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_DelProperty");
AutoCheckOperation aco(cx, self);
nsString in_id;
if (!jsval_to_nsString(cx, id, &in_id))
return JS_FALSE;
JSVariant out_v;
return (self->Manager()->RequestRunToCompletion() &&
self->CallDelProperty(in_id,
aco.StatusPtr(), &out_v) &&
aco.Ok() &&
jsval_from_JSVariant(cx, out_v, vp));
}
JSBool
ObjectWrapperParent::NewEnumerateInit(JSContext* cx, jsval* statep, jsid* idp)
{
AutoCheckOperation aco(cx, this);
JSVariant out_state;
int out_id;
return (CallNewEnumerateInit(aco.StatusPtr(), &out_state, &out_id) &&
aco.Ok() &&
jsval_from_JSVariant(cx, out_state, statep) &&
(!idp || jsid_from_int(cx, out_id, idp)));
}
JSBool
ObjectWrapperParent::NewEnumerateNext(JSContext* cx, jsval* statep, jsid* idp)
{
AutoCheckOperation aco(cx, this);
JSVariant in_state;
if (!jsval_to_JSVariant(cx, *statep, &in_state))
return JS_FALSE;
JSVariant out_state;
nsString out_id;
if (CallNewEnumerateNext(in_state,
aco.StatusPtr(), &out_state, &out_id) &&
aco.Ok() &&
jsval_from_JSVariant(cx, out_state, statep) &&
jsid_from_nsString(cx, out_id, idp))
{
JSObject* obj = GetJSObject(cx);
AutoResolveFlag arf(obj);
return JS_DefinePropertyById(cx, obj, *idp, JSVAL_VOID, NULL, NULL,
JSPROP_ENUMERATE);
}
return JS_FALSE;
}
JSBool
ObjectWrapperParent::NewEnumerateDestroy(JSContext* cx, jsval state)
{
AutoCheckOperation aco(cx, this);
JSVariant in_state;
if (!jsval_to_JSVariant(cx, state, &in_state))
return JS_FALSE;
return SendNewEnumerateDestroy(in_state);
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_NewEnumerate(JSContext *cx, JSObject *obj,
JSIterateOp enum_op, jsval *statep,
jsid *idp)
{
CPOW_LOG(("Calling CPOW_NewEnumerate..."));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_NewEnumerate");
switch (enum_op) {
case JSENUMERATE_INIT:
case JSENUMERATE_INIT_ALL:
self->Manager()->RequestRunToCompletion();
return self->NewEnumerateInit(cx, statep, idp);
case JSENUMERATE_NEXT:
return self->NewEnumerateNext(cx, statep, idp);
case JSENUMERATE_DESTROY:
return self->NewEnumerateDestroy(cx, *statep);
}
NS_NOTREACHED("Unknown enum_op value in CPOW_NewEnumerate");
return JS_FALSE;
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_NewResolve(JSContext *cx, JSObject *obj, jsid id,
uintN flags, JSObject **objp)
{
CPOW_LOG(("Calling CPOW_NewResolve (%s)...",
JSVAL_TO_CSTR(cx, id)));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_NewResolve");
AutoCheckOperation aco(cx, self);
nsString in_id;
if (!jsval_to_nsString(cx, id, &in_id))
return JS_FALSE;
PObjectWrapperParent* out_pobj;
if (!self->Manager()->RequestRunToCompletion() ||
!self->CallNewResolve(in_id, flags,
aco.StatusPtr(), &out_pobj) ||
!aco.Ok() ||
!JSObject_from_PObjectWrapperParent(cx, out_pobj, objp))
return JS_FALSE;
if (*objp) {
AutoResolveFlag arf(*objp);
JS_DefinePropertyById(cx, *objp, id, JSVAL_VOID, NULL, NULL,
JSPROP_ENUMERATE);
}
return JS_TRUE;
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_Convert(JSContext *cx, JSObject *obj, JSType type,
jsval *vp)
{
CPOW_LOG(("Calling CPOW_Convert (to %s)...",
JS_GetTypeName(cx, type)));
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_Convert");
*vp = OBJECT_TO_JSVAL(obj);
return JS_TRUE;
}
/*static*/ void
ObjectWrapperParent::CPOW_Finalize(JSContext* cx, JSObject* obj)
{
CPOW_LOG(("Calling CPOW_Finalize..."));
ObjectWrapperParent* self = Unwrap(obj);
if (self) {
self->mObj = NULL;
unused << ObjectWrapperParent::Send__delete__(self);
}
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_Call(JSContext* cx, uintN argc, jsval* vp)
{
CPOW_LOG(("Calling CPOW_Call..."));
JSObject* thisobj = JS_THIS_OBJECT(cx, vp);
if (!thisobj)
return JS_FALSE;
ObjectWrapperParent* function =
Unwrap(JSVAL_TO_OBJECT(JS_CALLEE(cx, vp)));
if (!function)
return with_error(cx, JS_FALSE, "Could not unwrap CPOW function");
AutoCheckOperation aco(cx, function);
ObjectWrapperParent* receiver = Unwrap(thisobj);
if (!receiver) {
// Substitute child global for parent global object.
// TODO First make sure we're really replacing the global object?
ContextWrapperParent* manager =
static_cast<ContextWrapperParent*>(function->Manager());
receiver = manager->GetGlobalObjectWrapper();
}
InfallibleTArray<JSVariant> in_argv(argc);
jsval* argv = JS_ARGV(cx, vp);
for (uintN i = 0; i < argc; i++)
if (!jsval_to_JSVariant(cx, argv[i], in_argv.AppendElement()))
return JS_FALSE;
JSVariant out_rval;
return (function->Manager()->RequestRunToCompletion() &&
function->CallCall(receiver, in_argv,
aco.StatusPtr(), &out_rval) &&
aco.Ok() &&
jsval_from_JSVariant(cx, out_rval, vp));
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_Construct(JSContext* cx, uintN argc, jsval* vp)
{
CPOW_LOG(("Calling CPOW_Construct..."));
ObjectWrapperParent* constructor = Unwrap(JSVAL_TO_OBJECT(JS_CALLEE(cx, vp)));
if (!constructor)
return with_error(cx, JS_FALSE, "Could not unwrap CPOW constructor function");
AutoCheckOperation aco(cx, constructor);
InfallibleTArray<JSVariant> in_argv(argc);
jsval* argv = JS_ARGV(cx, vp);
for (uintN i = 0; i < argc; i++)
if (!jsval_to_JSVariant(cx, argv[i], in_argv.AppendElement()))
return JS_FALSE;
PObjectWrapperParent* out_powp;
return (constructor->Manager()->RequestRunToCompletion() &&
constructor->CallConstruct(in_argv, aco.StatusPtr(), &out_powp) &&
aco.Ok() &&
jsval_from_PObjectWrapperParent(cx, out_powp, vp));
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_HasInstance(JSContext *cx, JSObject *obj, const jsval *v,
JSBool *bp)
{
CPOW_LOG(("Calling CPOW_HasInstance..."));
*bp = JS_FALSE;
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_HasInstance");
AutoCheckOperation aco(cx, self);
JSVariant in_v;
if (!jsval_to_JSVariant(cx, *v, &in_v))
return JS_FALSE;
return (self->Manager()->RequestRunToCompletion() &&
self->CallHasInstance(in_v,
aco.StatusPtr(), bp) &&
aco.Ok());
}
/*static*/ JSBool
ObjectWrapperParent::CPOW_Equality(JSContext *cx, JSObject *obj, const jsval *v,
JSBool *bp)
{
CPOW_LOG(("Calling CPOW_Equality..."));
*bp = JS_FALSE;
ObjectWrapperParent* self = Unwrap(obj);
if (!self)
return with_error(cx, JS_FALSE, "Unwrapping failed in CPOW_Equality");
if (JSVAL_IS_PRIMITIVE(*v))
return JS_TRUE;
ObjectWrapperParent* other = Unwrap(JSVAL_TO_OBJECT(*v));
if (!other)
return JS_TRUE;
*bp = (self == other);
return JS_TRUE;
}
| 29.449735 | 91 | 0.617679 | [
"object"
] |
60de02ca6ba2d408d7669f50054f2a21b28d4e2a | 5,267 | cc | C++ | src/developer/feedback/feedback_agent/attachments.cc | sysidos/fuchsia | 0c00fd3c78a9c0111af4689f1e038b3926c4dc9b | [
"BSD-3-Clause"
] | null | null | null | src/developer/feedback/feedback_agent/attachments.cc | sysidos/fuchsia | 0c00fd3c78a9c0111af4689f1e038b3926c4dc9b | [
"BSD-3-Clause"
] | null | null | null | src/developer/feedback/feedback_agent/attachments.cc | sysidos/fuchsia | 0c00fd3c78a9c0111af4689f1e038b3926c4dc9b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia 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 "src/developer/feedback/feedback_agent/attachments.h"
#include <fuchsia/mem/cpp/fidl.h>
#include <lib/fit/promise.h>
#include <zircon/errors.h>
#include <zircon/status.h>
#include <cinttypes>
#include <string>
#include <vector>
#include "src/developer/feedback/feedback_agent/attachments/inspect_ptr.h"
#include "src/developer/feedback/feedback_agent/attachments/kernel_log_ptr.h"
#include "src/developer/feedback/feedback_agent/attachments/previous_system_log_ptr.h"
#include "src/developer/feedback/feedback_agent/attachments/system_log_ptr.h"
#include "src/developer/feedback/feedback_agent/constants.h"
#include "src/developer/feedback/utils/archive.h"
#include "src/lib/fsl/vmo/file.h"
#include "src/lib/fsl/vmo/sized_vmo.h"
#include "src/lib/fsl/vmo/strings.h"
#include "src/lib/syslog/cpp/logger.h"
#include "third_party/rapidjson/include/rapidjson/document.h"
#include "third_party/rapidjson/include/rapidjson/prettywriter.h"
namespace feedback {
namespace {
using fuchsia::feedback::Annotation;
using fuchsia::feedback::Attachment;
// This is actually synchronous, but we return a fit::promise to match other attachment providers
// that are asynchronous.
fit::promise<fuchsia::mem::Buffer> VmoFromFilename(const std::string& filename) {
fsl::SizedVmo vmo;
if (!fsl::VmoFromFilename(filename, &vmo)) {
FX_LOGS(ERROR) << "Failed to read VMO from file " << filename;
return fit::make_result_promise<fuchsia::mem::Buffer>(fit::error());
}
return fit::make_ok_promise(std::move(vmo).ToTransport());
}
fit::promise<fuchsia::mem::Buffer> BuildValue(const std::string& key,
async_dispatcher_t* dispatcher,
std::shared_ptr<sys::ServiceDirectory> services,
const zx::duration timeout, Cobalt* cobalt) {
if (key == kAttachmentBuildSnapshot) {
return VmoFromFilename("/config/build-info/snapshot");
} else if (key == kAttachmentLogKernel) {
return CollectKernelLog(dispatcher, services, timeout, cobalt);
} else if (key == kAttachmentLogSystemPrevious) {
return CollectPreviousSystemLog();
} else if (key == kAttachmentLogSystem) {
return CollectSystemLog(dispatcher, services, timeout, cobalt);
} else if (key == kAttachmentInspect) {
return CollectInspectData(dispatcher, services, timeout, cobalt);
} else {
FX_LOGS(WARNING) << "Unknown attachment " << key;
return fit::make_result_promise<fuchsia::mem::Buffer>(fit::error());
}
}
fit::promise<Attachment> BuildAttachment(const std::string& key, async_dispatcher_t* dispatcher,
std::shared_ptr<sys::ServiceDirectory> services,
const zx::duration timeout, Cobalt* cobalt) {
return BuildValue(key, dispatcher, services, timeout, cobalt)
.and_then([key](fuchsia::mem::Buffer& vmo) -> fit::result<Attachment> {
Attachment attachment;
attachment.key = key;
attachment.value = std::move(vmo);
return fit::ok(std::move(attachment));
})
.or_else([key]() {
FX_LOGS(WARNING) << "Failed to build attachment " << key;
return fit::error();
});
}
} // namespace
std::vector<fit::promise<Attachment>> GetAttachments(
async_dispatcher_t* dispatcher, std::shared_ptr<sys::ServiceDirectory> services,
const std::set<std::string>& allowlist, const zx::duration timeout, Cobalt* cobalt) {
if (allowlist.empty()) {
FX_LOGS(WARNING) << "Attachment allowlist is empty, nothing to retrieve";
return {};
}
std::vector<fit::promise<Attachment>> attachments;
for (const auto& key : allowlist) {
attachments.push_back(BuildAttachment(key, dispatcher, services, timeout, cobalt));
}
return attachments;
}
void AddAnnotationsAsExtraAttachment(const std::vector<Annotation>& annotations,
std::vector<Attachment>* attachments) {
rapidjson::Document json;
json.SetObject();
for (const auto& annotation : annotations) {
json.AddMember(rapidjson::StringRef(annotation.key), annotation.value, json.GetAllocator());
}
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
json.Accept(writer);
if (!writer.IsComplete()) {
FX_LOGS(WARNING) << "Failed to write annotations as a JSON";
return;
}
std::string json_str(buffer.GetString(), buffer.GetSize());
Attachment extra_attachment;
extra_attachment.key = kAttachmentAnnotations;
if (!fsl::VmoFromString(json_str, &extra_attachment.value)) {
FX_LOGS(WARNING) << "Failed to write annotations as an extra attachment";
return;
}
attachments->push_back(std::move(extra_attachment));
}
bool BundleAttachments(const std::vector<Attachment>& attachments, Attachment* bundle) {
if (!::feedback::Archive(attachments, &(bundle->value))) {
FX_LOGS(ERROR) << "failed to archive attachments into one bundle";
return false;
}
bundle->key = kAttachmentBundle;
return true;
}
} // namespace feedback
| 39.30597 | 97 | 0.696032 | [
"vector"
] |
60de7c249e10c54b47b449ed3104502485059d0c | 9,511 | cpp | C++ | cegui/src/views/ListView.cpp | dutow/cegui | f7c0c4bdd1cca015070d0f2893aa919d03d362b4 | [
"MIT"
] | null | null | null | cegui/src/views/ListView.cpp | dutow/cegui | f7c0c4bdd1cca015070d0f2893aa919d03d362b4 | [
"MIT"
] | null | null | null | cegui/src/views/ListView.cpp | dutow/cegui | f7c0c4bdd1cca015070d0f2893aa919d03d362b4 | [
"MIT"
] | 1 | 2020-07-21T00:03:01.000Z | 2020-07-21T00:03:01.000Z | /***********************************************************************
created: Sat May 24 2014
author: Timotei Dolean <timotei21@gmail.com>
purpose: Implementation for a view that displays a list of model items.
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/views/ListView.h"
#include "CEGUI/CoordConverter.h"
#include <algorithm>
namespace CEGUI
{
typedef std::vector<ListViewItemRenderingState> ViewItemsVector;
//----------------------------------------------------------------------------//
static bool listViewItemPointerLess(
const ListViewItemRenderingState* item1,
const ListViewItemRenderingState* item2)
{
return *item1 < *item2;
}
//----------------------------------------------------------------------------//
static bool listViewItemPointerGreater(
const ListViewItemRenderingState* item1,
const ListViewItemRenderingState* item2)
{
return *item1 > *item2;
}
//----------------------------------------------------------------------------//
const String ListView::EventNamespace("ListView");
const String ListView::WidgetTypeName("CEGUI/ListView");
//----------------------------------------------------------------------------//
ListViewItemRenderingState::ListViewItemRenderingState(ListView* list_view) :
d_isSelected(false),
d_attachedListView(list_view)
{
}
bool ListViewItemRenderingState::operator<(ListViewItemRenderingState const& other) const
{
return d_attachedListView->getModel()->compareIndices(d_index, other.d_index) < 0;
}
//----------------------------------------------------------------------------//
bool ListViewItemRenderingState::operator>(const ListViewItemRenderingState& other) const
{
return d_attachedListView->getModel()->compareIndices(d_index, other.d_index) > 0;
}
//----------------------------------------------------------------------------//
ListView::ListView(const String& type, const String& name) :
ItemView(type, name)
{
}
//----------------------------------------------------------------------------//
ListView::~ListView()
{
}
//----------------------------------------------------------------------------//
void ListView::prepareForRender()
{
ItemView::prepareForRender();
if (d_itemModel == nullptr || !isDirty())
return;
if (d_needsFullRender)
{
d_renderedMaxWidth = d_renderedTotalHeight = 0;
d_items.clear();
}
ModelIndex root_index = d_itemModel->getRootIndex();
size_t child_count = d_itemModel->getChildCount(root_index);
for (size_t child = 0; child < child_count; ++child)
{
ModelIndex index = d_itemModel->makeIndex(child, root_index);
if (d_needsFullRender)
{
ListViewItemRenderingState state = ListViewItemRenderingState(this);
updateItem(state, index, d_renderedMaxWidth, d_renderedTotalHeight);
d_items.push_back(state);
}
else
{
ListViewItemRenderingState& item = d_items.at(child);
d_renderedTotalHeight -= item.d_size.d_height;
updateItem(item, index, d_renderedMaxWidth, d_renderedTotalHeight);
}
}
updateScrollbars();
setIsDirty(false);
resortListView();
d_needsFullRender = false;
}
//----------------------------------------------------------------------------//
ModelIndex ListView::indexAt(const glm::vec2& position)
{
if (d_itemModel == nullptr)
return ModelIndex();
//TODO: add prepareForLayout() as a cheaper operation alternative?
prepareForRender();
glm::vec2 window_position = CoordConverter::screenToWindow(*this, position);
Rectf render_area(getViewRenderer()->getViewRenderArea());
if (!render_area.isPointInRectf(window_position))
return ModelIndex();
float cur_height = render_area.d_min.y - getVertScrollbar()->getScrollPosition();
//TODO: start only on the visible area
for (size_t index = 0; index < d_sortedItems.size(); ++index)
{
ListViewItemRenderingState* item = d_sortedItems.at(index);
Sizef size = item->d_size;
float next_height = cur_height + size.d_height;
if (window_position.y >= cur_height &&
window_position.y <= next_height)
{
return item->d_index;
}
cur_height = next_height;
}
return ModelIndex();
}
//----------------------------------------------------------------------------//
const std::vector<ListViewItemRenderingState*>& ListView::getItems() const
{
return d_sortedItems;
}
//----------------------------------------------------------------------------//
void ListView::resortListView()
{
d_sortedItems.clear();
for (ViewItemsVector::iterator itor = d_items.begin();
itor != d_items.end(); ++itor)
{
d_sortedItems.push_back(&(*itor));
}
if (d_sortMode == ViewSortMode::NoSorting)
return;
sort(d_sortedItems.begin(), d_sortedItems.end(),
d_sortMode == ViewSortMode::Ascending ? &listViewItemPointerLess : &listViewItemPointerGreater);
}
//----------------------------------------------------------------------------//
void ListView::resortView()
{
resortListView();
invalidateView(false);
}
//----------------------------------------------------------------------------//
void ListView::updateItem(ListViewItemRenderingState &item, ModelIndex index,
float& max_width, float& total_height)
{
String text = d_itemModel->getData(index);
RenderedString rendered_string =
getRenderedStringParser().parse(text, getFont(), &d_textColourRect);
item.d_string = rendered_string;
item.d_index = index;
item.d_text = text;
item.d_icon = d_itemModel->getData(index, ItemDataRole::Icon);
item.d_size = Sizef(
rendered_string.getHorizontalExtent(this),
rendered_string.getVerticalExtent(this));
max_width = std::max(item.d_size.d_width, max_width);
total_height += item.d_size.d_height;
item.d_isSelected = isIndexSelected(index);
}
//----------------------------------------------------------------------------//
bool ListView::onChildrenAdded(const EventArgs& args)
{
ItemView::onChildrenAdded(args);
const ModelEventArgs& margs = static_cast<const ModelEventArgs&>(args);
if (!d_itemModel->areIndicesEqual(margs.d_parentIndex, d_itemModel->getRootIndex()))
return true;
ViewItemsVector items;
for (size_t i = 0; i < margs.d_count; ++i)
{
ListViewItemRenderingState item(this);
updateItem(item,
d_itemModel->makeIndex(margs.d_startId + i, margs.d_parentIndex),
d_renderedMaxWidth, d_renderedTotalHeight);
items.push_back(item);
}
d_items.insert(d_items.begin() + margs.d_startId, items.begin(), items.end());
//TODO: insert in the right place directly!
resortListView();
invalidateView(false);
return true;
}
//----------------------------------------------------------------------------//
bool ListView::onChildrenRemoved(const EventArgs& args)
{
ItemView::onChildrenRemoved(args);
const ModelEventArgs& margs = static_cast<const ModelEventArgs&>(args);
if (!d_itemModel->areIndicesEqual(margs.d_parentIndex, d_itemModel->getRootIndex()))
return true;
ViewItemsVector::iterator begin = d_items.begin() + margs.d_startId;
ViewItemsVector::iterator end = begin + margs.d_count;
for (ViewItemsVector::iterator itor = begin; itor < end; ++itor)
{
d_renderedTotalHeight -= (*itor).d_size.d_height;
}
d_items.erase(begin, end);
resortListView();
invalidateView(false);
return true;
}
//----------------------------------------------------------------------------//
Rectf ListView::getIndexRect(const ModelIndex& index)
{
int child_id = d_itemModel->getChildId(index);
if (child_id == -1)
{
return Rectf(0, 0, 0, 0);
}
glm::vec2 pos(0, 0);
for (size_t i = 0; i < static_cast<size_t>(child_id); ++i)
{
pos.y += d_items.at(i).d_size.d_height;
}
return Rectf(pos, d_items.at(static_cast<size_t>(child_id)).d_size);
}
}
| 32.910035 | 104 | 0.576806 | [
"vector",
"model"
] |
60e1aa12bbdb52946086c6917cbc9be8be8de236 | 80,763 | cxx | C++ | HMPID/HMPIDsim/AliHMPIDv3.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1 | 2017-04-27T17:28:15.000Z | 2017-04-27T17:28:15.000Z | HMPID/HMPIDsim/AliHMPIDv3.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 3 | 2017-07-13T10:54:50.000Z | 2018-04-17T19:04:16.000Z | HMPID/HMPIDsim/AliHMPIDv3.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 5 | 2017-03-29T12:21:12.000Z | 2018-01-15T15:52:24.000Z | // **************************************************************************
// * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
// * *
// * Author: The ALICE Off-line Project. *
// * Contributors are mentioned in the code where appropriate. *
// * *
// * Permission to use, copy, modify and distribute this software and its *
// * documentation strictly for non-commercial purposes is hereby granted *
// * without fee, provided that the above copyright notice appears in all *
// * copies and that both the copyright notice and this permission notice *
// * appear in the supporting documentation. The authors make no claims *
// * about the suitability of this software for any purpose. It is *
// * provided "as is" without express or implied warranty. *
// **************************************************************************
#include "AliHMPIDv3.h" //class header
#include "AliHMPIDParam.h" //StepManager()
#include "AliHMPIDHit.h" //Hits2SDigs(),StepManager()
#include "AliHMPIDDigit.h" //Digits2Raw(), Raw2SDigits()
#include "AliHMPIDRawStream.h" //Digits2Raw(), Raw2SDigits()
#include "AliRawReader.h" //Raw2SDigits()
#include "AliTrackReference.h"
#include <TVirtualMC.h> //StepManager() for TVirtualMC::GetMC()
#include <TPDGCode.h> //StepHistory()
#include <AliStack.h> //StepManager(),Hits2SDigits()78.6
#include <AliLoader.h> //Hits2SDigits()
#include <AliRunLoader.h> //Hits2SDigits()
#include <AliMC.h> //StepManager()
#include <AliRun.h> //CreateMaterials()
#include <AliMagF.h> //CreateMaterials()
#include "AliGeomManager.h" //AddAlignableVolumes()
#include <AliCDBEntry.h> //CreateMaterials()
#include <AliCDBManager.h> //CreateMaterials()
#include <TF1.h> //DefineOpticalProperties()
#include <TF2.h> //DefineOpticalProperties()
#include <TGeoCompositeShape.h> //CradleBaseVolume()
#include <TGeoGlobalMagField.h>
#include <TGeoPhysicalNode.h> //AddAlignableVolumes()
#include <TGeoXtru.h> //CradleBaseVolume()
#include <TLorentzVector.h> //IsLostByFresnel()
#include <TString.h> //StepManager()
#include <TTree.h>
ClassImp(AliHMPIDv3)
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::AddAlignableVolumes()const
{
// Associates the symbolic volume name with the corresponding volume path. Interface method from AliModule invoked from AliMC
// Arguments: none
// Returns: none
AliGeomManager::ELayerID idHMPID = AliGeomManager::kHMPID;
Int_t modUID, modnum = 0;
TGeoHMatrix *pGm = new TGeoHMatrix;
Double_t trans[3]={0.5*131.24,0.5*126.16,0}; //translation from LORS to TGeo RS (half size AllX, half size allY,0)
pGm->SetTranslation(trans);
Double_t ph[7]={10.,10., 30.,30.,30. ,50.,50};
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++) {
modUID = AliGeomManager::LayerToVolUID(idHMPID,modnum++);
if(!gGeoManager->SetAlignableEntry(Form("/HMPID/Chamber%i",iCh),Form("ALIC_1/Hmp%i_0",iCh),modUID))
AliError("AliHMPIDv3::Unable to set alignable entry!!"); //aligment without AliCluster3D
//Get Tracking To Local matricies for alignment with AliCluster3D
TGeoPNEntry *eCh = gGeoManager->GetAlignableEntryByUID(modUID);
TGeoHMatrix *globMatrix = eCh->GetGlobalOrig();
//Double_t phi = 20.0 * ((iCh+1) / 3) + 10.0;
Double_t phi = ph[iCh];
TGeoHMatrix *t2l = new TGeoHMatrix();
t2l->RotateZ(phi);
t2l->MultiplyLeft(&(globMatrix->Inverse()));
eCh->SetMatrix(t2l);
}//iCh loop
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::CreateMaterials()
{
// Definition of available HMPID materials
// Arguments: none
// Returns: none
AliDebug(1,"Start v2 HMPID.");
//clm update material definition later on from Antonello
//data from PDG booklet 2002 density [gr/cm^3] rad len [cm] abs len [cm]
Float_t aAir[4]={12,14,16,36} , zAir[4]={6,7,8,18} , wAir[4]={0.000124,0.755267,0.231781,0.012827} , dAir=0.00120479; Int_t nAir=4;//mixture 0.9999999
Float_t aC6F14[2]={ 12.01 , 18.99} , zC6F14[2]={ 6 , 9} , wC6F14[2]={6 , 14} , dC6F14=1.68 ; Int_t nC6F14=-2;
Float_t aSiO2[2]={ 28.09 , 15.99} , zSiO2[2]={14 , 8} , wSiO2[2]={1 , 2} , dSiO2=2.64 ; Int_t nSiO2=-2;
Float_t aCH4[2]={ 12.01 , 1.01} , zCH4[2]={ 6 , 1} , wCH4[2]={1 , 4} , dCH4=7.17e-4 ; Int_t nCH4=-2;
// not necessary...PCB properties instead! Float_t aCsI[2]={132.90 ,126.90} , zCsI[2]={55 ,53} , wCsI[2]={1 , 1} , dCsI=0.1 ; Int_t nCsI=-2;
Float_t aRoha = 12.01 , zRoha = 6 , dRoha = 0.10 , radRoha = 18.80 , absRoha = 86.3/dRoha; //special material- quasi quartz
Float_t aCu = 63.55 , zCu = 29 , dCu = 8.96 , radCu = 1.43 , absCu = 134.9/dCu ;
Float_t aW =183.84 , zW = 74 , dW = 19.30 , radW = 0.35 , absW = 185.0/dW ;
Float_t aAl = 26.98 , zAl = 13 , dAl = 2.70 , radAl = 8.90 , absAl = 106.4/dAl ;
Float_t aAr = 39.94 , zAr = 18 , dAr = 1.396e-3, radAr = 14.0 , absAr = 117.2/dAr ;
Int_t matId=0; //tmp material id number
Int_t unsens = 0, sens=1; //sensitive or unsensitive medium
Int_t itgfld = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Integ(); //type of field intergration 0 no field -1 user in guswim 1 Runge Kutta 2 helix 3 const field along z
Float_t maxfld = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Max(); //max field value
Float_t tmaxfd = -10.0; //max deflection angle due to magnetic field in one step
Float_t deemax = - 0.2; //max fractional energy loss in one step
Float_t stemax = - 0.1; //max step allowed [cm]
Float_t epsil = 0.001; //abs tracking precision [cm]
Float_t stmin = - 0.001; //min step size [cm] in continius process transport, negative value: choose it automatically
// PCB copmposed mainly by G10 (Si,C,H,O) -> CsI is negligible (<500nm thick)
// So what is called CsI has the optical properties of CsI, but the composition of G-10 (for delta elec, etc production...)
Float_t aG10[4] = {28.09,12.01,1.01,16.00};
Float_t zG10[4] = {14., 6., 1., 8.};
Float_t wG10[4] = {0.129060,0.515016,0.061873,0.294050};
Float_t dG10 = 1.7;
Int_t nG10 = 4;
AliMixture(++matId,"Air" ,aAir ,zAir ,dAir ,nAir ,wAir ); AliMedium(kAir ,"Air" ,matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
AliMixture(++matId,"C6F14",aC6F14,zC6F14,dC6F14,nC6F14,wC6F14); AliMedium(kC6F14,"C6F14",matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
AliMixture(++matId,"SiO2" ,aSiO2 ,zSiO2 ,dSiO2 ,nSiO2 ,wSiO2 ); AliMedium(kSiO2 ,"SiO2" ,matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
AliMixture(++matId,"CH4" ,aCH4 ,zCH4 ,dCH4 ,nCH4 ,wCH4 ); AliMedium(kCH4 ,"CH4" ,matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
// AliMixture(++matId,"CsI" ,aCsI ,zCsI ,dCsI ,nCsI ,wCsI ); AliMedium(kCsI ,"CsI" ,matId, sens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);//sensitive
AliMixture(++matId,"CsI+PCB",aG10 , zG10, dG10,nG10 ,wG10 ); AliMedium(kCsI ,"CsI" ,matId, sens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);//sensitive
AliMixture(++matId ,"Neo" ,aSiO2 ,zSiO2 ,dSiO2 ,nSiO2 ,wSiO2 ); AliMedium(kNeo ,"Neo" ,matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin); //clm neoceram
AliMaterial(++matId,"Roha",aRoha,zRoha,dRoha,radRoha,absRoha); AliMedium(kRoha ,"Roha" ,matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin); //Roha->honeycomb
AliMaterial(++matId,"Cu" ,aCu ,zCu ,dCu ,radCu ,absCu ); AliMedium(kCu ,"Cu" , matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
AliMaterial(++matId,"W" ,aW ,zW ,dW ,radW ,absW ); AliMedium(kW ,"W" , matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
AliMaterial(++matId,"Al" ,aAl ,zAl ,dAl ,radAl ,absAl ); AliMedium(kAl ,"Al" , matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
AliMaterial(++matId,"Ar" ,aAr ,zAr ,dAr ,radAr ,absAr ); AliMedium(kAr ,"Ar" , matId, unsens, itgfld, maxfld, tmaxfd, stemax, deemax, epsil, stmin);
}//void AliHMPID::CreateMaterials()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//void AliHMPIDv3::InitProperties()
//{
/*
* HMPID
* ====
*
* GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA ANNI BREM COMP DCAY DRAY HADR LOSS MULS PAIR PHOT RAYL
* Quarz Window (>1000 keV delta-electrons)
HMPID 3 1.e-4 1.e-4 1.e-4 -1. 1.e-4 -1. -1. 1.e-3 1.e-3 -1. -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1
* Freon Radiator (> 500 keV delta-electrons)
HMPID 4 1.e-4 1.e-4 1.e-4 -1. 1.e-4 -1. -1. 5.e-4 5.e-4 -1. -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1
* Methane Gap (> 100 keV delta-electrons)
HMPID 5 5.e-5 1.e-5 1.e-4 -1. 1.e-4 -1. -1. 1.e-4 1.e-4 -1. -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1
* Sensitive Volume (> 50 keV delta-electrons)
HMPID 9 1.e-5 1.e-5 1.e-4 -1. 1.e-4 -1. -1. 5.e-5 5.e-5 -1. -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1
* CSI (> 50 keV delta-electrons)
HMPID 6 1.e-5 1.e-5 1.e-4 -1. 1.e-4 -1. -1. 5.e-5 5.e-5 -1. -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1
* PCB backplane (> 50 keV delta-electrons)
HMPID 12 1.e-5 1.e-5 1.e-4 -1. 1.e-4 -1. -1. 5.e-5 5.e-5 -1. -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1
Int_t *idtmed = fIdtmed->GetArray();
Int_t imed;
imed = kSiO2; // * Quarz Window (>1000 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,1.e-3);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",1.e-3);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
imed = kC6F14; // * Freon Radiator (> 500 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,5.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",5.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
imed = kCH4; // * Methane Gap (> 100 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
imed = kCsI; // * CSI (> 50 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
imed = kAl; // * Alluminium (> 50 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
imed = kCu; // * Copper (> 50 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
imed = kW; // * Tungsten (> 50 keV delta-electrons)
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTGAM",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTELE",1.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTNEU",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTMUO",1.e-4);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DCUTE" ,5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "CUTHAD",5.e-5);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "DRAY",1);
TVirtualMC::GetMC()->Gstpar(idtmed[imed], "LOSS",1);
}*/
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::CreateGeometry()
{
//Creates detailed geometry simulation (currently GEANT volumes tree)
//includind the HMPID cradle
AliDebug(1,"Start main.");
if(!TVirtualMC::GetMC()->IsRootGeometrySupported()) return;
TGeoVolume *hmpcradle = CreateCradle();
TString title=GetTitle();
if(title.Contains("TestBeam")){
TGeoVolume *hmpid = CreateChamber(3);
gGeoManager->GetVolume("ALIC")->AddNode(hmpid,0);
}else{
for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){//place 7 chambers
TGeoVolume *hmpid = CreateChamber(iCh);
TGeoHMatrix *pMatrix=new TGeoHMatrix;
IdealPosition(iCh,pMatrix);
gGeoManager->GetVolume("ALIC")->AddNode(hmpid,0,pMatrix);
if(iCh==1 || iCh == 3 || iCh == 5){
TGeoHMatrix *pCradleMatrix=new TGeoHMatrix;
IdealPositionCradle(iCh,pCradleMatrix);
gGeoManager->GetVolume("ALIC")->AddNode(hmpcradle,iCh,pCradleMatrix);
}
}
}
AliDebug(1,"Stop v3. HMPID option");
}
TGeoVolume * AliHMPIDv3::CreateChamber(Int_t number)
{
//Single module geometry building
Double_t cm=1,mm=0.1*cm,um=0.001*mm;//default is cm
TGeoVolume *hmp = new TGeoVolumeAssembly(Form("Hmp%i",number));
TGeoMedium *al =gGeoManager->GetMedium("HMPID_Al");
TGeoMedium *ch4 =gGeoManager->GetMedium("HMPID_CH4");
TGeoMedium *roha =gGeoManager->GetMedium("HMPID_Roha");
TGeoMedium *neoc =gGeoManager->GetMedium("HMPID_Neo");
TGeoMedium *c6f14=gGeoManager->GetMedium("HMPID_C6F14");
TGeoMedium *sio2 =gGeoManager->GetMedium("HMPID_SiO2");
TGeoMedium *cu =gGeoManager->GetMedium("HMPID_Cu");
TGeoMedium *w =gGeoManager->GetMedium("HMPID_W");
TGeoMedium *csi =gGeoManager->GetMedium("HMPID_CsI");
TGeoMedium *ar =gGeoManager->GetMedium("HMPID_Ar");
TGeoRotation *rot=new TGeoRotation("HwireRot"); rot->RotateY(90); //rotate wires around Y to be along X (initially along Z)
TGeoVolume *sbo=gGeoManager->MakeBox ("Hsbo",ch4 , 1419*mm/2 , 1378.00*mm/2 , 50.5*mm/2);//2072P1
TGeoVolume *cov=gGeoManager->MakeBox ("Hcov",al , 1419*mm/2 , 1378.00*mm/2 , 0.5*mm/2);
TGeoVolume *hon=gGeoManager->MakeBox ("Hhon",roha , 1359*mm/2 , 1318.00*mm/2 , 49.5*mm/2);
TGeoVolume *rad=gGeoManager->MakeBox ("Hrad",c6f14, 1330*mm/2 , 413.00*mm/2 , 24.0*mm/2); //2011P1
TGeoVolume *neo=gGeoManager->MakeBox ("Hneo",neoc , 1330*mm/2 , 413.00*mm/2 , 4.0*mm/2);
TGeoVolume *win=gGeoManager->MakeBox ("Hwin",sio2 , 1330*mm/2 , 413.00*mm/2 , 5.0*mm/2);
TGeoVolume *si1=gGeoManager->MakeBox ("Hsi1",sio2 , 1330*mm/2 , 5.00*mm/2 , 15.0*mm/2);
TGeoVolume *si2=gGeoManager->MakeBox ("Hsi2",neoc , 10*mm/2 , 403.00*mm/2 , 15.0*mm/2);
TGeoVolume *spa=gGeoManager->MakeTube("Hspa",sio2 , 0*mm , 5.00*mm , 15.0*mm/2);
TGeoVolume *fr4=gGeoManager->MakeBox ("Hfr4",ch4 , 1407*mm/2 , 1366.00*mm/2 , 15.0*mm/2);//2043P1
TGeoVolume *f4a=gGeoManager->MakeBox ("Hf4a",al , 1407*mm/2 , 1366.00*mm/2 , 10.0*mm/2);
TGeoVolume *f4i=gGeoManager->MakeBox ("Hf4i",ch4 , 1323*mm/2 , 1296.00*mm/2 , 10.0*mm/2);
TGeoVolume *col=gGeoManager->MakeTube("Hcol",cu , 0*mm , 100.00*um , 1323.0*mm/2);
TGeoVolume *sec=gGeoManager->MakeBox ("Hsec",ch4 , 648*mm/2 , 411.00*mm/2 , 6.2*mm/2);//sec=gap 2099P1 (6.2 = 4.45 + 0.05 (1/2 diameter wire)+1.7)
Double_t cellx=8.04*mm,celly=8.4*mm; Int_t nPadX=80, nPadY=48;
TGeoVolume *gap=gGeoManager->MakeBox ("Hgap",ch4 , cellx*nPadX/2 , celly*nPadY/2 , 6.2*mm/2); //x=8.04*80 y=8.4*48 z=pad+pad-ano+marign 2006p1
TGeoVolume *row= gap->Divide ("Hrow",2,nPadY,0,0);//along Y->48 rows
TGeoVolume *cel= row->Divide (Form("Hcel%i",number),1,nPadX,0,0);//along X->80 cells
TGeoVolume *cat=gGeoManager->MakeTube("Hcat",cu , 0.00*mm , 50.00*um , cellx/2);
TGeoVolume *ano=gGeoManager->MakeTube("Hano",w , 0.00*mm , 20.00*um , cellx/2);
TGeoVolume *pad=gGeoManager->MakeBox (Form("Hpad%i",number),csi , 7.54*mm/2 , 7.90*mm/2 , 1.7*mm/2); //2006P1 PCB material...
TGeoVolume *fr1=gGeoManager->MakeBox ("Hfr1",al , 1463*mm/2 , 1422.00*mm/2 , 58.3*mm/2);//2040P1 and pad plane is excluded (62 - 2 - 17)
TGeoVolume *fr1up=gGeoManager->MakeBox ("Hfr1up",ch4,(1426.00-37.00)*mm/2 , (1385.00-37.00)*mm/2 , 20.0*mm/2);//2040P1
TGeoVolume *fr1upcard=gGeoManager->MakeBox ("Hfr1upcard",ch4,662.*mm/2., 425.*mm/2. ,19.0*mm/2);//needed to set the gassiplex
TGeoVolume *fr1perUpBig=gGeoManager->MakeBox ("Hfr1perUpBig",ch4,1389*mm/2,35*mm/2,10*mm/2);
TGeoVolume *fr1perUpSma=gGeoManager->MakeBox ("Hfr1perUpSma",ch4,35*mm/2,(1385-37-2*35)*mm/2,10*mm/2);
TGeoVolume *fr1perDowBig=gGeoManager->MakeBox ("Hfr1perDowBig",ch4,1389*mm/2,46*mm/2,2.3*mm/2);
TGeoVolume *fr1perDowSma=gGeoManager->MakeBox ("Hfr1perDowSma",ch4,46*mm/2,(1385-37-2*46)*mm/2,2.3*mm/2);
TGeoVolume *ppf=gGeoManager->MakeBox ("Hppf",al , 648*mm/2 , 411.00*mm/2 , 38.3*mm/2);//2001P2
TGeoVolume *lar=gGeoManager->MakeBox ("Hlar",ar , 181*mm/2 , 89.25*mm/2 , 38.3*mm/2);//2001P2
TGeoVolume *smo=gGeoManager->MakeBox ("Hsmo",ar , 114*mm/2 , 89.25*mm/2 , 38.3*mm/2);//2001P2
TGeoVolume *cufoil = gGeoManager->MakeBox("Hcufoil", csi, 662.*mm/2., 425.*mm/2., 1.*mm/2.);//PCB foil at the back of the ppf with holes for GASSIPLEX
TGeoVolume *rect = gGeoManager->MakeBox("Hrect",ch4, 48*mm/2, 19*mm/2., 1*mm/2.);
TGeoVolume *fr3= gGeoManager->MakeBox("Hfr3", al, 1463*mm/2, 1422*mm/2, 34*mm/2);//2041P1
TGeoVolume *fr3up= gGeoManager->MakeBox("Hfr3up", ch4, 1323*mm/2, 1282*mm/2, 20*mm/2);//2041P1
TGeoVolume *fr3down=gGeoManager->MakeBox("Hfr3down", ch4, 1437*mm/2, 1370*mm/2, 14*mm/2);//2041P1
TGeoVolume *proxgap1 = gGeoManager->MakeBox("Hproxgap1",ch4,1407*mm/2 , 1366.00*mm/2 ,(9.-7.5)*mm/2.);//methane volume between quartz and fr4
TGeoVolume *proxgap2 = gGeoManager->MakeBox("Hproxgap2",ch4,1407*mm/2 , 1366.00*mm/2 ,(81.7-6.2-34.-9.-7.5)*mm/2.);//methane volume between fr4 and Hgap(tot height(81.7) - Hsec (6.2) - proxygap2 (34) - upper bound of fr4 (9+7.5))
// ^ Y z= z=-12mm z=98.25mm ALIC->7xHmp (virtual)-->1xHsbo (virtual) --->2xHcov (real) 2072P1
// | ____________________________________ | |-->1xHhon (real) 2072P1
// | | ______ ____ ______ | |
// | | | | | * | | | |->3xHrad (virtual) --->1xHneo (real) 2011P1
// | |50.5mm| |24mm| * |45.5mm| | | |-->1xHwin (real) 2011P1
// | | | | | * | | | | |-->2xHsi1 (real) 2011P1
// | | | |____| * |______| | | |-->2xHsi2 (real) 2011P1
// | | | ____ * ______ | | |->30xHspa (real) 2011P1
// | | | | | * | | | |
// | | | | | * | | | |->1xHfr4 (vitual) --->1xHf4a (real)---->1xHf4i(virtual) 2043P1
// | | sb | | rad| * | | | | |-->322xHcol (real) 2043P1
// | | | |____| * |______| | |
// | | | ____ * ______ | |->1xHfr1 (real) --> 6xHppf(real) ---->8xHlar (virtual) 2001P1
// | | | | | * | | | | |--->8xHsmo (virtual) 2001P1
// | | | | | * | | | |
// | | | | | * | | | |-> 6xHgap (virtual) --->48xHrow (virtual) -->80xHcel (virtual) -->4xHcat (real) from p84 TDR
// | |______| |____| * |______| | |-->2xHano (real) from p84 TDR
// |____________________________________| |-->1xHpad (real) from p84 TDR
// --->Z
hmp->AddNode(sbo ,1,new TGeoTranslation( 0*mm, 0*mm, -73.75*mm)); //p.84 TDR
sbo->AddNode(hon ,1,new TGeoTranslation( 0*mm,0*mm, 0*mm)); //2072P1
sbo->AddNode(cov ,1,new TGeoTranslation( 0*mm,0*mm, +25*mm));
sbo->AddNode(cov ,2,new TGeoTranslation( 0*mm,0*mm, -25*mm));
hmp->AddNode(rad,2,new TGeoTranslation( 0*mm,+434*mm, -12.00*mm));
hmp->AddNode(rad,1,new TGeoTranslation( 0*mm, 0*mm, -12.00*mm));
hmp->AddNode(rad,0,new TGeoTranslation( 0*mm,-434*mm, -12.00*mm));
rad->AddNode(neo,1,new TGeoTranslation( 0*mm, 0*mm, -10.0*mm));
rad->AddNode(win,1,new TGeoTranslation( 0*mm, 0*mm, 9.5*mm));
rad->AddNode(si1,1,new TGeoTranslation( 0*mm,-204*mm, -0.5*mm)); rad->AddNode(si1,2,new TGeoTranslation( 0*mm,+204*mm, -0.5*mm));
rad->AddNode(si2,1,new TGeoTranslation(-660*mm, 0*mm, -0.5*mm)); rad->AddNode(si2,2,new TGeoTranslation(+660*mm, 0*mm, -0.5*mm));
for(Int_t i=0;i<3;i++) for(Int_t j=0;j<10;j++) rad->AddNode(spa,10*i+j,new TGeoTranslation(-1330*mm/2+116*mm+j*122*mm,(i-1)*105*mm,-0.5*mm));
hmp->AddNode(fr4,1,new TGeoTranslation( 0*mm, 0*mm, 9.00*mm)); //p.84 TDR
for(int i=1;i<=322;i++) fr4->AddNode(col,i,new TGeoCombiTrans( 0*mm, -1296/2*mm+i*4*mm,-5*mm,rot)); //F4 2043P1
fr4->AddNode(f4a,1,new TGeoTranslation( 0*mm,0*mm, 2.5*mm));
f4a->AddNode(f4i,1,new TGeoTranslation( 0*mm,0*mm, 0*mm));
hmp->AddNode(sec,4,new TGeoTranslation(-335*mm,+433*mm, 78.6*mm)); hmp->AddNode(sec,5,new TGeoTranslation(+335*mm,+433*mm, 78.6*mm));
hmp->AddNode(sec,2,new TGeoTranslation(-335*mm, 0*mm, 78.6*mm)); hmp->AddNode(sec,3,new TGeoTranslation(+335*mm, 0*mm, 78.6*mm));
hmp->AddNode(sec,0,new TGeoTranslation(-335*mm,-433*mm, 78.6*mm)); hmp->AddNode(sec,1,new TGeoTranslation(+335*mm,-433*mm, 78.6*mm));
sec->AddNode(gap,1,new TGeoTranslation(0,0,0.*mm));
cel->AddNode(cat,1,new TGeoCombiTrans (0, 3.15*mm , -2.70*mm , rot)); //4 cathode wires
cel->AddNode(ano,1,new TGeoCombiTrans (0, 2.00*mm , -0.29*mm , rot)); //2 anod wires
cel->AddNode(cat,2,new TGeoCombiTrans (0, 1.05*mm , -2.70*mm , rot));
cel->AddNode(cat,3,new TGeoCombiTrans (0, -1.05*mm , -2.70*mm , rot));
cel->AddNode(ano,2,new TGeoCombiTrans (0, -2.00*mm , -0.29*mm , rot));
cel->AddNode(cat,4,new TGeoCombiTrans (0, -3.15*mm , -2.70*mm , rot));
cel->AddNode(pad,1,new TGeoTranslation(0, 0.00*mm , 2.25*mm)); //1 pad
hmp->AddNode(fr1,1,new TGeoTranslation(0.,0.,(80.+1.7)*mm+58.3*mm/2.));
fr1->AddNode(fr1up,1,new TGeoTranslation(0.,0.,(58.3*mm-20.00*mm)/2.));
fr1->AddNode(fr1perUpBig,0,new TGeoTranslation(0.,(1385-37-35)*mm/2.,(58.3*mm-20.00*2*mm-10.0*mm)/2.));
fr1->AddNode(fr1perUpSma,0,new TGeoTranslation((1426-37-35)*mm/2.,0.,(58.3*mm-20.00*2*mm-10.0*mm)/2.));
fr1->AddNode(fr1perUpBig,1,new TGeoTranslation(0.,-(1385-37-35)*mm/2.,(58.3*mm-20.00*2*mm-10.0*mm)/2.));
fr1->AddNode(fr1perUpSma,1,new TGeoTranslation(-(1426-37-35)*mm/2.,0.,(58.3*mm-20.00*2*mm-10.0*mm)/2.));
fr1->AddNode(fr1perDowBig,0,new TGeoTranslation(0.,(1385-37)*mm/2.,(-58.3*mm+2.3*mm)/2.));
fr1->AddNode(fr1perDowSma,0,new TGeoTranslation((1426-37)*mm/2.,0.,(-58.3*mm+2.3*mm)/2.));
fr1->AddNode(fr1perDowBig,1,new TGeoTranslation(0.,-(1385-37)*mm/2.,(-58.3*mm+2.3*mm)/2.));
fr1->AddNode(fr1perDowSma,1,new TGeoTranslation(-(1426-37)*mm/2.,0.,(-58.3*mm+2.3*mm)/2.));
fr1->AddNode(ppf,4,new TGeoTranslation(-335*mm,433*mm,(-58.3+38.3)*mm/2.)); fr1->AddNode(ppf,5,new TGeoTranslation(335*mm,433*mm,(-58.3+38.3)*mm/2.));
fr1->AddNode(ppf,2,new TGeoTranslation(-335*mm,0.,(-58.3+38.3)*mm/2.)); fr1->AddNode(ppf,3,new TGeoTranslation(335*mm,0.,(-58.3+38.3)*mm/2.));
fr1->AddNode(ppf,0,new TGeoTranslation(-335*mm,-433*mm,(-58.3+38.3)*mm/2.)); fr1->AddNode(ppf,1,new TGeoTranslation(335*mm,-433*mm,(-58.3+38.3)*mm/2.));
Double_t offsetx = 16.*mm, offsety = 34.*mm/2., interdistx = 48*mm+offsetx+0.6666*mm,interdisty = 19.*mm+2.*offsety;
//gassiplex implementation
//it is in 3 different volumes: Hrec (in Hcufoil)+Hext
TGeoVolume *gassipl2 = gGeoManager->MakeBox("Hgassipl2",csi,32.*mm/2,3.*mm/2.,1.*mm/2.); //in Hrect
TGeoVolume *gassipl3 = gGeoManager->MakeBox("Hgassipl3",csi,60.*mm/2,3.*mm/2.,19.*mm/2.); //in Hfr1upcard
TGeoVolume *gassipl4 = gGeoManager->MakeBox("Hgassipl4",csi,60.*mm/2,3.*mm/2.,91.*mm/2.); //in Hext (the big rectangle of the card is 110 mm long, 62 mm wide and 1.5 mm high)
TGeoVolume *busext = gGeoManager->MakeTubs("Hbusext",csi,29*mm,30*mm,40*mm/2.,0.,180); //in Hext
TGeoVolume *ext = new TGeoVolumeAssembly("Hext");
rect->AddNode(gassipl2,1,new TGeoTranslation(0.,0.,0));
for(Int_t hor=0; hor< 10; hor++){
for(Int_t vert=0; vert < 8; vert++){
cufoil->AddNode(rect,hor+vert*10,new TGeoTranslation(offsetx+ 48.*mm/2 + hor*interdistx-662.*mm/2,offsety + 19.*mm/2 + vert*interdisty-425.*mm/2.,0.));
fr1upcard->AddNode(gassipl3,hor+vert*10,new TGeoTranslation(offsetx+ 48.*mm/2 + hor*interdistx-662.*mm/2,offsety + 19.*mm/2 + vert*interdisty-425.*mm/2.,0.));
ext->AddNode(gassipl4,hor+vert*10,new TGeoTranslation(offsetx+ 48.*mm/2 + hor*interdistx-662.*mm/2,offsety + 19.*mm/2 +
vert*interdisty-425.*mm/2.,0));
ext->AddNode(busext,hor+vert*10,new TGeoTranslation(offsetx+ 48.*mm/2 + hor*interdistx-662.*mm/2,offsety + 19.*mm/2 +
vert*interdisty-425.*mm/2 + 3.*mm/2.,0));
}
}
fr1up->AddNode(cufoil,4,new TGeoTranslation(-335*mm,433*mm,-20.0*mm/2+1.*mm/2)); fr1up->AddNode(cufoil,5,new TGeoTranslation(335*mm,433*mm,-20.0*mm/2+1.*mm/2));
fr1up->AddNode(cufoil,2,new TGeoTranslation(-335*mm,0,-20.0*mm/2+1.*mm/2)); fr1up->AddNode(cufoil,3,new TGeoTranslation(335*mm,0,-20.0*mm/2+1.*mm/2));
fr1up->AddNode(cufoil,0,new TGeoTranslation(-335*mm,-433*mm,-20.0*mm/2+1.*mm/2)); fr1up->AddNode(cufoil,1,new TGeoTranslation(335*mm,-433*mm,-20.0*mm/2+1.*mm/2));
fr1up->AddNode(fr1upcard,4,new TGeoTranslation(-335*mm,433*mm,1.*mm/2.)); fr1up->AddNode(fr1upcard,5,new TGeoTranslation(335*mm,433*mm,1.*mm/2.));
fr1up->AddNode(fr1upcard,2,new TGeoTranslation(-335*mm,0,1.*mm/2.)); fr1up->AddNode(fr1upcard,3,new TGeoTranslation(335*mm,0,1.*mm/2.));
fr1up->AddNode(fr1upcard,0,new TGeoTranslation(-335*mm,-433*mm,1.*mm/2)); fr1up->AddNode(fr1upcard,1,new TGeoTranslation(335*mm,-433*mm,1.*mm/2.));
hmp->AddNode(ext,4,new TGeoTranslation(-335*mm,+433*mm, (80.+1.7)*mm+58.3*mm+91*mm/2.)); hmp->AddNode(ext,5,new TGeoTranslation(+335*mm,+433*mm, (80.+1.7)*mm+58.3*mm+91*mm/2.));
hmp->AddNode(ext,2,new TGeoTranslation(-335*mm, 0*mm, (80.+1.7)*mm+58.3*mm+91*mm/2.)); hmp->AddNode(ext,3,new TGeoTranslation(+335*mm, 0*mm, (80.+1.7)*mm+58.3*mm+91*mm/2.));
hmp->AddNode(ext,0,new TGeoTranslation(-335*mm,-433*mm, (80.+1.7)*mm+58.3*mm+91*mm/2.)); hmp->AddNode(ext,1,new TGeoTranslation(+335*mm,-433*mm, (80.+1.7)*mm+58.3*mm+91*mm/2.));
hmp->AddNode(proxgap1,0,new TGeoTranslation(0.,0.,(9.-7.5)*mm/2.));//due to the TGeoVolumeAssembly definition the ch4 volume must be inserted around the collecting wires
hmp->AddNode(proxgap2,0,new TGeoTranslation(0.,0.,(9+7.5 +34)*mm + (81.7-6.2-34.-9.-7.5)*mm/2.));// tot height(81.7) - Hsec - proxygap2 - top edge fr4 at (9+7.5) mm
// ^ Y single cell 5.5mm CH4 = 1*mm CsI + 4.45*mm CsI x cath +0.05*mm safety margin
// | ______________________________
// | | | ^ ||
// | | 1.05mm ||
// 2.2*mm| xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- 50um x || cat shift x=0mm , y= 3.15mm , z=-2.70mm
// | | ||
// | | ||
// __ | .......................... | 2.1mm 20un . || ano shift x=0mm , y= 2.00mm , z=-0.29mm
// | | ||
// | | ||
// | xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- x || cat shift x=0mm , y= 1.05mm , z=-2.70mm
// | | ||
// | | 8.4mm ||
// 4*mm | | 2.1mm || pad shift x=0mm , y= 0.00mm , z=2.25*mm
// | | ||
// | | ||
// | xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- x || cat shift x=0mm , y=-1.05mm , z=-2.70mm
// | | ||
// | | ||
// __ | .......................... | 2.1mm . 2.04mm|| ano shift x=0mm , y=-2.00mm , z=-0.29mm
// | | ||
// | | ||
// | xxxxxxxxxxxxxxxxxxxxxxxxxxxx |-- x 4.45mm || cat shift x=0mm , y=-3.15mm , z=-2.70mm
// 2.2*mm| | ||
// | | 1.05mm ||
// |______________________________| v ||
// < 8 mm >
// ----->X ----->Z
ppf->AddNode(lar,0,new TGeoTranslation(-224.5*mm,-151.875*mm, 0.*mm));
ppf->AddNode(lar,1,new TGeoTranslation(-224.5*mm,- 50.625*mm, 0.*mm));
ppf->AddNode(lar,2,new TGeoTranslation(-224.5*mm,+ 50.625*mm, 0.*mm));
ppf->AddNode(lar,3,new TGeoTranslation(-224.5*mm,+151.875*mm, 0.*mm));
ppf->AddNode(lar,4,new TGeoTranslation(+224.5*mm,-151.875*mm, 0.*mm));
ppf->AddNode(lar,5,new TGeoTranslation(+224.5*mm,- 50.625*mm, 0.*mm));
ppf->AddNode(lar,6,new TGeoTranslation(+224.5*mm,+ 50.625*mm, 0.*mm));
ppf->AddNode(lar,7,new TGeoTranslation(+224.5*mm,+151.875*mm, 0.*mm));
ppf->AddNode(smo,0,new TGeoTranslation(- 65.0*mm,-151.875*mm, 0.*mm));
ppf->AddNode(smo,1,new TGeoTranslation(- 65.0*mm,- 50.625*mm, 0.*mm));
ppf->AddNode(smo,2,new TGeoTranslation(- 65.0*mm,+ 50.625*mm, 0.*mm));
ppf->AddNode(smo,3,new TGeoTranslation(- 65.0*mm,+151.875*mm, 0.*mm));
ppf->AddNode(smo,4,new TGeoTranslation(+ 65.0*mm,-151.875*mm, 0.*mm));
ppf->AddNode(smo,5,new TGeoTranslation(+ 65.0*mm,- 50.625*mm, 0.*mm));
ppf->AddNode(smo,6,new TGeoTranslation(+ 65.0*mm,+ 50.625*mm, 0.*mm));
ppf->AddNode(smo,7,new TGeoTranslation(+ 65.0*mm,+151.875*mm, 0.*mm));
//hmp->AddNode(fr3,1,new TGeoTranslation(0.,0.,(81.7-29.)*mm-34.*mm/2));
hmp->AddNode(fr3,1,new TGeoTranslation(0.,0.,(9.+7.5)*mm+34.*mm/2));
fr3->AddNode( fr3up,1, new TGeoTranslation(0., 0., 7*mm));
fr3->AddNode(fr3down,1,new TGeoTranslation(0., 0., -10*mm));
return hmp;
}//CreateChamber()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::Init()
{
// This method defines ID for sensitive volumes, i.e. such geometry volumes for which there are if(TVirtualMC::GetMC()->CurrentVolID()==XXX)
// statements in StepManager()
// Arguments: none
// Returns: none
AliDebug(1,"Start v2 HMPID.");
//InitProperties();
AliDebug(1,"Stop v2 HMPID.");
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::DefineOpticalProperties()
{
AliDebug(1,"");
// Optical properties definition.
const Int_t kNbins=30; //number of photon energy points
Float_t emin=5.5,emax=8.5; //Photon energy range,[eV]
Float_t deltaE = (emax - emin)/kNbins;
Float_t aEckov [kNbins];
Double_t dEckov [kNbins];
Float_t aAbsRad[kNbins], aAbsWin[kNbins], aAbsGap[kNbins], aAbsMet[kNbins];
Float_t aIdxRad[kNbins], aIdxWin[kNbins], aIdxGap[kNbins], aIdxMet[kNbins], aIdxPc[kNbins];
Float_t aQeAll [kNbins], aQePc [kNbins];
Double_t dReflMet[kNbins], dQePc[kNbins];
TF2 *pRaIF=new TF2("HidxRad","sqrt(1+0.554*(1239.84/x)^2/((1239.84/x)^2-5769)-0.0005*(y-20))" ,emin,emax,0,50); //DiMauro mail temp 0-50 degrees C
TF1 *pWiIF=new TF1("HidxWin","sqrt(1+46.411/(10.666*10.666-x*x)+228.71/(18.125*18.125-x*x))" ,emin,emax); //SiO2 idx TDR p.35
TF1 *pGaIF=new TF1("HidxGap","1+0.12489e-6/(2.62e-4 - x*x/1239.84/1239.84)" ,emin,emax); //?????? from where
TF1 *pRaAF=new TF1("HabsRad","(x<7.8)*(gaus+gaus(3))+(x>=7.8)*0.0001" ,emin,emax); //fit from DiMauro data 28.10.03
pRaAF->SetParameters(3.20491e16,-0.00917890,0.742402,3035.37,4.81171,0.626309);
TF1 *pWiAF=new TF1("HabsWin","(x<8.2)*(818.8638-301.0436*x+36.89642*x*x-1.507555*x*x*x)+(x>=8.2)*0.0001" ,emin,emax); //fit from DiMauro data 28.10.03
TF1 *pGaAF=new TF1("HabsGap","(x<7.75)*6512.399+(x>=7.75)*3.90743e-2/(-1.655279e-1+6.307392e-2*x-8.011441e-3*x*x+3.392126e-4*x*x*x)",emin,emax); //????? from where
TF1 *pQeF =new TF1("Hqe" ,"0+(x>6.07267)*0.344811*(1-exp(-1.29730*(x-6.07267)))" ,emin,emax); //fit from DiMauro data 28.10.03
TString title=GetTitle();
Bool_t isFlatIdx=title.Contains("FlatIdx");
for(Int_t i=0;i<kNbins;i++){
Float_t eV=emin+deltaE*i; //Ckov energy in eV
aEckov [i] =1e-9*eV; //Ckov energy in GeV
dEckov [i] = aEckov[i];
aAbsRad[i]=pRaAF->Eval(eV); (isFlatIdx)? aIdxRad[i]=1.292: aIdxRad[i]=pRaIF->Eval(eV,20);
aAbsWin[i]=pWiAF->Eval(eV); aIdxWin[i]=pWiIF->Eval(eV);
aAbsGap[i]=pGaAF->Eval(eV); aIdxGap[i]=pGaIF->Eval(eV);
aQeAll[i] =1; //QE for all other materials except for PC must be 1.
aAbsMet[i] =0.0001; aIdxMet[i]=0; //metal ref idx must be 0 in order to reflect photon
aIdxPc [i]=1; aQePc [i]=pQeF->Eval(eV); //PC ref idx must be 1 in order to apply photon to QE conversion
dQePc [i]= pQeF->Eval(eV);
dReflMet[i] = 0.; // no reflection on the surface of the pc (?)
}
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kC6F14] , kNbins, aEckov, aAbsRad , aQeAll , aIdxRad );
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kSiO2] , kNbins, aEckov, aAbsWin , aQeAll , aIdxWin );
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kCH4] , kNbins, aEckov, aAbsGap , aQeAll , aIdxGap );
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kCu] , kNbins, aEckov, aAbsMet , aQeAll , aIdxMet );
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kW] , kNbins, aEckov, aAbsMet , aQeAll , aIdxMet ); //n=0 means reflect photons
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kCsI] , kNbins, aEckov, aAbsMet , aQePc , aIdxPc ); //n=1 means convert photons
TVirtualMC::GetMC()->SetCerenkov((*fIdtmed)[kAl] , kNbins, aEckov, aAbsMet , aQeAll , aIdxMet );
// Define a skin surface for the photocatode to enable 'detection' in G4
for(Int_t i=0; i<7; i++){
TVirtualMC::GetMC()->DefineOpSurface(Form("surfPc%i",i), kGlisur /*kUnified*/,kDielectric_metal,kPolished, 0.);
TVirtualMC::GetMC()->SetMaterialProperty(Form("surfPc%i",i), "EFFICIENCY", kNbins, dEckov, dQePc);
TVirtualMC::GetMC()->SetMaterialProperty(Form("surfPc%i",i), "REFLECTIVITY", kNbins, dEckov, dReflMet);
TVirtualMC::GetMC()->SetSkinSurface(Form("skinPc%i",i), Form("Hpad%i",i),Form("surfPc%i",i)); }
delete pRaAF;delete pWiAF;delete pGaAF; delete pRaIF; delete pWiIF; delete pGaIF; delete pQeF;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Bool_t AliHMPIDv3::IsLostByFresnel()
{
// Calculate probability for the photon to be lost by Fresnel reflection.
TLorentzVector p4;
Double_t mom[3],localMom[3];
TVirtualMC::GetMC()->TrackMomentum(p4); mom[0]=p4(1); mom[1]=p4(2); mom[2]=p4(3);
localMom[0]=0; localMom[1]=0; localMom[2]=0;
TVirtualMC::GetMC()->Gmtod(mom,localMom,2);
Double_t localTc = localMom[0]*localMom[0]+localMom[2]*localMom[2];
Double_t localTheta = TMath::ATan2(TMath::Sqrt(localTc),localMom[1]);
Double_t cotheta = TMath::Abs(TMath::Cos(localTheta));
if(TVirtualMC::GetMC()->GetRandom()->Rndm() < Fresnel(p4.E()*1e9,cotheta,1)){
AliDebug(1,"Photon lost");
return kTRUE;
}else
return kFALSE;
}//IsLostByFresnel()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::GenFee(Float_t qtot)
{
// Generate FeedBack photons for the current particle. To be invoked from StepManager().
// eloss=0 means photon so only pulse height distribution is to be analysed.
TLorentzVector x4;
TVirtualMC::GetMC()->TrackPosition(x4);
Int_t iNphotons=TVirtualMC::GetMC()->GetRandom()->Poisson(0.02*qtot); //# of feedback photons is proportional to the charge of hit
AliDebug(1,Form("N photons=%i",iNphotons));
Int_t j;
Float_t cthf, phif, enfp = 0, sthf, e1[3], e2[3], e3[3], vmod, uswop,dir[3], phi,pol[3], mom[4];
//Generate photons
for(Int_t i=0;i<iNphotons;i++){//feedbacks loop
Double_t ranf[2];
TVirtualMC::GetMC()->GetRandom()->RndmArray(2,ranf); //Sample direction
cthf=ranf[0]*2-1.0;
if(cthf<0) continue;
sthf = TMath::Sqrt((1. - cthf) * (1. + cthf));
phif = ranf[1] * 2 * TMath::Pi();
if(Double_t randomNumber=TVirtualMC::GetMC()->GetRandom()->Rndm()<=0.57)
enfp = 7.5e-9;
else if(randomNumber<=0.7)
enfp = 6.4e-9;
else
enfp = 7.9e-9;
dir[0] = sthf * TMath::Sin(phif); dir[1] = cthf; dir[2] = sthf * TMath::Cos(phif);
TVirtualMC::GetMC()->Gdtom(dir, mom, 2);
mom[0]*=enfp; mom[1]*=enfp; mom[2]*=enfp;
mom[3] = TMath::Sqrt(mom[0]*mom[0]+mom[1]*mom[1]+mom[2]*mom[2]);
// Polarisation
e1[0]= 0; e1[1]=-dir[2]; e1[2]= dir[1];
e2[0]=-dir[1]; e2[1]= dir[0]; e2[2]= 0;
e3[0]= dir[1]; e3[1]= 0; e3[2]=-dir[0];
vmod=0;
for(j=0;j<3;j++) vmod+=e1[j]*e1[j];
if (!vmod) for(j=0;j<3;j++) {
uswop=e1[j];
e1[j]=e3[j];
e3[j]=uswop;
}
vmod=0;
for(j=0;j<3;j++) vmod+=e2[j]*e2[j];
if (!vmod) for(j=0;j<3;j++) {
uswop=e2[j];
e2[j]=e3[j];
e3[j]=uswop;
}
vmod=0; for(j=0;j<3;j++) vmod+=e1[j]*e1[j]; vmod=TMath::Sqrt(1/vmod); for(j=0;j<3;j++) e1[j]*=vmod;
vmod=0; for(j=0;j<3;j++) vmod+=e2[j]*e2[j]; vmod=TMath::Sqrt(1/vmod); for(j=0;j<3;j++) e2[j]*=vmod;
phi = TVirtualMC::GetMC()->GetRandom()->Rndm()* 2 * TMath::Pi();
for(j=0;j<3;j++) pol[j]=e1[j]*TMath::Sin(phi)+e2[j]*TMath::Cos(phi);
TVirtualMC::GetMC()->Gdtom(pol, pol, 2);
Int_t outputNtracksStored;
gAlice->GetMCApp()->PushTrack(1, //transport
gAlice->GetMCApp()->GetCurrentTrackNumber(),//parent track
50000051, //PID
mom[0],mom[1],mom[2],mom[3], //track momentum
x4.X(),x4.Y(),x4.Z(),x4.T(), //track origin
pol[0],pol[1],pol[2], //polarization
kPFeedBackPhoton, //process ID
outputNtracksStored, //on return how many new photons stored on stack
1.0); //weight
}//feedbacks loop
AliDebug(1,"Stop.");
}//GenerateFeedbacks()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::Hits2SDigits()
{
// Interface method ivoked from AliSimulation to create a list of sdigits corresponding to list of hits. Every hit generates one or more sdigits.
// Arguments: none
// Returns: none
AliDebug(1,"Start.");
for(Int_t iEvt=0;iEvt < GetLoader()->GetRunLoader()->GetNumberOfEvents();iEvt++){ //events loop
GetLoader()->GetRunLoader()->GetEvent(iEvt); //get next event
if(!GetLoader()->TreeH()) {GetLoader()->LoadHits(); }
if(!GetLoader()->TreeS()) {GetLoader()->MakeTree("S"); MakeBranch("S");}//to
for(Int_t iEnt=0;iEnt<GetLoader()->TreeH()->GetEntries();iEnt++){//prims loop
GetLoader()->TreeH()->GetEntry(iEnt);
Hit2Sdi(Hits(),SdiLst());
}//prims loop
GetLoader()->TreeS()->Fill();
GetLoader()->WriteSDigits("OVERWRITE");
SdiReset();
}//events loop
GetLoader()->UnloadHits();
GetLoader()->UnloadSDigits();
AliDebug(1,"Stop.");
}//Hits2SDigits()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::Hit2Sdi(TClonesArray *pHitLst,TClonesArray *pSdiLst)
{
// Converts list of hits to list of sdigits.
// Arguments: pHitLst - list of hits provided not empty
// pSDigLst - list of sdigits where to store the results
// Returns: none
for(Int_t iHit=0;iHit<pHitLst->GetEntries();iHit++){ //hits loop
AliHMPIDHit *pHit=(AliHMPIDHit*)pHitLst->At(iHit); //get pointer to current hit
pHit->Hit2Sdi(pSdiLst); //convert this hit to list of sdigits
}//hits loop loop
}//Hits2Sdi()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::Digits2Raw()
{
// Interface method invoked by AliSimulation to create raw data streams from digits. Events loop is done in AliSimulation
// Arguments: none
// Returns: none
AliDebug(1,"Start.");
GetLoader()->LoadDigits();
TTree * treeD = GetLoader()->TreeD();
if(!treeD) {
AliError("No digits tree!");
return;
}
treeD->GetEntry(0);
AliHMPIDRawStream *pRS=0x0;
pRS->WriteRaw(DigLst());
GetLoader()->UnloadDigits();
AliDebug(1,"Stop.");
}//Digits2Raw()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Float_t AliHMPIDv3::Fresnel(Float_t ene,Float_t pdoti, Bool_t pola)
{
// Correction for Fresnel ???????????
// Arguments: ene - photon energy [GeV],
// PDOTI=COS(INC.ANG.), PDOTR=COS(POL.PLANE ROT.ANG.)
// Returns:
Float_t en[36] = {5.0,5.1,5.2,5.3,5.4,5.5,5.6,5.7,5.8,5.9,6.0,6.1,6.2,
6.3,6.4,6.5,6.6,6.7,6.8,6.9,7.0,7.1,7.2,7.3,7.4,7.5,7.6,7.7,
7.8,7.9,8.0,8.1,8.2,8.3,8.4,8.5};
Float_t csin[36] = {2.14,2.21,2.33,2.48,2.76,2.97,2.99,2.59,2.81,3.05,
2.86,2.53,2.55,2.66,2.79,2.96,3.18,3.05,2.84,2.81,2.38,2.11,
2.01,2.13,2.39,2.73,3.08,3.15,2.95,2.73,2.56,2.41,2.12,1.95,
1.72,1.53};
Float_t csik[36] = {0.,0.,0.,0.,0.,0.196,0.408,0.208,0.118,0.49,0.784,0.543,
0.424,0.404,0.371,0.514,0.922,1.102,1.139,1.376,1.461,1.253,0.878,
0.69,0.612,0.649,0.824,1.347,1.571,1.678,1.763,1.857,1.824,1.824,
1.714,1.498};
Float_t xe=ene;
Int_t j=Int_t(xe*10)-49;
Float_t cn=csin[j]+((csin[j+1]-csin[j])/0.1)*(xe-en[j]);
Float_t ck=csik[j]+((csik[j+1]-csik[j])/0.1)*(xe-en[j]);
//FORMULAE FROM HANDBOOK OF OPTICS, 33.23 OR
//W.R. HUNTER, J.O.S.A. 54 (1964),15 , J.O.S.A. 55(1965),1197
Float_t sinin=TMath::Sqrt((1.-pdoti)*(1.+pdoti));
Float_t tanin=sinin/pdoti;
Float_t c1=cn*cn-ck*ck-sinin*sinin;
Float_t c2=4*cn*cn*ck*ck;
Float_t aO=TMath::Sqrt(0.5*(TMath::Sqrt(c1*c1+c2)+c1));
Float_t b2=0.5*(TMath::Sqrt(c1*c1+c2)-c1);
Float_t rs=((aO-pdoti)*(aO-pdoti)+b2)/((aO+pdoti)*(aO+pdoti)+b2);
Float_t rp=rs*((aO-sinin*tanin)*(aO-sinin*tanin)+b2)/((aO+sinin*tanin)*(aO+sinin*tanin)+b2);
//CORRECTION FACTOR FOR SURFACE ROUGHNESS
//B.J. STAGG APPLIED OPTICS, 30(1991),4113
Float_t sigraf=18.;
Float_t lamb=1240/ene;
Float_t fresn;
Float_t rO=TMath::Exp(-(4*TMath::Pi()*pdoti*sigraf/lamb)*(4*TMath::Pi()*pdoti*sigraf/lamb));
if(pola)
{
Float_t pdotr=0.8; //DEGREE OF POLARIZATION : 1->P , -1->S
fresn=0.5*(rp*(1+pdotr)+rs*(1-pdotr));
}
else
fresn=0.5*(rp+rs);
fresn = fresn*rO;
return fresn;
}//Fresnel()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::Print(Option_t *option)const
{
// Debug printout
TObject::Print(option);
}//void AliHMPID::Print(Option_t *option)const
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Bool_t AliHMPIDv3::Raw2SDigits(AliRawReader *pRR)
{
// Arguments: pRR- raw reader
// Returns: kTRUE on success (currently ignored in AliSimulation::ConvertRaw2SDigits())
//AliHMPIDDigit sdi; //tmp sdigit, raw digit will be converted to it
if(!GetLoader()->TreeS()) {MakeTree("S"); MakeBranch("S");}
TClonesArray *pSdiLst=SdiLst(); Int_t iSdiCnt=0; //tmp list of sdigits for all chambers
AliHMPIDRawStream stream(pRR);
while(stream.Next())
{
for(Int_t iPad=0;iPad<stream.GetNPads();iPad++) {
AliHMPIDDigit sdi(stream.GetPadArray()[iPad],stream.GetChargeArray()[iPad]);
new((*pSdiLst)[iSdiCnt++]) AliHMPIDDigit(sdi); //add this digit to the tmp list
}
}
GetLoader()->TreeS()->Fill(); GetLoader()->WriteSDigits("OVERWRITE");//write out sdigits
SdiReset();
return kTRUE;
}//Raw2SDigits
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::StepCount()
{
// Count number of ckovs created
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::StepHistory()
{
// This methode is invoked from StepManager() in order to print out
static Int_t iStepN;
const char *sParticle;
switch(TVirtualMC::GetMC()->TrackPid()){
case kProton: sParticle="PROTON" ;break;
case kNeutron: sParticle="neutron" ;break;
case kGamma: sParticle="gamma" ;break;
case 50000050: sParticle="CKOV" ;break;
case kPi0: sParticle="Pi0" ;break;
case kPiPlus: sParticle="Pi+" ;break;
case kPiMinus: sParticle="Pi-" ;break;
case kElectron: sParticle="electron" ;break;
default: sParticle="not known" ;break;
}
TString flag="fanny combination";
if(TVirtualMC::GetMC()->IsTrackAlive()) {
if(TVirtualMC::GetMC()->IsTrackEntering()) flag="enters to";
else if(TVirtualMC::GetMC()->IsTrackExiting()) flag="exits from";
else if(TVirtualMC::GetMC()->IsTrackInside()) flag="inside";
} else {
if(TVirtualMC::GetMC()->IsTrackStop()) flag="stopped in";
}
Int_t vid=0,copy=0;
TString path=TVirtualMC::GetMC()->CurrentVolName(); path.Prepend("-");path.Prepend(TVirtualMC::GetMC()->CurrentVolOffName(1));//current volume and his mother are always there
vid=TVirtualMC::GetMC()->CurrentVolOffID(2,copy); if(vid) {path.Prepend("-");path.Prepend(TVirtualMC::GetMC()->VolName(vid));}
vid=TVirtualMC::GetMC()->CurrentVolOffID(3,copy); if(vid) {path.Prepend("-");path.Prepend(TVirtualMC::GetMC()->VolName(vid));}
Printf("Step %i: %s (%i) %s %s m=%.6f GeV q=%.1f dEdX=%.4f Etot=%.4f",iStepN,sParticle,TVirtualMC::GetMC()->TrackPid(),flag.Data(),path.Data(),TVirtualMC::GetMC()->TrackMass(),TVirtualMC::GetMC()->TrackCharge(),TVirtualMC::GetMC()->Edep()*1e9,TVirtualMC::GetMC()->Etot());
Double_t gMcTrackPos[3]; TVirtualMC::GetMC()->TrackPosition(gMcTrackPos[0],gMcTrackPos[1],gMcTrackPos[2]);
Double_t gMcTrackPosLoc[3]; TVirtualMC::GetMC()->Gmtod(gMcTrackPos,gMcTrackPosLoc,1);
Printf("TVirtualMC::GetMC() Track Position (MARS) x: %5.3lf, y: %5.3lf, z: %5.3lf (r: %5.3lf) ---> (LOC) x: %5.3f, y: %5.3f, z: %5.3f",gMcTrackPos[0],gMcTrackPos[1],gMcTrackPos[2],TMath::Sqrt(gMcTrackPos[0]*gMcTrackPos[0]+gMcTrackPos[1]*gMcTrackPos[1]+gMcTrackPos[2]*gMcTrackPos[2]),gMcTrackPosLoc[0],gMcTrackPosLoc[1],gMcTrackPosLoc[2]);
Printf("Step %i: tid=%i flags alive=%i disap=%i enter=%i exit=%i inside=%i out=%i stop=%i new=%i",
iStepN, gAlice->GetMCApp()->GetCurrentTrackNumber(),
TVirtualMC::GetMC()->IsTrackAlive(), TVirtualMC::GetMC()->IsTrackDisappeared(),TVirtualMC::GetMC()->IsTrackEntering(), TVirtualMC::GetMC()->IsTrackExiting(),
TVirtualMC::GetMC()->IsTrackInside(),TVirtualMC::GetMC()->IsTrackOut(), TVirtualMC::GetMC()->IsTrackStop(), TVirtualMC::GetMC()->IsNewTrack());
Float_t a,z,den,rad,abs; a=z=den=rad=abs=-1;
Int_t mid=TVirtualMC::GetMC()->CurrentMaterial(a,z,den,rad,abs);
Printf("Step %i: mid=%i a=%7.2f z=%7.2f den=%9.4f rad=%9.2f abs=%9.2f\n\n",iStepN,mid,a,z,den,rad,abs);
TArrayI proc; TVirtualMC::GetMC()->StepProcesses(proc);
Printf("Processes in this step:");
for ( int i = 0 ; i < proc.GetSize(); i++)
{
Printf("%s",TMCProcessName[proc.At(i)]);
}
Printf("End process list");
iStepN++;
}//StepHistory()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::StepManager()
{
// Full Step Manager.
// Arguments: none
// Returns: none
// StepHistory(); return; //uncomment to print tracks history
// StepCount(); return; //uncomment to count photons
TString volname = fMC->CurrentVolName();
//Treat photons
if((fMC->TrackPid()==50000050||fMC->TrackPid()==50000051)&&volname.Contains("Hpad")){ //photon (Ckov or feedback) hits on module PC (Hpad)
if(fMC->Edep()>0){ //photon survided QE test i.e. produces electron
if(IsLostByFresnel()){ fMC->StopTrack(); return;} //photon lost due to fersnel reflection on PC
Int_t tid= fMC->GetStack()->GetCurrentTrackNumber(); //take TID
Int_t pid= fMC->TrackPid(); //take PID
Float_t etot= fMC->Etot(); //total hpoton energy, [GeV]
Double_t x[3]; fMC->TrackPosition(x[0],x[1],x[2]); //take MARS position at entrance to PC
Float_t hitTime= (Float_t)fMC->TrackTime(); //hit formation time
TString tmpname = volname; tmpname.Remove(0,4); Int_t idch = tmpname.Atoi(); //retrieve the chamber number
Float_t xl,yl; AliHMPIDParam::Instance()->Mars2Lors(idch,x,xl,yl); //take LORS position
new((*fHits)[fNhits++])AliHMPIDHit(idch,etot,pid,tid,xl,yl,hitTime,x); //HIT for photon, position at P, etot will be set to Q
if(fDoFeed) GenFee(etot); //generate feedback photons etot is modified in hit ctor to Q of hit
}//photon hit PC and DE >0
}//photon hit PC
//Treat charged particles
static Float_t eloss; //need to store mip parameters between different steps
static Double_t in[3];
if(fMC->IsTrackEntering() && fMC->TrackCharge() && volname.Contains("Hpad")) //Trackref stored when entering in the pad volume
AddTrackReference(fMC->GetStack()->GetCurrentTrackNumber(), AliTrackReference::kHMPID); //for acceptance calculations
if(fMC->TrackCharge() && volname.Contains("Hcel")){ //charged particle in amplification gap (Hcel)
if(fMC->IsTrackEntering()||fMC->IsNewTrack()) { //entering or newly created
eloss=0; //reset Eloss collector
fMC->TrackPosition(in[0],in[1],in[2]); //take position at the entrance
}else if(fMC->IsTrackExiting()||fMC->IsTrackStop()||fMC->IsTrackDisappeared()){ //exiting or disappeared
eloss +=fMC->Edep(); //take into account last step Eloss
Int_t tid= fMC->GetStack()->GetCurrentTrackNumber(); //take TID
Int_t pid= fMC->TrackPid(); //take PID
Double_t out[3]; fMC->TrackPosition(out[0],out[1],out[2]); //take MARS position at exit
Float_t hitTime= (Float_t)fMC->TrackTime(); //hit formation time
out[0]=0.5*(out[0]+in[0]); //
out[1]=0.5*(out[1]+in[1]); //take hit position at the anod plane
out[2]=0.5*(out[2]+in[2]);
TString tmpname = volname; tmpname.Remove(0,4); Int_t idch = tmpname.Atoi(); //retrieve the chamber number
Float_t xl,yl;AliHMPIDParam::Instance()->Mars2Lors(idch,out,xl,yl); //take LORS position
if(eloss>0) {
new((*fHits)[fNhits++])AliHMPIDHit(idch,eloss,pid,tid,xl,yl,hitTime,out); //HIT for MIP, position near anod plane, eloss will be set to Q
if(fDoFeed) GenFee(eloss); //generate feedback photons
eloss=0;
}
}else //just going inside
eloss += fMC->Edep(); //collect this step eloss
}//MIP in GAP
}//StepManager()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::TestPoint(Int_t ch,Float_t x,Float_t y)
{
// Utility method to check the validity of geometry by poviding some crucial points
// Arguments: ch,x,y- crucial point definition (cm) in LORS
// Returns: none
Double_t mars[3];
AliHMPIDParam::Instance()->Lors2Mars(ch,x,y,mars);
Printf("(ch=%i,locX=%.2f,locY=%.2f) %s",ch,x,y,gGeoManager->FindNode(mars[0],mars[1],mars[2])->GetName());
}//TestPoint()
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::TestGeom()
{
//
// Test method to check geometry
//
//TGeoManager::Import("misaligned_geometry.root");
TGeoManager::Import("geometry.root");
for(Int_t ch=AliHMPIDParam::kMinCh;ch<=AliHMPIDParam::kMaxCh;ch++)
TestPoint(ch,0,0);
}//TestPoint()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void AliHMPIDv3::IdealPosition(Int_t iCh,TGeoHMatrix *pMatrix) //ideal position of given chamber
{
// Construct ideal position matrix for a given chamber
// Arguments: iCh- chamber ID; pMatrix- pointer to precreated unity matrix where to store the results
// Returns: none
const Double_t kAngHor=19.5; // horizontal angle between chambers 19.5 grad
const Double_t kAngVer=20; // vertical angle between chambers 20 grad
const Double_t kAngCom=30; // common HMPID rotation with respect to x axis 30 grad
const Double_t kTrans[3]={490,0,0}; // center of the chamber is on window-gap surface
pMatrix->RotateY(90); // rotate around y since initial position is in XY plane -> now in YZ plane
pMatrix->SetTranslation(kTrans); // now plane in YZ is shifted along x
switch(iCh){
case 0: pMatrix->RotateY(kAngHor); pMatrix->RotateZ(-kAngVer); break; //right and down
case 1: pMatrix->RotateZ(-kAngVer); break; //down
case 2: pMatrix->RotateY(kAngHor); break; //right
case 3: break; //no rotation
case 4: pMatrix->RotateY(-kAngHor); break; //left
case 5: pMatrix->RotateZ(kAngVer); break; //up
case 6: pMatrix->RotateY(-kAngHor); pMatrix->RotateZ(kAngVer); break; //left and up
}
pMatrix->RotateZ(kAngCom); //apply common rotation in XY plane
}
void AliHMPIDv3::IdealPositionCradle(Int_t iCh,TGeoHMatrix *pMatrix) //ideal position of given one module of the cradle
{
// Construct ideal position matrix for a given module cradle
// Arguments: iCh- chamber ID; pMatrix- pointer to precreated unity matrix where to store the results
// Returns: none
const Double_t kAngHor=19.5; // horizontal angle between chambers 19.5 grad
const Double_t kAngVer=20; // vertical angle between chambers 20 grad
const Double_t kAngCom=30; // common HMPID rotation with respect to x axis 30 grad
const Double_t kTrans[3]={423.+ 29,0,67}; // z-center of the cradle module
pMatrix->RotateY(90); // rotate around y since initial position is in XY plane -> now in YZ plane
pMatrix->SetTranslation(kTrans); // now plane in YZ is shifted along x
switch(iCh){
case 0: pMatrix->RotateY(kAngHor); pMatrix->RotateZ(-kAngVer); break; //right and down
case 1: pMatrix->RotateZ(-kAngVer); break; //down
case 2: pMatrix->RotateY(kAngHor); break; //right
case 3: break; //no rotation
case 4: pMatrix->RotateY(-kAngHor); break; //left
case 5: pMatrix->RotateZ(kAngVer); break; //up
case 6: pMatrix->RotateY(-kAngHor); pMatrix->RotateZ(kAngVer); break; //left and up
}
pMatrix->RotateZ(kAngCom); //apply common rotation in XY plane
}
TGeoVolume* AliHMPIDv3::CreateCradle()
{
//Method that builds the Cradle geometry
//according to the base topology created
//in CradleBaseVolume(...)
Double_t mm = 0.1;
Double_t params[10]={0.5,10.,24.,-1,5.2,1.5,3.5,8.5,3.8,0.};
TGeoMedium *med =gGeoManager->GetMedium("HMPID_Al");
TGeoVolume *cradle=new TGeoVolumeAssembly("Hcradle");
//Double_t baselong[7]={6037*mm-2*60*mm, 6037*mm-2*60*mm,60*mm,0.,100*mm,10*mm,10*mm};//2CRE2112P3
Double_t baselong[7]={6037*mm-2*100*mm, 6037*mm-2*100*mm,60*mm,0.,100*mm,10*mm,10*mm};//2CRE2112P3
TGeoVolume *lbase = CradleBaseVolume(med,baselong,"cradleLbase");
lbase->SetLineColor(kGray);
Double_t baseshort[7]={1288.*mm+2*100*mm, 1288.*mm+2*100*mm,60*mm,0.,100*mm,10*mm,10*mm};//2CRE2112P3
TGeoVolume *sbase = CradleBaseVolume(med,baseshort,"cradleSbase");
sbase->SetLineColor(kGray);
//one side
Double_t height = 30.*mm; //30 = 2*(1488/2-729) (2CRE2112P3)
Double_t tubeheight = 50.*mm; Double_t heightred = 5.*mm; Double_t zred = 5.*mm;
Double_t oneshift = tubeheight/TMath::Tan(TMath::DegToRad()*20.)+(1458.-35)*mm/2 - (1607-35)*mm/2;
Double_t linclined[7] = {1458.*mm-params[6]-0.5,1607.*mm-params[6]-0.5,tubeheight,oneshift, height ,heightred,zred}; //3.5 is for not correct measurements in 2CRE2112P3<=> 597!=inclined*sin(20)
TGeoVolume *inclin = CradleBaseVolume(med,linclined,"inclinedbar");
inclin->SetLineColor(kGray);
Double_t lhorizontal[7] = {1641.36*mm+params[7],1659.*mm+params[7],tubeheight,0, height ,heightred,zred};
TGeoVolume *horiz = CradleBaseVolume(med,lhorizontal,"horizontalbar");
horiz->SetLineColor(kGray);
//inner bars, they are named as the numbering in 2CRE2112P3
Double_t fourshift = tubeheight/TMath::Tan(TMath::DegToRad()*55.);
Double_t lfour[7] = {592*mm,592*mm,tubeheight,fourshift,height,heightred,zred};
TGeoVolume *four = CradleBaseVolume(med,lfour,"bar4");
four->SetLineColor(kGray);
Double_t fiveshift = tubeheight/TMath::Tan(TMath::DegToRad()*75);
Double_t lfive[7] = {500.*mm,500.*mm,tubeheight,fiveshift,height,heightred,zred};
TGeoVolume *five = CradleBaseVolume(med,lfive,"bar5");
five->SetLineColor(kGray);
Double_t sixshift = tubeheight/TMath::Tan(TMath::DegToRad()*55)+459*mm/2-480*mm/2;
Double_t lsix[7] = {456*mm,477*mm,tubeheight,sixshift,height,heightred,zred};
TGeoVolume *six = CradleBaseVolume(med,lsix,"bar6");
six->SetLineColor(kGray);
Double_t sevenshift = tubeheight/TMath::Tan(TMath::DegToRad()*50)+472*mm/2-429.*mm/2;
Double_t lseven[7] = {429*mm,472*mm,tubeheight,sevenshift,height,heightred,zred};
TGeoVolume *seven = CradleBaseVolume(med,lseven,"bar7");
seven->SetLineColor(kGray);
Double_t eightshift = tubeheight/TMath::Tan(TMath::DegToRad()*30)+244.*mm/2-200.*mm/2 -3;
Double_t leight[7] = {200.*mm,244.*mm,tubeheight,eightshift,height,heightred,zred};
TGeoVolume *eight = CradleBaseVolume(med,leight,"bar8");
eight->SetLineColor(kGray);
Double_t nineshift = -tubeheight/TMath::Tan(TMath::DegToRad()*71)+83.*mm/2-66.*mm/2;
Double_t lnine[7] = {59.5*mm,76.5*mm,tubeheight,nineshift,height,heightred,zred};
TGeoVolume *nine = CradleBaseVolume(med,lnine,"bar9");
nine->SetLineColor(kGray);
Double_t tenshift = (-tubeheight/TMath::Tan(TMath::DegToRad()*60) -221.*mm/2+195.*mm/2);
Double_t lten[7] = {195.*mm,221.*mm,tubeheight,tenshift,height,heightred,zred};
TGeoVolume *ten = CradleBaseVolume(med,lten,"bar10");
ten->SetLineColor(kGray);
Double_t elevenshift = (-tubeheight/TMath::Tan(TMath::DegToRad()*70) -338.*mm/2+315.*mm/2);
Double_t leleven[7] = {308.*mm,331.*mm,tubeheight,elevenshift,height,heightred,zred};
TGeoVolume *eleven = CradleBaseVolume(med,leleven,"bar11");
eleven->SetLineColor(kGray);
Double_t twelveshift = (-tubeheight/TMath::Tan(TMath::DegToRad()*60) -538.*mm/2+508.*mm/2);
Double_t ltwelve[7] = {507.*mm,537.*mm,tubeheight,twelveshift,height,heightred,zred};
TGeoVolume *twelve = CradleBaseVolume(med,ltwelve,"bar12");
twelve->SetLineColor(kGray);
Double_t thirteenshift = tubeheight/TMath::Tan(TMath::DegToRad()*43);
Double_t lthirteen[7] = {708.*mm,708.*mm,tubeheight,thirteenshift,height,heightred,zred};
TGeoVolume *thirteen = CradleBaseVolume(med,lthirteen,"bar13");
thirteen->SetLineColor(kGray);
//vertical rectangles
TGeoVolume *vbox= new TGeoVolumeAssembly("Hvbox");
vbox->SetLineColor(kViolet);
Double_t width = 50.*mm;
TGeoVolume *vboxlast= new TGeoVolumeAssembly("Hvboxlast");//vertical structure on the short base
vboxlast->SetLineColor(kViolet);
Double_t barheight = 100.*mm;
Double_t lAfourteen[7] = {1488.*mm,1488.*mm,barheight,0,width,heightred,zred};
TGeoVolume *afourteen = CradleBaseVolume(med,lAfourteen,"bar14top");
afourteen->SetLineColor(kGray);
Double_t lBfourteen[7] = {387*mm,387.*mm,barheight,0,width,heightred,zred};
TGeoVolume *bfourteen = CradleBaseVolume(med,lBfourteen,"bar14vert");
bfourteen->SetLineColor(kGray);
Double_t lCfourteen[7] = {1288.*mm,1288.*mm,barheight,0,width,heightred,zred};
TGeoVolume *cfourteen = CradleBaseVolume(med,lCfourteen,"bar14bot");
cfourteen->SetLineColor(kGray);
Double_t oblshift = 50.*mm/ TMath::Tan(TMath::DegToRad()*35);
Double_t lDfourteen[7] = {603.*mm,603.*mm,50.*mm,oblshift,width,heightred,zred};
TGeoVolume *dfourteen = CradleBaseVolume(med,lDfourteen,"bar14incl");
dfourteen->SetLineColor(kGray);
Double_t lDfourteenlast[7] = {667.*mm,667.*mm,50.*mm,oblshift,width,heightred,zred};
TGeoVolume *dfourteenlast = CradleBaseVolume(med,lDfourteenlast,"bar14incllast");
dfourteenlast->SetLineColor(kGray);
vbox->AddNode(afourteen,1,new TGeoTranslation(0.,487.*mm/2 -100.*mm/2,0.));
TGeoRotation *vinrot = new TGeoRotation("vertbar"); vinrot->RotateZ(90);
vbox->AddNode(bfourteen,1,new TGeoCombiTrans(1488*mm/2-100.*mm/2,-100.*mm/2,0.,vinrot));
vbox->AddNode(bfourteen,2,new TGeoCombiTrans(-1488*mm/2+100.*mm/2,-100.*mm/2,0.,vinrot));
TGeoRotation *rotboxbar = new TGeoRotation("rotboxbar"); rotboxbar->RotateZ(-35);
TGeoRotation *arotboxbar = new TGeoRotation("arotboxbar"); arotboxbar->RotateZ(-35); arotboxbar->RotateY(180);
vbox->AddNode(dfourteen,1,new TGeoCombiTrans(-1488*mm/4,-1,0.4,rotboxbar));
vbox->AddNode(dfourteen,2,new TGeoCombiTrans(+1488*mm/4,-1,0.4,arotboxbar));
//vertical box on the short base of the cradle
vboxlast->AddNode(afourteen,1,new TGeoTranslation(0.,487.*mm/2 -100.*mm/2,0.));
vboxlast->AddNode(bfourteen,1,new TGeoCombiTrans(1488*mm/2-100.*mm/2,-100.*mm/2,0.,vinrot));
vboxlast->AddNode(bfourteen,2,new TGeoCombiTrans(-1488*mm/2+100.*mm/2,-100.*mm/2,0.,vinrot));
vboxlast->AddNode(dfourteenlast,1,new TGeoCombiTrans(-1488*mm/4+1.7,-3.,0.,rotboxbar));
vboxlast->AddNode(dfourteenlast,2,new TGeoCombiTrans(+1488*mm/4-1.7,-3.,0.,arotboxbar));
//POSITIONING IN THE VIRTUAL VOLUME "cradle"
//long base
TGeoRotation *rotl=new TGeoRotation("Clongbase"); rotl->RotateX(90);
cradle->AddNode(lbase,0,new TGeoCombiTrans ( 0*mm, (1488-100)*mm/2, -(597-60)*mm/2,rotl));
cradle->AddNode(lbase,1,new TGeoCombiTrans ( 0*mm, -(1488-100)*mm/2, -(597-60)*mm/2,rotl));
//short base
TGeoRotation *rots=new TGeoRotation("Cshortbase"); rots->RotateX(90); rots->RotateZ(90);
cradle->AddNode(sbase,1,new TGeoCombiTrans ((6037-100)*mm/2, 0.,-(597-60)*mm/2,rots));
cradle->AddNode(sbase,2,new TGeoCombiTrans (-(6037-100)*mm/2, 0.,-(597-60)*mm/2,rots));
//trapezoidal structure
Double_t origintrapstructure = (6037-2*60)*mm/2 - 2288*mm;
TGeoRotation *rot1=new TGeoRotation("inclrot"); rot1->RotateX(90); rot1->RotateY(200);
TGeoRotation *rot2=new TGeoRotation("horizrot"); rot2->RotateX(-90);
Double_t dx =(1607-35)*mm*TMath::Cos(TMath::DegToRad()*20)/2-tubeheight/2*TMath::Sin(TMath::DegToRad()*20)+params[5];
cradle->AddNode(inclin,1,new TGeoCombiTrans(origintrapstructure + (2288+60)*mm -dx,729*mm,params[0]+0.4,rot1));//+0.7 added
cradle->AddNode(horiz,1,new TGeoCombiTrans( origintrapstructure,729*mm, 597*mm/2 - tubeheight/2,rot2));//correctly positioned
TGeoRotation *rot1mirror=new TGeoRotation("inclmirrot"); rot1mirror->RotateX(90); rot1mirror->RotateY(200); rot1mirror->RotateZ(180);
cradle->AddNode(inclin,2,new TGeoCombiTrans(origintrapstructure - 2345*mm + dx,729*mm,params[0]+0.4,rot1mirror));//+0.7 added
cradle->AddNode(inclin,3,new TGeoCombiTrans(origintrapstructure + (2288+60)*mm -dx,-729*mm,params[0]+0.4,rot1));//0.7 added
cradle->AddNode(horiz,2,new TGeoCombiTrans( origintrapstructure,-729*mm, 597*mm/2 - tubeheight/2,rot2));//correctly positioned
cradle->AddNode(inclin,4,new TGeoCombiTrans(origintrapstructure - 2345*mm + dx,-729*mm,params[0]+0.4,rot1mirror));//0.7 added
//inner pieces on one side
TGeoRotation *rot4=new TGeoRotation("4rot"); rot4->RotateX(-90); rot4->RotateY(-55); rot4->RotateZ(180);
TGeoRotation *rot4a=new TGeoRotation("4arot"); rot4a->RotateX(-90); rot4a->RotateY(-55);
cradle->AddNode(four,1,new TGeoCombiTrans(origintrapstructure -(39+(597-50-60)/(2*TMath::Tan(TMath::DegToRad()*55)))*mm- tubeheight/(2*TMath::Sin(TMath::DegToRad()*55)),-729*mm,params[3],rot4));
cradle->AddNode(four,2,new TGeoCombiTrans(origintrapstructure +(39+(597-50-60)/(2*TMath::Tan(TMath::DegToRad()*55)))*mm+tubeheight/(2*TMath::Sin(TMath::DegToRad()*55)),-729*mm,params[3],rot4a));
TGeoRotation *rot5=new TGeoRotation("5rot"); rot5->RotateX(-90); rot5->RotateY(-75); rot5->RotateZ(180);
TGeoRotation *rot5a=new TGeoRotation("5arot"); rot5a->RotateX(-90); rot5a->RotateY(-75);
cradle->AddNode(five,1,new TGeoCombiTrans(origintrapstructure +(486+(597-50-60)/(2*TMath::Tan(TMath::DegToRad()*75)))*mm +tubeheight/(2*TMath::Sin(TMath::DegToRad()*75)),-729*mm,0,rot5));
cradle->AddNode(five,2,new TGeoCombiTrans(origintrapstructure -(486+(597-50-60)/(2*TMath::Tan(TMath::DegToRad()*75)))*mm - tubeheight/(2*TMath::Sin(TMath::DegToRad()*75)),-729*mm,0,rot5a));
cradle->AddNode(six,1,new TGeoCombiTrans(origintrapstructure+808*mm+(480*mm/2)*TMath::Cos(TMath::DegToRad()*55)+tubeheight/(2*TMath::Sin(TMath::DegToRad()*55)) +
2.,-729*mm,-params[4]-0.5,rot4a));
cradle->AddNode(six,2,new TGeoCombiTrans(origintrapstructure-808*mm-(480*mm/2)*TMath::Cos(TMath::DegToRad()*55)-tubeheight/(2*TMath::Sin(TMath::DegToRad()*55))
-2.,-729*mm,-params[4]-0.5,rot4));
TGeoRotation *rot7=new TGeoRotation("7rot"); rot7->RotateX(-90); rot7->RotateY(130); rot7->RotateZ(180);
TGeoRotation *rot7a=new TGeoRotation("7arot"); rot7a->RotateX(-90); rot7a->RotateY(130);
cradle->AddNode(seven,1,new TGeoCombiTrans(origintrapstructure+1478*mm-(472*mm/2)*TMath::Cos(TMath::DegToRad()*50)+tubeheight/(2*TMath::Sin(TMath::DegToRad()*50)),-729*mm,-params[8],rot7));
cradle->AddNode(seven,2,new
TGeoCombiTrans(origintrapstructure-1478*mm+(472*mm/2)*TMath::Cos(TMath::DegToRad()*50)-tubeheight/(2*TMath::Sin(TMath::DegToRad()*50)),-729*mm,-params[8],rot7a));
TGeoRotation *rot8=new TGeoRotation("8rot"); rot8->RotateX(-90); rot8->RotateY(-25);
TGeoRotation *rot8a=new TGeoRotation("8arot"); rot8a->RotateX(-90); rot8a->RotateY(-25); rot8a->RotateZ(180);
cradle->AddNode(eight,1,new TGeoCombiTrans(origintrapstructure+1640*mm+(244*mm/2)*TMath::Cos(TMath::DegToRad()*30)+tubeheight/(2*TMath::Sin(TMath::DegToRad()*30)),-729*mm,-20.5,rot8));
cradle->AddNode(eight,2,new
TGeoCombiTrans(origintrapstructure-1640*mm-(244*mm/2)*TMath::Cos(TMath::DegToRad()*30)-tubeheight/(2*TMath::Sin(TMath::DegToRad()*30)),-729*mm,-20.5,rot8a));
TGeoRotation *rot9=new TGeoRotation("9rot"); rot9->RotateX(-90); rot9->RotateY(-90);
TGeoRotation *rot9a=new TGeoRotation("9arot"); rot9a->RotateX(-90); rot9a->RotateY(-90); rot9a->RotateZ(180);
cradle->AddNode(nine,1,new TGeoCombiTrans(origintrapstructure+1960*mm+2.5+3.,-729.*mm,-20.,rot9));
cradle->AddNode(nine,2,new TGeoCombiTrans(origintrapstructure-1960*mm-2.5-3.,-729.*mm,-20.,rot9a));
//inner pieces on the other side
TGeoRotation *rot10=new TGeoRotation("10rot"); rot10->RotateX(-90); rot10->RotateY(-120);
TGeoRotation *rot10a=new TGeoRotation("10arot"); rot10a->RotateX(-90); rot10a->RotateY(-120); rot10a->RotateZ(180);
cradle->AddNode(ten,1,new TGeoCombiTrans(origintrapstructure+1738*mm+tubeheight/(2*TMath::Sin(TMath::DegToRad()*60))-2,+729.*mm,-13.,rot10));
cradle->AddNode(ten,2,new TGeoCombiTrans(origintrapstructure-1738*mm-tubeheight/(2*TMath::Sin(TMath::DegToRad()*60))+2,+729.*mm,-13.,rot10a));
TGeoRotation *rot11=new TGeoRotation("11rot"); rot11->RotateX(-90); rot11->RotateY(50);
TGeoRotation *rot11a=new TGeoRotation("11arot"); rot11a->RotateX(-90); rot11a->RotateY(50); rot11a->RotateZ(180);
cradle->AddNode(eleven,1,new TGeoCombiTrans(origintrapstructure-1738*mm-tubeheight/(2*TMath::Sin(TMath::DegToRad()*60))+352.*mm,+729.*mm,-12.7,rot11));
cradle->AddNode(eleven,2,new TGeoCombiTrans(origintrapstructure+1738*mm+tubeheight/(2*TMath::Sin(TMath::DegToRad()*60))-352.*mm,+729.*mm,-12.7,rot11a));
TGeoRotation *rot12=new TGeoRotation("12rot"); rot12->RotateX(-90); rot12->RotateY(-120);
TGeoRotation *rot12a=new TGeoRotation("12arot"); rot12a->RotateX(-90); rot12a->RotateY(-120); rot12a->RotateZ(180);
cradle->AddNode(twelve,1,new TGeoCombiTrans(origintrapstructure+1065*mm,+729.*mm,1.,rot12));
cradle->AddNode(twelve,2,new TGeoCombiTrans(origintrapstructure-1065*mm,+729.*mm,1.,rot12a));
TGeoRotation *rot13=new TGeoRotation("13rot"); rot13->RotateX(-90); rot13->RotateY(-43); rot13->RotateZ(180);
TGeoRotation *rot13a=new TGeoRotation("13arot"); rot13a->RotateX(-90); rot13a->RotateY(-43);
cradle->AddNode(thirteen,1,new TGeoCombiTrans(origintrapstructure+572*mm - 18.,+729.*mm,-1.5,rot13));
cradle->AddNode(thirteen,2,new TGeoCombiTrans(origintrapstructure-572*mm + 18.,+729.*mm,-1.5,rot13a));
//vertical structures
TGeoRotation *vrot = new TGeoRotation("vertbox"); vrot->RotateX(90); vrot->RotateZ(90);
cradle->AddNode(vboxlast,1,new TGeoCombiTrans(-6037*mm/2+50.*mm/2,0.,0.5,vrot));//vertial box on the short cradle base
cradle->AddNode(vbox,2,new TGeoCombiTrans(-6037*mm/2+50.*mm/2+990.*mm,0.,0.5,vrot));
cradle->AddNode(cfourteen,2,new TGeoCombiTrans(-6037*mm/2+50.*mm/2+990.*mm,0.,-477.*mm/2 -20.*mm/2,vrot));
cradle->AddNode(vbox, 3, new TGeoCombiTrans(origintrapstructure-(1641.36*mm+params[7])/2. + 50.*mm/2. +3, 0., 0.5,vrot));
cradle->AddNode(cfourteen,3,new TGeoCombiTrans(origintrapstructure-(1641.36*mm+params[7])/2. + 50.*mm/2. +3, 0.,-477.*mm/2 -20.*mm/2,vrot));
cradle->AddNode(vbox,4,new TGeoCombiTrans(origintrapstructure+(1641.36*mm+params[7])/2. - 50.*mm/2. -3,0.,0.5,vrot));
cradle->AddNode(cfourteen,4,new TGeoCombiTrans(origintrapstructure+(1641.36*mm+params[7])/2. - 50.*mm/2. -3,0.,-477.*mm/2 -20.*mm/2,vrot));
return cradle;
}//CreateCradle()
TGeoVolume * AliHMPIDv3::CradleBaseVolume(TGeoMedium *med, Double_t l[7],const char *name)
{
/*
The trapezoid is build in the xy plane
0 ________________ 1
/ | \
/ | \
/ (0,0) \
/ | \
3 /___________|____________\ 2
01 is right shifted => shift is positive
//1: small base (0-1); 2: long base (3-2);
//3: trapezoid height; 4: shift between the two bases;
//5: height 6: height reduction; 7: z-reduction;
*/
TGeoXtru *xtruIn = new TGeoXtru(2);
TGeoXtru *xtruOut = new TGeoXtru(2);
xtruIn->SetName(Form("%sIN",name));
xtruOut->SetName(Form("%sOUT",name));
Double_t xv[4], yv[4];
xv[0] = -(l[0]/2 - l[3]); yv[0] = l[2]/2;
xv[1] = l[0]/2 + l[3]; yv[1] = l[2]/2;
xv[2] = l[1]/2; yv[2] = -l[2]/2;
xv[3] = -l[1]/2; yv[3] = -l[2]/2;
xtruOut->DefinePolygon(4, xv, yv);
xtruOut->DefineSection(0, -l[4]/2., 0., 0., 1.0);//0= I plane z; (0.,0.) = shift wrt centre; 1.= shape scale factor
xtruOut->DefineSection(1, +l[4]/2., 0., 0., 1.0);//1= II plane z;
Double_t tgalpha = 0;
if(xv[3]-xv[0] == 0 ) tgalpha = 999999;
else tgalpha = l[2]/TMath::Abs(xv[3]-xv[0]);
Double_t tgbeta = 0;
if(xv[2]-xv[1]==0) tgbeta = 999999;
else tgbeta = l[2]/TMath::Abs(xv[2]-xv[1]);
xv[0] = xv[0]-l[5]/tgalpha; yv[0] = l[2]/2 - l[5];
xv[1] = xv[1]+l[5]/tgbeta; yv[1] = l[2]/2 - l[5];
xv[2] = xv[2]+l[5]/tgbeta; yv[2] = -l[2]/2+l[5];
xv[3] = xv[3]-l[5]/tgalpha; yv[3] = -l[2]/2+l[5];
xtruIn->DefinePolygon(4, xv, yv);
xtruIn->DefineSection(0, (-l[4]+l[6])/2, 0., 0., 1.0);
xtruIn->DefineSection(1, (+l[4]-l[6])/2, 0., 0., 1.0);
TGeoCompositeShape *shape = new TGeoCompositeShape(name, Form("%sOUT-%sIN",name,name));
TGeoVolume *vol = new TGeoVolume(name, shape, med);
return vol;
}//CradleBaseVolume()
| 62.125385 | 340 | 0.562733 | [
"geometry",
"shape"
] |
60e34735697e8b8f0fe9df165ae1048cdf110403 | 2,728 | hpp | C++ | include/transform.hpp | NapOli1084/pipes | 842cb9b4ca6c2711d1f38dd8dac768fefe8e5b47 | [
"MIT"
] | null | null | null | include/transform.hpp | NapOli1084/pipes | 842cb9b4ca6c2711d1f38dd8dac768fefe8e5b47 | [
"MIT"
] | null | null | null | include/transform.hpp | NapOli1084/pipes | 842cb9b4ca6c2711d1f38dd8dac768fefe8e5b47 | [
"MIT"
] | 1 | 2019-10-28T20:57:29.000Z | 2019-10-28T20:57:29.000Z | #ifndef PIPES_TRANSFORM_HPP
#define PIPES_TRANSFORM_HPP
#include "helpers/assignable.hpp"
#include "helpers/FWD.hpp"
#include "helpers/meta.hpp"
#include "helpers/warnings.hpp"
#include "output_iterator.hpp"
PIPES_DISABLE_WARNING_PUSH
PIPES_DISABLE_WARNING_MULTIPLE_ASSIGNMENT_OPERATORS_SPECIFIED
namespace pipes
{
template<typename TransformFunctionTuple, typename... OutputPipes>
class transform_pipe : public OutputIteratorBase<transform_pipe<TransformFunctionTuple, OutputPipes...>>
{
public:
template<typename T>
void onReceive(T&& input)
{
detail::for_each2([&input](auto&& function, auto&& outputPipe)
{
send(outputPipe, function(input));
}, transformFunctionTuple_, outputPipes_);
}
explicit transform_pipe(TransformFunctionTuple transformFunctionTuple, OutputPipes... outputPipes) : outputPipes_(outputPipes...), transformFunctionTuple_(transformFunctionTuple) {}
private:
std::tuple<OutputPipes...> outputPipes_;
TransformFunctionTuple transformFunctionTuple_;
public: // but technical
using OutputIteratorBase<transform_pipe<TransformFunctionTuple, OutputPipes...>>::operator=;
transform_pipe& operator=(transform_pipe const& other)
{
outputPipes_ = other.outputPipes_;
transformFunctionTuple_ = other.transformFunctionTuple_;
return *this;
}
transform_pipe& operator=(transform_pipe& other) { *this = const_cast<transform_pipe const&>(other); return *this; }
};
template<typename... TransformFunctions>
class transform_pipe_maker
{
public:
explicit transform_pipe_maker(TransformFunctions... transformFunctions) : transformFunctionsTuple_(transformFunctions...) {}
template<typename... OutputPipes>
transform_pipe<std::tuple<detail::assignable<TransformFunctions>...>, OutputPipes...> operator()(OutputPipes... outputPipes) const
{
return transform_pipe<std::tuple<detail::assignable<TransformFunctions>...>, OutputPipes...>(transformFunctionsTuple_, outputPipes...);
}
private:
std::tuple<detail::assignable<TransformFunctions>...> transformFunctionsTuple_;
};
template<typename TransformFunction, typename OutputPipe>
transform_pipe<std::tuple<detail::assignable<TransformFunction>>, OutputPipe> operator>>=(transform_pipe_maker<TransformFunction> const& outputTransformer, OutputPipe outputPipe)
{
return outputTransformer(outputPipe);
}
template<typename... TransformFunctions>
transform_pipe_maker<TransformFunctions...> transform(TransformFunctions... transformFunctions)
{
return transform_pipe_maker<TransformFunctions...>(transformFunctions...);
}
} // namespace pipes
PIPES_DISABLE_WARNING_POP
#endif /* PIPES_TRANSFORM_HPP */
| 34.531646 | 185 | 0.764296 | [
"transform"
] |
60e4f526ef00546ccf970cb08388d5138b847e94 | 711 | cpp | C++ | toonz/sources/toonzlib/tvectorimageutils.cpp | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonzlib/tvectorimageutils.cpp | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonzlib/tvectorimageutils.cpp | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | 1 | 2019-10-07T17:12:30.000Z | 2019-10-07T17:12:30.000Z |
#include "toonz/tvectorimageutils.h"
#include "tpalette.h"
//-------------------------------------------------------------------------------------
void getGroupsList(const TVectorImageP &vi, std::vector<TVectorImageP> &list)
{
//Scan vi's strokes
unsigned int i, j, strokeCount = vi->getStrokeCount();
for (i = 0; i < strokeCount;) {
std::vector<int> indexes;
//Find the group interval
for (j = i; j < strokeCount && vi->areDifferentGroup(i, false, j, false) == -1; ++j)
indexes.push_back(j);
//Fill a new list item with the strokes
TVectorImageP item(vi->splitImage(indexes, false));
if (item->getPalette() == 0)
item->setPalette(new TPalette);
list.push_back(item);
i = j;
}
}
| 26.333333 | 87 | 0.587904 | [
"vector"
] |
60e77e1de1ff2cf919f76da419ba043480a0bc05 | 512 | cpp | C++ | LeetCode/674. Longest Continuous Increasing Subsequence.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 2 | 2019-11-10T18:42:11.000Z | 2020-07-04T07:05:22.000Z | LeetCode/674. Longest Continuous Increasing Subsequence.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | null | null | null | LeetCode/674. Longest Continuous Increasing Subsequence.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 1 | 2019-11-04T11:05:17.000Z | 2019-11-04T11:05:17.000Z | class Solution {
public:
int findLengthOfLCIS(vector<int> &nums) {
if (nums.size() == 0) return 0;
int max_len = 1;
int len;
int prev = nums[0];
len = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > prev) {
len++;
prev = nums[i];
} else {
prev = nums[i];
len = 1;
}
max_len = max(max_len, len);
}
return max_len;
}
}; | 22.26087 | 47 | 0.376953 | [
"vector"
] |
60eaf92923f44699408e0154af40191e355e2383 | 54,019 | cpp | C++ | cpp/unittest/render/heatmap_test.cpp | yamasite/arctern | 7b8e8bd8ce30e2eb1093c4351fc0ea4b4a89b1fe | [
"Apache-2.0"
] | 1 | 2020-04-25T04:21:01.000Z | 2020-04-25T04:21:01.000Z | cpp/unittest/render/heatmap_test.cpp | yamasite/arctern | 7b8e8bd8ce30e2eb1093c4351fc0ea4b4a89b1fe | [
"Apache-2.0"
] | null | null | null | cpp/unittest/render/heatmap_test.cpp | yamasite/arctern | 7b8e8bd8ce30e2eb1093c4351fc0ea4b4a89b1fe | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019-2020 Zilliz. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "arrow/render_api.h"
TEST(HEATMAP_TEST, RAW_POINT_INT8_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (int8_t*)malloc(5 * sizeof(int8_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(int8_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::int8(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_INT16_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (int16_t*)malloc(5 * sizeof(int16_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(int16_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::int16(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_INT32_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(data_type, 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (int32_t*)malloc(5 * sizeof(int32_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(int32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::int32(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_INT64_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (int64_t*)malloc(5 * sizeof(int64_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(int64_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::int64(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_UINT8_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (uint8_t*)malloc(5 * sizeof(uint8_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(uint8_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::uint8(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_UINT16_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (uint16_t*)malloc(5 * sizeof(uint16_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(uint16_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::uint16(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_UINT32_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_UINT64_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (uint64_t*)malloc(5 * sizeof(uint64_t));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(uint64_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::uint64(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_FLOAT_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (float*)malloc(5 * sizeof(float));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(float));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::float32(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_DOUBLE_TEST) {
auto bit_map = new uint8_t{0xff};
auto data_type = arrow::uint32();
auto buff_data1 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data1[i] = i + 50;
}
auto buffer0 = std::make_shared<arrow::Buffer>(bit_map, 1 * sizeof(uint8_t));
auto buffer1 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data1, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers1;
buffers1.emplace_back(buffer0);
buffers1.emplace_back(buffer1);
auto array_data1 = arrow::ArrayData::Make(data_type, 5, buffers1);
auto array1 = arrow::MakeArray(array_data1);
auto bit_map2 = new uint8_t{0xff};
auto buff_data2 = (uint32_t*)malloc(5 * sizeof(uint32_t));
for (int i = 0; i < 5; ++i) {
buff_data2[i] = i + 50;
}
auto buffer20 = std::make_shared<arrow::Buffer>(bit_map2, 1 * sizeof(uint8_t));
auto buffer21 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data2, 5 * sizeof(uint32_t));
std::vector<std::shared_ptr<arrow::Buffer>> buffers2;
buffers2.emplace_back(buffer20);
buffers2.emplace_back(buffer21);
auto array_data2 = arrow::ArrayData::Make(arrow::uint32(), 5, buffers2);
auto array2 = arrow::MakeArray(array_data2);
auto bit_map3 = new uint8_t{0xff};
auto buff_data3 = (double*)malloc(5 * sizeof(double));
for (int i = 0; i < 5; ++i) {
buff_data3[i] = i + 50;
}
auto buffer30 = std::make_shared<arrow::Buffer>(bit_map3, 1 * sizeof(uint8_t));
auto buffer31 =
std::make_shared<arrow::Buffer>((uint8_t*)buff_data3, 5 * sizeof(double));
std::vector<std::shared_ptr<arrow::Buffer>> buffers3;
buffers3.emplace_back(buffer30);
buffers3.emplace_back(buffer31);
auto array_data3 = arrow::ArrayData::Make(arrow::float64(), 5, buffers3);
auto array3 = arrow::MakeArray(array_data3);
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(array1, array2, array3, vega);
}
TEST(HEATMAP_TEST, RAW_POINT_INVALID_DATA_TYPE_TEST) {
// param1: x
arrow::UInt32Builder x_builder;
auto status = x_builder.Append(50);
status = x_builder.Append(50);
status = x_builder.Append(50);
status = x_builder.Append(50);
status = x_builder.Append(50);
std::shared_ptr<arrow::UInt32Array> x_array;
status = x_builder.Finish(&x_array);
// param2: y
arrow::UInt32Builder y_builder;
status = y_builder.Append(50);
status = y_builder.Append(50);
status = y_builder.Append(50);
status = y_builder.Append(50);
status = y_builder.Append(50);
std::shared_ptr<arrow::UInt32Array> y_array;
status = y_builder.Finish(&y_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::StringBuilder color_builder;
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(x_array, y_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_INT8_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::Int8Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_INT16_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::Int16Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_INT32_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::Int32Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_INT64_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::Int64Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_UINT8_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::UInt8Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_UINT16_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::UInt16Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_UINT32_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::UInt32Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_UINT64_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::UInt64Builder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_FLOAT_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::FloatBuilder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_DOUBLE_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::DoubleBuilder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, WKT_POINT_INVALID_DATA_TYPE_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::StringBuilder color_builder;
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Append("");
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": 10}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
TEST(HEATMAP_TEST, INVALID_JSON_TEST) {
// param1: wkt string
std::string wkt1 = "POINT (50 50)";
std::string wkt2 = "POINT (51 51)";
std::string wkt3 = "POINT (52 52)";
std::string wkt4 = "POINT (53 53)";
std::string wkt5 = "POINT (54 54)";
arrow::StringBuilder string_builder;
auto status = string_builder.Append(wkt1);
status = string_builder.Append(wkt2);
status = string_builder.Append(wkt3);
status = string_builder.Append(wkt4);
status = string_builder.Append(wkt5);
std::shared_ptr<arrow::StringArray> string_array;
status = string_builder.Finish(&string_array);
// param2: color
std::shared_ptr<arrow::Array> color_array;
arrow::DoubleBuilder color_builder;
status = color_builder.Append(50);
status = color_builder.Append(51);
status = color_builder.Append(52);
status = color_builder.Append(53);
status = color_builder.Append(54);
status = color_builder.Finish(&color_array);
// param3: conf
const std::string vega =
"{\n"
" \"width\": 300,\n"
" \"height\": 200,\n"
" \"description\": \"circle_2d\",\n"
" \"data\": [\n"
" {\n"
" \"name\": \"data\",\n"
" \"url\": \"data/data.csv\"\n"
" }\n"
" ],\n"
" \"scales\": [\n"
" {\n"
" \"name\": \"x\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n"
" },\n"
" {\n"
" \"name\": \"y\",\n"
" \"type\": \"linear\",\n"
" \"domain\": {\"data\": \"data\", \"field\": \"c1\"}\n"
" }\n"
" ],\n"
" \"marks\": [\n"
" {\n"
" \"encode\": {\n"
" \"enter\": {\n"
" \"map_scale\": {\"value\": \"INVALID_NUMBER\"}\n"
" }\n"
" }\n"
" }\n"
" ]\n"
"}";
arctern::render::heat_map(string_array, color_array, vega);
}
| 31.406395 | 82 | 0.523557 | [
"render",
"vector"
] |
60ee23e625c132f5532bb4ba356ed0c73ce434b2 | 888 | cpp | C++ | Phoenix3D/PX2Core/PX2Visitor.cpp | PheonixFoundation/Phoenix3D | bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99 | [
"BSL-1.0"
] | 36 | 2016-04-24T01:40:38.000Z | 2022-01-18T07:32:26.000Z | Phoenix3D/PX2Core/PX2Visitor.cpp | PheonixFoundation/Phoenix3D | bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99 | [
"BSL-1.0"
] | null | null | null | Phoenix3D/PX2Core/PX2Visitor.cpp | PheonixFoundation/Phoenix3D | bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99 | [
"BSL-1.0"
] | 16 | 2016-06-13T08:43:51.000Z | 2020-09-15T13:25:58.000Z | // PX2Visitor.cpp
#include "PX2Visitor.hpp"
#include "PX2Any.hpp"
using namespace PX2;
//----------------------------------------------------------------------------
Visitor::Visitor ()
{
}
//----------------------------------------------------------------------------
Visitor::~Visitor ()
{
}
//----------------------------------------------------------------------------
void Visitor::Visit (Object *obj, int info)
{
PX2_UNUSED(obj);
PX2_UNUSED(info);
}
//----------------------------------------------------------------------------
void Visitor::Visit (Object *obj, const std::string &info)
{
PX2_UNUSED(obj);
PX2_UNUSED(info);
}
//----------------------------------------------------------------------------
void Visitor::Visit (Object *obj, const Any &info)
{
PX2_UNUSED(obj);
PX2_UNUSED(info);
}
//---------------------------------------------------------------------------- | 26.909091 | 78 | 0.323198 | [
"object"
] |
60ef24303654cd0fc8e3e0058dcc1b0d37d6485c | 26,119 | cpp | C++ | ZenGin/Gothic_I_Addon/classDef_Ver1.cpp | ThielHater/nyx-core | ebff02a548f8ca31d6000c69b0482c99a840c991 | [
"MIT"
] | null | null | null | ZenGin/Gothic_I_Addon/classDef_Ver1.cpp | ThielHater/nyx-core | ebff02a548f8ca31d6000c69b0482c99a840c991 | [
"MIT"
] | null | null | null | ZenGin/Gothic_I_Addon/classDef_Ver1.cpp | ThielHater/nyx-core | ebff02a548f8ca31d6000c69b0482c99a840c991 | [
"MIT"
] | 1 | 2022-01-26T20:28:39.000Z | 2022-01-26T20:28:39.000Z | #include "UnionAfx.h"
namespace Gothic_I_Addon {
#ifdef __ZPROTO_B_VER1__
zCEngine*& zengine = *(zCEngine**) 0x008A31DC;
zCOption*& zoptions = *(zCOption**) 0x008AE3AC;
zCTimer* ztimer = (zCTimer*) 0x009150C0;
oCGame*& ogame = *(oCGame**) 0x00920D8C;
zCInput*& zinput = *(zCInput**) 0x008B2798;
zCRenderer*& zrenderer = *(zCRenderer**) 0x0090BD90;
zCLineCache* zlineCache = (zCLineCache*) 0x008B51C0;
zERROR* zerr = (zERROR*) 0x008AE718;
zCSoundSystem*& zsound = *(zCSoundSystem**) 0x00914D14;
zCMusicSystem*& zmusic = *(zCMusicSystem**) 0x008B2FB8;
oCItem*& offer = *(oCItem**) 0x009209BC;
oCDoc*& document = *(oCDoc**) 0x00920B1C;
zCMallocGeneric* zmalloc = (zCMallocGeneric*) 0x008B9678;
zTEngineStats* zengineStats = (zTEngineStats*) 0x008B5218;
zCScanDir* dirScanner = (zCScanDir*) 0x008AE468;
oCObjectFactory*& zfactory = *(oCObjectFactory**) 0x008B9E00;
zCArchiverFactory* zarcFactory = (zCArchiverFactory*) 0x008B561C;
oCNpc*& player = *(oCNpc**) 0x00923134;
oCNpc*& stealnpc = *(oCNpc**) 0x009232F0;
zCView*& screen = *(zCView**) 0x00926414;
zCView*& messages = *(zCView**) 0x008B22F8;
zCConsole* zcon = (zCConsole*) 0x009247D8;
zCConsole*& game_species_con = *(zCConsole**) 0x00920DA8;
zCConsole*& game_fight_con = *(zCConsole**) 0x00920DAC;
zCConsole*& edit_con = *(zCConsole**) 0x00920DB0;
zCConsole*& game_cam_con = *(zCConsole**) 0x00920DB4;
zCConsole*& game_aiConsole = *(zCConsole**) 0x00920DB8;
zCNet*& znet = *(zCNet**) 0x008A99D4;
zCNetManager*& znetman = *(zCNetManager**) 0x008ADCAC;
CGameManager*& gameMan = *(CGameManager**) 0x008A31D8;
zCFontMan*& zfontman = *(zCFontMan**) 0x00924958;
oCRtnManager* rtnMan = (oCRtnManager*) 0x00923F38;
oCMissionManager* misMan = (oCMissionManager*) 0x00921C50;
zCRenderManager* zrenderMan = (zCRenderManager*) 0x009147C8;
zCResourceManager*& zresMan = *(zCResourceManager**) 0x00914898;
zCSoundManager*& zsndMan = *(zCSoundManager**) 0x00914D8C;
zCVertexBufferManager* zvertexBufferMan = (zCVertexBufferManager*)0x0091D0F8;
zCParser* parser = (zCParser* ) 0x00925048;
zCParser*& parserSoundFX = *(zCParser**) 0x008B38C0;
zCParser*& parserParticleFX = *(zCParser**) 0x008BA204;
zCParser*& parserVisualFX = *(zCParser**) 0x008AF4EC;
zCParser*& parserCamera = *(zCParser**) 0x008AFB5C;
zCParser*& parserMenu = *(zCParser**) 0x008B2F04;
zCParser*& parserMusic = *(zCParser**) 0x008B31FC;
zCFPUControler* zfpuControler = (zCFPUControler*) 0x009150E0;
oCParticleControl*& pfxc = *(oCParticleControl**) 0x00920D90;
HINSTANCE& hInstApp = *(HINSTANCE*) 0x008B50C8;
HDC& dcScreen = *(HDC*) 0x008B50CC;
HICON& hIconApp = *(HICON*) 0x008B50D0;
HWND& hWndApp = *(HWND*) 0x008B50D4;
namespace Gothic {
namespace Managers {
CGameManager*& Game = gameMan;
zCFontMan*& Font = zfontman;
oCRtnManager*& Routine = rtnMan;
oCMissionManager*& Mission = misMan;
zCRenderManager*& Render = zrenderMan;
zCResourceManager*& Resource = zresMan;
zCSoundManager*& Sound = zsndMan;
zCVertexBufferManager*& VertexBuffer = zvertexBufferMan;
}
namespace Parsers {
zCParser*& Game = parser;
zCParser*& SFX = parserSoundFX;
zCParser*& PFX = parserParticleFX;
zCParser*& VFX = parserVisualFX;
zCParser*& Camera = parserCamera;
zCParser*& Menu = parserMenu;
zCParser*& Music = parserMusic;
}
namespace Network {
zCNet*& Net = znet;
zCNetManager*& Manager = znetman;
}
namespace Entities {
oCNpc*& Player = player;
oCNpc*& StealNpc = stealnpc;
}
namespace Consoles {
zCConsole*& Main = zcon;
zCConsole*& Species = game_species_con;
zCConsole*& Fight = game_fight_con;
zCConsole*& Abilities = edit_con;
zCConsole*& Camera = game_cam_con;
zCConsole*& AI = game_aiConsole;
}
namespace Factories {
oCObjectFactory*& Objects = zfactory;
zCArchiverFactory*& Archives = zarcFactory;
}
namespace Views {
zCView*& Screen = screen;
zCView*& Messages = messages;
}
namespace Options {
zCOption*& Gothic = zoptions;
zCOption*& Game = zoptions;
}
namespace Game {
zCTimer*& Timer = ztimer;
oCGame*& Session = ogame;
zCInput*& Input = zinput;
zCRenderer*& Renderer = zrenderer;
zCLineCache*& LineCache = zlineCache;
zERROR*& Error = zerr;
zCSoundSystem*& Sound = zsound;
zCMusicSystem*& Music = zmusic;
zTEngineStats*& EngineStatus = zengineStats;
}
namespace Other {
zCEngine*& EnginePointer = zengine;
oCItem*& OfferItem = offer;
oCDoc*& Document = document;
zCMallocGeneric*& Malloc = zmalloc;
zCScanDir*& DirectoryExplorer = dirScanner;
zCFPUControler*& FPUController = zfpuControler;
oCParticleControl*& PartivleFXControl = pfxc;
}
namespace Application {
HINSTANCE& Instance = hInstApp;
HDC& ScreenDC = dcScreen;
HICON& Icon = hIconApp;
HWND& Window = hWndApp;
}
}
#endif // __ZPROTO_B_VER1__
#ifdef __OCS_MANAGER_H__VER1__
zCClassDef* oCCSManager::classDef = (zCClassDef*)0x008A2490;
#endif
#ifdef __OCS_PLAYER_H__VER1__
zCClassDef* oCCSPlayer::classDef = (zCClassDef*)0x008A2750;
#endif
#ifdef __OCS_PROPS_H__VER1__
zCClassDef* oCCSProps::classDef = (zCClassDef*)0x008A2810;
#endif
#ifdef __OCS_TRIGGER_H__VER1__
zCClassDef* oCCSTrigger::classDef = (zCClassDef*)0x008A2888;
#endif
#ifdef __ZCCS_CONTEXT_H__VER1__
zCClassDef* zCCSCutsceneContext::classDef = (zCClassDef*)0x008A2900;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCEvMsgCutscene::classDef = (zCClassDef*)0x008A2970;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCCSBlock::classDef = (zCClassDef*)0x008A29E8;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCCSSyncBlock::classDef = (zCClassDef*)0x008A2A58;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCCSAtomicBlock::classDef = (zCClassDef*)0x008A2AC8;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCCutscene::classDef = (zCClassDef*)0x008A2B38;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCCSBlockBase::classDef = (zCClassDef*)0x008A2C08;
#endif
#ifdef __ZCCS_CUTSCENE_H__VER1__
zCClassDef* zCCSRole::classDef = (zCClassDef*)0x008A2C78;
#endif
#ifdef __ZCCS_LIB_H__VER1__
zCClassDef* zCCSLib::classDef = (zCClassDef*)0x008A2CF0;
#endif
#ifdef __ZCCS_MANAGER_H__VER1__
zCClassDef* zCCSManager::classDef = (zCClassDef*)0x008A2D78;
#endif
#ifdef __ZCCS_PLAYER_H__VER1__
zCClassDef* zCCSPlayer::classDef = (zCClassDef*)0x008A2DF8;
#endif
#ifdef __ZCCS_POOL_H__VER1__
zCClassDef* zCCSPoolItem::classDef = (zCClassDef*)0x008A2E70;
#endif
#ifdef __ZCCS_PROPS_H__VER1__
zCClassDef* zCCSProps::classDef = (zCClassDef*)0x008A2EE8;
#endif
#ifdef __OSAVEGAME_H__VER1__
zCClassDef* oCSavegameInfo::classDef = (zCClassDef*)0x008A36D0;
#endif
#ifdef __OTRIGGER_H__VER1__
zCClassDef* oCTriggerScript::classDef = (zCClassDef*)0x008A37E8;
#endif
#ifdef __OTRIGGER_H__VER1__
zCClassDef* oCTriggerChangeLevel::classDef = (zCClassDef*)0x008A3928;
#endif
#ifdef __ZNET_EVENT_MAN_H__VER1__
zCClassDef* zCNetEventManager::classDef = (zCClassDef*)0x008ADB28;
#endif
#ifdef __ZNET_MANAGER_H__VER1__
zCClassDef* zCNetManager::classDef = (zCClassDef*)0x008ADC28;
#endif
#ifdef __ZNET_VOB_CONTROL_H__VER1__
zCClassDef* zCNetVobControl::classDef = (zCClassDef*)0x008ADD60;
#endif
#ifdef __OSPELL_H__VER1__
zCClassDef* oCSpell::classDef = (zCClassDef*)0x008AF290;
#endif
#ifdef __OVIS_FX_H__VER1__
zCClassDef* oCVisualFX::classDef = (zCClassDef*)0x008AF438;
#endif
#ifdef __OVIS_FX__MULTI_TARGET_H__VER1__
zCClassDef* oCVisFX_MultiTarget::classDef = (zCClassDef*)0x008AF838;
#endif
#ifdef __ZAI_CAMERA_H__VER1__
zCClassDef* zCAICamera::classDef = (zCClassDef*)0x008AF998;
#endif
#ifdef __ZCS_CAMERA_H__VER1__
zCClassDef* zCCSCamera_EventMsg::classDef = (zCClassDef*)0x008B2010;
#endif
#ifdef __ZCS_CAMERA_H__VER1__
zCClassDef* zCCSCamera::classDef = (zCClassDef*)0x008B2098;
#endif
#ifdef __ZCS_CAMERA_H__VER1__
zCClassDef* zCCamTrj_KeyFrame::classDef = (zCClassDef*)0x008B2108;
#endif
#ifdef __ZCS_CAMERA_H__VER1__
zCClassDef* zCCSCamera_EventMsgActivate::classDef = (zCClassDef*)0x008B2178;
#endif
#ifdef __ZAI_H__VER1__
zCClassDef* zCAIBase::classDef = (zCClassDef*)0x008B52A8;
#endif
#ifdef __ZAI_H__VER1__
zCClassDef* zCAIBaseSound::classDef = (zCClassDef*)0x008B5318;
#endif
#ifdef __ZAI_PLAYER_H__VER1__
zCClassDef* zCAIPlayer::classDef = (zCClassDef*)0x008B5420;
#endif
#ifdef __ZARCHIVER_H__VER1__
zCClassDef* zCArchiver::classDef = (zCClassDef*)0x008B5548;
#endif
#ifdef __ZARCHIVER2_H__VER1__
zCClassDef* zCArchiverBinSafe::classDef = (zCClassDef*)0x008B56B0;
#endif
#ifdef __ZARCHIVER_GENERIC_H__VER1__
zCClassDef* zCArchiverGeneric::classDef = (zCClassDef*)0x008B57B0;
#endif
#ifdef __ZVISUAL_H__VER1__
zCClassDef* zCDecal::classDef = (zCClassDef*)0x008B9438;
#endif
#ifdef __ZLENSFLARE_H__VER1__
zCClassDef* zCLensFlareFX::classDef = (zCClassDef*)0x008B9510;
#endif
#ifdef __ZMATERIAL_H__VER1__
zCClassDef* zCMaterial::classDef = (zCClassDef*)0x008B9608;
#endif
#ifdef __ZVISUAL_H__VER1__
zCClassDef* zCMesh::classDef = (zCClassDef*)0x008B96B8;
#endif
#ifdef __ZMODEL_H__VER1__
zCClassDef* zCModelAni::classDef = (zCClassDef*)0x008B9780;
#endif
#ifdef __ZMODEL_H__VER1__
zCClassDef* zCModel::classDef = (zCClassDef*)0x008B9850;
#endif
#ifdef __ZMODEL_H__VER1__
zCClassDef* zCModelMeshLib::classDef = (zCClassDef*)0x008B9B30;
#endif
#ifdef __ZMORPH_MESH_H__VER1__
zCClassDef* zCMorphMesh::classDef = (zCClassDef*)0x008B9BF8;
#endif
#ifdef __ZOBJECT_H__VER1__
zCClassDef* zCObject::classDef = (zCClassDef*)0x008B9CE0;
#endif
#ifdef __ZOBJECT_H__VER1__
zCClassDef* zCObjectFactory::classDef = (zCClassDef*)0x008B9D50;
#endif
#ifdef __ZPARTICLE_H__VER1__
zCClassDef* zCParticleFX::classDef = (zCClassDef*)0x008BA170;
#endif
#ifdef __ZPOLY_STRIP_H__VER1__
zCClassDef* zCPolyStrip::classDef = (zCClassDef*)0x008FA3E8;
#endif
#ifdef __ZPROG_MESH_H__VER1__
zCClassDef* zCMeshSoftSkin::classDef = (zCClassDef*)0x00905978;
#endif
#ifdef __ZPROG_MESH_H__VER1__
zCClassDef* zCProgMeshProto::classDef = (zCClassDef*)0x0090B9F8;
#endif
#ifdef __ZPOLY_STRIP_H__VER1__
zCClassDef* zCQuadMark::classDef = (zCClassDef*)0x0090BAA8;
#endif
#ifdef __ZRESOURCE_H__VER1__
zCClassDef* zCResource::classDef = (zCClassDef*)0x00914828;
#endif
#ifdef __ZSKY_H__VER1__
zCClassDef* zCSkyControler::classDef = (zCClassDef*)0x009148A8;
#endif
#ifdef __ZSKY_H__VER1__
zCClassDef* zCSkyControler_Mid::classDef = (zCClassDef*)0x00914998;
#endif
#ifdef __ZSKY_H__VER1__
zCClassDef* zCSkyControler_Indoor::classDef = (zCClassDef*)0x00914A10;
#endif
#ifdef __ZSKY__OUTDOOR_H__VER1__
zCClassDef* zCSkyControler_Outdoor::classDef = (zCClassDef*)0x00914928;
#endif
#ifdef __ZSOUND_H__VER1__
zCClassDef* zCSoundFX::classDef = (zCClassDef*)0x00914A98;
#endif
#ifdef __ZTEXTURE_H__VER1__
zCClassDef* zCTextureFileFormat::classDef = (zCClassDef*)0x00914DC8;
#endif
#ifdef __ZTEXTURE_H__VER1__
zCClassDef* zCTextureFileFormatTGA::classDef = (zCClassDef*)0x00914E38;
#endif
#ifdef __ZTEXTURE_H__VER1__
zCClassDef* zCTextureFileFormatInternal::classDef = (zCClassDef*)0x00914EC0;
#endif
#ifdef __ZTEXTURE_H__VER1__
zCClassDef* zCLightMap::classDef = (zCClassDef*)0x00914F38;
#endif
#ifdef __ZTEXTURE_H__VER1__
zCClassDef* zCTexture::classDef = (zCClassDef*)0x00914FE0;
#endif
#ifdef __ZVERTEX_BUFFER_H__VER1__
zCClassDef* zCVertexBuffer::classDef = (zCClassDef*)0x0091D118;
#endif
#ifdef __ZVOB_H__VER1__
zCClassDef* zCVob::classDef = (zCClassDef*)0x0091D1C0;
#endif
#ifdef __ZVOB_H__VER1__
zCClassDef* zCEventCore::classDef = (zCClassDef*)0x0091D230;
#endif
#ifdef __ZVOB_H__VER1__
zCClassDef* zCVobLevelCompo::classDef = (zCClassDef*)0x0091D2A0;
#endif
#ifdef __ZVOB_H__VER1__
zCClassDef* zCVobLightPreset::classDef = (zCClassDef*)0x0091D310;
#endif
#ifdef __ZVOB_H__VER1__
zCClassDef* zCEventMessage::classDef = (zCClassDef*)0x0091D380;
#endif
#ifdef __ZVISUAL_H__VER1__
zCClassDef* zCVisual::classDef = (zCClassDef*)0x0091D3F0;
#endif
#ifdef __ZVISUAL_H__VER1__
zCClassDef* zCVisualAnimate::classDef = (zCClassDef*)0x0091D460;
#endif
#ifdef __ZVOB_H__VER1__
zCClassDef* zCVobLight::classDef = (zCClassDef*)0x0091D4F8;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCEventMover::classDef = (zCClassDef*)0x0091D578;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCVobStair::classDef = (zCClassDef*)0x0091D5F0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTouchAnimate::classDef = (zCClassDef*)0x0091D668;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCMoverControler::classDef = (zCClassDef*)0x0091D6D8;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCMover::classDef = (zCClassDef*)0x0091D750;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCEarthquake::classDef = (zCClassDef*)0x0091D7C0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCPFXControler::classDef = (zCClassDef*)0x0091D830;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCVobLensFlare::classDef = (zCClassDef*)0x0091D8A0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCEventScreenFX::classDef = (zCClassDef*)0x0091D910;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTriggerBase::classDef = (zCClassDef*)0x0091D980;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTouchDamage::classDef = (zCClassDef*)0x0091D9F0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTrigger::classDef = (zCClassDef*)0x0091DA60;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCEffect::classDef = (zCClassDef*)0x0091DAD0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCVobAnimate::classDef = (zCClassDef*)0x0091DB40;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCMessageFilter::classDef = (zCClassDef*)0x0091DBB0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCVobScreenFX::classDef = (zCClassDef*)0x0091DC20;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCEventCommon::classDef = (zCClassDef*)0x0091DC90;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTriggerUntouch::classDef = (zCClassDef*)0x0091DD00;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTriggerTeleport::classDef = (zCClassDef*)0x0091DD70;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCCodeMaster::classDef = (zCClassDef*)0x0091DDE0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTriggerList::classDef = (zCClassDef*)0x0091DE50;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTouchAnimateSound::classDef = (zCClassDef*)0x0091DEC0;
#endif
#ifdef __ZVOB_MISC_H__VER1__
zCClassDef* zCTriggerWorldStart::classDef = (zCClassDef*)0x0091DF30;
#endif
#ifdef __ZWORLD_H__VER1__
zCClassDef* zCWorld::classDef = (zCClassDef*)0x0091E090;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCVobSound::classDef = (zCClassDef*)0x0091E1A8;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneZFog::classDef = (zCClassDef*)0x0091E218;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZone::classDef = (zCClassDef*)0x0091E288;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneZFogDefault::classDef = (zCClassDef*)0x0091E2F8;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCVobSoundDaytime::classDef = (zCClassDef*)0x0091E368;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneReverbDefault::classDef = (zCClassDef*)0x0091E3D8;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneVobFarPlaneDefault::classDef = (zCClassDef*)0x0091E448;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneReverb::classDef = (zCClassDef*)0x0091E4B8;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneMusic::classDef = (zCClassDef*)0x0091E528;
#endif
#ifdef __ZZONE_H__VER1__
zCClassDef* zCZoneVobFarPlane::classDef = (zCClassDef*)0x0091E598;
#endif
#ifdef __OMUSIC_ZONE_H__VER1__
zCClassDef* oCZoneMusicDefault::classDef = (zCClassDef*)0x00926678;
#endif
#ifdef __OMUSIC_ZONE_H__VER1__
zCClassDef* oCZoneMusic::classDef = (zCClassDef*)0x009266F0;
#endif
#ifdef __ZMUSIC_CTRL_H__VER1__
zCClassDef* zCEventMusicControler::classDef = (zCClassDef*)0x00926778;
#endif
#ifdef __ZMUSIC_CTRL_H__VER1__
zCClassDef* zCMusicControler::classDef = (zCClassDef*)0x009267E8;
#endif
#ifdef __OVIEW_DIALOG_INVENTORY_H__VER1__
zCClassDef* oCViewDialogInventory::classDef = (zCClassDef*)0x00A21D20;
#endif
#ifdef __OVIEW_DIALOG_ITEM_H__VER1__
zCClassDef* oCViewDialogItem::classDef = (zCClassDef*)0x00A21D98;
#endif
#ifdef __OVIEW_DIALOG_ITEM_CONTAINER_H__VER1__
zCClassDef* oCViewDialogItemContainer::classDef = (zCClassDef*)0x00A21E10;
#endif
#ifdef __OVIEW_DIALOG_STEAL_CONTAINER_H__VER1__
zCClassDef* oCViewDialogStealContainer::classDef = (zCClassDef*)0x00A21F58;
#endif
#ifdef __OVIEW_DIALOG_TRADE_H__VER1__
zCClassDef* oCViewDialogTrade::classDef = (zCClassDef*)0x00A22090;
#endif
#ifdef __ZVIEW_DIALOG_H__VER1__
zCClassDef* zCViewDialog::classDef = (zCClassDef*)0x00A22B18;
#endif
#ifdef __ZVIEW_DIALOG_CHOICE_H__VER1__
zCClassDef* zCViewDialogChoice::classDef = (zCClassDef*)0x00A22B90;
#endif
#ifdef __ZVIEW_DRAW_H__VER1__
zCClassDef* zCViewDraw::classDef = (zCClassDef*)0x00A22930;
#endif
#ifdef __ZVIEW_FX_H__VER1__
zCClassDef* zCViewFX::classDef = (zCClassDef*)0x00A229B0;
#endif
#ifdef __ZVIEW_OBJECT_H__VER1__
zCClassDef* zCViewObject::classDef = (zCClassDef*)0x00A22A28;
#endif
#ifdef __ZVIEW_PRINT_H__VER1__
zCClassDef* zCViewPrint::classDef = (zCClassDef*)0x00A22AA0;
#endif
#ifdef __OAI_HUMAN_H__VER1__
zCClassDef* oCAIHuman::classDef = (zCClassDef*)0x0091E688;
#endif
#ifdef __OAI_HUMAN_H__VER1__
zCClassDef* oCAIHuman_Stand::classDef = (zCClassDef*)0x0091E6F8;
#endif
#ifdef __OAI_HUMAN_H__VER1__
zCClassDef* oCAICamera::classDef = (zCClassDef*)0x0091E7A0;
#endif
#ifdef __OAI_SHOOT_H__VER1__
zCClassDef* oCAIVobMove::classDef = (zCClassDef*)0x0091E9C8;
#endif
#ifdef __OAI_SHOOT_H__VER1__
zCClassDef* oCAIArrowBase::classDef = (zCClassDef*)0x0091EA38;
#endif
#ifdef __OAI_SHOOT_H__VER1__
zCClassDef* oCAIDrop::classDef = (zCClassDef*)0x0091EAF8;
#endif
#ifdef __OAI_SHOOT_H__VER1__
zCClassDef* oCAIArrow::classDef = (zCClassDef*)0x0091EB98;
#endif
#ifdef __OAI_SHOOT_H__VER1__
zCClassDef* oCAISound::classDef = (zCClassDef*)0x0091EC38;
#endif
#ifdef __OAI_SHOOT_H__VER1__
zCClassDef* oCAIVobMoveTorch::classDef = (zCClassDef*)0x0091ECD8;
#endif
#ifdef __OANI_CTRL_H__VER1__
zCClassDef* oCAniCtrl_Human::classDef = (zCClassDef*)0x0091EED0;
#endif
#ifdef __OITEM_H__VER1__
zCClassDef* oCItem::classDef = (zCClassDef*)0x00921950;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobWheel::classDef = (zCClassDef*)0x00921D38;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobBed::classDef = (zCClassDef*)0x00921DA8;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobDoor::classDef = (zCClassDef*)0x00921E20;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobLockable::classDef = (zCClassDef*)0x00921EA8;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobMsg::classDef = (zCClassDef*)0x00921F30;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobFire::classDef = (zCClassDef*)0x00921FB8;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobItemSlot::classDef = (zCClassDef*)0x00922088;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobSwitch::classDef = (zCClassDef*)0x00922120;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobLadder::classDef = (zCClassDef*)0x009221A8;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobContainer::classDef = (zCClassDef*)0x00922218;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCDummyVobGenerator::classDef = (zCClassDef*)0x009222A0;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMobInter::classDef = (zCClassDef*)0x00922310;
#endif
#ifdef __OMOB_INTER_H__VER1__
zCClassDef* oCMOB::classDef = (zCClassDef*)0x00922398;
#endif
#ifdef __ONPC_H__VER1__
zCClassDef* oCNpc::classDef = (zCClassDef*)0x00922830;
#endif
#ifdef __ONPC_H__VER1__
zCClassDef* oCNpcTalent::classDef = (zCClassDef*)0x00923020;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgManipulate::classDef = (zCClassDef*)0x00923390;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgUseItem::classDef = (zCClassDef*)0x00923418;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgConversation::classDef = (zCClassDef*)0x009234D0;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgDamage::classDef = (zCClassDef*)0x00923540;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgAttack::classDef = (zCClassDef*)0x009235E0;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgState::classDef = (zCClassDef*)0x00923650;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCNpcMessage::classDef = (zCClassDef*)0x009236D8;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgMagic::classDef = (zCClassDef*)0x00923760;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgMovement::classDef = (zCClassDef*)0x009237D0;
#endif
#ifdef __ONPC_MESSAGES_H__VER1__
zCClassDef* oCMsgWeapon::classDef = (zCClassDef*)0x00923858;
#endif
#ifdef __OOBJ_FACTORY_H__VER1__
zCClassDef* oCObjectFactory::classDef = (zCClassDef*)0x00923C20;
#endif
#ifdef __OVOB_H__VER1__
zCClassDef* oCVob::classDef = (zCClassDef*)0x00924338;
#endif
#ifdef __OVOB_H__VER1__
zCClassDef* oCTouchDamage::classDef = (zCClassDef*)0x009243F0;
#endif
#ifdef __OWORLD_H__VER1__
zCClassDef* oCWorld::classDef = (zCClassDef*)0x009246E8;
#endif
#ifdef __ZEVENT_MAN_H__VER1__
zCClassDef* zCEventManager::classDef = (zCClassDef*)0x009248C8;
#endif
#ifdef __ZWAYNET_H__VER1__
zCClassDef* zCWayNet::classDef = (zCClassDef*)0x00926438;
#endif
#ifdef __ZWAYNET_H__VER1__
zCClassDef* zCVobWaypoint::classDef = (zCClassDef*)0x009264A8;
#endif
#ifdef __ZWAYNET_H__VER1__
zCClassDef* zCVobStartpoint::classDef = (zCClassDef*)0x00926518;
#endif
#ifdef __ZWAYNET_H__VER1__
zCClassDef* zCWaypoint::classDef = (zCClassDef*)0x00926588;
#endif
#ifdef __ZWAYNET_H__VER1__
zCClassDef* zCVobSpot::classDef = (zCClassDef*)0x009265F8;
#endif
} | 41.06761 | 80 | 0.658486 | [
"render"
] |
60f002dd4d64bbd703f5aa4a561bbecf88b4d0de | 55,265 | cpp | C++ | src/wrappers/buffer.cpp | thesmallcreeper/Anvil | f55a185d569a99b5cb4b2e5aa3286caf7f52705c | [
"MIT"
] | null | null | null | src/wrappers/buffer.cpp | thesmallcreeper/Anvil | f55a185d569a99b5cb4b2e5aa3286caf7f52705c | [
"MIT"
] | null | null | null | src/wrappers/buffer.cpp | thesmallcreeper/Anvil | f55a185d569a99b5cb4b2e5aa3286caf7f52705c | [
"MIT"
] | null | null | null | //
// Copyright (c) 2017-2018 Advanced Micro Devices, Inc. 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 "misc/buffer_create_info.h"
#include "misc/debug.h"
#include "misc/object_tracker.h"
#include "misc/struct_chainer.h"
#include "wrappers/buffer.h"
#include "wrappers/command_buffer.h"
#include "wrappers/command_pool.h"
#include "wrappers/device.h"
#include "wrappers/instance.h"
#include "wrappers/memory_block.h"
#include "wrappers/physical_device.h"
#include "wrappers/queue.h"
Anvil::Buffer::Buffer(Anvil::BufferCreateInfoUniquePtr in_create_info_ptr)
:CallbacksSupportProvider (BUFFER_CALLBACK_ID_COUNT),
DebugMarkerSupportProvider<Buffer>(in_create_info_ptr->get_device(),
Anvil::ObjectType::BUFFER),
MTSafetySupportProvider (Anvil::Utils::convert_mt_safety_enum_to_boolean(in_create_info_ptr->get_mt_safety(),
in_create_info_ptr->get_device () )),
m_buffer (VK_NULL_HANDLE),
m_memory_block_ptr (nullptr),
m_prefers_dedicated_allocation (false),
m_requires_dedicated_allocation (false),
m_staging_buffer_queue_ptr (nullptr)
{
if (in_create_info_ptr->get_type() == BufferType::NO_ALLOC)
{
if (((in_create_info_ptr->get_memory_features() & Anvil::MemoryFeatureFlagBits::MAPPABLE_BIT) == 0) ||
((in_create_info_ptr->get_create_flags () & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) == 0) ||
((in_create_info_ptr->get_create_flags () & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) == 0))
{
/* For host->gpu writes to work in this case, we will need the buffer to work as a target
* for buffer->buffer copy operations. Same goes for the other way around.
*/
auto usage_flags = in_create_info_ptr->get_usage_flags();
usage_flags |= Anvil::BufferUsageFlagBits::TRANSFER_DST_BIT | Anvil::BufferUsageFlagBits::TRANSFER_SRC_BIT;
in_create_info_ptr->set_usage_flags(usage_flags);
}
}
m_create_info_ptr = std::move(in_create_info_ptr);
}
/** Releases a buffer object and a memory object associated with this Buffer instance. */
Anvil::Buffer::~Buffer()
{
/* Unregister the object */
Anvil::ObjectTracker::get()->unregister_object(Anvil::ObjectType::BUFFER,
this);
if (m_buffer != VK_NULL_HANDLE &&
m_create_info_ptr->get_parent_buffer_ptr() == nullptr)
{
lock();
{
Anvil::Vulkan::vkDestroyBuffer(m_device_ptr->get_device_vk(),
m_buffer,
nullptr /* pAllocator */);
}
unlock();
m_buffer = VK_NULL_HANDLE;
}
}
Anvil::BufferUniquePtr Anvil::Buffer::create(Anvil::BufferCreateInfoUniquePtr in_create_info_ptr)
{
Anvil::BufferUniquePtr new_buffer_ptr(nullptr,
std::default_delete<Anvil::Buffer>() );
new_buffer_ptr.reset(
new Anvil::Buffer(std::move(in_create_info_ptr) )
);
if (new_buffer_ptr != nullptr)
{
if (!new_buffer_ptr->init() )
{
new_buffer_ptr.reset();
}
}
/* Register the object */
Anvil::ObjectTracker::get()->register_object(Anvil::ObjectType::BUFFER,
new_buffer_ptr.get() );
return new_buffer_ptr;
}
/* Please see header for specification */
const Anvil::Buffer* Anvil::Buffer::get_base_buffer()
{
const Anvil::Buffer* result_ptr = this;
Anvil::Buffer* parent_ptr = nullptr;
if ( (parent_ptr = result_ptr->get_create_info_ptr()->get_parent_buffer_ptr()) != nullptr)
{
result_ptr = parent_ptr;
}
return result_ptr;
}
/* Please see header for specification */
VkBuffer Anvil::Buffer::get_buffer(const bool& in_bake_memory_if_necessary)
{
const auto& create_flags = get_create_info_ptr()->get_create_flags();
const bool is_sparse = ((create_flags & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_BINDING_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) != 0);
if (!is_sparse)
{
if (in_bake_memory_if_necessary &&
m_memory_block_ptr == nullptr)
{
get_memory_block(0 /* in_n_memory_block */);
}
}
return m_buffer;
}
/* Please see header for specification */
Anvil::MemoryBlock* Anvil::Buffer::get_memory_block(uint32_t in_n_memory_block)
{
const auto& create_flags = get_create_info_ptr()->get_create_flags();
bool is_callback_needed = false;
const bool is_sparse = ((create_flags & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_BINDING_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) != 0);
if (is_sparse)
{
IsBufferMemoryAllocPendingQueryCallbackArgument callback_arg(this);
callback(BUFFER_CALLBACK_ID_IS_ALLOC_PENDING,
&callback_arg);
is_callback_needed = callback_arg.result;
}
else
{
is_callback_needed = (m_memory_block_ptr == nullptr);
}
if (is_callback_needed)
{
OnMemoryBlockNeededForBufferCallbackArgument callback_argument(this);
anvil_assert(m_create_info_ptr->get_parent_buffer_ptr() == nullptr);
callback_safe(BUFFER_CALLBACK_ID_MEMORY_BLOCK_NEEDED,
&callback_argument);
}
if (is_sparse)
{
return m_page_tracker_ptr->get_memory_block(in_n_memory_block);
}
else
{
return m_memory_block_ptr;
}
}
VkMemoryRequirements Anvil::Buffer::get_memory_requirements() const
{
auto parent_buffer_ptr = m_create_info_ptr->get_parent_buffer_ptr();
if (parent_buffer_ptr != nullptr)
{
return parent_buffer_ptr->get_memory_requirements();
}
else
{
return m_buffer_memory_reqs;
}
}
uint32_t Anvil::Buffer::get_n_memory_blocks() const
{
const auto& create_flags = get_create_info_ptr()->get_create_flags();
const bool is_sparse = ((create_flags & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) != 0);
if (is_sparse)
{
return m_page_tracker_ptr->get_n_memory_blocks();
}
else
{
return 1;
}
}
bool Anvil::Buffer::init()
{
uint32_t n_queue_family_indices;
uint32_t queue_family_indices [8];
VkResult result (VK_ERROR_INITIALIZATION_FAILED);
Anvil::StructChainer<VkBufferCreateInfo> struct_chainer;
bool use_dedicated_allocation(false);
if ( m_create_info_ptr->get_client_data () != nullptr &&
(m_create_info_ptr->get_memory_features() & Anvil::MemoryFeatureFlagBits::MAPPABLE_BIT) == 0)
{
m_create_info_ptr->set_usage_flags(m_create_info_ptr->get_usage_flags() | Anvil::BufferUsageFlagBits::TRANSFER_DST_BIT);
}
if (m_create_info_ptr->get_type() != BufferType::NO_ALLOC_CHILD)
{
/* Determine which queues the buffer should be available to. */
Anvil::Utils::convert_queue_family_bits_to_family_indices(m_device_ptr,
m_create_info_ptr->get_queue_families(),
queue_family_indices,
&n_queue_family_indices);
anvil_assert(n_queue_family_indices > 0);
anvil_assert(n_queue_family_indices < sizeof(queue_family_indices) / sizeof(queue_family_indices[0]) );
/* Prepare the create info structure */
{
VkBufferCreateInfo buffer_create_info;
buffer_create_info.flags = m_create_info_ptr->get_create_flags().get_vk();
buffer_create_info.pNext = nullptr;
buffer_create_info.pQueueFamilyIndices = queue_family_indices;
buffer_create_info.queueFamilyIndexCount = n_queue_family_indices;
buffer_create_info.sharingMode = static_cast<VkSharingMode>(m_create_info_ptr->get_sharing_mode() );
buffer_create_info.size = m_create_info_ptr->get_size();
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.usage = m_create_info_ptr->get_usage_flags().get_vk();
struct_chainer.append_struct(buffer_create_info);
}
{
const auto& external_memory_handle_types = m_create_info_ptr->get_exportable_external_memory_handle_types();
if (external_memory_handle_types != 0)
{
VkExternalMemoryBufferCreateInfoKHR external_memory_buffer_create_info;
external_memory_buffer_create_info.handleTypes = external_memory_handle_types.get_vk();
external_memory_buffer_create_info.pNext = nullptr;
external_memory_buffer_create_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR;
struct_chainer.append_struct(external_memory_buffer_create_info);
}
}
/* Create the buffer object */
{
auto struct_chain_ptr = struct_chainer.create_chain();
result = Anvil::Vulkan::vkCreateBuffer(m_device_ptr->get_device_vk(),
struct_chain_ptr->get_root_struct(),
nullptr, /* pAllocator */
&m_buffer);
}
anvil_assert_vk_call_succeeded(result);
if (is_vk_call_successful(result) )
{
set_vk_handle(m_buffer);
/* Cache buffer data memory requirements.
*
* Prefer facility exposed by VK_KHR_get_memory_requirements2, unless the extension is unavailable.
*/
if (m_device_ptr->get_extension_info()->khr_get_memory_requirements2() )
{
Anvil::StructID dedicated_reqs_struct_id = static_cast<Anvil::StructID>(UINT32_MAX);
const auto gmr2_entrypoints = m_device_ptr->get_extension_khr_get_memory_requirements2_entrypoints();
VkBufferMemoryRequirementsInfo2KHR info;
const bool khr_dedicated_allocation_available = m_device_ptr->get_extension_info()->khr_dedicated_allocation();
Anvil::StructChainUniquePtr<VkMemoryRequirements2KHR> result_reqs_chain_ptr;
VkMemoryRequirements2KHR* result_reqs_chain_raw_ptr = nullptr;
Anvil::StructChainer<VkMemoryRequirements2KHR> result_reqs_chainer;
info.buffer = m_buffer;
info.pNext = nullptr;
info.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR;
{
VkMemoryRequirements2KHR reqs;
reqs.pNext = nullptr;
reqs.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR;
result_reqs_chainer.append_struct(reqs);
}
if (khr_dedicated_allocation_available)
{
VkMemoryDedicatedRequirementsKHR dedicated_reqs;
dedicated_reqs.pNext = nullptr;
dedicated_reqs.prefersDedicatedAllocation = VK_FALSE;
dedicated_reqs.requiresDedicatedAllocation = VK_FALSE;
dedicated_reqs.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR;
dedicated_reqs_struct_id = result_reqs_chainer.append_struct(dedicated_reqs);
}
result_reqs_chain_ptr = result_reqs_chainer.create_chain();
anvil_assert(result_reqs_chain_ptr != nullptr);
result_reqs_chain_raw_ptr = result_reqs_chain_ptr->get_root_struct();
anvil_assert(result_reqs_chain_raw_ptr != nullptr);
gmr2_entrypoints.vkGetBufferMemoryRequirements2KHR(m_device_ptr->get_device_vk(),
&info,
result_reqs_chain_raw_ptr);
m_buffer_memory_reqs = result_reqs_chain_raw_ptr->memoryRequirements;
if (khr_dedicated_allocation_available)
{
const auto dedicated_alloc_info_ptr = result_reqs_chain_ptr->get_struct_with_id<VkMemoryDedicatedRequirementsKHR>(dedicated_reqs_struct_id);
m_prefers_dedicated_allocation = (dedicated_alloc_info_ptr->prefersDedicatedAllocation == VK_TRUE);
m_requires_dedicated_allocation = (dedicated_alloc_info_ptr->requiresDedicatedAllocation == VK_TRUE);
use_dedicated_allocation = m_requires_dedicated_allocation;
}
}
else
{
Anvil::Vulkan::vkGetBufferMemoryRequirements(m_device_ptr->get_device_vk(),
m_buffer,
&m_buffer_memory_reqs);
}
}
}
else
{
m_buffer = m_create_info_ptr->get_parent_buffer_ptr()->m_buffer;
anvil_assert(m_buffer != VK_NULL_HANDLE);
if (m_buffer != VK_NULL_HANDLE)
{
result = VK_SUCCESS;
}
}
switch (m_create_info_ptr->get_type() )
{
case Anvil::BufferType::ALLOC:
{
/* Create a memory object and preallocate as much space as we need */
auto client_data_ptr = m_create_info_ptr->get_client_data();
Anvil::MemoryBlockUniquePtr memory_block_ptr;
{
auto create_info_ptr = Anvil::MemoryBlockCreateInfo::create_regular(m_create_info_ptr->get_device(),
m_buffer_memory_reqs.memoryTypeBits,
m_buffer_memory_reqs.size,
m_create_info_ptr->get_memory_features() );
create_info_ptr->set_mt_safety(m_create_info_ptr->get_mt_safety() );
if (use_dedicated_allocation)
{
create_info_ptr->use_dedicated_allocation(this,
nullptr); /* in_opt_image_ptr */
}
memory_block_ptr = Anvil::MemoryBlock::create(std::move(create_info_ptr) );
}
if (!set_nonsparse_memory( std::move(memory_block_ptr) ))
{
anvil_assert_fail();
result = VK_ERROR_INITIALIZATION_FAILED;
goto end;
}
if (client_data_ptr != nullptr)
{
if (!write(0, /* in_start_offset */
m_create_info_ptr->get_size(),
client_data_ptr) )
{
anvil_assert_fail();
result = VK_ERROR_INITIALIZATION_FAILED;
goto end;
}
}
break;
}
case Anvil::BufferType::NO_ALLOC_CHILD:
{
Anvil::MemoryBlockUniquePtr mem_block_ptr;
{
auto create_info_ptr = Anvil::MemoryBlockCreateInfo::create_derived(m_create_info_ptr->get_parent_buffer_ptr()->get_memory_block(0 /* in_n_memory_block */),
m_create_info_ptr->get_start_offset(),
m_create_info_ptr->get_size() );
mem_block_ptr = Anvil::MemoryBlock::create(std::move(create_info_ptr) );
if (use_dedicated_allocation)
{
create_info_ptr->use_dedicated_allocation(this,
nullptr); /* in_opt_image_ptr */
}
}
anvil_assert(!is_memory_block_owned(mem_block_ptr.get()));
m_owned_memory_blocks.push_back(std::move(mem_block_ptr) );
m_memory_block_ptr = m_owned_memory_blocks.back().get();
anvil_assert(m_memory_block_ptr != nullptr);
break;
}
case BufferType::NO_ALLOC:
{
const auto& create_flags = get_create_info_ptr()->get_create_flags();
const bool is_sparse = ((create_flags & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_BINDING_BIT) != 0) ||
((create_flags & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) != 0);
if (is_sparse)
{
m_page_tracker_ptr.reset(
new Anvil::PageTracker(Anvil::Utils::round_up(m_create_info_ptr->get_size(),
m_buffer_memory_reqs.alignment),
m_buffer_memory_reqs.alignment)
);
}
/* No special action needed */
break;
}
default:
{
anvil_assert_fail();
}
}
end:
return is_vk_call_successful(result);
}
/* TODO */
bool Anvil::Buffer::init_staging_buffer(const VkDeviceSize& in_size,
Anvil::Queue* in_opt_queue_ptr)
{
Anvil::PrimaryCommandBufferUniquePtr copy_cmdbuf_ptr;
std::vector<const Anvil::PhysicalDevice*> helper_vec;
const auto queue_fams = m_create_info_ptr->get_queue_families();
Anvil::QueueFamilyFlagBits staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::NONE;
m_staging_buffer_ptr.reset();
m_staging_buffer_queue_ptr = nullptr;
if (m_create_info_ptr->get_sharing_mode() == Anvil::SharingMode::EXCLUSIVE)
{
/* We need to use a user-specified queue, since we can't tell which queue fam the buffer is currently configured to be compatible with.
*
* This can be worked around if the buffer can only be used with a specific queue family type.
*/
if (Anvil::Utils::is_pow2(queue_fams.get_vk() ) )
{
switch (queue_fams.get_vk() )
{
case static_cast<uint32_t>(Anvil::QueueFamilyFlagBits::COMPUTE_BIT): m_staging_buffer_queue_ptr = m_device_ptr->get_compute_queue (0); break;
case static_cast<uint32_t>(Anvil::QueueFamilyFlagBits::DMA_BIT): m_staging_buffer_queue_ptr = m_device_ptr->get_transfer_queue (0); break;
case static_cast<uint32_t>(Anvil::QueueFamilyFlagBits::GRAPHICS_BIT): m_staging_buffer_queue_ptr = m_device_ptr->get_universal_queue(0); break;
default:
{
anvil_assert_fail();
}
}
}
else
{
anvil_assert(in_opt_queue_ptr != nullptr);
m_staging_buffer_queue_ptr = in_opt_queue_ptr;
}
anvil_assert(m_staging_buffer_queue_ptr != nullptr);
switch (m_device_ptr->get_queue_family_type(m_staging_buffer_queue_ptr->get_queue_family_index() ) )
{
case Anvil::QueueFamilyType::COMPUTE: staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::COMPUTE_BIT; break;
case Anvil::QueueFamilyType::TRANSFER: staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::DMA_BIT; break;
case Anvil::QueueFamilyType::UNIVERSAL: staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::GRAPHICS_BIT; break;
default:
{
anvil_assert_fail();
}
}
}
else
{
/* We can use any queue from the list of queue fams this buffer is compatible with, in order to perform the copy op. */
if ((queue_fams & Anvil::QueueFamilyFlagBits::GRAPHICS_BIT) != 0)
{
m_staging_buffer_queue_ptr = m_device_ptr->get_universal_queue(0);
staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::GRAPHICS_BIT;
}
else
if ((queue_fams & Anvil::QueueFamilyFlagBits::DMA_BIT) != 0)
{
m_staging_buffer_queue_ptr = m_device_ptr->get_transfer_queue(0);
staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::DMA_BIT;
}
else
{
anvil_assert((queue_fams & Anvil::QueueFamilyFlagBits::COMPUTE_BIT) != 0)
m_staging_buffer_queue_ptr = m_device_ptr->get_compute_queue(0);
staging_buffer_queue_fam_bits = Anvil::QueueFamilyFlagBits::COMPUTE_BIT;
}
}
if (m_staging_buffer_ptr == nullptr ||
m_staging_buffer_ptr->get_create_info_ptr()->get_size() < in_size)
{
{
const auto sharing_mode = Anvil::Utils::is_pow2(static_cast<uint32_t>(staging_buffer_queue_fam_bits) ) ? Anvil::SharingMode::EXCLUSIVE
: Anvil::SharingMode::CONCURRENT;
auto create_info_ptr = Anvil::BufferCreateInfo::create_alloc(m_device_ptr,
in_size,
staging_buffer_queue_fam_bits,
sharing_mode,
Anvil::BufferCreateFlagBits::NONE,
Anvil::BufferUsageFlagBits::TRANSFER_DST_BIT | Anvil::BufferUsageFlagBits::TRANSFER_SRC_BIT,
Anvil::MemoryFeatureFlagBits::MAPPABLE_BIT);
create_info_ptr->set_mt_safety (Anvil::MTSafety::DISABLED);
m_staging_buffer_ptr = Anvil::Buffer::create(std::move(create_info_ptr) );
}
if (m_staging_buffer_ptr == nullptr)
{
anvil_assert(m_staging_buffer_ptr != nullptr);
}
}
return (m_staging_buffer_ptr != nullptr);
}
/* Please see header for specification */
bool Anvil::Buffer::read(VkDeviceSize in_start_offset,
VkDeviceSize in_size,
void* out_result_ptr)
{
return read(in_start_offset,
in_size,
UINT32_MAX, /* in_device_mask */
out_result_ptr);
}
/* Please see header for specification */
bool Anvil::Buffer::read(VkDeviceSize in_start_offset,
VkDeviceSize in_size,
uint32_t in_device_mask,
void* out_result_ptr)
{
const Anvil::DeviceType device_type (m_device_ptr->get_type() );
auto memory_block_ptr (get_memory_block(0 /* in_n_memory_block */) );
bool result (false);
/* TODO: Complete support for sparsely-bound & sparse-resident buffers */
anvil_assert((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) == 0);
if ((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_BINDING_BIT) != 0)
{
anvil_assert(m_page_tracker_ptr->get_n_memory_blocks () == 1);
anvil_assert(m_page_tracker_ptr->get_n_pages_with_memory_backing() == m_page_tracker_ptr->get_n_pages() );
}
if ((memory_block_ptr->get_create_info_ptr()->get_memory_features() & Anvil::MemoryFeatureFlagBits::MAPPABLE_BIT) != 0)
{
result = memory_block_ptr->read(in_start_offset,
in_size,
out_result_ptr);
}
else
{
/* The buffer memory is not mappable. We need to create a staging buffer,
* do a non-mappable->mappable memory copy, and then read back data from the mappable buffer. */
Anvil::PrimaryCommandBufferUniquePtr copy_cmdbuf_ptr;
if (m_staging_buffer_ptr == nullptr ||
m_staging_buffer_ptr->get_create_info_ptr()->get_size() < in_size)
{
if (!init_staging_buffer(in_size,
nullptr) ) /* in_opt_queue_ptr */
{
result = false;
goto end;
}
}
if (m_staging_buffer_ptr == nullptr)
{
anvil_assert(m_staging_buffer_ptr != nullptr);
goto end;
}
copy_cmdbuf_ptr = m_device_ptr->get_command_pool_for_queue_family_index(m_staging_buffer_queue_ptr->get_queue_family_index() )->alloc_primary_level_command_buffer();
if (copy_cmdbuf_ptr == nullptr)
{
anvil_assert(copy_cmdbuf_ptr != nullptr);
goto end;
}
if (device_type == Anvil::DeviceType::SINGLE_GPU)
{
copy_cmdbuf_ptr->start_recording(true, /* one_time_submit */
false); /* simultaneous_use_allowed */
}
else
{
anvil_assert(device_type == Anvil::DeviceType::MULTI_GPU);
anvil_assert(Utils::count_set_bits(in_device_mask) == 1);
copy_cmdbuf_ptr->start_recording(true, /* one_time_submit */
false, /* simultaneous_use_allowed */
in_device_mask); /* in_opt_device_mask */
}
{
Anvil::BufferBarrier buffer_barrier(Anvil::AccessFlagBits::TRANSFER_WRITE_BIT,
Anvil::AccessFlagBits::HOST_READ_BIT,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
m_staging_buffer_ptr.get(),
0, /* in_offset */
in_size);
Anvil::BufferCopy copy_region;
Anvil::MemoryBarrier pre_copy_barrier(Anvil::AccessFlagBits::TRANSFER_READ_BIT, /* in_destination_access_mask */
Anvil::AccessFlagBits::HOST_WRITE_BIT | Anvil::AccessFlagBits::MEMORY_WRITE_BIT | Anvil::AccessFlagBits::SHADER_WRITE_BIT | Anvil::AccessFlagBits::TRANSFER_WRITE_BIT);
copy_region.dst_offset = 0;
copy_region.size = in_size;
copy_region.src_offset = in_start_offset;
copy_cmdbuf_ptr->record_pipeline_barrier(Anvil::PipelineStageFlagBits::ALL_COMMANDS_BIT, /* in_src_stage_mask */
Anvil::PipelineStageFlagBits::TRANSFER_BIT, /* in_dst_stage_mask */
Anvil::DependencyFlagBits::NONE,
1, /* in_memory_barrier_count */
&pre_copy_barrier,
0, /* in_buffer_memory_barrier_count */
nullptr, /* in_buffer_memory_barriers_ptr */
0, /* in_image_memory_barrier_count */
nullptr); /* in_iamge_memory_barriers_ptr */
copy_cmdbuf_ptr->record_copy_buffer (this,
m_staging_buffer_ptr.get(),
1, /* in_region_count */
©_region);
copy_cmdbuf_ptr->record_pipeline_barrier(Anvil::PipelineStageFlagBits::TRANSFER_BIT,
Anvil::PipelineStageFlagBits::HOST_BIT,
Anvil::DependencyFlagBits::NONE,
0, /* in_memory_barrier_count */
nullptr, /* in_memory_barriers_ptr */
1, /* in_buffer_memory_barrier_count */
&buffer_barrier,
0, /* in_image_memory_barrier_count */
nullptr); /* in_image_memory_barriers_ptr */
}
copy_cmdbuf_ptr->stop_recording();
if (device_type == Anvil::DeviceType::SINGLE_GPU)
{
m_staging_buffer_queue_ptr->submit(
Anvil::SubmitInfo::create_execute(copy_cmdbuf_ptr.get(),
true /* should_block */)
);
}
else
{
Anvil::CommandBufferMGPUSubmission cmd_buffer_submission;
anvil_assert((in_device_mask != 0) && (in_device_mask != UINT32_MAX));
cmd_buffer_submission.cmd_buffer_ptr = copy_cmdbuf_ptr.get();
cmd_buffer_submission.device_mask = in_device_mask;
m_staging_buffer_queue_ptr->submit(
Anvil::SubmitInfo::create_execute(&cmd_buffer_submission,
1, /* in_n_command_buffer_submissions */
true /* should_block */)
);
}
result = m_staging_buffer_ptr->read(0,
in_size,
out_result_ptr);
}
end:
return result;
}
bool Anvil::Buffer::set_memory_nonsparse_internal(MemoryBlockUniquePtr in_memory_block_ptr,
uint32_t in_n_device_group_indices,
const uint32_t* in_device_group_indices_ptr)
{
const Anvil::DeviceType device_type (m_device_ptr->get_type() );
bool result (false);
VkResult result_vk;
if (in_memory_block_ptr == nullptr)
{
anvil_assert(!(in_memory_block_ptr == nullptr) );
goto end;
}
if (m_memory_block_ptr != nullptr)
{
anvil_assert(m_memory_block_ptr == nullptr);
goto end;
}
if (((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) != 0) ||
((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) != 0) )
{
anvil_assert(((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_ALIASED_BIT) == 0) &&
((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) == 0) );
goto end;
}
/* Bind the memory object to the buffer object */
if (device_type == Anvil::DeviceType::SINGLE_GPU)
{
lock();
{
result_vk = Anvil::Vulkan::vkBindBufferMemory(m_device_ptr->get_device_vk(),
m_buffer,
in_memory_block_ptr->get_memory (),
in_memory_block_ptr->get_start_offset() );
}
unlock();
}
else
{
StructChainUniquePtr<VkBindBufferMemoryInfoKHR> bind_info_struct_chain_ptr;
Anvil::StructChainer<VkBindBufferMemoryInfoKHR> bind_info_struct_chainer;
const Anvil::MGPUDevice* mgpu_device_ptr(dynamic_cast<const Anvil::MGPUDevice*>(m_device_ptr) );
const auto& entrypoints (mgpu_device_ptr->get_extension_khr_bind_memory2_entrypoints() );
anvil_assert(device_type == Anvil::DeviceType::MULTI_GPU);
{
VkBindBufferMemoryInfoKHR bind_info;
VkBindBufferMemoryDeviceGroupInfoKHR bind_info_dg;
bind_info_dg.deviceIndexCount = in_n_device_group_indices;
bind_info_dg.pDeviceIndices = in_device_group_indices_ptr;
bind_info_dg.pNext = nullptr;
bind_info_dg.sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO_KHR;
bind_info.buffer = m_buffer;
bind_info.memory = in_memory_block_ptr->get_memory ();
bind_info.memoryOffset = in_memory_block_ptr->get_start_offset();
bind_info.pNext = nullptr;
bind_info.sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR;
bind_info_struct_chainer.append_struct(bind_info);
bind_info_struct_chainer.append_struct(bind_info_dg);
}
bind_info_struct_chain_ptr = bind_info_struct_chainer.create_chain();
result_vk = entrypoints.vkBindBufferMemory2KHR(m_device_ptr->get_device_vk(),
1, /* bindInfoCount */
bind_info_struct_chain_ptr ->get_root_struct() );
}
if (!is_vk_call_successful(result_vk) )
{
anvil_assert_vk_call_succeeded(result_vk);
goto end;
}
/* All done */
m_memory_block_ptr = in_memory_block_ptr.get();
result = true;
anvil_assert(!is_memory_block_owned(in_memory_block_ptr.get()));
m_owned_memory_blocks.push_back(
std::move(in_memory_block_ptr)
);
end:
return result;
}
/* Please see header for specification */
bool Anvil::Buffer::set_memory_sparse(MemoryBlock* in_memory_block_ptr,
bool in_memory_block_owned_by_buffer,
VkDeviceSize in_memory_block_start_offset,
VkDeviceSize in_start_offset,
VkDeviceSize in_size)
{
anvil_assert((m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_BINDING_BIT) != 0);
if (m_page_tracker_ptr->set_binding(in_memory_block_ptr,
in_memory_block_start_offset,
in_start_offset,
in_size) )
{
if (in_memory_block_owned_by_buffer && !is_memory_block_owned(in_memory_block_ptr))
{
MemoryBlockUniquePtr mem_block_ptr(in_memory_block_ptr,
std::default_delete<MemoryBlock>() );
m_owned_memory_blocks.push_back(
std::move(mem_block_ptr)
);
}
return true;
}
else
{
return false;
}
}
/* Please see header for specification */
bool Anvil::Buffer::set_nonsparse_memory(MemoryBlockUniquePtr in_memory_block_ptr)
{
MemoryBlock* memory_block_raw_ptr = in_memory_block_ptr.release();
return set_nonsparse_memory(memory_block_raw_ptr,
true);
}
bool Anvil::Buffer::set_nonsparse_memory(MemoryBlock* in_memory_block_ptr,
bool in_memory_block_owned_by_buffer)
{
MemoryBlockUniquePtr memory_block_ptr;
if (in_memory_block_owned_by_buffer)
{
memory_block_ptr = MemoryBlockUniquePtr(in_memory_block_ptr,
std::default_delete<Anvil::MemoryBlock>() );
}
else
{
memory_block_ptr = MemoryBlockUniquePtr(in_memory_block_ptr,
[](MemoryBlock*)
{
/* Stub */
});
}
return set_memory_nonsparse_internal(std::move(memory_block_ptr),
0, /* n_physical_devices */
nullptr); /* physical_devices_ptr */
}
/* Please see header for specification */
bool Anvil::Buffer::set_nonsparse_memory(MemoryBlockUniquePtr in_memory_block_ptr,
uint32_t in_n_device_group_indices,
const uint32_t* in_device_group_indices_ptr)
{
MemoryBlockUniquePtr memory_block_ptr = MemoryBlockUniquePtr(in_memory_block_ptr.release(),
std::default_delete<Anvil::MemoryBlock>() );
return set_memory_nonsparse_internal(std::move(memory_block_ptr),
in_n_device_group_indices,
in_device_group_indices_ptr);
}
/* Please see header for specification */
bool Anvil::Buffer::set_nonsparse_memory(MemoryBlock* in_memory_block_ptr,
bool in_memory_block_owned_by_buffer,
uint32_t in_n_device_group_indices,
const uint32_t* in_device_group_indices_ptr)
{
MemoryBlockUniquePtr memory_block_ptr;
if (in_memory_block_owned_by_buffer)
{
memory_block_ptr = MemoryBlockUniquePtr(in_memory_block_ptr,
std::default_delete<Anvil::MemoryBlock>() );
}
else
{
memory_block_ptr = MemoryBlockUniquePtr(in_memory_block_ptr,
[](MemoryBlock*)
{
/* Stub */
});
}
return set_memory_nonsparse_internal(std::move(memory_block_ptr),
in_n_device_group_indices,
in_device_group_indices_ptr);
}
/* Please see header for specification */
bool Anvil::Buffer::set_nonsparse_memory_multi(uint32_t in_n_buffer_memory_binding_updates,
BufferMemoryBindingUpdate* in_updates_ptr)
{
StructChainVector<VkBindBufferMemoryInfoKHR> bind_info_struct_chains;
const Anvil::BaseDevice* device_ptr (nullptr);
uint32_t n_total_physical_devices(0);
bool result (false);
/* Sanity checks */
if (in_n_buffer_memory_binding_updates == 0)
{
anvil_assert(in_n_buffer_memory_binding_updates != 0);
goto end;
}
/* Convert input structure into VkBindBufferMemoryInfoKHR structures */
for (uint32_t n_update = 0;
n_update < in_n_buffer_memory_binding_updates;
++n_update)
{
const auto& current_update (in_updates_ptr[n_update]);
const Anvil::MGPUDevice* mgpu_device_ptr(dynamic_cast<const Anvil::MGPUDevice*>(current_update.buffer_ptr->m_device_ptr) );
if (current_update.physical_devices.size() != mgpu_device_ptr->get_n_physical_devices() )
{
anvil_assert(current_update.physical_devices.size() == mgpu_device_ptr->get_n_physical_devices() ||
current_update.physical_devices.size() == 0);
goto end;
}
n_total_physical_devices += static_cast<uint32_t>(current_update.physical_devices.size() );
if (n_update == 0)
{
device_ptr = current_update.buffer_ptr->m_device_ptr;
}
else
{
anvil_assert(device_ptr == current_update.buffer_ptr->m_device_ptr);
}
}
{
std::vector<uint32_t> device_indices (n_total_physical_devices);
uint32_t n_current_physical_device(0);
VkResult result_vk;
const auto& entrypoints (device_ptr->get_extension_khr_bind_memory2_entrypoints() );
for (uint32_t n_update = 0;
n_update < in_n_buffer_memory_binding_updates;
++n_update)
{
const auto& current_update = in_updates_ptr[n_update];
for (uint32_t n_physical_device = 0;
n_physical_device < current_update.physical_devices.size();
++n_physical_device, ++n_current_physical_device)
{
device_indices.at(n_current_physical_device) = current_update.physical_devices.at(n_physical_device)->get_device_group_device_index();
}
}
n_current_physical_device = 0;
for (uint32_t n_update = 0;
n_update < in_n_buffer_memory_binding_updates;
++n_update)
{
VkBindBufferMemoryInfoKHR current_bind_info;
VkBindBufferMemoryDeviceGroupInfoKHR current_bind_info_device_group;
StructChainer<VkBindBufferMemoryInfoKHR> current_bind_info_chain;
const auto& current_update = in_updates_ptr[n_update];
current_bind_info_device_group.sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR;
current_bind_info_device_group.deviceIndexCount = static_cast<uint32_t>(current_update.physical_devices.size());
current_bind_info_device_group.pDeviceIndices = &device_indices.at(n_current_physical_device);
current_bind_info.buffer = current_update.buffer_ptr->get_buffer ();
current_bind_info.memory = current_update.memory_block_ptr->get_memory ();
current_bind_info.memoryOffset = current_update.memory_block_ptr->get_start_offset();
current_bind_info.pNext = nullptr;
current_bind_info.sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR;
current_bind_info_chain.append_struct(current_bind_info);
current_bind_info_chain.append_struct(current_bind_info_device_group);
bind_info_struct_chains.append_struct_chain(current_bind_info_chain.create_chain() );
n_current_physical_device += static_cast<uint32_t>(current_update.physical_devices.size());
}
result_vk = entrypoints.vkBindBufferMemory2KHR(device_ptr->get_device_vk(),
in_n_buffer_memory_binding_updates,
bind_info_struct_chains.get_root_structs() );
if (!is_vk_call_successful(result_vk) )
{
anvil_assert(is_vk_call_successful(result_vk) );
goto end;
}
for (uint32_t n_update = 0;
n_update < in_n_buffer_memory_binding_updates;
++n_update)
{
auto& current_update = in_updates_ptr[n_update];
anvil_assert(current_update.buffer_ptr->m_memory_block_ptr == nullptr);
anvil_assert(std::find_if(current_update.buffer_ptr->m_owned_memory_blocks.begin(),
current_update.buffer_ptr->m_owned_memory_blocks.end (),
[=](const MemoryBlockUniquePtr& in_memory_block_ptr)
{
return (in_memory_block_ptr.get() == current_update.memory_block_ptr);
}) == current_update.buffer_ptr->m_owned_memory_blocks.end() );
current_update.buffer_ptr->m_memory_block_ptr = current_update.memory_block_ptr;
if (current_update.memory_block_owned_by_buffer)
{
MemoryBlockUniquePtr memory_block_ptr(current_update.memory_block_ptr,
std::default_delete<MemoryBlock>() );
anvil_assert(!current_update.buffer_ptr->is_memory_block_owned(current_update.memory_block_ptr));
current_update.buffer_ptr->m_owned_memory_blocks.push_back(
std::move(memory_block_ptr)
);
}
}
}
/* All done */
result = true;
end:
return result;
}
/* Please see header for specification */
bool Anvil::Buffer::write(VkDeviceSize in_start_offset,
VkDeviceSize in_size,
const void* in_data,
Anvil::Queue* in_opt_queue_ptr)
{
return write(in_start_offset,
in_size,
in_data,
UINT32_MAX, /* in_device_mask */
in_opt_queue_ptr);
}
/* Please see header for specification */
bool Anvil::Buffer::write(VkDeviceSize in_start_offset,
VkDeviceSize in_size,
const void* in_data,
uint32_t in_device_mask,
Anvil::Queue* in_opt_queue_ptr)
{
const Anvil::DeviceType device_type(m_device_ptr->get_type() );
bool result (false);
/** TODO: Support for sparse-resident buffers whose n_memory_blocks > 1 */
Anvil::MemoryBlock* memory_block_ptr(get_memory_block(0) );
if ( m_create_info_ptr->get_type() == Anvil::BufferType::NO_ALLOC &&
(m_create_info_ptr->get_create_flags() & Anvil::BufferCreateFlagBits::SPARSE_RESIDENCY_BIT) != 0)
{
anvil_assert(m_page_tracker_ptr->get_n_memory_blocks() == 1);
}
anvil_assert(memory_block_ptr != nullptr);
anvil_assert(memory_block_ptr->get_create_info_ptr()->get_size() >= in_size);
if ((memory_block_ptr->get_create_info_ptr()->get_memory_features() & Anvil::MemoryFeatureFlagBits::MAPPABLE_BIT) != 0)
{
anvil_assert((memory_block_ptr->get_create_info_ptr()->get_memory_features() & Anvil::MemoryFeatureFlagBits::MULTI_INSTANCE_BIT) == 0);
result = memory_block_ptr->write(in_start_offset,
in_size,
in_data);
}
else
{
/* The buffer memory is not mappable. We need to create a staging memory,
* upload user's data there, and then issue a copy op. */
Anvil::PrimaryCommandBufferUniquePtr copy_cmdbuf_ptr;
if (m_staging_buffer_ptr == nullptr ||
m_staging_buffer_ptr->get_create_info_ptr()->get_size() < in_size)
{
if (!init_staging_buffer(in_size,
in_opt_queue_ptr) )
{
result = false;
goto end;
}
anvil_assert(m_staging_buffer_ptr != nullptr);
}
m_staging_buffer_ptr->write(0, /* in_start_offset */
in_size,
in_data);
copy_cmdbuf_ptr = m_device_ptr->get_command_pool_for_queue_family_index(m_staging_buffer_queue_ptr->get_queue_family_index() )->alloc_primary_level_command_buffer();
if (copy_cmdbuf_ptr == nullptr)
{
anvil_assert(copy_cmdbuf_ptr != nullptr);
goto end;
}
if (device_type == Anvil::DeviceType::SINGLE_GPU)
{
copy_cmdbuf_ptr->start_recording(true, /* one_time_submit */
false); /* simultaneous_use_allowed */
}
else
{
anvil_assert(device_type == Anvil::DeviceType::MULTI_GPU);
copy_cmdbuf_ptr->start_recording(true, /* one_time_submit */
false, /* simultaneous_use_allowed */
in_device_mask);
}
{
BufferBarrier buffer_barrier(Anvil::AccessFlagBits::HOST_WRITE_BIT, /* in_source_access_mask */
(Anvil::AccessFlagBits::HOST_READ_BIT | Anvil::AccessFlagBits::MEMORY_READ_BIT | Anvil::AccessFlagBits::SHADER_READ_BIT | Anvil::AccessFlagBits::TRANSFER_READ_BIT |
Anvil::AccessFlagBits::HOST_WRITE_BIT | Anvil::AccessFlagBits::MEMORY_WRITE_BIT | Anvil::AccessFlagBits::SHADER_WRITE_BIT | Anvil::AccessFlagBits::TRANSFER_WRITE_BIT),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
m_staging_buffer_ptr.get(),
0, /* in_offset */
in_size);
Anvil::BufferCopy copy_region;
copy_region.dst_offset = in_start_offset;
copy_region.size = in_size;
copy_region.src_offset = 0;
copy_cmdbuf_ptr->record_pipeline_barrier(Anvil::PipelineStageFlagBits::HOST_BIT,
Anvil::PipelineStageFlagBits::ALL_COMMANDS_BIT,
Anvil::DependencyFlagBits::NONE,
0, /* in_memory_barrier_count */
nullptr, /* in_memory_barriers_ptr */
1, /* in_buffer_memory_barrier_count */
&buffer_barrier,
0, /* in_image_memory_barrier_count */
nullptr); /* in_image_memory_barriers_ptr */
copy_cmdbuf_ptr->record_copy_buffer (m_staging_buffer_ptr.get(),
this,
1, /* in_region_count */
©_region);
}
copy_cmdbuf_ptr->stop_recording();
if (device_type == Anvil::DeviceType::SINGLE_GPU)
{
m_staging_buffer_queue_ptr->submit(
Anvil::SubmitInfo::create_execute(copy_cmdbuf_ptr.get(),
true /* should_block */)
);
}
else
{
Anvil::CommandBufferMGPUSubmission copy_cmdbuf_submission;
copy_cmdbuf_submission.cmd_buffer_ptr = copy_cmdbuf_ptr.get();
copy_cmdbuf_submission.device_mask = in_device_mask;
/* Need to update all memory instances */
if ((memory_block_ptr->get_create_info_ptr()->get_memory_features() & Anvil::MemoryFeatureFlagBits::MULTI_INSTANCE_BIT) != 0)
{
auto device_mask = memory_block_ptr->get_create_info_ptr()->get_device_mask();
const Anvil::MGPUDevice* mgpu_device_ptr = dynamic_cast<const Anvil::MGPUDevice*>(m_device_ptr);
if (device_mask == 0)
{
device_mask = (1 << mgpu_device_ptr->get_n_physical_devices()) - 1;
}
copy_cmdbuf_submission.device_mask = device_mask;
}
m_staging_buffer_queue_ptr->submit(
Anvil::SubmitInfo::create_execute(©_cmdbuf_submission,
1, /* in_n_command_buffer_submissions */
true /* should_block */)
);
}
result = true;
}
end:
return result;
}
bool Anvil::Buffer::is_memory_block_owned(const MemoryBlock* in_memory_block_ptr) const
{
for (auto memory_block_ptr_iter = m_owned_memory_blocks.begin();
memory_block_ptr_iter != m_owned_memory_blocks.end();
++memory_block_ptr_iter)
{
if (in_memory_block_ptr == memory_block_ptr_iter->get())
{
return true;
}
}
return false;
}
| 43.515748 | 217 | 0.549679 | [
"object",
"vector"
] |
60f15b1b08c0b87de95b4b49c06acb5da5d7a6a9 | 2,163 | cpp | C++ | src/smtpclient.cpp | JamesBremner/mailout | a4c670680caa54d4aafbbad8520072e2bf3487f6 | [
"MIT"
] | null | null | null | src/smtpclient.cpp | JamesBremner/mailout | a4c670680caa54d4aafbbad8520072e2bf3487f6 | [
"MIT"
] | null | null | null | src/smtpclient.cpp | JamesBremner/mailout | a4c670680caa54d4aafbbad8520072e2bf3487f6 | [
"MIT"
] | null | null | null | #include "smtpclient.h"
#include "smtpserverstatuscodes.h"
#ifdef _WIN32
#include <WinSock2.h>
#include <ws2tcpip.h>
#else
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <vector>
using namespace jed_utils;
SmtpClient::SmtpClient(const char *pServerName, unsigned int pPort)
: SMTPClientBase(pServerName, pPort)
{
}
SmtpClient::~SmtpClient()
{
SmtpClient::cleanup();
}
//Assignment operator
SmtpClient& SmtpClient::operator=(const SmtpClient &other)
{
if (this != &other) {
SMTPClientBase::operator=(other);
}
return *this;
}
//Move constructor
SmtpClient::SmtpClient(SmtpClient &&other) noexcept
: SMTPClientBase(std::move(other))
{
}
//Move assignement
SmtpClient& SmtpClient::operator=(SmtpClient &&other) noexcept
{
if (this != &other) {
SMTPClientBase::operator=(std::move(other));
}
return *this;
}
void SmtpClient::cleanup()
{
int socket { getSocketFileDescriptor() };
if (socket != 0) {
#ifdef _WIN32
shutdown(socket, SD_BOTH);
closesocket(socket);
#else
close(socket);
#endif
}
clearSocketFileDescriptor();
#ifdef _WIN32
WSACleanup();
#endif
}
int SmtpClient::establishConnectionWithServer()
{
int session_init_return_code = initializeSession();
if (session_init_return_code != 0) {
return session_init_return_code;
}
int server_greetings_return_code = checkServerGreetings();
if (server_greetings_return_code != STATUS_CODE_SERVICE_READY) {
return server_greetings_return_code;
}
int client_init_return_code = sendServerIdentification();
if (client_init_return_code != STATUS_CODE_REQUESTED_MAIL_ACTION_OK_OR_COMPLETED) {
return client_init_return_code;
}
return 0;
}
int SmtpClient::sendCommand(const char *pCommand, int pErrorCode)
{
return sendRawCommand(pCommand, pErrorCode);
}
int SmtpClient::sendCommandWithFeedback(const char *pCommand, int pErrorCode, int pTimeoutCode)
{
return sendRawCommand(pCommand, pErrorCode, pTimeoutCode);
}
| 22.53125 | 96 | 0.687009 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.