blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4eae42c830c4b7e1b39340fac59fac33e8810499 | 81d2a7b10edee418626e4bdf7084cd2d1704b353 | /BlockFrame/Coordinate.cpp | 03f77063d42d8619f381fae535f088a21148078a | [] | no_license | yueyingyifeng/BlockFrame | 6af8fb79da072f8604dc47cafa0e89d4b6b78cfb | 7e574f0c44c51cb29786bd5af03c5ca1db82a456 | refs/heads/master | 2023-09-02T14:42:48.044661 | 2021-10-16T07:39:56 | 2021-10-16T07:39:56 | 417,736,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | #include "Coordinate.h"
//Coordinate Coordinate::operator=(Coordinate cdnt)
//{
// return Coordinate(cdnt.x, cdnt.y);
//}
Coordinate Coordinate::operator+(Coordinate& cdnt)
{
return Coordinate(x + cdnt.x, y + cdnt.y);
}
Coordinate Coordinate::operator-(Coordinate& cdnt)
{
return Coordinate(x - cdnt.x, y - cdnt.y);
}
bool Coordinate::operator==(const Coordinate cdnt)
{
return (x == cdnt.x && y == cdnt.y) ? true : false;
}
bool Coordinate::operator>(Coordinate cdnt)
{
return (x > cdnt.x && y > cdnt.y) ? true : false;
}
bool Coordinate::operator<(Coordinate cdnt)
{
return (x < cdnt.x && y < cdnt.y) ? true : false;
}
bool Coordinate::equalX(Coordinate cdnt)
{
return (x == cdnt.x) ? true : false;
}
bool Coordinate::equalY(Coordinate cdnt)
{
return (y == cdnt.y) ? true : false;
}
int Coordinate::index(int x, int y, int xm)
{
return y * xm + x;
}
int Coordinate::index(Coordinate cdnt, int xm)
{
return cdnt.y * xm + cdnt.x;
}
| [
"yueyingyifeng@Gmail.com"
] | yueyingyifeng@Gmail.com |
dc5f20a2de80d739f850fc1ff4644e01157571ac | 6c98ab874e17cb9169e5d13cbc398409b471cfb2 | /src/savedisk.cpp | 669e2588418b1801cf07496aecd6e5fbe1c49924 | [] | no_license | salvacam/dcastaway | 0106608218f949d84f9a02b928a35a5415077692 | c5e9d9adc68c75b28ab1d3849fd729fceb79146a | refs/heads/master | 2023-03-11T17:54:27.449186 | 2021-02-21T21:46:26 | 2021-02-21T21:46:26 | 340,199,517 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,985 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "savedisk.h"
unsigned savedisk_get_checksum(void *mem, unsigned size)
{
unsigned i,ret=0;
unsigned char *p=(unsigned char *)mem;
for(i=0;i<size;i++)
ret+=(i+1)*(((unsigned)p[i])+1);
return ret;
}
void savedisk_apply_changes(void *mem, void *patch, unsigned patch_size)
{
unsigned *src=(unsigned *)patch;
unsigned char *dst=(unsigned char *)mem;
unsigned pos=0;
patch_size/=sizeof(unsigned);
while(pos<patch_size)
{
unsigned n=(src[pos++])*SAVEDISK_SLOT;
memcpy((void *)&dst[n],(void *)&src[pos],SAVEDISK_SLOT);
pos+=(SAVEDISK_SLOT/sizeof(unsigned));
}
}
unsigned savedisk_get_changes_file(void *mem, unsigned size, void *patch, char *filename)
{
unsigned ret=0;
if (size%SAVEDISK_SLOT)
size++;
size/=SAVEDISK_SLOT;
FILE *f=fopen(filename,"rb");
if (f)
{
unsigned pos=0;
unsigned char *src=(unsigned char *)mem;
unsigned *dest=(unsigned *)patch;
while(size--)
{
unsigned i=(ret/sizeof(unsigned));
unsigned o=pos*SAVEDISK_SLOT;
dest[i++]=pos;
unsigned n=fread((void *)&dest[i],1,SAVEDISK_SLOT,f);
if (!n)
break;
if (memcmp((void *)&src[o],(void *)&dest[i],n))
{
memcpy((void *)&dest[i],(void *)&src[o],SAVEDISK_SLOT);
ret+=sizeof(unsigned)+SAVEDISK_SLOT;
}
pos++;
}
fclose(f);
}
return ret;
}
unsigned savedisk_get_changes(void *mem, unsigned size, void *patch, void *orig)
{
unsigned ret=0;
if (size%SAVEDISK_SLOT)
size++;
size/=SAVEDISK_SLOT;
if (orig)
{
unsigned pos=0;
unsigned char *src=(unsigned char *)mem;
unsigned *dest=(unsigned *)patch;
unsigned char *orig_p=(unsigned char *)orig;
while(size --)
{
unsigned i=(ret/sizeof(unsigned));
unsigned o=pos*SAVEDISK_SLOT;
dest[i++]=pos;
if (memcmp((void *)&src[o],(void *)&orig_p[o],SAVEDISK_SLOT))
{
memcpy((void *)&dest[i],(void *)&src[o],SAVEDISK_SLOT);
ret+=sizeof(unsigned)+SAVEDISK_SLOT;
}
pos++;
}
}
return ret;
}
| [
"salvacams@gmail.com"
] | salvacams@gmail.com |
361f1d207ebd7dd699325a7c58713e46e4417316 | ed093719d5e7db52c7a6a1e999c96eceea0f724f | /src/Properties.cpp | 6b8b8cc2cb761acd8eac0473fff58084e4654ffd | [] | no_license | Ponup/engine-desktop | e0fd5018dcaf1b1cd4afde981749c65f45840006 | f5376300951b20ec0825dc2c0037cb9af2bd60b8 | refs/heads/master | 2023-01-23T11:40:11.652876 | 2023-01-07T17:06:03 | 2023-01-07T17:06:40 | 24,429,929 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,047 | cpp | #include "Properties.h"
#include <fstream>
using std::ifstream;
using std::ofstream;
#include <iostream>
using std::ios;
using std::endl;
#include <stdexcept>
using std::runtime_error;
Properties::Properties() {
}
Properties::~Properties() {
}
void Properties::load( const string& fileName ) {
this->fileName = fileName;
properties.clear();
ifstream inputStream( fileName );
string line;
while( std::getline( inputStream, line ) )
{
if( line.size() == 0 || line[0] == '#' )
{
continue;
}
size_t equalPos = line.find( '=' );
if( string::npos == equalPos )
{
continue;
}
string key = line.substr( 0, equalPos );
string value = line.substr( equalPos + 1 );
properties.insert( KeyValue( key, value ) );
}
inputStream.close();
}
void Properties::save( const string* fileName ) {
string outputFilename = this->fileName;
if( nullptr != fileName )
{
outputFilename = *fileName;
}
ofstream outputStream( outputFilename, ios::out | ios::trunc );
if( !outputStream.is_open() )
{
return;
}
StringsMap::const_iterator it;
for(it = properties.begin(); it != properties.end(); it++) {
string key = it->first;
string value = it->second;
outputStream << key << "=" << value << endl;
}
outputStream.close();
}
string Properties::getProperty( const string& propertyName ) const {
StringsMap::const_iterator it;
it = properties.find(propertyName);
if(it == properties.end()) {
return nullptr;
} else {
return it->second;
}
}
void Properties::setProperty( const string& propertyName, const string& propertyValue ) {
StringsMap::const_iterator it;
it = properties.find( propertyName );
properties.erase( it->first );
properties.insert( KeyValue( propertyName, propertyValue ) );
}
bool Properties::getBoolProperty( const string& propertyName ) const {
string p = getProperty( propertyName );
return ( "True" == p );
}
void Properties::setBoolProperty( const string& propertyName, bool propertyValue ) {
setProperty( propertyName, ( propertyValue ? "True" : "False" ) );
}
| [
"santiago.lizardo@gmail.com"
] | santiago.lizardo@gmail.com |
bfb3c096dcb8de29560d26eb4dfc2a8d1e96b024 | 46e2b6250cc75c2941d3c58ab43e2fa14bb563f4 | /Divide.cpp | 04f24d26ad71d053b53fa7c02b0f11a06e6806f1 | [] | no_license | wshwbluebird/Solution | a83f55c91e8f60b467d2f47dd1e9bb1a1d0c16e1 | 90f0a03d4cd8a8ffbd9b79ee3bd1001636a8856a | refs/heads/master | 2021-01-09T20:56:38.499185 | 2016-07-09T01:05:08 | 2016-07-09T01:05:08 | 62,565,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,886 | cpp | ////
//// Created by Macbook Pro on 16/7/4.
////
//
//#include <iostream>
//using namespace std;
////构造 判断是否相同的方法
//bool nosame(int n){
// int a[10];
// memset(a,-1, sizeof(a));
//// for (int i = 0; i < 5; ++i) {
//// a[i] = n%10;
//// n = n/10;
//// }
//// for (int i = 0; i < 5; ++i) {
//// for (int j = i+1; j < 5 ; ++j) {
//// if(a[i]==a[j])
//// return false;
//// }
//// } //用哈西法来判断是否相同
// for (int i = 0; i < 5; ++i) {
// int temp = n % 10;
// if(a[temp]!=-1) return false;
//
// n = n/10;
// a[temp]=temp;
//
// }
// return true;
//
//} //运用哈西法 直接判断 是否又重复的数字
//bool nosame(int m ,int n){
// int a[10];
// memset(a,-1, sizeof(a));
// for (int i = 0; i < 5; ++i) {
// int temp = m % 10;
// if(a[temp]!=-1) return false;
//
// m=m/10;
// a[temp] = temp;
// }
// for (int i = 0; i < 5; ++i) {
// int temp = n % 10;
// if(a[temp]!=-1) return false;
//
// n = n/10;
// a[temp]=temp;
//
// }
// return true;
//
//}
//
//int main(){
// int n;
// cin>>n; //输入 要判断的数
// int divisor = 1234;//最小的可能符合条件的数就是01234
// int dividend;
// while(divisor<50000){
// if(nosame(divisor)){
// dividend = n * divisor;
// if(dividend<100000&&nosame(dividend,divisor)){
// if(dividend<10000) cout<<"0"<<dividend;
// else cout<<dividend;
// cout<<"/";
// if(divisor<10000) cout<<"0"<<divisor;
// else cout<<divisor;
// cout<<endl;
//
// }
// }
// divisor++;
// }
// return 0;
//} | [
"wshwbluebird@sina.cn"
] | wshwbluebird@sina.cn |
c39b92ae28bef30fa7b8281135e8d0e64e064597 | 509f78f852076c0ecf76e7d92e72f0f7521ffa06 | /Library/GraphicsTestRunner/Source/GraphicsConnection.cc | db52e64c011ba69f68f1891541aea670be68ada8 | [
"MIT"
] | permissive | chinmaygarde/radar | 3fe786efa68cb36bfdb98d031655090057f3be84 | ee79b5bd39b356b35e5205a861c97c7c7d132f71 | refs/heads/master | 2023-04-07T23:33:02.959108 | 2021-04-13T22:57:20 | 2021-04-13T22:57:20 | 39,474,689 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cc | /*
* This source file is part of the Radar project.
* Licensed under the MIT License. See LICENSE file for details.
*/
#include <Core/Platform.h>
#include "GraphicsConnection.h"
#if RL_OS_MAC
#include "GraphicsConnectionMac.h"
using PlatformGraphicsConnection = rl::testrunner::GraphicsConnectionMac;
#else
#error Unsupported Platform.
#endif
namespace rl {
namespace testrunner {
std::unique_ptr<GraphicsConnection> GraphicsConnection::Create(
const geom::Size& size) {
return std::make_unique<PlatformGraphicsConnection>(size);
}
GraphicsConnection::GraphicsConnection() = default;
GraphicsConnection::~GraphicsConnection() = default;
bool GraphicsConnection::isValid() const {
return _impl != nullptr && _impl->isValid();
}
bool GraphicsConnection::activate() {
return _impl != nullptr && _impl->activate();
}
bool GraphicsConnection::deactivate() {
return _impl != nullptr && _impl->deactivate();
}
} // namespace testrunner
} // namespace rl
| [
"chinmaygarde@google.com"
] | chinmaygarde@google.com |
fa7d254e25033132e08bac804e90ec53c4224be1 | cd08ca10256247f80b3095b94679c362dcd04961 | /src/FCone.cpp | b4fd10aa1637aab7c4371dc77c6a7f738ea61b34 | [] | no_license | Misttgun/RayTracingCpp | f0bdd9e3f4b2e59876824d295db103d67b99c659 | ab53b494a61f37b07f981c7cd1d52b8b4004cc88 | refs/heads/master | 2020-04-14T18:19:04.828374 | 2019-02-16T22:38:52 | 2019-02-16T22:38:52 | 164,014,321 | 0 | 0 | null | 2019-02-16T22:04:20 | 2019-01-03T19:28:12 | C++ | UTF-8 | C++ | false | false | 249 | cpp | #include "FCone.h"
bool FCone::intersect(const Ray& ray, Vector& impact) const
{
if (!Cone::intersect(ray, impact))
return false;
Vector local_impact = global_to_local_point(impact);
return local_impact[1] > -1.0f;
} | [
"girardot.vin@gmail.com"
] | girardot.vin@gmail.com |
744a27274a5e593aceea6d61591aac0d9e9eba33 | 3d6530151d783a3a600683ba254d35ec6561e941 | /lib/include/Shader.h | e05938fb14ca489f675a6f20a4a9b88ac0932f35 | [] | no_license | harry-z/3DApp | f987f7995c5252bd93868e243b663b2adb2cb838 | 216b1359e07c10ce687e2c84235702bb1a1bc504 | refs/heads/master | 2021-07-16T02:09:35.688215 | 2020-07-01T14:33:49 | 2020-07-01T14:33:49 | 175,924,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,806 | h | #pragma once
#include "Prereq.h"
#include "RendererTypes.h"
#define WORLD_MATRIX "WorldMatrix"
#define WORLD_VIEW_MATRIX "WorldViewMatrix"
#define WORLD_VIEW_PROJECTION_MATRIX "WorldViewProjectionMatrix"
#define INVERSE_WORLD_MATRIX "InverseWorldMatrix"
#define INVERSE_WORLD_VIEW_MATRIX "InverseWorldViewMatrix"
#define INVERSE_WORLD_VIEW_PROJECTION_MATRIX "InverseWorldViewProjectionMatrix"
#define VIEW_MATRIX "ViewMatrix"
#define VIEW_PROJECTION_MATRIX "ViewProjectionMatrix"
#define INVERSE_VIEW_MATRIX "InverseViewMatrix"
#define INVERSE_VIEW_PROJECTION_MATRIX "InverseViewProjectionMatrix"
#define PROJECTION_MATRIX "ProjectionMatrix"
#define INVERSE_PROJECTION_MATRIX "InverseProjectionMatrix"
#define CAMERA_POSITION "CameraPosition"
#define CAMERA_DIRECTION "CameraDirection"
#define NEAR_FAR_CLIP "NearFarClip"
struct AutoUpdatedShaderConstantIdStr
{
static IdString s_WorldMatrix;
static IdString s_WorldViewMatrix;
static IdString s_WorldViewProjMatrix;
static IdString s_InvWorldMatrix;
static IdString s_InvWorldViewMatrix;
static IdString s_InvWorldViewProjMatrix;
static IdString s_ViewMatrix;
static IdString s_ViewProjMatrix;
static IdString s_InvViewMatrix;
static IdString s_InvViewProjMatrix;
static IdString s_ProjMatrix;
static IdString s_InvProjMatrix;
static IdString s_CamPos;
static IdString s_CamDir;
static IdString s_NearFarClip;
};
struct ShaderParamInfo
{
IdString m_Name;
EShaderConstantType m_Type;
dword m_nLengthInBytes;
ShaderParamInfo()
: m_Type(EShaderConstantType::EShaderConstantType_Unknown)
, m_nLengthInBytes(0) {}
ShaderParamInfo(const String &szStr, EShaderConstantType Type, dword nSizeInBytes)
: m_Name(szStr)
, m_Type(Type)
, m_nLengthInBytes(nSizeInBytes) {}
};
struct ShaderUniformInfo
{
ShaderParamInfo m_ParamInfo;
dword m_nRegisterIndex;
dword m_nOffsetInBytes;
ShaderUniformInfo()
: m_nRegisterIndex(0xFFFFFFFF)
, m_nOffsetInBytes(0)
{}
ShaderUniformInfo(const String &szStr, EShaderConstantType Type, dword nRegisterIndex, dword nLengthInBytes, dword nOffsetInBytes)
: m_ParamInfo(szStr, Type, nLengthInBytes)
, m_nRegisterIndex(nRegisterIndex)
, m_nOffsetInBytes(nOffsetInBytes)
{}
};
struct AutoUpdatedUniform
{
dword m_nSizeInByte = 0;
byte *m_pData = nullptr;
~AutoUpdatedUniform()
{
if (m_pData != nullptr)
{
MEMFREE(m_pData);
}
}
};
class CShader
{
public:
virtual bool Load(EShaderType eType, const byte *pszShaderByteCode, dword nCodeSize) = 0;
virtual const ShaderUniformInfo& GetUniformInfoByName(const IdString &szName) const = 0;
inline word GetId() const { return m_nId; }
inline EShaderType GetShaderType() const { return m_Type; }
inline dword GetShaderByteCodeLength() const { return m_nByteCodeLen; }
inline const byte* GetShaderByteCode() const { return m_pByteCode; }
protected:
CShader() {}
virtual ~CShader() {}
virtual bool FillVariableMap(LPCVOID pFunction, dword nCodeSize) = 0;
protected:
word m_nId;
EShaderType m_Type = EShaderType::EShaderType_Unknown;
dword m_nByteCodeLen = 0;
byte *m_pByteCode = nullptr;
CMap<IdString, ShaderUniformInfo> m_VariableMap;
};
class CCamera;
class CShaderManager
{
public:
CShaderManager() { InitializeAutoShaderConstantMap(); }
virtual ~CShaderManager() {}
virtual bool LoadShaders() = 0;
inline CShader* FindShaderByName(const String &szName) {
IdString IdStr(szName);
ShaderMap::_MyIterType ShaderIterator = m_ShaderMap.Find(IdStr);
return ShaderIterator ? ShaderIterator.Value() : nullptr;
}
inline CShader* FindShaderById(word nShaderId) {
return m_ShaderArr.IsValidIndex(nShaderId - 1) ? m_ShaderArr[nShaderId - 1] : nullptr;
}
CShader* GetDefaultVertexShader() { return m_pDefaultVertexShader; }
CShader* GetDefaultPixelShader() { return m_pDefaultPixelShader; }
AutoUpdatedUniform& GetAutoUpdatedUniform(EAutoUpdatedConstant Constant);
const AutoUpdatedUniform& GetAutoUpdatedUniform(EAutoUpdatedConstant Constant) const;
void UpdateShaderUniformPerFrame(CCamera *pCamera);
private:
void InitializeAutoShaderConstantMap();
protected:
using ShaderMap = CMap<IdString, CShader*>;
ShaderMap m_ShaderMap;
using AutoUpdatedConstants = CArray<AutoUpdatedUniform>;
AutoUpdatedConstants m_AutoUpdatedConstants;
using ShaderArr = CArray<CShader*>;
ShaderArr m_ShaderArr;
CShader *m_pDefaultVertexShader = nullptr;
CShader *m_pDefaultPixelShader = nullptr;
}; | [
"shinji_akari@163.com"
] | shinji_akari@163.com |
ee188d34ed4b67d0393d66c91eda3013b3a90a65 | 5f9cba50fd27fe44c8c974efcc3d539b1b082850 | /sources/pawn.cpp | c787654ba39080244bf60819ab41f666fb25895e | [] | no_license | wangobango/GrafikaSzachy3D | 1119f4dd979d9928134ef899cf70b6321aab1086 | 5a3da38c00ad518d979b97695008364b71e8fa5a | refs/heads/master | 2020-03-18T04:10:13.752218 | 2018-06-27T22:48:28 | 2018-06-27T22:48:28 | 134,273,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | cpp | #include "headers/pawn.h"
Pawn::Pawn(bool white,ShaderProgram* sp,GLuint tex):Model(sp,tex){
if(white){
color =1;
texPath = "sources/white.png";
}
else{
color = 0;
texPath = "black.png";
}
path="models/pion.obj";
parse();
loadArrays();
prepare();
}
void Pawn::draw(glm::mat4 mP,glm::mat4 mV){
shaderProgram->use();
glUniformMatrix4fv(shaderProgram->getUniformLocation("P"),1, false, glm::value_ptr(mP));
glUniformMatrix4fv(shaderProgram->getUniformLocation("V"),1, false, glm::value_ptr(mV));
glUniformMatrix4fv(shaderProgram->getUniformLocation("M"),1, false, glm::value_ptr(M));
if(color){
glUniform1i(shaderProgram->getUniformLocation("textureMap0"),0);
glActiveTexture(GL_TEXTURE0);
}
else{
glActiveTexture(GL_TEXTURE1);
glUniform1i(shaderProgram->getUniformLocation("textureMap0"),1);
}
glBindTexture(GL_TEXTURE_2D,tex);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES,0,vertex_count);
glBindVertexArray(0);
}
| [
"bartnik.emil@gmail.com"
] | bartnik.emil@gmail.com |
a305d5dc624328634bf5f58aa2b8ba8fe3dfe454 | 7145976f1f3b07e6baa4be1b1e8b13390d6ccd69 | /src/cv_utils.cpp | 8302805663b97bc58df3eed51e4ce2111ef2eff6 | [] | no_license | pmusau17/ros2_utils | 8751aaac17888ae1d17f68e59e9b82e394d35036 | 90071b274b4b1719f5c4c9bf8bfe2444fe55d75f | refs/heads/master | 2023-07-13T19:59:46.385007 | 2021-08-27T00:53:19 | 2021-08-27T00:53:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,046 | cpp | // Copyright 2021 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ros2_utils/cv_utils.hpp"
#include <string>
#include "cv_bridge/cv_bridge.h"
#include "sensor_msgs/msg/image.hpp"
namespace ros2_utils
{
std::string
mat_type2encoding(int mat_type)
{
switch (mat_type) {
case CV_8UC1:
return "mono8";
case CV_8UC3:
return "bgr8";
case CV_16SC1:
return "mono16";
case CV_8UC4:
return "rgba8";
default:
throw std::runtime_error("unsupported encoding type");
}
}
int
encoding2mat_type(const std::string & encoding)
{
if (encoding == "mono8") {
return CV_8UC1;
} else if (encoding == "bgr8") {
return CV_8UC3;
} else if (encoding == "mono16") {
return CV_16SC1;
} else if (encoding == "rgba8") {
return CV_8UC4;
}
throw std::runtime_error("Unsupported mat type");
}
sensor_msgs::msg::Image::UniquePtr
toImageMsg(const cv::Mat & image, const rclcpp::Time current_time, const char * frame_id)
{
sensor_msgs::msg::Image::UniquePtr image_msg(new sensor_msgs::msg::Image());
image_msg->header.stamp = current_time;
image_msg->header.frame_id = frame_id;
image_msg->height = image.rows;
image_msg->width = image.cols;
image_msg->encoding = mat_type2encoding(image.type());
image_msg->is_bigendian = false;
image_msg->step = static_cast<sensor_msgs::msg::Image::_step_type>(image.step);
image_msg->data.assign(image.datastart, image.dataend);
return image_msg;
}
} // namespace ros2_utils
| [
"michael.jeronimo@openrobotics.org"
] | michael.jeronimo@openrobotics.org |
0a1c7100188e5d853373783375bd18e6296bec2b | 7a296b69842c34ea234dea660a1b242d2e0ab11c | /DigitalDesign/pseudoToVerilog/Component.h | ed4a11a2defad61e31e5778289d8996f93b1227c | [] | no_license | magarcia1/School | ee3353fd48207de6b11607a5082a43aadb8799d0 | 00f034ec8686197552d058c91e962df762c551f8 | refs/heads/master | 2021-01-01T19:48:00.357454 | 2017-07-28T21:14:52 | 2017-07-28T21:14:52 | 98,679,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,404 | h | //------------------------------------------------------------------------------------------------
//
// Author: Rubi Ballesteros and Miguel Garcia
// Date Created: September 2015
//
// Description: Data type for inputs outputs and wires
//
//------------------------------------------------------------------------------------------------
#ifndef COMPONENT_H
#define COMPONENT_H
//------------------------------------------------------------------------------------------------
#include <string>
#include <vector>
#include "Inoutput.h"
using namespace std;
//------------------------------------------------------------------------------------------------
class Component {
private:
string type;
string name;
vector<Inoutput*> inputs;
Inoutput* output;
int sizeoOutput;
public:
Component();
Component(string atype, string aname);
~Component();
void setType(string type);
void setName(string name);
void insertInput(Inoutput* anInput);
void setOutput(Inoutput* anOutput);
void setSize(int theSize);
string getType();
string getName();
Inoutput* getInput(int i);
Inoutput* getOutput();
int getSize();
int getInputSize();
void replaceInput(int i, Inoutput* newPut);
};
//------------------------------------------------------------------------------------------------
#endif
//------------------------------------------------------------------------------------------------
| [
"miguelgarcia@Miguels-MacBook-Pro.local"
] | miguelgarcia@Miguels-MacBook-Pro.local |
b06f62bd2802c046df14888a48a8617775efaccd | 68f51dec0a05162e687da24b5ba4f1b8fc7d5fb8 | /include/draw/ShaderBind.h | 05207ae31b95825cefad9944d5bb476095b80a23 | [] | no_license | tearitco/VastSpace | d4a1059d4ad2359ee7818e6980762195def7c5e0 | 36313c3d1defe2c44dedd7eef8a2be4b735f99f7 | refs/heads/master | 2022-04-25T18:12:11.086174 | 2019-11-16T05:15:39 | 2019-11-16T05:15:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,226 | h | #ifndef DRAW_SHADERBIND_H
#define DRAW_SHADERBIND_H
/** \file
* \brief Definition of ShaderBind class tree.
*/
#include "export.h"
#include "OpenGLState.h"
#include "antiglut.h"
#ifdef _WIN32
#define WINVER 0x0500
#define _WIN32_WINNT 0x0500
#include <windows.h>
#endif
#include <cpplib/vec3.h>
#include <GL/gl.h>
/// \brief A class that binds shader object name with location indices.
///
/// The specification of location names are specific to this ShadowMap class's use.
struct EXPORT ShaderBind{
GLuint shader;
GLint textureEnableLoc;
GLint texture2EnableLoc;
GLint textureLoc;
GLint texture2Loc;
GLint exposureLoc;
GLint tonemapLoc;
ShaderBind(GLuint shader = 0) : shader(shader),
textureEnableLoc(-1),
texture2EnableLoc(-1),
textureLoc(-1),
texture2Loc(-1),
exposureLoc(-1),
tonemapLoc(-1){}
~ShaderBind();
virtual void getUniformLocations();
void use()const;
void enableTextures(bool texture1, bool texture2 = false)const;
protected:
virtual void useInt()const;
};
EXPORT extern OpenGLState::weak_ptr<const ShaderBind*> g_currentShaderBind;
/// Binding of shadow mapping shader program.
struct EXPORT ShadowMapShaderBind : virtual ShaderBind{
GLint shadowmapLoc;
GLint shadowmap2Loc;
GLint shadowmap3Loc;
GLint shadowMatricesLoc;
GLint shadowSlopeScaledBiasLoc;
GLfloat shadowSlopeScaledBias;
ShadowMapShaderBind(GLuint shader = 0) :
ShaderBind(shader),
shadowmapLoc(-1),
shadowmap2Loc(-1),
shadowmap3Loc(-1){}
void build();
void getUniformLocations();
protected:
void useInt()const;
};
/// Binding of additive (brightness mapped) texturing shader program.
struct EXPORT AdditiveShaderBind : virtual ShaderBind{
GLint intensityLoc;
AdditiveShaderBind(GLuint shader = 0) : ShaderBind(0),
intensityLoc(-1){}
void build();
void getUniformLocations();
void setIntensity(const Vec3f&)const;
protected:
void useInt()const;
};
/// Binding of additive and shadow mapped shader program.
struct AdditiveShadowMapShaderBind : ShadowMapShaderBind, AdditiveShaderBind{
AdditiveShadowMapShaderBind(GLuint shader = 0) : ShadowMapShaderBind(shader), AdditiveShaderBind(shader){
}
void build();
void getUniformLocations();
protected:
void useInt()const;
};
#endif
| [
"masahiro.sakuta@gmail.com"
] | masahiro.sakuta@gmail.com |
e0c1caacb36f1197e8e13c1639359afa0cd70b81 | 327b1664448963ec7847e65c883a7edcc78ecb8b | /删除字符串中的子串.cpp | 203ff5f419be8bb3b71f3ac54a7075c14db3795b | [] | no_license | cydem/xiaopa | df1f021e4bfcc9355d1b380d95db286db8eec55d | 0f1e734f545265d77e250bcb213d713c2f30b213 | refs/heads/master | 2021-01-11T06:54:38.376516 | 2017-02-02T05:17:32 | 2017-02-02T05:17:32 | 72,336,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | cpp | /**************************************************************************************
*输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
* 输入格式:
* 输入在2行中分别给出不超过80个字符长度的、以回车结束的2个非空字符串,对应S1和S2。
* Tomcat is a male ccatat
* cat
* 输出格式:
* 在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。
* Tom is a male
***************************************************************************************/
/——————————————————————————————————————法1————————————————————————————————————————————/
#include <stdio.h>
#include <string.h>
#define N 80
void del_str(char *str, char *s, char *resultstr) //删除函数
{
int i,str_len,s_len,r_len;
strcpy(resultstr,str);
char *p;
s_len = strlen(s);
r_len = strlen(resultstr);
while((p=strstr(resultstr,s)) != NULL){
for( i = p - resultstr; i <= r_len - s_len;i++ ) //字符串左移
resultstr[i] = resultstr[i+s_len];
r_len = strlen(resultstr);
}
}
int main(){
char s1[N+1],s2[N+1],s3[N+1];
gets(s1);
gets(s2);
del_str(s1,s2,s3);
printf("%s",s3);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
9b018b36708e52e71a6ae2c4f6812456f5ef34db | b9a45f62bb90e66e12ad8b6e6247f7b62acacf0d | /src/Platform/Window/InputManager.cpp | b238f4d8ab95db357d6ba21ab851a17bd21e2f19 | [
"BSD-3-Clause"
] | permissive | WhiteBlackGoose/MxEngine | 4ce48aa14a000354103ea2f2e27b73c62ff251d4 | 41018d0e6ceb7d760be22721865cd88cca362a1d | refs/heads/master | 2021-07-05T13:58:15.616787 | 2020-06-27T13:45:46 | 2020-06-27T13:45:46 | 242,322,338 | 1 | 0 | BSD-3-Clause | 2020-05-13T08:13:37 | 2020-02-22T10:31:23 | C++ | UTF-8 | C++ | false | false | 870 | cpp | #include "InputManager.h"
#include "Core/Application/Application.h"
namespace MxEngine
{
#define WND(func, ...) Application::Get()->GetWindow().func(__VA_ARGS__)
Vector2 InputManager::GetCursorPosition()
{
return WND(GetCursorPosition);
}
void InputManager::SetCursorPosition(const Vector2& pos)
{
WND(UseCursorPosition, pos);
}
CursorMode InputManager::GetCursorMode()
{
return WND(GetCursorMode);
}
void InputManager::SetCursorMode(CursorMode mode)
{
WND(UseCursorMode, mode);
}
bool InputManager::IsKeyHeld(KeyCode key)
{
return WND(IsKeyHeld, key);
}
bool InputManager::IsKeyPressed(KeyCode key)
{
return WND(IsKeyPressed, key);
}
bool InputManager::IsKeyReleased(KeyCode key)
{
return WND(IsKeyReleased, key);
}
} | [
"Sasha.potapov2002@yandex.ru"
] | Sasha.potapov2002@yandex.ru |
be1ae048e6f669aef19c543c7b55c45095fbeeee | 935927010571e2f820e70cead9a1fd471d88ea16 | /Lomba Lomba/2021/IDEAFUSE/warmup/D.cpp | d9f492e7a26ea5632deebde223a590a8e518dace | [] | no_license | muhammadhasan01/cp | ebb0869b94c2a2ab9487861bd15a8e62083193ef | 3b0152b9621c81190dd1a96dde0eb80bff284268 | refs/heads/master | 2023-05-30T07:18:02.094877 | 2023-05-21T22:03:57 | 2023-05-21T22:03:57 | 196,739,005 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
vector<pair<int, int>> p(n);
for (int i = 0; i < n; i++) {
auto& [x, y] = p[i];
cin >> x >> y;
}
int ans = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
auto& [xi, yi] = p[i];
auto& [xj, yj] = p[j];
ans = max(ans, abs(xi - xj));
ans = max(ans, abs(yi - yj));
}
}
cout << ans * ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tc = 1;
cin >> tc;
for (int T = 1; T <= tc; T++) {
cout << "Case #" << T << ": ";
solve();
}
return 0;
} | [
"39514247+muhammadhasan01@users.noreply.github.com"
] | 39514247+muhammadhasan01@users.noreply.github.com |
e065bbbbb3f6c891ffcbecdcae3b96d903ef2785 | 14248aaedfa5f77c7fc5dd8c3741604fb987de5c | /luogu/P4931.cpp | 900147886ab51a9b76f05043b99a646bc5ed065e | [] | no_license | atubo/online-judge | fc51012465a1bd07561b921f5c7d064e336a4cd2 | 8774f6c608bb209a1ebbb721d6bbfdb5c1d1ce9b | refs/heads/master | 2021-11-22T19:48:14.279016 | 2021-08-29T23:16:16 | 2021-08-29T23:16:16 | 13,290,232 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | // https://www.luogu.com.cn/problem/P4931
// [MtOI2018]情侣?给我烧了!(加强版)
#include <bits/stdc++.h>
using namespace std;
const int MOD = 998244353;
const int MAXN = 5000010;
int F[MAXN];
int FC[MAXN], FI[MAXN];
int P[MAXN];
int INV[MAXN];
int mul(int64_t a, int64_t b) {
return (a * b) % MOD;
}
int add(int64_t a, int64_t b) {
return (a + b) % MOD;
}
void init() {
F[0] = 1;
F[1] = 0;
for (int i = 2; i < MAXN; i++) {
F[i] = mul(mul(2*i, 2*i-2), add(F[i-1], mul(2*i-2, F[i-2])));
}
P[0] = 1;
for (int i = 1; i < MAXN; i++) {
P[i] = (P[i-1] * 2) % MOD;
}
INV[1] = 1;
for (int i = 2; i < MAXN; i++) {
INV[i] = mul(MOD - MOD/i, INV[MOD%i]);
}
FC[0] = 1, FI[0] = 1;
for (int i = 1; i < MAXN; i++) {
FC[i] = mul(FC[i-1], i);
FI[i] = mul(FI[i-1], INV[i]);
}
}
int main() {
init();
int t;
scanf("%d", &t);
while (t--) {
int n, k;
scanf("%d%d", &n, &k);
int ans = mul(P[k], F[n-k]);
ans = mul(mul(FC[n], FC[n]), ans);
ans = mul(ans, FI[k]);
ans = mul(ans, mul(FI[n-k], FI[n-k]));
printf("%d\n", ans);
}
return 0;
}
| [
"err722@yahoo.com"
] | err722@yahoo.com |
de366a6e67ce36e1140f4a5ec0a85a838d149c6a | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_5/MP+dmb.sypl+dmb.stap.c.cbmc.cpp | d93aa7fc7d38bcf0bca63e99d5a8d8fef7d467f6 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 29,430 | cpp | // Global variabls:
// 0:vars:2
// 2:atom_1_X0_1:1
// 3:atom_1_X2_0:1
// Local global variabls:
// 0:thr0:1
// 1:thr1:1
#define ADDRSIZE 4
#define LOCALADDRSIZE 2
#define NTHREAD 3
#define NCONTEXT 5
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// Declare arrays for intial value version in contexts
int local_mem[LOCALADDRSIZE];
// Dumping initializations
local_mem[0+0] = 0;
local_mem[1+0] = 0;
int cstart[NTHREAD];
int creturn[NTHREAD];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NTHREAD*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NTHREAD*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NTHREAD*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NTHREAD*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NTHREAD*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NTHREAD*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NTHREAD*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NTHREAD*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NTHREAD*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NTHREAD];
int cdy[NTHREAD];
int cds[NTHREAD];
int cdl[NTHREAD];
int cisb[NTHREAD];
int caddr[NTHREAD];
int cctrl[NTHREAD];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
mem(0,1) = meminit(0,1);
co(0,1) = coinit(0,1);
delta(0,1) = deltainit(0,1);
mem(0,2) = meminit(0,2);
co(0,2) = coinit(0,2);
delta(0,2) = deltainit(0,2);
mem(0,3) = meminit(0,3);
co(0,3) = coinit(0,3);
delta(0,3) = deltainit(0,3);
mem(0,4) = meminit(0,4);
co(0,4) = coinit(0,4);
delta(0,4) = deltainit(0,4);
co(1,0) = 0;
delta(1,0) = -1;
mem(1,1) = meminit(1,1);
co(1,1) = coinit(1,1);
delta(1,1) = deltainit(1,1);
mem(1,2) = meminit(1,2);
co(1,2) = coinit(1,2);
delta(1,2) = deltainit(1,2);
mem(1,3) = meminit(1,3);
co(1,3) = coinit(1,3);
delta(1,3) = deltainit(1,3);
mem(1,4) = meminit(1,4);
co(1,4) = coinit(1,4);
delta(1,4) = deltainit(1,4);
co(2,0) = 0;
delta(2,0) = -1;
mem(2,1) = meminit(2,1);
co(2,1) = coinit(2,1);
delta(2,1) = deltainit(2,1);
mem(2,2) = meminit(2,2);
co(2,2) = coinit(2,2);
delta(2,2) = deltainit(2,2);
mem(2,3) = meminit(2,3);
co(2,3) = coinit(2,3);
delta(2,3) = deltainit(2,3);
mem(2,4) = meminit(2,4);
co(2,4) = coinit(2,4);
delta(2,4) = deltainit(2,4);
co(3,0) = 0;
delta(3,0) = -1;
mem(3,1) = meminit(3,1);
co(3,1) = coinit(3,1);
delta(3,1) = deltainit(3,1);
mem(3,2) = meminit(3,2);
co(3,2) = coinit(3,2);
delta(3,2) = deltainit(3,2);
mem(3,3) = meminit(3,3);
co(3,3) = coinit(3,3);
delta(3,3) = deltainit(3,3);
mem(3,4) = meminit(3,4);
co(3,4) = coinit(3,4);
delta(3,4) = deltainit(3,4);
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !36, metadata !DIExpression()), !dbg !45
// br label %label_1, !dbg !46
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !44), !dbg !47
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !37, metadata !DIExpression()), !dbg !48
// call void @llvm.dbg.value(metadata i64 1, metadata !40, metadata !DIExpression()), !dbg !48
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !49
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbsy(), !dbg !50
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,2+0));
ASSUME(cdy[1] >= cw(1,3+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,2+0));
ASSUME(cdy[1] >= cr(1,3+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !41, metadata !DIExpression()), !dbg !51
// call void @llvm.dbg.value(metadata i64 1, metadata !43, metadata !DIExpression()), !dbg !51
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !52
// ST: Guess
// : Release
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l22_c3
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l22_c3
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
ASSUME(cw(1,0+1*1) >= cr(1,0+0));
ASSUME(cw(1,0+1*1) >= cr(1,0+1));
ASSUME(cw(1,0+1*1) >= cr(1,2+0));
ASSUME(cw(1,0+1*1) >= cr(1,3+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+1));
ASSUME(cw(1,0+1*1) >= cw(1,2+0));
ASSUME(cw(1,0+1*1) >= cw(1,3+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
is(1,0+1*1) = iw(1,0+1*1);
cs(1,0+1*1) = cw(1,0+1*1);
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !53
ret_thread_1 = (- 1);
goto T1BLOCK_END;
T1BLOCK_END:
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !56, metadata !DIExpression()), !dbg !68
// br label %label_2, !dbg !50
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !67), !dbg !70
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !58, metadata !DIExpression()), !dbg !71
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !53
// LD: Guess
// : Acquire
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l28_c15
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
ASSUME(cr(2,0+1*1) >= cx(2,0+1*1));
ASSUME(cr(2,0+1*1) >= cs(2,0+0));
ASSUME(cr(2,0+1*1) >= cs(2,0+1));
ASSUME(cr(2,0+1*1) >= cs(2,2+0));
ASSUME(cr(2,0+1*1) >= cs(2,3+0));
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
ASSUME((!(( (cw(2,0+1*1) < 1) && (1 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(2,0+1*1) < 2) && (2 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(2,0+1*1) < 3) && (3 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(2,0+1*1) < 4) && (4 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
cl[2] = max(cl[2],cr(2,0+1*1));
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !60, metadata !DIExpression()), !dbg !71
// %conv = trunc i64 %0 to i32, !dbg !54
// call void @llvm.dbg.value(metadata i32 %conv, metadata !57, metadata !DIExpression()), !dbg !68
// call void (...) @dmbst(), !dbg !55
// dumbst: Guess
cds[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cds[2] >= cdy[2]);
ASSUME(cds[2] >= cw(2,0+0));
ASSUME(cds[2] >= cw(2,0+1));
ASSUME(cds[2] >= cw(2,2+0));
ASSUME(cds[2] >= cw(2,3+0));
ASSUME(creturn[2] >= cds[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !62, metadata !DIExpression()), !dbg !75
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !57
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l30_c15
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r1 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r1 = buff(2,0);
ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r1 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %1, metadata !64, metadata !DIExpression()), !dbg !75
// %conv4 = trunc i64 %1 to i32, !dbg !58
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !61, metadata !DIExpression()), !dbg !68
// %cmp = icmp eq i32 %conv, 1, !dbg !59
creg__r0__1_ = max(0,creg_r0);
// %conv5 = zext i1 %cmp to i32, !dbg !59
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !65, metadata !DIExpression()), !dbg !68
// store i32 %conv5, i32* @atom_1_X0_1, align 4, !dbg !60, !tbaa !61
// ST: Guess
iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l32_c15
old_cw = cw(2,2);
cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l32_c15
// Check
ASSUME(active[iw(2,2)] == 2);
ASSUME(active[cw(2,2)] == 2);
ASSUME(sforbid(2,cw(2,2))== 0);
ASSUME(iw(2,2) >= creg__r0__1_);
ASSUME(iw(2,2) >= 0);
ASSUME(cw(2,2) >= iw(2,2));
ASSUME(cw(2,2) >= old_cw);
ASSUME(cw(2,2) >= cr(2,2));
ASSUME(cw(2,2) >= cl[2]);
ASSUME(cw(2,2) >= cisb[2]);
ASSUME(cw(2,2) >= cdy[2]);
ASSUME(cw(2,2) >= cdl[2]);
ASSUME(cw(2,2) >= cds[2]);
ASSUME(cw(2,2) >= cctrl[2]);
ASSUME(cw(2,2) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,2) = (r0==1);
mem(2,cw(2,2)) = (r0==1);
co(2,cw(2,2))+=1;
delta(2,cw(2,2)) = -1;
ASSUME(creturn[2] >= cw(2,2));
// %cmp6 = icmp eq i32 %conv4, 0, !dbg !65
creg__r1__0_ = max(0,creg_r1);
// %conv7 = zext i1 %cmp6 to i32, !dbg !65
// call void @llvm.dbg.value(metadata i32 %conv7, metadata !66, metadata !DIExpression()), !dbg !68
// store i32 %conv7, i32* @atom_1_X2_0, align 4, !dbg !66, !tbaa !61
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l34_c15
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l34_c15
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= creg__r1__0_);
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r1==0);
mem(3,cw(2,3)) = (r1==0);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !67
ret_thread_2 = (- 1);
goto T2BLOCK_END;
T2BLOCK_END:
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !94, metadata !DIExpression()), !dbg !110
// call void @llvm.dbg.value(metadata i8** %argv, metadata !95, metadata !DIExpression()), !dbg !110
// %0 = bitcast i64* %thr0 to i8*, !dbg !57
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #6, !dbg !57
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !96, metadata !DIExpression()), !dbg !112
// %1 = bitcast i64* %thr1 to i8*, !dbg !59
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #6, !dbg !59
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !100, metadata !DIExpression()), !dbg !114
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !101, metadata !DIExpression()), !dbg !115
// call void @llvm.dbg.value(metadata i64 0, metadata !103, metadata !DIExpression()), !dbg !115
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !62
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l42_c3
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l42_c3
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !104, metadata !DIExpression()), !dbg !117
// call void @llvm.dbg.value(metadata i64 0, metadata !106, metadata !DIExpression()), !dbg !117
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !64
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l43_c3
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l43_c3
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// store i32 0, i32* @atom_1_X0_1, align 4, !dbg !65, !tbaa !66
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l44_c15
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l44_c15
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// store i32 0, i32* @atom_1_X2_0, align 4, !dbg !70, !tbaa !66
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l45_c15
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l45_c15
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #6, !dbg !71
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #6, !dbg !72
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %2 = load i64, i64* %thr0, align 8, !dbg !73, !tbaa !74
r3 = local_mem[0];
// %call4 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !76
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %3 = load i64, i64* %thr1, align 8, !dbg !77, !tbaa !74
r4 = local_mem[1];
// %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !78
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %4 = load i32, i32* @atom_1_X0_1, align 4, !dbg !79, !tbaa !66
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l53_c12
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r5 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r5 = buff(0,2);
ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0));
ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0));
ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0));
ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0));
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r5 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i32 %4, metadata !107, metadata !DIExpression()), !dbg !110
// %5 = load i32, i32* @atom_1_X2_0, align 4, !dbg !80, !tbaa !66
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l54_c12
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r6 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r6 = buff(0,3);
ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0));
ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0));
ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0));
ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0));
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r6 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i32 %5, metadata !108, metadata !DIExpression()), !dbg !110
// %and = and i32 %4, %5, !dbg !81
creg_r7 = max(creg_r5,creg_r6);
r7 = r5 & r6;
// call void @llvm.dbg.value(metadata i32 %and, metadata !109, metadata !DIExpression()), !dbg !110
// %cmp = icmp eq i32 %and, 1, !dbg !82
creg__r7__1_ = max(0,creg_r7);
// br i1 %cmp, label %if.then, label %if.end, !dbg !84
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg__r7__1_);
if((r7==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([105 x i8], [105 x i8]* @.str.1, i64 0, i64 0), i32 noundef 56, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #7, !dbg !85
// unreachable, !dbg !85
r8 = 1;
goto T0BLOCK_END;
T0BLOCK2:
// %6 = bitcast i64* %thr1 to i8*, !dbg !88
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %6) #6, !dbg !88
// %7 = bitcast i64* %thr0 to i8*, !dbg !88
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %7) #6, !dbg !88
// ret i32 0, !dbg !89
ret_thread_0 = 0;
goto T0BLOCK_END;
T0BLOCK_END:
ASSUME(meminit(0,1) == mem(0,0));
ASSUME(coinit(0,1) == co(0,0));
ASSUME(deltainit(0,1) == delta(0,0));
ASSUME(meminit(0,2) == mem(0,1));
ASSUME(coinit(0,2) == co(0,1));
ASSUME(deltainit(0,2) == delta(0,1));
ASSUME(meminit(0,3) == mem(0,2));
ASSUME(coinit(0,3) == co(0,2));
ASSUME(deltainit(0,3) == delta(0,2));
ASSUME(meminit(0,4) == mem(0,3));
ASSUME(coinit(0,4) == co(0,3));
ASSUME(deltainit(0,4) == delta(0,3));
ASSUME(meminit(1,1) == mem(1,0));
ASSUME(coinit(1,1) == co(1,0));
ASSUME(deltainit(1,1) == delta(1,0));
ASSUME(meminit(1,2) == mem(1,1));
ASSUME(coinit(1,2) == co(1,1));
ASSUME(deltainit(1,2) == delta(1,1));
ASSUME(meminit(1,3) == mem(1,2));
ASSUME(coinit(1,3) == co(1,2));
ASSUME(deltainit(1,3) == delta(1,2));
ASSUME(meminit(1,4) == mem(1,3));
ASSUME(coinit(1,4) == co(1,3));
ASSUME(deltainit(1,4) == delta(1,3));
ASSUME(meminit(2,1) == mem(2,0));
ASSUME(coinit(2,1) == co(2,0));
ASSUME(deltainit(2,1) == delta(2,0));
ASSUME(meminit(2,2) == mem(2,1));
ASSUME(coinit(2,2) == co(2,1));
ASSUME(deltainit(2,2) == delta(2,1));
ASSUME(meminit(2,3) == mem(2,2));
ASSUME(coinit(2,3) == co(2,2));
ASSUME(deltainit(2,3) == delta(2,2));
ASSUME(meminit(2,4) == mem(2,3));
ASSUME(coinit(2,4) == co(2,3));
ASSUME(deltainit(2,4) == delta(2,3));
ASSUME(meminit(3,1) == mem(3,0));
ASSUME(coinit(3,1) == co(3,0));
ASSUME(deltainit(3,1) == delta(3,0));
ASSUME(meminit(3,2) == mem(3,1));
ASSUME(coinit(3,2) == co(3,1));
ASSUME(deltainit(3,2) == delta(3,1));
ASSUME(meminit(3,3) == mem(3,2));
ASSUME(coinit(3,3) == co(3,2));
ASSUME(deltainit(3,3) == delta(3,2));
ASSUME(meminit(3,4) == mem(3,3));
ASSUME(coinit(3,4) == co(3,3));
ASSUME(deltainit(3,4) == delta(3,3));
ASSERT(r8== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
3f1c341e55777896704de4dea4d503547fcec894 | b64b0ea5aab9b860bac63aef5aefa8f65994c66b | /nanomind/src/test_cpp.cpp | 30e70be2c0c128147120a5fd7571c1916e714066 | [] | no_license | Minimal88/arm | 093cf9860ee03eea0a37e6bbf502800046732fd0 | 597aaf1ca8898ce2bb103800101e1b150762f709 | refs/heads/master | 2021-01-22T11:27:48.251568 | 2014-11-28T07:50:52 | 2014-11-28T07:50:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | cpp | /*
* test_cpp.cpp
*
* Created on: 19/07/2011
* Author: johan
*/
#include <stdio.h>
#if ENABLE_CPP
using namespace std;
class test_rectangle {
int *width, *height;
public:
test_rectangle(int a, int b) {
printf("Constructor overload with arguments\r\n");
width = new int;
height = new int;
*width = a;
*height = b;
}
test_rectangle() {
printf("Constructor default \r\n");
width = new int;
height = new int;
*width = 10;
*height = 20;
}
~test_rectangle() {
printf("Destructor\r\n");
delete width;
delete height;
}
int area() {
return (*width * *height);
}
};
test_rectangle rectb;
extern "C" void test_cpp_call(void) {
printf("C-function calling C++ object\r\n");
test_rectangle recta(3, 4);
printf("recta area: %u\r\n", recta.area());
printf("rectb area: %u\r\n", rectb.area());
}
#endif
| [
"991353018@qq.com"
] | 991353018@qq.com |
cd211929a12f5adf7d0c989b8673eff948c5b0fd | 0dca3325c194509a48d0c4056909175d6c29f7bc | /domain/src/model/QueryAuctionDetailResult.cc | 41ebc4f308685ce1c1fd51f691a2bd588d6a7846 | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,039 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/domain/model/QueryAuctionDetailResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Domain;
using namespace AlibabaCloud::Domain::Model;
QueryAuctionDetailResult::QueryAuctionDetailResult() :
ServiceResult()
{}
QueryAuctionDetailResult::QueryAuctionDetailResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryAuctionDetailResult::~QueryAuctionDetailResult()
{}
void QueryAuctionDetailResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["DomainName"].isNull())
domainName_ = value["DomainName"].asString();
if(!value["AuctionId"].isNull())
auctionId_ = value["AuctionId"].asString();
if(!value["DomainType"].isNull())
domainType_ = value["DomainType"].asString();
if(!value["BookedPartner"].isNull())
bookedPartner_ = value["BookedPartner"].asString();
if(!value["PartnerType"].isNull())
partnerType_ = value["PartnerType"].asString();
if(!value["Currency"].isNull())
currency_ = value["Currency"].asString();
if(!value["YourCurrentBid"].isNull())
yourCurrentBid_ = std::stof(value["YourCurrentBid"].asString());
if(!value["YourMaxBid"].isNull())
yourMaxBid_ = std::stof(value["YourMaxBid"].asString());
if(!value["HighBid"].isNull())
highBid_ = std::stof(value["HighBid"].asString());
if(!value["NextValidBid"].isNull())
nextValidBid_ = std::stof(value["NextValidBid"].asString());
if(!value["ReserveMet"].isNull())
reserveMet_ = value["ReserveMet"].asString() == "true";
if(!value["TransferInPrice"].isNull())
transferInPrice_ = std::stof(value["TransferInPrice"].asString());
if(!value["PayPrice"].isNull())
payPrice_ = std::stof(value["PayPrice"].asString());
if(!value["HighBidder"].isNull())
highBidder_ = value["HighBidder"].asString();
if(!value["Status"].isNull())
status_ = value["Status"].asString();
if(!value["PayStatus"].isNull())
payStatus_ = value["PayStatus"].asString();
if(!value["ProduceStatus"].isNull())
produceStatus_ = value["ProduceStatus"].asString();
if(!value["AuctionEndTime"].isNull())
auctionEndTime_ = std::stol(value["AuctionEndTime"].asString());
if(!value["BookEndTime"].isNull())
bookEndTime_ = std::stol(value["BookEndTime"].asString());
if(!value["PayEndTime"].isNull())
payEndTime_ = std::stol(value["PayEndTime"].asString());
if(!value["DeliveryTime"].isNull())
deliveryTime_ = std::stol(value["DeliveryTime"].asString());
if(!value["FailCode"].isNull())
failCode_ = value["FailCode"].asString();
}
std::string QueryAuctionDetailResult::getPartnerType()const
{
return partnerType_;
}
std::string QueryAuctionDetailResult::getStatus()const
{
return status_;
}
float QueryAuctionDetailResult::getTransferInPrice()const
{
return transferInPrice_;
}
std::string QueryAuctionDetailResult::getPayStatus()const
{
return payStatus_;
}
std::string QueryAuctionDetailResult::getDomainName()const
{
return domainName_;
}
std::string QueryAuctionDetailResult::getHighBidder()const
{
return highBidder_;
}
std::string QueryAuctionDetailResult::getFailCode()const
{
return failCode_;
}
float QueryAuctionDetailResult::getYourCurrentBid()const
{
return yourCurrentBid_;
}
float QueryAuctionDetailResult::getPayPrice()const
{
return payPrice_;
}
long QueryAuctionDetailResult::getDeliveryTime()const
{
return deliveryTime_;
}
float QueryAuctionDetailResult::getHighBid()const
{
return highBid_;
}
std::string QueryAuctionDetailResult::getDomainType()const
{
return domainType_;
}
std::string QueryAuctionDetailResult::getBookedPartner()const
{
return bookedPartner_;
}
std::string QueryAuctionDetailResult::getCurrency()const
{
return currency_;
}
bool QueryAuctionDetailResult::getReserveMet()const
{
return reserveMet_;
}
std::string QueryAuctionDetailResult::getProduceStatus()const
{
return produceStatus_;
}
float QueryAuctionDetailResult::getNextValidBid()const
{
return nextValidBid_;
}
float QueryAuctionDetailResult::getYourMaxBid()const
{
return yourMaxBid_;
}
long QueryAuctionDetailResult::getAuctionEndTime()const
{
return auctionEndTime_;
}
long QueryAuctionDetailResult::getBookEndTime()const
{
return bookEndTime_;
}
long QueryAuctionDetailResult::getPayEndTime()const
{
return payEndTime_;
}
std::string QueryAuctionDetailResult::getAuctionId()const
{
return auctionId_;
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
a27e98f5691a5e6a8cac1ad249fc8bf7e93fada2 | 265b98719aa85f5876d9acda4e278dd2b4318a82 | /src/test/sighash_tests.cpp | 36b89d041ef376efb7d09c4ea5ca8b18cdcbf145 | [
"MIT"
] | permissive | JcoEighty6/digifel-core | 6d51e8ba4044dfc1b6824daab8da487cf1f97a86 | 36aa85b2f7a50b0b11a7f6521e0a7f8a3fda033e | refs/heads/master | 2021-04-28T09:28:41.445229 | 2018-02-13T23:49:14 | 2018-02-13T23:49:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,139 | cpp | // Copyright (c) 2013-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "consensus/validation.h"
#include "data/sighash.json.h"
#include "hash.h"
#include "main.h" // For CheckTransaction
#include "random.h"
#include "script/interpreter.h"
#include "script/script.h"
#include "serialize.h"
#include "streams.h"
#include "test/test_digifel.h"
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
extern UniValue read_json(const std::string& jsondata);
// Old script.cpp SignatureHash function
uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn);
return one;
}
CMutableTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut);
return one;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript();
int ops = (insecure_rand() % 10);
for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))];
}
void static RandomTransaction(CMutableTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand();
tx.vin.clear();
tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;
int ins = (insecure_rand() % 4) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1;
for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash();
txin.prevout.n = insecure_rand() % 4;
RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;
}
for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000;
RandomScript(txout.scriptPubKey);
}
}
BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(sighash_test)
{
seed_insecure_rand(false);
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
#endif
int nRandomTests = 50000;
#if defined(PRINT_SIGHASH_JSON)
nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand();
CMutableTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode;
RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size();
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
sh = SignatureHash(scriptCode, txTo, nIn, nHashType);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
std::cout << "\t[\"" ;
std::cout << HexStr(ss.begin(), ss.end()) << "\", \"";
std::cout << HexStr(scriptCode) << "\", ";
std::cout << nIn << ", ";
std::cout << nHashType << ", \"";
std::cout << sho.GetHex() << "\"]";
if (i+1 != nRandomTests) {
std::cout << ",";
}
std::cout << "\n";
#endif
BOOST_CHECK(sh == sho);
}
#if defined(PRINT_SIGHASH_JSON)
std::cout << "]\n";
#endif
}
// Goal: check that SignatureHash generates correct hash
BOOST_AUTO_TEST_CASE(sighash_from_data)
{
UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
if (test.size() == 1) continue; // comment
std::string raw_tx, raw_script, sigHashHex;
int nIn, nHashType;
uint256 sh;
CTransaction tx;
CScript scriptCode = CScript();
try {
// deserialize test data
raw_tx = test[0].get_str();
raw_script = test[1].get_str();
nIn = test[2].get_int();
nHashType = test[3].get_int();
sigHashHex = test[4].get_str();
uint256 sh;
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
stream >> tx;
CValidationState state;
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
BOOST_CHECK(state.IsValid());
std::vector<unsigned char> raw = ParseHex(raw_script);
scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
} catch (...) {
BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
continue;
}
sh = SignatureHash(scriptCode, tx, nIn, nHashType);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"35785858+digifel@users.noreply.github.com"
] | 35785858+digifel@users.noreply.github.com |
dbf117591202d55a5ce8bad88d78f83edcb7b925 | 85e7114ea63a080c1b9b0579e66c7a2d126cffec | /SDK/SoT_BP_TreasureChest_Proxy_PirateLegend_DVR_classes.hpp | 0b1d6112aefcf1b107e2677668e6c11b62113835 | [] | no_license | EO-Zanzo/SeaOfThieves-Hack | 97094307d943c2b8e2af071ba777a000cf1369c2 | d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51 | refs/heads/master | 2020-04-02T14:18:24.844616 | 2018-10-24T15:02:43 | 2018-10-24T15:02:43 | 154,519,316 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 835 | hpp | #pragma once
// Sea of Thieves (1.2.6) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_TreasureChest_Proxy_PirateLegend_DVR_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_TreasureChest_Proxy_PirateLegend_DVR.BP_TreasureChest_Proxy_PirateLegend_DVR_C
// 0x0000 (0x0A60 - 0x0A60)
class ABP_TreasureChest_Proxy_PirateLegend_DVR_C : public ABP_TreasureChestProxy_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass BP_TreasureChest_Proxy_PirateLegend_DVR.BP_TreasureChest_Proxy_PirateLegend_DVR_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
8f72d2fcd976f48810d2a256ced03ff5dfe52967 | e758fae7c14f09ba185b8aaa8f8306dad5cd4905 | /src/gpu/ops/GrTextureOp.cpp | 5b7a30dedfe41cf295e92d7f4dc9074786923c4b | [
"BSD-3-Clause"
] | permissive | dnfield/skia | 6ccd64425d7c5ef9a1df51caebe74ee588756c3c | 1e7c65806f3fbde13b5d8064dc5734d98c32a284 | refs/heads/master | 2021-07-05T06:41:09.489996 | 2018-05-21T20:10:17 | 2018-05-21T21:53:54 | 131,202,088 | 0 | 0 | null | 2018-04-26T19:35:41 | 2018-04-26T19:35:41 | null | UTF-8 | C++ | false | false | 44,484 | cpp | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureOp.h"
#include "GrAppliedClip.h"
#include "GrCaps.h"
#include "GrDrawOpTest.h"
#include "GrGeometryProcessor.h"
#include "GrMeshDrawOp.h"
#include "GrOpFlushState.h"
#include "GrQuad.h"
#include "GrResourceProvider.h"
#include "GrShaderCaps.h"
#include "GrTexture.h"
#include "GrTexturePriv.h"
#include "GrTextureProxy.h"
#include "SkGr.h"
#include "SkMathPriv.h"
#include "SkMatrixPriv.h"
#include "SkPoint.h"
#include "SkPoint3.h"
#include "glsl/GrGLSLColorSpaceXformHelper.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLGeometryProcessor.h"
#include "glsl/GrGLSLVarying.h"
#include "glsl/GrGLSLVertexGeoBuilder.h"
namespace {
/**
* Geometry Processor that draws a texture modulated by a vertex color (though, this is meant to be
* the same value across all vertices of a quad and uses flat interpolation when available). This is
* used by TextureOp below.
*/
class TextureGeometryProcessor : public GrGeometryProcessor {
public:
template <typename P> struct Vertex {
static constexpr GrAA kAA = GrAA::kNo;
static constexpr bool kIsMultiTexture = false;
using Position = P;
P fPosition;
SkPoint fTextureCoords;
GrColor fColor;
};
template <typename P> struct AAVertex : Vertex<P> {
static constexpr GrAA kAA = GrAA::kYes;
SkPoint3 fEdges[4];
};
template <typename P> struct MultiTextureVertex : Vertex<P> {
static constexpr bool kIsMultiTexture = true;
int fTextureIdx;
};
template <typename P> struct AAMultiTextureVertex : MultiTextureVertex<P> {
static constexpr GrAA kAA = GrAA::kYes;
SkPoint3 fEdges[4];
};
// Maximum number of textures supported by this op. Must also be checked against the caps
// limit. These numbers were based on some limited experiments on a HP Z840 and Pixel XL 2016
// and could probably use more tuning.
#ifdef SK_BUILD_FOR_ANDROID
static constexpr int kMaxTextures = 4;
#else
static constexpr int kMaxTextures = 8;
#endif
static int SupportsMultitexture(const GrShaderCaps& caps) {
return caps.integerSupport() && caps.maxFragmentSamplers() > 1;
}
static sk_sp<GrGeometryProcessor> Make(sk_sp<GrTextureProxy> proxies[], int proxyCnt,
sk_sp<GrColorSpaceXform> csxf, bool coverageAA,
bool perspective, const GrSamplerState::Filter filters[],
const GrShaderCaps& caps) {
// We use placement new to avoid always allocating space for kMaxTextures TextureSampler
// instances.
int samplerCnt = NumSamplersToUse(proxyCnt, caps);
size_t size = sizeof(TextureGeometryProcessor) + sizeof(TextureSampler) * (samplerCnt - 1);
void* mem = GrGeometryProcessor::operator new(size);
return sk_sp<TextureGeometryProcessor>(
new (mem) TextureGeometryProcessor(proxies, proxyCnt, samplerCnt, std::move(csxf),
coverageAA, perspective, filters, caps));
}
~TextureGeometryProcessor() override {
int cnt = this->numTextureSamplers();
for (int i = 1; i < cnt; ++i) {
fSamplers[i].~TextureSampler();
}
}
const char* name() const override { return "TextureGeometryProcessor"; }
void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
b->add32(GrColorSpaceXform::XformKey(fColorSpaceXform.get()));
uint32_t x = this->usesCoverageEdgeAA() ? 0 : 1;
x |= kFloat3_GrVertexAttribType == fPositions.fType ? 0 : 2;
b->add32(x);
}
GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps& caps) const override {
class GLSLProcessor : public GrGLSLGeometryProcessor {
public:
void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& proc,
FPCoordTransformIter&& transformIter) override {
const auto& textureGP = proc.cast<TextureGeometryProcessor>();
this->setTransformDataHelper(SkMatrix::I(), pdman, &transformIter);
if (fColorSpaceXformHelper.isValid()) {
fColorSpaceXformHelper.setData(pdman, textureGP.fColorSpaceXform.get());
}
}
private:
void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
using Interpolation = GrGLSLVaryingHandler::Interpolation;
const auto& textureGP = args.fGP.cast<TextureGeometryProcessor>();
fColorSpaceXformHelper.emitCode(
args.fUniformHandler, textureGP.fColorSpaceXform.get());
if (kFloat2_GrVertexAttribType == textureGP.fPositions.fType) {
args.fVaryingHandler->setNoPerspective();
}
args.fVaryingHandler->emitAttributes(textureGP);
gpArgs->fPositionVar = textureGP.fPositions.asShaderVar();
this->emitTransforms(args.fVertBuilder,
args.fVaryingHandler,
args.fUniformHandler,
textureGP.fTextureCoords.asShaderVar(),
args.fFPCoordTransformHandler);
args.fVaryingHandler->addPassThroughAttribute(&textureGP.fColors,
args.fOutputColor,
Interpolation::kCanBeFlat);
args.fFragBuilder->codeAppend("float2 texCoord;");
args.fVaryingHandler->addPassThroughAttribute(&textureGP.fTextureCoords,
"texCoord");
if (textureGP.numTextureSamplers() > 1) {
// If this changes to float, reconsider Interpolation::kMustBeFlat.
SkASSERT(kInt_GrVertexAttribType == textureGP.fTextureIdx.fType);
SkASSERT(args.fShaderCaps->integerSupport());
args.fFragBuilder->codeAppend("int texIdx;");
args.fVaryingHandler->addPassThroughAttribute(&textureGP.fTextureIdx, "texIdx",
Interpolation::kMustBeFlat);
args.fFragBuilder->codeAppend("switch (texIdx) {");
for (int i = 0; i < textureGP.numTextureSamplers(); ++i) {
args.fFragBuilder->codeAppendf("case %d: %s = ", i, args.fOutputColor);
args.fFragBuilder->appendTextureLookupAndModulate(args.fOutputColor,
args.fTexSamplers[i],
"texCoord",
kFloat2_GrSLType,
&fColorSpaceXformHelper);
args.fFragBuilder->codeAppend("; break;");
}
args.fFragBuilder->codeAppend("}");
} else {
args.fFragBuilder->codeAppendf("%s = ", args.fOutputColor);
args.fFragBuilder->appendTextureLookupAndModulate(args.fOutputColor,
args.fTexSamplers[0],
"texCoord",
kFloat2_GrSLType,
&fColorSpaceXformHelper);
}
args.fFragBuilder->codeAppend(";");
if (textureGP.usesCoverageEdgeAA()) {
const char* aaDistName = nullptr;
bool mulByFragCoordW = false;
// When interpolation is inaccurate we perform the evaluation of the edge
// equations in the fragment shader rather than interpolating values computed
// in the vertex shader.
if (!args.fShaderCaps->interpolantsAreInaccurate()) {
GrGLSLVarying aaDistVarying(kFloat4_GrSLType,
GrGLSLVarying::Scope::kVertToFrag);
if (kFloat3_GrVertexAttribType == textureGP.fPositions.fType) {
args.fVaryingHandler->addVarying("aaDists", &aaDistVarying);
// The distance from edge equation e to homogenous point p=sk_Position
// is e.x*p.x/p.wx + e.y*p.y/p.w + e.z. However, we want screen space
// interpolation of this distance. We can do this by multiplying the
// varying in the VS by p.w and then multiplying by sk_FragCoord.w in
// the FS. So we output e.x*p.x + e.y*p.y + e.z * p.w
args.fVertBuilder->codeAppendf(
R"(%s = float4(dot(aaEdge0, %s), dot(aaEdge1, %s),
dot(aaEdge2, %s), dot(aaEdge3, %s));)",
aaDistVarying.vsOut(), textureGP.fPositions.fName,
textureGP.fPositions.fName, textureGP.fPositions.fName,
textureGP.fPositions.fName);
mulByFragCoordW = true;
} else {
args.fVaryingHandler->addVarying("aaDists", &aaDistVarying);
args.fVertBuilder->codeAppendf(
R"(%s = float4(dot(aaEdge0.xy, %s.xy) + aaEdge0.z,
dot(aaEdge1.xy, %s.xy) + aaEdge1.z,
dot(aaEdge2.xy, %s.xy) + aaEdge2.z,
dot(aaEdge3.xy, %s.xy) + aaEdge3.z);)",
aaDistVarying.vsOut(), textureGP.fPositions.fName,
textureGP.fPositions.fName, textureGP.fPositions.fName,
textureGP.fPositions.fName);
}
aaDistName = aaDistVarying.fsIn();
} else {
GrGLSLVarying aaEdgeVarying[4]{
{kFloat3_GrSLType, GrGLSLVarying::Scope::kVertToFrag},
{kFloat3_GrSLType, GrGLSLVarying::Scope::kVertToFrag},
{kFloat3_GrSLType, GrGLSLVarying::Scope::kVertToFrag},
{kFloat3_GrSLType, GrGLSLVarying::Scope::kVertToFrag}
};
for (int i = 0; i < 4; ++i) {
SkString name;
name.printf("aaEdge%d", i);
args.fVaryingHandler->addVarying(name.c_str(), &aaEdgeVarying[i],
Interpolation::kCanBeFlat);
args.fVertBuilder->codeAppendf(
"%s = aaEdge%d;", aaEdgeVarying[i].vsOut(), i);
}
args.fFragBuilder->codeAppendf(
R"(float4 aaDists = float4(dot(%s.xy, sk_FragCoord.xy) + %s.z,
dot(%s.xy, sk_FragCoord.xy) + %s.z,
dot(%s.xy, sk_FragCoord.xy) + %s.z,
dot(%s.xy, sk_FragCoord.xy) + %s.z);)",
aaEdgeVarying[0].fsIn(), aaEdgeVarying[0].fsIn(),
aaEdgeVarying[1].fsIn(), aaEdgeVarying[1].fsIn(),
aaEdgeVarying[2].fsIn(), aaEdgeVarying[2].fsIn(),
aaEdgeVarying[3].fsIn(), aaEdgeVarying[3].fsIn());
aaDistName = "aaDists";
}
args.fFragBuilder->codeAppendf(
"float mindist = min(min(%s.x, %s.y), min(%s.z, %s.w));",
aaDistName, aaDistName, aaDistName, aaDistName);
if (mulByFragCoordW) {
args.fFragBuilder->codeAppend("mindist *= sk_FragCoord.w;");
}
args.fFragBuilder->codeAppendf("%s = float4(clamp(mindist, 0, 1));",
args.fOutputCoverage);
} else {
args.fFragBuilder->codeAppendf("%s = float4(1);", args.fOutputCoverage);
}
}
GrGLSLColorSpaceXformHelper fColorSpaceXformHelper;
};
return new GLSLProcessor;
}
bool usesCoverageEdgeAA() const { return SkToBool(fAAEdges[0].isInitialized()); }
private:
// This exists to reduce the number of shaders generated. It does some rounding of sampler
// counts.
static int NumSamplersToUse(int numRealProxies, const GrShaderCaps& caps) {
SkASSERT(numRealProxies > 0 && numRealProxies <= kMaxTextures &&
numRealProxies <= caps.maxFragmentSamplers());
if (1 == numRealProxies) {
return 1;
}
if (numRealProxies <= 4) {
return 4;
}
// Round to the next power of 2 and then clamp to kMaxTextures and the max allowed by caps.
return SkTMin(SkNextPow2(numRealProxies), SkTMin(kMaxTextures, caps.maxFragmentSamplers()));
}
TextureGeometryProcessor(sk_sp<GrTextureProxy> proxies[], int proxyCnt, int samplerCnt,
sk_sp<GrColorSpaceXform> csxf, bool coverageAA, bool perspective,
const GrSamplerState::Filter filters[], const GrShaderCaps& caps)
: INHERITED(kTextureGeometryProcessor_ClassID), fColorSpaceXform(std::move(csxf)) {
SkASSERT(proxyCnt > 0 && samplerCnt >= proxyCnt);
fSamplers[0].reset(std::move(proxies[0]), filters[0]);
this->addTextureSampler(&fSamplers[0]);
for (int i = 1; i < proxyCnt; ++i) {
// This class has one sampler built in, the rest come from memory this processor was
// placement-newed into and so haven't been constructed.
new (&fSamplers[i]) TextureSampler(std::move(proxies[i]), filters[i]);
this->addTextureSampler(&fSamplers[i]);
}
if (perspective) {
fPositions = this->addVertexAttrib("position", kFloat3_GrVertexAttribType);
} else {
fPositions = this->addVertexAttrib("position", kFloat2_GrVertexAttribType);
}
fTextureCoords = this->addVertexAttrib("textureCoords", kFloat2_GrVertexAttribType);
fColors = this->addVertexAttrib("color", kUByte4_norm_GrVertexAttribType);
if (samplerCnt > 1) {
// Here we initialize any extra samplers by repeating the last one samplerCnt - proxyCnt
// times.
GrTextureProxy* dupeProxy = fSamplers[proxyCnt - 1].proxy();
for (int i = proxyCnt; i < samplerCnt; ++i) {
new (&fSamplers[i]) TextureSampler(sk_ref_sp(dupeProxy), filters[proxyCnt - 1]);
this->addTextureSampler(&fSamplers[i]);
}
SkASSERT(caps.integerSupport());
fTextureIdx = this->addVertexAttrib("textureIdx", kInt_GrVertexAttribType);
}
if (coverageAA) {
fAAEdges[0] = this->addVertexAttrib("aaEdge0", kFloat3_GrVertexAttribType);
fAAEdges[1] = this->addVertexAttrib("aaEdge1", kFloat3_GrVertexAttribType);
fAAEdges[2] = this->addVertexAttrib("aaEdge2", kFloat3_GrVertexAttribType);
fAAEdges[3] = this->addVertexAttrib("aaEdge3", kFloat3_GrVertexAttribType);
}
}
Attribute fPositions;
Attribute fColors;
Attribute fTextureCoords;
Attribute fTextureIdx;
Attribute fAAEdges[4];
sk_sp<GrColorSpaceXform> fColorSpaceXform;
TextureSampler fSamplers[1];
typedef GrGeometryProcessor INHERITED;
};
// This computes the four edge equations for a quad, then outsets them and computes a new quad
// as the intersection points of the outset edges. 'x' and 'y' contain the original points as input
// and the outset points as output. 'a', 'b', and 'c' are the edge equation coefficients on output.
static void compute_quad_edges_and_outset_vertices(Sk4f* x, Sk4f* y, Sk4f* a, Sk4f* b, Sk4f* c) {
static constexpr auto fma = SkNx_fma<4, float>;
// These rotate the points/edge values either clockwise or counterclockwise assuming tri strip
// order.
auto nextCW = [](const Sk4f& v) { return SkNx_shuffle<2, 0, 3, 1>(v); };
auto nextCCW = [](const Sk4f& v) { return SkNx_shuffle<1, 3, 0, 2>(v); };
auto xnext = nextCCW(*x);
auto ynext = nextCCW(*y);
*a = ynext - *y;
*b = *x - xnext;
*c = fma(xnext, *y, -ynext * *x);
Sk4f invNormLengths = (*a * *a + *b * *b).rsqrt();
// Make sure the edge equations have their normals facing into the quad in device space.
auto test = fma(*a, nextCW(*x), fma(*b, nextCW(*y), *c));
if ((test < Sk4f(0)).anyTrue()) {
invNormLengths = -invNormLengths;
}
*a *= invNormLengths;
*b *= invNormLengths;
*c *= invNormLengths;
// Here is the outset. This makes our edge equations compute coverage without requiring a
// half pixel offset and is also used to compute the bloated quad that will cover all
// pixels.
*c += Sk4f(0.5f);
// Reverse the process to compute the points of the bloated quad from the edge equations.
// This time the inputs don't have 1s as their third coord and we want to homogenize rather
// than normalize.
auto anext = nextCW(*a);
auto bnext = nextCW(*b);
auto cnext = nextCW(*c);
*x = fma(bnext, *c, -*b * cnext);
*y = fma(*a, cnext, -anext * *c);
auto ic = (fma(anext, *b, -bnext * *a)).invert();
*x *= ic;
*y *= ic;
}
namespace {
// This is a class soley so it can be partially specialized (functions cannot be).
template <typename Vertex, GrAA AA = Vertex::kAA, typename Position = typename Vertex::Position>
class VertexAAHandler;
template<typename Vertex> class VertexAAHandler<Vertex, GrAA::kNo, SkPoint> {
public:
static void AssignPositionsAndTexCoords(Vertex* vertices, const GrPerspQuad& quad,
const SkRect& texRect) {
SkASSERT((quad.w4f() == Sk4f(1.f)).allTrue());
SkPointPriv::SetRectTriStrip(&vertices[0].fTextureCoords, texRect, sizeof(Vertex));
for (int i = 0; i < 4; ++i) {
vertices[i].fPosition = {quad.x(i), quad.y(i)};
}
}
};
template<typename Vertex> class VertexAAHandler<Vertex, GrAA::kNo, SkPoint3> {
public:
static void AssignPositionsAndTexCoords(Vertex* vertices, const GrPerspQuad& quad,
const SkRect& texRect) {
SkPointPriv::SetRectTriStrip(&vertices[0].fTextureCoords, texRect, sizeof(Vertex));
for (int i = 0; i < 4; ++i) {
vertices[i].fPosition = quad.point(i);
}
}
};
template<typename Vertex> class VertexAAHandler<Vertex, GrAA::kYes, SkPoint> {
public:
static void AssignPositionsAndTexCoords(Vertex* vertices, const GrPerspQuad& quad,
const SkRect& texRect) {
SkASSERT((quad.w4f() == Sk4f(1.f)).allTrue());
auto x = quad.x4f();
auto y = quad.y4f();
Sk4f a, b, c;
compute_quad_edges_and_outset_vertices(&x, &y, &a, &b, &c);
for (int i = 0; i < 4; ++i) {
vertices[i].fPosition = {x[i], y[i]};
for (int j = 0; j < 4; ++j) {
vertices[i].fEdges[j] = {a[j], b[j], c[j]};
}
}
AssignTexCoords(vertices, quad, texRect);
}
private:
static void AssignTexCoords(Vertex* vertices, const GrPerspQuad& quad, const SkRect& tex) {
SkMatrix q = SkMatrix::MakeAll(quad.x(0), quad.x(1), quad.x(2),
quad.y(0), quad.y(1), quad.y(2),
1.f, 1.f, 1.f);
SkMatrix qinv;
if (!q.invert(&qinv)) {
return;
}
SkMatrix t = SkMatrix::MakeAll(tex.fLeft, tex.fLeft, tex.fRight,
tex.fTop, tex.fBottom, tex.fTop,
1.f, 1.f, 1.f);
SkMatrix map;
map.setConcat(t, qinv);
SkMatrixPriv::MapPointsWithStride(map, &vertices[0].fTextureCoords, sizeof(Vertex),
&vertices[0].fPosition, sizeof(Vertex), 4);
}
};
template<typename Vertex> class VertexAAHandler<Vertex, GrAA::kYes, SkPoint3> {
public:
static void AssignPositionsAndTexCoords(Vertex* vertices, const GrPerspQuad& quad,
const SkRect& texRect) {
auto x = quad.x4f();
auto y = quad.y4f();
auto iw = quad.iw4f();
x *= iw;
y *= iw;
// Get an equation for w from device space coords.
SkMatrix P;
P.setAll(x[0], y[0], 1, x[1], y[1], 1, x[2], y[2], 1);
SkAssertResult(P.invert(&P));
SkPoint3 weq{quad.w(0), quad.w(1), quad.w(2)};
P.mapHomogeneousPoints(&weq, &weq, 1);
Sk4f a, b, c;
compute_quad_edges_and_outset_vertices(&x, &y, &a, &b, &c);
// Compute new w values for the output vertices;
auto w = Sk4f(weq.fX) * x + Sk4f(weq.fY) * y + Sk4f(weq.fZ);
x *= w;
y *= w;
for (int i = 0; i < 4; ++i) {
vertices[i].fPosition = {x[i], y[i], w[i]};
for (int j = 0; j < 4; ++j) {
vertices[i].fEdges[j] = {a[j], b[j], c[j]};
}
}
AssignTexCoords(vertices, quad, texRect);
}
private:
static void AssignTexCoords(Vertex* vertices, const GrPerspQuad& quad, const SkRect& tex) {
SkMatrix q = SkMatrix::MakeAll(quad.x(0), quad.x(1), quad.x(2),
quad.y(0), quad.y(1), quad.y(2),
quad.w(0), quad.w(1), quad.w(2));
SkMatrix qinv;
if (!q.invert(&qinv)) {
return;
}
SkMatrix t = SkMatrix::MakeAll(tex.fLeft, tex.fLeft, tex.fRight,
tex.fTop, tex.fBottom, tex.fTop,
1.f, 1.f, 1.f);
SkMatrix map;
map.setConcat(t, qinv);
SkPoint3 tempTexCoords[4];
SkMatrixPriv::MapHomogeneousPointsWithStride(map, tempTexCoords, sizeof(SkPoint3),
&vertices[0].fPosition, sizeof(Vertex), 4);
for (int i = 0; i < 4; ++i) {
auto invW = 1.f / tempTexCoords[i].fZ;
vertices[i].fTextureCoords.fX = tempTexCoords[i].fX * invW;
vertices[i].fTextureCoords.fY = tempTexCoords[i].fY * invW;
}
}
};
template <typename Vertex, bool MT = Vertex::kIsMultiTexture> struct TexIdAssigner;
template <typename Vertex> struct TexIdAssigner<Vertex, true> {
static void Assign(Vertex* vertices, int textureIdx) {
for (int i = 0; i < 4; ++i) {
vertices[i].fTextureIdx = textureIdx;
}
}
};
template <typename Vertex> struct TexIdAssigner<Vertex, false> {
static void Assign(Vertex* vertices, int textureIdx) {}
};
} // anonymous namespace
template <typename Vertex>
static void tessellate_quad(const GrPerspQuad& devQuad, const SkRect& srcRect, GrColor color,
GrSurfaceOrigin origin, Vertex* vertices, SkScalar iw, SkScalar ih,
int textureIdx) {
SkRect texRect = {
iw * srcRect.fLeft,
ih * srcRect.fTop,
iw * srcRect.fRight,
ih * srcRect.fBottom
};
if (origin == kBottomLeft_GrSurfaceOrigin) {
texRect.fTop = 1.f - texRect.fTop;
texRect.fBottom = 1.f - texRect.fBottom;
}
VertexAAHandler<Vertex>::AssignPositionsAndTexCoords(vertices, devQuad, texRect);
vertices[0].fColor = color;
vertices[1].fColor = color;
vertices[2].fColor = color;
vertices[3].fColor = color;
TexIdAssigner<Vertex>::Assign(vertices, textureIdx);
}
/**
* Op that implements GrTextureOp::Make. It draws textured quads. Each quad can modulate against a
* the texture by color. The blend with the destination is always src-over. The edges are non-AA.
*/
class TextureOp final : public GrMeshDrawOp {
public:
static std::unique_ptr<GrDrawOp> Make(sk_sp<GrTextureProxy> proxy,
GrSamplerState::Filter filter, GrColor color,
const SkRect& srcRect, const SkRect& dstRect,
GrAAType aaType, const SkMatrix& viewMatrix,
sk_sp<GrColorSpaceXform> csxf, bool allowSRBInputs) {
return std::unique_ptr<GrDrawOp>(new TextureOp(std::move(proxy), filter, color, srcRect,
dstRect, aaType, viewMatrix, std::move(csxf),
allowSRBInputs));
}
~TextureOp() override {
if (fFinalized) {
auto proxies = this->proxies();
for (int i = 0; i < fProxyCnt; ++i) {
proxies[i]->completedRead();
}
if (fProxyCnt > 1) {
delete[] reinterpret_cast<const char*>(proxies);
}
} else {
SkASSERT(1 == fProxyCnt);
fProxy0->unref();
}
}
const char* name() const override { return "TextureOp"; }
void visitProxies(const VisitProxyFunc& func) const override {
auto proxies = this->proxies();
for (int i = 0; i < fProxyCnt; ++i) {
func(proxies[i]);
}
}
SkString dumpInfo() const override {
SkString str;
str.appendf("AllowSRGBInputs: %d\n", fAllowSRGBInputs);
str.appendf("# draws: %d\n", fDraws.count());
auto proxies = this->proxies();
for (int i = 0; i < fProxyCnt; ++i) {
str.appendf("Proxy ID %d: %d, Filter: %d\n", i, proxies[i]->uniqueID().asUInt(),
static_cast<int>(this->filters()[i]));
}
for (int i = 0; i < fDraws.count(); ++i) {
const Draw& draw = fDraws[i];
str.appendf(
"%d: Color: 0x%08x, ProxyIdx: %d, TexRect [L: %.2f, T: %.2f, R: %.2f, B: %.2f] "
"Quad [(%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f), (%.2f, %.2f)]\n",
i, draw.fColor, draw.fTextureIdx, draw.fSrcRect.fLeft, draw.fSrcRect.fTop,
draw.fSrcRect.fRight, draw.fSrcRect.fBottom, draw.fQuad.point(0).fX,
draw.fQuad.point(0).fY, draw.fQuad.point(1).fX, draw.fQuad.point(1).fY,
draw.fQuad.point(2).fX, draw.fQuad.point(2).fY, draw.fQuad.point(3).fX,
draw.fQuad.point(3).fY);
}
str += INHERITED::dumpInfo();
return str;
}
RequiresDstTexture finalize(const GrCaps& caps, const GrAppliedClip* clip,
GrPixelConfigIsClamped dstIsClamped) override {
SkASSERT(!fFinalized);
SkASSERT(1 == fProxyCnt);
fFinalized = true;
fProxy0->addPendingRead();
fProxy0->unref();
return RequiresDstTexture::kNo;
}
FixedFunctionFlags fixedFunctionFlags() const override {
return this->aaType() == GrAAType::kMSAA ? FixedFunctionFlags::kUsesHWAA
: FixedFunctionFlags::kNone;
}
DEFINE_OP_CLASS_ID
private:
// This is used in a heursitic for choosing a code path. We don't care what happens with
// really large rects, infs, nans, etc.
#if defined(__clang__) && (__clang_major__ * 1000 + __clang_minor__) >= 3007
__attribute__((no_sanitize("float-cast-overflow")))
#endif
size_t RectSizeAsSizeT(const SkRect& rect) {;
return static_cast<size_t>(SkTMax(rect.width(), 1.f) * SkTMax(rect.height(), 1.f));
}
static constexpr int kMaxTextures = TextureGeometryProcessor::kMaxTextures;
TextureOp(sk_sp<GrTextureProxy> proxy, GrSamplerState::Filter filter, GrColor color,
const SkRect& srcRect, const SkRect& dstRect, GrAAType aaType,
const SkMatrix& viewMatrix, sk_sp<GrColorSpaceXform> csxf, bool allowSRGBInputs)
: INHERITED(ClassID())
, fColorSpaceXform(std::move(csxf))
, fProxy0(proxy.release())
, fFilter0(filter)
, fProxyCnt(1)
, fAAType(static_cast<unsigned>(aaType))
, fFinalized(0)
, fAllowSRGBInputs(allowSRGBInputs ? 1 : 0) {
SkASSERT(aaType != GrAAType::kMixedSamples);
Draw& draw = fDraws.push_back();
draw.fSrcRect = srcRect;
draw.fTextureIdx = 0;
draw.fColor = color;
fPerspective = viewMatrix.hasPerspective();
SkRect bounds;
draw.fQuad = GrPerspQuad(dstRect, viewMatrix);
bounds = draw.fQuad.bounds();
this->setBounds(bounds, HasAABloat::kNo, IsZeroArea::kNo);
fMaxApproxDstPixelArea = RectSizeAsSizeT(bounds);
}
void onPrepareDraws(Target* target) override {
sk_sp<GrTextureProxy> proxiesSPs[kMaxTextures];
auto proxies = this->proxies();
auto filters = this->filters();
for (int i = 0; i < fProxyCnt; ++i) {
if (!proxies[i]->instantiate(target->resourceProvider())) {
return;
}
proxiesSPs[i] = sk_ref_sp(proxies[i]);
}
bool coverageAA = GrAAType::kCoverage == this->aaType();
sk_sp<GrGeometryProcessor> gp = TextureGeometryProcessor::Make(
proxiesSPs, fProxyCnt, std::move(fColorSpaceXform), coverageAA, fPerspective,
filters, *target->caps().shaderCaps());
GrPipeline::InitArgs args;
args.fProxy = target->proxy();
args.fCaps = &target->caps();
args.fResourceProvider = target->resourceProvider();
args.fFlags = 0;
if (fAllowSRGBInputs) {
args.fFlags |= GrPipeline::kAllowSRGBInputs_Flag;
}
if (GrAAType::kMSAA == this->aaType()) {
args.fFlags |= GrPipeline::kHWAntialias_Flag;
}
const GrPipeline* pipeline = target->allocPipeline(args, GrProcessorSet::MakeEmptySet(),
target->detachAppliedClip());
int vstart;
const GrBuffer* vbuffer;
void* vdata = target->makeVertexSpace(gp->getVertexStride(), 4 * fDraws.count(), &vbuffer,
&vstart);
if (!vdata) {
SkDebugf("Could not allocate vertices\n");
return;
}
// Generic lambda in C++14?
#define TESS_VERTS(Vertex) \
SkASSERT(gp->getVertexStride() == sizeof(Vertex)); \
auto vertices = static_cast<Vertex*>(vdata); \
for (const auto& draw : fDraws) { \
auto origin = proxies[draw.fTextureIdx]->origin(); \
tessellate_quad<Vertex>(draw.fQuad, draw.fSrcRect, draw.fColor, origin, vertices, \
iw[draw.fTextureIdx], ih[draw.fTextureIdx], draw.fTextureIdx); \
vertices += 4; \
}
float iw[kMaxTextures];
float ih[kMaxTextures];
for (int t = 0; t < fProxyCnt; ++t) {
const auto* texture = proxies[t]->priv().peekTexture();
iw[t] = 1.f / texture->width();
ih[t] = 1.f / texture->height();
}
if (1 == fProxyCnt) {
if (coverageAA) {
if (fPerspective) {
TESS_VERTS(TextureGeometryProcessor::AAVertex<SkPoint3>)
} else {
TESS_VERTS(TextureGeometryProcessor::AAVertex<SkPoint>)
}
} else {
if (fPerspective) {
TESS_VERTS(TextureGeometryProcessor::Vertex<SkPoint3>)
} else {
TESS_VERTS(TextureGeometryProcessor::Vertex<SkPoint>)
}
}
} else {
if (coverageAA) {
if (fPerspective) {
TESS_VERTS(TextureGeometryProcessor::AAMultiTextureVertex<SkPoint3>)
} else {
TESS_VERTS(TextureGeometryProcessor::AAMultiTextureVertex<SkPoint>)
}
} else {
if (fPerspective) {
TESS_VERTS(TextureGeometryProcessor::MultiTextureVertex<SkPoint3>)
} else {
TESS_VERTS(TextureGeometryProcessor::MultiTextureVertex<SkPoint>)
}
}
}
GrPrimitiveType primitiveType =
fDraws.count() > 1 ? GrPrimitiveType::kTriangles : GrPrimitiveType::kTriangleStrip;
GrMesh mesh(primitiveType);
if (fDraws.count() > 1) {
sk_sp<const GrBuffer> ibuffer = target->resourceProvider()->refQuadIndexBuffer();
if (!ibuffer) {
SkDebugf("Could not allocate quad indices\n");
return;
}
mesh.setIndexedPatterned(ibuffer.get(), 6, 4, fDraws.count(),
GrResourceProvider::QuadCountOfQuadBuffer());
} else {
mesh.setNonIndexedNonInstanced(4);
}
mesh.setVertexData(vbuffer, vstart);
target->draw(gp.get(), pipeline, mesh);
}
bool onCombineIfPossible(GrOp* t, const GrCaps& caps) override {
const auto* that = t->cast<TextureOp>();
const auto& shaderCaps = *caps.shaderCaps();
if (!GrColorSpaceXform::Equals(fColorSpaceXform.get(), that->fColorSpaceXform.get())) {
return false;
}
if (this->aaType() != that->aaType()) {
return false;
}
// Because of an issue where GrColorSpaceXform adds the same function every time it is used
// in a texture lookup, we only allow multiple textures when there is no transform.
if (TextureGeometryProcessor::SupportsMultitexture(shaderCaps) && !fColorSpaceXform &&
fMaxApproxDstPixelArea <= shaderCaps.disableImageMultitexturingDstRectAreaThreshold() &&
that->fMaxApproxDstPixelArea <=
shaderCaps.disableImageMultitexturingDstRectAreaThreshold()) {
int map[kMaxTextures];
int numNewProxies = this->mergeProxies(that, map, shaderCaps);
if (numNewProxies < 0) {
return false;
}
if (1 == fProxyCnt && numNewProxies) {
void* mem = new char[(sizeof(GrSamplerState::Filter) + sizeof(GrTextureProxy*)) *
kMaxTextures];
auto proxies = reinterpret_cast<GrTextureProxy**>(mem);
auto filters = reinterpret_cast<GrSamplerState::Filter*>(proxies + kMaxTextures);
proxies[0] = fProxy0;
filters[0] = fFilter0;
fProxyArray = proxies;
}
fProxyCnt += numNewProxies;
auto thisProxies = fProxyArray;
auto thatProxies = that->proxies();
auto thatFilters = that->filters();
auto thisFilters = reinterpret_cast<GrSamplerState::Filter*>(thisProxies +
kMaxTextures);
for (int i = 0; i < that->fProxyCnt; ++i) {
if (map[i] < 0) {
thatProxies[i]->addPendingRead();
thisProxies[-map[i]] = thatProxies[i];
thisFilters[-map[i]] = thatFilters[i];
map[i] = -map[i];
}
}
int firstNewDraw = fDraws.count();
fDraws.push_back_n(that->fDraws.count(), that->fDraws.begin());
for (int i = firstNewDraw; i < fDraws.count(); ++i) {
fDraws[i].fTextureIdx = map[fDraws[i].fTextureIdx];
}
} else {
// We can get here when one of the ops is already multitextured but the other cannot
// be because of the dst rect size.
if (fProxyCnt > 1 || that->fProxyCnt > 1) {
return false;
}
if (fProxy0->uniqueID() != that->fProxy0->uniqueID() || fFilter0 != that->fFilter0) {
return false;
}
fDraws.push_back_n(that->fDraws.count(), that->fDraws.begin());
}
this->joinBounds(*that);
fMaxApproxDstPixelArea = SkTMax(that->fMaxApproxDstPixelArea, fMaxApproxDstPixelArea);
fPerspective |= that->fPerspective;
return true;
}
/**
* Determines a mapping of indices from that's proxy array to this's proxy array. A negative map
* value means that's proxy should be added to this's proxy array at the absolute value of
* the map entry. If it is determined that the ops shouldn't combine their proxies then a
* negative value is returned. Otherwise, return value indicates the number of proxies that have
* to be added to this op or, equivalently, the number of negative entries in map.
*/
int mergeProxies(const TextureOp* that, int map[kMaxTextures], const GrShaderCaps& caps) const {
std::fill_n(map, kMaxTextures, -kMaxTextures);
int sharedProxyCnt = 0;
auto thisProxies = this->proxies();
auto thisFilters = this->filters();
auto thatProxies = that->proxies();
auto thatFilters = that->filters();
for (int i = 0; i < fProxyCnt; ++i) {
for (int j = 0; j < that->fProxyCnt; ++j) {
if (thisProxies[i]->uniqueID() == thatProxies[j]->uniqueID()) {
if (thisFilters[i] != thatFilters[j]) {
// In GL we don't currently support using the same texture with different
// samplers. If we added support for sampler objects and a cap bit to know
// it's ok to use different filter modes then we could support this.
// Otherwise, we could also only allow a single filter mode for each op
// instance.
return -1;
}
map[j] = i;
++sharedProxyCnt;
break;
}
}
}
int actualMaxTextures = SkTMin(caps.maxFragmentSamplers(), kMaxTextures);
int newProxyCnt = that->fProxyCnt - sharedProxyCnt;
if (newProxyCnt + fProxyCnt > actualMaxTextures) {
return -1;
}
GrPixelConfig config = thisProxies[0]->config();
int nextSlot = fProxyCnt;
for (int j = 0; j < that->fProxyCnt; ++j) {
// We want to avoid making many shaders because of different permutations of shader
// based swizzle and sampler types. The approach taken here is to require the configs to
// be the same and to only allow already instantiated proxies that have the most
// common sampler type. Otherwise we don't merge.
if (thatProxies[j]->config() != config) {
return -1;
}
if (GrTexture* tex = thatProxies[j]->priv().peekTexture()) {
if (tex->texturePriv().samplerType() != kTexture2DSampler_GrSLType) {
return -1;
}
}
if (map[j] < 0) {
map[j] = -(nextSlot++);
}
}
return newProxyCnt;
}
GrAAType aaType() const { return static_cast<GrAAType>(fAAType); }
GrTextureProxy* const* proxies() const { return fProxyCnt > 1 ? fProxyArray : &fProxy0; }
const GrSamplerState::Filter* filters() const {
if (fProxyCnt > 1) {
return reinterpret_cast<const GrSamplerState::Filter*>(fProxyArray + kMaxTextures);
}
return &fFilter0;
}
struct Draw {
SkRect fSrcRect;
int fTextureIdx;
GrPerspQuad fQuad;
GrColor fColor;
};
SkSTArray<1, Draw, true> fDraws;
sk_sp<GrColorSpaceXform> fColorSpaceXform;
// Initially we store a single proxy ptr and a single filter. If we grow to have more than
// one proxy we instead store pointers to dynamically allocated arrays of size kMaxTextures
// followed by kMaxTextures filters.
union {
GrTextureProxy* fProxy0;
GrTextureProxy** fProxyArray;
};
size_t fMaxApproxDstPixelArea;
GrSamplerState::Filter fFilter0;
uint8_t fProxyCnt;
unsigned fAAType : 2;
unsigned fPerspective : 1;
// Used to track whether fProxy is ref'ed or has a pending IO after finalize() is called.
unsigned fFinalized : 1;
unsigned fAllowSRGBInputs : 1;
typedef GrMeshDrawOp INHERITED;
};
constexpr int TextureGeometryProcessor::kMaxTextures;
constexpr int TextureOp::kMaxTextures;
} // anonymous namespace
namespace GrTextureOp {
std::unique_ptr<GrDrawOp> Make(sk_sp<GrTextureProxy> proxy, GrSamplerState::Filter filter,
GrColor color, const SkRect& srcRect, const SkRect& dstRect,
GrAAType aaType, const SkMatrix& viewMatrix,
sk_sp<GrColorSpaceXform> csxf, bool allowSRGBInputs) {
return TextureOp::Make(std::move(proxy), filter, color, srcRect, dstRect, aaType, viewMatrix,
std::move(csxf), allowSRGBInputs);
}
} // namespace GrTextureOp
#if GR_TEST_UTILS
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrProxyProvider.h"
GR_DRAW_OP_TEST_DEFINE(TextureOp) {
GrSurfaceDesc desc;
desc.fConfig = kRGBA_8888_GrPixelConfig;
desc.fHeight = random->nextULessThan(90) + 10;
desc.fWidth = random->nextULessThan(90) + 10;
auto origin = random->nextBool() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin;
SkBackingFit fit = random->nextBool() ? SkBackingFit::kApprox : SkBackingFit::kExact;
GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider();
sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(desc, origin, fit, SkBudgeted::kNo);
SkRect rect = GrTest::TestRect(random);
SkRect srcRect;
srcRect.fLeft = random->nextRangeScalar(0.f, proxy->width() / 2.f);
srcRect.fRight = random->nextRangeScalar(0.f, proxy->width()) + proxy->width() / 2.f;
srcRect.fTop = random->nextRangeScalar(0.f, proxy->height() / 2.f);
srcRect.fBottom = random->nextRangeScalar(0.f, proxy->height()) + proxy->height() / 2.f;
SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
GrColor color = SkColorToPremulGrColor(random->nextU());
GrSamplerState::Filter filter = (GrSamplerState::Filter)random->nextULessThan(
static_cast<uint32_t>(GrSamplerState::Filter::kMipMap) + 1);
auto csxf = GrTest::TestColorXform(random);
bool allowSRGBInputs = random->nextBool();
GrAAType aaType = GrAAType::kNone;
if (random->nextBool()) {
aaType = (fsaaType == GrFSAAType::kUnifiedMSAA) ? GrAAType::kMSAA : GrAAType::kCoverage;
}
return GrTextureOp::Make(std::move(proxy), filter, color, srcRect, rect, aaType, viewMatrix,
std::move(csxf), allowSRGBInputs);
}
#endif
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
3d540e292bc8fb6de65f349927e00ec9f7984a70 | 3eae9c14c119ee2d6a7d02ef1ba5d61420959e3c | /modules/core/util/yangtools/lib/rw_keyspec.cpp | e71d17fbccb4b937fd0f0921581eb3b685c14d8c | [
"Apache-2.0"
] | permissive | RIFTIO/RIFT.ware | 94d3a34836a04546ea02ec0576dae78d566dabb3 | 4ade66a5bccbeb4c5ed5b56fed8841e46e2639b0 | refs/heads/RIFT.ware-4.4.1 | 2020-05-21T14:07:31.092287 | 2017-06-05T16:02:48 | 2017-06-05T16:02:48 | 52,545,688 | 9 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 180,826 | cpp | /* STANDARD_RIFT_IO_COPYRIGHT */
/**
* @file rw_keyspec.cpp
* @author Tom Seidenberg
* @date 2014/08/29
* @brief RiftWare general schema utilities
*/
#include <rw_keyspec.h>
#include <rw_schema.pb-c.h>
#include <rw_namespace.h>
#include "rw_ks_util.hpp"
#include <protobuf-c/rift/rw_pb_delta.h>
#include <execinfo.h>
#include <algorithm>
#include <stack>
#include <sstream>
#include <boost/format.hpp>
using namespace rw_yang;
#define IS_PATH_ENTRY_GENERIC(entry_) (((const ProtobufCMessage *)entry_)->descriptor == &rw_schema_path_entry__descriptor)
#define IS_KEYSPEC_GENERIC(ks_) (((const ProtobufCMessage *)ks_)->descriptor == &rw_schema_path_spec__descriptor)
#define KEYSPEC_ERROR(instance_, ...) \
keyspec_error_message(instance_, __LINE__, ##__VA_ARGS__)
#define KEYSPEC_INC_ERROR_STATS(instance_, name_) \
instance_->stats.error.name_++; // Need atomic increment here? keyspec instance is inside dts api handle which is already thread safe??
#define KEYSPEC_INC_FCALL_STATS(instance_, type_, name_) \
instance_->stats.fcall.type_.name_++;
static inline bool is_good_ks(const rw_keyspec_path_t* ks) {
return ks
&& ks->base.descriptor
&& PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC == ks->base.descriptor->magic;
}
static inline bool is_good_pe(const rw_keyspec_entry_t* pe) {
return pe
&& pe->base.descriptor
&& PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC == pe->base.descriptor->magic;
}
static const char*
get_yang_name_from_pb_name(const ProtobufCMessageDescriptor *mdesc,
const char* pb_fname);
// Global default keyspec instance.
rw_keyspec_instance_t keyspec_default_instance =
{
.pbc_instance = NULL,
.ymodel = NULL,
.ylib_data = NULL,
.user_data = NULL,
.error = keyspec_default_error_cb,
};
typedef enum {
REROOT_ITER_INIT = 0,
REROOT_ITER_FIRST,
REROOT_ITER_NEXT,
REROOT_ITER_DONE
} iter_state_t;
typedef enum {
PE_CONTAINER,
PE_LISTY_WITH_ALL_KEYS,
PE_LISTY_WITH_ALL_WC,
PE_LISTY_WITH_WC_AND_KEYS
} listy_pe_type_t;
typedef struct {
iter_state_t next_state;
KeySpecHelper *ks_in;
KeySpecHelper *ks_out;
rw_keyspec_instance_t* instance;
const ProtobufCMessage *in_msg;
size_t depth_i;
size_t depth_o;
rw_keyspec_path_t *cur_ks;
const ProtobufCMessage *cur_msg;
uint32_t n_path_ens;
protobuf_c_boolean is_out_ks_wc;
protobuf_c_boolean ks_has_iter_pes;
struct {
uint32_t count;
uint32_t next_index;
protobuf_c_boolean is_listy;
protobuf_c_boolean is_iteratable;
listy_pe_type_t type;
protobuf_c_boolean is_last_iter_index;
protobuf_c_boolean is_first_iter_index;
} path_entries[RW_SCHEMA_PB_MAX_PATH_ENTRIES];
} keyspec_reroot_iter_state_t;
static_assert((sizeof(keyspec_reroot_iter_state_t) == RW_SCHEMA_REROOT_STATE_SIZE),
"keyspec_reroot_iter_state_t structure modified. Update RW_SCHEMA_REROOT_STATE_SIZE");
// keyspec instance related APIs.
rw_keyspec_instance_t* rw_keyspec_instance_default()
{
// Set to the default.
keyspec_default_instance.pbc_instance = NULL;
keyspec_default_instance.ymodel = NULL;
keyspec_default_instance.ylib_data = NULL;
keyspec_default_instance.user_data = NULL;
keyspec_default_instance.error = keyspec_default_error_cb;
return &keyspec_default_instance;
}
ProtobufCInstance* rw_keyspec_instance_set_pbc_instance(
rw_keyspec_instance_t* ks_inst,
ProtobufCInstance* pbc_inst)
{
ProtobufCInstance* old_inst = ks_inst->pbc_instance;
ks_inst->pbc_instance = pbc_inst;
return old_inst;
}
rw_yang_model_t* rw_keyspec_instance_set_yang_model(
rw_keyspec_instance_t* ks_inst,
rw_yang_model_t* ymodel)
{
rw_yang_model_t* old_ymodel = ks_inst->ymodel;
ks_inst->ymodel = ymodel;
return old_ymodel;
}
void* rw_keyspec_instance_set_user_data(
rw_keyspec_instance_t* ks_inst,
void* user_data)
{
void* old_ud = ks_inst->user_data;
ks_inst->user_data = user_data;
return old_ud;
}
void* rw_keyspec_instance_get_user_data(
rw_keyspec_instance_t* ks_inst)
{
return ks_inst->user_data;
}
static inline rw_keyspec_instance_t* ks_instance_get(
rw_keyspec_instance_t* ks_inst)
{
if (ks_inst) {
return ks_inst;
}
return &keyspec_default_instance;
}
static inline void extract_args(
std::ostringstream& oss,
boost::format& msg)
{
oss << msg;
}
template<typename TValue, typename... TArgs>
static inline void extract_args(
std::ostringstream& oss,
boost::format& msg,
TValue arg,
TArgs... args)
{
msg % arg;
extract_args(oss, msg, args...);
}
template<typename... TArgs>
static inline void extract_args(
std::ostringstream& oss,
const char* format,
TArgs... args)
{
boost::format fstr(format);
extract_args(oss, fstr, args...);
}
template<typename... TArgs>
static inline void extract_args(
std::ostringstream& oss,
const rw_keyspec_path_t* ks,
TArgs... args)
{
auto ypbc_mdesc = ks->base.descriptor->ypbc_mdesc;
if (ypbc_mdesc) {
oss << ypbc_mdesc->module->module_name
<< ',' << ypbc_mdesc->pbc_mdesc->short_name;
} else {
// Generic keyspec. Print the nsid and tag??
}
oss << "(" << ks->base.descriptor << ")";
extract_args(oss, args...);
}
#define KEYSPEC_ERROR_NUM_BT_ELEMENTS 5
template<typename... TArgs>
static inline void keyspec_error_message(
rw_keyspec_instance_t* instance,
int line_no,
TArgs... args)
{
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_ERROR_STATS(instance, total_errors);
if (!instance->error) {
return;
}
void *array[KEYSPEC_ERROR_NUM_BT_ELEMENTS];
size_t size;
char **strings;
size = backtrace (array, 5);
strings = backtrace_symbols (array, size);
std::ostringstream oss;
oss << "Line:" << line_no << ' ';
size_t i;
// Skip the first element as it will be this function
for (i = 1; i < size; i++) {
oss << i << ':' << strings[i] << ' ';
}
free (strings);
extract_args(oss, args...);
instance->error(instance, oss.str().c_str());
}
static ProtobufCMessage* dup_and_convert_to_type(
rw_keyspec_instance_t* instance,
const ProtobufCMessage* in_msg,
const ProtobufCMessageDescriptor* out_pbcmd)
{
RW_ASSERT(in_msg);
RW_ASSERT(out_pbcmd);
RW_ASSERT(PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC == out_pbcmd->magic);
RW_ASSERT(instance);
// Encode the old. Hope that it fits on the stack.
uint8_t stackbuf[4096];
uint8_t* buf = nullptr;
size_t size = protobuf_c_message_get_packed_size(instance->pbc_instance, in_msg);
if (size <= sizeof(stackbuf)) {
buf = stackbuf;
} else {
buf = (uint8_t*)malloc(size);
RW_ASSERT(buf);
}
size_t actual_size = protobuf_c_message_pack(instance->pbc_instance, in_msg, buf);
RW_ASSERT(actual_size == size);
// Allocate new and decode into it.
ProtobufCMessage* out_msg = protobuf_c_message_unpack(
instance->pbc_instance, out_pbcmd, size, buf);
// ATTN: Want this?: RW_ASSERT(out_msg);
if (buf != stackbuf) {
free(buf);
}
return out_msg;
}
static bool dup_and_convert_in_place(
rw_keyspec_instance_t* instance,
const ProtobufCMessage* in_msg,
ProtobufCMessage* out_msg)
{
RW_ASSERT(in_msg);
RW_ASSERT(out_msg);
RW_ASSERT(out_msg->descriptor);
RW_ASSERT(PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC == out_msg->descriptor->magic);
RW_ASSERT(instance);
// Encode the old. Hope that it fits on the stack.
uint8_t stackbuf[4096];
uint8_t* buf = nullptr;
size_t size = protobuf_c_message_get_packed_size(instance->pbc_instance, in_msg);
if (size <= sizeof(stackbuf)) {
buf = stackbuf;
} else {
buf = (uint8_t*)malloc(size);
RW_ASSERT(buf);
}
size_t actual_size = protobuf_c_message_pack(instance->pbc_instance, in_msg, buf);
RW_ASSERT(actual_size == size);
// Decode into the new.
ProtobufCMessage* dup_out = protobuf_c_message_unpack_usebody(
instance->pbc_instance, out_msg->descriptor, size, buf, out_msg);
if (buf != stackbuf) {
free(buf);
}
return (dup_out == out_msg);
}
rw_status_t rw_keyspec_path_create_dup(
const rw_keyspec_path_t* input,
rw_keyspec_instance_t* instance,
rw_keyspec_path_t** output)
{
RW_ASSERT(is_good_ks(input));
RW_ASSERT(output);
RW_ASSERT(!*output);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_dup);
// Dup to the same type
ProtobufCMessage* out_msg = dup_and_convert_to_type(
instance, &input->base, input->base.descriptor);
if (out_msg) {
*output = reinterpret_cast<rw_keyspec_path_t*>(out_msg);
return RW_STATUS_SUCCESS;
}
KEYSPEC_ERROR(instance, input, "Create dup failed(%p)", input->base.descriptor);
return RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_create_dup_category(
const rw_keyspec_path_t* input,
rw_keyspec_instance_t* instance,
rw_keyspec_path_t** output,
RwSchemaCategory category)
{
RW_ASSERT(is_good_ks(input));
RW_ASSERT(output);
RW_ASSERT(!*output);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
// Dup to the same type
ProtobufCMessage* out_msg = dup_and_convert_to_type(
instance, &input->base, input->base.descriptor);
if (out_msg) {
*output = reinterpret_cast<rw_keyspec_path_t*>(out_msg);
rw_keyspec_path_set_category(*output, instance, category);
return RW_STATUS_SUCCESS;
}
KEYSPEC_ERROR(instance, input, "Create dup failed(%p)", input->base.descriptor);
return RW_STATUS_FAILURE;
}
rw_keyspec_path_t* rw_keyspec_path_create_dup_of_type(
const rw_keyspec_path_t* input,
rw_keyspec_instance_t* instance,
const ProtobufCMessageDescriptor* out_pbcmd)
{
RW_ASSERT(is_good_ks(input));
RW_ASSERT(out_pbcmd);
RW_ASSERT(PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC == out_pbcmd->magic);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_dup_type);
// Dup to the other type
ProtobufCMessage* out_msg = dup_and_convert_to_type(
instance, &input->base, out_pbcmd);
if (out_msg) {
return reinterpret_cast<rw_keyspec_path_t*>(out_msg);
}
KEYSPEC_ERROR(instance, input, "Create dup failed(%p)", out_pbcmd);
return nullptr;
}
rw_keyspec_path_t* rw_keyspec_path_create_dup_of_type_trunc(
const rw_keyspec_path_t* input,
rw_keyspec_instance_t* instance,
const ProtobufCMessageDescriptor* out_pbcmd)
{
RW_ASSERT(is_good_ks(input));
RW_ASSERT(out_pbcmd);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_dup_type_trunc);
// Dup to the other type
rw_keyspec_path_t* out_ks = rw_keyspec_path_create_dup_of_type(
input, instance, out_pbcmd);
if (out_ks) {
rw_status_t status = rw_keyspec_path_trunc_concrete(out_ks, instance);
RW_ASSERT(RW_STATUS_SUCCESS == status);
return out_ks;
}
KEYSPEC_ERROR(instance, input, "Create dup&trunc failed(%p)", out_pbcmd);
return nullptr;
}
rw_status_t rw_keyspec_path_find_spec_ks(
const rw_keyspec_path_t* ks,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema,
rw_keyspec_path_t** spec_ks)
{
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, find_spec_ks);
const rw_yang_pb_msgdesc_t* curr_ypbc_msgdesc = nullptr;
rw_status_t rs = rw_keyspec_path_find_msg_desc_schema (
ks, instance, schema, &curr_ypbc_msgdesc, nullptr);
if (RW_STATUS_SUCCESS != rs) {
return rs;
}
RW_ASSERT(curr_ypbc_msgdesc);
RW_ASSERT(curr_ypbc_msgdesc->pbc_mdesc);
*spec_ks = rw_keyspec_path_create_dup_of_type(
ks, instance, curr_ypbc_msgdesc->pbc_mdesc);
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_copy(
const rw_keyspec_path_t* input,
rw_keyspec_instance_t* instance,
rw_keyspec_path_t* output)
{
RW_ASSERT(is_good_ks(input));
RW_ASSERT(is_good_ks(output));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
// Dup, possibly to a different type.
bool okay = dup_and_convert_in_place(instance, &input->base, &output->base);
if (okay) {
return RW_STATUS_SUCCESS;
}
KEYSPEC_ERROR(instance, input, "Copy ks failed(%p)", &input->base.descriptor);
return RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_move(
rw_keyspec_instance_t* instance,
rw_keyspec_path_t* input,
rw_keyspec_path_t* output)
{
RW_ASSERT(is_good_ks(input));
RW_ASSERT(is_good_ks(output));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
// Dup, possibly to a different type.
bool okay = dup_and_convert_in_place(instance, &input->base, &output->base);
if (okay) {
return RW_STATUS_SUCCESS;
}
KEYSPEC_ERROR(instance, input, "Move ks failed(%p)", &input->base.descriptor);
return RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_swap(
rw_keyspec_instance_t* instance,
rw_keyspec_path_t* a,
rw_keyspec_path_t* b)
{
RW_ASSERT(is_good_ks(a));
RW_ASSERT(is_good_ks(b));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
// Encode the a. Hope that it fits on the stack.
uint8_t stackbufa[4096];
uint8_t* bufa = nullptr;
size_t sizea = protobuf_c_message_get_packed_size(
instance->pbc_instance, &a->base);
if (sizea <= sizeof(stackbufa)) {
bufa = stackbufa;
} else {
bufa = (uint8_t*)malloc(sizea);
RW_ASSERT(bufa);
}
size_t actual_sizea = protobuf_c_message_pack(
instance->pbc_instance, &a->base, bufa);
RW_ASSERT(actual_sizea == sizea);
// Encode the old. Hope that it fits on the stack.
uint8_t stackbufb[4096];
uint8_t* bufb = nullptr;
size_t sizeb = protobuf_c_message_get_packed_size(
instance->pbc_instance, &b->base);
if (sizeb <= sizeof(stackbufb)) {
bufb = stackbufb;
} else {
bufb = (uint8_t*)malloc(sizeb);
RW_ASSERT(bufb);
}
size_t actual_sizeb = protobuf_c_message_pack(
instance->pbc_instance, &b->base, bufb);
RW_ASSERT(actual_sizeb == sizeb);
// Free current contents (just in case they are bumpy).
const ProtobufCMessageDescriptor* pbcmda = a->base.descriptor;
const ProtobufCMessageDescriptor* pbcmdb = b->base.descriptor;
protobuf_c_message_free_unpacked_usebody(instance->pbc_instance, &a->base);
protobuf_c_message_free_unpacked_usebody(instance->pbc_instance, &b->base);
// Ensure that protobuf-c won't crash on unpack...
protobuf_c_message_init(pbcmda, &a->base);
protobuf_c_message_init(pbcmdb, &b->base);
// Decode a into b.
ProtobufCMessage* b_dup = protobuf_c_message_unpack_usebody(
instance->pbc_instance, b->base.descriptor, sizea, bufa, &b->base);
// Decode b into a.
ProtobufCMessage* a_dup = protobuf_c_message_unpack_usebody(
instance->pbc_instance, a->base.descriptor, sizeb, bufb, &a->base);
if (bufa != stackbufa) {
free(bufa);
}
if (bufb != stackbufb) {
free(bufb);
}
if (a_dup == &a->base && b_dup == &b->base) {
return RW_STATUS_SUCCESS;
}
protobuf_c_message_free_unpacked_usebody(instance->pbc_instance, &a->base);
protobuf_c_message_free_unpacked_usebody(instance->pbc_instance, &b->base);
KEYSPEC_ERROR(instance, "KS swap failed(%p)(%p)", pbcmda, pbcmdb);
return RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_update_binpath(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
if (!ks.has_dompath()) {
KEYSPEC_ERROR(instance, k, "Update binpath, domapth not set");
return status;
}
if (ks.has_binpath()) {
if (rw_keyspec_path_delete_binpath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(!ks.has_binpath());
const ProtobufCMessage *dom_path = ks.get_dompath();
RW_ASSERT(dom_path);
std::unique_ptr<uint8_t> uptr;
uint8_t stack_buff[2048], *buff = nullptr;
size_t len = protobuf_c_message_get_packed_size(
instance->pbc_instance, dom_path);
if (len > 2048) {
buff = (uint8_t *)malloc(len);
RW_ASSERT(buff);
uptr.reset(buff);
} else {
buff = &stack_buff[0];
}
if ((protobuf_c_message_pack(instance->pbc_instance, dom_path, buff)) != len) {
return status;
}
auto bin_fd = protobuf_c_message_descriptor_get_field(
k->base.descriptor, RW_SCHEMA_TAG_KEYSPEC_BINPATH);
RW_ASSERT(bin_fd);
if (!protobuf_c_message_set_field_text_value(
instance->pbc_instance, &k->base, bin_fd, (char *)buff, len)) {
KEYSPEC_ERROR(instance, k, "Failed to set binpath in ks");
return status;
}
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_delete_binpath(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
protobuf_c_boolean ok = protobuf_c_message_delete_field(
instance->pbc_instance, &k->base, RW_SCHEMA_TAG_KEYSPEC_BINPATH);
return ok?RW_STATUS_SUCCESS:RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_update_dompath(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
if (!ks.has_binpath()) {
KEYSPEC_ERROR(instance, k, "Update dompath, binpath not set");
return status;
}
if (ks.has_dompath()) {
if (rw_keyspec_path_delete_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
const uint8_t *bd = nullptr;
size_t len = ks.get_binpath(&bd);
RW_ASSERT(bd);
ProtobufCMessage *dom_path = nullptr;
auto fd = protobuf_c_message_descriptor_get_field(
k->base.descriptor, RW_SCHEMA_TAG_KEYSPEC_DOMPATH);
protobuf_c_message_set_field_message(
instance->pbc_instance, &k->base, fd, &dom_path);
RW_ASSERT(dom_path);
if (protobuf_c_message_unpack_usebody(
instance->pbc_instance, dom_path->descriptor, len, bd, dom_path) != dom_path) {
KEYSPEC_ERROR(instance, k, "Update dompath, failed to unpack");
rw_keyspec_path_delete_dompath(k, instance);
return status;
}
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_delete_dompath(
rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
protobuf_c_boolean ok = protobuf_c_message_delete_field(
instance->pbc_instance, &k->base, RW_SCHEMA_TAG_KEYSPEC_DOMPATH);
return ok?RW_STATUS_SUCCESS:RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_delete_strpath(
rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
protobuf_c_boolean ok = protobuf_c_message_delete_field(
instance->pbc_instance, &k->base, RW_SCHEMA_TAG_KEYSPEC_STRPATH);
return ok?RW_STATUS_SUCCESS:RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_path_get_binpath(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const uint8_t** buf,
size_t* len)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(buf);
RW_ASSERT(len);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
if (!ks.has_binpath()) {
if (rw_keyspec_path_update_binpath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_binpath());
*len = ks.get_binpath(buf);
RW_ASSERT(*buf);
return RW_STATUS_SUCCESS;
}
#define IS_SAME_ELEMENT(e1, e2) \
((e1->system_ns_id == e2->system_ns_id) && \
(e1->element_tag == e2->element_tag) && \
(e1->element_type == e2->element_type))
rw_schema_ns_and_tag_t rw_keyspec_entry_get_schema_id (
const rw_keyspec_entry_t *path_entry) {
auto elem_id =
rw_keyspec_entry_get_element_id (path_entry);
rw_schema_ns_and_tag_t schema_id;
schema_id.ns = elem_id->system_ns_id;
schema_id.tag = elem_id->element_tag;
return schema_id;
}
const RwSchemaElementId* rw_keyspec_entry_get_element_id(
const rw_keyspec_entry_t *path_entry)
{
const ProtobufCFieldDescriptor *fd = nullptr;
RW_ASSERT(path_entry);
void *msg_ptr = nullptr;
size_t offset = 0;
protobuf_c_boolean is_dptr = false;
size_t count = protobuf_c_message_get_field_desc_count_and_offset(&path_entry->base,
RW_SCHEMA_TAG_ELEMENT_ID, &fd, &msg_ptr, &offset, &is_dptr);
RW_ASSERT(count);
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(fd->label != PROTOBUF_C_LABEL_REPEATED);
return (RwSchemaElementId *)msg_ptr;
}
size_t rw_keyspec_path_get_depth(
const rw_keyspec_path_t* k)
{
RW_ASSERT(is_good_ks(k));
return KeySpecHelper(k).get_depth();
}
RwSchemaCategory rw_keyspec_path_get_category(
const rw_keyspec_path_t* k)
{
RW_ASSERT(is_good_ks(k));
return KeySpecHelper(k).get_category();
}
void rw_keyspec_path_set_category(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
RwSchemaCategory category)
{
RW_ASSERT(is_good_ks(k));
RW_ASSERT((category >= RW_SCHEMA_CATEGORY_ANY) &&
(category <= RW_SCHEMA_CATEGORY_NOTIFICATION));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, set_category);
KeySpecHelper ks(k);
if (!ks.has_dompath()) {
rw_status_t s = rw_keyspec_path_update_dompath(k, instance);
RW_ASSERT(s == RW_STATUS_SUCCESS);
}
RW_ASSERT(ks.has_dompath());
ProtobufCMessage *dom_ptr = (ProtobufCMessage *)(ks.get_dompath());
const ProtobufCFieldDescriptor *fd = protobuf_c_message_descriptor_get_field(
dom_ptr->descriptor, RW_SCHEMA_TAG_KEYSPEC_CATEGORY);
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_ENUM);
RW_ASSERT(fd->label == PROTOBUF_C_LABEL_OPTIONAL);
RW_ASSERT(&rw_schema_category__descriptor == fd->descriptor);
auto field_ptr = (RwSchemaCategory *)((uint8_t *)dom_ptr + fd->offset);
*field_ptr = category;
RW_ASSERT(fd->quantifier_offset);
auto qf = (protobuf_c_boolean *)((uint8_t *)dom_ptr + fd->quantifier_offset);
*qf = TRUE;
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
}
const rw_keyspec_entry_t* rw_keyspec_path_get_path_entry(
const rw_keyspec_path_t* k,
size_t entry_index)
{
RW_ASSERT(is_good_ks(k));
KeySpecHelper ks(k);
// To return the path_entry, dompath must be present in the keyspec.
if (!ks.has_dompath()) {
return nullptr;
}
return ks.get_path_entry(entry_index);
}
size_t rw_keyspec_entry_num_keys(
const rw_keyspec_entry_t *path_entry)
{
const RwSchemaElementId *element = rw_keyspec_entry_get_element_id(path_entry);
switch (element->element_type) {
case RW_SCHEMA_ELEMENT_TYPE_ROOT:
case RW_SCHEMA_ELEMENT_TYPE_MODULE_ROOT:
case RW_SCHEMA_ELEMENT_TYPE_CONTAINER:
case RW_SCHEMA_ELEMENT_TYPE_LEAF:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_0:
return 0;
case RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_FLOAT:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_DOUBLE:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_INT32:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_SFIXED32:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_SINT32:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_UINT32:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_FIXED32:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_INT64:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_SINT64:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_SFIXED64:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_UINT64:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_FIXED64:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_BOOL:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_BYTES:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_1_STRING:
return 1;
case RW_SCHEMA_ELEMENT_TYPE_LISTY_2:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_3:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_4:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_5:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_6:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_7:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_8:
case RW_SCHEMA_ELEMENT_TYPE_LISTY_9:
return 2 + element->element_type - RW_SCHEMA_ELEMENT_TYPE_LISTY_2;
case _RW_SCHEMA_ELEMENT_TYPE_IS_INT_SIZE:
break;
}
// Don't assert here - element-=id could be from the wire.
return 0;
}
static int find_mis_matching_key_value_index(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry1,
const rw_keyspec_entry_t *path_entry2,
bool is_wild_card_match)
{
void *key1 = nullptr;
void *key2 = nullptr;
size_t count1 = 0, offset = 0, count2 = 0;
size_t len1 = 0, len2 = 0;
ProtobufCMessage *mkey1 = nullptr, *mkey2 = nullptr;
protobuf_c_boolean is_dptr = false;
const ProtobufCFieldDescriptor *fd1 = nullptr, *fd2 = nullptr;
uint8_t stackbuf1[1024];
uint8_t stackbuf2[1024];
size_t n_keys = rw_keyspec_entry_num_keys(path_entry1);
// Number of keys is determined from the element type. Hence
// it should be same in both the path entries.
for (unsigned i = 0; i < n_keys; i++) {
count1 = protobuf_c_message_get_field_desc_count_and_offset(&path_entry1->base,
RW_SCHEMA_TAG_ELEMENT_KEY_START+i, &fd1, &key1, &offset, &is_dptr);
if (count1) {
RW_ASSERT(fd1->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(fd1->label != PROTOBUF_C_LABEL_REPEATED);
mkey1 = (ProtobufCMessage *)key1;
size_t size = protobuf_c_message_get_packed_size(
instance->pbc_instance, mkey1);
RW_ASSERT(size <= sizeof(stackbuf1));
len1 = protobuf_c_message_pack(instance->pbc_instance, mkey1, stackbuf1);
RW_ASSERT(len1 == size);
key1 = stackbuf1;
}
count2 = protobuf_c_message_get_field_desc_count_and_offset(&path_entry2->base,
RW_SCHEMA_TAG_ELEMENT_KEY_START+i, &fd2, &key2, &offset, &is_dptr);
if (count2) {
RW_ASSERT(fd2->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(fd2->label != PROTOBUF_C_LABEL_REPEATED);
mkey2 = (ProtobufCMessage *)key2;
size_t size = protobuf_c_message_get_packed_size(
instance->pbc_instance, mkey2);
RW_ASSERT(size <= sizeof(stackbuf2));
len2 = protobuf_c_message_pack(instance->pbc_instance, mkey2, stackbuf2);
RW_ASSERT(len2 == size);
key2 = stackbuf2;
}
if (count1 && count2) {
if (len1 != len2) {
return i;
}
if (memcmp(key1, key2, len1)) {
return i;
}
} else {
if (!is_wild_card_match) {
return i;
}
}
}
return -1;
}
static bool compare_path_entries(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry1,
const rw_keyspec_entry_t *path_entry2,
int* key_index,
bool wc_match)
{
if (key_index) {
*key_index = -1;
}
if (protobuf_c_message_is_equal_deep(instance->pbc_instance,
&path_entry1->base,
&path_entry2->base)) {
return true;
}
auto elemid1 = rw_keyspec_entry_get_element_id(path_entry1);
RW_ASSERT(elemid1);
auto elemid2 = rw_keyspec_entry_get_element_id(path_entry2);
RW_ASSERT(elemid2);
// Compare element ids.
if (IS_SAME_ELEMENT(elemid1, elemid2)) {
if (key_index) {
*key_index = find_mis_matching_key_value_index(
instance, path_entry1, path_entry2, wc_match);
}
return true;
}
return false;
}
bool rw_keyspec_path_is_entry_at_tip(
const rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t* entry,
size_t* entry_index,
int* key_index)
{
bool retval = false;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(is_good_pe(entry));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, has_entry);
KeySpecHelper ks(k);
size_t depth = ks.get_depth();
if (!depth) {
return retval;
}
if (key_index) {
*key_index = -1;
}
std::stack <uint32_t> pe_path;
auto pe_ypbc = entry->base.descriptor->ypbc_mdesc;
RW_ASSERT(pe_ypbc);
while (pe_ypbc) {
pe_path.push(pe_ypbc->pb_element_tag);
pe_ypbc = pe_ypbc->parent;
}
for (unsigned i = 0; i < depth; i++) {
auto path_entry = ks.get_path_entry(i);
RW_ASSERT(path_entry);
auto id = pe_path.top();
pe_ypbc = path_entry->base.descriptor->ypbc_mdesc;
if ((nullptr == pe_ypbc) || (pe_ypbc->pb_element_tag != id)) {
return false;
}
pe_path.pop();
if (!pe_path.empty()) {
continue;
}
if (i != depth - 1) {
// lengths differ
return false;
}
int ki = -1;
retval = compare_path_entries(instance, path_entry, entry, &ki, false);
if (retval) {
if (entry_index) {
*entry_index = i;
}
if (key_index) {
*key_index = ki;
}
break;
}
}
return retval;
}
bool rw_keyspec_path_has_element(
const rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const RwSchemaElementId* element,
size_t* element_index)
{
bool retval = false;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(element);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
size_t depth = ks.get_depth();
for (unsigned i = 0; i < depth; i++) {
auto path_entry = ks.get_path_entry(i);
RW_ASSERT(path_entry);
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id);
if (IS_SAME_ELEMENT(element, elem_id)) {
*element_index = i;
retval = true;
break;
}
}
return retval;
}
bool rw_keyspec_entry_has_key (
const rw_keyspec_entry_t* entry,
int key_index)
{
if (!entry) {
return false;
}
const ProtobufCFieldDescriptor *fd = nullptr;
void *msg_ptr = nullptr;
size_t offset = 0;
protobuf_c_boolean is_dptr = false;
size_t count = protobuf_c_message_get_field_desc_count_and_offset (
&entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START + key_index, &fd,
&msg_ptr, &offset, &is_dptr);
RW_ASSERT(count < 2);
return (0 != count);
}
rw_status_t rw_keyspec_entry_get_key_value(const rw_keyspec_entry_t* entry,
int key_index,
ProtobufCFieldInfo *value)
{
if (entry->base.descriptor ==
(const ProtobufCMessageDescriptor *)&rw_schema_path_entry__concrete_descriptor) {
return RW_STATUS_FAILURE;
}
if (!rw_keyspec_entry_has_key (entry, key_index)) {
return RW_STATUS_FAILURE;
}
memset (value, 0, sizeof (ProtobufCFieldInfo));
const ProtobufCMessage *msg = (const ProtobufCMessage *)entry;
// The keyXXX message
const ProtobufCFieldDescriptor *fld = protobuf_c_message_descriptor_get_field (
msg->descriptor,RW_SCHEMA_TAG_ELEMENT_KEY_START + key_index);
RW_ASSERT(nullptr != fld);
ProtobufCMessage *key =
STRUCT_MEMBER_PTR (ProtobufCMessage, msg, fld->offset);
const ProtobufCMessageDescriptor *desc = key->descriptor;
size_t i = 0;
while (i < desc->n_fields) {
// the named key within the field
if (PROTOBUF_C_LABEL_REQUIRED == desc->fields[i].label) {
break;
}
++i;
}
if (i >= desc->n_fields) {
return RW_STATUS_FAILURE;
}
auto found_key = protobuf_c_message_get_field_instance(
nullptr, key, &desc->fields[i], 0, value);
RW_ASSERT(found_key);
return RW_STATUS_SUCCESS;
}
ProtobufCMessage*
rw_keyspec_entry_get_key(const rw_keyspec_entry_t *path_entry,
int index)
{
const ProtobufCFieldDescriptor *fd = NULL;
protobuf_c_boolean is_dptr = false;
void *key_msg = NULL;
size_t off = 0;
RW_ASSERT(path_entry);
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
&path_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+index, &fd, &key_msg, &off, &is_dptr);
if (count) {
RW_ASSERT(key_msg);
return (ProtobufCMessage *)key_msg;
}
return NULL;
}
uint8_t*
rw_keyspec_entry_get_key_packed(const rw_keyspec_entry_t* entry,
rw_keyspec_instance_t* instance,
int key_index,
size_t* len)
{
RW_ASSERT(is_good_pe(entry));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
ProtobufCMessage* key = rw_keyspec_entry_get_key(entry, key_index);
if (!key) {
return nullptr;
}
return protobuf_c_message_serialize(instance->pbc_instance, key, len);
}
uint8_t*
rw_keyspec_entry_get_keys_packed(const rw_keyspec_entry_t* entry,
rw_keyspec_instance_t* instance,
size_t* len)
{
RW_ASSERT(is_good_pe(entry));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
uint8_t *packed_buffer = NULL;
*len = 0;
size_t num_keys = rw_keyspec_entry_num_keys(entry);
for (size_t key_index = 0; key_index< num_keys; key_index++) {
ProtobufCMessage* key = rw_keyspec_entry_get_key(entry, key_index);
if (!key) {
// free the current buffer if any also
return nullptr;
}
packed_buffer = protobuf_c_message_serialize_append(instance->pbc_instance, key, packed_buffer, len);
if (packed_buffer == 0) {
return nullptr;
}
}
return packed_buffer;
}
bool rw_keyspec_path_is_equal(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* a,
const rw_keyspec_path_t* b)
{
RW_ASSERT(is_good_ks(a));
RW_ASSERT(is_good_ks(b));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, is_equal);
KeySpecHelper ks_a(a);
KeySpecHelper ks_b(b);
return ks_a.is_equal(ks_b);
}
bool rw_keyspec_path_is_equal_detail(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* a,
const rw_keyspec_path_t* b,
size_t* entry_index,
int* key_index)
{
/*
* ATTN: This function should return an indication of *HOW* the
* keyspecs differ - not just which PE and key.
*/
RW_ASSERT(is_good_ks(a));
RW_ASSERT(is_good_ks(b));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, is_equal_detail);
if (entry_index) {
*entry_index = 0;
}
if (key_index) {
*key_index = -1;
}
bool retval = false;
KeySpecHelper ks_a(a);
KeySpecHelper ks_b(b);
RwSchemaCategory cat1 = ks_a.get_category();
RwSchemaCategory cat2 = ks_b.get_category();
if (cat1 != cat2) {
return false;
}
if (ks_a.is_rooted() != ks_b.is_rooted()) {
return false;
}
const ProtobufCMessage *dompath_a = ks_a.get_dompath();
if (!dompath_a) {
return retval;
}
const ProtobufCMessage *dompath_b = ks_b.get_dompath();
if (!dompath_b) {
return retval;
}
if (protobuf_c_message_is_equal_deep(
instance->pbc_instance, dompath_a, dompath_b)) {
retval = true;
return retval;
}
size_t depth_a = ks_a.get_depth();
RW_ASSERT(depth_a);
size_t depth_b = ks_b.get_depth();
RW_ASSERT(depth_b);
if (depth_a != depth_b) {
if (!entry_index) {
return retval;
}
}
size_t path_len = std::min(depth_a, depth_b);
unsigned i;
for (i = 0; i < path_len; i++) {
auto path_entry1 = ks_a.get_path_entry(i);
RW_ASSERT(path_entry1);
auto path_entry2 = ks_b.get_path_entry(i);
RW_ASSERT(path_entry2);
int ki = -1;
retval = compare_path_entries(instance, path_entry1, path_entry2, &ki, false);
if (!retval || ki != -1) {
if (key_index) {
*key_index = ki;
}
break;
}
}
if ((i == path_len) && (depth_a == depth_b)) {
retval = true;
} else {
if (entry_index) {
*entry_index = i;
}
retval = false;
}
return retval;
}
bool rw_keyspec_path_is_match_detail(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* a,
const rw_keyspec_path_t* b,
size_t* entry_index,
int* key_index)
{
RW_ASSERT(is_good_ks(a));
RW_ASSERT(is_good_ks(b));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, is_match_detail);
if (entry_index) {
*entry_index = 0;
}
if (key_index) {
*key_index = -1;
}
bool retval = false;
KeySpecHelper ks_a(a);
KeySpecHelper ks_b(b);
RwSchemaCategory cat1 = ks_a.get_category();
RwSchemaCategory cat2 = ks_b.get_category();
if ( cat1 != cat2
&& cat1 != RW_SCHEMA_CATEGORY_ANY
&& cat2 != RW_SCHEMA_CATEGORY_ANY) {
return retval;
}
if (ks_a.is_rooted() != ks_b.is_rooted()) {
return retval;
}
const ProtobufCMessage *dompath_a = ks_a.get_dompath();
if (!dompath_a) {
return retval;
}
const ProtobufCMessage *dompath_b = ks_b.get_dompath();
if (!dompath_b) {
return retval;
}
if (protobuf_c_message_is_equal_deep(
instance->pbc_instance, dompath_a, dompath_b)) {
return true;
}
size_t depth_a = ks_a.get_depth();
RW_ASSERT(depth_a);
size_t depth_b = ks_b.get_depth();
RW_ASSERT(depth_b);
if (depth_a != depth_b) {
if (!entry_index) {
return retval;
}
}
size_t path_len = std::min(depth_a, depth_b);
unsigned i = 0;
for (i = 0; i < path_len; i++) {
auto path_entry1 = ks_a.get_path_entry(i);
RW_ASSERT(path_entry1);
auto path_entry2 = ks_b.get_path_entry(i);
RW_ASSERT(path_entry2);
int ki = -1;
retval = compare_path_entries(instance, path_entry1, path_entry2, &ki, true);
if (!retval || ki != -1) {
if (key_index) {
*key_index = ki;
}
break;
}
}
if ((i == path_len) && (depth_a == depth_b)) {
retval = true;
} else {
if (entry_index) {
*entry_index = i;
}
retval = false;
}
return retval;
}
bool rw_keyspec_path_is_same_path_detail(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* a,
const rw_keyspec_path_t* b,
size_t* entry_index)
{
RW_ASSERT(is_good_ks(a));
RW_ASSERT(is_good_ks(b));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, is_path_detail);
bool retval = false;
KeySpecHelper ks_a(a);
KeySpecHelper ks_b(b);
size_t depth1 = ks_a.get_depth();
RW_ASSERT(depth1);
size_t depth2 = ks_b.get_depth();
RW_ASSERT(depth2);
if (depth1 != depth2) {
if (!entry_index) {
return retval;
}
}
if (entry_index) {
*entry_index = 0;
}
RwSchemaCategory cat1 = ks_a.get_category();
RwSchemaCategory cat2 = ks_b.get_category();
if ( cat1 != cat2
&& cat1 != RW_SCHEMA_CATEGORY_ANY
&& cat2 != RW_SCHEMA_CATEGORY_ANY) {
return retval;
}
if (ks_a.is_rooted() != ks_b.is_rooted()) {
return retval;
}
size_t path_len = std::min(depth1, depth2);
unsigned i = 0;
for (i = 0; i < path_len; i++) {
auto path_entry1 = ks_a.get_path_entry(i);
RW_ASSERT(path_entry1);
auto path_entry2 = ks_b.get_path_entry(i);
RW_ASSERT(path_entry2);
retval = compare_path_entries(instance, path_entry1, path_entry2, NULL, false);
if (!retval) {
break;
}
}
if ((i == path_len) && (depth1 == depth2)) {
retval = true;
} else {
if (entry_index) {
*entry_index = i;
}
retval = false;
}
return retval;
}
bool rw_keyspec_path_is_branch_detail(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* prefix,
const rw_keyspec_path_t* suffix,
bool ignore_keys,
size_t* start_index,
size_t* len)
{
RW_ASSERT(is_good_ks(prefix));
RW_ASSERT(is_good_ks(suffix));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, is_branch_detail);
KeySpecHelper ks_p(prefix);
KeySpecHelper ks_s(suffix);
RwSchemaCategory cat1 = ks_p.get_category();
RwSchemaCategory cat2 = ks_s.get_category();
if ( cat1 != cat2
&& cat1 != RW_SCHEMA_CATEGORY_ANY
&& cat2 != RW_SCHEMA_CATEGORY_ANY) {
return false;
}
size_t depth_s = ks_s.get_depth();
if (!depth_s) {
return false;
}
size_t depth_p = ks_p.get_depth();
if (!depth_p) {
return false;
}
if (len) {
*len = 0;
}
unsigned pi = 0, si = 0;
bool start_found = false;
while(pi < depth_p && si < depth_s) {
auto pe_s = ks_s.get_path_entry(si);
RW_ASSERT(pe_s);
auto pe_p = ks_p.get_path_entry(pi);
RW_ASSERT(pe_p);
int ki = -1;
bool retval = compare_path_entries(instance, pe_s, pe_p, &ki, false);
if (retval && (ignore_keys || ki == -1)) {
if (len) (*len)++;
if (!start_found) {
start_found = true;
if (start_index) {
*start_index = pi;
}
}
pi++; si++;
} else {
if (start_found) {
break;
}
pi++;
}
}
return start_found;
}
static rw_status_t copy_path_entry_at(
rw_keyspec_instance_t* instance,
ProtobufCMessage *dom_path,
const rw_keyspec_entry_t *entry,
unsigned index)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_pe(entry));
RW_ASSERT(dom_path);
auto fd = protobuf_c_message_descriptor_get_field(
dom_path->descriptor, RW_SCHEMA_TAG_PATH_ENTRY_START+index);
if (!fd) {
return status;
}
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(fd->label != PROTOBUF_C_LABEL_REPEATED);
// Make sure to delete any previous value.
protobuf_c_message_delete_field(
instance->pbc_instance, dom_path, RW_SCHEMA_TAG_PATH_ENTRY_START+index);
ProtobufCMessage *pmsg = nullptr;
protobuf_c_message_set_field_message(instance->pbc_instance, dom_path, fd, &pmsg);
RW_ASSERT(pmsg);
if (!protobuf_c_message_copy_usebody(
instance->pbc_instance, &entry->base, pmsg)) {
KEYSPEC_ERROR(instance, "Failed to copy path entry to ks(%p)", pmsg->descriptor);
protobuf_c_message_delete_field(instance->pbc_instance, dom_path, fd->id);
return status;
}
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_append_entry(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t* entry)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(is_good_pe(entry));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, append_entry);
KeySpecHelper ks(k);
if (!ks.has_dompath()) {
if (rw_keyspec_path_update_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_dompath());
size_t depth = ks.get_depth();
ProtobufCMessage *dom_path = (ProtobufCMessage *)ks.get_dompath();
RW_ASSERT(dom_path);
status = copy_path_entry_at(instance, dom_path, entry, depth);
if (status == RW_STATUS_SUCCESS) {
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
}
return status;
}
rw_status_t rw_keyspec_path_append_entries(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t* const* entries,
size_t len)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(entries);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
if (!ks.has_dompath()) {
if (rw_keyspec_path_update_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_dompath());
size_t depth = ks.get_depth();
ProtobufCMessage *dom_path = (ProtobufCMessage *)ks.get_dompath();
RW_ASSERT(dom_path);
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
unsigned i = 0, j = 0;
for (i = depth, j = 0; j < len; i++, j++) {
RW_ASSERT(entries[j]);
status = copy_path_entry_at(instance, dom_path, entries[j], i);
if (status != RW_STATUS_SUCCESS) {
break;
}
}
if (j == len) {
status = RW_STATUS_SUCCESS;
} else {
// Failed to append all the entries. Free any allocated path entries.
for (i = depth; i < (depth+j); i++) {
protobuf_c_message_delete_field(instance->pbc_instance, dom_path,
RW_SCHEMA_TAG_PATH_ENTRY_START+i);
}
}
return status;
}
rw_status_t rw_keyspec_path_append_keyspec(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* other)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(is_good_ks(other));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
KeySpecHelper ks_o(other);
if (!ks.has_dompath()) {
if (rw_keyspec_path_update_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_dompath());
size_t depth_s = ks.get_depth();
size_t depth_d = ks_o.get_depth();
if (!depth_d) {
return status;
}
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
ProtobufCMessage *dom_path = (ProtobufCMessage *)ks.get_dompath();
RW_ASSERT(dom_path);
unsigned i = 0, j = depth_s;
for (i = 0; i < depth_d; i++, j++) {
auto pentry = ks_o.get_path_entry(i);
RW_ASSERT(pentry);
status = copy_path_entry_at(instance, dom_path, pentry, j);
if (status != RW_STATUS_SUCCESS) {
break;
}
}
if (i == depth_d) {
status = RW_STATUS_SUCCESS;
}
else if (i != depth_d) {
// Free any allocated messages.
for (unsigned j = depth_s; j < (depth_s+i); j++) {
protobuf_c_message_delete_field(
instance->pbc_instance, dom_path, RW_SCHEMA_TAG_PATH_ENTRY_START+j);
}
}
return status;
}
rw_status_t rw_keyspec_path_append_replace(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* other,
int k_index,
size_t other_index,
int other_len)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(is_good_ks(other));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
KeySpecHelper ks_o(other);
if (!ks.has_dompath()) {
if (rw_keyspec_path_update_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_dompath());
size_t depth_s = ks.get_depth();
size_t depth_d = ks_o.get_depth();
if (k_index < -1) {
return RW_STATUS_OUT_OF_BOUNDS;
}
if ((k_index > 0) && ((size_t)k_index > depth_s)) {
return RW_STATUS_OUT_OF_BOUNDS;
}
if ((other_index >= depth_d) || (other_len <= 0) || ((other_index + other_len) > depth_d)) {
return RW_STATUS_OUT_OF_BOUNDS;
}
if (((size_t)k_index == depth_s) || (k_index == -1)) {
k_index = depth_s;
}
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
ProtobufCMessage *dom_path = (ProtobufCMessage *)ks.get_dompath();
RW_ASSERT(dom_path);
unsigned i = 0;
for (i = other_index; i < (other_index+other_len); i++) {
auto pentry = ks_o.get_path_entry(i);
RW_ASSERT(pentry);
status = copy_path_entry_at(instance, dom_path, pentry, k_index++);
if (status != RW_STATUS_SUCCESS) {
break;
}
}
if (i != (other_index+other_len)) {
unsigned st = k_index;
for (unsigned j = st; j < (i-other_index)+1; j++) {
protobuf_c_message_delete_field(instance->pbc_instance, dom_path,
RW_SCHEMA_TAG_PATH_ENTRY_START+j);
}
} else {
status = RW_STATUS_SUCCESS;
}
return status;
}
rw_status_t rw_keyspec_path_trunc_suffix_n(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
size_t index)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, trunc_suffix);
KeySpecHelper ks(k);
if (!ks.has_dompath()) {
if (rw_keyspec_path_update_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_dompath());
size_t depth = ks.get_depth();
if (index > depth) {
status = RW_STATUS_OUT_OF_BOUNDS;
return status;
}
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
ProtobufCMessage *dom_path = (ProtobufCMessage *)ks.get_dompath();
RW_ASSERT(dom_path);
for (unsigned i = index; i < depth; i++) {
if(!protobuf_c_message_delete_field(
instance->pbc_instance, dom_path, RW_SCHEMA_TAG_PATH_ENTRY_START+i)) {
return status;
}
}
/* Delete any path entries in the unknown buffer */
for (unsigned i = RW_SCHEMA_TAG_PATH_ENTRY_START+depth;
(i <= RW_SCHEMA_TAG_PATH_ENTRY_END && (nullptr != dom_path->unknown_buffer));
++i) {
protobuf_c_message_delete_field(instance->pbc_instance, dom_path, i);
}
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_trunc_concrete(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(k);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
// Get the field descriptor for dompath
const ProtobufCFieldDescriptor* path_fd
= protobuf_c_message_descriptor_get_field(
k->base.descriptor,
RW_SCHEMA_TAG_KEYSPEC_DOMPATH);
RW_ASSERT(path_fd);
RW_ASSERT(path_fd->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(path_fd->label != PROTOBUF_C_LABEL_REPEATED);
RW_ASSERT(!path_fd->ctype);
// Get the message descriptor for dompath
const ProtobufCMessageDescriptor* dom_mdesc
= reinterpret_cast<const ProtobufCMessageDescriptor*>(path_fd->descriptor);
// Find the truncation depth - the first non-concrete path entry
unsigned entry = RW_SCHEMA_TAG_PATH_ENTRY_START;
for (; entry <= RW_SCHEMA_TAG_PATH_ENTRY_END; ++entry) {
const ProtobufCFieldDescriptor* entry_fd
= protobuf_c_message_descriptor_get_field(dom_mdesc, entry);
if ( entry_fd == NULL
|| entry_fd->descriptor == &rw_schema_path_entry__descriptor) {
break;
}
}
// Truncate all generic path elements
rw_status_t rs = rw_keyspec_path_trunc_suffix_n(k, instance, entry-RW_SCHEMA_TAG_PATH_ENTRY_START);
if (RW_STATUS_SUCCESS != rs) {
return rs;
}
protobuf_c_boolean ok
= protobuf_c_message_delete_unknown_all(instance->pbc_instance, &k->base);
if (ok) {
return RW_STATUS_SUCCESS;
}
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_serialize_dompath(
const rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
ProtobufCBinaryData* data)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(data && !data->data);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, pack_dompath);
KeySpecHelper ks(k);
const uint8_t *bd = nullptr;
size_t len = ks.get_binpath(&bd);
if (!bd) {
KEYSPEC_ERROR(instance, k, "Failed to serialize dompath");
return status;
}
data->data = (uint8_t *)malloc(len);
RW_ASSERT(data->data);
data->len = len;
memcpy(data->data, bd, len);
return RW_STATUS_SUCCESS;
}
rw_keyspec_path_t* rw_keyspec_path_create_with_binpath_buf(
rw_keyspec_instance_t* instance,
size_t len,
const void* data)
{
RW_ASSERT(data);
RW_ASSERT(len);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_with_binpath);
RwSchemaPathSpec *kspec = (RwSchemaPathSpec *)malloc(sizeof(RwSchemaPathSpec));
RW_ASSERT(kspec);
rw_schema_path_spec__init(kspec);
kspec->has_binpath = true;
kspec->binpath.len = len;
kspec->binpath.data = (uint8_t *)malloc(len);
RW_ASSERT(kspec->binpath.data);
memcpy(kspec->binpath.data, data, len);
rw_status_t s = rw_keyspec_path_update_dompath(
&kspec->rw_keyspec_path_t, instance);
if (s != RW_STATUS_SUCCESS) {
KEYSPEC_ERROR(instance, "Failed to unpack ks to generic type");
rw_schema_path_spec__free_unpacked(instance->pbc_instance, kspec);
return NULL;
}
return &kspec->rw_keyspec_path_t;
}
rw_keyspec_path_t* rw_keyspec_path_create_with_binpath_binary_data(
rw_keyspec_instance_t* instance,
const ProtobufCBinaryData* data)
{
RW_ASSERT(data);
RW_ASSERT(data->data);
RW_ASSERT(data->len);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_with_binpath);
RwSchemaPathSpec *kspec = (RwSchemaPathSpec *)malloc(sizeof(RwSchemaPathSpec));
RW_ASSERT(kspec);
rw_schema_path_spec__init(kspec);
kspec->has_binpath = true;
kspec->binpath.len = data->len;
kspec->binpath.data = (uint8_t *)malloc(data->len);
RW_ASSERT(kspec->binpath.data);
memcpy(kspec->binpath.data, data->data, data->len);
rw_status_t s = rw_keyspec_path_update_dompath(
&kspec->rw_keyspec_path_t, instance);
if (s != RW_STATUS_SUCCESS) {
KEYSPEC_ERROR(instance, "Failed to unpack ks to generic type");
rw_schema_path_spec__free_unpacked(instance->pbc_instance, kspec);
return NULL;
}
return &kspec->rw_keyspec_path_t;
}
rw_keyspec_path_t* rw_keyspec_path_create_with_dompath_binary_data(
rw_keyspec_instance_t* instance,
const ProtobufCBinaryData* data)
{
RW_ASSERT(data);
RW_ASSERT(data->data);
RW_ASSERT(data->len);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_with_dompath);
RwSchemaPathSpec *kspec = (RwSchemaPathSpec *)malloc(sizeof(RwSchemaPathSpec));
RW_ASSERT(kspec);
rw_schema_path_spec__init(kspec);
kspec->dompath = (RwSchemaPathDom *)malloc(sizeof(RwSchemaPathDom));
RW_ASSERT(kspec->dompath);
rw_schema_path_dom__init(kspec->dompath);
if (!protobuf_c_message_unpack_usebody(
instance->pbc_instance, kspec->dompath->base.descriptor,
data->len, data->data, &kspec->dompath->base)) {
KEYSPEC_ERROR(instance, "Failed to unpack ks to generic type");
rw_schema_path_spec__free_unpacked(instance->pbc_instance, kspec);
return NULL;
}
return &kspec->rw_keyspec_path_t;
}
rw_keyspec_path_t* rw_keyspec_path_create_concrete_with_dompath_binary_data(
rw_keyspec_instance_t* instance,
const ProtobufCBinaryData* data,
const ProtobufCMessageDescriptor *mdesc)
{
RW_ASSERT(data);
RW_ASSERT(data->data);
RW_ASSERT(data->len);
RW_ASSERT(mdesc);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, create_with_dompath);
ProtobufCMessage *out_ks = nullptr;
out_ks = (ProtobufCMessage *)malloc(mdesc->sizeof_message);
RW_ASSERT(out_ks);
protobuf_c_message_init(mdesc, out_ks);
const ProtobufCFieldDescriptor *fd = nullptr;
fd = protobuf_c_message_descriptor_get_field(out_ks->descriptor,
RW_SCHEMA_TAG_KEYSPEC_DOMPATH);
RW_ASSERT(fd);
ProtobufCMessage *dom = nullptr;
protobuf_c_message_set_field_message(instance->pbc_instance, out_ks, fd, &dom);
RW_ASSERT(dom);
if (!protobuf_c_message_unpack_usebody(
instance->pbc_instance, (const ProtobufCMessageDescriptor *)(fd->descriptor),
data->len, data->data, dom)) {
KEYSPEC_ERROR(instance, "Failed to unpack ks(%p)", mdesc);
protobuf_c_message_free_unpacked(instance->pbc_instance, out_ks);
return NULL;
}
return (rw_keyspec_path_t *)out_ks;
}
rw_status_t rw_keyspec_path_free(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, free);
protobuf_c_message_free_unpacked(instance->pbc_instance, &k->base);
return RW_STATUS_SUCCESS;
}
bool rw_keyspec_path_has_wildcards(
const rw_keyspec_path_t *k)
{
RW_ASSERT(is_good_ks(k));
return KeySpecHelper(k).has_wildcards();
}
bool rw_keyspec_path_has_wildcards_for_depth(
const rw_keyspec_path_t *k,
size_t depth)
{
RW_ASSERT(is_good_ks(k));
if (!depth) {
return false;
}
return KeySpecHelper(k).has_wildcards(0, depth);
}
bool rw_keyspec_path_has_wildcards_for_last_entry(
const rw_keyspec_path_t *k)
{
RW_ASSERT(is_good_ks(k));
KeySpecHelper ks(k);
size_t depth = ks.get_depth();
if (!depth) {
return false;
}
return ks.has_wildcards(depth-1);
}
static listy_pe_type_t get_path_entry_type(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *entry)
{
RW_ASSERT(entry);
const RwSchemaElementId *element = rw_keyspec_entry_get_element_id(entry);
switch (element->element_type) {
case RW_SCHEMA_ELEMENT_TYPE_CONTAINER:
return PE_CONTAINER;
case RW_SCHEMA_ELEMENT_TYPE_LISTY_0:
return PE_LISTY_WITH_ALL_WC;
case RW_SCHEMA_ELEMENT_TYPE_LEAF:
case RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST:
RW_ASSERT_NOT_REACHED();
default:
break;
}
unsigned no_wc = 0, no_keys = 0;
// any wildcarded path entries are also iteratable.
// Listy type. Check whether the key values are specified.
no_keys = rw_keyspec_entry_num_keys(entry);
for (unsigned j = 0; j < no_keys; j++) {
if (!protobuf_c_message_has_field(instance->pbc_instance,
&entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+j)) {
no_wc++;
}
}
RW_ASSERT(no_keys);
if (no_wc == 0) {
return PE_LISTY_WITH_ALL_KEYS;
}
if (no_wc == no_keys) {
return PE_LISTY_WITH_ALL_WC;
}
return PE_LISTY_WITH_WC_AND_KEYS;
}
bool rw_keyspec_entry_is_listy(
const rw_keyspec_entry_t *entry)
{
RW_ASSERT(entry);
auto element = rw_keyspec_entry_get_element_id(entry);
RW_ASSERT(element);
return ((element->element_type >= RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST)
&& (element->element_type <= RW_SCHEMA_ELEMENT_TYPE_LISTY_9));
}
bool rw_keyspec_path_is_listy(
const rw_keyspec_path_t *ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).is_listy();
}
bool rw_keyspec_path_is_generic(const rw_keyspec_path_t *ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).is_generic();
}
bool rw_keyspec_path_is_leafy(const rw_keyspec_path_t *ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).is_leafy();
}
const ProtobufCFieldDescriptor*
rw_keyspec_path_get_leaf_field_desc(const rw_keyspec_path_t *ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).get_leaf_pb_desc();
}
bool rw_keyspec_path_is_rooted(
const rw_keyspec_path_t* ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).is_rooted();
}
bool rw_keyspec_path_is_module_root(
const rw_keyspec_path_t* ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).is_module_root();
}
bool rw_keyspec_path_is_root(
const rw_keyspec_path_t* ks)
{
RW_ASSERT(is_good_ks(ks));
return KeySpecHelper(ks).is_schema_root();
}
static const rw_yang_pb_msgdesc_t*
rw_keyspec_path_find_root_mdesc_schema(
KeySpecHelper& k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema)
{
RW_ASSERT(schema);
RW_ASSERT(k.is_module_root()); // Only module root supported as of now
auto path_entry = k.get_specific_path_entry(RW_SCHEMA_TAG_PATH_ENTRY_MODULE_ROOT);
RW_ASSERT(path_entry);
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id);
auto cat = k.get_category();
const rw_yang_pb_msgdesc_t *mr_mdesc = nullptr;
for (unsigned m = 0; m < schema->module_count; m++) {
auto ypbc_module = schema->modules[m];
RW_ASSERT(ypbc_module);
switch (cat) {
case RW_SCHEMA_CATEGORY_ANY:
case RW_SCHEMA_CATEGORY_DATA:
case RW_SCHEMA_CATEGORY_CONFIG:
if (ypbc_module->data_module) {
mr_mdesc = ypbc_module->data_module;
}
break;
case RW_SCHEMA_CATEGORY_RPC_INPUT:
if (ypbc_module->rpci_module) {
mr_mdesc = ypbc_module->rpci_module;
}
break;
case RW_SCHEMA_CATEGORY_RPC_OUTPUT:
if (ypbc_module->rpco_module) {
mr_mdesc = ypbc_module->rpco_module;
}
break;
case RW_SCHEMA_CATEGORY_NOTIFICATION:
if (ypbc_module->notif_module) {
mr_mdesc = ypbc_module->notif_module;
}
break;
default:
RW_ASSERT_NOT_REACHED();
}
if (mr_mdesc) {
auto elem_id_c = rw_keyspec_entry_get_element_id(mr_mdesc->schema_entry_value);
if (IS_SAME_ELEMENT(elem_id, elem_id_c)) {
return mr_mdesc;
}
mr_mdesc = nullptr;
}
}
return mr_mdesc;
}
rw_status_t rw_keyspec_path_find_msg_desc_schema(
const rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema,
const rw_yang_pb_msgdesc_t** result_ypbc_msgdesc,
rw_keyspec_path_t** remainder)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
RW_ASSERT(result_ypbc_msgdesc);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, find_mdesc);
KeySpecHelper ks(k);
*result_ypbc_msgdesc = nullptr;
if (remainder) {
*remainder = nullptr;
}
if (!schema) {
auto ypbc_msgdesc = k->base.descriptor->ypbc_mdesc;
if (!ypbc_msgdesc) {
KEYSPEC_ERROR(instance, "Generic KS input without schema");
return status;
}
schema = ypbc_msgdesc->module->schema;
}
if (!ks.is_rooted()) {
//Keyspec is not rooted. What to do??
return status;
}
size_t depth_k = ks.get_depth();
if (!depth_k) {
*result_ypbc_msgdesc = rw_keyspec_path_find_root_mdesc_schema(ks, instance, schema);
if (!*result_ypbc_msgdesc) {
return status;
}
return RW_STATUS_SUCCESS;
}
auto path_entry = ks.get_path_entry(0);
RW_ASSERT(path_entry);
auto elemid = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elemid);
for (unsigned m = 0; m < schema->module_count; m++) {
auto ypbc_module = schema->modules[m];
RW_ASSERT(ypbc_module);
auto data_module = ypbc_module->data_module;
if (data_module) {
for (unsigned i = 0; i < data_module->child_msg_count; i++) {
auto top_level_msg = data_module->child_msgs[i];
RW_ASSERT(top_level_msg);
auto elemid_s = rw_keyspec_entry_get_element_id(
top_level_msg->schema_entry_value);
RW_ASSERT(elemid_s);
if (IS_SAME_ELEMENT(elemid, elemid_s)) {
// This top level message matched, go deep further.
status = rw_keyspec_path_find_msg_desc_msg(
k, instance, top_level_msg, 0, result_ypbc_msgdesc, remainder);
return status;
}
}
}
auto rpci_module = ypbc_module->rpci_module;
if (rpci_module) {
for (unsigned i = 0; i < rpci_module->child_msg_count; i++) {
auto top_level_msg = rpci_module->child_msgs[i];
RW_ASSERT(top_level_msg);
auto elemid_s = rw_keyspec_entry_get_element_id(
top_level_msg->schema_entry_value);
RW_ASSERT(elemid_s);
if (IS_SAME_ELEMENT(elemid_s, elemid)) {
// This top level message matched, go deep further.
status = rw_keyspec_path_find_msg_desc_msg(
k, instance, top_level_msg, 0, result_ypbc_msgdesc, remainder);
return status;
}
}
}
auto rpco_module = ypbc_module->rpco_module;
if (rpco_module) {
for (unsigned i = 0; i < rpco_module->child_msg_count; i++) {
auto top_level_msg = rpco_module->child_msgs[i];
RW_ASSERT(top_level_msg);
auto elemid_s = rw_keyspec_entry_get_element_id(
top_level_msg->schema_entry_value);
RW_ASSERT(elemid_s);
if (IS_SAME_ELEMENT(elemid_s, elemid)) {
// This top level message matched, go deep further.
status = rw_keyspec_path_find_msg_desc_msg(
k, instance, top_level_msg, 0, result_ypbc_msgdesc, remainder);
return status;
}
}
}
auto notif_module = ypbc_module->notif_module;
if (notif_module) {
for (unsigned i = 0; i < notif_module->child_msg_count; i++) {
auto top_level_msg = notif_module->child_msgs[i];
RW_ASSERT(top_level_msg);
auto elemid_s = rw_keyspec_entry_get_element_id(
top_level_msg->schema_entry_value);
RW_ASSERT(elemid_s);
if (IS_SAME_ELEMENT(elemid_s, elemid)) {
// This top level message matched, go deep further.
status = rw_keyspec_path_find_msg_desc_msg(
k, instance, top_level_msg, 0, result_ypbc_msgdesc, remainder);
return status;
}
}
}
}
return status;
}
rw_status_t rw_keyspec_path_find_msg_desc_msg(
const rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_msgdesc_t* start_ypbc_msgdesc,
size_t start_depth,
const rw_yang_pb_msgdesc_t** result_ypbc_msgdesc,
rw_keyspec_path_t** remainder)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(start_ypbc_msgdesc);
RW_ASSERT(k);
RW_ASSERT(result_ypbc_msgdesc);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
size_t depth_k = ks.get_depth();
if (start_depth >= (depth_k)) {
return status;
}
*result_ypbc_msgdesc = NULL;
if (remainder) {
*remainder = NULL;
}
unsigned path_index = start_depth+1;
const rw_keyspec_entry_t *path_entry = nullptr;
auto temp = start_ypbc_msgdesc;
auto deepest_match = start_ypbc_msgdesc;
const RwSchemaElementId* ele_id_k = nullptr;
while (path_index < depth_k) {
path_entry = ks.get_path_entry(path_index);
RW_ASSERT(path_entry);
ele_id_k = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(ele_id_k);
unsigned i = 0;
const rw_yang_pb_msgdesc_t *child = nullptr;
for (i = 0; i < temp->child_msg_count; i++) {
child = temp->child_msgs[i];
RW_ASSERT(child);
auto ele_id_s = rw_keyspec_entry_get_element_id(child->schema_entry_value);
RW_ASSERT(ele_id_s);
if (IS_SAME_ELEMENT(ele_id_s, ele_id_k)) {
break;
}
}
if (i == temp->child_msg_count) {
break;
}
temp = child;
deepest_match = child;
path_index++;
}
if (path_index == depth_k) {
*result_ypbc_msgdesc = deepest_match->schema_path_ypbc_desc;
return RW_STATUS_SUCCESS;
}
if (path_index == depth_k - 1) {
const ProtobufCMessageDescriptor *desc = deepest_match->pbc_mdesc;
RW_ASSERT(desc);
if (protobuf_c_message_descriptor_get_field(
desc, ele_id_k->element_tag) != nullptr) {
*result_ypbc_msgdesc = deepest_match->schema_path_ypbc_desc;
return RW_STATUS_SUCCESS;
}
}
status = RW_STATUS_OUT_OF_BOUNDS;
*result_ypbc_msgdesc = deepest_match->schema_path_ypbc_desc;
if (remainder) {
RwSchemaPathSpec* new_ks =
(RwSchemaPathSpec*)malloc(sizeof(RwSchemaPathSpec));
RW_ASSERT(new_ks);
rw_schema_path_spec__init(new_ks);
new_ks->dompath = (RwSchemaPathDom*)malloc(sizeof(RwSchemaPathDom));
RW_ASSERT(new_ks->dompath);
rw_schema_path_dom__init(new_ks->dompath);
if (rw_keyspec_path_append_replace(
&new_ks->rw_keyspec_path_t, instance, k, 0, path_index,
(depth_k - path_index)) != RW_STATUS_SUCCESS) {
rw_schema_path_spec__free_unpacked(instance->pbc_instance, new_ks);
} else {
*remainder = &new_ks->rw_keyspec_path_t;
}
}
return status;
}
static bool rw_keyspec_path_is_prefix_match_impl(
rw_keyspec_instance_t* instance,
KeySpecHelper& ks_a,
KeySpecHelper& ks_b,
size_t depth_a,
size_t depth_b)
{
bool retval = false;
size_t min_depth = (depth_a > depth_b) ? depth_b: depth_a;
unsigned i = 0;
for (i = 0; i < min_depth; i++) {
auto path_entry1 = ks_a.get_path_entry(i);
RW_ASSERT(path_entry1);
auto path_entry2 = ks_b.get_path_entry(i);
RW_ASSERT(path_entry2);
int ki = -1;
retval = compare_path_entries(instance, path_entry1, path_entry2, &ki, true);
if (!retval || ki != -1) {
retval = false;
break;
}
}
if (i == min_depth) {
retval = true;
}
return retval;
}
bool rw_keyspec_path_is_a_sub_keyspec(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *a,
const rw_keyspec_path_t *b)
{
RW_ASSERT(a);
RW_ASSERT(b);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, is_sub_ks);
KeySpecHelper ks_a(a);
KeySpecHelper ks_b(b);
size_t depth_a = ks_a.get_depth();
size_t depth_b = ks_b.get_depth();
if (!depth_a || !depth_b) {
// Empty keyspec
// ATTN: Why false? Shouldn't it be true?
return false;
}
return rw_keyspec_path_is_prefix_match_impl(
instance, ks_a, ks_b, depth_a, depth_b);
}
bool rw_keyspec_path_is_match_or_prefix(
const rw_keyspec_path_t *shorter_ks,
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *longer_ks)
{
RW_ASSERT(shorter_ks);
RW_ASSERT(longer_ks);
KeySpecHelper ks_s(shorter_ks);
KeySpecHelper ks_l(longer_ks);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
size_t depth_a = ks_s.get_depth();
size_t depth_b = ks_l.get_depth();
if (!depth_a || !depth_b) {
// Empty keyspec
// ATTN: Why false? Shouldn't it be true?
return false;
}
if (depth_a > depth_b) {
// Can't be prefix match
return false;
}
return rw_keyspec_path_is_prefix_match_impl(
instance, ks_s, ks_l, depth_a, depth_b);
}
/*
* Gets the key_tag from the path_entry message.
* This function should not be called for generic
* path_entry types.
*/
static uint32_t get_key_tag_from_path_entry_desc(
const rw_keyspec_entry_t* path_entry,
uint32_t key_index)
{
RW_ASSERT(path_entry);
uint32_t key_tag = 0;
const ProtobufCFieldDescriptor* fd = nullptr;
fd = protobuf_c_message_descriptor_get_field(
path_entry->base.descriptor, RW_SCHEMA_TAG_ELEMENT_KEY_START+key_index);
if (!fd) {
return (key_tag);
}
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
const ProtobufCMessageDescriptor *mdesc = (const ProtobufCMessageDescriptor *)fd->descriptor;
RW_ASSERT(mdesc);
RW_ASSERT(mdesc->n_fields == 2);
key_tag = mdesc->fields[1].id;
return (key_tag);
}
/*
* The below function converts the generic path_entry
* to concerete path entry using the schema. This is required
* to extract the key values from the generic path entry
* which will be in the unknown fields list.
*/
static rw_keyspec_entry_t* convert_generic_pe_to_concerete(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry,
const rw_yang_pb_msgdesc_t *msg_ypbmd)
{
RW_ASSERT(is_good_pe(path_entry));
RW_ASSERT(msg_ypbmd);
if (!IS_PATH_ENTRY_GENERIC(path_entry)) {
return nullptr;
}
const rw_yang_pb_msgdesc_t *entry_ypbmd = nullptr;
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id);
if (elem_id->element_type == RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST) {
// For leaf-list, this is the parent ypb-msg desc.
for (unsigned i = 0; i < msg_ypbmd->child_msg_count; i++) {
if (msg_ypbmd->child_msgs[i]->pb_element_tag == elem_id->element_tag) {
entry_ypbmd = msg_ypbmd->child_msgs[i]->schema_entry_ypbc_desc;
break;
}
}
} else {
entry_ypbmd = msg_ypbmd->schema_entry_ypbc_desc;
}
if (!entry_ypbmd) {
return nullptr;
}
rw_keyspec_entry_t* cpentry = rw_keyspec_entry_create_dup_of_type(
path_entry, instance, entry_ypbmd->pbc_mdesc);
return cpentry;
}
/*
* Gets the Field description and Value
* pointer from the Path entry
*/
static bool get_key_finfo_by_index(
const rw_keyspec_entry_t* path_entry,
uint32_t key_index,
ProtobufCFieldInfo* finfo)
{
RW_ASSERT(path_entry);
bool retval = false;
size_t off = 0;
void* key_ptr = nullptr;
protobuf_c_boolean is_dptr = false;
const ProtobufCFieldDescriptor* fd = nullptr;
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
&path_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+key_index,
&fd, &key_ptr, &off, &is_dptr);
if (!count) {
return retval;
}
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(key_ptr);
ProtobufCMessage *key = (ProtobufCMessage *)key_ptr;
// ATTN: Change this when the option string_key is removed
// from the actual key entries.
if (key->descriptor->n_fields == 2) {
fd = &key->descriptor->fields[1];
} else {
// Generic path-entry. This is just a place-holder.
// We cannot extract the keys anyway even if they are present in the
// unknown list.
// ATTN: We should try to compare serialized data
// against keys that are also serialized data.
//*odesc = &key->descriptor->fields[0];
return false;
}
auto found_key = protobuf_c_message_get_field_instance(
NULL, key, fd, 0, finfo );
return found_key;
}
/*
* Gets the string value of the key.
*/
static bool get_key_string_from_path_entry(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry,
uint32_t key_index,
char *key_str,
size_t *key_len)
{
RW_ASSERT(path_entry);
bool retval = false;
const ProtobufCFieldDescriptor* fd = nullptr;
const ProtobufCFieldDescriptor* kfd = nullptr;
void *key_ptr = nullptr;
size_t off = 0;
protobuf_c_boolean is_dptr = false;
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
&path_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+key_index,
&fd, &key_ptr, &off, &is_dptr);
if (!count) {
return retval;
}
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
RW_ASSERT(key_ptr);
ProtobufCMessage *key = (ProtobufCMessage *)key_ptr;
// ATTN: Change this when the option string_key is removed
// from the actual key entries.
if (key->descriptor->n_fields == 2) {
kfd = &key->descriptor->fields[1];
} else {
// Generic path-entry. This is just a place-holder.
// We cannot extract the keys anyway even if they are present in the
// unknown list.
kfd = &key->descriptor->fields[0];
}
RW_ASSERT(kfd);
count = protobuf_c_message_get_field_count_and_offset(
key, kfd, &key_ptr, &off, &is_dptr);
if (count) {
retval = protobuf_c_field_get_text_value(
instance->pbc_instance, kfd, key_str, key_len, key_ptr);
}
return retval;
}
static bool rw_keyspec_entry_has_wildcards(
const rw_keyspec_entry_t *path_entry)
{
RW_ASSERT(is_good_pe(path_entry));
uint32_t num_keys = rw_keyspec_entry_num_keys(path_entry);
for (unsigned i = 0; i < num_keys; i++) {
if (!rw_keyspec_entry_has_key(path_entry, i)) {
return true;
}
}
return false;
}
static rw_status_t path_entry_copy_keys_to_msg(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry,
ProtobufCMessage *msg)
{
RW_ASSERT(msg);
RW_ASSERT(is_good_pe(path_entry));
rw_status_t status = RW_STATUS_FAILURE;
UniquePtrKeySpecEntry::uptr_t uptr(nullptr, instance);
if (IS_PATH_ENTRY_GENERIC(path_entry)) {
rw_keyspec_entry_t* cpe = convert_generic_pe_to_concerete(
instance, path_entry, msg->descriptor->ypbc_mdesc);
if (!cpe) {
return status;
}
uptr.reset(cpe);
path_entry = uptr.get();
}
uint32_t num_keys = rw_keyspec_entry_num_keys(path_entry);
for (unsigned i = 0; i < num_keys; i++) {
if (!rw_keyspec_entry_has_key(path_entry, i)) {
continue;
}
ProtobufCMessage* keym = rw_keyspec_entry_get_key(path_entry, i);
RW_ASSERT(keym);
RW_ASSERT(keym->descriptor->n_fields == 2); // ATTN: This should be fixed when the implementation changes
ProtobufCFieldInfo field = {};
protobuf_c_boolean ok = protobuf_c_message_get_field_instance(
instance->pbc_instance, keym, &keym->descriptor->fields[1], 0, &field);
RW_ASSERT(ok);
field.fdesc = protobuf_c_message_descriptor_get_field(
msg->descriptor, keym->descriptor->fields[1].id);
RW_ASSERT(field.fdesc);
ok = protobuf_c_message_set_field(instance->pbc_instance, msg, &field);
if (!ok) {
return status;
}
}
return RW_STATUS_SUCCESS;
}
#define KEY_STR_LEN 512
/*
* Given a path_entry in the keyspec
* and its corresponding protobuf message
* this functions checks whether the keys are
* equal in both.
*/
static bool compare_path_entry_and_message(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry,
const ProtobufCMessage *msg,
bool match_wc)
{
RW_ASSERT(path_entry);
RW_ASSERT(msg);
bool retval = false;
unsigned i = 0;
const rw_yang_pb_msgdesc_t *ypbc_md = msg->descriptor->ypbc_mdesc;
rw_keyspec_entry_t *conc_pe = NULL;
RW_ASSERT(ypbc_md);
if (IS_PATH_ENTRY_GENERIC(path_entry)) {
/* If this was a generic keyspec (generic pathentry), try
converting it to concerete pathentry using the schema. This is
required to compare key values. */
conc_pe = convert_generic_pe_to_concerete(instance, path_entry, ypbc_md);
if (conc_pe) {
path_entry = conc_pe;
}
}
auto num_keys = rw_keyspec_entry_num_keys(path_entry);
for(i = 0; i < num_keys; i++) {
ProtobufCFieldInfo key_finfo;
bool rc = get_key_finfo_by_index(path_entry, i, &key_finfo);
if (!rc) {
if (!match_wc) {
break;
}
continue;
}
auto key_tag = get_key_tag_from_path_entry_desc(
ypbc_md->schema_entry_value, i);
RW_ASSERT(key_tag);
auto fd = protobuf_c_message_descriptor_get_field( msg->descriptor, key_tag );
if (!fd) {
break;
}
ProtobufCFieldInfo msg_finfo;
auto found_key = protobuf_c_message_get_field_instance(
instance->pbc_instance, msg, fd, 0, &msg_finfo );
if (!found_key) {
break;
}
int cmp = protobuf_c_field_info_compare( &key_finfo, &msg_finfo );
if (cmp != 0) {
break;
}
}
if (i == num_keys) {
retval = true;
}
if (conc_pe) {
protobuf_c_message_free_unpacked(instance->pbc_instance, &conc_pe->base);
}
return (retval);
}
const ProtobufCMessage* keyspec_find_deeper(
rw_keyspec_instance_t* instance,
size_t depth_i,
const ProtobufCMessage *in_msg,
KeySpecHelper& ks_o,
size_t depth_o)
{
const ProtobufCFieldDescriptor *fd = nullptr;
const ProtobufCMessage *final_msg = nullptr;
const ProtobufCMessage *out_msg = nullptr;
void *msg_ptr = nullptr;
protobuf_c_boolean is_dptr = false;
size_t off = 0;
size_t index = depth_i;
final_msg = in_msg;
while (index < depth_o) {
auto path_entry = ks_o.get_path_entry(index);
RW_ASSERT(path_entry);
auto element_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(element_id);
//Get the msg corresponding to this entry.
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
final_msg, element_id->element_tag, &fd, &msg_ptr, &off, &is_dptr);
if (!count) {
break;
}
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
if (is_dptr) {
final_msg = *((ProtobufCMessage **)msg_ptr);
} else {
final_msg = (ProtobufCMessage *)msg_ptr;
}
// Compare keyvalues if any.
if (element_id->element_type > RW_SCHEMA_ELEMENT_TYPE_LISTY_0) {
RW_ASSERT(fd->label == PROTOBUF_C_LABEL_REPEATED);
unsigned i;
for (i = 0; i < count; i++) { //Find the matching message.
if (is_dptr) {
final_msg = *((ProtobufCMessage **)msg_ptr + i);
} else {
final_msg = (ProtobufCMessage *)(((char *)msg_ptr + (off * i)));
}
if (compare_path_entry_and_message(instance, path_entry, final_msg, false)) {
break;
}
}
if (i == count) {
// No messages matched.
break;
}
}
index++;
}
if (index == depth_o) {
// return the msg corresponding to the keyspec.
out_msg = final_msg;
}
return out_msg;
}
static ProtobufCMessage* keyspec_reroot_shallower(
rw_keyspec_instance_t *instance,
const rw_yang_pb_schema_t* schema,
KeySpecHelper& ks_i,
size_t depth_i,
const ProtobufCMessage *in_msg,
KeySpecHelper& ks_o,
size_t depth_o)
{
// One of in_msg or schema can be null, but not both
const ProtobufCFieldDescriptor *fd = nullptr;
ProtobufCMessage *final_msg = nullptr;
ProtobufCMessage *out_msg = nullptr;
if ((nullptr == schema) && (nullptr == in_msg)) {
// no way to find a message descriptor
return nullptr;
}
const rw_yang_pb_msgdesc_t* ypbc_msgdesc;
std::stack<const rw_yang_pb_msgdesc_t*> msg_stack;
if (in_msg) {
ypbc_msgdesc = in_msg->descriptor->ypbc_mdesc;
} else {
// Find the specific ks msg descriptor
rw_keyspec_path_t *unused = 0;
rw_status_t rs = rw_keyspec_path_find_msg_desc_schema (
ks_i.get(), instance, schema, &ypbc_msgdesc, &unused);
if (RW_STATUS_SUCCESS != rs) {
return nullptr;
}
RW_ASSERT(RW_YANGPBC_MSG_TYPE_SCHEMA_PATH == ypbc_msgdesc->msg_type);
// The desc of the message to generate is in the union
ypbc_msgdesc = (const rw_yang_pb_msgdesc_t*)ypbc_msgdesc->u;
// This descriptor needs to be in the stack as well
// Push it in now, so that the rest of the code is generic
msg_stack.push (ypbc_msgdesc);
}
RW_ASSERT(ypbc_msgdesc);
size_t shallow_d = (depth_i - depth_o);
for (unsigned i = shallow_d; i > 0; i--) {
if (ypbc_msgdesc->parent) {
ypbc_msgdesc = ypbc_msgdesc->parent;
} else {
RW_ASSERT(i == 1);
RW_ASSERT(ks_o.is_module_root());
ypbc_msgdesc = rw_yang_pb_get_module_root_msgdesc(ypbc_msgdesc);
}
RW_ASSERT(ypbc_msgdesc);
msg_stack.push(ypbc_msgdesc);
}
RW_ASSERT(!msg_stack.empty());
size_t index = depth_o - 1;
ProtobufCMessage *temp_msg = nullptr;
while (!msg_stack.empty()) {
ypbc_msgdesc = msg_stack.top();
msg_stack.pop();
if (!final_msg) { // The message that the out_ks corresponds to.
final_msg = (ProtobufCMessage *)malloc(ypbc_msgdesc->pbc_mdesc->sizeof_message);
RW_ASSERT(final_msg);
protobuf_c_message_init(ypbc_msgdesc->pbc_mdesc, final_msg);
temp_msg = final_msg;
} else {
fd = protobuf_c_message_descriptor_get_field(
temp_msg->descriptor, ypbc_msgdesc->pb_element_tag);
RW_ASSERT(fd);
// This function will internally initialize the sub message.
ProtobufCMessage *inner_msg = nullptr;
protobuf_c_message_set_field_message(
instance->pbc_instance, temp_msg, fd, &inner_msg);
RW_ASSERT(inner_msg);
temp_msg = inner_msg;
}
// Populate the keyvalues if any from the in keyspec.
auto path_entry = ks_i.get_path_entry(index++);
if (path_entry) {
if (rw_keyspec_entry_num_keys(path_entry)) {
rw_status_t s = path_entry_copy_keys_to_msg(instance, path_entry, temp_msg);
RW_ASSERT(s == RW_STATUS_SUCCESS);
}
}
}
// Finally copy the in_msg into the new_message.
if (in_msg) {
fd = protobuf_c_message_descriptor_get_field(
temp_msg->descriptor, in_msg->descriptor->ypbc_mdesc->pb_element_tag);
RW_ASSERT(fd);
ProtobufCMessage *inner_msg = nullptr;
protobuf_c_message_set_field_message(instance->pbc_instance, temp_msg, fd, &inner_msg);
RW_ASSERT(inner_msg);
protobuf_c_message_copy_usebody(instance->pbc_instance, in_msg, inner_msg);
}
out_msg = final_msg;
return out_msg;
}
ProtobufCMessage* rw_keyspec_path_schema_reroot(
const rw_keyspec_path_t *in_k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema,
const rw_keyspec_path_t *out_k)
{
RW_ASSERT(is_good_ks(in_k));
RW_ASSERT(schema);
RW_ASSERT(is_good_ks(out_k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, reroot);
ProtobufCMessage *out_msg = nullptr;
KeySpecHelper ks_i(in_k);
KeySpecHelper ks_o(out_k);
size_t depth_i = ks_i.get_depth();
size_t depth_o = ks_o.get_depth();
if (!depth_i || !depth_o) {
return nullptr;
}
if (depth_i < depth_o) {
// The new keyspec is deeper. There is no deeper message, since there is no in msg
return nullptr;
}
// Check whether the keyspecs are for the same schema with varying depths.
if (!rw_keyspec_path_is_prefix_match_impl(instance, ks_i, ks_o, depth_i, depth_o)) {
KEYSPEC_ERROR(instance, in_k, out_k, "Keyspecs are not prefix match");
return nullptr;
}
out_msg = keyspec_reroot_shallower(
instance, schema, ks_i, depth_i, nullptr, ks_o, depth_o);
return out_msg;
}
ProtobufCMessage* rw_keyspec_path_reroot(
const rw_keyspec_path_t *in_k,
rw_keyspec_instance_t* instance,
const ProtobufCMessage *in_msg,
const rw_keyspec_path_t *out_k)
{
ProtobufCMessage *out_msg = nullptr;
RW_ASSERT(is_good_ks(in_k));
RW_ASSERT(is_good_ks(out_k));
RW_ASSERT(in_msg);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, reroot);
KeySpecHelper ks_i(in_k);
KeySpecHelper ks_o(out_k);
// Assertion to check that the in_ks is not wildcarded..
RW_ASSERT(!ks_i.has_wildcards());
size_t depth_i = ks_i.get_depth();
size_t depth_o = ks_o.get_depth();
// Check whether the keyspecs are for the same schema with varying depths.
if (!rw_keyspec_path_is_prefix_match_impl(instance, ks_i, ks_o, depth_i, depth_o)) {
KEYSPEC_ERROR(instance, in_k, out_k, "Keyspecs are not prefix match");
return out_msg;
}
if (depth_i == depth_o) {
return protobuf_c_message_duplicate(
instance->pbc_instance, in_msg, in_msg->descriptor);
}
if (depth_i < depth_o) {
// The new keyspec is deeper. Extract the message corresponding to the
// keyspec from the original message.
const ProtobufCMessage *target =
keyspec_find_deeper(instance, depth_i, in_msg, ks_o, depth_o);
if (target) {
out_msg = protobuf_c_message_duplicate(
instance->pbc_instance, target, target->descriptor);
}
}
else {
// The new keyspec is shallower than the original message.
// Create a new message.
out_msg = keyspec_reroot_shallower(
instance, nullptr, ks_i, depth_i, in_msg, ks_o, depth_o);
}
return out_msg;
}
static bool add_key_to_path_entry(
rw_keyspec_instance_t* instance,
ProtobufCMessage *path_entry,
unsigned index,
char *key,
size_t key_len)
{
const ProtobufCFieldDescriptor* fd = nullptr;
const ProtobufCFieldDescriptor* key_fd = nullptr;
ProtobufCMessage *key_msg = nullptr;
fd = protobuf_c_message_descriptor_get_field(
path_entry->descriptor, RW_SCHEMA_TAG_ELEMENT_KEY_START+index);
RW_ASSERT(fd);
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
const ProtobufCMessageDescriptor *mdesc = (const ProtobufCMessageDescriptor *)fd->descriptor;
RW_ASSERT(mdesc);
RW_ASSERT(mdesc->n_fields == 2);
key_fd = &mdesc->fields[1];
protobuf_c_message_set_field_message(
instance->pbc_instance, path_entry, fd, &key_msg);
if (!key_msg) {
return false;
}
if (protobuf_c_message_set_field_text_value(
instance->pbc_instance, key_msg, key_fd, key, key_len)) {
return true;
}
return false;
}
rw_keyspec_entry_t* rw_keyspec_entry_create_from_proto(
rw_keyspec_instance_t* instance,
const ProtobufCMessage *msg)
{
const ProtobufCFieldDescriptor *key_fd = nullptr;
RW_ASSERT(msg);
const rw_yang_pb_msgdesc_t *ypbc_msgdesc = msg->descriptor->ypbc_mdesc;
RW_ASSERT(ypbc_msgdesc);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, entry, create_from_proto);
// Clone a path entry message from the global static object.
auto path_entry = (rw_keyspec_entry_t *)protobuf_c_message_duplicate(
instance->pbc_instance, &ypbc_msgdesc->schema_entry_value->base,
ypbc_msgdesc->schema_entry_ypbc_desc->pbc_mdesc);
if (!path_entry) {
return NULL;
}
// Populate key values if any from the message.
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id);
if (elem_id->element_type > RW_SCHEMA_ELEMENT_TYPE_LISTY_0) {
auto num_keys = rw_keyspec_entry_num_keys(path_entry);
for (unsigned i = 0; i < num_keys; i++) {
auto key_tag = get_key_tag_from_path_entry_desc(
ypbc_msgdesc->schema_entry_value, i);
size_t off = 0;
void *key_ptr = nullptr;
protobuf_c_boolean is_dptr = false;
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
msg, key_tag, &key_fd, &key_ptr, &off, &is_dptr);
if (!count) {
// Key not present in the message. What to do??
continue;
}
RW_ASSERT(key_ptr);
char key_str[KEY_STR_LEN];
size_t key_str_len = sizeof(key_str);
// Get the key string from the message.
if (!protobuf_c_field_get_text_value(
instance->pbc_instance, key_fd, key_str, &key_str_len, key_ptr)) {
continue;
}
//copy the key to the pathentry.
if (!key_str_len) {
key_str_len = strlen(key_str);
}
add_key_to_path_entry(instance, &path_entry->base, i, key_str, key_str_len);
}
}
return path_entry;
}
// Used only in this file. If needed expose.
static const char*
get_yang_name_from_pb_name(const ProtobufCMessageDescriptor *mdesc,
const char* pb_fname)
{
const rw_yang_pb_msgdesc_t *ypbc = mdesc->ypbc_mdesc;
if ((nullptr == ypbc) || (nullptr == ypbc->ypbc_flddescs)) {
return nullptr;
}
for (size_t i = 0; i < ypbc->num_fields; i++) {
const rw_yang_pb_flddesc_t *y_desc = &ypbc->ypbc_flddescs[i];
if (!strcmp(y_desc->pbc_fdesc->name, pb_fname)) {
return y_desc->yang_node_name;
}
}
return nullptr;
}
static void print_buffer_add_key_values(
rw_keyspec_instance_t* instance,
std::ostringstream& oss,
const rw_yang_pb_msgdesc_t *ypbc_msgdesc,
const rw_keyspec_entry_t *path_entry)
{
const ProtobufCFieldDescriptor *fd = nullptr;
const ProtobufCMessageDescriptor *kdesc = nullptr;
rw_keyspec_entry_t *con_pe = nullptr;
uint32_t n_keys = rw_keyspec_entry_num_keys(path_entry);
if (IS_PATH_ENTRY_GENERIC(path_entry)) {
// Convert into concerete type to extract key values if any.
con_pe = convert_generic_pe_to_concerete(instance, path_entry, ypbc_msgdesc);
if (!con_pe) {
return;
}
path_entry = con_pe;
}
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
for (unsigned k = 0; k < n_keys; k++) {
fd = protobuf_c_message_descriptor_get_field(
path_entry->base.descriptor, RW_SCHEMA_TAG_ELEMENT_KEY_START+k);
if(!fd) {
break;
}
kdesc = (const ProtobufCMessageDescriptor *)fd->descriptor;
RW_ASSERT(kdesc);
RW_ASSERT(kdesc->n_fields == 2);
char key_str[KEY_STR_LEN];
size_t key_len = KEY_STR_LEN;
bool rc = get_key_string_from_path_entry(instance, path_entry, k, key_str, &key_len);
if (!rc) {
continue; // Dont print wildcarded keys.
}
oss << "[";
if (elem_id->element_type == RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST) {
oss << ".=";
} else {
const char* ynode_name = get_yang_name_from_pb_name(
ypbc_msgdesc->pbc_mdesc, kdesc->fields[1].name);
RW_ASSERT(ynode_name);
oss << ypbc_msgdesc->module->prefix <<":" << ynode_name << "=";
}
oss << "\'" << key_str << "\'";
oss << "]";
}
if (con_pe) {
protobuf_c_message_free_unpacked(instance->pbc_instance, &con_pe->base);
}
return;
}
rw_status_t rw_keyspec_path_deserialize_msg_ks_pair (
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema,
const ProtobufCBinaryData* msg_b,
const ProtobufCBinaryData* keyspec_b,
ProtobufCMessage** msg,
rw_keyspec_path_t** ks)
{
RW_ASSERT(schema);
RW_ASSERT(msg_b);
RW_ASSERT(keyspec_b);
RW_ASSERT(msg);
RW_ASSERT(ks);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
rw_keyspec_path_t *gen_ks = rw_keyspec_path_create_with_binpath_binary_data(
instance, keyspec_b);
if (nullptr == gen_ks) {
return RW_STATUS_FAILURE;
}
rw_status_t rs = rw_keyspec_path_find_spec_ks (gen_ks, instance, schema, ks);
RW_ASSERT(RW_STATUS_SUCCESS == rs);
rw_keyspec_path_free (gen_ks, instance);
gen_ks = nullptr;
ProtobufCMessage *tmp_msg_ptr = (ProtobufCMessage *) *ks;
RW_ASSERT(tmp_msg_ptr);
RW_ASSERT(tmp_msg_ptr->descriptor);
const rw_yang_pb_msgdesc_t* ypbc_desc = tmp_msg_ptr->descriptor->ypbc_mdesc;
RW_ASSERT(ypbc_desc);
RW_ASSERT(RW_YANGPBC_MSG_TYPE_SCHEMA_PATH == ypbc_desc->msg_type);
// Get to the messages message definition
ypbc_desc = (const rw_yang_pb_msgdesc_t* )ypbc_desc->u;
RW_ASSERT(ypbc_desc);
*msg = protobuf_c_message_unpack(
instance->pbc_instance, ypbc_desc->pbc_mdesc, msg_b->len, msg_b->data);
if (nullptr == *msg) {
return RW_STATUS_FAILURE;
}
return RW_STATUS_SUCCESS;
}
static void print_buffer_add_key_values(
rw_keyspec_instance_t* instance,
std::ostringstream& oss,
const rw_keyspec_entry_t *path_entry)
{
const ProtobufCFieldDescriptor *fd = nullptr;
size_t off = 0;
void *key_ptr = nullptr;
protobuf_c_boolean is_dptr = false;
uint32_t n_keys = rw_keyspec_entry_num_keys(path_entry);
oss << "[";
for (unsigned k = 0; k < n_keys; k++) {
char key_str[KEY_STR_LEN];
size_t key_len = KEY_STR_LEN;
bool rc = get_key_string_from_path_entry(instance, path_entry, k, key_str, &key_len);
if (rc) {
if (k) {
oss << ",";
}
oss << "Key" << k+1 << "=" << "\'" << key_str << "\'";
} else {
// Keys can be present in unknown fields for generic keyspecs
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
&path_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+k,
&fd, &key_ptr, &off, &is_dptr);
if (count) {
RW_ASSERT(key_ptr);
ProtobufCMessage *msg = (ProtobufCMessage *)key_ptr;
if (protobuf_c_message_unknown_get_count(msg) > 0) {
if (k) {
oss << ",";
}
auto unkf = protobuf_c_message_unknown_get_index(msg, 0);
RW_ASSERT(unkf);
oss << "Unkey" << k+1 << "=\'Tag:" << unkf->base_.tag << "\'";
}
}
}
}
oss << "]";
}
static bool create_xpath_string_from_ks(
rw_keyspec_instance_t* instance,
KeySpecHelper& ks,
size_t depth,
const rw_yang_pb_schema_t *schema,
std::ostringstream &oss)
{
bool ret_val = false;
if (!depth) {
RW_ASSERT(ks.is_root());
oss << "/";
return true;
}
const rw_yang_pb_module_t *ypbc_module = nullptr;
const rw_yang_pb_msgdesc_t *top_msgdesc = nullptr;
auto path_entry = ks.get_path_entry(0);
RW_ASSERT(path_entry);
auto element_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(element_id);
// find the top level message that the ks corresponds to.
for (unsigned m = 0; m < schema->module_count; m++) {
ypbc_module = schema->modules[m];
auto data_module = ypbc_module->data_module;
if (data_module) {
unsigned i = 0;
for (i = 0; i < data_module->child_msg_count; i++) {
top_msgdesc = data_module->child_msgs[i];
if (top_msgdesc->pb_element_tag == element_id->element_tag) {
break;
}
}
if (i != data_module->child_msg_count) {
break;
}
}
auto rpci_module = ypbc_module->rpci_module;
if (rpci_module) {
unsigned i = 0;
for (i = 0; i < rpci_module->child_msg_count; i++) {
top_msgdesc = rpci_module->child_msgs[i];
if (top_msgdesc->pb_element_tag == element_id->element_tag) {
break;
}
}
if (i != rpci_module->child_msg_count) {
break;
}
}
auto rpco_module = ypbc_module->rpco_module;
if (rpco_module) {
unsigned i = 0;
for (i = 0; i < rpco_module->child_msg_count; i++) {
top_msgdesc = rpco_module->child_msgs[i];
if (top_msgdesc->pb_element_tag == element_id->element_tag) {
break;
}
}
if (i != rpco_module->child_msg_count) {
break;
}
}
auto notif_module = ypbc_module->notif_module;
if (notif_module) {
unsigned i = 0;
for (i = 0; i < notif_module->child_msg_count; i++) {
top_msgdesc = notif_module->child_msgs[i];
if (top_msgdesc->pb_element_tag == element_id->element_tag) {
break;
}
}
if (i != notif_module->child_msg_count) {
break;
}
}
// else try searching other modules.
top_msgdesc = nullptr;
}
if (top_msgdesc) {
size_t index = 1;
oss << "/" << top_msgdesc->module->prefix << ":"
<< top_msgdesc->yang_node_name;
if (element_id->element_type > RW_SCHEMA_ELEMENT_TYPE_LISTY_0) {
// Include key values;
print_buffer_add_key_values(instance, oss, top_msgdesc, path_entry);
}
auto curr_msgdesc = top_msgdesc;
while (index < depth) {
auto path_entry = ks.get_path_entry(index);
RW_ASSERT(path_entry);
auto element_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(element_id);
// Get the child message corresponding to the path entry.
unsigned i;
if (element_id->element_type == RW_SCHEMA_ELEMENT_TYPE_LEAF) {
RW_ASSERT(index == (depth-1));
// Search the yang leaf-nodes.
for (i = 0; curr_msgdesc && i < curr_msgdesc->num_fields; i++) {
if (curr_msgdesc->ypbc_flddescs[i].pbc_fdesc->id
== element_id->element_tag) {
break;
}
}
if (!curr_msgdesc || (i == curr_msgdesc->num_fields)) {
// No leaf node matched. Just op a non-texty entry
oss << "/" << element_id->system_ns_id << ":"
<< element_id->element_tag;
} else {
oss << "/" << curr_msgdesc->ypbc_flddescs[i].module->prefix << ":"
<< curr_msgdesc->ypbc_flddescs[i].yang_node_name;
}
} else {
const rw_yang_pb_msgdesc_t *child_msgdesc = nullptr;
for (i = 0; curr_msgdesc && i < curr_msgdesc->child_msg_count; i++) {
child_msgdesc = curr_msgdesc->child_msgs[i];
if (child_msgdesc->pb_element_tag == element_id->element_tag) {
break;
}
}
// No child message matched this path_entry.
if (!curr_msgdesc || (i == curr_msgdesc->child_msg_count)) {
oss << "/" << element_id->system_ns_id << ":"
<< element_id->element_tag;
if (rw_keyspec_entry_num_keys(path_entry)) {
print_buffer_add_key_values(instance, oss, path_entry);
}
curr_msgdesc = nullptr;
} else {
oss << "/" << child_msgdesc->module->prefix << ":"
<< child_msgdesc->yang_node_name;
if (rw_keyspec_entry_num_keys(path_entry)) {
// Include key values.
print_buffer_add_key_values(instance, oss, child_msgdesc, path_entry);
}
curr_msgdesc = child_msgdesc;
}
}
index++;
}
if (index == depth) {
// Perfect.
ret_val = true;
}
}
return ret_val;
}
static std::string generate_ks_print_buffer_from_schema(
rw_keyspec_instance_t* instance,
KeySpecHelper& ks,
const rw_yang_pb_schema_t *schema)
{
std::ostringstream oss;
bool is_rooted = ks.is_rooted();
// Let us not try walking the schema for an unrooted keyspec.
if (!is_rooted) {
return oss.str();
}
RwSchemaCategory cat = ks.get_category();
switch(cat) {
case RW_SCHEMA_CATEGORY_DATA:
oss << "D,";
break;
case RW_SCHEMA_CATEGORY_CONFIG:
oss << "C,";
break;
case RW_SCHEMA_CATEGORY_RPC_INPUT:
oss << "I,";
break;
case RW_SCHEMA_CATEGORY_RPC_OUTPUT:
oss << "O,";
break;
case RW_SCHEMA_CATEGORY_NOTIFICATION:
oss << "N,";
break;
case RW_SCHEMA_CATEGORY_ANY:
default:
oss << "A,";
}
size_t depth = ks.get_depth();
if (!create_xpath_string_from_ks(instance, ks, depth, schema, oss)) {
return std::string();
}
return oss.str();
}
static std::string generate_ks_print_buffer_raw(
rw_keyspec_instance_t* instance,
KeySpecHelper& ks)
{
// Try normal plain printing of keyspec.
std::ostringstream oss;
bool is_rooted = ks.is_rooted();
size_t depth = ks.get_depth();
if (!depth) {
RW_ASSERT(ks.is_root());
}
// Output category
RwSchemaCategory cat = ks.get_category();
switch(cat) {
case RW_SCHEMA_CATEGORY_DATA:
oss << "D,";
break;
case RW_SCHEMA_CATEGORY_CONFIG:
oss << "C,";
break;
case RW_SCHEMA_CATEGORY_RPC_INPUT:
oss << "I,";
break;
case RW_SCHEMA_CATEGORY_RPC_OUTPUT:
oss << "O,";
break;
case RW_SCHEMA_CATEGORY_NOTIFICATION:
oss << "N,";
break;
case RW_SCHEMA_CATEGORY_ANY:
default:
oss << "A,";
}
if (is_rooted) {
oss << "/";
}
for (unsigned i = 0; i < depth; i++) {
auto path_entry = ks.get_path_entry(i);
RW_ASSERT(path_entry);
auto element_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(element_id);
oss << element_id->system_ns_id << ":" << element_id->element_tag;
if (rw_keyspec_entry_num_keys(path_entry)) {
print_buffer_add_key_values(instance, oss, path_entry);
}
if (i != (depth-1)) {
oss << "/";
}
}
return oss.str();
}
static void ltruncate_keystr(const char* keystr, char *buf, int buflen)
{
int src_len = strlen(keystr);
int src_pos = 0;
// buflen should be atleast 3
// Skip first 2 chars
*buf++ = keystr[0];
*buf++ = keystr[1];
buflen -= 2;
if (keystr[2] == '/') {
// Rooted, copy the / too
*buf++ = keystr[2];
buflen--;
}
// Calculate the truncation positions
// reserve 3 for '...' and 1 for null
if (buflen < 4) {
// Not enough buffer, return only the first few
*buf = '\0';
return;
}
strcpy(buf, "...");
buf += 3;
buflen -= 3;
src_pos = src_len - buflen + 1;
memcpy(buf, keystr + src_pos, buflen - 1);
buf[buflen-1] = '\0';
}
int rw_keyspec_path_get_print_buffer(
const rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t *schema,
char *buf,
size_t buflen)
{
int ret_val = -1;
RW_ASSERT(k);
RW_ASSERT(buf);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, get_print_buff);
// Perform sanity checks.
if (!buflen) {
return ret_val;
}
if (buflen < 3) {
return ret_val;
}
if (!schema) {
auto ypbc_msgdesc = k->base.descriptor->ypbc_mdesc;
if (ypbc_msgdesc) {
RW_ASSERT(ypbc_msgdesc->module);
schema = ypbc_msgdesc->module->schema;
}
}
KeySpecHelper ks(k);
// Check if the str_path of the keyspec is present.
if (ks.has_strpath()) {
const char *strpath = ks.get_strpath();
size_t len = strlen(strpath);
if (len < (buflen - 1)) {
memcpy(buf, strpath, len);
buf[len] = '\0';
ret_val = len;
} else {
memcpy(buf, strpath, (buflen-1));
buf[(buflen-1)] = '\0';
ret_val = buflen-1;
}
return ret_val;
}
// If we have schema, then generate a better readable print buffer.
std::string keystr;
if (schema) {
keystr = generate_ks_print_buffer_from_schema(instance, ks, schema);
}
if (keystr.empty()) {
// Try a normal plain print
keystr = generate_ks_print_buffer_raw(instance, ks);
}
if (keystr.empty()) {
// Both methods failed
return -1;
}
size_t len = keystr.size();
if (len < buflen) {
memcpy(buf, keystr.c_str(), len);
buf[len] = '\0';
ret_val = len;
} else {
memcpy(buf, keystr.c_str(), buflen - 1);
buf[buflen - 1] = '\0';
ret_val = buflen - 1;
}
return ret_val;
}
int rw_keyspec_path_get_print_buffer_ltruncate(
const rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t *schema,
char *buf,
size_t buflen)
{
int ret_val = -1;
RW_ASSERT(k);
RW_ASSERT(buf);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, get_print_buff);
// Perform sanity checks.
if (!buflen) {
return ret_val;
}
if (buflen < 3) {
return ret_val;
}
if (!schema) {
auto ypbc_msgdesc = k->base.descriptor->ypbc_mdesc;
if (ypbc_msgdesc) {
RW_ASSERT(ypbc_msgdesc->module);
schema = ypbc_msgdesc->module->schema;
}
}
KeySpecHelper ks(k);
// Check if the str_path of the keyspec is present.
if (ks.has_strpath()) {
const char *strpath = ks.get_strpath();
size_t len = strlen(strpath);
if (len < (buflen - 1)) {
memcpy(buf, strpath, len);
buf[len] = '\0';
ret_val = len;
} else {
ltruncate_keystr(strpath, buf, buflen);
ret_val = strlen(buf);
}
return ret_val;
}
// If we have schema, then generate a better readable print buffer.
std::string keystr;
if (schema) {
keystr = generate_ks_print_buffer_from_schema(instance, ks, schema);
}
if (keystr.empty()) {
// Try a normal plain print
keystr = generate_ks_print_buffer_raw(instance, ks);
}
if (keystr.empty()) {
// Both methods failed
return -1;
}
size_t len = keystr.size();
if (len < buflen) {
memcpy(buf, keystr.c_str(), len);
buf[len] = '\0';
ret_val = len;
} else {
ltruncate_keystr(keystr.c_str(), buf, buflen);
ret_val = strlen(buf);
}
return ret_val;
}
int rw_keyspec_path_get_new_print_buffer(
const rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t *schema,
char **buf)
{
int ret_val = -1;
RW_ASSERT(k);
RW_ASSERT(buf);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, get_print_buff);
*buf = NULL;
if (!schema) {
auto ypbc_msgdesc = k->base.descriptor->ypbc_mdesc;
if (ypbc_msgdesc) {
RW_ASSERT(ypbc_msgdesc->module);
schema = ypbc_msgdesc->module->schema;
}
}
KeySpecHelper ks(k);
// Check if the str_path of the keyspec is present.
if (ks.has_strpath()) {
const char *strpath = ks.get_strpath();
ret_val = strlen(strpath);
*buf = strdup(strpath);
return ret_val;
}
// If we have schema, then generate a better readable print buffer.
std::string keystr;
if (schema) {
keystr = generate_ks_print_buffer_from_schema(instance, ks, schema);
}
if (keystr.empty()) {
// Try a normal plain print
keystr = generate_ks_print_buffer_raw(instance, ks);
}
if (keystr.empty()) {
// Both methods failed
return -1;
}
ret_val = keystr.size();
*buf = strdup(keystr.c_str());
return ret_val;
}
rw_status_t rw_keyspec_path_get_strpath(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema,
const char** str_path)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(k);
RW_ASSERT(!*str_path);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
if (!ks.has_strpath()) {
if (rw_keyspec_path_update_strpath(k, instance, schema) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_strpath());
*str_path = ks.get_strpath();
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_path_update_strpath(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(is_good_ks(k));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
if (ks.has_strpath()) {
if (rw_keyspec_path_delete_strpath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
char *str_buf = NULL;
int len = rw_keyspec_path_get_new_print_buffer(k, instance, schema, &str_buf);
if (len == -1) {
return status;
}
auto str_fd = protobuf_c_message_descriptor_get_field(
k->base.descriptor, RW_SCHEMA_TAG_KEYSPEC_STRPATH);
RW_ASSERT(str_fd);
protobuf_c_boolean ok = protobuf_c_message_set_field_text_value(
instance->pbc_instance, &k->base, str_fd, str_buf, len);
free(str_buf);
if (!ok) {
return status;
}
return RW_STATUS_SUCCESS;
}
static int rw_keyspec_path_get_common_prefix_index(
rw_keyspec_instance_t* instance,
KeySpecHelper& ks1,
KeySpecHelper& ks2,
size_t depth_1,
size_t depth_2)
{
int index = -1;
if (!depth_1 || !depth_2) {
return index;
}
size_t min_depth = (depth_1 < depth_2) ? depth_1 : depth_2;
for (index = 0; index < (int)min_depth; index++) {
auto path_entry1 = ks1.get_path_entry(index);
RW_ASSERT(path_entry1);
auto path_entry2 = ks2.get_path_entry(index);
RW_ASSERT(path_entry2);
switch (get_path_entry_type(instance, path_entry1)) {
case PE_CONTAINER:
case PE_LISTY_WITH_ALL_KEYS:
break;
case PE_LISTY_WITH_ALL_WC:
case PE_LISTY_WITH_WC_AND_KEYS:
goto ret;
default:
RW_ASSERT_NOT_REACHED();
}
switch (get_path_entry_type(instance, path_entry2)){
case PE_CONTAINER:
case PE_LISTY_WITH_ALL_KEYS:
break;
case PE_LISTY_WITH_ALL_WC:
case PE_LISTY_WITH_WC_AND_KEYS:
goto ret;
default:
RW_ASSERT_NOT_REACHED();
}
if (!protobuf_c_message_is_equal_deep(
instance->pbc_instance, &path_entry1->base, &path_entry2->base)) {
break;
}
}
ret:
index -= 1;
return index;
}
static rw_keyspec_path_t* create_parent_keyspec(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *ks,
const ProtobufCMessage *msg,
size_t parent_index)
{
const rw_yang_pb_msgdesc_t* current = nullptr;
current = msg->descriptor->ypbc_mdesc;
RW_ASSERT(current);
for (unsigned i = 0; i < parent_index; i++) {
current = current->parent;
RW_ASSERT(current);
}
// The Generic path entry and the unknown's will be deleted.
rw_keyspec_path_t *out_ks = rw_keyspec_path_create_dup_of_type_trunc(
ks, instance, current->schema_path_ypbc_desc->pbc_mdesc);
return (out_ks);
}
static rw_status_t path_entry_copy_keys(
rw_keyspec_instance_t* instance,
const ProtobufCMessage *msg,
rw_keyspec_entry_t *path_entry)
{
RW_ASSERT(msg);
RW_ASSERT(path_entry);
// Need to convert generic ks into concrete for this function to work
UniquePtrProtobufCMessage<rw_keyspec_entry_t>::uptr_t path_entry_temp;
rw_keyspec_entry_t* path_entry_save = path_entry;
const ProtobufCMessageDescriptor *path_entry_mdesc = path_entry->base.descriptor;
if (path_entry_mdesc == &rw_schema_path_entry__concrete_descriptor.base) {
// Convert generic path entry to concrete.
const rw_yang_pb_msgdesc_t* p_ydesc = rw_schema_pbcm_get_entry_msgdesc(
instance, msg, nullptr);
RW_ASSERT(p_ydesc); // the message must be concrete and have schema
RW_ASSERT(p_ydesc->pbc_mdesc);
path_entry_temp.reset(
rw_keyspec_entry_create_dup_of_type(path_entry, instance, p_ydesc->pbc_mdesc) );
path_entry = path_entry_temp.get();
}
rw_status_t status = RW_STATUS_SUCCESS;
uint32_t n_keys = rw_keyspec_entry_num_keys(path_entry);
for (unsigned i = 0; i < n_keys; i++) {
const ProtobufCFieldDescriptor *p_kfd = nullptr;
ProtobufCMessage *p_keym = nullptr;
protobuf_c_boolean is_dptr = false;
size_t off = 0;
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
&path_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+i,
&p_kfd, (void **)&p_keym, &off, &is_dptr);
if (count) {
continue;
}
RW_ASSERT(p_kfd);
protobuf_c_message_set_field_message(
instance->pbc_instance, &path_entry->base, p_kfd, &p_keym);
RW_ASSERT(p_keym);
const ProtobufCMessageDescriptor *p_kmdesc = p_kfd->msg_desc;
RW_ASSERT(p_kmdesc);
RW_ASSERT(p_kmdesc->n_fields == 2);
uint32_t key_tag = p_kmdesc->fields[1].id; // ATTN: This is bogus - we cannot assume the index here!
void *m_keyp = nullptr;
const ProtobufCFieldDescriptor *m_kfd = nullptr;
count = protobuf_c_message_get_field_desc_count_and_offset(msg,
key_tag, &m_kfd, &m_keyp, &off, &is_dptr);
RW_ASSERT(count);
char m_key[1024];
size_t m_key_len = sizeof(m_key);
bool ret = protobuf_c_field_get_text_value(
instance->pbc_instance, m_kfd, m_key, &m_key_len, m_keyp);
if (!ret) {
return RW_STATUS_FAILURE;
}
protobuf_c_boolean ok = protobuf_c_message_set_field_text_value(
instance->pbc_instance, p_keym, &p_kmdesc->fields[1], m_key, m_key_len);
if (!ok) {
return RW_STATUS_FAILURE;
}
}
if ( RW_STATUS_SUCCESS == status
&& path_entry_save != path_entry) {
protobuf_c_message_free_unpacked_usebody(instance->pbc_instance, &path_entry_save->base);
// Here the path-entry that we freed is generic, so it is fine to call init.
protobuf_c_message_init(path_entry_mdesc, &path_entry_save->base);
protobuf_c_boolean ok = protobuf_c_message_copy_usebody(
instance->pbc_instance, &path_entry->base, &path_entry_save->base);
if (!ok) {
status = RW_STATUS_FAILURE;
}
}
return status;
}
static rw_status_t path_entry_copy_keys(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t* in_entry,
rw_keyspec_entry_t* out_entry)
{
rw_status_t status = RW_STATUS_SUCCESS;
const ProtobufCFieldDescriptor *p_kfd1 = NULL;
const ProtobufCFieldDescriptor *p_kfd2 = NULL;
void *p_keym = NULL;
size_t off = 0;
protobuf_c_boolean is_dptr = false;
RW_ASSERT(in_entry);
RW_ASSERT(out_entry);
uint32_t n_keys = rw_keyspec_entry_num_keys(in_entry);
for (unsigned i = 0; i < n_keys; i++) {
size_t count = protobuf_c_message_get_field_desc_count_and_offset(
&out_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+i, &p_kfd1,
(void **)&p_keym, &off, &is_dptr);
if (count) {
continue; // This key is already present. Dont overwrite it.
}
count = protobuf_c_message_get_field_desc_count_and_offset(
&in_entry->base, RW_SCHEMA_TAG_ELEMENT_KEY_START+i, &p_kfd2,
(void **)&p_keym, &off, &is_dptr);
if (!count) {
continue; // No key in in_entry.
}
RW_ASSERT(p_keym);
ProtobufCMessage *inner_msg = nullptr;
auto ok = protobuf_c_message_set_field_message(
instance->pbc_instance, &out_entry->base, p_kfd1, &inner_msg);
RW_ASSERT(ok);
ok = protobuf_c_message_copy_usebody(
instance->pbc_instance, (ProtobufCMessage *)p_keym, inner_msg);
RW_ASSERT(ok);
}
return status;
}
static rw_status_t keyspec_copy_keys(
rw_keyspec_instance_t* instance,
KeySpecHelper& in_ks,
KeySpecHelper& out_ks,
size_t depth)
{
rw_status_t status = RW_STATUS_SUCCESS;
for (unsigned i = 0; i < depth; i++) {
auto path_entry1 = in_ks.get_path_entry(i);
RW_ASSERT(path_entry1);
auto path_entry2 = out_ks.get_path_entry(i);
RW_ASSERT(path_entry2);
rw_keyspec_entry_t *path_entry_o = const_cast<rw_keyspec_entry_t *>(path_entry2);
auto element_id = rw_keyspec_entry_get_element_id(path_entry1);
if (element_id->element_type > RW_SCHEMA_ELEMENT_TYPE_LISTY_0) {
status = path_entry_copy_keys(instance, path_entry1, path_entry_o);
}
}
return status;
}
ProtobufCMessage*
rw_keyspec_path_reroot_and_merge(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *k1,
const rw_keyspec_path_t *k2,
const ProtobufCMessage *msg1,
const ProtobufCMessage *msg2,
rw_keyspec_path_t **ks_out)
{
ProtobufCMessage *out_msg = nullptr;
RW_ASSERT(is_good_ks(k1));
RW_ASSERT(is_good_ks(k2));
RW_ASSERT(msg1);
RW_ASSERT(msg2);
RW_ASSERT(!*ks_out);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, reroot_and_merge);
KeySpecHelper ks1(k1);
KeySpecHelper ks2(k2);
size_t depth1 = ks1.get_depth();
size_t depth2 = ks2.get_depth();
int c_prefix_idx =
rw_keyspec_path_get_common_prefix_index(instance, ks1, ks2, depth1, depth2);
if (c_prefix_idx == -1) {
KEYSPEC_ERROR(instance, k1, k2, "No common prefix to reroot");
return out_msg;
}
rw_keyspec_path_t *out_ks =
create_parent_keyspec(instance, ks1.get(), msg1, (depth1-(c_prefix_idx+1)));
RW_ASSERT(out_ks);
if (ks1.get_category() != ks2.get_category()) {
rw_keyspec_path_set_category(out_ks, instance, RW_SCHEMA_CATEGORY_ANY);
}
ProtobufCMessage *rr_msg1 = nullptr;
ProtobufCMessage *rr_msg2 = nullptr;
size_t depth_o = c_prefix_idx+1;
KeySpecHelper ks_o(out_ks);
do {
// Now reroot msg1 and msg2 to out_ks.
if (depth_o < depth1) {
rr_msg1 = keyspec_reroot_shallower(
instance, nullptr, ks1, depth1, msg1, ks_o, depth_o);
if (!rr_msg1) {
KEYSPEC_ERROR(instance, k1, out_ks, "Failed to reroot to shallower depth(%d)", depth_o);
break;
}
} else {
rr_msg1 = (ProtobufCMessage *)msg1;
}
if (depth_o < depth2) {
rr_msg2 = keyspec_reroot_shallower(
instance, nullptr, ks2, depth2, msg2, ks_o, depth_o);
if (!rr_msg2) {
KEYSPEC_ERROR(instance, k2, out_ks, "Failed to reroot to shallower depth(%d)", depth_o);
break;
}
} else {
rr_msg2 = (ProtobufCMessage *)malloc(msg2->descriptor->sizeof_message);
RW_ASSERT(rr_msg2);
protobuf_c_message_init(msg2->descriptor, rr_msg2);
if (!protobuf_c_message_copy_usebody(
instance->pbc_instance, msg2, rr_msg2)) {
break;
}
}
// Now merge the rerooted messages.
protobuf_c_boolean ret = protobuf_c_message_merge_new(
instance->pbc_instance, rr_msg1, rr_msg2);
if (!ret) {
KEYSPEC_ERROR(instance, "Merge failed(%p)", rr_msg1->descriptor);
break;
}
out_msg = rr_msg2;
*ks_out = out_ks;
} while(0);
if (rr_msg1 != msg1) {
protobuf_c_message_free_unpacked(instance->pbc_instance, rr_msg1);
}
if (!out_msg) {
protobuf_c_message_free_unpacked(instance->pbc_instance, rr_msg2);
rw_keyspec_path_free(out_ks, instance);
}
return out_msg;
}
void rw_keyspec_path_reroot_iter_init(
const rw_keyspec_path_t *in_ks,
rw_keyspec_instance_t* instance,
rw_keyspec_path_reroot_iter_state_t *st,
const ProtobufCMessage *in_msg,
const rw_keyspec_path_t *out_ks)
{
RW_ASSERT(is_good_ks(in_ks));
RW_ASSERT(is_good_ks(out_ks));
RW_ASSERT(in_msg);
RW_ASSERT(st);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, reroot_iter);
keyspec_reroot_iter_state_t *state = NULL;
state = (keyspec_reroot_iter_state_t *)st;
state->ks_in = new KeySpecHelper(in_ks);
state->ks_out = new KeySpecHelper(out_ks);
state->in_msg = in_msg;
state->instance = instance;
state->cur_ks = NULL;
state->cur_msg = NULL;
state->depth_i = state->ks_in->get_depth();
state->depth_o = state->ks_out->get_depth();
if (!rw_keyspec_path_is_prefix_match_impl(
instance, *state->ks_in, *state->ks_out, state->depth_i, state->depth_o)) {
KEYSPEC_ERROR(instance, in_ks, out_ks, "Keyspecs are not prefix match");
state->next_state = REROOT_ITER_DONE;
return;
}
state->n_path_ens = 0;
state->is_out_ks_wc = state->ks_out->has_wildcards();
state->ks_has_iter_pes = false;
RW_ASSERT(!state->ks_in->has_wildcards());
unsigned last_iter_idx = UINT_MAX;
unsigned first_iter_idx = UINT_MAX;
// Let us store the details about each path entries in the out ks.
for (unsigned i = state->depth_i; i < state->depth_o; i++) {
auto path_entry = state->ks_out->get_path_entry(i);
RW_ASSERT(path_entry);
// Is this path entry listy?
state->path_entries[state->n_path_ens].is_listy = rw_keyspec_entry_is_listy(path_entry);
if (state->path_entries[state->n_path_ens].is_listy) {
state->path_entries[state->n_path_ens].type = get_path_entry_type(instance, path_entry);
auto pe_type = state->path_entries[state->n_path_ens].type;
RW_ASSERT(pe_type != PE_CONTAINER);
// Iteratable path entries are the ones with wildcards and listy_0
if (pe_type != PE_LISTY_WITH_ALL_KEYS) {
state->path_entries[state->n_path_ens].is_iteratable = true;
} else {
state->path_entries[state->n_path_ens].is_iteratable = false;
}
// Keep track of the first and the last iteratable index.
if (state->path_entries[state->n_path_ens].is_iteratable) {
last_iter_idx = state->n_path_ens;
if (first_iter_idx == UINT_MAX) {
first_iter_idx = state->n_path_ens;
}
}
} else {
state->path_entries[state->n_path_ens].is_iteratable = false;
state->path_entries[state->n_path_ens].type = PE_CONTAINER;
}
state->path_entries[state->n_path_ens].count = 0;
state->path_entries[state->n_path_ens].next_index = 0;
state->path_entries[state->n_path_ens].is_last_iter_index = false;
state->path_entries[state->n_path_ens++].is_first_iter_index = false;
}
// Mark the last iteratable index in the out keyspec.
if (last_iter_idx != UINT_MAX) {
state->path_entries[last_iter_idx].is_last_iter_index = true;
state->ks_has_iter_pes = true;
}
// Mark the first iteratable index in the out keyspec.
if (first_iter_idx != UINT_MAX) {
state->path_entries[first_iter_idx].is_first_iter_index = true;
}
state->next_state = REROOT_ITER_FIRST;
}
static bool bt_and_check_for_iter_end(
keyspec_reroot_iter_state_t *state,
int pe_idx)
{
if (!pe_idx) {
return true;
}
int i;
for (i = pe_idx - 1; i >= 0; i--) {
if (state->path_entries[i].is_iteratable) {
state->path_entries[i].next_index++;
if (state->path_entries[i].next_index < state->path_entries[i].count) {
// We still have not exhausted this level.
return false;
}
// This level is exhausted.
if (state->path_entries[i].is_first_iter_index) { // Top level, cannot iterate anymore
return true;
}
// Not top-level, reset the index and continue going up
state->path_entries[i].next_index = 0;
}
}
return true;
}
#define PREPARE_FOR_ITERATION(state_)\
msg = state_->in_msg; \
pe_idx = 0; \
index = state_->depth_i; \
if (state->cur_ks != nullptr) { \
rw_keyspec_path_free(state->cur_ks, state->instance); \
} \
state->cur_ks = nullptr;\
rw_keyspec_path_create_dup(state->ks_out->get(), state->instance, &state->cur_ks); \
RW_ASSERT(state->cur_ks);\
ks_cur.set(state->cur_ks);\
if (state_->is_out_ks_wc) { \
rw_keyspec_path_delete_binpath(state->cur_ks, state->instance); \
size_t min_depth = (state->depth_i < state->depth_o)?state->depth_i:state->depth_o; \
if (ks_cur.has_wildcards(0, min_depth)) {\
rw_status_t s_ = keyspec_copy_keys(state->instance, *state->ks_in, ks_cur, min_depth);\
RW_ASSERT(s_ == RW_STATUS_SUCCESS); \
}\
}
/* ATTN: This function can be optimized. It does many repeated processing over
the iterations. This can be avoided by stored results from the previous
iterations.
*/
bool rw_keyspec_path_reroot_iter_next(
rw_keyspec_path_reroot_iter_state_t *st)
{
const ProtobufCFieldDescriptor *fd = nullptr;
size_t count = 0, off = 0;
void *msg_ptr = nullptr;
protobuf_c_boolean is_dptr = false;
bool retval = false;
const ProtobufCMessage *msg = nullptr;
size_t index = 0;
int pe_idx = 0;
keyspec_reroot_iter_state_t *state = (keyspec_reroot_iter_state_t *)st;
KEYSPEC_INC_FCALL_STATS(state->instance, path, reroot_iter);
if (state->next_state == REROOT_ITER_DONE) {
rw_keyspec_path_reroot_iter_done(st);
return retval;
}
KeySpecHelper ks_cur(state->cur_ks);
PREPARE_FOR_ITERATION(state);
// Shallower case.
if (index > state->depth_o) {
RW_ASSERT(state->next_state == REROOT_ITER_FIRST);
state->cur_msg = keyspec_reroot_shallower(
state->instance, nullptr, *state->ks_in, state->depth_i,
state->in_msg, *state->ks_out, state->depth_o);
// curr_ks is already setup as part of the macro PREPARE_FOR_ITERATION.
state->next_state = REROOT_ITER_DONE;
if (!state->cur_msg) {
rw_keyspec_path_reroot_iter_done(st);
return false;
}
return true;
}
// Deeper case
while (index < state->depth_o) {
bool exit_wloop = false;
auto path_entry = state->ks_out->get_path_entry(index);
RW_ASSERT(path_entry);
auto path_entry2 = ks_cur.get_path_entry(index);
RW_ASSERT(path_entry2);
auto element_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(element_id);
count = protobuf_c_message_get_field_desc_count_and_offset(msg,
element_id->element_tag, &fd, &msg_ptr, &off, &is_dptr);
if (!count) {
// There is no message for this path entry. Check whether we can continue
// the iteration
if (!bt_and_check_for_iter_end(state, pe_idx)) {
// Start over the iteration again.
PREPARE_FOR_ITERATION(state);
continue;
}
break;
}
RW_ASSERT(fd->type == PROTOBUF_C_TYPE_MESSAGE);
if (is_dptr) {
msg = *((ProtobufCMessage **)msg_ptr);
} else {
msg = (ProtobufCMessage *)msg_ptr;
}
if (element_id->element_type >= RW_SCHEMA_ELEMENT_TYPE_LISTY_0) {
state->path_entries[pe_idx].count = count;
RW_ASSERT(state->path_entries[pe_idx].is_listy);
}
if (state->path_entries[pe_idx].is_listy) {
RW_ASSERT(fd->label == PROTOBUF_C_LABEL_REPEATED);
switch (state->path_entries[pe_idx].type) {
// All the keys are specified.
case PE_LISTY_WITH_ALL_KEYS:
{
unsigned i;
for (i = 0; i < count; i++) {
if (is_dptr) {
msg = *((ProtobufCMessage **)msg_ptr + i);
} else {
msg = (ProtobufCMessage *)(((char *)msg_ptr + (off * i)));
}
if (compare_path_entry_and_message(
state->instance, path_entry, msg, false)) {
break;
}
}
if (i == count) {
// No message matched for the path entry.
if (!bt_and_check_for_iter_end(state, pe_idx)) {
// Start over the iteration again.
PREPARE_FOR_ITERATION(state);
continue;
}
exit_wloop = true;
}
}
break;
case PE_LISTY_WITH_ALL_WC:
{
/* The path_entry is completely wildcarded. */
if (state->path_entries[pe_idx].next_index < state->path_entries[pe_idx].count) {
if (is_dptr) {
msg = *((ProtobufCMessage **)msg_ptr + state->path_entries[pe_idx].next_index);
} else {
msg = (ProtobufCMessage *)(((char *)msg_ptr + (off * state->path_entries[pe_idx].next_index)));
}
path_entry_copy_keys(state->instance, msg, (rw_keyspec_entry_t *)path_entry2);
} else {
// No more messages.
exit_wloop = true;
}
}
break;
case PE_LISTY_WITH_WC_AND_KEYS:
{
/* Only some keys in the path entry are specified.
* Other keys are wildcarded.
*/
unsigned i = state->path_entries[pe_idx].next_index;
while (i < count) {
if (is_dptr) {
msg = *((ProtobufCMessage **)msg_ptr + i);
} else {
msg = (ProtobufCMessage *)(((char *)msg_ptr + (off * i)));
}
if (compare_path_entry_and_message(
state->instance, path_entry, msg, true)) {
break;
}
i++;
}
if (i == count) {
// No message matched for the path entry.
if (!bt_and_check_for_iter_end(state, pe_idx)) {
// Start over the iteration again.
PREPARE_FOR_ITERATION(state);
continue;
}
exit_wloop = true;
} else {
// A message was found.
path_entry_copy_keys(state->instance, msg, const_cast<rw_keyspec_entry_t *>(path_entry2));
state->path_entries[pe_idx].next_index = i;
}
}
break;
default:
RW_ASSERT_NOT_REACHED();
}
}
if (exit_wloop) {
break;
}
index++;
pe_idx++;
}
if (index == state->depth_o) {
state->cur_msg = msg;
if (!state->ks_has_iter_pes) {
RW_ASSERT(state->next_state == REROOT_ITER_FIRST);
state->next_state = REROOT_ITER_DONE;
} else {
// Update indices for next iteration.
for (unsigned i = 0; i < state->n_path_ens; ++i) {
if (state->path_entries[i].is_last_iter_index) {
state->path_entries[i].next_index++;
if (state->path_entries[i].next_index == state->path_entries[i].count) {
if (!state->path_entries[i].is_first_iter_index) {
state->path_entries[i].next_index = 0;
bt_and_check_for_iter_end(state, i); // ignore the return value.
}
}
break;
}
}
state->next_state = REROOT_ITER_NEXT;
}
return true;
}
rw_keyspec_path_reroot_iter_done(st);
return retval;
}
const rw_keyspec_path_t* rw_keyspec_path_reroot_iter_get_ks(
rw_keyspec_path_reroot_iter_state_t *st)
{
keyspec_reroot_iter_state_t *state = (keyspec_reroot_iter_state_t *)st;
RW_ASSERT(state->cur_ks);
return (state->cur_ks);
}
const ProtobufCMessage* rw_keyspec_path_reroot_iter_get_msg(
rw_keyspec_path_reroot_iter_state_t *st)
{
keyspec_reroot_iter_state_t *state = (keyspec_reroot_iter_state_t *)st;
RW_ASSERT(state->cur_msg);
return (state->cur_msg);
}
rw_keyspec_path_t* rw_keyspec_path_reroot_iter_take_ks(
rw_keyspec_path_reroot_iter_state_t *st)
{
keyspec_reroot_iter_state_t *state = (keyspec_reroot_iter_state_t *)st;
RW_ASSERT(state->cur_ks);
rw_keyspec_path_t *out_ks = state->cur_ks;
state->cur_ks = NULL;
return (out_ks);
}
ProtobufCMessage* rw_keyspec_path_reroot_iter_take_msg(
rw_keyspec_path_reroot_iter_state_t *st)
{
keyspec_reroot_iter_state_t *state = (keyspec_reroot_iter_state_t *)st;
RW_ASSERT(state->cur_msg);
ProtobufCMessage *out_msg = nullptr;
if (state->depth_i > state->depth_o) {
// for shallower case, the cur_msg is always a new message.
out_msg = (ProtobufCMessage *)state->cur_msg;
} else {
out_msg = protobuf_c_message_duplicate(
state->instance->pbc_instance, state->cur_msg, state->cur_msg->descriptor);
}
state->cur_msg = NULL;
return (out_msg);
}
void rw_keyspec_path_reroot_iter_done(
rw_keyspec_path_reroot_iter_state_t *st)
{
keyspec_reroot_iter_state_t *state = (keyspec_reroot_iter_state_t *)st;
if (state->cur_ks) {
rw_keyspec_path_free(state->cur_ks, state->instance);
}
if (state->depth_i > state->depth_o) {
// for shallower case, the cur_msg is always a new message.
if (state->cur_msg) {
protobuf_c_message_free_unpacked(
state->instance->pbc_instance, (ProtobufCMessage *)state->cur_msg);
}
}
state->cur_ks = NULL;
state->cur_msg = NULL;
delete state->ks_out;
state->ks_out = NULL;
delete state->ks_in;
state->ks_in = NULL;
state->in_msg = NULL;
state->instance = NULL;
state->next_state = REROOT_ITER_INIT;
}
rw_status_t rw_keyspec_path_add_keys_to_entry(
rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry,
size_t index)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(k);
RW_ASSERT(path_entry);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, add_keys);
KeySpecHelper ks(k);
if (!ks.has_dompath()) {
if (rw_keyspec_path_update_dompath(k, instance) != RW_STATUS_SUCCESS) {
return status;
}
}
RW_ASSERT(ks.has_dompath());
auto ks_path_entry = (rw_keyspec_entry_t *) ks.get_path_entry(index);
if (!ks_path_entry) {
KEYSPEC_ERROR(instance, k, "No path entry at index(%d)", index);
return status;
}
auto elem_id1 = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id1);
auto elem_id2 = rw_keyspec_entry_get_element_id(ks_path_entry);
RW_ASSERT(elem_id2);
if (!IS_SAME_ELEMENT(elem_id1, elem_id2)) {
return status;
}
if (path_entry_copy_keys(
instance, path_entry, ks_path_entry) != RW_STATUS_SUCCESS) {
return status;
}
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_entry_create_dup(
const rw_keyspec_entry_t* input,
rw_keyspec_instance_t* instance,
rw_keyspec_entry_t** output)
{
RW_ASSERT(is_good_pe(input));
RW_ASSERT(output);
RW_ASSERT(!*output);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, entry, create_dup);
// Dup to the same type
ProtobufCMessage* out_msg = dup_and_convert_to_type(
instance, &input->base, input->base.descriptor);
if (out_msg) {
*output = reinterpret_cast<rw_keyspec_entry_t *>(out_msg);
return RW_STATUS_SUCCESS;
}
return RW_STATUS_FAILURE;
}
rw_keyspec_entry_t* rw_keyspec_entry_create_dup_of_type(
const rw_keyspec_entry_t* input,
rw_keyspec_instance_t* instance,
const ProtobufCMessageDescriptor* out_pbcmd)
{
RW_ASSERT(is_good_pe(input));
RW_ASSERT(out_pbcmd);
RW_ASSERT(PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC == out_pbcmd->magic);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, entry, create_dup_type);
// Dup to the other type
ProtobufCMessage* out_msg = dup_and_convert_to_type(
instance, &input->base, out_pbcmd);
if (out_msg) {
return reinterpret_cast<rw_keyspec_entry_t *>(out_msg);
}
return nullptr;
}
rw_status_t rw_keyspec_entry_free(
rw_keyspec_entry_t *path_entry,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(is_good_pe(path_entry));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
protobuf_c_message_free_unpacked(
instance->pbc_instance, &path_entry->base);
return RW_STATUS_SUCCESS;
}
rw_status_t rw_keyspec_entry_free_usebody(
rw_keyspec_entry_t *path_entry,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(is_good_pe(path_entry));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
protobuf_c_message_free_unpacked_usebody(
instance->pbc_instance, &path_entry->base);
return RW_STATUS_SUCCESS;
}
int rw_keyspec_entry_get_print_buffer(
const rw_keyspec_entry_t *path_entry,
rw_keyspec_instance_t* instance,
char *buf,
size_t buflen)
{
RW_ASSERT(is_good_pe(path_entry));
RW_ASSERT(buf);
RW_ASSERT(buflen);
int ret_val = -1;
std::ostringstream oss;
instance = ks_instance_get(instance);
RW_ASSERT(instance);
const rw_yang_pb_msgdesc_t *ypbc = path_entry->base.descriptor->ypbc_mdesc;
const RwSchemaElementId *elem =
rw_keyspec_entry_get_element_id(path_entry);
if (ypbc) {
oss << ypbc->module->module_name << ":";
oss << ypbc->yang_node_name;
} else {
oss << elem->system_ns_id << ":" << elem->element_tag;
}
if (rw_keyspec_entry_num_keys(path_entry)) {
if (ypbc) {
print_buffer_add_key_values(
instance, oss, &ypbc->u->msg_msgdesc, path_entry);
} else {
print_buffer_add_key_values(instance, oss, path_entry);
}
}
std::string out_str = oss.str();
size_t len = out_str.length();
if (len) {
if (len < buflen-1) {
memcpy(buf, out_str.c_str(), len);
buf[len] = 0;
ret_val = len;
} else {
memcpy(buf, out_str.c_str(), buflen-1);
buf[buflen-1] = 0;
ret_val = buflen-1;
}
}
return ret_val;
}
rw_keyspec_entry_t* rw_keyspec_entry_unpack(
rw_keyspec_instance_t* instance,
const ProtobufCMessageDescriptor* mdesc,
uint8_t *data,
size_t len)
{
rw_keyspec_entry_t *path_entry = nullptr;
RW_ASSERT(data);
RW_ASSERT(len);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
ProtobufCMessage *out = nullptr;
if (mdesc) {
out = protobuf_c_message_unpack(instance->pbc_instance, mdesc, len, data);
} else {
// Create a generic path entry.
out = protobuf_c_message_unpack(
instance->pbc_instance, &rw_schema_path_entry__descriptor, len, data);
}
if (out) {
path_entry = reinterpret_cast<rw_keyspec_entry_t *>(out);
}
return path_entry;
}
size_t rw_keyspec_entry_pack(
const rw_keyspec_entry_t* path_entry,
rw_keyspec_instance_t* instance,
uint8_t *buf,
size_t len)
{
size_t ret_len = -1;
RW_ASSERT(path_entry);
RW_ASSERT(buf);
RW_ASSERT(len);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
size_t size = protobuf_c_message_get_packed_size(instance->pbc_instance, &path_entry->base);
if (size > len) {
return ret_len;
}
ret_len = protobuf_c_message_pack(instance->pbc_instance, &path_entry->base, buf);
RW_ASSERT(ret_len == size);
return ret_len;
}
rw_status_t rw_keyspec_path_create_leaf_entry(
rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const rw_yang_pb_msgdesc_t *ypb_mdesc,
const char *leaf)
{
RW_ASSERT(is_good_ks(k));
RW_ASSERT(ypb_mdesc);
RW_ASSERT(leaf);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
rw_status_t status = RW_STATUS_FAILURE;
KeySpecHelper ks(k);
RW_ASSERT(ks.has_dompath());
if (ks.is_leafy()) {
// already refers to leaf??
return status;
}
size_t depth = ks.get_depth();
ProtobufCMessage *dom_path = (ProtobufCMessage *)ks.get_dompath();
auto fd = protobuf_c_message_descriptor_get_field(
dom_path->descriptor, RW_SCHEMA_TAG_PATH_ENTRY_START+depth);
if ((!fd) || (fd->msg_desc != &rw_schema_path_entry__descriptor)) {
return status;
}
auto ypb_fdescs = ypb_mdesc->ypbc_flddescs;
unsigned i = 0;
for (i = 0; i < ypb_mdesc->num_fields; i++) {
if (!strcmp(leaf, ypb_fdescs[i].yang_node_name)) {
break;
}
}
if (i == ypb_mdesc->num_fields) {
return status;
}
ProtobufCMessage* leaf_entry = nullptr;
protobuf_c_message_set_field_message(
instance->pbc_instance, dom_path, fd, &leaf_entry);
RW_ASSERT(leaf_entry);
auto elem = rw_keyspec_entry_get_schema_id(ypb_mdesc->schema_entry_value);
elem.tag = ypb_fdescs[i].pbc_fdesc->id;
RwSchemaPathEntry *pe = (RwSchemaPathEntry *)leaf_entry;
RW_ASSERT(pe);
pe->element_id = (RwSchemaElementId *)malloc(sizeof(RwSchemaElementId));
RW_ASSERT(pe->element_id);
rw_schema_element_id__init(pe->element_id);
if (ypb_fdescs[i].module != ypb_mdesc->module) {
pe->element_id->system_ns_id =
NamespaceManager::get_global().get_ns_hash(ypb_fdescs[i].module->ns); // ATTN:- Should we need to keep the nsid in ypbc module?
} else {
pe->element_id->system_ns_id = elem.ns;
}
pe->element_id->element_tag = elem.tag;
pe->element_id->element_type = RW_SCHEMA_ELEMENT_TYPE_LEAF;
rw_keyspec_path_delete_binpath(k, instance);
rw_keyspec_path_delete_strpath(k, instance);
return RW_STATUS_SUCCESS;
}
const char* rw_keyspec_path_leaf_name(
const rw_keyspec_path_t* k,
rw_keyspec_instance_t* instance,
const ProtobufCMessageDescriptor *pbcmd)
{
RW_ASSERT(is_good_ks(k));
RW_ASSERT(pbcmd);
if (!pbcmd->ypbc_mdesc) {
return NULL;
}
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(k);
size_t depth = ks.get_depth();
if (depth < 2) {
return NULL;
}
const rw_keyspec_entry_t *entry = ks.get_path_entry(depth-1);
const RwSchemaElementId *elem_id =
rw_keyspec_entry_get_element_id(entry);
RW_ASSERT(elem_id);
if (elem_id->element_type != RW_SCHEMA_ELEMENT_TYPE_LEAF) {
KEYSPEC_ERROR(instance, k, "KS is not for leaf(%d)", elem_id->element_type);
return NULL;
}
/* Validations to make sure that correct descriptor has been passed. */
const rw_yang_pb_msgdesc_t* msg_ypbd =
rw_yang_pb_msgdesc_get_msg_msgdesc(pbcmd->ypbc_mdesc);
RW_ASSERT(msg_ypbd);
RW_ASSERT(msg_ypbd->schema_path_value);
KeySpecHelper cks(msg_ypbd->schema_path_value);
size_t depth_c = cks.get_depth();
if (depth != depth_c + 1) {
return NULL;
}
if (!rw_keyspec_path_is_prefix_match_impl(instance, cks, ks, depth_c, depth)) {
KEYSPEC_ERROR(instance, k, "KS and ypbcdesc doesnt match");
return NULL;
}
/* Ok, now check for the leaf node */
auto ypbc_fdescs = msg_ypbd->ypbc_flddescs;
for (unsigned i = 0; i < msg_ypbd->num_fields; i++) {
if (ypbc_fdescs[i].pbc_fdesc->id == elem_id->element_tag) {
return ypbc_fdescs[i].yang_node_name;
}
}
return NULL;
}
rw_keyspec_path_t*
rw_keyspec_path_from_xpath(const rw_yang_pb_schema_t* schema,
const char* xpath,
rw_xpath_type_t xpath_type,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(schema);
RW_ASSERT(xpath);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, from_xpath);
rw_keyspec_path_t* keyspec = nullptr;
if (!strlen(xpath)) {
return keyspec;
}
char cat = 0;
if (xpath[0] != '/') {
if (strlen(xpath) < 3 || xpath[1] != ',') {
return keyspec;
}
cat = xpath[0];
xpath += 2;
}
RwSchemaCategory category = RW_SCHEMA_CATEGORY_ANY;
if (cat != 0) {
switch (cat) {
case 'D':
category = RW_SCHEMA_CATEGORY_DATA;
break;
case 'C':
category = RW_SCHEMA_CATEGORY_CONFIG;
break;
case 'I':
category = RW_SCHEMA_CATEGORY_RPC_INPUT;
break;
case 'O':
category = RW_SCHEMA_CATEGORY_RPC_OUTPUT;
break;
case 'N':
category = RW_SCHEMA_CATEGORY_NOTIFICATION;
break;
case 'A':
break;
default:
KEYSPEC_ERROR(instance, "Invalid category in xpath(%c)", cat);
return nullptr;
}
}
XpathIIParser parser(xpath, xpath_type);
if (!parser.parse_xpath()) {
KEYSPEC_ERROR(instance, "Failed to parse xpath(%s)", xpath);
return keyspec;
}
auto ypbc_mdesc = parser.validate_xpath(schema, category);
if (!ypbc_mdesc) {
KEYSPEC_ERROR(instance, "xpath(%s)-schema validation error", xpath);
return keyspec;
}
rw_status_t s = rw_keyspec_path_create_dup(
ypbc_mdesc->schema_path_value, instance, &keyspec);
RW_ASSERT(s == RW_STATUS_SUCCESS);
RW_ASSERT(keyspec);
UniquePtrKeySpecPath::uptr_t uptr(keyspec);
KeySpecHelper ks(keyspec);
size_t depth = ks.get_depth();
if (depth < parser.get_depth()) {
if (depth + 1 != parser.get_depth()) {
return nullptr;
}
}
for (unsigned i = 0; i < depth; i++) {
auto path_entry = ks.get_path_entry(i);
RW_ASSERT(path_entry);
if (rw_keyspec_entry_num_keys(path_entry)) {
s = parser.populate_keys(
instance, const_cast<rw_keyspec_entry_t*>(path_entry), i);
if (s != RW_STATUS_SUCCESS) {
KEYSPEC_ERROR(instance, "Failed to add keys to xpath(%s)", xpath);
break;
}
}
}
if (s == RW_STATUS_SUCCESS && (depth + 1 == parser.get_depth())) {
// Keypsec for leaf.
s = rw_keyspec_path_create_leaf_entry(
keyspec, instance, ypbc_mdesc, parser.get_leaf_token().c_str());
}
if (s != RW_STATUS_SUCCESS) {
return nullptr;
}
if (cat != 0) {
rw_keyspec_path_set_category(keyspec, instance, category);
}
return uptr.release();
}
char* rw_keyspec_path_to_xpath(
const rw_keyspec_path_t* keyspec,
const rw_yang_pb_schema_t* schema,
rw_keyspec_instance_t* instance)
{
std::ostringstream oss;
char *buf = nullptr;
RW_ASSERT(schema);
RW_ASSERT(keyspec);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks(keyspec);
bool is_rooted = ks.is_rooted();
// Let us not try walking the schema for an unrooted keyspec.
if (!is_rooted) {
return nullptr;
}
size_t depth = ks.get_depth();
if (!create_xpath_string_from_ks(instance, ks, depth, schema, oss)) {
return nullptr;
}
std::string out_str = oss.str();
auto out_len = out_str.length();
buf = (char *)malloc(out_len+1);
RW_ASSERT(buf);
strncpy(buf, out_str.c_str(), out_len);
buf[out_len] = 0;
return buf;
}
static rw_keyspec_path_t* create_lcp_keyspec(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *ks1,
const rw_keyspec_path_t *ks2,
size_t depth1,
size_t depth2,
int lcp_index)
{
rw_keyspec_path_t *out_ks = NULL;
const rw_keyspec_path_t *conc_ks = NULL;
rw_status_t status;
size_t depth = 0;
if (!IS_KEYSPEC_GENERIC(ks1)) {
conc_ks = ks1;
depth = depth1;
} else if (!IS_KEYSPEC_GENERIC(ks2)) {
conc_ks = ks2;
depth = depth2;
}
if (conc_ks != NULL) {
auto ypbc_d = conc_ks->base.descriptor->ypbc_mdesc;
RW_ASSERT(ypbc_d);
for (int i = depth - 1; i > lcp_index; i--) {
ypbc_d = ypbc_d->parent;
RW_ASSERT(ypbc_d);
}
// The Generic path entry and the unknowns will be stripped off.
out_ks = rw_keyspec_path_create_dup_of_type_trunc(
conc_ks, instance, ypbc_d->pbc_mdesc);
} else {
// Both the keyspecs are generic KS. Create a generic out keyspec.
if (depth1 <= depth2) {
status = rw_keyspec_path_create_dup(ks1, instance, &out_ks);
depth = depth1;
} else {
status = rw_keyspec_path_create_dup(ks2, instance, &out_ks);
depth = depth2;
}
if (status == RW_STATUS_SUCCESS) {
for (int i = depth - 1; i > lcp_index; i--) {
status = rw_keyspec_path_trunc_suffix_n(out_ks, instance, i);
if (status != RW_STATUS_SUCCESS) {
rw_keyspec_path_free(out_ks, instance);
out_ks = NULL;
break;
}
}
}
}
if (out_ks) {
rw_keyspec_path_delete_binpath(out_ks, instance);
rw_keyspec_path_delete_strpath(out_ks, instance);
}
return (out_ks);
}
static size_t reroot_opaque_get_packed_msg_size(
rw_keyspec_instance_t* instance,
const ProtobufCBinaryData *msg,
KeySpecHelper& ks,
int curr_index,
int end_index)
{
size_t rv = 0;
if (curr_index == end_index) {
rv += msg->len;
return rv;
}
auto path_entry = ks.get_path_entry(curr_index);
RW_ASSERT(path_entry);
auto elemid = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elemid);
if (rw_keyspec_entry_is_listy(path_entry)) {
int n_keys = rw_keyspec_entry_num_keys(path_entry);
for (int k = 0; k < n_keys; k++) {
ProtobufCMessage *key = rw_keyspec_entry_get_key(path_entry, k);
if (key) {
if (IS_PATH_ENTRY_GENERIC(path_entry)) {
/* For generic keyspec, keys are in the unknown fields list..*/
RW_ASSERT(protobuf_c_message_unknown_get_count(key));
rv += protobuf_c_message_get_unknown_fields_pack_size(key);
} else {
rv += protobuf_c_message_get_packed_size(instance->pbc_instance, key);
}
}
}
}
RW_ASSERT(curr_index+1 <= end_index);
auto path_entry_next = ks.get_path_entry(curr_index+1);
RW_ASSERT(path_entry_next);
auto elemid_next = rw_keyspec_entry_get_element_id(path_entry_next);
RW_ASSERT(elemid_next);
rv += protobuf_c_message_get_tag_size(elemid_next->element_tag);
size_t sub_rv = reroot_opaque_get_packed_msg_size(instance, msg, ks, curr_index + 1, end_index);
RW_ASSERT(sub_rv);
rv += protobuf_c_message_get_uint32_size(sub_rv);
rv += sub_rv;
return rv;
}
static size_t reroot_opaque_create_packed_msg(
rw_keyspec_instance_t* instance,
const ProtobufCBinaryData *msg,
KeySpecHelper& ks,
int curr_index,
int end_index,
uint8_t *out)
{
size_t rv = 0;
if (curr_index == end_index) {
memcpy(out, msg->data, msg->len);
rv += msg->len;
return rv;
}
auto path_entry = ks.get_path_entry(curr_index);
RW_ASSERT(path_entry);
auto elemid = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elemid);
if (rw_keyspec_entry_is_listy(path_entry)) {
int n_keys = rw_keyspec_entry_num_keys(path_entry);
for (int k = 0; k < n_keys; k++) {
ProtobufCMessage *key = rw_keyspec_entry_get_key(path_entry, k);
if (key) {
if (IS_PATH_ENTRY_GENERIC(path_entry)) {
/* Generic keyspec.. Keys are already in unknown list..just combine.. */
RW_ASSERT(protobuf_c_message_unknown_get_count(key));
rv += protobuf_c_message_pack_unknown_fields(instance->pbc_instance, key, out + rv);
} else {
// Conceret keyspec..
rv += protobuf_c_message_pack(instance->pbc_instance, key, out + rv);
}
}
}
}
RW_ASSERT(curr_index+1 <= end_index);
auto next_path_entry = ks.get_path_entry(curr_index+1);
RW_ASSERT(next_path_entry);
auto next_elemid = rw_keyspec_entry_get_element_id(next_path_entry);
RW_ASSERT(next_elemid);
uint8_t *out1 = out + rv;
rv += protobuf_c_message_pack_tag(next_elemid->element_tag, out1);
out1[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED;
out1 = out + rv + 1;
size_t msg_rv = 0;
msg_rv += reroot_opaque_create_packed_msg(instance, msg, ks, curr_index+1, end_index, out1);
RW_ASSERT(msg_rv);
size_t rv_packed_size = protobuf_c_message_get_uint32_size(msg_rv);
if (rv_packed_size != 1) {
rv_packed_size -= 1;
memmove(out1 + rv_packed_size, out1, msg_rv);
}
rv += msg_rv + protobuf_c_message_pack_uint32(msg_rv, out + rv);
return rv;
}
rw_status_t
rw_keyspec_path_reroot_and_merge_opaque(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *k1,
const rw_keyspec_path_t *k2,
const ProtobufCBinaryData *msg1,
const ProtobufCBinaryData *msg2,
rw_keyspec_path_t **ks_out,
ProtobufCBinaryData *msg_out)
{
RW_ASSERT(is_good_ks(k1));
RW_ASSERT(is_good_ks(k2));
RW_ASSERT(msg1);
RW_ASSERT(msg2);
RW_ASSERT(!*ks_out);
RW_ASSERT(msg_out);
RW_ASSERT(!msg_out->data);
rw_status_t status = RW_STATUS_FAILURE;
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, reroot_and_merge_op);
KeySpecHelper ks1(k1);
KeySpecHelper ks2(k2);
size_t depth1 = ks1.get_depth();
size_t depth2 = ks2.get_depth();
/*
* Get least common prefix index. This does an extact match of the
* path entries.
*/
int lcp = rw_keyspec_path_get_common_prefix_index(
instance, ks1, ks2, depth1, depth2);
if (lcp == -1) {
KEYSPEC_ERROR(instance, k1, k2, "No common prefix to merge at");
return status;
}
RW_ASSERT((msg1->len) && (msg1->data));
RW_ASSERT((msg2->len) && (msg2->data));
if ((depth1 == depth2) && ((lcp + 1) == static_cast<int>(depth1))) {
/*
* No re-root is required. Just combine the serialized data and return the
* result
*/
msg_out->len = msg1->len + msg2->len;
msg_out->data = (uint8_t *)malloc(msg_out->len);
RW_ASSERT(msg_out->data);
memcpy(msg_out->data, msg1->data, msg1->len);
memcpy(msg_out->data+msg1->len, msg2->data, msg2->len);
rw_keyspec_path_create_dup(ks1.get(), instance, ks_out);
return (RW_STATUS_SUCCESS);
}
*ks_out = create_lcp_keyspec(instance, k1, k2, depth1, depth2, lcp);
if (!*ks_out) {
return status;
}
size_t rr_size1 = msg1->len;
if (lcp != static_cast<int>(depth1 - 1)) {
rr_size1 = reroot_opaque_get_packed_msg_size(
instance, msg1, ks1, lcp, depth1-1);
RW_ASSERT(rr_size1);
}
size_t rr_size2 = msg2->len;
if (lcp != static_cast<int>(depth2 - 1)) {
rr_size2 = reroot_opaque_get_packed_msg_size(
instance, msg2, ks2, lcp, depth2-1);
RW_ASSERT(rr_size2);
}
msg_out->len = rr_size1 + rr_size2;
msg_out->data = (uint8_t *)RW_MALLOC0(msg_out->len);
RW_ASSERT(msg_out->data);
if (lcp != static_cast<int>(depth1 - 1)) {
size_t ret_sz = reroot_opaque_create_packed_msg(
instance, msg1, ks1, lcp, depth1-1, msg_out->data);
RW_ASSERT(ret_sz == rr_size1);
} else {
memcpy(msg_out->data, msg1->data, rr_size1);
}
if (lcp != static_cast<int>(depth2 - 1)) {
size_t ret_sz = reroot_opaque_create_packed_msg(
instance, msg2, ks2, lcp, depth2-1, msg_out->data + rr_size1);
RW_ASSERT(ret_sz == rr_size2);
} else {
memcpy(msg_out->data + rr_size1, msg2->data, rr_size2);
}
status = RW_STATUS_SUCCESS;
return status;
}
rw_keyspec_path_t * rw_keyspec_path_merge(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *k1,
const rw_keyspec_path_t *k2)
{
rw_keyspec_path_t *out = NULL;
rw_keyspec_path_t *inp = NULL;
RW_ASSERT(is_good_ks(k1));
RW_ASSERT(is_good_ks(k2));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KeySpecHelper ks1(k1);
KeySpecHelper ks2(k2);
size_t depth_1 = ks1.get_depth();
size_t depth_2 = ks2.get_depth();
if (!depth_1 || !depth_2) {
return out;
}
if (!rw_keyspec_path_is_prefix_match_impl(instance, ks1, ks2, depth_1, depth_2)) {
// One or more path elements didnot match for the common depth.
KEYSPEC_ERROR(instance, k1, k2, "Keyspecs are not prefix match");
return out;
}
// For the merge to happen, both the keyspec should be of same type.
// Convert concrete keyspec to generic and do a merge.
inp = (rw_keyspec_path_t *)k1;
if (!ks1.is_generic()) {
inp = rw_keyspec_path_create_dup_of_type(k1, instance, &rw_schema_path_spec__descriptor);
RW_ASSERT(inp);
out = inp;
}
if (!ks2.is_generic()) {
out = rw_keyspec_path_create_dup_of_type(k2, instance, &rw_schema_path_spec__descriptor);
RW_ASSERT(out);
} else {
if (NULL != out) {
inp = (rw_keyspec_path_t *)k2; // To ensure that we always create the minimun number of dups.
}
}
// Out should always be the dupped one, as the original input keyspec should
// not be altered.
if (NULL == out) {
rw_keyspec_path_create_dup(k2, instance, &out);
RW_ASSERT(out);
}
if (!protobuf_c_message_merge_new(instance->pbc_instance, &inp->base, &out->base)) {
rw_keyspec_path_free(out, instance);
out = NULL;
}
if ((inp != k1) && (inp != k2)) {
rw_keyspec_path_free(inp, instance); // Can happen if both the keyspecs are concrete type.
}
return out;
}
static rw_keyspec_entry_t* rw_keyspec_entry_gi_ref(
rw_keyspec_entry_t* pe)
{
rw_keyspec_entry_t* dup_pe = NULL;
rw_status_t rs = rw_keyspec_entry_create_dup(pe, NULL, &dup_pe);
RW_ASSERT(rs == RW_STATUS_SUCCESS);
return dup_pe;
}
static void rw_keyspec_entry_gi_unref(
rw_keyspec_entry_t* pe)
{
rw_status_t rs = rw_keyspec_entry_free(pe, NULL);
RW_ASSERT(rs == RW_STATUS_SUCCESS);
}
G_DEFINE_BOXED_TYPE(
rw_keyspec_entry_t,
rw_keyspec_entry,
rw_keyspec_entry_gi_ref,
rw_keyspec_entry_gi_unref);
static rw_keyspec_path_t* rw_keyspec_path_gi_ref(
rw_keyspec_path_t* ks)
{
rw_keyspec_path_t *out_ks = NULL;
rw_status_t rs = rw_keyspec_path_create_dup(ks, NULL, &out_ks);
RW_ASSERT(rs == RW_STATUS_SUCCESS);
return out_ks;
}
static void rw_keyspec_path_gi_unref(
rw_keyspec_path_t* ks)
{
rw_status_t rs = rw_keyspec_path_free(ks, NULL);
RW_ASSERT(rs == RW_STATUS_SUCCESS);
}
G_DEFINE_BOXED_TYPE(
rw_keyspec_path_t,
rw_keyspec_path,
rw_keyspec_path_gi_ref,
rw_keyspec_path_gi_unref);
G_DEFINE_POINTER_TYPE(rw_keyspec_instance_t,
rw_keyspec_instance)
static const GEnumValue _rw_xpath_type_enum_values[] = {
{ RW_XPATH_KEYSPEC, "KEYSPEC", "KEYSPEC" },
{ RW_XPATH_INSTANCEID, "INSTANCE_ID", "INSTANCE_ID"},
{ 0, NULL, NULL}
};
GType rw_keyspec_xpath_type_get_type(void)
{
static GType type = 0; /* G_TYPE_INVALID */
if (!type) {
type = g_enum_register_static("rw_xpath_type_t", _rw_xpath_type_enum_values);
}
return type;
}
ProtobufCGiMessageBox* rw_keyspec_entry_check_and_create_gi_dup_of_type(
const rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance,
const ProtobufCMessageDescriptor* pbcmd)
{
RW_ASSERT(is_good_ks(k));
RW_ASSERT(pbcmd);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
/*
* Must have a schema-aware protobuf descriptor for this function to
* work, because there needs to be some way to discriminate which
* path entry is desired.
*/
if (nullptr == pbcmd->ypbc_mdesc) {
return nullptr;
}
const rw_yang_pb_msgdesc_t* msg_msgdesc
= rw_yang_pb_msgdesc_get_msg_msgdesc(pbcmd->ypbc_mdesc);
/*
* Compare the keyspec we have (ks) with the keyspec that we want
* (the one associated with msg_msgdesc). Assume the provided
* msgdesc is the message's desc.
*/
RW_ASSERT(msg_msgdesc->schema_path_value);
KeySpecHelper ks(k);
KeySpecHelper ks_c(msg_msgdesc->schema_path_value);
size_t depth_c = ks_c.get_depth();
size_t depth = ks.get_depth();
if (depth_c > depth) {
// Cannot be a prefix match.
return nullptr;
}
if (!rw_keyspec_path_is_prefix_match_impl(instance, ks_c, ks, depth_c, depth)) {
// Not a prefix or match, so cannot create a box.
return nullptr;
}
/*
* The schema location in msg_msgdesc matches with ks. Find the
* corresponding path entry in ks - it might not be the last one in
* ks, but it is the last one in the schema location.
*/
const rw_keyspec_entry_t* pe_orig = ks.get_path_entry(depth_c-1);
RW_ASSERT(pe_orig);
/*
* Create a new concrete path entry message.
*/
const rw_yang_pb_msgdesc_t* pe_msgdesc = msg_msgdesc->schema_entry_ypbc_desc;
RW_ASSERT(pe_msgdesc);
const ProtobufCMessageDescriptor* pe_pbcmd = pe_msgdesc->pbc_mdesc;
RW_ASSERT(pe_pbcmd);
ProtobufCMessage* pe_cc = protobuf_c_message_duplicate(
instance->pbc_instance, &pe_orig->base, pe_pbcmd);
if (!pe_cc) {
// Cound not create it? Maybe there's something wrong with keys or extensions?
return nullptr;
}
/*
* Put the path entry in a box.
*/
const ProtobufCMessageGiDescriptor* pe_pbcgid = pe_pbcmd->gi_descriptor;
RW_ASSERT(pe_pbcgid);
RW_ASSERT(pe_pbcgid->new_adopt);
ProtobufCGiMessageBox* box = (pe_pbcgid->new_adopt)(
pe_cc,
nullptr/*parent*/,
nullptr/*parent_unref*/);
if (!box) {
protobuf_c_message_free_unpacked(instance->pbc_instance, pe_cc);
}
return box;
}
rw_status_t
rw_keyspec_path_key_descriptors_by_yang_name (const rw_keyspec_entry_t* entry,
const char *name,
const char *ns,
const ProtobufCFieldDescriptor** k_desc,
const ProtobufCFieldDescriptor** f_desc)
{
if (nullptr == entry) {
return RW_STATUS_FAILURE;
}
ProtobufCMessage *path = (ProtobufCMessage *)entry;
const ProtobufCMessageDescriptor *desc = path->descriptor;
// Find the associated descriptor of the protobuf message
const rw_yang_pb_msgdesc_t *ypbc = desc->ypbc_mdesc;
if ((nullptr == ypbc) || (ypbc->msg_type != RW_YANGPBC_MSG_TYPE_SCHEMA_ENTRY)
|| (nullptr == ypbc->u)) {
return RW_STATUS_FAILURE;
}
uint32_t tag = 0;
if (ypbc->u->msg_msgdesc.msg_type == RW_YANGPBC_MSG_TYPE_LEAF_LIST) {
RW_ASSERT(!ypbc->u->msg_msgdesc.pbc_mdesc);
tag = ypbc->u->msg_msgdesc.pb_element_tag; // Same as the key tag.
} else {
const ProtobufCFieldDescriptor *fd =
protobuf_c_message_descriptor_get_field_by_yang(ypbc->u->msg_msgdesc.pbc_mdesc,
name, ns);
if (nullptr == fd) {
return RW_STATUS_FAILURE;
}
tag = fd->id;
}
// Search for this tag in each of the submessages of this descriptor
for (size_t i = 0; i < desc->n_fields; i++) {
if (desc->fields[i].type != PROTOBUF_C_TYPE_MESSAGE) {
continue;
}
*k_desc = &desc->fields[i];
*f_desc = protobuf_c_message_descriptor_get_field (
(const ProtobufCMessageDescriptor *)(*k_desc)->descriptor,tag);
if (*f_desc) {
return RW_STATUS_SUCCESS;
}
}
RW_ASSERT(nullptr == *f_desc);
*k_desc = nullptr;
return RW_STATUS_FAILURE;
}
rw_status_t rw_keyspec_entry_get_key_at_or_after(
const rw_keyspec_entry_t* entry,
size_t *key_index)
{
size_t key_count = rw_keyspec_entry_num_keys (entry);
// THE PASSED IN INDEX SHOULD NOT CHANGE IF THERE IS NO KEY AFTER THIS.
for (size_t i = *key_index; i < key_count; i++) {
if (rw_keyspec_entry_has_key (entry, i)) {
*key_index = i;
return RW_STATUS_SUCCESS;
}
}
return RW_STATUS_FAILURE;
}
// ATTN: This function must not make requirements on the caller to
// check and free. There should be a unique_ptr in here somehow.
static rw_keyspec_entry_t*
get_key_from_leaf_list_path_entry(
rw_keyspec_instance_t* instance,
const rw_keyspec_entry_t *path_entry,
const rw_yang_pb_msgdesc_t *parent_mdesc)
{
RW_ASSERT(parent_mdesc);
RW_ASSERT(path_entry);
const rw_yang_pb_msgdesc_t *ll_ymdesc = nullptr;
rw_keyspec_entry_t *cpe = const_cast<rw_keyspec_entry_t*>(path_entry);
if (path_entry->base.descriptor == &rw_schema_path_entry__descriptor) {
// Convert the generic path entry to concerete type to extract keys.
// For leaf-list path entries, the element id is same as the key's tag.
// So, search for the child-msg-desc using the element id in parent ypbc msg
// desc.
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
for (unsigned i = 0; i < parent_mdesc->child_msg_count; i++) {
if (parent_mdesc->child_msgs[i]->pb_element_tag == elem_id->element_tag) {
ll_ymdesc = parent_mdesc->child_msgs[i];
break;
}
}
if (!ll_ymdesc) {
return nullptr;
}
// ATTN: Caller of this function should free cpe
// at the called site.
cpe = rw_keyspec_entry_create_dup_of_type(
path_entry, instance, ll_ymdesc->schema_entry_ypbc_desc->pbc_mdesc);
if (!cpe) {
return nullptr;
}
}
return cpe;
}
bool rw_keyspec_path_matches_message (
const rw_keyspec_path_t *k,
rw_keyspec_instance_t* instance,
const ProtobufCMessage *msg,
bool match_c_struct)
{
RW_ASSERT(k);
RW_ASSERT(msg);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, matches_msg);
const ProtobufCMessage *path = &k->base;
if ((nullptr == path->descriptor) ||
(nullptr == path->descriptor->ypbc_mdesc)) {
return false;
}
const rw_yang_pb_msgdesc_t* ypbc =
rw_yang_pb_msgdesc_get_msg_msgdesc (path->descriptor->ypbc_mdesc);
if ((nullptr == msg->descriptor) ||
(nullptr == msg->descriptor->ypbc_mdesc)) {
return false;
}
if ( match_c_struct && (ypbc != msg->descriptor->ypbc_mdesc)) {
return false;
}
if (ypbc != msg->descriptor->ypbc_mdesc) {
if ( (ypbc->pb_element_tag != msg->descriptor->ypbc_mdesc->pb_element_tag) ||
(strcmp(ypbc->module->ns, msg->descriptor->ypbc_mdesc->module->ns)) ) {
return false;
}
}
// Match the values at the tip of the keyspec, removing the extraneous
// leaf path
KeySpecHelper ks(k);
size_t count = ks.get_depth() - 1;
const rw_keyspec_entry_t *entry = ks.get_path_entry(count);
RW_ASSERT(nullptr != entry);
count = rw_keyspec_entry_num_keys (entry);
for (size_t i = 0; i < count; i++) {
ProtobufCFieldInfo key_value;
if (RW_STATUS_SUCCESS == rw_keyspec_entry_get_key_value (entry, i, &key_value)) {
// The key is present, and has a value
if (!protobuf_c_message_has_field_with_value (msg, key_value.fdesc->name,
&key_value)) {
return false;
}
}
}
return true;
}
rw_status_t rw_keyspec_path_delete_proto_field(
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* msg_ks,
const rw_keyspec_path_t* del_ks,
ProtobufCMessage *msg)
{
rw_status_t status = RW_STATUS_FAILURE;
RW_ASSERT(msg_ks);
RW_ASSERT(del_ks);
RW_ASSERT(msg);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
KEYSPEC_INC_FCALL_STATS(instance, path, delete_proto_field);
KeySpecHelper ks_m(msg_ks);
KeySpecHelper ks_d(del_ks);
size_t depth_m = ks_m.get_depth();
size_t depth_d = ks_d.get_depth();
if (depth_d <= depth_m) {
KEYSPEC_ERROR(instance, del_ks, msg_ks, "Delete ks(%d) shallower than msg ks(%d)", depth_d, depth_m);
return status;
}
// Sanity checks.
if (!rw_keyspec_path_is_prefix_match_impl(instance, ks_m, ks_d, depth_m, depth_d)) {
KEYSPEC_ERROR(instance, del_ks, msg_ks, "Keyspecs are not prefix match");
return status;
}
// Only the last path entry can be wildcarded?
if (ks_d.has_wildcards(0, depth_d-1)) {
KEYSPEC_ERROR(instance, del_ks, "Delete keyspec has wildcards for non terminals");
return status;
}
ProtobufCMessage *parent_msg =
(ProtobufCMessage *)keyspec_find_deeper(instance, depth_m, msg, ks_d, depth_d - 1);
if (!parent_msg) {
return status;
}
auto path_entry = ks_d.get_path_entry(depth_d - 1);
RW_ASSERT(path_entry);
auto element_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(element_id);
uint32_t field_tag = element_id->element_tag;
auto msg_fd = protobuf_c_message_descriptor_get_field( parent_msg->descriptor, field_tag );
if (!msg_fd) {
return status;
}
size_t count = protobuf_c_message_get_field_count( parent_msg, msg_fd );
if (0 == count) {
// The field to delete is not set, is this an error?
return status;
}
if (!rw_keyspec_entry_is_listy(path_entry)) {
protobuf_c_boolean ret = protobuf_c_message_delete_field(
instance->pbc_instance, parent_msg, field_tag);
if (!ret) {
return RW_STATUS_FAILURE;
}
return RW_STATUS_SUCCESS;
}
int field_index = -1;
/*
* ATTN: Currently handles only deleting a single repeated element
* or all the elements. Can the delete request contain wildcards for
* only for some keys??
*/
if (!ks_d.has_wildcards(depth_d-1)) {
if (element_id->element_type == RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST) {
auto cpe = get_key_from_leaf_list_path_entry(
instance, path_entry, parent_msg->descriptor->ypbc_mdesc);
if (cpe == nullptr) {
return status;
}
ProtobufCFieldInfo key_finfo;
if (!get_key_finfo_by_index(cpe, 0, &key_finfo)) {
return status;
}
for (field_index = 0; 1; field_index++) {
ProtobufCFieldInfo msg_finfo;
auto found_data = protobuf_c_message_get_field_instance(
instance->pbc_instance, parent_msg, msg_fd, field_index, &msg_finfo );
if (!found_data) {
return status;
}
int cmp = protobuf_c_field_info_compare( &key_finfo, &msg_finfo );
if (cmp == 0) {
break;
}
}
// ATTN: Fix this. This function should not know the
// implementation details of get_key_from_leaf_list_path_entry
if (path_entry->base.descriptor == &rw_schema_path_entry__descriptor) {
rw_keyspec_entry_free (cpe, instance);
}
} else {
for (field_index = 0; 1; field_index++) {
ProtobufCFieldInfo msg_finfo;
auto found_data = protobuf_c_message_get_field_instance(
instance->pbc_instance, parent_msg, msg_fd, field_index, &msg_finfo );
if (!found_data) {
return status;
}
if (compare_path_entry_and_message(
instance, path_entry, (ProtobufCMessage*)(msg_finfo.element), false)) {
break;
}
}
}
}
protobuf_c_boolean ret = false;
if (field_index != -1) {
// delete one list entry
ret = protobuf_c_message_delete_field_index(
instance->pbc_instance, parent_msg, field_tag, field_index);
} else {
// delete whole list
ret = protobuf_c_message_delete_field(
instance->pbc_instance, parent_msg, field_tag);
}
if (!ret) {
return status;
}
return RW_STATUS_SUCCESS;
}
/*
* return an allocated string -- the caller owns the string
*/
char*
rw_keyspec_path_create_string(const rw_keyspec_path_t* keyspec,
const rw_yang_pb_schema_t* schema,
rw_keyspec_instance_t* instance)
{
int retval;
char* buffer = NULL;
retval = rw_keyspec_path_get_new_print_buffer(keyspec,
instance,
schema,
&buffer);
RW_ASSERT((retval > 0 && *buffer) || buffer == NULL);
return buffer;
}
namespace rw_yang {
rw_status_t get_string_value (const ProtobufCFieldInfo *val,
std::string& str)
{
const ProtobufCFieldDescriptor* fld = val->fdesc;
const void *v = val->element;
switch (fld->type) {
case PROTOBUF_C_TYPE_MESSAGE: {
const ProtobufCMessageDescriptor *desc =
(const ProtobufCMessageDescriptor *)fld->descriptor;
RW_ASSERT(desc);
RW_ASSERT(desc->ypbc_mdesc);
str = desc->ypbc_mdesc->yang_node_name;
}
break;
case PROTOBUF_C_TYPE_INT32:
case PROTOBUF_C_TYPE_FIXED32:
case PROTOBUF_C_TYPE_SINT32:
case PROTOBUF_C_TYPE_SFIXED32:
str = std::to_string(*(const int32_t *) v);
break;
case PROTOBUF_C_TYPE_UINT32:
str = std::to_string(*(const uint32_t *) v);
break;
case PROTOBUF_C_TYPE_INT64:
case PROTOBUF_C_TYPE_FIXED64:
case PROTOBUF_C_TYPE_SINT64:
case PROTOBUF_C_TYPE_SFIXED64:
str = std::to_string(*(const int64_t *) v);
break;
case PROTOBUF_C_TYPE_UINT64:
str = std::to_string(*(const uint64_t *) v);
break;
case PROTOBUF_C_TYPE_FLOAT:
str = std::to_string(*(const float *) v);
break;
case PROTOBUF_C_TYPE_DOUBLE:
str = std::to_string(*(const double *) v);
break;
case PROTOBUF_C_TYPE_BOOL:
str = (*(const uint32_t *)v)?"true":"false";
break;
case PROTOBUF_C_TYPE_ENUM: {
const ProtobufCEnumValue *enum_v = protobuf_c_enum_descriptor_get_value (
(const ProtobufCEnumDescriptor *)fld->descriptor, *(int *)v);
RW_ASSERT(enum_v);
str = enum_v->name;
}
break;
case PROTOBUF_C_TYPE_STRING:
str = (const char *) v;
break;
case PROTOBUF_C_TYPE_BYTES:
default:
RW_CRASH();
}
return RW_STATUS_SUCCESS;
}
}
int rw_keyspec_export_error_records(rw_keyspec_instance_t* instance,
ProtobufCMessage* msg,
const char* record_fname,
const char* ts_fname,
const char* es_fname)
{
instance = ks_instance_get(instance);
RW_ASSERT(instance);
if (!msg || !record_fname || !ts_fname || !es_fname) {
return 0;
}
return keyspec_export_ebuf(instance, msg, record_fname, ts_fname, es_fname);
}
rw_keyspec_path_t*
rw_keyspec_path_create_output_from_input(const rw_keyspec_path_t* input,
rw_keyspec_instance_t* instance,
const rw_yang_pb_schema_t* schema)
{
RW_ASSERT(is_good_ks(input));
rw_keyspec_path_t* output = nullptr;
instance = ks_instance_get(instance);
RW_ASSERT(instance);
RwSchemaCategory cat = rw_keyspec_path_get_category(input);
if (cat != RW_SCHEMA_CATEGORY_RPC_OUTPUT &&
cat != RW_SCHEMA_CATEGORY_RPC_INPUT) {
KEYSPEC_ERROR(instance, input, "KS is not RPC IN/OUT");
return output;
}
auto ypbc_mdesc = input->base.descriptor->ypbc_mdesc;
if (!ypbc_mdesc && !schema) {
KEYSPEC_ERROR(instance, "Generic KS and no schema");
return output;
}
if (!ypbc_mdesc) {
rw_status_t rs = rw_keyspec_path_find_msg_desc_schema(
input, instance, schema, &ypbc_mdesc, NULL);
if (rs != RW_STATUS_SUCCESS) {
KEYSPEC_ERROR(instance, input, "Schema and KS mismatch");
return output;
}
}
RW_ASSERT(ypbc_mdesc->msg_type == RW_YANGPBC_MSG_TYPE_SCHEMA_PATH);
const rw_yang_pb_msgdesc_t* msg_ypbd =
rw_yang_pb_msgdesc_get_msg_msgdesc(ypbc_mdesc);
RW_ASSERT(msg_ypbd);
const rw_yang_pb_msgdesc_t* output_mypbcd = nullptr;
switch (msg_ypbd->msg_type) {
case RW_YANGPBC_MSG_TYPE_CONTAINER:
case RW_YANGPBC_MSG_TYPE_LIST:
case RW_YANGPBC_MSG_TYPE_LEAF_LIST: {
// Get the parent rpc input/output ypbc msg descriptor.
msg_ypbd = msg_ypbd->parent;
while (msg_ypbd) {
if (msg_ypbd->msg_type == RW_YANGPBC_MSG_TYPE_RPC_INPUT ||
msg_ypbd->msg_type == RW_YANGPBC_MSG_TYPE_RPC_OUTPUT) {
output_mypbcd = msg_ypbd;
break;
}
msg_ypbd = msg_ypbd->parent;
}
RW_ASSERT(output_mypbcd);
if (output_mypbcd->msg_type == RW_YANGPBC_MSG_TYPE_RPC_OUTPUT) {
break;
}
//Fall through
}
case RW_YANGPBC_MSG_TYPE_RPC_INPUT: {
RW_ASSERT(msg_ypbd->u);
const rw_yang_pb_rpcdef_t* rpc_def = &msg_ypbd->u->rpcdef;
output_mypbcd = rpc_def->output;
break;
}
case RW_YANGPBC_MSG_TYPE_RPC_OUTPUT: {
output_mypbcd = msg_ypbd;
break;
}
default:
RW_ASSERT_NOT_REACHED();
}
RW_ASSERT(output_mypbcd);
RW_ASSERT(output_mypbcd->msg_type == RW_YANGPBC_MSG_TYPE_RPC_OUTPUT);
rw_keyspec_path_create_dup(output_mypbcd->schema_path_value, instance, &output);
return output;
}
ProtobufCMessage*
rw_keyspec_path_create_delete_delta(const rw_keyspec_path_t* del_ks,
rw_keyspec_instance_t* instance,
const rw_keyspec_path_t* reg_ks)
{
RW_ASSERT(is_good_ks(del_ks));
RW_ASSERT(is_good_ks(reg_ks));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
UniquePtrKeySpecPath::uptr_t ks_uptr;
if (!IS_KEYSPEC_GENERIC(del_ks)) {
auto generic_ks = rw_keyspec_path_create_dup_of_type(
del_ks, instance, &rw_schema_path_spec__descriptor);
if (!generic_ks) {
return nullptr;
}
del_ks = generic_ks;
ks_uptr.reset(generic_ks);
}
KeySpecHelper ks_r(reg_ks);
KeySpecHelper ks_d(del_ks);
size_t depth_r = ks_r.get_depth();
size_t depth_d = ks_d.get_depth();
ProtobufCMessage* out_msg = nullptr;
if (depth_d < depth_r) {
KEYSPEC_ERROR(instance, del_ks, reg_ks, "Delete ks(%d) shallower than reg ks(%d)", depth_d, depth_r);
return out_msg;
}
// Sanity checks.
if (!rw_keyspec_path_is_prefix_match_impl(instance, ks_r, ks_d, depth_r, depth_d)) {
KEYSPEC_ERROR(instance, del_ks, reg_ks, "Keyspecs are not prefix match");
return out_msg;
}
// Only the last path entry can be wildcarded?
if (ks_d.has_wildcards(0, depth_d-1)) {
KEYSPEC_ERROR(instance, del_ks, "Delete keyspec has wildcards for non terminals");
return out_msg;
}
RW_ASSERT(reg_ks->base.descriptor->ypbc_mdesc);
auto ypbc_mdesc = rw_yang_pb_msgdesc_get_msg_msgdesc(
reg_ks->base.descriptor->ypbc_mdesc);
RW_ASSERT(ypbc_mdesc);
out_msg = protobuf_c_message_create(NULL, ypbc_mdesc->pbc_mdesc);
RW_ASSERT(out_msg);
UniquePtrProtobufCMessage<>::uptr_t uptr(out_msg);
ProtobufCMessage* cur_msg = out_msg, *parent = NULL;
size_t index = depth_r - 1;
auto path_entry = ks_d.get_path_entry(index++);
RW_ASSERT(path_entry);
auto elem_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id);
rw_status_t status;
if (rw_keyspec_entry_num_keys(path_entry)) {
if (rw_keyspec_entry_has_wildcards(path_entry)) {
RW_ASSERT (depth_d == depth_r);
auto reg_pathe = ks_r.get_path_entry(depth_r-1);
RW_ASSERT (reg_pathe);
if (rw_keyspec_entry_has_wildcards(reg_pathe)) {
KEYSPEC_ERROR(instance, del_ks, reg_ks, "Cannot create PbDelta");
return nullptr;
}
status = path_entry_copy_keys_to_msg(instance, reg_pathe, cur_msg);
RW_ASSERT (status == RW_STATUS_SUCCESS);
} else {
status = path_entry_copy_keys_to_msg(instance, path_entry, cur_msg);
RW_ASSERT (status == RW_STATUS_SUCCESS);
}
}
while (index < depth_d) {
RW_ASSERT(cur_msg);
parent = cur_msg; cur_msg = NULL;
path_entry = ks_d.get_path_entry(index);
RW_ASSERT(path_entry);
elem_id = rw_keyspec_entry_get_element_id(path_entry);
RW_ASSERT(elem_id);
// Find me in my parent.
const ProtobufCFieldDescriptor* fdesc =
protobuf_c_message_descriptor_get_field(parent->descriptor, elem_id->element_tag);
if (!fdesc) {
KEYSPEC_ERROR(instance, "Del Ks and reg Ks are from diff schema (%u)", elem_id->element_tag);
return nullptr;
}
if ((index == (depth_d - 1)) &&
(elem_id->element_type == RW_SCHEMA_ELEMENT_TYPE_LEAF ||
elem_id->element_type == RW_SCHEMA_ELEMENT_TYPE_CONTAINER)) {
break;
}
RW_ASSERT(elem_id->element_type != RW_SCHEMA_ELEMENT_TYPE_LEAF);
if (elem_id->element_type != RW_SCHEMA_ELEMENT_TYPE_LEAF_LIST) {
protobuf_c_message_set_field_message(instance->pbc_instance, parent, fdesc, &cur_msg);
RW_ASSERT(cur_msg);
status = path_entry_copy_keys_to_msg(instance, path_entry, cur_msg);
RW_ASSERT (status == RW_STATUS_SUCCESS);
} else {
status = path_entry_copy_keys_to_msg(instance, path_entry, parent);
RW_ASSERT (status == RW_STATUS_SUCCESS);
}
index++;
}
ProtobufCFieldReference fref = PROTOBUF_C_FIELD_REF_INIT_VALUE;
if (parent) {
protobuf_c_field_ref_goto_tag(&fref, parent, elem_id->element_tag);
protobuf_c_field_ref_mark_field_deleted(&fref);
}
if (cur_msg) {
protobuf_c_field_ref_goto_whole_message(&fref, cur_msg);
protobuf_c_field_ref_mark_field_deleted(&fref);
}
return uptr.release();
}
const ProtobufCMessageDescriptor*
rw_keyspec_get_pbcmd_from_xpath(const char* xpath,
const rw_yang_pb_schema_t* schema,
rw_keyspec_instance_t* instance)
{
RW_ASSERT(xpath);
RW_ASSERT(schema);
instance = ks_instance_get(instance);
RW_ASSERT(instance);
if (!strlen(xpath)) {
return nullptr;
}
char cat = 0;
if (xpath[0] != '/') {
if (strlen(xpath) < 3 || xpath[1] != ',') {
return nullptr;
}
cat = xpath[0];
xpath += 2;
}
RwSchemaCategory category = RW_SCHEMA_CATEGORY_ANY;
if (cat != 0) {
switch (cat) {
case 'D':
category = RW_SCHEMA_CATEGORY_DATA;
break;
case 'C':
category = RW_SCHEMA_CATEGORY_CONFIG;
break;
case 'I':
category = RW_SCHEMA_CATEGORY_RPC_INPUT;
break;
case 'O':
category = RW_SCHEMA_CATEGORY_RPC_OUTPUT;
break;
case 'N':
category = RW_SCHEMA_CATEGORY_NOTIFICATION;
break;
case 'A':
break;
default:
KEYSPEC_ERROR(instance, "Invalid category in xpath(%c)", cat);
return nullptr;
}
}
XpathIIParser parser(xpath, RW_XPATH_KEYSPEC);
if (!parser.parse_xpath()) {
KEYSPEC_ERROR(instance, "Failed to parse xpath(%s)", xpath);
return nullptr;
}
const rw_yang_pb_msgdesc_t* ypbc_mdesc = parser.validate_xpath(schema, category);
if (!ypbc_mdesc) {
KEYSPEC_ERROR(instance, "xpath(%s)-schema validation error", xpath);
return nullptr;
}
if (RW_YANGPBC_MSG_TYPE_LEAF_LIST == ypbc_mdesc->msg_type) {
KEYSPEC_ERROR(instance, "xpath(%s) - Get pbcmd for leaf-list", xpath);
return nullptr;
}
// Make sure that the xpath was for a message
KeySpecHelper ks(ypbc_mdesc->schema_path_value);
size_t depth = ks.get_depth();
if (depth != parser.get_depth()) {
KEYSPEC_ERROR(instance, "xpath(%s) - get pbcmd for leaf?", xpath);
return nullptr;
}
return ypbc_mdesc->pbc_mdesc;
}
ProtobufCMessage*
rw_keyspec_pbcm_create_from_keyspec(rw_keyspec_instance_t* instance,
const rw_keyspec_path_t *ks)
{
RW_ASSERT(is_good_ks(ks));
instance = ks_instance_get(instance);
RW_ASSERT(instance);
if (IS_KEYSPEC_GENERIC(ks)) {
return nullptr;
}
ProtobufCMessage* out_msg = nullptr;
RW_ASSERT(ks->base.descriptor->ypbc_mdesc);
auto ypbc_mdesc = rw_yang_pb_msgdesc_get_msg_msgdesc(
ks->base.descriptor->ypbc_mdesc);
RW_ASSERT(ypbc_mdesc);
out_msg = protobuf_c_message_create(NULL, ypbc_mdesc->pbc_mdesc);
RW_ASSERT(out_msg);
// TODO: Add key value to the protobuf??
return out_msg;
}
| [
"Leslie.Giles@riftio.com"
] | Leslie.Giles@riftio.com |
cf63a7f3047699bd1bcba9fd3405ed70c5a937f9 | 8544380a90a32d92854f2dfb82b7cef806fa741a | /ZBSCOMM V1.1/mscomm.h | 76ead45c436707899a429c1f7d19e191f5ef87c7 | [] | no_license | 563886019/test | a386427253ea40ac933705557853a67d325adbda | a351b778ca40dcb5787dc6ef98f13be86b940d7f | refs/heads/master | 2021-01-13T00:38:21.957944 | 2015-10-28T07:53:31 | 2015-10-28T07:53:31 | 45,096,605 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,121 | h | #if !defined(AFX_MSCOMM_H__CA6500D7_7195_46BD_B2FE_BE3D37DE5E6F__INCLUDED_)
#define AFX_MSCOMM_H__CA6500D7_7195_46BD_B2FE_BE3D37DE5E6F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
/////////////////////////////////////////////////////////////////////////////
// CMSComm wrapper class
class CMSComm : public CWnd
{
protected:
DECLARE_DYNCREATE(CMSComm)
public:
CLSID const& GetClsid()
{
static CLSID const clsid
= { 0x648a5600, 0x2c6e, 0x101b, { 0x82, 0xb6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x14 } };
return clsid;
}
virtual BOOL Create(LPCTSTR lpszClassName,
LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect,
CWnd* pParentWnd, UINT nID,
CCreateContext* pContext = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID); }
BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect, CWnd* pParentWnd, UINT nID,
CFile* pPersist = NULL, BOOL bStorage = FALSE,
BSTR bstrLicKey = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID,
pPersist, bStorage, bstrLicKey); }
// Attributes
public:
// Operations
public:
void SetCDHolding(BOOL bNewValue);
BOOL GetCDHolding();
void SetCommID(long nNewValue);
long GetCommID();
void SetCommPort(short nNewValue);
short GetCommPort();
void SetCTSHolding(BOOL bNewValue);
BOOL GetCTSHolding();
void SetDSRHolding(BOOL bNewValue);
BOOL GetDSRHolding();
void SetDTREnable(BOOL bNewValue);
BOOL GetDTREnable();
void SetHandshaking(long nNewValue);
long GetHandshaking();
void SetInBufferSize(short nNewValue);
short GetInBufferSize();
void SetInBufferCount(short nNewValue);
short GetInBufferCount();
void SetBreak(BOOL bNewValue);
BOOL GetBreak();
void SetInputLen(short nNewValue);
short GetInputLen();
void SetNullDiscard(BOOL bNewValue);
BOOL GetNullDiscard();
void SetOutBufferSize(short nNewValue);
short GetOutBufferSize();
void SetOutBufferCount(short nNewValue);
short GetOutBufferCount();
void SetParityReplace(LPCTSTR lpszNewValue);
CString GetParityReplace();
void SetPortOpen(BOOL bNewValue);
BOOL GetPortOpen();
void SetRThreshold(short nNewValue);
short GetRThreshold();
void SetRTSEnable(BOOL bNewValue);
BOOL GetRTSEnable();
void SetSettings(LPCTSTR lpszNewValue);
CString GetSettings();
void SetSThreshold(short nNewValue);
short GetSThreshold();
void SetOutput(const VARIANT& newValue);
VARIANT GetOutput();
void SetInput(const VARIANT& newValue);
VARIANT GetInput();
void SetCommEvent(short nNewValue);
short GetCommEvent();
void SetEOFEnable(BOOL bNewValue);
BOOL GetEOFEnable();
void SetInputMode(long nNewValue);
long GetInputMode();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MSCOMM_H__CA6500D7_7195_46BD_B2FE_BE3D37DE5E6F__INCLUDED_)
| [
"563886019@qq.com"
] | 563886019@qq.com |
79ac3ce09fcb8a5a86927d7e84c8ef6f8c6c767f | 16a04a189c2f14d6d28a78d774a8c0ad8fb3bf28 | /CADMIUM - Cooperative Caching/data_structures/messageT.hpp | a554cd7a391864402c8764bcfc5c5ec88e4bcce8 | [] | no_license | F951/Models-HPCS | 7895b9d708df04f7b2fe70c9e14c46ac32dd3d67 | 64b24311499b8ffd7e86c3698389494f0f5a8787 | refs/heads/main | 2023-03-07T16:02:02.620133 | 2021-02-24T15:38:44 | 2021-02-24T15:38:44 | 341,332,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,983 | hpp | #ifndef MessageT_MESSAGE_HPP
#define MessageT_MESSAGE_HPP
#include <assert.h>
#include <iostream>
#include <string>
#include "../glob.h"
#include "../atomics/p2pLayer/NodeEntry.h"
#include "../atomics/applicationLayer/LCache.h"
#include "../atomics/applicationLayer/Entry.h"
using namespace std;
enum MessageTType { T_P2P = 0,
T_BDC = 1
};
//Esto sirve para ver el peso de los datos que transporta el msje, y simular la latencia correpondiente.
enum DataType { SOLICITUD_TAREA = 20, //Este nunca se usa, porque los mensajes de solicitud de tarea llegan direcmtamente al voluntario, desde el wse, a través del isp.
SOLICITUD_OBJETO = 21,
OBJETO_OPCIONES = 22,
TRABAJO_TERMINADO = 23,
TRABAJO_AGREGADO = 24 //Esta no la uso. La mezclo con TRABAJO_TERMINADO.
};
/*******************************************/
/**************** MessageT ****************/
/*******************************************/
class MessageT{
public:
int src; // index of the peer source of the message
int dest; // index of the peer destination of the meesage
void *DATA; // data transmited by this message
MessageTType type;
DataType dataType;
//Constructor
MessageT(MessageTType _type, void* _D, int _src, int _dest)
{
src= _src;
dest = _dest;
DATA=_D;
type=_type;
setDataType((DataType)0);
}
int getType(){
return type;
}
void setType(MessageTType _t){
type=_t;
}
int getDataType(){
return dataType;
}
void setDataType(DataType _t){
dataType=_t;
}
void * getData(){
return DATA;
}
MessageT* clone(){
MessageT* newMsg = new MessageT(this->type, this->DATA, this->src, this->dest);
return newMsg;
}
int getDest(){
return dest;
}
int getSrc(){
return src;
}
};
istream& operator>> (istream& is, MessageT& msg);
ostream& operator<<(ostream& os, const MessageT& msg);
#endif // MessageT_MESSAGE_HPP
| [
"fer_06@hotmail.com"
] | fer_06@hotmail.com |
e3a9eadce1456026738c73fde6a0b4f8fee13741 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/PSID_NAME_USE.hpp | e97f00821c1ad5c2743b09d9b84ea7a41de8fd0c | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 232 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
typedef _SID_NAME_USE *PSID_NAME_USE;
END_ATF_NAMESPACE
| [
"b1ll.cipher@yandex.ru"
] | b1ll.cipher@yandex.ru |
1c93c1354e3ac6bf2e3a7154cc024baf35d7a801 | 0804854c11ebc0b7f1185b55b991a7f06c1e7a00 | /mcpe/McpeHandler.h | b1974e0dac34057e0cb5092f13da05c753f663e1 | [] | no_license | bledogit/MinecraftMapper | d54a0212e81faeb37d6488fca39455b5b53d633f | 73fd589765e352528b2c31fbae65bf76cce59e97 | refs/heads/master | 2022-03-07T00:58:52.490342 | 2019-11-08T16:07:33 | 2019-11-08T16:07:33 | 220,504,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,483 | h | //
// McpeHandler.h
// MineMapper
//
// Created by Jose on 6/10/15.
// Copyright (c) 2015 Jose. All rights reserved.
//
#ifndef __MineMapper__McpeHandler__
#define __MineMapper__McpeHandler__
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include "leveldb/db.h"
#include "leveldb/zlib_compressor.h"
#include "leveldb/zstd_compressor.h"
#include "leveldb/zopfli_compressor.h"
#include "leveldb/snappy_compressor.h"
#include "leveldb/filter_policy.h"
#include "leveldb/env.h"
#include "leveldb/cache.h"
#ifndef MCPELOG
#define MCPELOG(x) do { std::cerr << x << std::endl;} while (0)
#endif
typedef union Color
{
unsigned int c;
struct argbTag
{
unsigned char b;
unsigned char g;
unsigned char r;
unsigned char a;
} argb;
} COLOR4B;
class BlockInfo {
Color c;
};
typedef struct Key {
int x;
int y;
char code;
} _Key;
typedef enum MapType {
NORMAL = 0,
TOPO = 1
} _MapType;
class McpeHandler {
Color colorarr[256];
int width;
int height;
int offX;
int offY;
int maxBlocks;
int blocksize;
int blocksize2;
Color* map;
std::string filename;
leveldb::DB *db;
leveldb::Options options;
char layerCode = 48; //'0';
void (*progress)(int, void*) = 0;
void* progressContext = 0;
void clear (int x1, int y1, int x2, int y2, char action);
public:
McpeHandler();
McpeHandler(std::string name);
~McpeHandler();
void loadLevelDB(std::string name);
void moveBlock(int z, const char* block, char* target, size_t size);
void getBlock(const char* block, Color* map, int zmax);
void getTopo(const char* block, Color* map);
void findSizes();
void loadMap(MapType type = NORMAL);
void savePNM(char* filename);
const char* getBitmap ();
int getBitmapSize();
int getBitmapWidth ();
int getBitmapHeight ();
int getOffsetW () { return offX;}
int getOffsetH () { return offY;}
void testMap(int width, int height);
leveldb::DB *getDB();
void addToMap(int x, int y, int z, McpeHandler& other);
void crop (int x1, int y1, int x2, int y2);
void erase (int x1, int y1, int x2, int y2);
void getBlockInfo(int x, int y);
void setProgressHanler(void (*progress)(int, void*), void* context);
void compact ();
};
#endif /* defined(__MineMapper__McpeHandler__) */
| [
"jose.mortensen@nielsen.com"
] | jose.mortensen@nielsen.com |
15b0e8cd565cb86191dcfe3f9953b615c80066cd | 9859eb8b90ba054e87547cc0f368ef162dbcf351 | /motion-lib/Supremo.cpp | 10c4165f6c5223bd624e1e902c9bfa09f028440e | [
"BSD-3-Clause"
] | permissive | jamie-mcclelland/SuPReMo | 5afa2709b6ee94a9a7e0d9957302f27e892b2ada | 09c3dd25201626bf22cd012d0a9f064287369479 | refs/heads/main | 2023-07-12T21:27:53.423536 | 2021-08-26T15:47:04 | 2021-08-26T15:47:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,347 | cpp | // ====================================================================================================
//
// SuPReMo: Surrogate Parameterised Respiratory Motion Model
// An implementation of the generalised motion modelling and image registration framework
//
// Copyright (c) University College London (UCL). All rights reserved.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.
//
// See LICENSE.txt in the top level directory for details.
//
// ====================================================================================================
//----------
// Includes
//----------
#include "Supremo.h"
#include "_reg_ReadWriteImage.h"
#include "_reg_tools.h"
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
//------------------
// Supremo::Supremo
//------------------
Supremo::Supremo() :
numberOfSurrogateSignals( 0 ),
numberOfDynamicImages( 0 ),
allDynamicImages( nullptr ),
referenceStateImage( nullptr ),
defSpaceImage( nullptr ),
finalMoCoReconImage( nullptr ),
dynamicImageDataType( SAME_RES_AS_STATIC ),
maxSwitchIterationNumber( -1 ),
maxModelFitIterationNumber( 0 ),
numberOfLevels( 3 ),
numberOfLevelsToPerform( 3 ),
currentLevel( 0 ),
transformationType( STANDARD_B_SPLINE ),
bSplineBendingEnergyWeight( 0 ),
bSplineLinearEnergyWeight( 0 ),
slidingSignedDistanceMapImage( nullptr ),
slidingGapOverlapConstraintWeight( 0 ),
outputInterMCRFolder( "" ),
outputInterGradientFolder( "" ),
initialised( false ),
referenceStatePyramid( nullptr ),
currentReferenceStateImage( nullptr ),
transform( nullptr ),
correspondenceModel( nullptr ),
similarityMeasure( nullptr ),
imageAcquisition( nullptr ),
mocoReconstructor( nullptr ),
levelID( "" )
{
// Array needs to be initialised here for compatibility with VS2013
// otherwise bSplineSpacing{0,0,0} in list above would have worked.
this->bSplineCPGSpacing[0] = this->bSplineCPGSpacing[1] = this->bSplineCPGSpacing[2] = 0;
}
//-------------------
// Supremo::~Supremo
//-------------------
Supremo::~Supremo()
{
this->transform.reset();
nifti_image_free( this->finalMoCoReconImage );
}
//---------------------------
// Supremo::SetDynamicImages
//---------------------------
void Supremo::SetDynamicImages(nifti_image** dynamicImagesIn, int numberOfDynamicImagesIn)
{
// Save the dynamic images to the member variables
this->allDynamicImages = dynamicImagesIn;
this->numberOfDynamicImages = numberOfDynamicImagesIn;
}
//---------------------------------
// Supremo::SetReferenceStateImage
//---------------------------------
void Supremo::SetReferenceStateImage( nifti_image* referenceStateImageIn )
{
// Save the pointer to the reference state image to the member variable
this->referenceStateImage = referenceStateImageIn;
return;
}
//-----------------------------------
// Supremo::SetReferenceStateImage
//-----------------------------------
void Supremo::SetDefSpaceImage( nifti_image* defSpaceImageIn )
{
// Save an image that defines the reference space
this->defSpaceImage = defSpaceImageIn;
}
//--------------------------------
// Supremo::SetSurrogateSignals
//--------------------------------
void Supremo::SetSurrogateSignals( float* surrogateSignalsIn, int numberOfSurrogateSignalsIn )
{
// Remember the number of surrogate signals
this->numberOfSurrogateSignals = numberOfSurrogateSignalsIn;
if (this->numberOfDynamicImages == 0)
{
char msg[200];
sprintf_s( msg, "Number of dynamic images is %i. These have to be set prior to calling this function", this->numberOfDynamicImages );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
// Save the raw surrogate data pointer into an array
for (int iTimePoint = 0; iTimePoint < this->numberOfDynamicImages; ++iTimePoint)
{
std::vector<float> tmpVect;
for (int iSurrSig = 0; iSurrSig < this->numberOfSurrogateSignals; ++iSurrSig)
{
tmpVect.push_back( surrogateSignalsIn[iTimePoint*this->numberOfSurrogateSignals + iSurrSig] );
}
this->surrogateSignals.push_back( tmpVect );
}
}
//------------------------------------
// Supremo::SetDynamicImageDataType
//------------------------------------
void Supremo::SetDynamicImageDataType( t_dynamicData dynamicImgaeDataTypeIn )
{
// Set the dynamic image data type
this->dynamicImageDataType = dynamicImgaeDataTypeIn;
return;
}
//-----------------------
// Supremo::SetMCRType
//-----------------------
void Supremo::SetMotionCompensatedReconstruction( std::shared_ptr<MoCoRecon> mocoReconstructionIn )
{
// Set the motion-compensated image reconstruction type
this->mocoReconstructor = mocoReconstructionIn;
}
//------------------------------------
// Supremo::SetInterMCROutputFolder
//------------------------------------
void Supremo::SetInterMCROutputFolder( const std::string & outputFolderIn)
{
// Define the folder name where to save the intermediate motion-compensated images
this->outputInterMCRFolder = outputFolderIn;
}
//------------------------------------
// Supremo::SetInterMCROutputFolder
//------------------------------------
void Supremo::SetInterGradOutputFolder( const std::string & outputFolderIn )
{
// Define the folder name where to save the intermediate gradient images will be saved
this->outputInterGradientFolder = outputFolderIn;
}
//------------------------------------
// Supremo::SetInterMCROutputFolder
//------------------------------------
void Supremo::SetTransformationType( t_transformationType tranformationTypeIn )
{
// Set the transformation type
this->transformationType = tranformationTypeIn;
}
//---------------------------------
// Supremo::SetBSplineCPGSpacing
//---------------------------------
void Supremo::SetBSplineCPGSpacing( float sxIn, float syIn, float szIn )
{
// Define the bspline spacing in x, y, and z
this->bSplineCPGSpacing[0] = sxIn;
this->bSplineCPGSpacing[1] = syIn;
this->bSplineCPGSpacing[2] = szIn;
}
//----------------------------------
// Supremo::SetBSplineBendingEnergy
//----------------------------------
void Supremo::SetBSplineBendingEnergy( float beIn )
{
// Define the bending energy (on the final level)
this->bSplineBendingEnergyWeight = beIn;
}
//---------------------------------
// Supremo::SetBSplineLinearEnergy
//---------------------------------
void Supremo::SetBSplineLinearEnergy( float leIn )
{
// Define the linear energy for the bspline transformation regularisation
this->bSplineLinearEnergyWeight = leIn;
}
//-----------------------------------------------
// Supremo::SetSlidingGapOverlapConstraintWeight
//-----------------------------------------------
void Supremo::SetSlidingGapOverlapConstraintWeight( float goIn )
{
// Set the gap/overlap constraint weight for the sliding transformation
this->slidingGapOverlapConstraintWeight = goIn;
}
//-------------------------------------
// Supremo::SetSlidingTrafoDistanceMap
//-------------------------------------
void Supremo::SetSlidingTrafoDistanceMap( nifti_image* signedDistanceMapImageIn )
{
this->slidingSignedDistanceMapImage = signedDistanceMapImageIn;
}
//-----------------------------------------
// Supremo::FitMotionModelAndReconstruct
//-----------------------------------------
void Supremo::FitMotionModelAndReconstruct()
{
// Initialise
this->Initialise();
// Loop over resolution levels
for (; currentLevel < this->numberOfLevelsToPerform; ++currentLevel)
{
// Update the level ID to have the same ID for various outputs
{
std::ostringstream ossLevelID;
ossLevelID.clear();
ossLevelID << "lev_" << std::setfill( '0' ) << std::setw( 2 ) << currentLevel << "_initial";
this->levelID = ossLevelID.str();
}
// Initialise the current level of the transformation and correspondence model
this->transform->InitialiseLevel( currentLevel );
this->correspondenceModel->InitialiseLevel( currentLevel );
// member variable currentReferenceStateImage may not be required
this->currentReferenceStateImage = this->referenceStatePyramid->GetLevel( currentLevel );
// Display current level parameters
this->DisplayCurrentLevelParameters( currentLevel );
// Extract relevant dynamic images from vector of pyramids
std::vector<nifti_image*> curDynamicImages;
for (int nDynImg = 0; nDynImg < this->numberOfDynamicImages; ++nDynImg)
{
curDynamicImages.push_back( this->allDynamicPyramids[nDynImg]->GetLevel( currentLevel ) );
}
// Motion compensated image reconstruction
if (this->mocoReconstructor != nullptr)
{
this->mocoReconstructor->SetSurrogateSignals( this->surrogateSignals );
this->mocoReconstructor->SetDynamicImages( curDynamicImages );
this->mocoReconstructor->SetCorrespondenceModel( this->correspondenceModel );
this->mocoReconstructor->SetImageAcquisition( this->imageAcquisition );
this->mocoReconstructor->SetReconstructionGeometryImage( this->currentReferenceStateImage );
// and perform the first reconstruction for this level
this->mocoReconstructor->Update();
// copy the reconstructed image into the current reference state image
this->mocoReconstructor->CopyReconstructedImageContentsToImage( this->currentReferenceStateImage );
// Update the levelID used to save the intermediate results
this->SaveInterMCRToImage( this->mocoReconstructor->GetReconstructedImage() );
}
// Initialise the objective function to be optimised and
// feed in all required paramters
std::shared_ptr<ObjectiveFunction> objectiveFunction = std::make_shared<ObjectiveFunction>();
objectiveFunction->SetCorrespondenceModel( this->correspondenceModel );
objectiveFunction->SetSurrogateSignals( this->surrogateSignals );
objectiveFunction->SetSimilarityMeasure( this->similarityMeasure );
objectiveFunction->SetReferenceStateImage( this->currentReferenceStateImage );
objectiveFunction->SetDynamicImages( curDynamicImages, this->dynamicImageDataType );
objectiveFunction->SetImageAcquisition( this->imageAcquisition );
// initialise the optimiser for fitting the model
std::shared_ptr<Optimiser> optimiser = std::make_shared<ConjugateGradientOptimiser>();
optimiser->SetObjectiveFunction( objectiveFunction );
optimiser->SetMaxIterations( this->maxModelFitIterationNumber );
optimiser->SetOutputIntermediateGradientFolder( outputInterGradientFolder, levelID );
optimiser->Initialise();
// Need to store objective function value from previous switch iteration (i.e. starting point of the optimisation)
// Hence this will be read from the optimisation afterwards;
double prevObjectiveFunctionValue;
// Ask the correspondence model to save the the model parameters
// in case they need to be recovered later on
this->correspondenceModel->SaveCurrentModelParametersForRecovery();
// switch between model fitting and motion compensated image reconstruction
// until max number of switch iterations performed
for (int switchIter = 0; switchIter < this->maxSwitchIterationNumber; switchIter++)
{
// Update the level ID to have the same ID for various outputs
{
std::ostringstream ossLevelID;
ossLevelID.clear();
ossLevelID << "lev_" << std::setfill( '0' ) << std::setw( 2 ) << currentLevel
<< "_iter_" << std::setfill( '0' ) << std::setw( 2 ) << switchIter;
this->levelID = ossLevelID.str();
}
optimiser->SetOutputIntermediateGradientFolder( outputInterGradientFolder, levelID );
// Perfrom the optimisation with the starting point defined by the correspondence model,
// iteration counts are reset everytime Optimise() is being called
optimiser->Optimise( this->correspondenceModel->GetParameters() );
this->correspondenceModel->SetParameters( optimiser->GetBestPoint() );
prevObjectiveFunctionValue = optimiser->GetInitialObjectiveFunctionValue();
//check if objective function improved from model fitting
if (prevObjectiveFunctionValue >= optimiser->GetBestObjectiveFunctionValue())
{
// model has not changed (or is worse than before, but this should be impossible)
// so no need to redo reconstruction unless super-resolution with update is requried
if (nullptr == this->mocoReconstructor || !this->mocoReconstructor->GetRepeatedUpdateChangesMCR())
break;
}
CorrespondenceModel::PrecisionType objectiveFunctionValueAfterRecon = optimiser->GetBestObjectiveFunctionValue();
if (nullptr != mocoReconstructor)
{
// Update the motion-compensated image reconstruction
// The correspondence model was already updated
mocoReconstructor->Update();
// Save the newly reconstructed image if requried
this->SaveInterMCRToImage( mocoReconstructor->GetReconstructedImage() );
// the updated reference state image will have an impact on the objective function value
// ideally this has improved
// need to evaluate the objective function
// but this is done when the optimiser is called... so if we do this here explicitly,
objectiveFunction->SetReferenceStateImage( mocoReconstructor->GetReconstructedImage() );
objectiveFunctionValueAfterRecon = objectiveFunction->GetValue( this->correspondenceModel->GetParameters() );
objectiveFunction->SetReferenceStateImage( this->currentReferenceStateImage );
std::cout << "fValAfterReco=" << std::setprecision( 5 ) << objectiveFunctionValueAfterRecon << std::endl;
}
std::cout << "End of switch iteration " << switchIter << std::endl;
// if the reconstruction results in a better objective function than the one directly after model fitting, then
// update the correspondence model and the reference state image
if (objectiveFunctionValueAfterRecon > prevObjectiveFunctionValue)
{
// updating the reconstruction improved the objective function, so update and continue
if (nullptr != mocoReconstructor) mocoReconstructor->CopyReconstructedImageContentsToImage( this->currentReferenceStateImage );
this->correspondenceModel->SaveCurrentModelParametersForRecovery();
prevObjectiveFunctionValue = objectiveFunctionValueAfterRecon;
optimiser->SetPreviouslyEvaluatedObjectiveFunctionValue( objectiveFunctionValueAfterRecon );
}
else
{
// The fitting and reconstruction did not improve the result. Do NOT upadte the current
// reference-state image and recover the correspondence model parameters
this->correspondenceModel->RecoverSavedModelParameters();
break;
}
} // for (int switchIter = 0; switchIter < this->maxSwitchIterationNumber; switchIter++)
} // for currentLevel
// The current reference state image is located in the image pyramid. Hence, we better copy it into a dedicated
// destination instead.
this->finalMoCoReconImage = nifti_copy_nim_info( this->currentReferenceStateImage );
this->finalMoCoReconImage->data = malloc( this->finalMoCoReconImage->nvox * this->finalMoCoReconImage->nbyper );
memcpy( this->finalMoCoReconImage->data,
this->currentReferenceStateImage->data,
this->finalMoCoReconImage->nvox * this->finalMoCoReconImage->nbyper );
return;
}
//----------------------------------------
// Supremo::GetCorrespondenceModelAsImage
//----------------------------------------
std::vector<nifti_image*> Supremo::GetCorrespondenceModelAsImage()
{
// Cannot get the correspondence model if it does not exist (anymore)
if (this->correspondenceModel == nullptr)
{
supremo_print_error( "No correspondence model set." );
supremo_exit( EXIT_FAILURE, __FILE__, __LINE__ );
}
// Request the image from the correspondence model
std::vector<nifti_image*> correspModelImages = this->correspondenceModel->GetCorrespondenceModelAsImage();
// Set description in the nifti header accordingly in each returned image
for (size_t i = 0; i < correspModelImages.size(); ++i)
{
memset( correspModelImages[i]->descrip, 0, 80 );
strcpy( correspModelImages[i]->descrip, "Respiratory correspondence model from SuPReMo" );
}
return correspModelImages;
}
//--------------------------------
// Supremo::SimulateDynamicImages
//--------------------------------
std::vector<nifti_image*> Supremo::SimulateDynamicImages()
{
// Check that all required members are available
if (nullptr == this->allDynamicImages)
{
supremo_print_error( "Dynamic images not available." );
supremo_exit( 1, __FILE__, __LINE__ );
}
if (nullptr == this->imageAcquisition)
{
supremo_print_error( "Image acquisition not defined." );
supremo_exit( 1, __FILE__, __LINE__ );
}
if (nullptr == this->correspondenceModel)
{
supremo_print_error( "Correspondence model not defined." );
supremo_exit( 1, __FILE__, __LINE__ );
}
if (nullptr == this->finalMoCoReconImage)
{
supremo_print_error( "Final motion-compensated reconstructed image not defined." );
supremo_exit( 1, __FILE__, __LINE__ );
}
std::vector<nifti_image*> outDynamicImages;
for (unsigned int iImg = 0; iImg < this->numberOfDynamicImages; ++iImg)
{
// Get the transformation for the current surrogate value
std::shared_ptr<Transformation> curTrafo = this->correspondenceModel->GetTransformationFromSurrogateSignal( this->surrogateSignals[iImg] );
// Convert the current dynamic image to the data type needed
nifti_image* curDynImg = nifti_copy_nim_info( this->allDynamicImages[iImg] );
curDynImg->data = malloc( curDynImg->nbyper * curDynImg->nvox );
memcpy( curDynImg->data, this->allDynamicImages[iImg]->data, curDynImg->nbyper * curDynImg->nvox );
reg_tools_changeDatatype<VoxelType>( curDynImg );
// Use the image acquisition class to define the minimum sized image that we need to define the
nifti_image* curMinSizeImgInFullImgSpace = this->imageAcquisition->AllocateMinimumSizeImgInFullImgSpace( this->finalMoCoReconImage, curDynImg );
// Use the transformation to warp the final image into the min-sized space
curTrafo->TransformImage( this->finalMoCoReconImage, curMinSizeImgInFullImgSpace );
// Simulate the acquisition
nifti_image* curSimulatedDynamicImg = this->imageAcquisition->SimulateImageAcquisition( curMinSizeImgInFullImgSpace, curDynImg );
outDynamicImages.push_back( curSimulatedDynamicImg );
// Free the intermediate images if it was not simply copied over by the image-acquisition object
if (curMinSizeImgInFullImgSpace != curSimulatedDynamicImg)
{
nifti_image_free( curMinSizeImgInFullImgSpace );
}
nifti_image_free( curDynImg );
}
return outDynamicImages;
}
//----------------------------------------------
// Supremo::GenerateDVFsFromCorrespondenceModel
//----------------------------------------------
std::vector<nifti_image*> Supremo::GenerateDVFsFromCorrespondenceModel()
{
// Check that all required members are available
if (nullptr == this->allDynamicImages)
{
supremo_print_error( "Dynamic images not available." );
supremo_exit( 1, __FILE__, __LINE__ );
}
if (nullptr == this->imageAcquisition)
{
supremo_print_error( "Image acquisition not defined." );
supremo_exit( 1, __FILE__, __LINE__ );
}
if (nullptr == this->correspondenceModel)
{
supremo_print_error( "Correspondence model not defined." );
supremo_exit( 1, __FILE__, __LINE__ );
}
// Generate a vector that holds the generated DVF images
std::vector<nifti_image*> outDVFs;
for (unsigned int iImg = 0; iImg < this->numberOfDynamicImages; ++iImg)
{
// Get the transformation for the current surrogate value
std::shared_ptr<Transformation> curTrafo = this->correspondenceModel->GetTransformationFromSurrogateSignal( this->surrogateSignals[iImg] );
// The transformation will return a pointer to the internal nifti image holding the dvf.
// Request it for the size of the current dynamic image
// Hence a copy of this DVF needs to be generated, otherwise it will be lost
nifti_image* curDVF = curTrafo->GetDeformationVectorField( this->allDynamicImages[iImg] );
nifti_image* curDVFOut = nifti_copy_nim_info( curDVF );
curDVFOut->data = malloc( curDVFOut->nvox * curDVFOut->nbyper );
memcpy( curDVFOut->data, curDVF->data, curDVFOut->nvox * curDVFOut->nbyper );
outDVFs.push_back( curDVFOut );
}
return outDVFs;
}
//---------------------
// Supremo::Initialise
//---------------------
void Supremo::Initialise()
{
// No need to initialise if this was already done before
if (this->initialised) return;
// Check that all parameters were set correctly
this->CheckParameters();
// Generate the dynamic image pyramids
for ( unsigned int i = 0; i < this->numberOfDynamicImages; ++i )
{
auto curDynPyramid = std::make_shared<ImagePyramid<VoxelType> >();
curDynPyramid->GenerateLevels( this->allDynamicImages[i], this->numberOfLevels, this->numberOfLevelsToPerform );
allDynamicPyramids.push_back( curDynPyramid );
}
// Generate the reference state image pyramid
this->referenceStatePyramid = std::make_shared<ImagePyramid<VoxelType> >();
this->referenceStatePyramid->GenerateLevels( this->referenceStateImage,
this->numberOfLevels,
this->numberOfLevelsToPerform,
2 );
// Initialise the transformation
if (this->transformationType == STANDARD_B_SPLINE)
{
auto bsplTrafo = std::make_shared<BSplineTransformation>( this->defSpaceImage,
this->numberOfLevelsToPerform,
this->bSplineCPGSpacing );
bsplTrafo->SetBendingEnergyWeight( this->bSplineBendingEnergyWeight );
bsplTrafo->SetLinearEnergyWeight( this->bSplineLinearEnergyWeight );
this->transform = bsplTrafo;
}
else if (SLIDING_B_SPLINE == this->transformationType)
{
// We need two transforms for setting up the sliding transform, these do not have to be the same
auto bsplTrafoA = std::make_shared<BSplineTransformation>( this->defSpaceImage,
this->numberOfLevelsToPerform,
this->bSplineCPGSpacing );
bsplTrafoA->SetBendingEnergyWeight( this->bSplineBendingEnergyWeight );
bsplTrafoA->SetLinearEnergyWeight( this->bSplineLinearEnergyWeight );
auto bsplTrafoB = bsplTrafoA->DeepCopy();
// Use the two transformations above to generate a sliding transformation
auto slidingBSplineTrafo = std::make_shared<SlidingTransformation>( bsplTrafoA, bsplTrafoB, this->defSpaceImage, numberOfLevels, numberOfLevelsToPerform );
slidingBSplineTrafo->SetGapOverlapConstraintWeight( this->slidingGapOverlapConstraintWeight );
slidingBSplineTrafo->SetSignedDistanceMapImage( this->slidingSignedDistanceMapImage );
this->transform = slidingBSplineTrafo;
}
// Initialise the correspondence model
this->correspondenceModel = std::make_shared<CorrespondenceModel>( this->numberOfSurrogateSignals, this->transform );
// Check if an input correspondence model was provided
if (this->inputRCMImages.size() > 0)
{
std::cout << "Input correspondence model given. Findin appropriate multi-resolution level..." << std::endl;
// Check how many voxels are in the given images
unsigned int totalNumOfInputRCMParameters = 0;
for (size_t iRCMImg = 0; iRCMImg < this->inputRCMImages.size(); ++iRCMImg)
{
totalNumOfInputRCMParameters += this->inputRCMImages[iRCMImg]->nvox;
}
std::cout << "Total number of input correspondence model parameters: " << totalNumOfInputRCMParameters << std::endl;
for (this->currentLevel = 0; this->currentLevel < numberOfLevelsToPerform; ++this->currentLevel)
{
this->correspondenceModel->InitialiseLevel( this->currentLevel );
/// Todo: Remove transform. Does not need to be a member variable!
this->transform->InitialiseLevel( this->currentLevel );
unsigned int numberOfCorrespondenceModelParameters = this->correspondenceModel->GetNumberOfParameters();
if (numberOfCorrespondenceModelParameters != totalNumOfInputRCMParameters)
{
std::cout << "Mismatch of parameter numer on level: " << this->currentLevel
<< " input: " << totalNumOfInputRCMParameters
<< " vs. expected: " << numberOfCorrespondenceModelParameters << std::endl;
continue;
}
else
{
std::cout << "Match of parameter numer on level: " << this->currentLevel << std::endl;
std::cout << "Processing will commence on this level: " << this->currentLevel << std::endl;
break;
}
}
this->correspondenceModel->SetParameters( this->inputRCMImages );
}
// Initialise the image similarity measure
// Currently only SSD supported
this->similarityMeasure = std::make_shared<SSDImageSimilarity>();
// Initialise the image acquisition
switch (this->dynamicImageDataType)
{
case SAME_RES_AS_STATIC:
{
auto noImageAcquisition = std::make_shared<NoImageAcquisition>();
this->imageAcquisition = noImageAcquisition;
break;
}
case LOWER_RES_THAN_STATIC:
{
auto lowResImageAcquisition = std::make_shared<LowResolutionImageAcquisition>();
this->imageAcquisition = lowResImageAcquisition;
break;
}
default:
// Defaults to no-image-acquisition simulation
auto noImageAcquisition = std::make_shared<NoImageAcquisition>();
this->imageAcquisition = noImageAcquisition;
break;
}
this->initialised = true;
}
//--------------------------
// Supremo::CheckParameters
//--------------------------
void Supremo::CheckParameters()
{
// Check the reference image
if (this->referenceStateImage == nullptr)
{
char msg[200];
sprintf_s( msg, "Reference state image was not set." );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
// Check all dynamic images
for ( unsigned int i = 0; i < this->numberOfDynamicImages; ++i )
{
if ( this->allDynamicImages[i] == nullptr )
{
char msg[200];
sprintf_s( msg, "Dynamic image %i was not set.", i );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
}
// Check if the image that defines the space was set, otherwise use the reference state image
if (this->defSpaceImage == nullptr)
{
this->defSpaceImage = this->referenceStateImage;
}
// number of levels and number of levels to perform
if ( this->numberOfLevels <= 0 )
{
char msg[200];
sprintf_s( msg, "Number of levels was set to %i, but has to be larger than zero.", this->numberOfLevels );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
if ( this->numberOfLevelsToPerform <= 0 )
{
char msg[200];
sprintf_s( msg, "Number of levels to perform was set to %i, but has to be larger than zero.", this->numberOfLevelsToPerform );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
// Check the b-spline control-point spacing
// Set the spacing along y and z if undefined. Their values are set to match
// the spacing along the x axis
if (this->bSplineCPGSpacing[0] != this->bSplineCPGSpacing[0])
{
char msg[200];
sprintf_s( msg, "B-spline control point spacing was set to undefined value." );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
if (this->bSplineCPGSpacing[1] != this->bSplineCPGSpacing[1]) this->bSplineCPGSpacing[1] = this->bSplineCPGSpacing[0];
if (this->bSplineCPGSpacing[2] != this->bSplineCPGSpacing[2]) this->bSplineCPGSpacing[2] = this->bSplineCPGSpacing[0];
// Check that the number of surrogate signals is geq 1
if ( this->numberOfSurrogateSignals <= 1 )
{
char msg[200];
sprintf_s( msg, "Number of surrogate signals must not be lower than 1." );
supremo_print_error( msg );
supremo_exit( 1, __FILE__, __LINE__ );
}
//check if maxSwitchIterationNumber has been set (will be -1 if not)
//if not set to 10 if motion compensated reconstruction is being used, to 1 if not
if (this->maxSwitchIterationNumber < 0)
{
if (this->mocoReconstructor == nullptr)
this->maxSwitchIterationNumber = 1;
else
this->maxSwitchIterationNumber = 10;
}
}
//----------------------------------------
// Supremo::DisplayCurrentLevelParameters
//----------------------------------------
void Supremo::DisplayCurrentLevelParameters(unsigned int levelIn)
{
printf( "Current level: %i / %i\n", levelIn+1, this->numberOfLevelsToPerform );
// Display the reference state image parameters
printf( "Reference state image\n");
printf( "\t* image dimension: %i x %i x %i\n",
this->currentReferenceStateImage->nx,
this->currentReferenceStateImage->ny,
this->currentReferenceStateImage->nz );
printf( "\t* image spacing: %g x %g x %g mm\n\n",
this->currentReferenceStateImage->dx,
this->currentReferenceStateImage->dy,
this->currentReferenceStateImage->dz );
// Display the transoformation parameters
this->transform->DisplayTransformationParameters();
// Display the dynamic image parameters
printf( "1st Dynamic image\n");
printf( "\t* image dimension: %i x %i x %i\n",
this->allDynamicPyramids[0]->GetLevel( levelIn )->nx,
this->allDynamicPyramids[0]->GetLevel( levelIn )->ny,
this->allDynamicPyramids[0]->GetLevel( levelIn )->nz );
printf( "\t* image spacing: %g x %g x %g mm\n",
this->allDynamicPyramids[0]->GetLevel( levelIn )->dx,
this->allDynamicPyramids[0]->GetLevel( levelIn )->dy,
this->allDynamicPyramids[0]->GetLevel( levelIn )->dz );
#ifdef _DEBUG
for (unsigned int n = 0; n < this->numberOfDynamicImages; ++n)
{
printf( "Dynamic image: %i\n", n );
printf( "\t* image dimension: %i x %i x %i\n",
this->allDynamicPyramids[n]->GetLevel( levelIn )->nx,
this->allDynamicPyramids[n]->GetLevel( levelIn )->ny,
this->allDynamicPyramids[n]->GetLevel( levelIn )->nz );
printf( "\t* image spacing: %g x %g x %g\n",
this->allDynamicPyramids[n]->GetLevel( levelIn )->dx,
this->allDynamicPyramids[n]->GetLevel( levelIn )->dy,
this->allDynamicPyramids[n]->GetLevel( levelIn )->dz );
if (this->allDynamicPyramids[n]->GetLevel(levelIn)->sform_code>0)
reg_mat44_disp( &(this->allDynamicPyramids[n]->GetLevel( levelIn )->sto_xyz), (char *)"\t* sform matrix" );
else reg_mat44_disp( &(this->allDynamicPyramids[n]->GetLevel( levelIn )->qto_xyz), (char *)"\t* qform matrix" );
}
#endif
return;
}
void Supremo::SaveInterMCRToImage( nifti_image* mcrImage )
{
// write the reconstructed image to the defined destination
if (!this->outputInterMCRFolder.empty())
{
std::ostringstream osOutFileName;
osOutFileName << this->outputInterMCRFolder << "/MCR_" << this->levelID << ".nii.gz";
osOutFileName.str().c_str();
reg_io_WriteImageFile( mcrImage, osOutFileName.str().c_str() );
}
}
| [
"b.eiben@ucl.ac.uk"
] | b.eiben@ucl.ac.uk |
7f59b0341fde9343f819361972f743e325847bcf | 0298da594869a4e8e994ea3c3ce4e16add4534ea | /Atcoder/ABC/A/Four_Digits.cpp | ee8a0bfa6d1609f05b3085d684d62f8b24a9d392 | [] | no_license | tsuyosshi/competitive-programming | 2d5c749aa115e11f8f64e58a2cba6e322a3ffc73 | ed7c696081fd73710ab50b0803153e79159f4eda | refs/heads/master | 2023-08-16T03:10:19.989027 | 2021-10-24T06:19:55 | 2021-10-24T06:19:55 | 264,047,491 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | cpp | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define ALL(x) (x).begin(),(x).end()
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
typedef pair<int,int> PI;
typedef pair<int,pair<int,int>> PII;
static const int INF=1010000000000000017LL;
static const double eps=1e-12;
static const double pi=3.14159265358979323846;
static const int dx[4]={1,-1,0,0};
static const int dy[4]={0,0,1,-1};
static const int ddx[8]={1,-1,0,0,1,1,-1,-1};
static const int ddy[8]={0,0,1,-1,1,-1,1,-1};
template<class T> inline bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;}
template<class T> inline bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;}
string N;
signed main(){
cin>>N;
while(N.size()<4){
N='0'+N;
}
cout<<N<<endl;
} | [
"koutarou1276@yahoo.co.jp"
] | koutarou1276@yahoo.co.jp |
1c553b0e7fbc280d88e62481248080536d97e231 | 4e9aa6d8635d6bfcbaeecbb9420ebdc4c4489fba | /QtTest/WildMagic/Wm5Mathematics/Wm5ApprCircleFit2.h | f22fd2163609d419eaea8d4c7e756d26ff1a228c | [] | no_license | softwarekid/myexercise | 4daf73591917c8ba96f81e620fd2c353323a1ae5 | 7bea007029c4c656c49490a69062648797084117 | refs/heads/master | 2021-01-22T11:47:01.421922 | 2014-03-15T09:47:41 | 2014-03-15T09:47:41 | 18,024,710 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,302 | h | // Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.1 (2010/10/01)
#ifndef WM5APPRCIRCLEFIT2_H
#define WM5APPRCIRCLEFIT2_H
#include "Wm5MathematicsLIB.h"
#include "Wm5Circle2.h"
namespace Wm5
{
// Least-squares fit of a circle to a set of points. A successful fit is
// indicated by the return value of 'true'. If the return value is 'false',
// the number of iterations was exceeded. Try increasing the maximum number
// of iterations.
//
// If initialCenterIsAverage is set to 'true', the initial guess for the
// circle center is the average of the data points. If the data points are
// clustered along a small arc, CircleFit2 is very slow to converge. If
// initialCenterIsAverage is set to 'false', the initial guess for the
// circle center is computed using a least-squares estimate of the
// coefficients for a quadratic equation that represents a circle. This
// approach tends to converge rapidly.
template <typename Real> WM5_MATHEMATICS_ITEM
bool CircleFit2 (int numPoints, const Vector2<Real>* points,
int maxIterations, Circle2<Real>& circle, bool initialCenterIsAverage);
}
#endif
| [
"anheihb03dlj@163.com"
] | anheihb03dlj@163.com |
9f358df6e5a4615b79c4e882a300dfac2fce4809 | c2e2c3e5d531a58750457dda6fc33f72ebcb4e74 | /Include/Mesh.h | 3c6920b3271eb87469a8ea034070396c071335a3 | [
"MIT"
] | permissive | CS3141Team1/modeler3d | 5f34a53521f32ab38e675ce433612e19f9d4b8a8 | 1f5bb3a16cdfc25db1081d8df461685385fa88c4 | refs/heads/master | 2021-08-19T22:31:49.272072 | 2017-11-27T16:10:59 | 2017-11-27T16:10:59 | 105,296,723 | 1 | 3 | null | 2017-11-27T14:49:00 | 2017-09-29T16:56:42 | C++ | UTF-8 | C++ | false | false | 1,131 | h | #pragma once
#include <vector>
#include "Math/ModelerMath.h"
#include "IGraphicsDevice.h"
#include "VertexFormat.h"
namespace Video
{
/**
* Vertex for a mesh
*
* @author Nicholas Hamilton
*/
struct MeshVertex
{
Core::Math::Vector3f Position;
Core::Math::Vector3f Normal;
};
/**
* Holds mesh data
*
* TODO finish
*
* @author Nicholas Hamilton
*/
class Mesh
{
public:
Mesh(IGraphicsDevice* mGraphics);
~Mesh();
/**
* Get pointer to position data
*/
Core::Math::Vector3f* GetPositions() { return &mPositions[0]; }
/**
* Get pointer to position data
*/
const Core::Math::Vector3f* GetPositions() const { return &mPositions[0]; }
/**
* Get pointer to normal data
*/
Core::Math::Vector3f* GetNormals() { return &mNormals[0]; }
/**
* Get pointer to normal data
*/
const Core::Math::Vector3f* GetNormals() const { return &mNormals[0]; }
private:
std::vector<Core::Math::Vector3f> mPositions;
std::vector<Core::Math::Vector3f> mNormals;
IGraphicsDevice* mGraphics;
IVertexBuffer* mVbo;
IGeometry* mGeom;
};
}
| [
"nrhamilt@mtu.edu"
] | nrhamilt@mtu.edu |
f871536398a05b70df01f815f727940384c67e40 | a06515f4697a3dbcbae4e3c05de2f8632f8d5f46 | /corpus/taken_from_cppcheck_tests/stolen_9795.cpp | 5758606efdffa509de54bdc4f167fec4a0168933 | [] | no_license | pauldreik/fuzzcppcheck | 12d9c11bcc182cc1f1bb4893e0925dc05fcaf711 | 794ba352af45971ff1f76d665b52adeb42dcab5f | refs/heads/master | 2020-05-01T01:55:04.280076 | 2019-03-22T21:05:28 | 2019-03-22T21:05:28 | 177,206,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | int *test(int *Z)
{
int *Q=NULL;
if (Z) {
Q = Z;
}
else {
try {
} catch(...) {
}
}
*Q=1;
return Q;
} | [
"github@pauldreik.se"
] | github@pauldreik.se |
770d76c7ca79457a6dcf8ab59e034c7a07304d56 | 41943cc70147f9b4a65fec7515832bdc22050d39 | /google/cloud/storage/internal/curl_client.h | 262c672b512299917024eac767617a2bcc60fc78 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lian-hu/google-cloud-cpp | e98391c74724d19049c02fad3a4c620410e33681 | e9f5f2383a9d8d64e5543b2ee97049723ea217ee | refs/heads/master | 2023-08-08T01:08:52.085102 | 2019-03-11T19:19:51 | 2019-03-11T19:19:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,594 | h | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_CURL_CLIENT_H_
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_CURL_CLIENT_H_
#include "google/cloud/internal/random.h"
#include "google/cloud/storage/internal/curl_handle_factory.h"
#include "google/cloud/storage/internal/raw_client.h"
#include "google/cloud/storage/internal/resumable_upload_session.h"
#include "google/cloud/storage/oauth2/credentials.h"
#include <mutex>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
class CurlRequestBuilder;
/**
* Implements the low-level RPCs to Google Cloud Storage using libcurl.
*/
class CurlClient : public RawClient,
public std::enable_shared_from_this<CurlClient> {
public:
static std::shared_ptr<CurlClient> Create(ClientOptions options) {
// Cannot use std::make_shared because the constructor is private.
return std::shared_ptr<CurlClient>(new CurlClient(std::move(options)));
}
static std::shared_ptr<CurlClient> Create(
std::shared_ptr<oauth2::Credentials> credentials) {
return Create(ClientOptions(std::move(credentials)));
}
CurlClient(CurlClient const& rhs) = delete;
CurlClient(CurlClient&& rhs) = delete;
CurlClient& operator=(CurlClient const& rhs) = delete;
CurlClient& operator=(CurlClient&& rhs) = delete;
using LockFunction =
std::function<void(CURL*, curl_lock_data, curl_lock_access)>;
using UnlockFunction = std::function<void(CURL*, curl_lock_data)>;
//@{
/// @name Implement the CurlResumableSession operations.
// Note that these member functions are not inherited from RawClient, they are
// called only by `CurlResumableUploadSession`, because the retry loop for
// them is very different from the standard retry loop. Also note that these
// are virtual functions only because we need to override them in the unit
// tests.
virtual StatusOr<ResumableUploadResponse> UploadChunk(
UploadChunkRequest const&);
virtual StatusOr<ResumableUploadResponse> QueryResumableUpload(
QueryResumableUploadRequest const&);
//@}
ClientOptions const& client_options() const override { return options_; }
StatusOr<ListBucketsResponse> ListBuckets(
ListBucketsRequest const& request) override;
StatusOr<BucketMetadata> CreateBucket(
CreateBucketRequest const& request) override;
StatusOr<BucketMetadata> GetBucketMetadata(
GetBucketMetadataRequest const& request) override;
StatusOr<EmptyResponse> DeleteBucket(DeleteBucketRequest const&) override;
StatusOr<BucketMetadata> UpdateBucket(
UpdateBucketRequest const& request) override;
StatusOr<BucketMetadata> PatchBucket(
PatchBucketRequest const& request) override;
StatusOr<IamPolicy> GetBucketIamPolicy(
GetBucketIamPolicyRequest const& request) override;
StatusOr<IamPolicy> SetBucketIamPolicy(
SetBucketIamPolicyRequest const& request) override;
StatusOr<TestBucketIamPermissionsResponse> TestBucketIamPermissions(
TestBucketIamPermissionsRequest const& request) override;
StatusOr<BucketMetadata> LockBucketRetentionPolicy(
LockBucketRetentionPolicyRequest const& request) override;
StatusOr<ObjectMetadata> InsertObjectMedia(
InsertObjectMediaRequest const& request) override;
StatusOr<ObjectMetadata> GetObjectMetadata(
GetObjectMetadataRequest const& request) override;
StatusOr<std::unique_ptr<ObjectReadStreambuf>> ReadObject(
ReadObjectRangeRequest const&) override;
StatusOr<std::unique_ptr<ObjectWriteStreambuf>> WriteObject(
InsertObjectStreamingRequest const&) override;
StatusOr<ListObjectsResponse> ListObjects(
ListObjectsRequest const& request) override;
StatusOr<EmptyResponse> DeleteObject(
DeleteObjectRequest const& request) override;
StatusOr<ObjectMetadata> UpdateObject(
UpdateObjectRequest const& request) override;
StatusOr<ObjectMetadata> PatchObject(
PatchObjectRequest const& request) override;
StatusOr<ObjectMetadata> ComposeObject(
ComposeObjectRequest const& request) override;
StatusOr<std::unique_ptr<ResumableUploadSession>> CreateResumableSession(
ResumableUploadRequest const& request) override;
StatusOr<std::unique_ptr<ResumableUploadSession>> RestoreResumableSession(
std::string const& session_id) override;
StatusOr<ListBucketAclResponse> ListBucketAcl(
ListBucketAclRequest const& request) override;
StatusOr<ObjectMetadata> CopyObject(
CopyObjectRequest const& request) override;
StatusOr<BucketAccessControl> CreateBucketAcl(
CreateBucketAclRequest const&) override;
StatusOr<BucketAccessControl> GetBucketAcl(
GetBucketAclRequest const&) override;
StatusOr<EmptyResponse> DeleteBucketAcl(
DeleteBucketAclRequest const&) override;
StatusOr<BucketAccessControl> UpdateBucketAcl(
UpdateBucketAclRequest const&) override;
StatusOr<BucketAccessControl> PatchBucketAcl(
PatchBucketAclRequest const&) override;
StatusOr<ListObjectAclResponse> ListObjectAcl(
ListObjectAclRequest const& request) override;
StatusOr<ObjectAccessControl> CreateObjectAcl(
CreateObjectAclRequest const&) override;
StatusOr<EmptyResponse> DeleteObjectAcl(
DeleteObjectAclRequest const&) override;
StatusOr<ObjectAccessControl> GetObjectAcl(
GetObjectAclRequest const&) override;
StatusOr<ObjectAccessControl> UpdateObjectAcl(
UpdateObjectAclRequest const&) override;
StatusOr<ObjectAccessControl> PatchObjectAcl(
PatchObjectAclRequest const&) override;
StatusOr<RewriteObjectResponse> RewriteObject(
RewriteObjectRequest const&) override;
StatusOr<ListDefaultObjectAclResponse> ListDefaultObjectAcl(
ListDefaultObjectAclRequest const& request) override;
StatusOr<ObjectAccessControl> CreateDefaultObjectAcl(
CreateDefaultObjectAclRequest const&) override;
StatusOr<EmptyResponse> DeleteDefaultObjectAcl(
DeleteDefaultObjectAclRequest const&) override;
StatusOr<ObjectAccessControl> GetDefaultObjectAcl(
GetDefaultObjectAclRequest const&) override;
StatusOr<ObjectAccessControl> UpdateDefaultObjectAcl(
UpdateDefaultObjectAclRequest const&) override;
StatusOr<ObjectAccessControl> PatchDefaultObjectAcl(
PatchDefaultObjectAclRequest const&) override;
StatusOr<ServiceAccount> GetServiceAccount(
GetProjectServiceAccountRequest const&) override;
StatusOr<ListHmacKeysResponse> ListHmacKeys(
ListHmacKeysRequest const&) override;
StatusOr<CreateHmacKeyResponse> CreateHmacKey(
CreateHmacKeyRequest const&) override;
StatusOr<ListNotificationsResponse> ListNotifications(
ListNotificationsRequest const&) override;
StatusOr<NotificationMetadata> CreateNotification(
CreateNotificationRequest const&) override;
StatusOr<NotificationMetadata> GetNotification(
GetNotificationRequest const&) override;
StatusOr<EmptyResponse> DeleteNotification(
DeleteNotificationRequest const&) override;
StatusOr<std::string> AuthorizationHeader(
std::shared_ptr<google::cloud::storage::oauth2::Credentials> const&);
void LockShared();
void UnlockShared();
protected:
// The constructor is private because the class must always be created
// as a shared_ptr<>.
explicit CurlClient(ClientOptions options);
private:
/// Setup the configuration parameters that do not depend on the request.
Status SetupBuilderCommon(CurlRequestBuilder& builder, char const* method);
/// Applies the common configuration parameters to @p builder.
template <typename Request>
Status SetupBuilder(CurlRequestBuilder& builder, Request const& request,
char const* method);
StatusOr<ObjectMetadata> InsertObjectMediaXml(
InsertObjectMediaRequest const& request);
StatusOr<std::unique_ptr<ObjectReadStreambuf>> ReadObjectXml(
ReadObjectRangeRequest const& request);
StatusOr<std::unique_ptr<ObjectWriteStreambuf>> WriteObjectXml(
InsertObjectStreamingRequest const& request);
/// Insert an object using uploadType=multipart.
StatusOr<ObjectMetadata> InsertObjectMediaMultipart(
InsertObjectMediaRequest const& request);
std::string PickBoundary(std::string const& text_to_avoid);
/// Insert an object using uploadType=media.
StatusOr<ObjectMetadata> InsertObjectMediaSimple(
InsertObjectMediaRequest const& request);
/// Upload an object using uploadType=simple.
StatusOr<std::unique_ptr<ObjectWriteStreambuf>> WriteObjectSimple(
InsertObjectStreamingRequest const& request);
/// Upload an object using uploadType=resumable.
StatusOr<std::unique_ptr<ObjectWriteStreambuf>> WriteObjectResumable(
InsertObjectStreamingRequest const& request);
template <typename RequestType>
StatusOr<std::unique_ptr<ResumableUploadSession>>
CreateResumableSessionGeneric(RequestType const& request);
ClientOptions options_;
std::string storage_endpoint_;
std::string upload_endpoint_;
std::string xml_upload_endpoint_;
std::string xml_download_endpoint_;
std::mutex mu_;
CurlShare share_ /* GUARDED_BY(mu_) */;
google::cloud::internal::DefaultPRNG generator_;
// The factories must be listed *after* the CurlShare. libcurl keeps a
// usage count on each CURLSH* handle, which is only released once the CURL*
// handle is *closed*. So we want the order of destruction to be (1)
// factories, as that will delete all the CURL* handles, and then (2) CURLSH*.
// To guarantee this order just list the members in the opposite order.
std::shared_ptr<CurlHandleFactory> storage_factory_;
std::shared_ptr<CurlHandleFactory> upload_factory_;
std::shared_ptr<CurlHandleFactory> xml_upload_factory_;
std::shared_ptr<CurlHandleFactory> xml_download_factory_;
};
} // namespace internal
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_CURL_CLIENT_H_
| [
"noreply@github.com"
] | noreply@github.com |
4657f83903f1eb484e65532b080aa4ac09e6d330 | 5af9fec13724667b3d20e8669238426855b97d2b | /_3_5_12v_voltage_monitorwLCD/_3_5_12v_voltage_monitor.ino | 3a90b523a1c2481cea40040c710a081aab3de221 | [] | no_license | skull-candy/Arduino | b8153d3e81effbce484a7d9fdf537953b9b48edb | 2cea06352f2e7d35a32e4efbac762c24363666c3 | refs/heads/master | 2021-01-10T04:12:57.247521 | 2019-10-22T06:37:35 | 2019-10-22T06:37:35 | 52,384,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | ino | /*Arduino Controlled Voltage Monitor
*/
#include <LiquidCrystal.h>
//Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup()
{
lcd.begin(16, 2); //Set up the LCD's number of columns and rows
lcd.print("Internal Votlage"); //First line opening message
lcd.setCursor(0, 1);
lcd.print("Adruino Minitor"); //Second line opening message
delay(5000);
lcd.setCursor(0, 1); //Clear bottom line
lcd.print(" ");
lcd.setCursor(0,0);
lcd.print(" 3v 5v 12v "); //Update top line readout
}
void loop()
{
lcd.setCursor(0, 1);
float f = analogRead(0) * 4.88 / 1023; // 3.3 => 9.9
lcd.print(f, 2); // print float with two decimals
lcd.setCursor(6, 1);
float g = analogRead(1) * 8.5 / 1023; // 5.0 => 9.9
lcd.print(g, 2);
lcd.setCursor(11, 1);
float h = analogRead(2) * 17.25 / 1023; // 12.0 => 25.0
lcd.print(h, 2);
delay(500);
}
| [
"ahsan@alahsan.xyz"
] | ahsan@alahsan.xyz |
8615e18d36e0fc9010d5952907860f96d9ba3a8e | 03ab3cc87d2eeb9b4081a1e4bc9c74bffad33809 | /glimac/src/TrackballCamera.cpp | e1d7b56c5e4d829a60ad13775ebe5564e53d7a91 | [] | no_license | ClawsDevlp/world_Imaker | 8b3f2ad3c0342949ff521455fabb8d9611d7bd72 | ef7229c1217c94abef2f39f1084edde2f8ec44ca | refs/heads/master | 2020-11-25T10:34:26.374211 | 2020-01-10T14:42:07 | 2020-01-10T14:42:07 | 220,536,065 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include "glimac/TrackballCamera.hpp"
namespace glimac {
float TrackballCamera::getDistance() {
return m_fDistance;
}
float TrackballCamera::getAngleX() {
return m_fAngleX;
}
float TrackballCamera::getAngleY() {
return m_fAngleY;
}
void TrackballCamera::moveFront(const float delta){
// if(delta > 0) {
m_fDistance += delta;
// } else
}
void TrackballCamera::rotateLeft(const float degrees){
m_fAngleY += degrees;
}
void TrackballCamera::rotateUp(const float degrees){
m_fAngleX += degrees;
}
glm::mat4 TrackballCamera::getViewMatrix() const {
glm::mat4 ViewMatrix;
ViewMatrix = glm::translate(ViewMatrix, glm::vec3(0, 0, -m_fDistance)); // Translation
ViewMatrix = glm::rotate(ViewMatrix, glm::radians(m_fAngleX), glm::vec3(1, 0, 0)); // Rotation
ViewMatrix = glm::rotate(ViewMatrix, glm::radians(m_fAngleY), glm::vec3(0, 1, 0)); // Rotation
return ViewMatrix;
}
} | [
"clara.daigmorte@gmail.com"
] | clara.daigmorte@gmail.com |
ab92074720bad412a40a267d183f4fa0e34150ce | 8f451ce13a8bc4861f107787e3d78c719036bbd8 | /src/adobe_serial_tweak.cc | e9dcc11fe16989064f64f022350e312c5f4e33af | [] | no_license | proprietary/adobe_cc_serial_tweak | d590e216a9a76d4382be4f76400be628cda11a9d | 5917fe4ea3dbf1b78f4f3460e74f9911e9c07dc6 | refs/heads/master | 2020-04-26T09:49:27.014076 | 2019-03-02T16:07:55 | 2019-03-02T16:07:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,171 | cc | #include <string>
#include <sstream>
#include <string_view>
#include <fstream>
#include <rapidxml/rapidxml.hpp>
#include <rapidxml/rapidxml_print.hpp>
constexpr std::string_view default_filename {"/Library/Application Support/Adobe/Adobe Photoshop CC 2018/AMT/application.xml"};
int main(int argc, char* argv[]) {
const std::string_view filename {argc > 1 ? argv[1] : default_filename};
rapidxml::xml_document<char> doc;
std::string straight_text{};
{
std::fstream f {default_filename.data(), std::ios::in};
std::stringstream buf{};
buf << f.rdbuf();
straight_text = buf.str();
}
doc.parse<0>(straight_text.data());
auto other_block = doc.first_node()->first_node("Other");
if (other_block == nullptr) return 1;
for (auto data_element = other_block->first_node(); data_element;
data_element = data_element->next_sibling()) {
if (std::string_view{data_element->first_attribute()->value()} ==
std::string_view{"TrialSerialNumber"}) {
const std::string_view preexisting_trial_key {data_element->value()};
std::string new_trial_key{};
{
std::stringstream buf;
buf <<
preexisting_trial_key.substr(0, preexisting_trial_key.length() - 5)
<< std::atoi(preexisting_trial_key.end() - 5) + 1;
new_trial_key = buf.str();
}
constexpr std::string_view data_node_name {"Data"};
auto new_node = doc.allocate_node(rapidxml::node_element, data_node_name.data(), new_trial_key.c_str(), data_node_name.length());
auto new_attr = doc.allocate_attribute("key", "TrialSerialNumber");
new_node->append_attribute(new_attr);
other_block->append_node(new_node);
other_block->remove_node(data_element);
// RapidXML doesn't re-serialize with the first line, so we have to manually retrieve it
const auto first_line =
std::string_view{&straight_text[0],
straight_text.find('\n', 0)};
// Write the new XML to file
std::fstream f {filename.data(), std::ios::out | std::ios::trunc};
f << first_line << '\n' << doc << '\n';
doc.clear();
break;
}
}
return 0;
}
| [
"zelly@outlook.com"
] | zelly@outlook.com |
d4627db6a57403937e1da79e3a76a2d76d94363f | 8c3ca0b6f4814bdf0167b3735f7b2de0965a0070 | /Lib/PortableWildcards.h | 411b2fcb82c932876834e736d48762cf04d3c84b | [
"MIT"
] | permissive | olivier-kozak/PortableWildcards | 96e554bbdd4a1447b7c91cf49fdb86b550056acb | f7dac2508d1c6833f997546a1debafe686826a3c | refs/heads/master | 2020-03-25T07:17:16.351125 | 2018-08-04T18:16:43 | 2018-08-04T18:16:43 | 143,552,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | h | #ifndef PORTABLE_WILDCARDS_H
#define PORTABLE_WILDCARDS_H
#include <string>
namespace PortableWildcards {
bool matches(const std::string &string, const std::string &pattern);
}
#endif //PORTABLE_WILDCARDS_H
| [
"olivier.kozak@gmail.com"
] | olivier.kozak@gmail.com |
de6b20f0bd83229bfdc3ee16b93935d0c6b2008d | 5c52826dbc530e3b409d47b5749a1ccf5fb0a250 | /HackerRank/STRINGS/SHERLOCKVALID2.cpp | 35e5a2050a9f328cd8c3e338e70b7608d265c5fd | [] | no_license | rahulrj/MTV | 5905595cf5b5dfb1c029e485a5094945e0c0a0db | 646a496e3e30bb2351c10bab74cd47283c31a999 | refs/heads/master | 2021-01-12T03:37:06.375283 | 2017-12-22T22:30:01 | 2017-12-22T22:30:01 | 78,239,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,878 | cpp | #include<bits/stdc++.h>
#define assn(n,a,b) assert(n<=b and n>=a)
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define SET(a,b) memset(a,b,sizeof(a))
#define LET(x,a) __typeof(a) x(a)
#define TR(v,it) for( LET(it,v.begin()) ; it != v.end() ; it++)
#define repi(i,n) for(int i=0; i<(int)n;i++)
#define sd(n) scanf("%d",&n)
#define sl(n) scanf("%lld",&n)
#define sortv(a) sort(a.begin(),a.end())
#define all(a) a.begin(),a.end()
#define DRT() int t; cin>>t; while(t--)
#define TRACE
using namespace std;
//FILE *fin = freopen("in","r",stdin);
//FILE *fout = freopen("out","w",stdout);
#ifdef TRACE
#define trace1(x) cerr << #x << ": " << x << endl;
#define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;
#define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl;
#else
#define trace1(x)
#define trace2(x, y)
#define trace3(x, y, z)
#define trace4(a, b, c, d)
#define trace5(a, b, c, d, e)
#define trace6(a, b, c, d, e, f)
#endif
typedef long long LL;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector< PII > VPII;
int main()
{
set<int> myset;
string s;
cin >> s;
string ans="NO";
//cnt[i] stores frequency of character i+'a'
int cnt[26]={},n=s.length();
assn(n,1,100000);
for(int i=0; i<n; i++){
//increasing frequency
cnt[s[i]-'a']++;
assn(s[i]-'a',0,25);
}
//for i>=0, it means we are removing character i+'a', if possible
//case i=-1 is for checking if string is already valid
for(int i=-1; i<26; i++){
//if character i+'a' is not present in string continue
if(i>=0 and cnt[i]==0)continue;
//reduce frequency
if(i>=0)cnt[i]--;
//if we insert all positive frequencies into a set, it should contain
//only 1 element if string is now valid
set<int> myset;
//insert remaining positive frequencies into set
for(int j=0; j<26; j++){
if(cnt[j])myset.insert(cnt[j]);
}
//if set size is 1, string is now valid
if(myset.size()==1)ans="YES";
//increase the frequency back again
if(i>=0)cnt[i]++;
}
cout << ans << endl;
return 0;
}
| [
"rahul.raja@inmobi.com"
] | rahul.raja@inmobi.com |
087762f1b25538bfab70a3f8f3aa1a64970e2e1c | 5bb277d676944b89bd6d5e7ba6a4bc6635cd1845 | /SRM 652/ValueOfString.cpp | 38fc8f27fe1cb406024de454b22ea84c9f6bf7f0 | [] | no_license | tanmesh/topcoder_code | 6b63f7176322daf0e0d19bef849bffae4f2cec74 | 0cc1cf1861ed56d8c7d79f7e4e975d5045438ca6 | refs/heads/master | 2020-05-22T01:06:12.100903 | 2018-07-26T06:29:39 | 2018-07-26T06:29:39 | 62,441,732 | 1 | 0 | null | 2018-07-29T10:49:55 | 2016-07-02T08:30:19 | C++ | UTF-8 | C++ | false | false | 3,270 | cpp | #include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <typeinfo>
#include <fstream>
using namespace std;
class ValueOfString {
public:
int findValue(string s) {
int ans=0;
vector<int> arr;
for(int i=0;i<s.length();++i){
int cnt=0;
for(int j=0;j<s.length();++j){
if(s[i]>=s[j]) ++cnt;
}
arr.push_back(cnt);
}
cout << endl;
for(int i=0;i<s.length();++i){
// cout << s[i]-'a'+1 << " " << arr[i] << endl;
ans+=(s[i]-'a'+1)*arr[i];
}
return ans;
}
};
// CUT begin
ifstream data("ValueOfString.sample");
string next_line() {
string s;
getline(data, s);
return s;
}
template <typename T> void from_stream(T &t) {
stringstream ss(next_line());
ss >> t;
}
void from_stream(string &s) {
s = next_line();
}
template <typename T>
string to_string(T t) {
stringstream s;
s << t;
return s.str();
}
string to_string(string t) {
return "\"" + t + "\"";
}
bool do_test(string s, int __expected) {
time_t startClock = clock();
ValueOfString *instance = new ValueOfString();
int __result = instance->findValue(s);
double elapsed = (double)(clock() - startClock) / CLOCKS_PER_SEC;
delete instance;
if (__result == __expected) {
cout << "PASSED!" << " (" << elapsed << " seconds)" << endl;
return true;
}
else {
cout << "FAILED!" << " (" << elapsed << " seconds)" << endl;
cout << " Expected: " << to_string(__expected) << endl;
cout << " Received: " << to_string(__result) << endl;
return false;
}
}
int run_test(bool mainProcess, const set<int> &case_set, const string command) {
int cases = 0, passed = 0;
while (true) {
if (next_line().find("--") != 0)
break;
string s;
from_stream(s);
next_line();
int __answer;
from_stream(__answer);
cases++;
if (case_set.size() > 0 && case_set.find(cases - 1) == case_set.end())
continue;
cout << " Testcase #" << cases - 1 << " ... ";
if ( do_test(s, __answer)) {
passed++;
}
}
if (mainProcess) {
cout << endl << "Passed : " << passed << "/" << cases << " cases" << endl;
int T = time(NULL) - 1473067367;
double PT = T / 60.0, TT = 75.0;
cout << "Time : " << T / 60 << " minutes " << T % 60 << " secs" << endl;
cout << "Score : " << 250 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) << " points" << endl;
}
return 0;
}
int main(int argc, char *argv[]) {
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
set<int> cases;
bool mainProcess = true;
for (int i = 1; i < argc; ++i) {
if ( string(argv[i]) == "-") {
mainProcess = false;
} else {
cases.insert(atoi(argv[i]));
}
}
if (mainProcess) {
cout << "ValueOfString (250 Points)" << endl << endl;
}
return run_test(mainProcess, cases, argv[0]);
}
// CUT end
| [
"tanmeshnm@gmail.com"
] | tanmeshnm@gmail.com |
6669228ff80a79265b82c21d301bd208abaaf3aa | 380e7c42037c48a2fe22a359ea7cb167addea179 | /Temperature/temperature.cpp | c5c1b788d236bcdb73f5693dfab962cd86c9d7c2 | [] | no_license | sagar0698/CPP-Projects | 8cc5ad5cdc36f35aa6913f8c134358479f8d9def | 84324478ee94b5281dca650111d81c40d287b43a | refs/heads/master | 2020-09-26T02:56:56.834847 | 2020-01-06T08:24:12 | 2020-01-06T08:24:12 | 226,148,026 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,816 | cpp | /*C++ program that reads a temperature.txt file
and finds the lowest and highest temperatures,
then finds the average of the lowest and highest
temperatures, and finally writes the histogram to
the file report.txt*/
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
const int SIZE = 100;
int histogram[12] = { 0 };
int tempCount;
int count = 0;
int lowestTemperatureCount = 0;
int highestTemperatureCount = 0;
string date;
int highestTemperature[SIZE]; //Reads highest temeperature
int lowestTemperature[SIZE]; //Reads lowest temperature
int temperature;
//Assuming that the highest temperature is set at 50 degrees
int HIGH_TEMP = 50;
ifstream fileData;
fileData.open("temperature.txt");
if (!fileData)
{
cout << "File does not exist" << endl;
cout << "Enter a key to close the program" << endl;
cin.get();
exit(0);
}
fileData >> date; //read count of temperatures in the file
fileData >> tempCount; //read temepratures from file and store in temperatures
while (count < tempCount)
{
fileData >> temperature;
if (temperature >= HIGH_TEMP)
{
highestTemperature[highestTemperatureCount] = temperature;
highestTemperatureCount++;
count++;
}
else
{
lowestTemperature[lowestTemperatureCount] = temperature;
lowestTemperatureCount++;
count++;
}
}
/*increment the count of values in the corresponding histogram
from 1 to lowestTemeperature*/
for (int i = 0; i < lowestTemperatureCount; i++)
{
if (lowestTemperature[i] < 0)
histogram[0]++;
else if (lowestTemperature[i] > 0 && lowestTemperature[i] < 9)
histogram[1]++;
else if (lowestTemperature[i] >= 10 && lowestTemperature[i] < 19)
histogram[2]++;
else if (lowestTemperature[i] >= 20 && lowestTemperature[i] < 29)
histogram[3]++;
else if (lowestTemperature[i] >= 30 && lowestTemperature[i] < 39)
histogram[4]++;
else if (lowestTemperature[i] >= 40 && lowestTemperature[i] < 49)
histogram[5]++;
}
/*increment the coutn of values in the corresponding histogram*/
for (int i = 0; i < highestTemperatureCount; i++)
{
if (lowestTemperature[i] >= 50 && lowestTemperature[i] < 59)
histogram[6]++;
else if (lowestTemperature[i] >= 60 && lowestTemperature[i] < 69)
histogram[7]++;
else if (lowestTemperature[i] >= 70 && lowestTemperature[i] < 79)
histogram[8]++;
else if (lowestTemperature[i] >= 80 && lowestTemperature[i] < 89)
histogram[9]++;
else if (lowestTemperature[i] >= 90 && lowestTemperature[i] < 99)
histogram[10]++;
else if (lowestTemperature[i] > 100)
histogram[11]++;
}
/*writing data to the file report.txt*/
ofstream outData;
outData.open("report.txt");
/*set precision to 2 decimals*/
outData.precision(2);
outData.setf(ios::fixed);
outData.setf(ios::showpoint);
outData << "Lowest temperature: " << setw(5) << findLowestTemperature(lowestTemperature, lowestTemperatureCount) << endl;
outData << "Highest temperature: " << setw(5) << findHighestTemperatureAverage(highestTemperature, highestTemperatureCount) << endl;
outData << "Average of low temperature: " << setw(5) << findLowestTemperatureAverage(lowestTemperature, lowestTemperatureCount) << endl;
outData << "Average of high temperature: " << setw(5) << findHighestTemperatureAverage(highestTemperature, highestTemperatureCount) << endl;
/*writing the histogram to our file report.txt*/
outData << "Below 0: ";
for (int star = 1; star < histogram[0]; star++)
outData << "*";
outData << endl;
for (int index = 1; index = 12; index++)
{
outData << "[" << index << "," << index * 10 << "]:";
for (int star = 1; star < histogram[index]; star++)
outData << endl;
}
system("pause");
return 0;
}
/*returns the average of the lowest temperatures*/
float findLowestTemperatureAverage(int lowestTemperatures[], int size)
{
float sum = 0;
for (int index = 0; index < size; index++)
sum += lowestTemperatures[index];
return sum / size;
}
/*returns the average of the highest temperatures*/
float findHighestTemperatureAverage(int lowestTemperatures[], int size)
{
float sum = 0;
for (int index = 0; index < size; index++)
sum += lowestTemperatures[index];
return sum / size;
}
/*returns lowest temperature from the lowest temperature array*/
float findLowestTemperature(int temperatures[], int size)
{
float lowest = temperatures[0];
for (int index = 1; index < size; index++)
if (temperatures[index] < lowest)
lowest = temperatures[index];
return lowest;
}
/*returns lowest temperature from the highest temperature array*/
float findHighestTemperature(int temperatures[], int size)
{
float highest = temperatures[0];
for (int index = 1; index < size; index++)
if (temperatures[index] > highest)
highest = temperatures[index];
return highest;
}
| [
"noreply@github.com"
] | noreply@github.com |
687f769bae2e87449cbacda80926ddefad25f9bf | b30ce2bde2534904932266f67d93444360d21db2 | /Arduino/libraries/ros_lib/automotive_platform_msgs/SteeringCommand.h | d47aae461871ac8b230930d553ac3ee10791d885 | [] | no_license | MaxDeSantis/pid_ball_balancer_cbs | ee987b00474ec69d09ddc5f74bf9b9a3bc08f722 | 5266c1802631bdfce0425fbba75240a5f29c1c71 | refs/heads/main | 2023-04-07T15:12:24.028858 | 2021-04-18T16:44:02 | 2021-04-18T16:44:02 | 339,237,652 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,228 | h | #ifndef _ROS_automotive_platform_msgs_SteeringCommand_h
#define _ROS_automotive_platform_msgs_SteeringCommand_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "std_msgs/Header.h"
namespace automotive_platform_msgs
{
class SteeringCommand : public ros::Msg
{
public:
typedef std_msgs::Header _header_type;
_header_type header;
typedef float _steering_wheel_angle_type;
_steering_wheel_angle_type steering_wheel_angle;
SteeringCommand():
header(),
steering_wheel_angle(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->header.serialize(outbuffer + offset);
union {
float real;
uint32_t base;
} u_steering_wheel_angle;
u_steering_wheel_angle.real = this->steering_wheel_angle;
*(outbuffer + offset + 0) = (u_steering_wheel_angle.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_steering_wheel_angle.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_steering_wheel_angle.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_steering_wheel_angle.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->steering_wheel_angle);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->header.deserialize(inbuffer + offset);
union {
float real;
uint32_t base;
} u_steering_wheel_angle;
u_steering_wheel_angle.base = 0;
u_steering_wheel_angle.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_steering_wheel_angle.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_steering_wheel_angle.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_steering_wheel_angle.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->steering_wheel_angle = u_steering_wheel_angle.real;
offset += sizeof(this->steering_wheel_angle);
return offset;
}
const char * getType(){ return "automotive_platform_msgs/SteeringCommand"; };
const char * getMD5(){ return "f61fd13efbfee4ea479942d1f6acebc4"; };
};
}
#endif | [
"ctvmdesantis@cox.net"
] | ctvmdesantis@cox.net |
32bbe81ef3351ee1e8b96bd6a5b8916b5df78f34 | f1a2325795dcd90f940e45a3535ac3a0cb765616 | /development/TelecomServices/Monitoring/MON_IBETHStatus.h | 166cedc34a7d3313b702f9968db2e439800d2fcc | [] | no_license | MoonStart/Frame | 45c15d1e6febd7eb390b74b891bc5c40646db5de | e3a3574e5c243d9282778382509858514585ae03 | refs/heads/master | 2021-01-01T19:09:58.670794 | 2015-12-02T07:52:55 | 2015-12-02T07:52:55 | 31,520,344 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | h | //Copyright(c) Tellabs Transport Group. All rights reserved
#ifndef MON_IBETHSTATUS_H
#define MON_IBETHSTATUS_H
#include <CommonTypes/CT_Telecom.h>
#include <CommonTypes/CT_IBETH_Definitions.h>
#include "MON_Object.h"
class MON_IBETHStatus
: public MON_Object
{
public:
//Constructor.
MON_IBETHStatus(uint32 theIndex);
//Virtual destructor.
virtual ~MON_IBETHStatus();
// These methods are modifiers and accessors for
// the current state of the GCC Protocol Link
CT_IBETH_LinkState GetProtocolLinkState() const;
bool SetProtocolLinkState(CT_IBETH_LinkState theLinkState);
//Debug Methods
void Reset();
virtual void Display(FC_Stream& theStream);
protected:
//Serialization methods
virtual ostream& WriteObject( ostream& theStream );
virtual istream& ReadObject( istream& theStream );
virtual FC_Stream& WriteObjectBinary( FC_Stream& theStream );
virtual FC_Stream& ReadObjectBinary( FC_Stream& theStream );
private:
//The current state of the GCC Protocol Link.
CT_IBETH_LinkState myLinkState;
};
#endif
| [
"lijin303x@163.com"
] | lijin303x@163.com |
03bdaedbf07d50bcdd76b2bd9e4c2882ac08ea92 | f19016d752ce901373869f9e032c039a2a61da40 | /UAlbertaBot/Source/base/BuildingManager.cpp | 92d3a954b14e06292c566125688c415023a0ec63 | [
"Apache-2.0"
] | permissive | abeshry/StarcraftAI | 4480dce3a23ef862043a3b48f40c99728cb7759f | 2eca612783d1b4c06469885ebc3cce46cc0c6fce | refs/heads/master | 2021-01-10T14:45:28.221810 | 2015-09-30T01:27:59 | 2015-09-30T01:27:59 | 43,404,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,721 | cpp | #include "Common.h"
#include "BuildingManager.h"
BuildingManager::BuildingManager()
: debugMode(false)
, reservedMinerals(0)
, reservedGas(0)
, buildingSpace(1)
, totalBuildTasks(0)
{
}
// gets called every frame from GameCommander
void BuildingManager::update()
{
// Step through building logic, issue orders, manage data as necessary
//drawBuildingInformation(340, 50);
// check to see if assigned workers have died en route or while constructing
validateWorkersAndBuildings();
// assign workers to the unassigned buildings and label them 'planned'
assignWorkersToUnassignedBuildings();
// for each planned building, if the worker isn't constructing, send the command
constructAssignedBuildings();
// check to see if any buildings have started construction and update data structures
checkForStartedConstruction();
// if we are terran and a building is under construction without a worker, assign a new one
checkForDeadTerranBuilders();
// check to see if any buildings have completed and update data structures
checkForCompletedBuildings();
// draw some debug information
//BuildingPlacer::Instance().drawReservedTiles();
}
// checks all relevant data structures to see if the given type is being built
bool BuildingManager::isBeingBuilt(BWAPI::UnitType type)
{
// check unassigned buildings
return buildingData.isBeingBuilt(type);
}
// STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED
void BuildingManager::validateWorkersAndBuildings()
{
// TODO: if a terran worker dies while constructing and its building
// is under construction, place unit back into buildingsNeedingBuilders
buildingData.begin(ConstructionData::UnderConstruction);
while (buildingData.hasNextBuilding(ConstructionData::UnderConstruction))
{
Building & b = buildingData.getNextBuilding(ConstructionData::UnderConstruction);
if (b.buildingUnit == NULL || !b.buildingUnit->getType().isBuilding() || b.buildingUnit->getHitPoints() <= 0)
{
buildingData.removeCurrentBuilding(ConstructionData::UnderConstruction);
break;
}
}
}
// STEP 2: ASSIGN WORKERS TO BUILDINGS WITHOUT THEM
void BuildingManager::assignWorkersToUnassignedBuildings()
{
// for each building that doesn't have a builder, assign one
buildingData.begin(ConstructionData::Unassigned);
while (buildingData.hasNextBuilding(ConstructionData::Unassigned))
{
Building & b = buildingData.getNextBuilding(ConstructionData::Unassigned);
if (debugMode) { BWAPI::Broodwar->printf("Assigning Worker To: %s", b.type.getName().c_str()); }
// remove all refineries after 3, i don't know why this happens
if (b.type.isRefinery() && (BWAPI::Broodwar->self()->allUnitCount(b.type) >= 3))
{
buildingData.removeCurrentBuilding(ConstructionData::Unassigned);
break;
}
// get the building location
BWAPI::TilePosition testLocation = getBuildingLocation(b);
// if we can't find a valid build location, we can't assign this building
if (!testLocation.isValid())
{
continue;
}
// set the final position of the building as this location
b.finalPosition = testLocation;
// grab a worker unit from WorkerManager which is closest to this final position
BWAPI::Unit * workerToAssign = WorkerManager::Instance().getBuilder(b);
// if the worker exists
if (workerToAssign) {
//BWAPI::Broodwar->printf("VALID WORKER BEING ASSIGNED: %d", workerToAssign->getID());
// TODO: special case of terran building whose worker died mid construction
// send the right click command to the buildingUnit to resume construction
// skip the buildingsAssigned step and push it back into buildingsUnderConstruction
// set the worker we have assigned
b.builderUnit = workerToAssign;
// re-search for a building location with the builder unit ignored for space
testLocation = getBuildingLocation(b);
// hopefully this will not blow up
if (!testLocation.isValid())
{
continue;
}
// set the final position of the building
b.finalPosition = testLocation;
// reserve this space
BuildingPlacer::Instance().reserveTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// this building has now been assigned
buildingData.addBuilding(ConstructionData::Assigned, b);
// remove this Building
buildingData.removeCurrentBuilding(ConstructionData::Unassigned);
}
}
}
BWAPI::TilePosition BuildingManager::getBuildingLocation(const Building & b)
{
BWAPI::TilePosition testLocation = BWAPI::TilePositions::None;
int numPylons = BWAPI::Broodwar->self()->completedUnitCount(BWAPI::UnitTypes::Protoss_Pylon);
if (b.type.isRefinery())
{
return BuildingPlacer::Instance().getRefineryPosition();
}
/* @@
BWTA::Chokepoint * test;
if (b.type == BWAPI::UnitTypes::Protoss_Pylon && (numPylons > 3)){
test = BWTA::getNearestChokepoint(BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition());
BWAPI::TilePosition posInRegion = (BWAPI::TilePosition)test->getCenter();
return posInRegion;
}
// @@ Build cannon at chokepoint{
if (b.type == BWAPI::UnitTypes::Protoss_Photon_Cannon){
BWAPI::Broodwar->printf("******************************* BUILDING PHOTON CANNON\n");
test = BWTA::getNearestChokepoint(BWTA::getStartLocation(BWAPI::Broodwar->self())->getTilePosition());
BWAPI::TilePosition posInRegion = (BWAPI::TilePosition)test->getCenter();
return posInRegion;
}
*/ //@@
// special case for early pylons
if (b.type == BWAPI::UnitTypes::Protoss_Pylon && (numPylons < 3))
{
BWAPI::TilePosition posInRegion = BuildingPlacer::Instance().getBuildLocationNear(b, 4, true);
BWAPI::TilePosition posNotInRegion = BuildingPlacer::Instance().getBuildLocationNear(b, 4, false);
testLocation = (posInRegion != BWAPI::TilePositions::None) ? posInRegion : posNotInRegion;
}
// every other type of building
else
{
// if it is a protoss building and we have no pylons, quick check
if (b.type.requiresPsi() && (numPylons == 0))
{
// nothing
}
// if the unit is a resource depot
else if (b.type.isResourceDepot())
{
// get the location
BWAPI::TilePosition tile = MapTools::Instance().getNextExpansion();
return tile;
}
// any other building
else
{
// set the building padding specifically
int distance = b.type == BWAPI::UnitTypes::Protoss_Photon_Cannon ? 0 : 1;
// whether or not we want the distance to be horizontal only
bool horizontalOnly = b.type == BWAPI::UnitTypes::Protoss_Citadel_of_Adun ? true : false;
// get a position within our region
BWAPI::TilePosition posInRegion = BuildingPlacer::Instance().getBuildLocationNear(b, distance, true, horizontalOnly);
// get a region anywhere
BWAPI::TilePosition posNotInRegion = BuildingPlacer::Instance().getBuildLocationNear(b, distance, false, horizontalOnly);
// set the location with priority on positions in our own region
testLocation = (posInRegion != BWAPI::TilePositions::None) ? posInRegion : posNotInRegion;
}
}
// send back the location
return testLocation;
}
// STEP 3: ISSUE CONSTRUCTION ORDERS TO ASSIGN BUILDINGS AS NEEDED
void BuildingManager::constructAssignedBuildings()
{
// for each of the buildings which have been assigned a worker
buildingData.begin(ConstructionData::Assigned);
while(buildingData.hasNextBuilding(ConstructionData::Assigned))
{
// get a handy reference to the worker
Building & b = buildingData.getNextBuilding(ConstructionData::Assigned);
// if that worker is not currently constructing
if (!b.builderUnit->isConstructing())
{
// if we haven't explored the build position, go there
if (!isBuildingPositionExplored(b))
{
b.builderUnit->move(BWAPI::Position(b.finalPosition));
//BWAPI::Broodwar->printf("Can't see build position, walking there");
}
// if this is not the first time we've sent this guy to build this
// it must be the case that something was in the way of building
else if (b.buildCommandGiven)
{
//BWAPI::Broodwar->printf("A builder got stuck");
// tell worker manager the unit we had is not needed now, since we might not be able
// to get a valid location soon enough
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
// free the previous location in reserved
BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// nullify its current builder unit
b.builderUnit = NULL;
// reset the build command given flag
b.buildCommandGiven = false;
// add the building back to be assigned
buildingData.addBuilding(ConstructionData::Unassigned, b);
// remove the building from Assigned
buildingData.removeCurrentBuilding(ConstructionData::Assigned);
}
else
{
if (debugMode) { BWAPI::Broodwar->printf("Issuing Build Command To %s", b.type.getName().c_str()); }
// issue the build order!
b.builderUnit->build(b.finalPosition, b.type);
// set the flag to true
b.buildCommandGiven = true;
}
}
}
}
// STEP 4: UPDATE DATA STRUCTURES FOR BUILDINGS STARTING CONSTRUCTION
void BuildingManager::checkForStartedConstruction()
{
// for each building unit which is being constructed
BOOST_FOREACH (BWAPI::Unit * buildingStarted, BWAPI::Broodwar->self()->getUnits()) {
// filter out units which aren't buildings under construction
if (!(buildingStarted->getType().isBuilding() && buildingStarted->isBeingConstructed()))
{
continue;
}
// for each Building which is currently assigned, check it
buildingData.begin(ConstructionData::Assigned);
while (buildingData.hasNextBuilding(ConstructionData::Assigned))
{
Building & b = buildingData.getNextBuilding(ConstructionData::Assigned);
// check if the positions match
if (b.finalPosition == buildingStarted->getTilePosition()) {
// the resources should now be spent, so unreserve them
reservedMinerals -= buildingStarted->getType().mineralPrice();
reservedGas -= buildingStarted->getType().gasPrice();
if (debugMode) { BWAPI::Broodwar->printf("Construction Started: %s", b.type.getName().c_str()); }
// flag it as started and set the buildingUnit
b.underConstruction = true;
b.buildingUnit = buildingStarted;
// if we are zerg, the buildingUnit now becomes NULL since it's destroyed
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Zerg) {
b.builderUnit = NULL;
// if we are protoss, give the worker back to worker manager
} else if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Protoss) {
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
b.builderUnit = NULL;
}
// put it in the under construction vector
buildingData.addBuilding(ConstructionData::UnderConstruction, b);
// remove it from buildingsAssigned
buildingData.removeCurrentBuilding(ConstructionData::Assigned);
// free this space
BuildingPlacer::Instance().freeTiles(b.finalPosition, b.type.tileWidth(), b.type.tileHeight());
// only one building will match
break;
}
}
}
}
// STEP 5: IF WE ARE TERRAN, THIS MATTERS, SO: LOL
void BuildingManager::checkForDeadTerranBuilders() {}
// STEP 6: CHECK FOR COMPLETED BUILDINGS
void BuildingManager::checkForCompletedBuildings() {
// for each of our buildings under construction
buildingData.begin(ConstructionData::UnderConstruction);
while (buildingData.hasNextBuilding(ConstructionData::UnderConstruction)) {
Building & b = buildingData.getNextBuilding(ConstructionData::UnderConstruction);
// if the unit has completed
if (b.buildingUnit->isCompleted())
{
if (debugMode) { BWAPI::Broodwar->printf("Construction Completed: %s", b.type.getName().c_str()); }
// if we are terran, give the worker back to worker manager
if (BWAPI::Broodwar->self()->getRace() == BWAPI::Races::Terran)
{
WorkerManager::Instance().finishedWithWorker(b.builderUnit);
}
// remove this unit from the under construction vector
buildingData.removeCurrentBuilding(ConstructionData::UnderConstruction);
}
}
}
void BuildingManager::printBuildingNumbers()
{
BWAPI::Broodwar->printf("BUILDINGS: %d %d %d",
buildingData.getNumBuildings(ConstructionData::Unassigned),
buildingData.getNumBuildings(ConstructionData::Assigned),
buildingData.getNumBuildings(ConstructionData::UnderConstruction));
}
// COMPLETED
bool BuildingManager::isEvolvedBuilding(BWAPI::UnitType type) {
if (type == BWAPI::UnitTypes::Zerg_Sunken_Colony ||
type == BWAPI::UnitTypes::Zerg_Spore_Colony ||
type == BWAPI::UnitTypes::Zerg_Lair ||
type == BWAPI::UnitTypes::Zerg_Hive ||
type == BWAPI::UnitTypes::Zerg_Greater_Spire)
{
return true;
}
return false;
}
// add a new building to be constructed
void BuildingManager::addBuildingTask(BWAPI::UnitType type, BWAPI::TilePosition desiredLocation) {
if (debugMode) { BWAPI::Broodwar->printf("Issuing addBuildingTask: %s", type.getName().c_str()); }
totalBuildTasks++;
// reserve the resources for this building
reservedMinerals += type.mineralPrice();
reservedGas += type.gasPrice();
// set it up to receive a worker
buildingData.addBuilding(ConstructionData::Unassigned, Building(type, desiredLocation));
}
bool BuildingManager::isBuildingPositionExplored(const Building & b) const
{
BWAPI::TilePosition tile = b.finalPosition;
// for each tile where the building will be built
for (int x=0; x<b.type.tileWidth(); ++x)
{
for (int y=0; y<b.type.tileHeight(); ++y)
{
if (!BWAPI::Broodwar->isExplored(tile.x() + x, tile.y() + y))
{
return false;
}
}
}
return true;
}
char BuildingManager::getBuildingWorkerCode(const Building & b) const
{
if (b.builderUnit == NULL) return 'X';
else return 'W';
}
int BuildingManager::getReservedMinerals() {
return reservedMinerals;
}
int BuildingManager::getReservedGas() {
return reservedGas;
}
void BuildingManager::drawBuildingInformation(int x, int y) {
BOOST_FOREACH (BWAPI::Unit * unit, BWAPI::Broodwar->self()->getUnits())
{
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextMap(unit->getPosition().x(), unit->getPosition().y()+5, "\x07%d", unit->getID());
}
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x, y, "\x04 Building Information:");
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x, y+20, "\x04 Name");
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x+150, y+20, "\x04 State");
int yspace = 0;
buildingData.begin(ConstructionData::Unassigned);
while (buildingData.hasNextBuilding(ConstructionData::Unassigned)) {
Building & b = buildingData.getNextBuilding(ConstructionData::Unassigned);
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x, y+40+((yspace)*10), "\x03 %s", b.type.getName().c_str());
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x+150, y+40+((yspace++)*10), "\x03 Need %c", getBuildingWorkerCode(b));
}
buildingData.begin(ConstructionData::Assigned);
while (buildingData.hasNextBuilding(ConstructionData::Assigned)) {
Building & b = buildingData.getNextBuilding(ConstructionData::Assigned);
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x, y+40+((yspace)*10), "\x03 %s %d", b.type.getName().c_str(), b.builderUnit->getID());
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x+150, y+40+((yspace++)*10), "\x03 A %c (%d,%d)", getBuildingWorkerCode(b), b.finalPosition.x(), b.finalPosition.y());
int x1 = b.finalPosition.x()*32;
int y1 = b.finalPosition.y()*32;
int x2 = (b.finalPosition.x() + b.type.tileWidth())*32;
int y2 = (b.finalPosition.y() + b.type.tileHeight())*32;
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawLineMap(b.builderUnit->getPosition().x(), b.builderUnit->getPosition().y(), (x1+x2)/2, (y1+y2)/2, BWAPI::Colors::Orange);
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawBoxMap(x1, y1, x2, y2, BWAPI::Colors::Red, false);
}
buildingData.begin(ConstructionData::UnderConstruction);
while (buildingData.hasNextBuilding(ConstructionData::UnderConstruction)) {
Building & b = buildingData.getNextBuilding(ConstructionData::UnderConstruction);
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x, y+40+((yspace)*10), "\x03 %s %d", b.type.getName().c_str(), b.buildingUnit->getID());
if (Options::Debug::DRAW_UALBERTABOT_DEBUG) BWAPI::Broodwar->drawTextScreen(x+150, y+40+((yspace++)*10), "\x03 Const %c", getBuildingWorkerCode(b));
}
}
BuildingManager & BuildingManager::Instance()
{
static BuildingManager instance;
return instance;
} | [
"abeshry@gmail.com"
] | abeshry@gmail.com |
917fbb08479d65ce02dbec112351e860dc368314 | ec71579a12bfad56a21bea33c4301e2580ba3dd2 | /doc/ch341/i2c_master/Software/USB2I2C with Source Code/Resource/USB2I2C_VC/OtherPage.h | e9389d0b74c635ad74776af2af730b6298d63ee3 | [] | no_license | CutClassH/ScdTool | 6839e4d2ae2fccaaea5eaeb3dc800beb86f72bb2 | e014835da02280005aa1192cbdc805614dd7f4db | refs/heads/main | 2023-07-29T07:20:44.021654 | 2021-09-12T17:16:08 | 2021-09-12T17:16:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | h | #if !defined(AFX_OTHERPAGE_H__DDA810B7_F37F_47EB_8D2E_3FB5F0100165__INCLUDED_)
#define AFX_OTHERPAGE_H__DDA810B7_F37F_47EB_8D2E_3FB5F0100165__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// OtherPage.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// COtherPage dialog
class COtherPage : public CPropertyPage
{
DECLARE_DYNCREATE(COtherPage)
// Construction
public:
ULONG mIndex;
CUSB2I2CDlg * p_Dlg;
BOOL m_open;
COtherPage();
~COtherPage();
// Dialog Data
//{{AFX_DATA(COtherPage)
enum { IDD = IDD_DLGOTHER };
CString m_data;
CString m_dataaddr;
CString m_devaddr;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(COtherPage)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(COtherPage)
afx_msg void OnButtonI2cread();
afx_msg void OnButtonI2cwrite();
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_OTHERPAGE_H__DDA810B7_F37F_47EB_8D2E_3FB5F0100165__INCLUDED_)
| [
"1939261764@qq.com"
] | 1939261764@qq.com |
dbee1adbc1c8456dd3463f9b75efe58571069c91 | 347c5c2128cc1193e7ca1a2d338e89466a368072 | /include/operator/expression/EQ.h | 51506c7f9d78c5db35f59a5a2e013a0ecbb9f537 | [
"MIT"
] | permissive | Tobias-Werner/GStream | 9aec79106646bb82b698272c41dc145654830a12 | b8650c71a607413f965d6582d1eb738481e682bd | refs/heads/master | 2020-08-03T10:57:47.462632 | 2019-10-11T15:31:15 | 2019-10-11T15:31:15 | 211,727,263 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 734 | h | //
// Created by tobias on 06.08.18.
//
#ifndef STREAMS_EQ_H
#define STREAMS_EQ_H
#include "ACondition.h"
namespace STREAM {
class EQ : public ACondition {
public:
bool check(Long &first, Long &second) {
return first.get() == second.get();
}
bool check(Double &first, Double &second) {
return first.get() == second.get();
}
bool check(String &first, String &second) {
return first.get() == second.get();
}
bool check(Blob &first, Blob &second) {
return first.get() == second.get();
}
bool check(Null &first, Null &second) {
return true;
}
};
}
#endif //STREAMS_EQ_H
| [
"info@x-ploit.de"
] | info@x-ploit.de |
de07e53b16acfc3a8ab252b9c1173ced48d16999 | b4f02ef40bfa932dcb8cef5286d5c75bab820c06 | /PandoraSDK/include/Managers/ClusterManager.h | 6120a0ab7431fc381385bd4365223f8eeda855d8 | [] | no_license | kpedro88/pandora | 5de313d67168ba1eb59eca91f0b7576178930c20 | e4825cb52f9a6c8b04ec93b9506b12631e3a475f | refs/heads/master | 2021-01-17T22:39:59.261759 | 2015-02-26T09:20:32 | 2015-02-26T09:20:32 | 32,041,513 | 0 | 0 | null | 2015-03-11T21:13:42 | 2015-03-11T21:13:41 | C++ | UTF-8 | C++ | false | false | 5,811 | h | /**
* @file PandoraSDK/include/Managers/ClusterManager.h
*
* @brief Header file for the cluster manager class.
*
* $Log: $
*/
#ifndef PANDORA_CLUSTER_MANAGER_H
#define PANDORA_CLUSTER_MANAGER_H 1
#include "Api/PandoraContentApi.h"
#include "Managers/AlgorithmObjectManager.h"
#include "Objects/Cluster.h"
#include "Pandora/PandoraInternal.h"
namespace pandora
{
/**
* @brief ClusterManager class
*/
class ClusterManager : public AlgorithmObjectManager<Cluster>
{
public:
/**
* @brief Constructor
*
* @param pPandora address of the associated pandora object
*/
ClusterManager(const Pandora *const pPandora);
/**
* @brief Destructor
*/
~ClusterManager();
private:
/**
* @brief Create cluster
*
* @param parameters the cluster parameters
* @param pCluster to receive the address of the cluster created
*/
StatusCode CreateCluster(const PandoraContentApi::Cluster::Parameters ¶meters, const Cluster *&pCluster);
/**
* @brief Alter the metadata information stored in a cluster
*
* @param pCluster address of the cluster to modify
* @param metaData the metadata (only populated metadata fields will be propagated to the object)
*/
StatusCode AlterMetadata(const Cluster *const pCluster, const PandoraContentApi::Cluster::Metadata &metadata) const;
/**
* @brief Is a cluster, or a list of clusters, available to add to a particle flow object
*
* @param pT address of the object or object list
*
* @return boolean
*/
template <typename T>
bool IsAvailable(const T *const pT) const;
/**
* @brief Set availability of a cluster, or a list of clusters, to be added to a particle flow object
*
* @param pT the address of the object or object list
* @param isAvailable the availability
*/
template <typename T>
void SetAvailability(const T *const pT, bool isAvailable) const;
/**
* @brief Add a calo hit to a cluster
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to add
*/
StatusCode AddToCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Remove a calo hit from a cluster
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to remove
*/
StatusCode RemoveFromCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Add an isolated calo hit to a cluster. This is not counted as a regular calo hit: it contributes only
* towards the cluster energy and does not affect any other cluster properties.
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to add
*/
StatusCode AddIsolatedToCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Remove an isolated calo hit from a cluster
*
* @param pCluster address of the cluster to modify
* @param pCaloHit address of the hit to remove
*/
StatusCode RemoveIsolatedFromCluster(const Cluster *const pCluster, const CaloHit *const pCaloHit);
/**
* @brief Merge two clusters in the current list, enlarging one cluster and deleting the second
*
* @param pClusterToEnlarge address of the cluster to enlarge
* @param pClusterToDelete address of the cluster to delete
*/
StatusCode MergeAndDeleteClusters(const Cluster *const pClusterToEnlarge, const Cluster *const pClusterToDelete);
/**
* @brief Merge two clusters from two specified lists, enlarging one cluster and deleting the second
*
* @param pClusterToEnlarge address of the cluster to enlarge
* @param pClusterToDelete address of the cluster to delete
* @param enlargeListName name of the list containing the cluster to enlarge
* @param deleteListName name of the list containing the cluster to delete
*/
StatusCode MergeAndDeleteClusters(const Cluster *const pClusterToEnlarge, const Cluster *const pClusterToDelete, const std::string &enlargeListName,
const std::string &deleteListName);
/**
* @brief Add an association between a cluster and a track
*
* @param pCluster the address of the relevant cluster
* @param pTrack the address of the track with which the cluster is associated
*/
StatusCode AddTrackAssociation(const Cluster *const pCluster, const Track *const pTrack) const;
/**
* @brief Remove an association between a cluster and a track
*
* @param pCluster the address of the relevant cluster
* @param pTrack the address of the track with which the cluster is no longer associated
*/
StatusCode RemoveTrackAssociation(const Cluster *const pCluster, const Track *const pTrack) const;
/**
* @brief Remove all cluster to track associations
*/
StatusCode RemoveAllTrackAssociations() const;
/**
* @brief Remove cluster to track associations from all clusters in the current list
*
* @param danglingTracks to receive the list of "dangling" associations
*/
StatusCode RemoveCurrentTrackAssociations(TrackList &danglingTracks) const;
/**
* @brief Remove a specified list of cluster to track associations
*
* @param trackToClusterList the specified track to cluster list
*/
StatusCode RemoveTrackAssociations(const TrackToClusterMap &trackToClusterList) const;
friend class PandoraContentApiImpl;
friend class PandoraImpl;
};
} // namespace pandora
#endif // #ifndef PANDORA_CLUSTER_MANAGER_H
| [
"a.degano@gmail.com"
] | a.degano@gmail.com |
25da714095ece958be4174ef8b48743ad7360fe7 | a303be0a547d717b0deb19b5bdcc75010e131b51 | /Contests/College Contests/ CodeNight/p3.cpp | d6d8f0ef6a9ade9288f06a08edf9ca7b21ee170e | [] | no_license | harrypotter0/competitive-programming | ff883c4dc5aa8d72f1af589bb654a422e32c8a38 | 82a8497e69212dc62e75af74b0d5a3b390b8aca2 | refs/heads/master | 2023-03-23T07:07:14.295053 | 2021-03-17T01:24:45 | 2021-03-17T01:24:45 | 70,964,689 | 16 | 9 | null | 2021-03-17T01:24:49 | 2016-10-15T03:52:53 | Python | UTF-8 | C++ | false | false | 616 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long lnt;
int a[110],b[110];
int x[110],y[110],ok[110];
int main(){
int n;
scanf("%d",&n);
for(int k=1;k<=n;k++) scanf("%d%d",&a[k],&b[k]);
for(int k=1;k<=n;k++){
if(k<=n/2) x[k]=a[k]-b[k];
else y[k-n/2]=b[k];
}
sort(x+1,x+n/2+1);
sort(y+1,y+n/2+1);
int ans=0;
for(int k=n/2;k>=1;k--){
for(int i=n/2;i>=1;i--){
if(ok[i]) continue;
if(y[k]<=x[i]){
ans++;
ok[i]=1;
break;
}
}
}
printf("%d\n",ans);
}
| [
"9654263057akashkandpal@gmail.com"
] | 9654263057akashkandpal@gmail.com |
a415da3dc3c3556f306de6224dd6cb7a60ffd06e | 8c114792636e9336c70fcaf4abc83eb25679d894 | /src/core-master/cpp/ecp_NUMS256W.h | 64eae9598ed9d7d44d1e0d21acb19d67d5d13975 | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | permissive | cri-lab-hbku/auth-ais | c7cfeb1dee74c6947a9cc8530a01fb59994c94c5 | 9283c65fbe961ba604aab0f3cb35ddea99277c34 | refs/heads/master | 2023-03-23T00:22:29.430698 | 2021-03-12T18:53:27 | 2021-03-12T18:53:27 | 250,838,562 | 0 | 0 | BSD-3-Clause | 2021-03-12T18:53:28 | 2020-03-28T16:10:17 | C++ | UTF-8 | C++ | false | false | 13,072 | h | /*
Copyright (C) 2019 MIRACL UK Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
https://www.gnu.org/licenses/agpl-3.0.en.html
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the MIRACL Core Crypto SDK
without disclosing the source code of your own applications, or shipping
the MIRACL Core Crypto SDK with a closed source product.
*/
#ifndef ECP_NUMS256W_H
#define ECP_NUMS256W_H
#include "fp_F256PMW.h"
#include "config_curve_NUMS256W.h"
using namespace core;
namespace NUMS256W {
/* Curve Params - see rom.c */
extern const int CURVE_A; /**< Elliptic curve A parameter */
extern const int CURVE_B_I;
extern const int CURVE_Cof_I;
extern const B256_56::BIG CURVE_B; /**< Elliptic curve B parameter */
extern const B256_56::BIG CURVE_Order; /**< Elliptic curve group order */
extern const B256_56::BIG CURVE_Cof; /**< Elliptic curve cofactor */
/* Generator point on G1 */
extern const B256_56::BIG CURVE_Gx; /**< x-coordinate of generator point in group G1 */
extern const B256_56::BIG CURVE_Gy; /**< y-coordinate of generator point in group G1 */
/* For Pairings only */
/* Generator point on G2 */
extern const B256_56::BIG CURVE_Pxa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pya; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyb; /**< imaginary part of y-coordinate of generator point in group G2 */
/*** needed for BLS24 curves ***/
extern const B256_56::BIG CURVE_Pxaa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxab; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxba; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaa; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyab; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyba; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybb; /**< imaginary part of y-coordinate of generator point in group G2 */
/*** needed for BLS48 curves ***/
extern const B256_56::BIG CURVE_Pxaaa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxaab; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxaba; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxabb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbaa; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbab; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbba; /**< real part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pxbbb; /**< imaginary part of x-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaaa; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaab; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyaba; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pyabb; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybaa; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybab; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybba; /**< real part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Pybbb; /**< imaginary part of y-coordinate of generator point in group G2 */
extern const B256_56::BIG CURVE_Bnx; /**< BN curve x parameter */
extern const B256_56::BIG CURVE_Cru; /**< BN curve Cube Root of Unity */
extern const B256_56::BIG Fra; /**< real part of BN curve Frobenius Constant */
extern const B256_56::BIG Frb; /**< imaginary part of BN curve Frobenius Constant */
extern const B256_56::BIG CURVE_W[2]; /**< BN curve constant for GLV decomposition */
extern const B256_56::BIG CURVE_SB[2][2]; /**< BN curve constant for GLV decomposition */
extern const B256_56::BIG CURVE_WB[4]; /**< BN curve constant for GS decomposition */
extern const B256_56::BIG CURVE_BB[4][4]; /**< BN curve constant for GS decomposition */
/**
@brief ECP structure - Elliptic Curve Point over base field
*/
typedef struct
{
// int inf; /**< Infinity Flag - not needed for Edwards representation */
F256PMW::FP x; /**< x-coordinate of point */
#if CURVETYPE_NUMS256W!=MONTGOMERY
F256PMW::FP y; /**< y-coordinate of point. Not needed for Montgomery representation */
#endif
F256PMW::FP z;/**< z-coordinate of point */
} ECP;
/* ECP E(Fp) prototypes */
/** @brief Tests for ECP point equal to infinity
*
@param P ECP point to be tested
@return 1 if infinity, else returns 0
*/
extern int ECP_isinf(ECP *P);
/** @brief Tests for equality of two ECPs
*
@param P ECP instance to be compared
@param Q ECP instance to be compared
@return 1 if P=Q, else returns 0
*/
extern int ECP_equals(ECP *P, ECP *Q);
/** @brief Copy ECP point to another ECP point
*
@param P ECP instance, on exit = Q
@param Q ECP instance to be copied
*/
extern void ECP_copy(ECP *P, ECP *Q);
/** @brief Negation of an ECP point
*
@param P ECP instance, on exit = -P
*/
extern void ECP_neg(ECP *P);
/** @brief Set ECP to point-at-infinity
*
@param P ECP instance to be set to infinity
*/
extern void ECP_inf(ECP *P);
/** @brief Calculate Right Hand Side of curve equation y^2=f(x)
*
Function f(x) depends on form of elliptic curve, Weierstrass, Edwards or Montgomery.
Used internally.
@param r BIG n-residue value of f(x)
@param x BIG n-residue x
*/
extern void ECP_rhs(F256PMW::FP *r, F256PMW::FP *x);
/** @brief Set ECP to point(x,y) given just x and sign of y
*
Point P set to infinity if no such point on the curve. If x is on the curve then y is calculated from the curve equation.
The correct y value (plus or minus) is selected given its sign s.
@param P ECP instance to be set (x,[y])
@param x BIG x coordinate of point
@param s an integer representing the "sign" of y, in fact its least significant bit.
*/
extern int ECP_setx(ECP *P, B256_56::BIG x, int s);
#if CURVETYPE_NUMS256W==MONTGOMERY
/** @brief Set ECP to point(x,[y]) given x
*
Point P set to infinity if no such point on the curve. Note that y coordinate is not needed.
@param P ECP instance to be set (x,[y])
@param x BIG x coordinate of point
@return 1 if point exists, else 0
*/
extern int ECP_set(ECP *P, B256_56::BIG x);
/** @brief Extract x coordinate of an ECP point P
*
@param x BIG on exit = x coordinate of point
@param P ECP instance (x,[y])
@return -1 if P is point-at-infinity, else 0
*/
extern int ECP_get(B256_56::BIG x, ECP *P);
/** @brief Adds ECP instance Q to ECP instance P, given difference D=P-Q
*
Differential addition of points on a Montgomery curve
@param P ECP instance, on exit =P+Q
@param Q ECP instance to be added to P
@param D Difference between P and Q
*/
extern void ECP_add(ECP *P, ECP *Q, ECP *D);
#else
/** @brief Set ECP to point(x,y) given x and y
*
Point P set to infinity if no such point on the curve.
@param P ECP instance to be set (x,y)
@param x BIG x coordinate of point
@param y BIG y coordinate of point
@return 1 if point exists, else 0
*/
extern int ECP_set(ECP *P, B256_56::BIG x, B256_56::BIG y);
/** @brief Extract x and y coordinates of an ECP point P
*
If x=y, returns only x
@param x BIG on exit = x coordinate of point
@param y BIG on exit = y coordinate of point (unless x=y)
@param P ECP instance (x,y)
@return sign of y, or -1 if P is point-at-infinity
*/
extern int ECP_get(B256_56::BIG x, B256_56::BIG y, ECP *P);
/** @brief Adds ECP instance Q to ECP instance P
*
@param P ECP instance, on exit =P+Q
@param Q ECP instance to be added to P
*/
extern void ECP_add(ECP *P, ECP *Q);
/** @brief Subtracts ECP instance Q from ECP instance P
*
@param P ECP instance, on exit =P-Q
@param Q ECP instance to be subtracted from P
*/
extern void ECP_sub(ECP *P, ECP *Q);
#endif
/** @brief Converts an ECP point from Projective (x,y,z) coordinates to affine (x,y) coordinates
*
@param P ECP instance to be converted to affine form
*/
extern void ECP_affine(ECP *P);
/** @brief Formats and outputs an ECP point to the console, in projective coordinates
*
@param P ECP instance to be printed
*/
extern void ECP_outputxyz(ECP *P);
/** @brief Formats and outputs an ECP point to the console, converted to affine coordinates
*
@param P ECP instance to be printed
*/
extern void ECP_output(ECP * P);
/** @brief Formats and outputs an ECP point to the console
*
@param P ECP instance to be printed
*/
extern void ECP_rawoutput(ECP * P);
/** @brief Formats and outputs an ECP point to an octet string
*
The octet string is normally in the standard form 0x04|x|y
Here x (and y) are the x and y coordinates in left justified big-endian base 256 form.
For Montgomery curve it is 0x06|x
If c is true, only the x coordinate is provided as in 0x2|x if y is even, or 0x3|x if y is odd
@param c compression required, true or false
@param S output octet string
@param P ECP instance to be converted to an octet string
*/
extern void ECP_toOctet(octet *S, ECP *P, bool c);
/** @brief Creates an ECP point from an octet string
*
The octet string is normally in the standard form 0x04|x|y
Here x (and y) are the x and y coordinates in left justified big-endian base 256 form.
For Montgomery curve it is 0x06|x
If in compressed form only the x coordinate is provided as in 0x2|x if y is even, or 0x3|x if y is odd
@param P ECP instance to be created from the octet string
@param S input octet string
@param c true for compression
return 1 if octet string corresponds to a point on the curve, else 0
*/
extern int ECP_fromOctet(ECP *P, octet *S);
/** @brief Doubles an ECP instance P
*
@param P ECP instance, on exit =2*P
*/
extern void ECP_dbl(ECP *P);
/** @brief Multiplies an ECP instance P by a small integer, side-channel resistant
*
@param P ECP instance, on exit =i*P
@param i small integer multiplier
@param b maximum number of bits in multiplier
*/
extern void ECP_pinmul(ECP *P, int i, int b);
/** @brief Multiplies an ECP instance P by a BIG, side-channel resistant
*
Uses Montgomery ladder for Montgomery curves, otherwise fixed sized windows.
@param P ECP instance, on exit =b*P
@param b BIG number multiplier
*/
extern void ECP_mul(ECP *P, B256_56::BIG b);
/** @brief Calculates double multiplication P=e*P+f*Q, side-channel resistant
*
@param P ECP instance, on exit =e*P+f*Q
@param Q ECP instance
@param e BIG number multiplier
@param f BIG number multiplier
*/
extern void ECP_mul2(ECP *P, ECP *Q, B256_56::BIG e, B256_56::BIG f);
/** @brief Multiplies random point by co-factor
*
@param Q ECP multiplied by co-factor
*/
extern void ECP_cfp(ECP *Q);
/** @brief Hashes random BIG to curve point
*
@param Q ECP instance
@param x Fp derived from hash
*/
extern void ECP_hashit(ECP *Q, B256_56::BIG x);
/** @brief Maps random octet to curve point of correct order
*
@param Q ECP instance of correct order
@param w OCTET byte array to be mapped
*/
extern void ECP_mapit(ECP *Q, octet *w);
/** @brief Get Group Generator from ROM
*
@param G ECP instance
@return true or false
*/
extern int ECP_generator(ECP *G);
}
#endif
| [
"ahmedaziz.nust@hotmail.com"
] | ahmedaziz.nust@hotmail.com |
faf5e4a31c3dd2815c933faa91c1f5344ac89366 | 0654228578d742c8aadc52f1755268c2ef4cabe0 | /IPSSIM_December/dataSet_12.cpp | fa0725f315b9a7152fbc8d0d7977bc8228642349 | [] | no_license | ir0nheart/IPSSIM_December | 4c7c4060a6f1de213921838de31e952b701227ec | 81f1e6b8b6c19f4755d21e45df6b1a5391837532 | refs/heads/master | 2020-04-13T18:35:32.857545 | 2019-01-07T20:06:14 | 2019-01-07T20:06:14 | 163,379,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,576 | cpp | #include "dataSet_12.h"
#include <iostream>
#include <locale>
dataSet_12::dataSet_12(std::string data_)
{
name = "Data Set 12";
data = data_;
std::cout << "Data Set 12 - is created " << std::endl;
}
dataSet_12::~dataSet_12()
{
std::cout << "Data Set 12 - is destroyed " << std::endl;
}
void dataSet_12::parse_data()
{
while (std::find(data.begin(), data.end(), '\r') != data.end()){
data.erase(std::remove(data.begin(), data.end(), '\r'), data.end());
}
//Remove fortran string char "'" from the string
while (std::find(data.begin(), data.end(), '\'') != data.end()){
data.erase(std::remove(data.begin(), data.end(), '\''), data.end());
}
std::vector<std::string> strs;
//Split string into a vector by line
while (std::find(data.begin(), data.end(), '\n') != data.end())
{
strs.push_back(data.substr(0, data.find_first_of("\n")));
data.erase(0, data.find_first_of("\n") + 1);
}
//Data Set 12
std::vector<std::string> _12 = makeStringVector(strs[0]);
prodf0 = std::stod(_12[0]);
prods0 = std::stod(_12[1]);
prodf1 = std::stod(_12[2]);
prods1 = std::stod(_12[3]);
//Data Set 13
std::vector<std::string> _13 = makeStringVector(strs[1]);
gravx = std::stod(_13[0]);
gravy = std::stod(_13[1]);
if (!std::isalpha(_13[2][0], std::locale()))
gravz = std::stod(_13[2]);
else
gravz = 0;
//Data Set 14A
std::vector<std::string> _14a = makeStringVector(strs[2]);
if (_14a[0] == "NODE"){
scalx = std::stod(_14a[1]);
scaly = std::stod(_14a[2]);
scalz = std::stod(_14a[3]);
porfac = std::stod(_14a[4]);
} else
{
//Command Error
}
}
| [
"demiryurek.a@husky.neu.edu"
] | demiryurek.a@husky.neu.edu |
0c75d6c87065d3ebb64597da341a687d61dc7df1 | 342a1a560615fc707481b7e940e59fe2c4f8cead | /install_native_2.0.10/resources/cocos2d-x/cocos/platform/CCImage.cpp | ba20521760a85f0ce2d3c1038571075bd17dedec | [] | no_license | dixon1988/creator_tool | ae0e8180e2e835b4a90aa31cca3d5e122e9acdf5 | 1998634b2654bd4cd7114b07d4fe9235782c61cd | refs/heads/main | 2023-07-13T02:02:34.273788 | 2021-08-24T03:16:47 | 2021-08-24T03:16:47 | 399,299,536 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68,398 | cpp | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCImage.h"
#include <string>
#include <ctype.h>
#include <assert.h>
#include "base/CCData.h"
#include "base/ccConfig.h" // CC_USE_JPEG, CC_USE_TIFF, CC_USE_WEBP
#include "base/ccUtils.h"
#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif // MIN
#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX
extern "C"
{
// To resolve link error when building 32bits with Xcode 6.
// More information please refer to the discussion in https://github.com/cocos2d/cocos2d-x/pull/6986
#if defined (__unix) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#ifndef __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
#define __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
#include <stdio.h>
FILE *fopen$UNIX2003( const char *filename, const char *mode )
{
return fopen(filename, mode);
}
size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
{
return fwrite(a, b, c, d);
}
char *strerror$UNIX2003( int errnum )
{
return strerror(errnum);
}
#endif
#endif
#if CC_USE_PNG
#include "png/png.h"
#endif //CC_USE_PNG
#if CC_USE_TIFF
#include "tiff/tiffio.h"
#endif //CC_USE_TIFF
#if CC_USE_JPEG
#include "jpeg/jpeglib.h"
#endif // CC_USE_JPEG
#include "base/etc1.h"
}
#if CC_USE_WEBP
#include "webp/decode.h"
#endif // CC_USE_WEBP
#include "base/pvr.h"
#include "base/TGAlib.h"
#include "base/ccMacros.h"
#include "platform/CCStdC.h"
#include "platform/CCFileUtils.h"
#include "base/CCConfiguration.h"
#include "base/ZipUtils.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCFileUtils-android.h"
#endif
#include <map>
#define CC_GL_ATC_RGB_AMD 0x8C92
#define CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
#define CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
NS_CC_BEGIN
//////////////////////////////////////////////////////////////////////////
//struct and data for pvr structure
namespace
{
typedef Image::PixelFormatInfoMap::value_type PixelFormatInfoMapValue;
static const PixelFormatInfoMapValue TexturePixelFormatInfoTablesValue[] =
{
PixelFormatInfoMapValue(Image::PixelFormat::BGRA8888, Image::PixelFormatInfo(GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE, 32, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGBA8888, Image::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGBA4444, Image::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGB5A1, Image::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, false, true)),
PixelFormatInfoMapValue(Image::PixelFormat::RGB565, Image::PixelFormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::RGB888, Image::PixelFormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, 24, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::A8, Image::PixelFormatInfo(GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 8, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::I8, Image::PixelFormatInfo(GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, false, false)),
PixelFormatInfoMapValue(Image::PixelFormat::AI88, Image::PixelFormatInfo(GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 16, false, true)),
#ifdef GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC2, Image::PixelFormatInfo(GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 2, true, false)),
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC2A, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 2, true, true)),
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC4, Image::PixelFormatInfo(GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
PixelFormatInfoMapValue(Image::PixelFormat::PVRTC4A, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, true)),
#endif
#ifdef GL_ETC1_RGB8_OES
PixelFormatInfoMapValue(Image::PixelFormat::ETC, Image::PixelFormatInfo(GL_ETC1_RGB8_OES, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif
#ifdef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
PixelFormatInfoMapValue(Image::PixelFormat::S3TC_DXT1, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif
#ifdef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
PixelFormatInfoMapValue(Image::PixelFormat::S3TC_DXT3, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
#ifdef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
PixelFormatInfoMapValue(Image::PixelFormat::S3TC_DXT5, Image::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
#ifdef GL_ATC_RGB_AMD
PixelFormatInfoMapValue(Image::PixelFormat::ATC_RGB, Image::PixelFormatInfo(GL_ATC_RGB_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif
#ifdef GL_ATC_RGBA_EXPLICIT_ALPHA_AMD
PixelFormatInfoMapValue(Image::PixelFormat::ATC_EXPLICIT_ALPHA, Image::PixelFormatInfo(GL_ATC_RGBA_EXPLICIT_ALPHA_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
#ifdef GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD
PixelFormatInfoMapValue(Image::PixelFormat::ATC_INTERPOLATED_ALPHA, Image::PixelFormatInfo(GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
};
//CLASS IMPLEMENTATIONS:
//The PixpelFormat corresponding information
const Image::PixelFormatInfoMap _pixelFormatInfoTables(TexturePixelFormatInfoTablesValue,
TexturePixelFormatInfoTablesValue + sizeof(TexturePixelFormatInfoTablesValue) / sizeof(TexturePixelFormatInfoTablesValue[0]));
const Image::PixelFormatInfoMap& getPixelFormatInfoMap()
{
return _pixelFormatInfoTables;
}
static const int PVR_TEXTURE_FLAG_TYPE_MASK = 0xff;
static bool _PVRHaveAlphaPremultiplied = false;
// Values taken from PVRTexture.h from http://www.imgtec.com
enum class PVR2TextureFlag
{
Mipmap = (1<<8), // has mip map levels
Twiddle = (1<<9), // is twiddled
Bumpmap = (1<<10), // has normals encoded for a bump map
Tiling = (1<<11), // is bordered for tiled pvr
Cubemap = (1<<12), // is a cubemap/skybox
FalseMipCol = (1<<13), // are there false colored MIP levels
Volume = (1<<14), // is this a volume texture
Alpha = (1<<15), // v2.1 is there transparency info in the texture
VerticalFlip = (1<<16), // v2.1 is the texture vertically flipped
};
enum class PVR3TextureFlag
{
PremultipliedAlpha = (1<<1) // has premultiplied alpha
};
static const char gPVRTexIdentifier[5] = "PVR!";
// v2
enum class PVR2TexturePixelFormat : unsigned char
{
RGBA4444 = 0x10,
RGBA5551,
RGBA8888,
RGB565,
RGB555, // unsupported
RGB888,
I8,
AI88,
PVRTC2BPP_RGBA,
PVRTC4BPP_RGBA,
BGRA8888,
A8,
};
// v3
enum class PVR3TexturePixelFormat : uint64_t
{
PVRTC2BPP_RGB = 0ULL,
PVRTC2BPP_RGBA = 1ULL,
PVRTC4BPP_RGB = 2ULL,
PVRTC4BPP_RGBA = 3ULL,
PVRTC2_2BPP_RGBA = 4ULL,
PVRTC2_4BPP_RGBA = 5ULL,
ETC1 = 6ULL,
DXT1 = 7ULL,
DXT2 = 8ULL,
DXT3 = 9ULL,
DXT4 = 10ULL,
DXT5 = 11ULL,
BC1 = 7ULL,
BC2 = 9ULL,
BC3 = 11ULL,
BC4 = 12ULL,
BC5 = 13ULL,
BC6 = 14ULL,
BC7 = 15ULL,
UYVY = 16ULL,
YUY2 = 17ULL,
BW1bpp = 18ULL,
R9G9B9E5 = 19ULL,
RGBG8888 = 20ULL,
GRGB8888 = 21ULL,
ETC2_RGB = 22ULL,
ETC2_RGBA = 23ULL,
ETC2_RGBA1 = 24ULL,
EAC_R11_Unsigned = 25ULL,
EAC_R11_Signed = 26ULL,
EAC_RG11_Unsigned = 27ULL,
EAC_RG11_Signed = 28ULL,
BGRA8888 = 0x0808080861726762ULL,
RGBA8888 = 0x0808080861626772ULL,
RGBA4444 = 0x0404040461626772ULL,
RGBA5551 = 0x0105050561626772ULL,
RGB565 = 0x0005060500626772ULL,
RGB888 = 0x0008080800626772ULL,
A8 = 0x0000000800000061ULL,
L8 = 0x000000080000006cULL,
LA88 = 0x000008080000616cULL,
};
// v2
typedef const std::map<PVR2TexturePixelFormat, Image::PixelFormat> _pixel2_formathash;
static const _pixel2_formathash::value_type v2_pixel_formathash_value[] =
{
_pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, Image::PixelFormat::BGRA8888),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, Image::PixelFormat::RGBA8888),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, Image::PixelFormat::RGBA4444),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, Image::PixelFormat::RGB5A1),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, Image::PixelFormat::RGB565),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, Image::PixelFormat::RGB888),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, Image::PixelFormat::A8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, Image::PixelFormat::I8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, Image::PixelFormat::AI88),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, Image::PixelFormat::PVRTC2A),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, Image::PixelFormat::PVRTC4A),
};
static const int PVR2_MAX_TABLE_ELEMENTS = sizeof(v2_pixel_formathash_value) / sizeof(v2_pixel_formathash_value[0]);
static const _pixel2_formathash v2_pixel_formathash(v2_pixel_formathash_value, v2_pixel_formathash_value + PVR2_MAX_TABLE_ELEMENTS);
// v3
typedef const std::map<PVR3TexturePixelFormat, Image::PixelFormat> _pixel3_formathash;
static _pixel3_formathash::value_type v3_pixel_formathash_value[] =
{
_pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, Image::PixelFormat::BGRA8888),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, Image::PixelFormat::RGBA8888),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, Image::PixelFormat::RGBA4444),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, Image::PixelFormat::RGB5A1),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, Image::PixelFormat::RGB565),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, Image::PixelFormat::RGB888),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, Image::PixelFormat::A8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, Image::PixelFormat::I8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, Image::PixelFormat::AI88),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, Image::PixelFormat::PVRTC2),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, Image::PixelFormat::PVRTC2A),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, Image::PixelFormat::PVRTC4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, Image::PixelFormat::PVRTC4A),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, Image::PixelFormat::ETC),
};
static const int PVR3_MAX_TABLE_ELEMENTS = sizeof(v3_pixel_formathash_value) / sizeof(v3_pixel_formathash_value[0]);
static const _pixel3_formathash v3_pixel_formathash(v3_pixel_formathash_value, v3_pixel_formathash_value + PVR3_MAX_TABLE_ELEMENTS);
typedef struct _PVRTexHeader
{
unsigned int headerLength;
unsigned int height;
unsigned int width;
unsigned int numMipmaps;
unsigned int flags;
unsigned int dataLength;
unsigned int bpp;
unsigned int bitmaskRed;
unsigned int bitmaskGreen;
unsigned int bitmaskBlue;
unsigned int bitmaskAlpha;
unsigned int pvrTag;
unsigned int numSurfs;
} PVRv2TexHeader;
#ifdef _MSC_VER
#pragma pack(push,1)
#endif
typedef struct
{
uint32_t version;
uint32_t flags;
uint64_t pixelFormat;
uint32_t colorSpace;
uint32_t channelType;
uint32_t height;
uint32_t width;
uint32_t depth;
uint32_t numberOfSurfaces;
uint32_t numberOfFaces;
uint32_t numberOfMipmaps;
uint32_t metadataLength;
#ifdef _MSC_VER
} PVRv3TexHeader;
#pragma pack(pop)
#else
} __attribute__((packed)) PVRv3TexHeader;
#endif
}
//pvr structure end
//////////////////////////////////////////////////////////////////////////
//struct and data for s3tc(dds) struct
namespace
{
struct DDColorKey
{
uint32_t colorSpaceLowValue;
uint32_t colorSpaceHighValue;
};
struct DDSCaps
{
uint32_t caps;
uint32_t caps2;
uint32_t caps3;
uint32_t caps4;
};
struct DDPixelFormat
{
uint32_t size;
uint32_t flags;
uint32_t fourCC;
uint32_t RGBBitCount;
uint32_t RBitMask;
uint32_t GBitMask;
uint32_t BBitMask;
uint32_t ABitMask;
};
struct DDSURFACEDESC2
{
uint32_t size;
uint32_t flags;
uint32_t height;
uint32_t width;
union
{
uint32_t pitch;
uint32_t linearSize;
} DUMMYUNIONNAMEN1;
union
{
uint32_t backBufferCount;
uint32_t depth;
} DUMMYUNIONNAMEN5;
union
{
uint32_t mipMapCount;
uint32_t refreshRate;
uint32_t srcVBHandle;
} DUMMYUNIONNAMEN2;
uint32_t alphaBitDepth;
uint32_t reserved;
uint32_t surface;
union
{
DDColorKey ddckCKDestOverlay;
uint32_t emptyFaceColor;
} DUMMYUNIONNAMEN3;
DDColorKey ddckCKDestBlt;
DDColorKey ddckCKSrcOverlay;
DDColorKey ddckCKSrcBlt;
union
{
DDPixelFormat ddpfPixelFormat;
uint32_t FVF;
} DUMMYUNIONNAMEN4;
DDSCaps ddsCaps;
uint32_t textureStage;
} ;
#pragma pack(push,1)
struct S3TCTexHeader
{
char fileCode[4];
DDSURFACEDESC2 ddsd;
};
#pragma pack(pop)
}
//s3tc struct end
namespace
{
typedef struct
{
const unsigned char * data;
ssize_t size;
int offset;
}tImageSource;
#ifdef CC_USE_PNG
static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length)
{
tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr);
if((int)(isource->offset + length) <= isource->size)
{
memcpy(data, isource->data+isource->offset, length);
isource->offset += length;
}
else
{
png_error(png_ptr, "pngReaderCallback failed");
}
}
#endif //CC_USE_PNG
}
Image::PixelFormat getDevicePixelFormat(Image::PixelFormat format)
{
switch (format) {
case Image::PixelFormat::PVRTC4:
case Image::PixelFormat::PVRTC4A:
case Image::PixelFormat::PVRTC2:
case Image::PixelFormat::PVRTC2A:
if(Configuration::getInstance()->supportsPVRTC())
return format;
else
return Image::PixelFormat::RGBA8888;
case Image::PixelFormat::ETC:
if(Configuration::getInstance()->supportsETC())
return format;
else
return Image::PixelFormat::RGB888;
default:
return format;
}
}
//////////////////////////////////////////////////////////////////////////
// Implement Image
//////////////////////////////////////////////////////////////////////////
bool Image::PNG_PREMULTIPLIED_ALPHA_ENABLED = false;
Image::Image()
: _data(nullptr)
, _dataLen(0)
, _width(0)
, _height(0)
, _fileType(Format::UNKNOWN)
, _renderFormat(Image::PixelFormat::NONE)
, _numberOfMipmaps(0)
, _hasPremultipliedAlpha(false)
{
}
Image::~Image()
{
CC_SAFE_FREE(_data);
}
bool Image::initWithImageFile(const std::string& path)
{
bool ret = false;
//NOTE: fullPathForFilename isn't threadsafe. we should make sure the parameter is a full path.
// _filePath = FileUtils::getInstance()->fullPathForFilename(path);
_filePath = path;
Data data = FileUtils::getInstance()->getDataFromFile(_filePath);
//decrypt
if ( !data.isNull() && DecryptImageFile(path, data.getBytes(), data.getSize()) )
{
data.fastSet1(data.getBytes(), data.getSize()-1);
}
if (!data.isNull())
{
ret = initWithImageData(data.getBytes(), data.getSize());
}
return ret;
}
bool Image::initWithImageData(const unsigned char * data, ssize_t dataLen)
{
bool ret = false;
do
{
CC_BREAK_IF(! data || dataLen <= 0);
unsigned char* unpackedData = nullptr;
ssize_t unpackedLen = 0;
//detect and unzip the compress file
if (ZipUtils::isCCZBuffer(data, dataLen))
{
unpackedLen = ZipUtils::inflateCCZBuffer(data, dataLen, &unpackedData);
}
else if (ZipUtils::isGZipBuffer(data, dataLen))
{
unpackedLen = ZipUtils::inflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
}
else
{
unpackedData = const_cast<unsigned char*>(data);
unpackedLen = dataLen;
}
_fileType = detectFormat(unpackedData, unpackedLen);
switch (_fileType)
{
case Format::PNG:
ret = initWithPngData(unpackedData, unpackedLen);
break;
case Format::JPG:
ret = initWithJpgData(unpackedData, unpackedLen);
break;
case Format::TIFF:
ret = initWithTiffData(unpackedData, unpackedLen);
break;
case Format::WEBP:
ret = initWithWebpData(unpackedData, unpackedLen);
break;
case Format::PVR:
ret = initWithPVRData(unpackedData, unpackedLen);
break;
case Format::ETC:
ret = initWithETCData(unpackedData, unpackedLen);
break;
case Format::S3TC:
ret = initWithS3TCData(unpackedData, unpackedLen);
break;
default:
{
// load and detect image format
tImageTGA* tgaData = tgaLoadBuffer(unpackedData, unpackedLen);
if (tgaData != nullptr && tgaData->status == TGA_OK)
{
ret = initWithTGAData(tgaData);
}
else
{
CCLOG("Image: unsupported image format!");
}
free(tgaData);
break;
}
}
if(unpackedData != data)
{
free(unpackedData);
}
} while (0);
return ret;
}
bool Image::isPng(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 8)
{
return false;
}
static const unsigned char PNG_SIGNATURE[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0;
}
bool Image::isEtc(const unsigned char * data, ssize_t dataLen)
{
return etc1_pkm_is_valid((etc1_byte*)data) ? true : false;
}
bool Image::isS3TC(const unsigned char * data, ssize_t /*dataLen*/)
{
S3TCTexHeader *header = (S3TCTexHeader *)data;
if (strncmp(header->fileCode, "DDS", 3) != 0)
{
return false;
}
return true;
}
bool Image::isJpg(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 4)
{
return false;
}
static const unsigned char JPG_SOI[] = {0xFF, 0xD8};
return memcmp(data, JPG_SOI, 2) == 0;
}
bool Image::isTiff(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 4)
{
return false;
}
static const char* TIFF_II = "II";
static const char* TIFF_MM = "MM";
return (memcmp(data, TIFF_II, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 42 && *(static_cast<const unsigned char*>(data) + 3) == 0) ||
(memcmp(data, TIFF_MM, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 0 && *(static_cast<const unsigned char*>(data) + 3) == 42);
}
bool Image::isWebp(const unsigned char * data, ssize_t dataLen)
{
if (dataLen <= 12)
{
return false;
}
static const char* WEBP_RIFF = "RIFF";
static const char* WEBP_WEBP = "WEBP";
return memcmp(data, WEBP_RIFF, 4) == 0
&& memcmp(static_cast<const unsigned char*>(data) + 8, WEBP_WEBP, 4) == 0;
}
bool Image::isPvr(const unsigned char * data, ssize_t dataLen)
{
if (static_cast<size_t>(dataLen) < sizeof(PVRv2TexHeader) || static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
{
return false;
}
const PVRv2TexHeader* headerv2 = static_cast<const PVRv2TexHeader*>(static_cast<const void*>(data));
const PVRv3TexHeader* headerv3 = static_cast<const PVRv3TexHeader*>(static_cast<const void*>(data));
return memcmp(&headerv2->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) == 0 || CC_SWAP_INT32_BIG_TO_HOST(headerv3->version) == 0x50565203;
}
Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen)
{
if (isPng(data, dataLen))
{
return Format::PNG;
}
else if (isJpg(data, dataLen))
{
return Format::JPG;
}
else if (isTiff(data, dataLen))
{
return Format::TIFF;
}
else if (isWebp(data, dataLen))
{
return Format::WEBP;
}
else if (isPvr(data, dataLen))
{
return Format::PVR;
}
else if (isEtc(data, dataLen))
{
return Format::ETC;
}
else if (isS3TC(data, dataLen))
{
return Format::S3TC;
}
else
{
return Format::UNKNOWN;
}
}
int Image::getBitPerPixel() const
{
return getPixelFormatInfoMap().at(_renderFormat).bpp;
}
bool Image::hasAlpha() const
{
return getPixelFormatInfoMap().at(_renderFormat).alpha;
}
bool Image::isCompressed() const
{
return getPixelFormatInfoMap().at(_renderFormat).compressed;
}
const Image::PixelFormatInfo& Image::getPixelFormatInfo() const
{
return getPixelFormatInfoMap().at(_renderFormat);
}
namespace
{
/*
* ERROR HANDLING:
*
* The JPEG library's standard error handler (jerror.c) is divided into
* several "methods" which you can override individually. This lets you
* adjust the behavior without duplicating a lot of code, which you might
* have to update with each future release.
*
* We override the "error_exit" method so that control is returned to the
* library's caller when a fatal error occurs, rather than calling exit()
* as the standard error_exit method does.
*
* We use C's setjmp/longjmp facility to return control. This means that the
* routine which calls the JPEG library must first execute a setjmp() call to
* establish the return point. We want the replacement error_exit to do a
* longjmp(). But we need to make the setjmp buffer accessible to the
* error_exit routine. To do this, we make a private extension of the
* standard JPEG error handler object. (If we were using C++, we'd say we
* were making a subclass of the regular error handler.)
*
* Here's the extended error handler struct:
*/
#if CC_USE_JPEG
struct MyErrorMgr
{
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct MyErrorMgr * MyErrorPtr;
/*
* Here's the routine that will replace the standard error_exit method:
*/
METHODDEF(void)
myErrorExit(j_common_ptr cinfo)
{
/* cinfo->err really points to a MyErrorMgr struct, so coerce pointer */
MyErrorPtr myerr = (MyErrorPtr) cinfo->err;
/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
/* internal message function can't show error message in some platforms, so we rewrite it here.
* edit it if has version conflict.
*/
//(*cinfo->err->output_message) (cinfo);
char buffer[JMSG_LENGTH_MAX];
(*cinfo->err->format_message) (cinfo, buffer);
CCLOG("jpeg error: %s", buffer);
/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
#endif // CC_USE_JPEG
}
bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WIC
return decodeWithWIC(data, dataLen);
#elif CC_USE_JPEG
/* these are standard libjpeg structures for reading(decompression) */
struct jpeg_decompress_struct cinfo;
/* We use our private extension JPEG error handler.
* Note that this struct must live as long as the main JPEG parameter
* struct, to avoid dangling-pointer problems.
*/
struct MyErrorMgr jerr;
/* libjpeg data structure for storing one row, that is, scanline of an image */
JSAMPROW row_pointer[1] = {0};
unsigned long location = 0;
bool ret = false;
do
{
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = myErrorExit;
/* Establish the setjmp return context for MyErrorExit to use. */
if (setjmp(jerr.setjmp_buffer))
{
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object, close the input file, and return.
*/
jpeg_destroy_decompress(&cinfo);
break;
}
/* setup decompression process and source, then read JPEG header */
jpeg_create_decompress( &cinfo );
#ifndef CC_TARGET_QT5
jpeg_mem_src(&cinfo, const_cast<unsigned char*>(data), dataLen);
#endif /* CC_TARGET_QT5 */
/* reading the image header which contains image information */
#if (JPEG_LIB_VERSION >= 90)
// libjpeg 0.9 adds stricter types.
jpeg_read_header(&cinfo, TRUE);
#else
jpeg_read_header(&cinfo, TRUE);
#endif
// we only support RGB or grayscale
if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
{
_renderFormat = Image::PixelFormat::I8;
}else
{
cinfo.out_color_space = JCS_RGB;
_renderFormat = Image::PixelFormat::RGB888;
}
/* Start decompression jpeg here */
jpeg_start_decompress( &cinfo );
/* init image info */
_width = cinfo.output_width;
_height = cinfo.output_height;
_hasPremultipliedAlpha = false;
_dataLen = cinfo.output_width*cinfo.output_height*cinfo.output_components;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
CC_BREAK_IF(! _data);
/* now actually read the jpeg into the raw buffer */
/* read one scan line at a time */
while (cinfo.output_scanline < cinfo.output_height)
{
row_pointer[0] = _data + location;
location += cinfo.output_width*cinfo.output_components;
jpeg_read_scanlines(&cinfo, row_pointer, 1);
}
/* When read image file with broken data, jpeg_finish_decompress() may cause error.
* Besides, jpeg_destroy_decompress() shall deallocate and release all memory associated
* with the decompression object.
* So it doesn't need to call jpeg_finish_decompress().
*/
//jpeg_finish_decompress( &cinfo );
jpeg_destroy_decompress( &cinfo );
/* wrap up decompression, destroy objects, free pointers and close open files */
ret = true;
} while (0);
return ret;
#else
CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_JPEG
}
bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WIC
return decodeWithWIC(data, dataLen);
#elif CC_USE_PNG
// length of bytes to check if it is a valid png file
#define PNGSIGSIZE 8
bool ret = false;
png_byte header[PNGSIGSIZE] = {0};
png_structp png_ptr = 0;
png_infop info_ptr = 0;
do
{
// png header len is 8 bytes
CC_BREAK_IF(dataLen < PNGSIGSIZE);
// check the data is png or not
memcpy(header, data, PNGSIGSIZE);
CC_BREAK_IF(png_sig_cmp(header, 0, PNGSIGSIZE));
// init png_struct
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
CC_BREAK_IF(! png_ptr);
// init png_info
info_ptr = png_create_info_struct(png_ptr);
CC_BREAK_IF(!info_ptr);
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL)
CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr)));
#endif
// set the read call back function
tImageSource imageSource;
imageSource.data = (unsigned char*)data;
imageSource.size = dataLen;
imageSource.offset = 0;
png_set_read_fn(png_ptr, &imageSource, pngReadCallback);
// read png header info
// read png file info
png_read_info(png_ptr, info_ptr);
_width = png_get_image_width(png_ptr, info_ptr);
_height = png_get_image_height(png_ptr, info_ptr);
png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr);
//CCLOG("color type %u", color_type);
// force palette images to be expanded to 24-bit RGB
// it may include alpha channel
if (color_type == PNG_COLOR_TYPE_PALETTE)
{
png_set_palette_to_rgb(png_ptr);
}
// low-bit-depth grayscale images are to be expanded to 8 bits
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
{
bit_depth = 8;
png_set_expand_gray_1_2_4_to_8(png_ptr);
}
// expand any tRNS chunk data into a full alpha channel
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
{
png_set_tRNS_to_alpha(png_ptr);
}
// reduce images with 16-bit samples to 8 bits
if (bit_depth == 16)
{
png_set_strip_16(png_ptr);
}
// Expanded earlier for grayscale, now take care of palette and rgb
if (bit_depth < 8)
{
png_set_packing(png_ptr);
}
// update info
png_read_update_info(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
_renderFormat = Image::PixelFormat::I8;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
_renderFormat = Image::PixelFormat::AI88;
break;
case PNG_COLOR_TYPE_RGB:
_renderFormat = Image::PixelFormat::RGB888;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
_renderFormat = Image::PixelFormat::RGBA8888;
break;
default:
break;
}
// read png data
png_size_t rowbytes;
png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * _height );
rowbytes = png_get_rowbytes(png_ptr, info_ptr);
_dataLen = rowbytes * _height;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
if (!_data)
{
if (row_pointers != nullptr)
{
free(row_pointers);
}
break;
}
for (unsigned short i = 0; i < _height; ++i)
{
row_pointers[i] = _data + i*rowbytes;
}
png_read_image(png_ptr, row_pointers);
png_read_end(png_ptr, nullptr);
// premultiplied alpha for RGBA8888
if (PNG_PREMULTIPLIED_ALPHA_ENABLED && color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
premultipliedAlpha();
}
else
{
_hasPremultipliedAlpha = false;
}
if (row_pointers != nullptr)
{
free(row_pointers);
}
ret = true;
} while (0);
if (png_ptr)
{
png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0);
}
return ret;
#else
CCLOG("png is not enabled, please enable it in ccConfig.h");
return false;
#endif //CC_USE_PNG
}
#if CC_USE_TIFF
namespace
{
static tmsize_t tiffReadProc(thandle_t fd, void* buf, tmsize_t size)
{
tImageSource* isource = (tImageSource*)fd;
uint8* ma;
uint64 mb;
unsigned long n;
unsigned long o;
tmsize_t p;
ma=(uint8*)buf;
mb=size;
p=0;
while (mb>0)
{
n=0x80000000UL;
if ((uint64)n>mb)
n=(unsigned long)mb;
if ((int)(isource->offset + n) <= isource->size)
{
memcpy(ma, isource->data+isource->offset, n);
isource->offset += n;
o = n;
}
else
{
return 0;
}
ma+=o;
mb-=o;
p+=o;
if (o!=n)
{
break;
}
}
return p;
}
static tmsize_t tiffWriteProc(thandle_t fd, void* buf, tmsize_t size)
{
CC_UNUSED_PARAM(fd);
CC_UNUSED_PARAM(buf);
CC_UNUSED_PARAM(size);
return 0;
}
static uint64 tiffSeekProc(thandle_t fd, uint64 off, int whence)
{
tImageSource* isource = (tImageSource*)fd;
uint64 ret = -1;
do
{
if (whence == SEEK_SET)
{
CC_BREAK_IF(off >= (uint64)isource->size);
ret = isource->offset = (uint32)off;
}
else if (whence == SEEK_CUR)
{
CC_BREAK_IF(isource->offset + off >= (uint64)isource->size);
ret = isource->offset += (uint32)off;
}
else if (whence == SEEK_END)
{
CC_BREAK_IF(off >= (uint64)isource->size);
ret = isource->offset = (uint32)(isource->size-1 - off);
}
else
{
CC_BREAK_IF(off >= (uint64)isource->size);
ret = isource->offset = (uint32)off;
}
} while (0);
return ret;
}
static uint64 tiffSizeProc(thandle_t fd)
{
tImageSource* imageSrc = (tImageSource*)fd;
return imageSrc->size;
}
static int tiffCloseProc(thandle_t fd)
{
CC_UNUSED_PARAM(fd);
return 0;
}
static int tiffMapProc(thandle_t fd, void** base, toff_t* size)
{
CC_UNUSED_PARAM(fd);
CC_UNUSED_PARAM(base);
CC_UNUSED_PARAM(size);
return 0;
}
static void tiffUnmapProc(thandle_t fd, void* base, toff_t size)
{
CC_UNUSED_PARAM(fd);
CC_UNUSED_PARAM(base);
CC_UNUSED_PARAM(size);
}
}
#endif // CC_USE_TIFF
bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WIC
return decodeWithWIC(data, dataLen);
#elif CC_USE_TIFF
bool ret = false;
do
{
// set the read call back function
tImageSource imageSource;
imageSource.data = data;
imageSource.size = dataLen;
imageSource.offset = 0;
TIFF* tif = TIFFClientOpen("file.tif", "r", (thandle_t)&imageSource,
tiffReadProc, tiffWriteProc,
tiffSeekProc, tiffCloseProc, tiffSizeProc,
tiffMapProc,
tiffUnmapProc);
CC_BREAK_IF(nullptr == tif);
uint32 w = 0, h = 0;
uint16 bitsPerSample = 0, samplePerPixel = 0, planarConfig = 0;
size_t npixels = 0;
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel);
TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig);
npixels = w * h;
_renderFormat = Image::PixelFormat::RGBA8888;
_width = w;
_height = h;
_dataLen = npixels * sizeof (uint32);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
uint32* raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
if (raster != nullptr)
{
if (TIFFReadRGBAImageOriented(tif, w, h, raster, ORIENTATION_TOPLEFT, 0))
{
/* the raster data is pre-multiplied by the alpha component
after invoking TIFFReadRGBAImageOriented*/
_hasPremultipliedAlpha = true;
memcpy(_data, raster, npixels*sizeof (uint32));
}
_TIFFfree(raster);
}
TIFFClose(tif);
ret = true;
} while (0);
return ret;
#else
CCLOG("tiff is not enabled, please enable it in ccConfig.h");
return false;
#endif //CC_USE_TIFF
}
namespace
{
bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat format)
{
return true;
}
bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format)
{
switch (format) {
case PVR3TexturePixelFormat::BGRA8888:
return Configuration::getInstance()->supportsBGRA8888();
case PVR3TexturePixelFormat::PVRTC2BPP_RGB:
case PVR3TexturePixelFormat::PVRTC2BPP_RGBA:
case PVR3TexturePixelFormat::PVRTC4BPP_RGB:
case PVR3TexturePixelFormat::PVRTC4BPP_RGBA:
case PVR3TexturePixelFormat::ETC1:
case PVR3TexturePixelFormat::RGBA8888:
case PVR3TexturePixelFormat::RGBA4444:
case PVR3TexturePixelFormat::RGBA5551:
case PVR3TexturePixelFormat::RGB565:
case PVR3TexturePixelFormat::RGB888:
case PVR3TexturePixelFormat::A8:
case PVR3TexturePixelFormat::L8:
case PVR3TexturePixelFormat::LA88:
return true;
default:
return false;
}
}
}
bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen)
{
int dataLength = 0, dataOffset = 0, dataSize = 0;
int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
int width = 0, height = 0;
//Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader
const PVRv2TexHeader *header = static_cast<const PVRv2TexHeader *>(static_cast<const void*>(data));
//Make sure that tag is in correct formatting
if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0)
{
return false;
}
Configuration *configuration = Configuration::getInstance();
//can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead.
_hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied;
unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
PVR2TexturePixelFormat formatFlags = static_cast<PVR2TexturePixelFormat>(flags & PVR_TEXTURE_FLAG_TYPE_MASK);
bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false;
if (flipped)
{
CCLOG("initWithPVRv2Data: WARNING: Image is flipped. Regenerate it using PVRTexTool");
}
if (! configuration->supportsNPOT() &&
(static_cast<int>(header->width) != utils::nextPOT(header->width)
|| static_cast<int>(header->height) != utils::nextPOT(header->height)))
{
CCLOG("initWithPVRv2Data: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height);
return false;
}
if (!testFormatForPvr2TCSupport(formatFlags))
{
CCLOG("initWithPVRv2Data: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
return false;
}
if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end())
{
CCLOG("initWithPVRv2Data: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
return false;
}
auto it = getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags)));
if (it == getPixelFormatInfoMap().end())
{
CCLOG("initWithPVRv2Data: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
return false;
}
_renderFormat = it->first;
int bpp = it->second.bpp;
//Reset num of mipmaps
_numberOfMipmaps = 0;
//Get size of mipmap
_width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
_height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
//Get ptr to where data starts..
dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength);
assert(Configuration::getInstance()->supportsPVRTC());
//Move by size of header
_dataLen = dataLen - sizeof(PVRv2TexHeader);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen);
// Calculate the data size for each texture level and respect the minimum number of blocks
while (dataOffset < dataLength)
{
switch (formatFlags) {
case PVR2TexturePixelFormat::PVRTC2BPP_RGBA:
blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
widthBlocks = width / 8;
heightBlocks = height / 4;
break;
case PVR2TexturePixelFormat::PVRTC4BPP_RGBA:
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
break;
case PVR2TexturePixelFormat::BGRA8888:
if (Configuration::getInstance()->supportsBGRA8888() == false)
{
CCLOG("initWithPVRv2Data: Image. BGRA8888 not supported on this device");
return false;
}
default:
blockSize = 1;
widthBlocks = width;
heightBlocks = height;
break;
}
// Clamp to minimum number of blocks
if (widthBlocks < 2)
{
widthBlocks = 2;
}
if (heightBlocks < 2)
{
heightBlocks = 2;
}
dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
int packetLength = (dataLength - dataOffset);
packetLength = packetLength > dataSize ? dataSize : packetLength;
//Make record to the mipmaps array and increment counter
_mipmaps[_numberOfMipmaps].address = _data + dataOffset;
_mipmaps[_numberOfMipmaps].offset = dataOffset;
_mipmaps[_numberOfMipmaps].len = packetLength;
_numberOfMipmaps++;
dataOffset += packetLength;
//Update width and height to the next lower power of two
width = std::max(width >> 1, 1);
height = std::max(height >> 1, 1);
}
return true;
}
bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen)
{
if (static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
{
return false;
}
const PVRv3TexHeader *header = static_cast<const PVRv3TexHeader *>(static_cast<const void*>(data));
// validate version
if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203)
{
CCLOG("initWithPVRv3Data: WARNING: pvr file version mismatch");
return false;
}
// parse pixel format
PVR3TexturePixelFormat pixelFormat = static_cast<PVR3TexturePixelFormat>(header->pixelFormat);
if (!testFormatForPvr3TCSupport(pixelFormat))
{
CCLOG("initWithPVRv3Data: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
static_cast<unsigned long long>(pixelFormat));
return false;
}
if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end())
{
CCLOG("initWithPVRv3Data: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
static_cast<unsigned long long>(pixelFormat));
return false;
}
auto it = getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat)));
if (it == getPixelFormatInfoMap().end())
{
CCLOG("initWithPVRv3Data: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
static_cast<unsigned long long>(pixelFormat));
return false;
}
_renderFormat = it->first;
int bpp = it->second.bpp;
// flags
int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
// PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files
if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha)
{
_hasPremultipliedAlpha = true;
}
else
{
_hasPremultipliedAlpha = false;
}
// sizing
int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
_width = width;
_height = height;
int dataOffset = 0, dataSize = 0;
int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
assert(Configuration::getInstance()->supportsPVRTC());
_dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, static_cast<const unsigned char*>(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen);
_numberOfMipmaps = header->numberOfMipmaps;
CCASSERT(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increase the CC_MIPMAP_MAX value");
for (int i = 0; i < _numberOfMipmaps; i++)
{
switch ((PVR3TexturePixelFormat)pixelFormat)
{
case PVR3TexturePixelFormat::PVRTC2BPP_RGB :
case PVR3TexturePixelFormat::PVRTC2BPP_RGBA :
blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
widthBlocks = width / 8;
heightBlocks = height / 4;
break;
case PVR3TexturePixelFormat::PVRTC4BPP_RGB :
case PVR3TexturePixelFormat::PVRTC4BPP_RGBA :
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
break;
case PVR3TexturePixelFormat::ETC1:
blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
widthBlocks = width / 4;
heightBlocks = height / 4;
break;
case PVR3TexturePixelFormat::BGRA8888:
if (! Configuration::getInstance()->supportsBGRA8888())
{
CCLOG("initWithPVRv3Data: Image. BGRA8888 not supported on this device");
return false;
}
default:
blockSize = 1;
widthBlocks = width;
heightBlocks = height;
break;
}
// Clamp to minimum number of blocks
if (widthBlocks < 2)
{
widthBlocks = 2;
}
if (heightBlocks < 2)
{
heightBlocks = 2;
}
dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
auto packetLength = _dataLen - dataOffset;
packetLength = packetLength > dataSize ? dataSize : packetLength;
_mipmaps[i].address = _data + dataOffset;
_mipmaps[i].offset = dataOffset;
_mipmaps[i].len = static_cast<int>(packetLength);
dataOffset += packetLength;
CCASSERT(dataOffset <= _dataLen, "Image: Invalid length");
width = std::max(width >> 1, 1);
height = std::max(height >> 1, 1);
}
return true;
}
bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen)
{
const etc1_byte* header = static_cast<const etc1_byte*>(data);
//check the data
if (! etc1_pkm_is_valid(header))
{
return false;
}
_width = etc1_pkm_get_width(header);
_height = etc1_pkm_get_height(header);
if (0 == _width || 0 == _height)
{
return false;
}
assert(Configuration::getInstance()->supportsETC());
//old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy.
#ifdef GL_ETC1_RGB8_OES
_renderFormat = Image::PixelFormat::ETC;
_dataLen = dataLen - ETC_PKM_HEADER_SIZE;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, _dataLen);
return true;
#endif
return false;
}
bool Image::initWithTGAData(tImageTGA* tgaData)
{
bool ret = false;
do
{
CC_BREAK_IF(tgaData == nullptr);
// tgaLoadBuffer only support type 2, 3, 10
if (2 == tgaData->type || 10 == tgaData->type)
{
// true color
// unsupported RGB555
if (tgaData->pixelDepth == 16)
{
_renderFormat = Image::PixelFormat::RGB5A1;
}
else if(tgaData->pixelDepth == 24)
{
_renderFormat = Image::PixelFormat::RGB888;
}
else if(tgaData->pixelDepth == 32)
{
_renderFormat = Image::PixelFormat::RGBA8888;
}
else
{
CCLOG("Image WARNING: unsupported true color tga data pixel format. FILE: %s", _filePath.c_str());
break;
}
}
else if(3 == tgaData->type)
{
// gray
if (8 == tgaData->pixelDepth)
{
_renderFormat = Image::PixelFormat::I8;
}
else
{
// actually this won't happen, if it happens, maybe the image file is not a tga
CCLOG("Image WARNING: unsupported gray tga data pixel format. FILE: %s", _filePath.c_str());
break;
}
}
_width = tgaData->width;
_height = tgaData->height;
_data = tgaData->imageData;
_dataLen = _width * _height * tgaData->pixelDepth / 8;
_fileType = Format::TGA;
_hasPremultipliedAlpha = false;
ret = true;
}while(false);
if (ret)
{
if (FileUtils::getInstance()->getFileExtension(_filePath) != ".tga")
{
CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str());
}
}
else
{
if (tgaData && tgaData->imageData != nullptr)
{
free(tgaData->imageData);
_data = nullptr;
}
}
return ret;
}
static uint32_t makeFourCC(char ch0, char ch1, char ch2, char ch3)
{
const uint32_t fourCC = ((uint32_t)(char)(ch0) | ((uint32_t)(char)(ch1) << 8) | ((uint32_t)(char)(ch2) << 16) | ((uint32_t)(char)(ch3) << 24 ));
return fourCC;
}
bool Image::initWithS3TCData(const unsigned char * data, ssize_t dataLen)
{
const uint32_t FOURCC_DXT1 = makeFourCC('D', 'X', 'T', '1');
const uint32_t FOURCC_DXT3 = makeFourCC('D', 'X', 'T', '3');
const uint32_t FOURCC_DXT5 = makeFourCC('D', 'X', 'T', '5');
/* load the .dds file */
S3TCTexHeader *header = (S3TCTexHeader *)data;
unsigned char *pixelData = static_cast<unsigned char*>(malloc((dataLen - sizeof(S3TCTexHeader)) * sizeof(unsigned char)));
memcpy((void *)pixelData, data + sizeof(S3TCTexHeader), dataLen - sizeof(S3TCTexHeader));
_width = header->ddsd.width;
_height = header->ddsd.height;
_numberOfMipmaps = MAX(1, header->ddsd.DUMMYUNIONNAMEN2.mipMapCount); //if dds header reports 0 mipmaps, set to 1 to force correct software decoding (if needed).
_dataLen = 0;
int blockSize = (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) ? 8 : 16;
/* calculate the dataLen */
int width = _width;
int height = _height;
assert(Configuration::getInstance()->supportsS3TC());
_dataLen = dataLen - sizeof(S3TCTexHeader);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy((void *)_data,(void *)pixelData , _dataLen);
/* if hardware supports s3tc, set pixelformat before loading mipmaps, to support non-mipmapped textures */
//decode texture through hardware
if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
{
_renderFormat = PixelFormat::S3TC_DXT1;
}
else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
{
_renderFormat = PixelFormat::S3TC_DXT3;
}
else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
{
_renderFormat = PixelFormat::S3TC_DXT5;
}
/* load the mipmaps */
int encodeOffset = 0;
width = _width;
height = _height;
for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;
int size = ((width+3)/4)*((height+3)/4)*blockSize;
//decode texture through hardware
_mipmaps[i].address = (unsigned char *)_data + encodeOffset;
_mipmaps[i].offset = encodeOffset;
_mipmaps[i].len = size;
encodeOffset += size;
width >>= 1;
height >>= 1;
}
/* end load the mipmaps */
if (pixelData != nullptr)
{
free(pixelData);
}
return true;
}
bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen)
{
return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen);
}
bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen)
{
#if CC_USE_WEBP
bool ret = false;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
CCLOG("WEBP image format not supported on WinRT or WP8");
#else
do
{
WebPDecoderConfig config;
if (WebPInitDecoderConfig(&config) == 0) break;
if (WebPGetFeatures(static_cast<const uint8_t*>(data), dataLen, &config.input) != VP8_STATUS_OK) break;
if (config.input.width == 0 || config.input.height == 0) break;
config.output.colorspace = config.input.has_alpha?MODE_rgbA:MODE_RGB;
_renderFormat = config.input.has_alpha?Image::PixelFormat::RGBA8888:Image::PixelFormat::RGB888;
_width = config.input.width;
_height = config.input.height;
//we ask webp to give data with premultiplied alpha
_hasPremultipliedAlpha = (config.input.has_alpha != 0);
_dataLen = _width * _height * (config.input.has_alpha?4:3);
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
config.output.u.RGBA.rgba = static_cast<uint8_t*>(_data);
config.output.u.RGBA.stride = _width * (config.input.has_alpha?4:3);
config.output.u.RGBA.size = _dataLen;
config.output.is_external_memory = 1;
if (WebPDecode(static_cast<const uint8_t*>(data), dataLen, &config) != VP8_STATUS_OK)
{
free(_data);
_data = nullptr;
break;
}
ret = true;
} while (0);
#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
return ret;
#else
CCLOG("webp is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_WEBP
}
bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti)
{
bool ret = false;
do
{
CC_BREAK_IF(0 == width || 0 == height);
_height = height;
_width = width;
_hasPremultipliedAlpha = preMulti;
_renderFormat = Image::PixelFormat::RGBA8888;
// only RGBA8888 supported
int bytesPerComponent = 4;
_dataLen = height * width * bytesPerComponent;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
CC_BREAK_IF(! _data);
memcpy(_data, data, _dataLen);
ret = true;
} while (0);
return ret;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
bool Image::saveToFile(const std::string& filename, bool isToRGB)
{
//only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data
if (isCompressed() || (_renderFormat != Image::PixelFormat::RGB888 && _renderFormat != Image::PixelFormat::RGBA8888))
{
CCLOG("saveToFile: Image: saveToFile is only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data for now");
return false;
}
std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename);
if (fileExtension == ".png")
{
return saveImageToPNG(filename, isToRGB);
}
else if (fileExtension == ".jpg")
{
return saveImageToJPG(filename);
}
else
{
CCLOG("saveToFile: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str());
return false;
}
}
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB)
{
#if CC_USE_WIC
return encodeWithWIC(filePath, isToRGB, GUID_ContainerFormatPng);
#elif CC_USE_PNG
bool ret = false;
do
{
FILE *fp;
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette;
png_bytep *row_pointers;
fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb");
CC_BREAK_IF(nullptr == fp);
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (nullptr == png_ptr)
{
fclose(fp);
break;
}
info_ptr = png_create_info_struct(png_ptr);
if (nullptr == info_ptr)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, nullptr);
break;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL)
if (setjmp(png_jmpbuf(png_ptr)))
{
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);
break;
}
#endif
png_init_io(png_ptr, fp);
if (!isToRGB && hasAlpha())
{
png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
}
else
{
png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
}
palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color));
png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);
png_write_info(png_ptr, info_ptr);
png_set_packing(png_ptr);
row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep));
if(row_pointers == nullptr)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);
break;
}
if (!hasAlpha())
{
for (int i = 0; i < (int)_height; i++)
{
row_pointers[i] = (png_bytep)_data + i * _width * 3;
}
png_write_image(png_ptr, row_pointers);
free(row_pointers);
row_pointers = nullptr;
}
else
{
if (isToRGB)
{
unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
if (nullptr == tempData)
{
fclose(fp);
png_destroy_write_struct(&png_ptr, &info_ptr);
free(row_pointers);
row_pointers = nullptr;
break;
}
for (int i = 0; i < _height; ++i)
{
for (int j = 0; j < _width; ++j)
{
tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
}
}
for (int i = 0; i < (int)_height; i++)
{
row_pointers[i] = (png_bytep)tempData + i * _width * 3;
}
png_write_image(png_ptr, row_pointers);
free(row_pointers);
row_pointers = nullptr;
if (tempData != nullptr)
{
free(tempData);
}
}
else
{
for (int i = 0; i < (int)_height; i++)
{
row_pointers[i] = (png_bytep)_data + i * _width * 4;
}
png_write_image(png_ptr, row_pointers);
free(row_pointers);
row_pointers = nullptr;
}
}
png_write_end(png_ptr, info_ptr);
png_free(png_ptr, palette);
palette = nullptr;
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
ret = true;
} while (0);
return ret;
#else
CCLOG("png is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_PNG
}
bool Image::saveImageToJPG(const std::string& filePath)
{
#if CC_USE_WIC
return encodeWithWIC(filePath, false, GUID_ContainerFormatJpeg);
#elif CC_USE_JPEG
bool ret = false;
do
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE * outfile; /* target file */
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
int row_stride; /* physical row width in image buffer */
cinfo.err = jpeg_std_error(&jerr);
/* Now we can initialize the JPEG compression object. */
jpeg_create_compress(&cinfo);
CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr);
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = _width; /* image width and height, in pixels */
cinfo.image_height = _height;
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 90, TRUE);
jpeg_start_compress(&cinfo, TRUE);
row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */
if (hasAlpha())
{
unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
if (nullptr == tempData)
{
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(outfile);
break;
}
for (int i = 0; i < _height; ++i)
{
for (int j = 0; j < _width; ++j)
{
tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
}
}
while (cinfo.next_scanline < cinfo.image_height)
{
row_pointer[0] = & tempData[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
if (tempData != nullptr)
{
free(tempData);
}
}
else
{
while (cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = & _data[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
}
jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);
ret = true;
} while (0);
return ret;
#else
CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
return false;
#endif // CC_USE_JPEG
}
void Image::premultipliedAlpha()
{
if (PNG_PREMULTIPLIED_ALPHA_ENABLED && _renderFormat == Image::PixelFormat::RGBA8888)
{
unsigned int* fourBytes = (unsigned int*)_data;
for(int i = 0; i < _width * _height; i++)
{
unsigned char* p = _data + i * 4;
fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]);
}
_hasPremultipliedAlpha = true;
}
else
{
_hasPremultipliedAlpha = false;
return;
}
}
void Image::setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied)
{
_PVRHaveAlphaPremultiplied = haveAlphaPremultiplied;
}
NS_CC_END
| [
"399500269@qq.com"
] | 399500269@qq.com |
c5049c7110bde7f4b6b62d772b3f846abfe92cae | c67dbdad03baee2d255586d6db34b7e96072a355 | /src/impl_windows.cpp | 3be175bd05157990e347b5e65136c1c44b0eba4a | [] | no_license | rayburgemeestre/SuperMouser | d8275347b5a25b404e990403c934706717726c2a | 97bcaf0df242dc26832dcfcaa86eae3412d2ec0f | refs/heads/master | 2020-06-02T21:56:13.120024 | 2013-12-16T10:46:46 | 2013-12-16T10:46:46 | 1,573,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,352 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: abstractwindow.cpp
// Purpose:
// Author: Ray Burgemeestre
// Modified by:
// Created: 04/04/2011 19:32:52
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#ifdef __WXMSW__
#include "AbstractWindow.h"
void init_screensize(int *width, int *height)
{
wxDisplaySize(width, height);
}
void register_hotkey(AbstractWindow *window)
{
window->RegisterHotKey(wxID_ANY, wxMOD_CONTROL | wxMOD_SHIFT, 'M');
}
void move_to(int x, int y)
{
SetCursorPos(x, y);
}
void click_left(int x, int y)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
void click_right(int x, int y)
{
mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
}
void click_double(int x, int y)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
GetDoubleClickTime;
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
#endif // __WXMSW__ | [
"ray.burgemeestre@gmail.com"
] | ray.burgemeestre@gmail.com |
609e13d9d322e68540ad0aacb96d8f66b0b4e48e | 4547c086eb45aeec361679e80e52148a6e4d9519 | /source/Main.cpp | a5ebcfddd03d5492b63e1b7db397bc13e496b2a7 | [] | no_license | balazsbanto/VolumetricRayCasting-GL | 753c174316bdd5206b064dbaa024328766a5539c | 6382605628ada55068964865d69dc095eb8e8740 | refs/heads/master | 2021-05-21T16:37:41.786985 | 2020-12-30T11:06:09 | 2020-12-30T11:06:09 | 252,719,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,536 | cpp | // Qt5 includes
#include <QGuiApplication>
#include <QMessageLogger>
#include <QCommandLineParser>
// Custom made includes
#include <InteropWindowImpl.hpp>
// SYCL include
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4310 ) // Prevents warning about cast truncates constant value
#pragma warning( disable : 4100 ) // Prevents warning about unreferenced formal parameter
#endif
#include <CL/sycl.hpp>
#ifdef _MSC_VER
#pragma warning( pop )
#endif
#include <LatticeBoltzmann2D.hpp>
#include <RaycasterLatticeBoltzmann2D.hpp>
#include <RaycasterLbm3D.hpp>
#include <SphericalHarmonicsRaycaster.hpp>
#include <CubeRaycaster.hpp>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QCoreApplication::setApplicationName("SYCL-GL Raycaster sample");
QCoreApplication::setApplicationVersion("1.0");
QCommandLineParser parser;
parser.setApplicationDescription("Sample application demonstrating OpenCL-OpenGL interop");
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({
{{"p", "platform"}, "The index of the platform to use", "unsigned integral", "0"},
{{"d", "device"}, "The index of the device to use", "unsigned integral", "0"},
{{"t", "type"}, "Device type to use", "[cpu|gpu|acc]", "def"}
});
parser.process(app);
cl_bitfield dev_type = CL_DEVICE_TYPE_DEFAULT;
std::size_t plat_id = 0u, dev_id = 0u;
if (!parser.value("platform").isEmpty()) plat_id = parser.value("platform").toULong();
if (!parser.value("device").isEmpty()) dev_id = parser.value("device").toULong();
//if(!parser.value("type").isEmpty())
//{
// if(parser.value("type") == "cpu")
// dev_type = CL_DEVICE_TYPE_CPU;
// else if(parser.value("type") == "gpu")
// dev_type = CL_DEVICE_TYPE_GPU;
// else if(parser.value("type") == "acc")
// dev_type = CL_DEVICE_TYPE_ACCELERATOR;
// else
// {
// qFatal("SYCL-InteropWindowImpl: Invalid device type: valid values are [cpu|gpu|acc]. Using CL_DEVICE_TYPE_DEFAULT instead.");
// }
//}
dev_type = CL_DEVICE_TYPE_GPU;
//RaycasterLbm3D raycaster(plat_id, dev_id, dev_type);
//RaycasterLatticeBoltzmann2D raycaster(plat_id, dev_id, dev_type);
LatticeBoltzmann2D raycaster(plat_id, dev_id, dev_type);
//SphericalHarmonicsRaycaster raycaster(plat_id, dev_id, dev_type);
//CubeRaycaster raycaster(plat_id, dev_id, dev_type);
raycaster.setGeometry(QRect(0, 0, 256, 256));
raycaster.setVisibility(QWindow::Windowed);
//raycaster.setVisibility(QWindow::Maximized);
raycaster.setAnimating(false);
// Qt5 constructs
QSurfaceFormat my_surfaceformat;
// Setup desired format
my_surfaceformat.setRenderableType(QSurfaceFormat::RenderableType::OpenGL);
my_surfaceformat.setProfile(QSurfaceFormat::OpenGLContextProfile::CoreProfile);
my_surfaceformat.setSwapBehavior(QSurfaceFormat::SwapBehavior::DoubleBuffer);
my_surfaceformat.setOption(QSurfaceFormat::DebugContext);
my_surfaceformat.setMajorVersion(3);
my_surfaceformat.setMinorVersion(3);
my_surfaceformat.setRedBufferSize(8);
my_surfaceformat.setGreenBufferSize(8);
my_surfaceformat.setBlueBufferSize(8);
my_surfaceformat.setAlphaBufferSize(8);
my_surfaceformat.setDepthBufferSize(24);
my_surfaceformat.setStencilBufferSize(8);
my_surfaceformat.setStereo(false);
raycaster.setFormat(my_surfaceformat);
return app.exec();
}
| [
"balazs.banto@agroninja.com"
] | balazs.banto@agroninja.com |
44c2e3b23d437591b1cefe1243dee26516edb263 | 2091684e56ab65127b44908e0ad93a908325331b | /ECE 250/avltree/bailyTest.cpp | bff8a47c2cb9ff82969c91f680bb4bd956d59bfa | [] | no_license | NathanielRN/uwaterloo-class-resources | c3d5b150ade4e992186d7b8096eb584fe19e7cfd | 38a6e43e81f523f84cc04c18e1d59e79a8344750 | refs/heads/master | 2023-06-18T07:01:13.070547 | 2021-07-11T06:33:49 | 2021-07-11T06:33:49 | 384,876,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,497 | cpp | /*
* Bailey Thompson
* github.com/bkthomps
*
* Automated test for AVL tree and iterator. Make sure to make your inner Node
* class is public for this test.
*/
#include <iostream>
#include <cassert>
#include "Search_tree.h"
static void forward_iterate(Search_tree<int>& tree) {
int count = 0;
int last = -13371337;
for (auto itr = tree.begin(); itr != tree.end(); ++itr) {
int num = *itr;
assert(last < num);
last = num;
count++;
}
assert(count == tree.size());
}
static void reverse_iterate(Search_tree<int>& tree) {
int count = 0;
int last = 13371337;
for (auto itr = tree.rbegin(); itr != tree.rend(); --itr) {
int num = *itr;
assert(last > num);
last = num;
count++;
}
assert(count == tree.size());
}
static void verify_avl_tree(Search_tree<int>::Node* node) {
if (!node) {
return;
}
if (node->left_tree) {
assert(node->left_tree->node_value < node->node_value);
}
if (node->right_tree) {
assert(node->right_tree->node_value > node->node_value);
}
verify_avl_tree(node->left_tree);
verify_avl_tree(node->right_tree);
}
static bool stub_insert(Search_tree<int>& me, int obj) {
bool ret = me.insert(obj);
verify_avl_tree(me.root_node);
forward_iterate(me);
reverse_iterate(me);
return ret;
}
static bool contains_recurse(Search_tree<int>::Node* node, int obj) {
if (!node) {
return false;
}
if (node->node_value == obj) {
return true;
}
return contains_recurse(node->left_tree, obj) || contains_recurse(node->right_tree, obj);
}
static bool stub_contains(Search_tree<int>& me, int obj) {
bool ret = contains_recurse(me.root_node, obj);
verify_avl_tree(me.root_node);
forward_iterate(me);
reverse_iterate(me);
return ret;
}
int main() {
{
Search_tree<int> me{};
int key;
// left-left
key = 5;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 1;
stub_insert(me, key);
key = 0xdeadbeef;
me.clear();
// right-right
key = 1;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 5;
stub_insert(me, key);
key = 0xdeadbeef;
me.clear();
// left-right
key = 5;
stub_insert(me, key);
key = 1;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 0xdeadbeef;
me.clear();
// right-left
key = 1;
stub_insert(me, key);
key = 5;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 0xdeadbeef;
me.clear();
// Two children edge case.
key = 8;
stub_insert(me, key);
key = 5;
stub_insert(me, key);
key = 11;
stub_insert(me, key);
key = 2;
stub_insert(me, key);
key = 6;
stub_insert(me, key);
key = 10;
stub_insert(me, key);
key = 15;
stub_insert(me, key);
key = 1;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 4;
stub_insert(me, key);
key = 7;
stub_insert(me, key);
key = 9;
stub_insert(me, key);
key = 12;
stub_insert(me, key);
key = 13;
stub_insert(me, key);
key = 16;
stub_insert(me, key);
key = 14;
me.clear();
// Two children edge case.
key = 8;
stub_insert(me, key);
key = 4;
stub_insert(me, key);
key = 12;
stub_insert(me, key);
key = 2;
stub_insert(me, key);
key = 6;
stub_insert(me, key);
key = 10;
stub_insert(me, key);
key = 15;
stub_insert(me, key);
key = 1;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 5;
stub_insert(me, key);
key = 7;
stub_insert(me, key);
key = 9;
stub_insert(me, key);
key = 11;
stub_insert(me, key);
key = 13;
stub_insert(me, key);
key = 16;
stub_insert(me, key);
key = 14;
stub_insert(me, key);
me.clear();
// Add a lot of items.
int count = 0;
bool flip = false;
for (int i = 1234; i < 82400; i++) {
int num = i % 765;
const bool is_already_present = !stub_insert(me, num);
const bool is_now_present = !stub_insert(me, num);
if (!is_already_present && is_now_present) {
count++;
}
if (i == 1857 && !flip) {
i *= -1;
flip = true;
}
}
assert(count == me.size());
} // Destructor call
{
Search_tree<int> me{};
assert(me.size() == 0);
assert(me.empty());
int key = 4;
stub_insert(me, key);
assert(me.size() == 1);
stub_insert(me, key);
assert(me.size() == 1);
assert(!me.empty());
assert(stub_contains(me, key));
key = 7;
assert(!stub_contains(me, key));
stub_insert(me, key);
assert(me.size() == 2);
assert(stub_contains(me, key));
int c[10] = {5, 9, 4, -5, 0, 6, 1, 5, 7, 2};
for (int i = 0; i < 10; i++) {
stub_insert(me, c[i]);
assert(stub_contains(me, c[i]));
}
assert(me.size() == 9);
for (int i = 0; i < 10; i++) {
assert(stub_contains(me, c[i]));
}
for (int i = -100; i < 100; i++) {
bool contains = false;
for (int j = 0; j < 10; j++) {
if (c[j] == i) {
contains = true;
}
}
assert(stub_contains(me, i) == contains);
}
int num = -3;
assert(!me.erase(num));
assert(me.size() == 9);
assert(!stub_contains(me, num));
num = 6;
assert(me.erase(num));
assert(me.size() == 8);
assert(!stub_contains(me, num));
num = 4;
assert(me.erase(num));
assert(me.size() == 7);
assert(!stub_contains(me, num));
num = 7;
assert(me.erase(num));
assert(me.size() == 6);
assert(!stub_contains(me, num));
num = 9;
assert(me.erase(num));
assert(me.size() == 5);
assert(!stub_contains(me, num));
num = -5;
assert(me.erase(num));
assert(me.size() == 4);
assert(!stub_contains(me, num));
num = 0;
assert(me.erase(num));
assert(me.size() == 3);
assert(!stub_contains(me, num));
num = 1;
assert(me.erase(num));
assert(me.size() == 2);
assert(!stub_contains(me, num));
num = 5;
assert(me.erase(num));
assert(me.size() == 1);
assert(!stub_contains(me, num));
num = 2;
assert(me.erase(num));
assert(me.size() == 0);
assert(!stub_contains(me, num));
// Add a lot of items and remove individually.
for (int i = 5000; i < 6000; i++) {
stub_insert(me, i);
assert(stub_contains(me, i));
}
assert(me.size() == 1000);
for (int i = 5000; i < 5500; i++) {
me.erase(i);
assert(!stub_contains(me, i));
}
assert(me.size() == 500);
assert(!me.empty());
me.clear();
assert(me.size() == 0);
assert(me.empty());
// Add a lot of items and clear.
for (int i = 5000; i < 6000; i++) {
stub_insert(me, i);
assert(stub_contains(me, i));
}
assert(me.size() == 1000);
me.clear();
int p = 0xdeadbeef;
assert(!me.erase(p));
assert(me.size() == 0);
assert(me.empty());
} // Call destructor
{
// Create odd shape graph.
Search_tree<int> me{};
int key = 10;
stub_insert(me, key);
key = 5;
stub_insert(me, key);
key = 15;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 8;
stub_insert(me, key);
key = 12;
stub_insert(me, key);
key = 18;
stub_insert(me, key);
key = 12;
me.erase(key);
key = 5;
me.erase(key);
key = 3;
me.erase(key);
key = 8;
me.erase(key);
me.clear();
// Allocate many nodes.
for (int i = 8123; i < 12314; i += 3) {
stub_insert(me, i);
assert(stub_contains(me, i));
}
for (int i = 13000; i > 8000; i--) {
stub_insert(me, i);
assert(stub_contains(me, i));
}
me.clear();
// Create another odd shape graph.
key = 20;
stub_insert(me, key);
key = 10;
stub_insert(me, key);
key = 40;
stub_insert(me, key);
key = 5;
stub_insert(me, key);
key = 15;
stub_insert(me, key);
key = 30;
stub_insert(me, key);
key = 50;
stub_insert(me, key);
key = 25;
stub_insert(me, key);
key = 35;
stub_insert(me, key);
key = 36;
stub_insert(me, key);
key = 34;
stub_insert(me, key);
key = 33;
stub_insert(me, key);
key = 32;
stub_insert(me, key);
key = 30;
me.erase(key);
key = 32;
assert(stub_contains(me, key));
me.clear();
// One sided tree.
key = 10;
stub_insert(me, key);
key = 9;
stub_insert(me, key);
key = 8;
stub_insert(me, key);
key = 7;
stub_insert(me, key);
key = 8;
me.erase(key);
key = 7;
assert(stub_contains(me, key));
} // Call constructor
// Replace two sided two children.
Search_tree<int> me{};
int key = 5;
stub_insert(me, key);
key = 1;
stub_insert(me, key);
key = 6;
stub_insert(me, key);
key = -1;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 7;
stub_insert(me, key);
key = -2;
stub_insert(me, key);
key = 0;
stub_insert(me, key);
key = 2;
stub_insert(me, key);
key = 4;
stub_insert(me, key);
key = 1;
me.erase(key);
assert(!stub_contains(me, key));
me.clear();
key = 5;
stub_insert(me, key);
key = 1;
stub_insert(me, key);
key = 6;
stub_insert(me, key);
key = -1;
stub_insert(me, key);
key = 3;
stub_insert(me, key);
key = 7;
stub_insert(me, key);
key = -2;
stub_insert(me, key);
key = 0;
stub_insert(me, key);
key = 4;
stub_insert(me, key);
key = 1;
me.erase(key);
assert(!stub_contains(me, key));
}
| [
"nathanielruiz98@gmail.com"
] | nathanielruiz98@gmail.com |
9cf267bd325aab9a25fa70d8d30040baec9d10cd | 94a85a1b28ca1a55634490c32540241f4f60a3e6 | /module_4/ex01/PlasmaRifle.cpp | 88b8f4eea690ea788dbdba62d630f2bb4793b2cb | [] | no_license | Saske912/cpp | 054507793021d90bb174f3039639b74f36f4f05d | 05691dca31531b3ce865189dee2c692ba4d5f21f | refs/heads/master | 2023-05-28T12:29:28.884531 | 2021-06-08T01:46:30 | 2021-06-08T01:46:30 | 353,736,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | cpp | //
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣠⣴⣖⣁⣀⣀⡄⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⢀⣀⣠⣴⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⣤⣄⣀⣀
// ⠀⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠁
// ⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠁⠀
// ⠀⠀⠀⠀⠀⣼⣿⡟⠀⢠⡲⠖⠀⣿⣿⣿⣿⣿⣿⣿⣉⠁⠀⠀⠀
// ╱╱╱╱╭━╮╭╮ ⣼⣿⣿⡷⢤⠤⠤⣥⡤⣿⠿⣿⣿⣿⡿⣿⣿⣷⡀
// ╱╱╱╱┃╭╯┃┃ ⠀⣀⣠⣼⣿⣿⣿⣧⠑⠟⠀⠈⠙⠱⢦⣿⣿⣿⠁⣸⣿⣿⣇⠀
// ╭━━┳╯╰┳┫┃╭━━╮ ⠊⠉⠉⠉⠉⠩⠞⠁⠀⠀⠄⠀⠀⡴⣿⣿⣿⠗⣵⣿⠡⠉⠉⠁⠀
// ┃╭╮┣╮╭╋┫┃┃┃━┫ ⠀⢡⠀⠀⠀⢈⣾⣟⣵⣯⣼⣿⣬⣄⣀⠀⠀
// ┃╰╯┃┃┃┃┃╰┫┃━┫ ⠀⠀⣶⣶⣶⣾⣥⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀
// ┃╭━╯╰╯╰┻━┻━━╯ ⠀⢺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⡄
// ┃┃ ⢠⢤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣿⣿⣿⣿⣿⣿⡄
// ╰╯ ⠀⠠⣰⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠇⠀
// 27.02.2021⠀⠀⠀⠀
//
#include "PlasmaRifle.hpp"
#include <iostream>
PlasmaRifle::PlasmaRifle( void ) : AWeapon("Plasma Rifle", 5, 21) {
}
PlasmaRifle::~PlasmaRifle( void ) {
}
PlasmaRifle::PlasmaRifle( PlasmaRifle const &src ) {
*this = src;
}
PlasmaRifle &PlasmaRifle::operator=( PlasmaRifle const &rhs ) {
(void)rhs;
return *this;
}
void PlasmaRifle::attack( ) const
{
std::cout << "* piouuu piouuu piouuu *" << std::endl;
} | [
"pfile@student.21-school.ru"
] | pfile@student.21-school.ru |
ab0d961f0c77f7a9b812dbc78e68bd158c66e5f1 | 6e28d6f7bc3d01cd33a30025f34f0419f9473838 | /Game/libs/Box2D/Collision/b2CollidePolygon.cpp | 340eb13d095dce892b82f3260be8ce29f081d5df | [
"MIT",
"Apache-2.0",
"Zlib"
] | permissive | dev2dev/tiny-wings | 721d7d7fdf6efcc2eafd7f05e7b0eb854020828e | 27d5625b864a85863807fbabb25c0e8689351cce | refs/heads/master | 2021-01-18T16:40:05.700629 | 2011-06-13T09:45:16 | 2011-06-13T09:45:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,777 | cpp | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/b2Collision.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
// Find the separation between poly1 and poly2 for a give edge normal on poly1.
static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1,
const b2PolygonShape* poly2, const b2Transform& xf2)
{
// int32 count1 = poly1->m_vertexCount;
const b2Vec2* vertices1 = poly1->m_vertices;
const b2Vec2* normals1 = poly1->m_normals;
int32 count2 = poly2->m_vertexCount;
const b2Vec2* vertices2 = poly2->m_vertices;
b2Assert(0 <= edge1 && edge1 < count1);
// Convert normal from poly1's frame into poly2's frame.
b2Vec2 normal1World = b2Mul(xf1.R, normals1[edge1]);
b2Vec2 normal1 = b2MulT(xf2.R, normal1World);
// Find support vertex on poly2 for -normal.
int32 index = 0;
float32 minDot = b2_maxFloat;
for (int32 i = 0; i < count2; ++i)
{
float32 dot = b2Dot(vertices2[i], normal1);
if (dot < minDot)
{
minDot = dot;
index = i;
}
}
b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]);
b2Vec2 v2 = b2Mul(xf2, vertices2[index]);
float32 separation = b2Dot(v2 - v1, normal1World);
return separation;
}
// Find the max separation between poly1 and poly2 using edge normals from poly1.
static float32 b2FindMaxSeparation(int32* edgeIndex,
const b2PolygonShape* poly1, const b2Transform& xf1,
const b2PolygonShape* poly2, const b2Transform& xf2)
{
int32 count1 = poly1->m_vertexCount;
const b2Vec2* normals1 = poly1->m_normals;
// Vector pointing from the centroid of poly1 to the centroid of poly2.
b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid);
b2Vec2 dLocal1 = b2MulT(xf1.R, d);
// Find edge normal on poly1 that has the largest projection onto d.
int32 edge = 0;
float32 maxDot = -b2_maxFloat;
for (int32 i = 0; i < count1; ++i)
{
float32 dot = b2Dot(normals1[i], dLocal1);
if (dot > maxDot)
{
maxDot = dot;
edge = i;
}
}
// Get the separation for the edge normal.
float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2);
// Check the separation for the previous edge normal.
int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1;
float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2);
// Check the separation for the next edge normal.
int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0;
float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2);
// Find the best edge and the search direction.
int32 bestEdge;
float32 bestSeparation;
int32 increment;
if (sPrev > s && sPrev > sNext)
{
increment = -1;
bestEdge = prevEdge;
bestSeparation = sPrev;
}
else if (sNext > s)
{
increment = 1;
bestEdge = nextEdge;
bestSeparation = sNext;
}
else
{
*edgeIndex = edge;
return s;
}
// Perform a local search for the best edge normal.
for ( ; ; )
{
if (increment == -1)
edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1;
else
edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0;
s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2);
if (s > bestSeparation)
{
bestEdge = edge;
bestSeparation = s;
}
else
{
break;
}
}
*edgeIndex = bestEdge;
return bestSeparation;
}
static void b2FindIncidentEdge(b2ClipVertex c[2],
const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1,
const b2PolygonShape* poly2, const b2Transform& xf2)
{
// int32 count1 = poly1->m_vertexCount;
const b2Vec2* normals1 = poly1->m_normals;
int32 count2 = poly2->m_vertexCount;
const b2Vec2* vertices2 = poly2->m_vertices;
const b2Vec2* normals2 = poly2->m_normals;
b2Assert(0 <= edge1 && edge1 < count1);
// Get the normal of the reference edge in poly2's frame.
b2Vec2 normal1 = b2MulT(xf2.R, b2Mul(xf1.R, normals1[edge1]));
// Find the incident edge on poly2.
int32 index = 0;
float32 minDot = b2_maxFloat;
for (int32 i = 0; i < count2; ++i)
{
float32 dot = b2Dot(normal1, normals2[i]);
if (dot < minDot)
{
minDot = dot;
index = i;
}
}
// Build the clip vertices for the incident edge.
int32 i1 = index;
int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0;
c[0].v = b2Mul(xf2, vertices2[i1]);
c[0].id.features.referenceEdge = (uint8)edge1;
c[0].id.features.incidentEdge = (uint8)i1;
c[0].id.features.incidentVertex = 0;
c[1].v = b2Mul(xf2, vertices2[i2]);
c[1].id.features.referenceEdge = (uint8)edge1;
c[1].id.features.incidentEdge = (uint8)i2;
c[1].id.features.incidentVertex = 1;
}
// Find edge normal of max separation on A - return if separating axis is found
// Find edge normal of max separation on B - return if separation axis is found
// Choose reference edge as min(minA, minB)
// Find incident edge
// Clip
// The normal points from 1 to 2
void b2CollidePolygons(b2Manifold* manifold,
const b2PolygonShape* polyA, const b2Transform& xfA,
const b2PolygonShape* polyB, const b2Transform& xfB)
{
manifold->pointCount = 0;
float32 totalRadius = polyA->m_radius + polyB->m_radius;
int32 edgeA = 0;
float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB);
if (separationA > totalRadius)
return;
int32 edgeB = 0;
float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA);
if (separationB > totalRadius)
return;
const b2PolygonShape* poly1; // reference polygon
const b2PolygonShape* poly2; // incident polygon
b2Transform xf1, xf2;
int32 edge1; // reference edge
uint8 flip;
const float32 k_relativeTol = 0.98f;
const float32 k_absoluteTol = 0.001f;
if (separationB > k_relativeTol * separationA + k_absoluteTol)
{
poly1 = polyB;
poly2 = polyA;
xf1 = xfB;
xf2 = xfA;
edge1 = edgeB;
manifold->type = b2Manifold::e_faceB;
flip = 1;
}
else
{
poly1 = polyA;
poly2 = polyB;
xf1 = xfA;
xf2 = xfB;
edge1 = edgeA;
manifold->type = b2Manifold::e_faceA;
flip = 0;
}
b2ClipVertex incidentEdge[2];
b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
int32 count1 = poly1->m_vertexCount;
const b2Vec2* vertices1 = poly1->m_vertices;
b2Vec2 v11 = vertices1[edge1];
b2Vec2 v12 = edge1 + 1 < count1 ? vertices1[edge1+1] : vertices1[0];
b2Vec2 localTangent = v12 - v11;
localTangent.Normalize();
b2Vec2 localNormal = b2Cross(localTangent, 1.0f);
b2Vec2 planePoint = 0.5f * (v11 + v12);
b2Vec2 tangent = b2Mul(xf1.R, localTangent);
b2Vec2 normal = b2Cross(tangent, 1.0f);
v11 = b2Mul(xf1, v11);
v12 = b2Mul(xf1, v12);
// Face offset.
float32 frontOffset = b2Dot(normal, v11);
// Side offsets, extended by polytope skin thickness.
float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius;
float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius;
// Clip incident edge against extruded edge1 side edges.
b2ClipVertex clipPoints1[2];
b2ClipVertex clipPoints2[2];
int np;
// Clip to box side 1
np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1);
if (np < 2)
return;
// Clip to negative box side 1
np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2);
if (np < 2)
{
return;
}
// Now clipPoints2 contains the clipped points.
manifold->localNormal = localNormal;
manifold->localPoint = planePoint;
int32 pointCount = 0;
for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
{
float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset;
if (separation <= totalRadius)
{
b2ManifoldPoint* cp = manifold->points + pointCount;
cp->localPoint = b2MulT(xf2, clipPoints2[i].v);
cp->id = clipPoints2[i].id;
cp->id.features.flip = flip;
++pointCount;
}
}
manifold->pointCount = pointCount;
}
| [
"st@haqu.net"
] | st@haqu.net |
0dcc063a315250ff1d6d2e46c5196143a84ecc9a | 33b1f0b8915b2934dcd6cbc19d89b88f74f009b9 | /PROJECT/server/GameServer/Include/ThingContainer.h | bbc382b88bf7cfc0dfd3d3809c4e789f177afa0e | [] | no_license | huangtao/codeview | 3a8dab3a402401e5287fec88eb050f030d0151a3 | 6534217b5915ddc3367e64266a2bf324c28bf0b1 | refs/heads/master | 2020-04-11T11:00:28.706157 | 2016-09-27T23:48:53 | 2016-09-27T23:48:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,031 | h |
#ifndef __THINGSERVER_THING_CONTAINER_H__
#define __THINGSERVER_THING_CONTAINER_H__
#include <vector>
#include "IThing.h"
#include "IGameWorld.h"
#include "IVisitWorldThing.h"
#include "IActor.h"
//用来放置所有的游戏对象
class ThingContainer
{
//所有游戏对象的Map
typedef std::hash_map<UID, IThing*,std::hash<UID>, std::equal_to<UID> > THING_MAP;
typedef std::vector<THING_MAP> THING_TYPE_MAP;
THING_TYPE_MAP m_emap;
public:
ThingContainer()
{
for(int i=0; i<enThing_Class_Max; i++)
{
m_emap.push_back(THING_MAP());
}
//m_emap.resize(enThing_Class_Max);
}
bool AddThing(IThing * pthing)
{
if(pthing==0)
{
return false;
}
enThing_Class thingclass = pthing->GetThingClass();
UID uid = pthing->GetUID();
m_emap[thingclass][uid] = pthing;
return true;
}
void RemoveThing(const UID & uid)
{
if(!uid.IsValid())
{
return ;
}
m_emap[uid.m_thingClass].erase(uid);
}
void RemoveThing(IThing * pThing)
{
if(pThing == 0)
{
return;
}
RemoveThing(pThing->GetUID());
}
//通过UID查询对象
IThing* GetThing(const UID & uid) const
{
if(!uid.IsValid() || uid.m_thingClass >= enThing_Class_Max)
{
return 0;
}
const THING_MAP & ThingMap = m_emap[uid.m_thingClass];
THING_MAP::const_iterator it = ThingMap.find(uid);
if (it == m_emap[uid.m_thingClass].end())
{
return 0;
}
return it->second;
}
//通过UserID获取人物
IActor * GetUserByUserID(TUserID userID) const
{
const THING_MAP & ActorMap = m_emap[enThing_Class_Actor];
THING_MAP::const_iterator iter = ActorMap.begin();
for( ; iter != ActorMap.end(); ++iter)
{
IActor * pActor = (IActor *)(iter->second);
if( 0 == pActor){
continue;
}
if( userID == pActor->GetCrtProp(enCrtProp_ActorUserID)){
return pActor;
}
}
return 0;
}
//返回指定类型的实体数量
int GetThingCount(enThing_Class cls) { return m_emap[cls].size();}
//访问世界指定类事物
void Visit(enThing_Class cls, IVisitWorldThing & VisitThing)
{
THING_MAP & emap = m_emap[cls];
for(THING_MAP::iterator it = emap.begin(); it != emap.end(); )
{
IThing* pThing = it->second;
++it;//提前++, 防止遍历器失效
VisitThing.Visit(pThing);
}
}
//移除指定类事物
void RemoveThingClass(enThing_Class cls)
{
THING_MAP & emap = m_emap[cls];
emap.clear();
}
///通过这个访问者,提供遍历等扩展操作
template <class Visitor> void Visit(Visitor & v);
template <class Visitor> void Visit(enThing_Class cls, Visitor & v);
};
template <class Visitor>
void ThingContainer::Visit(enThing_Class cls,Visitor & v)
{
THING_MAP & emap = m_emap[cls];
for(THING_MAP::iterator it = emap.begin(); it != emap.end(); )
{
IThing* pThing = it->second;
++it;//提前++, 防止遍历器失效
v(pThing);
}
}
template <class Visitor>
void ThingContainer::Visit(Visitor & v)
{
for(int k =0; k< enThing_Class_Max; ++k)
{
Visit((enThing_Class)k, v);
}
}
#endif
| [
"[309930133@qq.com]"
] | [309930133@qq.com] |
1a5079a955f81bda6109fdfe9181db7b955833c8 | 7c6ddc8c816029766d485fc9fe5348ac4b6a9129 | /src/PositionSensor.cpp | 4371be9bd8ecc659a19776f6d49841f388f8c024 | [
"Unlicense"
] | permissive | oturpe/crystal-c-levitation | b2b8358408076fb53a845d59497f81dd2d9235da | 1ff5d4c524d7a6599c80982cdb7d777ad53de6f9 | refs/heads/master | 2016-09-11T08:19:44.012097 | 2014-02-21T17:15:53 | 2014-02-21T17:15:53 | 13,458,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,100 | cpp | /*
* PositionSensor.cpp
*
* Created on: 11.11.2013
* Author: Otto Urpelainen
*/
// Precompiled library dependencies
#include "Arduino.h"
// Project configuration
#include "CrystalCLevitation.h"
// In-project dependencies
#include "PositionSensor.h"
PositionSensor::PositionSensor(int sensorPin,int resetPin) :
sensorPin(sensorPin), resetPin(resetPin), positionCursor(0), smoothPosition(0), resetValue(0) {
pinMode(resetPin,INPUT_PULLUP);
}
int PositionSensor::read() {
int position = analogRead(sensorPin) - resetValue;
if (position <= SENSOR_QUIESCENT_TOLERANCE) {
return -1;
}
// Increment cursor
positionCursor = (positionCursor + 1) % POSITION_SAMPLES;
// Read new value and adjust smooth reading.
smoothPosition -= positions[positionCursor];
positions[positionCursor] = position;
smoothPosition += positions[positionCursor];
return smoothPosition / POSITION_SAMPLES;
}
void PositionSensor::readParameters() {
if(digitalRead(resetPin) == HIGH) {
return;
}
resetValue = analogRead(sensorPin);
}
| [
"oturpe@iki.fi"
] | oturpe@iki.fi |
2a338f0c00f389f6052b5df26716f4d40962db37 | 981511cfbb6533914af0f72bdf4d779ad7a1c9ae | /cppHellow/85类模板头文件和源文件分离/Person.hpp | bbde46a120099536986eead6f027b99d860e0795 | [
"Apache-2.0"
] | permissive | coderTong/cppStudy | f59b70f0550bde3da414b4793900b24b652a20cb | fddf4954395b5e9b89471c1a15d33f3554710105 | refs/heads/master | 2023-01-22T21:14:00.648666 | 2020-12-05T05:11:51 | 2020-12-05T05:11:51 | 282,211,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 689 | hpp | //
// Person.hpp
// 85类模板头文件和源文件分离
//
// Created by codew on 10/5/20.
// Copyright © 2020 codertom. All rights reserved.
//
#ifndef Person_hpp
#define Person_hpp
#include <stdio.h>
#pragma once
using namespace std;
template <class T1, class T2>
class Person {
public:
Person(T1 name, T2 age);
void showPerson();
public:
T1 name;
T2 age;
};
template <class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
template <class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << "name: " << this->name << " age: " << this->age << endl;
}
#endif /* Person_hpp */
| [
"tong.wu@netviewtech.com"
] | tong.wu@netviewtech.com |
c98f6c85cece69bafe7bafa6f75665e4b64928a0 | 59ec5e4622992181bc720ab68cdc4aca84fad4ef | /src/TaggedNum.hh | 21ccae08e8cacd17880766b131cee0da59d1078c | [
"MIT"
] | permissive | leilakechache/DeBruijnGraph | 3ebc707dfcc9b02852bca265ac025bd0d7b3414f | b3680948bb94872d4a9fbbc9006861940ec2e23e | refs/heads/master | 2020-07-01T06:46:06.764739 | 2019-08-08T12:38:17 | 2019-08-08T12:38:17 | 201,079,540 | 0 | 1 | NOASSERTION | 2019-08-08T12:38:18 | 2019-08-07T15:41:14 | C++ | UTF-8 | C++ | false | false | 2,072 | hh | // Copyright (c) 2008-1016, NICTA (National ICT Australia).
// Copyright (c) 2016, Commonwealth Scientific and Industrial Research
// Organisation (CSIRO) ABN 41 687 119 230.
//
// Licensed under the CSIRO Open Source Software License Agreement;
// you may not use this file except in compliance with the License.
// Please see the file LICENSE, included with this distribution.
//
#ifndef TAGGEDNUM_HH
#define TAGGEDNUM_HH
#ifndef STDINT_H
#include <stdint.h>
#define STDINT_H
#endif
#ifndef BOOST_OPERATORS_HPP
#include <boost/operators.hpp>
#define BOOST_OPERATORS_HPP
#endif
#ifndef BOOST_CALL_TRAITS_HPP
#include <boost/call_traits.hpp>
#define BOOST_CALL_TRAITS_HPP
#endif
#ifndef STD_UNORDERED_SET
#include <unordered_set>
#define STD_UNORDERED_SET
#endif
template <typename Tag, typename ValueType = uint64_t>
class TaggedNum
: public boost::equality_comparable<TaggedNum<Tag,ValueType>
, boost::less_than_comparable<TaggedNum<Tag,ValueType>
> >
{
public:
typedef ValueType value_type;
typedef typename boost::call_traits<value_type>::value_type value_return_type;
typedef typename boost::call_traits<value_type>::param_type value_param_type;
typedef typename boost::call_traits<value_type>::reference value_reference;
struct Hash
{
size_t operator() (TaggedNum<Tag,ValueType> pTaggedNum) const
{
return std::hash<typename TaggedNum<Tag,ValueType>::value_type>()(
pTaggedNum.value());
}
};
value_return_type value() const
{
return mValue;
}
value_reference value()
{
return mValue;
}
bool operator<(TaggedNum<Tag,ValueType> pRhs) const
{
return mValue < pRhs.mValue;
}
bool operator==(TaggedNum<Tag,ValueType> pRhs) const
{
return mValue == pRhs.mValue;
}
TaggedNum()
: mValue(value_param_type())
{
}
explicit TaggedNum(value_param_type pValue)
: mValue(pValue)
{
}
private:
ValueType mValue;
};
#endif // TAGGEDNUM_HH
| [
"noreply@github.com"
] | noreply@github.com |
1f082b9fb5c02aa25fb817834d4126030ad06b5e | 58d485aeafc1aad1489c5ca557a9bf94ee07a466 | /6 семестр/api/widget.h | 74ee6e9d06fad11b491d4bc3465292e536a07f2e | [] | no_license | IlchenkoRoman/Ilchenko | a8c0ae3c8abf394f47f5fa9a711edec8362a0ea6 | e199274352425d0c33c2f7589664e3eb147ccbfa | refs/heads/main | 2023-01-13T06:08:12.810174 | 2020-11-04T11:03:41 | 2020-11-04T11:03:41 | 302,682,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | h | #ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "api.h"
class Widget : public QWidget
{
Q_OBJECT
private:
public:
Widget(QWidget *parent = nullptr);
~Widget();
};
#endif // WIDGET_H
| [
"67579698+IlchenkoRoman@users.noreply.github.com"
] | 67579698+IlchenkoRoman@users.noreply.github.com |
f165f7f0e379b8a9b1ef36df28edee58deb017a1 | 8c1add484810df818286a6bbf7331c213e945018 | /Chapter6/PauseState.cpp | eb3dc81e4124dbdbc5cf18b524d90a6d95e8f16e | [
"BSD-3-Clause"
] | permissive | sgeos/book_sdl_game_development | 558075ed34177298fa9026c285ffe6af68d89485 | a37466bfe916313216f332cbcff07dc6b3800908 | refs/heads/master | 2020-05-04T21:02:00.730299 | 2019-06-13T06:16:20 | 2019-06-13T06:16:20 | 179,461,655 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | cpp | #include <iostream>
#include <string>
#include "Constants.h"
#include "DemoBackground.h"
#include "Game.h"
#include "GameStateMachine.h"
#include "InputHandler.h"
#include "PauseState.h"
#include "MenuButton.h"
#include "MainMenuState.h"
#include "StateParser.h"
#include "TextureManager.h"
const std::string PauseState::sStateId = "pause";
GameState *PauseState::sTransitionState = nullptr;
void PauseState::update(void) {
for (std::vector<GameObject *>::size_type i = 0; i < mGameObjectList.size(); i++) {
mGameObjectList[i]->update();
}
if (nullptr != sTransitionState) {
Game::Instance()->getStateMachine()->popAndChangeState(sTransitionState);
}
}
void PauseState::render(void) {
for (std::vector<GameObject *>::size_type i = 0; i < mGameObjectList.size(); i++) {
mGameObjectList[i]->draw();
}
}
bool PauseState::onEnter(void) {
sTransitionState = nullptr;
StateParser stateParser;
stateParser.parseState("demo.xml", sStateId, &mGameObjectList, &mTextureIdList);
mCallbackList.push_back(sPauseToMain);
mCallbackList.push_back(sResumePlay);
setCallbacks();
std::cout << "Entering state \"" << sStateId << "\"." << std::endl;
return true;
}
void PauseState::sPauseToMain() {
sTransitionState = new MainMenuState();
}
void PauseState::sResumePlay() {
Game::Instance()->getStateMachine()->popState();
}
| [
"b-sechter@unext.jp"
] | b-sechter@unext.jp |
32d1356f6e9fe4013c748fea625b49802a40d3f7 | c014e5edd39d8a9892351b466d363215c74ce674 | /LunarLander/Entity.h | d4d045e1ee68113c475df4c429c96c1373a30f8e | [] | no_license | PayalNareshNYU/CS3113LunarLander | 618659889a521f210351892ee07e6addc90491e3 | b77c655da3c5a204be6a18c9d1e020b42bb1f2a1 | refs/heads/master | 2021-03-19T21:02:17.902556 | 2020-03-13T19:21:07 | 2020-03-13T19:21:07 | 247,146,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,236 | h | #define GL_SILENCE_DEPRECATION
#ifdef _WINDOWS
#include <GL/glew.h>
#endif
#define GL_GLEXT_PROTOTYPES 1
#include <SDL.h>
#include <SDL_opengl.h>
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "ShaderProgram.h"
#include <string>
class Entity {
public:
glm::vec3 position;
glm::vec3 movement;
glm::vec3 acceleration;
glm::vec3 velocity;
float width = 1;
float height = 1;
float speed;
GLuint textureID;
glm::mat4 modelMatrix;
int* animRight = NULL;
int* animLeft = NULL;
int* animUp = NULL;
int* animDown = NULL;
bool isActive = true;
bool isFrozen = false;
std::string hasWon;
bool collidedTop = false;
bool collidedBottom = false;
bool collidedLeft = false;
bool collidedRight = false;
Entity();
bool CheckCollision(Entity* other);
void CheckCollisionsY(Entity* objects, int objectCount, GLuint& collidedWithX, GLuint& collidedWithY);
void CheckCollisionsX(Entity* objects, int objectCount, GLuint& collidedWithX, GLuint& collidedWithY);
void Update(float deltaTime, Entity* platforms, int platformCount, GLuint& collidedWithX, GLuint& collidedWithY);
void Render(ShaderProgram* program);
}; | [
"pn785@nyu.edu"
] | pn785@nyu.edu |
ec0d02ea6ceccdd23eff319814e2af9578948519 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/content/renderer/pepper/resource_converter.h | 57b72a1fb8042c78231bc45d645eabb529f2e813 | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 2,684 | h | // 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.
#ifndef CONTENT_RENDERER_PEPPER_RESOURCE_CONVERTER_H
#define CONTENT_RENDERER_PEPPER_RESOURCE_CONVERTER_H
#include <vector>
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "content/common/content_export.h"
#include "content/renderer/pepper/host_resource_var.h"
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_var.h"
#include "v8/include/v8.h"
namespace IPC {
class Message;
}
namespace ppapi {
class ScopedPPVar;
}
namespace content {
class RendererPpapiHost;
class CONTENT_EXPORT ResourceConverter {
public:
virtual ~ResourceConverter();
virtual void Reset() = 0;
virtual bool NeedsFlush() = 0;
virtual void Flush(const base::Callback<void(bool)>& callback) = 0;
virtual bool FromV8Value(v8::Handle<v8::Object> val,
v8::Handle<v8::Context> context,
PP_Var* result,
bool* was_resource) = 0;
virtual bool ToV8Value(const PP_Var& var,
v8::Handle<v8::Context> context,
v8::Handle<v8::Value>* result) = 0;
};
class ResourceConverterImpl : public ResourceConverter {
public:
ResourceConverterImpl(PP_Instance instance, RendererPpapiHost* host);
virtual ~ResourceConverterImpl();
virtual void Reset() OVERRIDE;
virtual bool NeedsFlush() OVERRIDE;
virtual void Flush(const base::Callback<void(bool)>& callback) OVERRIDE;
virtual bool FromV8Value(v8::Handle<v8::Object> val,
v8::Handle<v8::Context> context,
PP_Var* result,
bool* was_resource) OVERRIDE;
virtual bool ToV8Value(const PP_Var& var,
v8::Handle<v8::Context> context,
v8::Handle<v8::Value>* result) OVERRIDE;
private:
scoped_refptr<HostResourceVar> CreateResourceVar(
int pending_renderer_id,
const IPC::Message& create_message);
scoped_refptr<HostResourceVar> CreateResourceVarWithBrowserHost(
int pending_renderer_id,
const IPC::Message& create_message,
const IPC::Message& browser_host_create_message);
PP_Instance instance_;
RendererPpapiHost* host_;
std::vector<IPC::Message> browser_host_create_messages_;
std::vector<scoped_refptr<HostResourceVar> > browser_vars_;
DISALLOW_COPY_AND_ASSIGN(ResourceConverterImpl);
};
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
03bfbf23f7f96cc6ab2121e73df287f63955a6d2 | 0577a46d8d28e1fd8636893bbdd2b18270bb8eb8 | /update_notifier/thirdparty/wxWidgets/src/osx/core/mimetype.cpp | 9f878b0ab3f82c44cd61461c36cfcfb05323610c | [
"BSD-3-Clause"
] | permissive | ric2b/Vivaldi-browser | 388a328b4cb838a4c3822357a5529642f86316a5 | 87244f4ee50062e59667bf8b9ca4d5291b6818d7 | refs/heads/master | 2022-12-21T04:44:13.804535 | 2022-12-17T16:30:35 | 2022-12-17T16:30:35 | 86,637,416 | 166 | 41 | BSD-3-Clause | 2021-03-31T18:49:30 | 2017-03-29T23:09:05 | null | UTF-8 | C++ | false | false | 23,180 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: src/osx/core/mimetype.cpp
// Purpose: Mac OS X implementation for wx MIME-related classes
// Author: Neil Perkins
// Modified by:
// Created: 2010-05-15
// Copyright: (C) 2010 Neil Perkins
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/defs.h"
#endif
#if wxUSE_MIMETYPE
#include "wx/osx/mimetype.h"
#include "wx/osx/private.h"
/////////////////////////////////////////////////////////////////////////////
// Helper functions
/////////////////////////////////////////////////////////////////////////////
// Read a string or array of strings from a CFDictionary for a given key
// Return an empty list on error
wxArrayString ReadStringListFromCFDict( CFDictionaryRef dictionary, CFStringRef key )
{
// Create an empty list
wxArrayString results;
// Look up the requested key
CFTypeRef valueData = CFDictionaryGetValue( dictionary, key );
if( valueData )
{
// Value is an array
if( CFGetTypeID( valueData ) == CFArrayGetTypeID() )
{
CFArrayRef valueList = reinterpret_cast< CFArrayRef >( valueData );
CFTypeRef itemData;
wxCFStringRef item;
// Look at each item in the array
for( CFIndex i = 0, n = CFArrayGetCount( valueList ); i < n; i++ )
{
itemData = CFArrayGetValueAtIndex( valueList, i );
// Make sure the item is a string
if( CFGetTypeID( itemData ) == CFStringGetTypeID() )
{
// wxCFStringRef will automatically CFRelease, so an extra CFRetain is needed
item = reinterpret_cast< CFStringRef >( itemData );
wxCFRetain( item.get() );
// Add the string to the list
results.Add( item.AsString() );
}
}
}
// Value is a single string - return a list of one item
else if( CFGetTypeID( valueData ) == CFStringGetTypeID() )
{
// wxCFStringRef will automatically CFRelease, so an extra CFRetain is needed
wxCFStringRef value = reinterpret_cast< CFStringRef >( valueData );
wxCFRetain( value.get() );
// Add the string to the list
results.Add( value.AsString() );
}
}
// Return the list. If the dictionary did not contain key,
// or contained the wrong data type, the list will be empty
return results;
}
// Given a single CFDictionary representing document type data, check whether
// it matches a particular file extension. Return true for a match, false otherwise
bool CheckDocTypeMatchesExt( CFDictionaryRef docType, CFStringRef requiredExt )
{
const static wxCFStringRef extKey( "CFBundleTypeExtensions" );
CFTypeRef extData = CFDictionaryGetValue( docType, extKey );
if( !extData )
return false;
if( CFGetTypeID( extData ) == CFArrayGetTypeID() )
{
CFArrayRef extList = reinterpret_cast< CFArrayRef >( extData );
CFTypeRef extItem;
for( CFIndex i = 0, n = CFArrayGetCount( extList ); i < n; i++ )
{
extItem = CFArrayGetValueAtIndex( extList, i );
if( CFGetTypeID( extItem ) == CFStringGetTypeID() )
{
CFStringRef ext = reinterpret_cast< CFStringRef >( extItem );
if( CFStringCompare( ext, requiredExt, kCFCompareCaseInsensitive ) == kCFCompareEqualTo )
return true;
}
}
}
if( CFGetTypeID( extData ) == CFStringGetTypeID() )
{
CFStringRef ext = reinterpret_cast< CFStringRef >( extData );
if( CFStringCompare( ext, requiredExt, kCFCompareCaseInsensitive ) == kCFCompareEqualTo )
return true;
}
return false;
}
// Given a data structure representing document type data, or a list of such
// structures, find the one which matches a particular file extension
// The result will be a CFDictionary containining document type data
// if a match is found, or null otherwise
CFDictionaryRef GetDocTypeForExt( CFTypeRef docTypeData, CFStringRef requiredExt )
{
if( !docTypeData )
return NULL;
if( CFGetTypeID( docTypeData ) == CFArrayGetTypeID() )
{
CFTypeRef item;
CFArrayRef docTypes;
docTypes = reinterpret_cast< CFArrayRef >( docTypeData );
for( CFIndex i = 0, n = CFArrayGetCount( docTypes ); i < n; i++ )
{
item = CFArrayGetValueAtIndex( docTypes, i );
if( CFGetTypeID( item ) == CFDictionaryGetTypeID() )
{
CFDictionaryRef docType;
docType = reinterpret_cast< CFDictionaryRef >( item );
if( CheckDocTypeMatchesExt( docType, requiredExt ) )
return docType;
}
}
}
if( CFGetTypeID( docTypeData ) == CFDictionaryGetTypeID() )
{
CFDictionaryRef docType = reinterpret_cast< CFDictionaryRef >( docTypeData );
if( CheckDocTypeMatchesExt( docType, requiredExt ) )
return docType;
}
return NULL;
}
// Given an application bundle reference and the name of an icon file
// which is a resource in that bundle, look up the full (posix style)
// path to that icon. Returns the path, or an empty wxString on failure
wxString GetPathForIconFile( CFBundleRef bundle, CFStringRef iconFile )
{
// If either parameter is NULL there is no hope of success
if( !bundle || !iconFile )
return wxEmptyString;
// Create a range object representing the whole string
CFRange wholeString;
wholeString.location = 0;
wholeString.length = CFStringGetLength( iconFile );
// Index of the period in the file name for iconFile
UniCharCount periodIndex;
// In order to locate the period delimiting the extension,
// iconFile must be represented as UniChar[]
{
// Allocate a buffer and copy in the iconFile string
UniChar* buffer = new UniChar[ wholeString.length ];
CFStringGetCharacters( iconFile, wholeString, buffer );
// Locate the period character
OSStatus status = LSGetExtensionInfo( wholeString.length, buffer, &periodIndex );
// Deallocate the buffer
delete [] buffer;
// If the period could not be located it will not be possible to get the URL
if( status != noErr || periodIndex == kLSInvalidExtensionIndex )
return wxEmptyString;
}
// Range representing the name part of iconFile
CFRange iconNameRange;
iconNameRange.location = 0;
iconNameRange.length = periodIndex - 1;
// Range representing the extension part of iconFile
CFRange iconExtRange;
iconExtRange.location = periodIndex;
iconExtRange.length = wholeString.length - periodIndex;
// Get the name and extension strings
wxCFStringRef iconName = CFStringCreateWithSubstring( kCFAllocatorDefault, iconFile, iconNameRange );
wxCFStringRef iconExt = CFStringCreateWithSubstring( kCFAllocatorDefault, iconFile, iconExtRange );
// Now it is possible to query the URL for the icon as a resource
wxCFRef< CFURLRef > iconUrl = wxCFRef< CFURLRef >( CFBundleCopyResourceURL( bundle, iconName, iconExt, NULL ) );
if( !iconUrl.get() )
return wxEmptyString;
// All being well, return the icon path
return wxCFStringRef( CFURLCopyFileSystemPath( iconUrl, kCFURLPOSIXPathStyle ) ).AsString();
}
wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
{
}
wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
{
}
/////////////////////////////////////////////////////////////////////////////
// Init / shutdown functions
//
// The Launch Services / UTI API provides no helpful way of getting a list
// of all registered types. Instead the API is focused around looking up
// information for a particular file type once you already have some
// identifying piece of information. In order to get a list of registered
// types it would first be necessary to get a list of all bundles exporting
// type information (all application bundles may be sufficient) then look at
// the Info.plist file for those bundles and store the type information. As
// this would require trawling the hard disk when a wxWidgets program starts
// up it was decided instead to load the information lazily.
//
// If this behaviour really messes up your app, please feel free to implement
// the trawling approach (perhaps with a configure switch?). A good place to
// start would be CFBundleCreateBundlesFromDirectory( NULL, "/Applications", "app" )
/////////////////////////////////////////////////////////////////////////////
void wxMimeTypesManagerImpl::Initialize(int WXUNUSED(mailcapStyles), const wxString& WXUNUSED(extraDir))
{
// NO-OP
}
void wxMimeTypesManagerImpl::ClearData()
{
// NO-OP
}
/////////////////////////////////////////////////////////////////////////////
// Lookup functions
//
// Apple uses a number of different systems for file type information.
// As of Spring 2010, these include:
//
// OS Types / OS Creators
// File Extensions
// Mime Types
// Uniform Type Identifiers (UTI)
//
// This implementation of the type manager for Mac supports all except OS
// Type / OS Creator codes, which have been deprecated for some time with
// less and less support in recent versions of OS X.
//
// The UTI system is the internal system used by OS X, as such it offers a
// one-to-one mapping with file types understood by Mac OS X and is the
// easiest way to convert between type systems. However, UTI meta-data is
// not stored with data files (as of OS X 10.6), instead the OS looks at
// the file extension and uses this to determine the UTI. Simillarly, most
// applications do not yet advertise the file types they can handle by UTI.
//
// The result is that no one typing system is suitable for all tasks. Further,
// as there is not a one-to-one mapping between type systems for the
// description of any given type, it follows that ambiguity cannot be precluded,
// whichever system is taken to be the "master".
//
// In the implementation below I have used UTI as the master key for looking
// up file types. Extensions and mime types are mapped to UTIs and the data
// for each UTI contains a list of all associated extensions and mime types.
// This has the advantage that unknown types will still be assigned a unique
// ID, while using any other system as the master could result in conflicts
// if there were no mime type assigned to an extension or vice versa. However
// there is still plenty of room for ambiguity if two or more applications
// are fighting over ownership of a particular type or group of types.
//
// If this proves to be serious issue it may be helpful to add some slightly
// more cleve logic to the code so that the key used to look up a file type is
// always first in the list in the resulting wxFileType object. I.e, if you
// look up .mpeg3 the list you get back could be .mpeg3, mp3, .mpg3, while
// looking up .mp3 would give .mp3, .mpg3, .mpeg3. The simplest way to do
// this would probably to keep two separate sets of data, one for lookup
// by extetnsion and one for lookup by mime type.
//
// One other point which may require consideration is handling of unrecognised
// types. Using UTI these will be assigned a unique ID of dyn.xxx. This will
// result in a wxFileType object being returned, although querying properties
// on that object will fail. If it would be more helpful to return NULL in this
// case a suitable check can be added.
/////////////////////////////////////////////////////////////////////////////
// Look up a file type by extension
// The extensions if mapped to a UTI
// If the requested extension is not know the OS is querried and the results saved
wxFileType *wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
{
wxString uti;
const TagMap::const_iterator extItr = m_extMap.find( ext );
if( extItr == m_extMap.end() )
{
wxCFStringRef utiRef = UTTypeCreatePreferredIdentifierForTag( kUTTagClassFilenameExtension, wxCFStringRef( ext ), NULL );
m_extMap[ ext ] = uti = utiRef.AsString();
}
else
uti = extItr->second;
return GetFileTypeFromUti( uti );
}
// Look up a file type by mime type
// The mime type is mapped to a UTI
// If the requested extension is not know the OS is querried and the results saved
wxFileType *wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
{
wxString uti;
const TagMap::const_iterator mimeItr = m_mimeMap.find( mimeType );
if( mimeItr == m_mimeMap.end() )
{
wxCFStringRef utiRef = UTTypeCreatePreferredIdentifierForTag( kUTTagClassFilenameExtension, wxCFStringRef( mimeType ), NULL );
m_mimeMap[ mimeType ] = uti = utiRef.AsString();
}
else
uti = mimeItr->second;
return GetFileTypeFromUti( uti );
}
// Look up a file type by UTI
// If the requested extension is not know the OS is querried and the results saved
wxFileType *wxMimeTypesManagerImpl::GetFileTypeFromUti(const wxString& uti)
{
UtiMap::const_iterator utiItr = m_utiMap.find( uti );
if( utiItr == m_utiMap.end() )
{
LoadTypeDataForUti( uti );
LoadDisplayDataForUti( uti );
}
wxFileType* const ft = new wxFileType;
ft->m_impl->m_uti = uti;
ft->m_impl->m_manager = this;
return ft;
}
/////////////////////////////////////////////////////////////////////////////
// Load functions
//
// These functions query the OS for information on a particular file type
/////////////////////////////////////////////////////////////////////////////
// Look up all extensions and mime types associated with a UTI
void wxMimeTypesManagerImpl::LoadTypeDataForUti(const wxString& uti)
{
// Keys in to the UTI declaration plist
const static wxCFStringRef tagsKey( "UTTypeTagSpecification" );
const static wxCFStringRef extKey( "public.filename-extension" );
const static wxCFStringRef mimeKey( "public.mime-type" );
// Get the UTI as a CFString
wxCFStringRef utiRef( uti );
// Get a copy of the UTI declaration
wxCFRef< CFDictionaryRef > utiDecl;
utiDecl = wxCFRef< CFDictionaryRef >( UTTypeCopyDeclaration( utiRef ) );
if( !utiDecl )
return;
// Get the tags spec (the section of a UTI declaration containing mappings to other type systems)
CFTypeRef tagsData = CFDictionaryGetValue( utiDecl, tagsKey );
if( CFGetTypeID( tagsData ) != CFDictionaryGetTypeID() )
return;
CFDictionaryRef tags = reinterpret_cast< CFDictionaryRef >( tagsData );
// Read tags for extensions and mime types
m_utiMap[ uti ].extensions = ReadStringListFromCFDict( tags, extKey );
m_utiMap[ uti ].mimeTypes = ReadStringListFromCFDict( tags, mimeKey );
}
// Look up the (locale) display name and icon file associated with a UTI
void wxMimeTypesManagerImpl::LoadDisplayDataForUti(const wxString& uti)
{
// Keys in to Info.plist
const static wxCFStringRef docTypesKey( "CFBundleDocumentTypes" );
const static wxCFStringRef descKey( "CFBundleTypeName" );
const static wxCFStringRef iconKey( "CFBundleTypeIconFile" );
wxCFStringRef cfuti(uti);
wxCFStringRef ext = UTTypeCopyPreferredTagWithClass( cfuti, kUTTagClassFilenameExtension );
// Look up the preferred application
wxCFRef<CFURLRef> appUrl = LSCopyDefaultApplicationURLForContentType( cfuti, kLSRolesAll, NULL);
if( !appUrl )
return;
// Create a bundle object for that application
wxCFRef< CFBundleRef > bundle;
bundle = wxCFRef< CFBundleRef >( CFBundleCreate( kCFAllocatorDefault, appUrl ) );
if( !bundle )
return;
// Also get the open command while we have the bundle
wxCFStringRef cfsAppPath(CFURLCopyFileSystemPath(appUrl, kCFURLPOSIXPathStyle));
m_utiMap[ uti ].application = cfsAppPath.AsString();
// Get all the document type data in this bundle
CFTypeRef docTypeData;
docTypeData = CFBundleGetValueForInfoDictionaryKey( bundle, docTypesKey );
if( !docTypeData )
return;
// Find the document type entry that matches ext
CFDictionaryRef docType;
docType = GetDocTypeForExt( docTypeData, ext );
if( !docType )
return;
// Get the display name for docType
wxCFStringRef description = reinterpret_cast< CFStringRef >( CFDictionaryGetValue( docType, descKey ) );
wxCFRetain( description.get() );
m_utiMap[ uti ].description = description.AsString();
// Get the icon path for docType
CFStringRef iconFile = reinterpret_cast< CFStringRef > ( CFDictionaryGetValue( docType, iconKey ) );
m_utiMap[ uti ].iconLoc.SetFileName( GetPathForIconFile( bundle, iconFile ) );
}
/////////////////////////////////////////////////////////////////////////////
// The remaining functionality from the public interface of
// wxMimeTypesManagerImpl is not implemented.
//
// Please see the note further up this file on Initialise/Clear to explain why
// EnumAllFileTypes is not available.
//
// Some thought will be needed before implementing Associate / Unassociate
// for OS X to ensure proper integration with the many file type and
// association mechanisms already used by the OS. Leaving these methods as
// NO-OP on OS X and asking client apps to put suitable entries in their
// Info.plist files when building their OS X bundle may well be the
// correct solution.
/////////////////////////////////////////////////////////////////////////////
size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& WXUNUSED(mimetypes))
{
return 0;
}
wxFileType *wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& WXUNUSED(ftInfo))
{
return 0;
}
bool wxMimeTypesManagerImpl::Unassociate(wxFileType *WXUNUSED(ft))
{
return false;
}
/////////////////////////////////////////////////////////////////////////////
// Getter methods
//
// These methods are private and should only ever be called by wxFileTypeImpl
// after the required information has been loaded. It should not be possible
// to get a wxFileTypeImpl for a UTI without information for that UTI being
// querried, however it is possible that some information may not have been
// found.
/////////////////////////////////////////////////////////////////////////////
bool wxMimeTypesManagerImpl::GetExtensions(const wxString& uti, wxArrayString& extensions)
{
const UtiMap::const_iterator itr = m_utiMap.find( uti );
if( itr == m_utiMap.end() || itr->second.extensions.GetCount() < 1 )
{
extensions.Clear();
return false;
}
extensions = itr->second.extensions;
return true;
}
bool wxMimeTypesManagerImpl::GetMimeType(const wxString& uti, wxString *mimeType)
{
const UtiMap::const_iterator itr = m_utiMap.find( uti );
if( itr == m_utiMap.end() || itr->second.mimeTypes.GetCount() < 1 )
{
mimeType->clear();
return false;
}
*mimeType = itr->second.mimeTypes[ 0 ];
return true;
}
bool wxMimeTypesManagerImpl::GetMimeTypes(const wxString& uti, wxArrayString& mimeTypes)
{
const UtiMap::const_iterator itr = m_utiMap.find( uti );
if( itr == m_utiMap.end() || itr->second.mimeTypes.GetCount() < 1 )
{
mimeTypes.Clear();
return false;
}
mimeTypes = itr->second.mimeTypes;
return true;
}
bool wxMimeTypesManagerImpl::GetIcon(const wxString& uti, wxIconLocation *iconLoc)
{
const UtiMap::const_iterator itr = m_utiMap.find( uti );
if( itr == m_utiMap.end() || !itr->second.iconLoc.IsOk() )
{
*iconLoc = wxIconLocation();
return false;
}
*iconLoc = itr->second.iconLoc;
return true;
}
bool wxMimeTypesManagerImpl::GetDescription(const wxString& uti, wxString *desc)
{
const UtiMap::const_iterator itr = m_utiMap.find( uti );
if( itr == m_utiMap.end() || itr->second.description.empty() )
{
desc->clear();
return false;
}
*desc = itr->second.description;
return true;
}
bool wxMimeTypesManagerImpl::GetApplication(const wxString& uti, wxString *command)
{
const UtiMap::const_iterator itr = m_utiMap.find( uti );
if( itr == m_utiMap.end() )
{
command->clear();
return false;
}
*command = itr->second.application;
return true;
}
/////////////////////////////////////////////////////////////////////////////
// The remaining functionality has not yet been implemented for OS X
/////////////////////////////////////////////////////////////////////////////
wxFileTypeImpl::wxFileTypeImpl()
{
}
wxFileTypeImpl::~wxFileTypeImpl()
{
}
// Query wxMimeTypesManagerImple to get real information for a file type
bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions) const
{
return m_manager->GetExtensions( m_uti, extensions );
}
bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
{
return m_manager->GetMimeType( m_uti, mimeType );
}
bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
{
return m_manager->GetMimeTypes( m_uti, mimeTypes );
}
bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
{
return m_manager->GetIcon( m_uti, iconLoc );
}
bool wxFileTypeImpl::GetDescription(wxString *desc) const
{
return m_manager->GetDescription( m_uti, desc );
}
namespace
{
// Helper function for GetOpenCommand(): returns the string surrounded by
// (singly) quotes if it contains spaces.
wxString QuoteIfNecessary(const wxString& path)
{
wxString result(path);
if ( path.find(' ') != wxString::npos )
{
result.insert(0, "'");
result.append("'");
}
return result;
}
} // anonymous namespace
bool wxFileTypeImpl::GetOpenCommand(wxString *openCmd, const wxFileType::MessageParameters& params) const
{
wxString application;
if ( !m_manager->GetApplication(m_uti, &application) )
return false;
*openCmd << QuoteIfNecessary(application)
<< ' ' << QuoteIfNecessary(params.GetFileName());
return true;
}
bool wxFileTypeImpl::GetPrintCommand(wxString *WXUNUSED(printCmd), const wxFileType::MessageParameters& WXUNUSED(params)) const
{
return false;
}
size_t wxFileTypeImpl::GetAllCommands(wxArrayString *WXUNUSED(verbs), wxArrayString *WXUNUSED(commands), const wxFileType::MessageParameters& WXUNUSED(params)) const
{
return false;
}
bool wxFileTypeImpl::SetCommand(const wxString& WXUNUSED(cmd), const wxString& WXUNUSED(verb), bool WXUNUSED(overwriteprompt))
{
return false;
}
bool wxFileTypeImpl::SetDefaultIcon(const wxString& WXUNUSED(strIcon), int WXUNUSED(index))
{
return false;
}
bool wxFileTypeImpl::Unassociate(wxFileType *WXUNUSED(ft))
{
return false;
}
wxString
wxFileTypeImpl::GetExpandedCommand(const wxString& WXUNUSED(verb),
const wxFileType::MessageParameters& WXUNUSED(params)) const
{
return wxString();
}
#endif // wxUSE_MIMETYPE
| [
"mathieu.caroff@free.fr"
] | mathieu.caroff@free.fr |
58647f5869b65351b19614acf218d091752c19bb | 7042dd8b567f30d926f682907f5b2f53f93e8980 | /winxsamp/tutorials/winx/step019-scroll-window/4.zoomview/hello.cpp | c4f02e87c9b9398d36119697ceb3527638e540ee | [] | no_license | xushiwei/winx | 9e02558ddbb4f873119c172f186f06730b93092d | 83f6b65193137e9ec08644a4391dfc96c0969313 | refs/heads/master | 2020-12-24T22:29:36.717051 | 2018-04-20T11:57:26 | 2018-04-20T11:57:26 | 2,092,114 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | cpp | /* -------------------------------------------------------------------------
// WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE
//
// This file is a part of the WINX Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.txt at this distribution. By using
// this software in any fashion, you are agreeing to be bound by the terms
// of this license. You must not remove this notice, or any other, from
// this software.
//
// Module: hello.cpp
// Creator: xushiwei
// Email: xushiweizh@gmail.com
// Date: 2007-1-28 18:17:50
//
// $Id: hello.cpp,v 1.1 2006/08/22 09:02:17 xushiwei Exp $
// -----------------------------------------------------------------------*/
#include <winx/ScrollWindow.h>
#include "resource.h"
// -------------------------------------------------------------------------
// class CMyView
class CMyView : public winx::ZoomScrollWindow<CMyView>
{
WINX_CLASS("MyView");
public:
BOOL OnSetCursor(HWND hWnd, HWND hWndContainsCursor, UINT nHitTest, UINT uMouseMsg)
{
::SetCursor(::LoadCursor(NULL, nHitTest == HTCLIENT ? IDC_UPARROW : IDC_ARROW));
return TRUE;
}
LRESULT OnCreate(HWND hWnd, LPCREATESTRUCT lpCS)
{
SetScrollSize(400, 400);
SetZoomMode(ZOOMMODE_IN);
return 0;
}
void DoPaint(winx::DCHandle dc)
{
dc.TextOut(1, 1, _T("Hello, ZoomScrollWindow! Please click left mouse button."));
dc.TextOut(1, 100, _T("You are welcome!"));
}
};
// -------------------------------------------------------------------------
// CHelloDlg
class CHelloDlg : public winx::ModelDialog<CHelloDlg, IDD_HELLO>
{
};
// -------------------------------------------------------------------------
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
CMyView::RegisterClass();
CHelloDlg dlg;
dlg.DoModal();
return 0;
}
// -------------------------------------------------------------------------
// $Log: hello.cpp,v $
| [
"xushiweizh@gmail.com"
] | xushiweizh@gmail.com |
310dd5bec5e5d349182130637cd9be78a49a8946 | 30934e1bec424f277598c4270a05f82edc17479d | /FirstProject/FloorSwitch.h | 5c987a9581625fed01f24364951ebabeaafc3059 | [] | no_license | wahmarco96/ProtoTypeGameUE4 | ca9dec9ad399e8f7f6acad8a78f3aa6259a0bd9c | d4fd208468f877d99455ca4371ab6b5542224b62 | refs/heads/master | 2020-07-03T17:10:54.105794 | 2019-08-20T18:14:46 | 2019-08-20T18:14:46 | 201,980,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "FloorSwitch.generated.h"
UCLASS()
class FIRSTPROJECT_API AFloorSwitch : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AFloorSwitch();
/** Overlap volume for functionality to be triggered */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Floor Switch")
class UBoxComponent* TriggerBox;
/** Switch for the character to step on */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Floor Switch")
class UStaticMeshComponent* FloorSwitch;
/** Door to move when the floor switch is stepped on */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Floor Switch")
UStaticMeshComponent* Door;
/** Initial location for the door */
UPROPERTY(BlueprintReadWrite, Category = "Floor Switch")
FVector InitialDoorLocation;
/** Initial location for the floor switch */
UPROPERTY(BlueprintReadWrite, Category = "Floor Switch")
FVector InitialSwitchLocation;
FTimerHandle SwitchHandle;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Floor Switch")
float SwitchTime;
bool bCharacterOnSwitch;
void CloseDoor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION()
void OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);
UFUNCTION()
void OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
UFUNCTION(BlueprintImplementableEvent, Category = "Floor Switch")
void RaiseDoor();
UFUNCTION(BlueprintImplementableEvent, Category = "Floor Switch")
void LowerDoor();
UFUNCTION(BlueprintImplementableEvent, Category = "Floor Switch")
void RaiseFloorSwitch();
UFUNCTION(BlueprintImplementableEvent, Category = "Floor Switch")
void LowerFloorSwitch();
UFUNCTION(BlueprintCallable, Category = "Floor Switch")
void UpdateDoorLocation(float Z);
UFUNCTION(BlueprintCallable, Category = "Floor Switch")
void UpdateFloorSwitchLocation(float Z);
};
| [
"noreply@github.com"
] | noreply@github.com |
40d1c974690535afc7d795c2d9a2118ab077ac43 | b518d7b94bf1e14ab580da417b133e59c8664e79 | /graph/printing sortest path using BFS.cpp | f3498e1b5dbf80d025083f3e99aca2c257c7cb20 | [] | no_license | jitunmohajan/competitive-programming | 919c7b26af01c30b2398c1284f95f40fafd50061 | 3cbaa761f00cd311989cfcc4aa8422d481e29435 | refs/heads/master | 2023-02-24T16:36:02.150414 | 2021-01-30T19:09:26 | 2021-01-30T19:09:26 | 170,622,999 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | #include<bits/stdc++.h>
using namespace std;
vector<vector<int> >adj(0,vector<int>(0,0));
vector<int>visit,dis;
int u,v,s,e,node,edge;
void bfs(int s,int e){
queue<int>q;
q.push(s);
visit[s]=1;
dis[s]=s;
while(!q.empty()){
u=q.front();
q.pop();
for(int i=0;i<adj[u].size();i++)
{
v=adj[u][i];
if(!visit[v])
{
visit[v]=visit[u]+1;
dis[v]=u;
q.push(v);
}
}
}
if(!visit[e])//e is the end node
return;
vector<int>path;
int now=e;
path.push_back(e);
while(now!=s){
now=dis[now];
path.push_back(now);
}
for(int i=path.size()-1;i>=0;i--)
cout<<path[i]<<" ";
}
int main(){
cin>>node>>edge;
visit.assign(node+1,0);
dis.assign(node+1,0);
adj.assign(node+1,vector<int>(0,0));
for(int i=0;i<edge;i++)
{
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cin>>s>>e;
bfs(s,e);
return 0;
}
| [
"jitunmohajan@gmail.com"
] | jitunmohajan@gmail.com |
b10aae7638f649739d4ade61549feb8a4cf661cc | 71451806a4d21a2212731969575cff90e967de7e | /src/MonitorManagerBackend/include/DBManager.h | cbe3b6fe7cfa577c4bae61c923ed7104fcdc7171 | [] | no_license | radtek/MonitorIntegration | 74222945fa1aa6e6732d4ee5494673f13bca8cbf | 0f5adffe035a0953ca0136d407b0b4a383158926 | refs/heads/main | 2023-04-03T09:11:31.163549 | 2021-04-07T06:33:57 | 2021-04-07T06:33:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,112 | h | //
// Created by felix lee on 2020/10/27.
//
#ifndef MONITORINTEGRATION_DBMANAGER_H
#define MONITORINTEGRATION_DBMANAGER_H
#include <string>
#include <fstream>
#include <memory>
#include <iostream>
#include "nlohmann/json.hpp"
#include "sqlite3.h"
#include "fmt/format.h"
class DB {
public:
DB(const std::string& dbFilePath){
db_file_path_ = dbFilePath;
sqlite3_ptr_ = NULL; // һ�������ݿ�ʵ��
int result = sqlite3_open_v2(dbFilePath.c_str(), &sqlite3_ptr_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_SHAREDCACHE, NULL);
if (result == SQLITE_OK) {
load_status = true;
}
else {
load_status = false;
std::cout << "Failed to create db, error_code: " << result << std::endl;
}
auto create_table_sql = "CREATE TABLE IF NOT EXISTS t_monitor_item (appname text PRIMARY KEY, address text NOT NULL, port integer NOT NULL, zabbix_host text NOT NULL, zabbix_itemid text);";
sqlite3_stmt *stmt = NULL; //stmt�����
int res = sqlite3_prepare_v2(sqlite3_ptr_, create_table_sql, -1, &stmt, NULL);
if (res == SQLITE_OK) {
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
}
~DB() {
}
int InsertData(const std::string& appname, const std::string & address, int port, const std::string &zabbixhost){
auto sql = fmt::format("INSERT INTO t_monitor_item(appname, address, port, zabbix_host) VALUES('{}', '{}', {}, '{}'); ",
appname, address, port, zabbixhost);
sqlite3_stmt *stmt = NULL; //stmt�����
//���в���ǰ������������������Ϸ���
//-1����ϵͳ���Զ�����SQL���ij���
int result = sqlite3_prepare_v2(sqlite3_ptr_, sql.c_str(), -1, &stmt, NULL);
if (result == SQLITE_OK) {
std::clog << "insert success";
//ִ�и����
sqlite3_step(stmt);
} else {
std::clog << "insert failed";
}
//�������������ִ����һ�����
sqlite3_finalize(stmt);
return result;
};
int DeleteData(const std::string& appname) {
auto sql = fmt::format("delete from t_monitor_item where appname = '{}'; ", appname);
sqlite3_stmt *stmt = NULL; //stmt�����
//���в���ǰ������������������Ϸ���
//-1����ϵͳ���Զ�����SQL���ij���
int result = sqlite3_prepare_v2(sqlite3_ptr_, sql.c_str(), -1, &stmt, NULL);
if (result == SQLITE_OK) {
std::clog << "delete success";
//ִ�и����
sqlite3_step(stmt);
} else {
std::clog << "delete failed";
}
//�������������ִ����һ�����
sqlite3_finalize(stmt);
return result;
}
int ModifyData(const std::string& appname, const std::string & address, int port, const std::string& hostname){
auto sql = fmt::format("update t_monitor_item set address = '{}' , port = {}, zabbix_host = '{}' where appname = '{}'; ", address, port, hostname, appname);
sqlite3_stmt *stmt = NULL; //stmt�����
//���в���ǰ������������������Ϸ���
//-1����ϵͳ���Զ�����SQL���ij���
int result = sqlite3_prepare_v2(sqlite3_ptr_, sql.c_str(), -1, &stmt, NULL);
if (result == SQLITE_OK) {
std::clog << "modify success";
//ִ�и����
sqlite3_step(stmt);
} else {
std::clog << "modify failed";
}
//�������������ִ����һ�����
sqlite3_finalize(stmt);
return result;
}
nlohmann::json QryDataList() {
nlohmann::json j;
const char *sqlSentence = "SELECT appname, address, port, zabbix_host, zabbix_itemid FROM t_monitor_item;"; //SQL���
sqlite3_stmt *stmt = NULL; // stmt�����
//���в�ѯǰ������������������Ϸ���
//-1����ϵͳ���Զ�����SQL���ij���
int result = sqlite3_prepare_v2(sqlite3_ptr_, sqlSentence, -1, &stmt, NULL);
if (result == SQLITE_OK) {
std::clog << "OK";
// ÿ��һ��sqlite3_step()������stmt������ͻ�ָ����һ����¼
while (sqlite3_step(stmt) == SQLITE_ROW) {
// ȡ����0���ֶε�ֵ
auto appname = (const char *)sqlite3_column_text(stmt, 0);
// ȡ����1���ֶε�ֵ
auto address = (const char *)sqlite3_column_text(stmt, 1);
//�����ز�ѯ������
auto port = sqlite3_column_int(stmt, 2);
auto hostname = (const char *)sqlite3_column_text(stmt, 3);
auto itemid = (const char *)sqlite3_column_text(stmt, 4);
nlohmann::json item;
item["appname"] = appname;
item["address"] = address;
item["port"] = port;
item["zabbixhost"] = hostname;
if (itemid != nullptr) {
item["itemid"] = itemid;
}
else {
item["itemid"] = "";
}
j.push_back(item);
}
} else {
std::clog << "qry failed";
}
//�������������ִ����һ�����
sqlite3_finalize(stmt);
return j;
}
int UpdateMonitorItemByAppname(const std::string& appname, const std::string& itemID) {
auto sql = fmt::format("update t_monitor_item set zabbix_itemid = '{}' where appname = '{}'; ", itemID, appname);
sqlite3_stmt *stmt = NULL; //stmt�����
//���в���ǰ������������������Ϸ���
//-1����ϵͳ���Զ�����SQL���ij���
int result = sqlite3_prepare_v2(sqlite3_ptr_, sql.c_str(), -1, &stmt, NULL);
if (result == SQLITE_OK) {
std::clog << "modify success";
//ִ�и����
sqlite3_step(stmt);
} else {
std::clog << "modify failed";
}
//�������������ִ����һ�����
sqlite3_finalize(stmt);
return result;
}
private:
std::string db_file_path_;
bool load_status;
sqlite3* sqlite3_ptr_;
};
#endif //MONITORINTEGRATION_DBMANAGER_H
| [
"lf729263226@outlook.com"
] | lf729263226@outlook.com |
43aae84f41a69ea027c2eaeb42dddc9238ddf25e | e853157395e4b35fcb18804c6640e387a316c210 | /ddbtoaster/srccpp/lib/date_type.hpp | 7728dd87811dd0231c99964386be5cd355ae106f | [
"Apache-2.0"
] | permissive | dbtoaster/dbtoaster-backend | d8d9cf56daef16e04501c890a68a86291a62bb88 | e47273968b360b1c3685449f23d0510c78f59216 | refs/heads/master | 2022-03-04T01:56:02.288950 | 2022-02-14T12:26:43 | 2022-02-14T12:26:43 | 10,745,011 | 53 | 17 | Apache-2.0 | 2021-01-04T20:40:27 | 2013-06-17T19:17:56 | C++ | UTF-8 | C++ | false | false | 1,840 | hpp | #ifndef DBTOASTER_DATETYPE_HPP
#define DBTOASTER_DATETYPE_HPP
#include <cstdint>
namespace dbtoaster {
struct DateType {
public:
constexpr DateType(uint16_t t_year, uint8_t t_month, uint8_t t_day)
: day(t_day), month(t_month), year(t_year) { }
constexpr DateType() : day(0), month(0), year(0) { }
constexpr uint16_t getYear() const { return year; }
constexpr uint8_t getMonth() const { return month; }
constexpr uint8_t getDay() const { return day; }
constexpr uint32_t getNumeric() const { return numeric; }
friend constexpr bool operator==(const DateType& d1, const DateType& d2);
friend constexpr bool operator!=(const DateType& d1, const DateType& d2);
friend constexpr bool operator< (const DateType& d1, const DateType& d2);
friend constexpr bool operator<=(const DateType& d1, const DateType& d2);
friend constexpr bool operator> (const DateType& d1, const DateType& d2);
friend constexpr bool operator>=(const DateType& d1, const DateType& d2);
private:
union {
struct {
uint8_t day;
uint8_t month;
uint16_t year;
};
uint32_t numeric;
};
};
inline constexpr bool operator==(const DateType& d1, const DateType& d2) {
return d1.numeric == d2.numeric;
}
inline constexpr bool operator!=(const DateType& d1, const DateType& d2) {
return d1.numeric != d2.numeric;
}
inline constexpr bool operator< (const DateType& d1, const DateType& d2) {
return d1.numeric < d2.numeric;
}
inline constexpr bool operator<=(const DateType& d1, const DateType& d2) {
return d1.numeric <= d2.numeric;
}
inline constexpr bool operator> (const DateType& d1, const DateType& d2) {
return d1.numeric > d2.numeric;
}
inline constexpr bool operator>=(const DateType& d1, const DateType& d2) {
return d1.numeric >= d2.numeric;
}
}
#endif /* DBTOASTER_DATETYPE_HPP */ | [
"milos.nikolic@ed.ac.uk"
] | milos.nikolic@ed.ac.uk |
5c95f32d357855b69113e408032b84d04f02168e | c2dc67d6ab1f32252d3e50cbc8e3d75c595cc21a | /Practice/Find Pair With Given Sum.cpp | 736f9317bfc0fd5852b13cb28cef633dcaa9aee8 | [] | no_license | KN999/Data-Structure | 91e0f83a59bc7288bffeb38a33e5e925ec594e46 | 2d90646663c92f35980b2a656cc3e411ae48f520 | refs/heads/master | 2022-12-28T06:38:15.642877 | 2020-03-11T08:12:46 | 2020-03-11T08:12:46 | 256,546,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 985 | cpp | #include<iostream>
#include<vector>
#include<map>
#include<bits/stdc++.h>
#include<algorithm>
#include<set>
#include<string.h>
using namespace std;
class Solution {
public:
vector<int> solve(vector<int> &nums, int target) {
map<int, int> m;
vector<int> result;
for(int i=0; i<nums.size(); i++) {
if(m.find(target-nums[i]) != m.end()) {
int index = m[target-nums[i]];
result.push_back(index);
result.push_back(i);
}
m[nums[i]] = i;
}
if(result.size() == 0)
return vector<int>({-1,-1});
return vector<int>({result[result.size()-2], result[result.size()-1]});
}
};
int main()
{
vector<int> nums = {20, 50, 40, 25, 30, 10};
int target = 90;
Solution S;
vector<int> result = S.solve(nums, target-30);
for(auto res : result) {
cout<<res<<" ";
}
cout<<endl;
return 0;
}
| [
"navinkumar0299@outlook.com"
] | navinkumar0299@outlook.com |
c1ad3e3aaed4b5647549b875b04635af95f13e9a | 4cd7933a74084f6a6d04a1f5e6c75f6d087ed042 | /ScanConvertSliceSeries/ScanConvertSliceSeries.cxx | 497786892efc2fd0587e6bbe5693b70a96795e37 | [
"Apache-2.0"
] | permissive | Guokr1991/SlicerITKUltrasound | 8006c37e01c00fdfc084e9e58f1f6d9e5f9ff78a | 60354507920cf4190e807c8bb0f9b1eab8ed0e24 | refs/heads/master | 2021-01-16T18:06:04.405961 | 2016-06-01T06:26:43 | 2016-06-01T06:26:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,867 | cxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkImageFileWriter.h"
#include "itkSliceSeriesSpecialCoordinatesImage.h"
#include "itkEuler3DTransform.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkUltrasoundImageFileReader.h"
#include "itkHDF5UltrasoundImageIOFactory.h"
#include "itkReplaceNonFiniteImageFilter.h"
#include "itkPluginUtilities.h"
#include "ScanConvertSliceSeriesCLP.h"
#include "ScanConversionResamplingMethods.h"
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template< typename TPixel >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
const unsigned int Dimension = 3;
const unsigned int SliceDimension = Dimension - 1;
typedef TPixel PixelType;
typedef double ParametersValueType;
typedef itk::Image< PixelType, SliceDimension > SliceImageType;
typedef itk::Euler3DTransform< ParametersValueType > TransformType;
typedef itk::SliceSeriesSpecialCoordinatesImage< SliceImageType, TransformType, PixelType, Dimension > InputImageType;
typedef itk::Image< PixelType, Dimension > OutputImageType;
typedef itk::UltrasoundImageFileReader< InputImageType > ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputVolume );
typedef itk::ReplaceNonFiniteImageFilter< InputImageType > ReplaceNonFiniteFilterType;
typename ReplaceNonFiniteFilterType::Pointer replaceNonFiniteFilter = ReplaceNonFiniteFilterType::New();
replaceNonFiniteFilter->SetInput( reader->GetOutput() );
replaceNonFiniteFilter->InPlaceOn();
itk::PluginFilterWatcher watchReplaceNonFinite(replaceNonFiniteFilter, "Replace NonFinite", CLPProcessInformation);
replaceNonFiniteFilter->UpdateLargestPossibleRegion();
typename InputImageType::Pointer inputImage = replaceNonFiniteFilter->GetOutput();
// Find the bounding box of the input
typedef typename OutputImageType::PointType OutputPointType;
OutputPointType lowerBound( itk::NumericTraits< typename OutputPointType::CoordRepType >::max() );
OutputPointType upperBound( itk::NumericTraits< typename OutputPointType::CoordRepType >::NonpositiveMin() );
typename InputImageType::SizeType inputSize = inputImage->GetLargestPossibleRegion().GetSize();
typename InputImageType::IndexType inputIndex;
typename InputImageType::PointType point;
// Only sample with some of the slices so we get a sufficient sampling of
// the bounds
const itk::IndexValueType sliceStride = 4;
for( itk::IndexValueType sliceIndex = 0; sliceIndex < inputSize[2]; sliceIndex += sliceStride )
{
inputIndex[0] = 0;
inputIndex[1] = 0;
inputIndex[2] = sliceIndex;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
inputIndex[0] = inputSize[0] - 1;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
inputIndex[0] = 0;
inputIndex[1] = inputSize[1] - 1;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
inputIndex[0] = inputSize[0] - 1;
inputIndex[1] = inputSize[1] - 1;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
}
const itk::IndexValueType sliceIndex = inputSize[2] - 1;
inputIndex[2] = sliceIndex;
inputIndex[0] = 0;
inputIndex[1] = 0;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
inputIndex[0] = inputSize[0] - 1;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
inputIndex[0] = 0;
inputIndex[1] = inputSize[1] - 1;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
inputIndex[0] = inputSize[0] - 1;
inputIndex[1] = inputSize[1] - 1;
inputImage->TransformIndexToPhysicalPoint( inputIndex, point );
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
lowerBound[ii] = std::min( lowerBound[ii], point[ii] );
upperBound[ii] = std::max( upperBound[ii], point[ii] );
}
typename OutputImageType::SpacingType spacing;
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
spacing[ii] = outputSpacing[ii];
}
typename OutputImageType::SizeType size;
for( unsigned int ii = 0; ii < Dimension; ++ii )
{
size[ii] = ( upperBound[ii] - lowerBound[ii] ) / outputSpacing[ii] + 1;
}
typename OutputImageType::DirectionType direction;
direction.SetIdentity();
typename OutputImageType::Pointer outputImage;
ScanConversionResampling< InputImageType, OutputImageType >( inputImage,
outputImage,
size,
spacing,
lowerBound,
direction,
method,
CLPProcessInformation
);
typedef itk::ImageFileWriter< OutputImageType > WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputVolume );
writer->SetInput( outputImage );
writer->SetUseCompression( true );
itk::PluginFilterWatcher watchWriter(writer, "Write Output", CLPProcessInformation);
writer->Update();
return EXIT_SUCCESS;
}
} // end of anonymous namespace
int main( int argc, char * argv[] )
{
PARSE_ARGS;
itk::ImageIOBase::IOPixelType inputPixelType;
itk::ImageIOBase::IOComponentType inputComponentType;
try
{
// TODO: use the CMake configured factory registration
itk::HDF5UltrasoundImageIOFactory::RegisterOneFactory();
itk::GetImageType(inputVolume, inputPixelType, inputComponentType);
switch( inputComponentType )
{
//case itk::ImageIOBase::UCHAR:
//return DoIt< unsigned char >( argc, argv );
//break;
//case itk::ImageIOBase::USHORT:
//return DoIt< unsigned short >( argc, argv );
//break;
//case itk::ImageIOBase::SHORT:
//return DoIt< short >( argc, argv );
//break;
case itk::ImageIOBase::FLOAT:
return DoIt< float >( argc, argv );
break;
//case itk::ImageIOBase::DOUBLE:
//return DoIt< double >( argc, argv );
//break;
default:
std::cerr << "Unknown input image pixel component type: "
<< itk::ImageIOBase::GetComponentTypeAsString( inputComponentType )
<< std::endl;
return EXIT_FAILURE;
break;
}
}
catch( itk::ExceptionObject & excep )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| [
"matt.mccormick@kitware.com"
] | matt.mccormick@kitware.com |
a846e1fd23bc8a9848d15262926a04fe6452af9d | b5e51cfb027bb6b4354925ad28ab5f65215230e7 | /dayTwoCppProjects/multiplyBy2.cpp | bbd973df307d1846ab899d0af867330b903a748d | [] | no_license | Isaac-Tait/myCppCreations | 74a142e6738a1bd25ea839779b70206c2bb636aa | d37dfbafd4a2a1860a63784b0c8b977bfc9fd738 | refs/heads/main | 2023-07-06T12:35:19.988762 | 2021-08-09T14:14:41 | 2021-08-09T14:14:41 | 383,000,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | cpp | /*
* multiplyBy2.cpp
*
* Created on: Jun 30, 2021
* Author: isaactait
*/
#import <iostream>
int main() {
std::cout << "Enter an integer: ";
int x{ };
std::cin >> x;
std::cout << "Enter another integer: ";
int y{ };
std::cin >> y;
std::cout << "Your first and second choice added together equals: " << x + y << '\n';
std::cout << "Subtracting your first and second choice equals: " << x - y;
return 0;
}
//I wrote this using my brain! No cheating AND I implemented the lesson's "Preferred Solution" to boot!
| [
"isaac@mountaintopcoding.com"
] | isaac@mountaintopcoding.com |
8278651ab487251a80492c244a51a932bcedd3e3 | 97e0d023d36c14a1b7d8c5ae4d579066492b5c58 | /搜索/BFS/POJ3126 素数替换/main.cpp | aacff8401c0c999a761eb50d233f11973dd722be | [] | no_license | gmy987/ACM | f6f809811b54a1e106624b83eda56120ac85d852 | 4b807f61b35d07db0d35e2195a8d93cff648b7bb | refs/heads/master | 2021-01-13T01:28:55.209296 | 2015-09-03T07:09:28 | 2015-09-03T07:09:28 | 41,202,863 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | #include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int vist[10005];
int m,a,b;
struct Number
{
int num,step;
};
bool isPrime( int x )
{
if(x==1||!(x%2)) return false;
if(x==2) return true;
for( int i = 3 ; i <= sqrt(x) ; i+=2 )
if(!(x%i))
return false;
return true;
}
int bfs( int a , int b )
{
memset(vist,0,sizeof(vist));
Number n;
n.num = a,n.step = 0;
queue<Number> q;
q.push(n);
vist[n.num] = 1;
while(!q.empty())
{
Number v;
n = q.front();
q.pop();
if( n.num == b )
return n.step;
for( int i = 3 ; i >= 0 ; i-- )
{
int p = pow(10,i);
int x = (n.num/p)%10;
for( int j = 0 ; j < 10 ; j++ )
{
if( i == 3 && j == 0 )
continue;
int y = n.num + (j-x)*p;
if(!vist[y]&&isPrime(y) )
{
v.num = y;
v.step = n.step + 1;
vist[y] = 1;
q.push(v);
}
}
}
}
return -1;
}
int main()
{
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&a,&b);
int step = bfs( a , b );
if( step == -1)
printf("Impossible\n");
else
printf("%d\n",step);
}
}
| [
"46922547@qq.com"
] | 46922547@qq.com |
b9c57d82f57d91e403a1a6f9fde8b18cdd17f170 | 2ad9f9026c21c4392df4d4fb63d349a2f21a6c42 | /samples/VR2Arm/LighthouseTracking.cpp | 39252f2f96f2e549da4b0d0a828d1a5376026715 | [
"MIT",
"BSD-3-Clause"
] | permissive | itsgohtime/VR | a935e0f83275f6c773e19c74109333cec4c6c71d | 25f3851224f1a7cc09e219e26f2dc1a7774519be | refs/heads/master | 2022-04-12T19:36:44.425960 | 2020-02-28T22:53:24 | 2020-02-28T22:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,517 | cpp |
// The main file for dealing with VR specifically. See LighthouseTracking.h for descriptions of each function in the class.
#include "LighthouseTracking.h"
#define NOMINMAX
#include <windows.h>
// Destructor for the LighthouseTracking object
LighthouseTracking::~LighthouseTracking()
{
if (vr_pointer != NULL)
{
// VR Shutdown: https://github.com/ValveSoftware/openvr/wiki/API-Documentation#initialization-and-cleanup
VR_Shutdown();
vr_pointer = NULL;
}
}
// Constructor for the LighthouseTracking object
LighthouseTracking::LighthouseTracking(InitFlags f, Human& O, AllViveDevices& V) : Operator(O), ViveSystem(V)
{
flags = f;
coordsBuf = new char[1024];
trackBuf = new char[1024];
rotBuf = new char[1024];
trackers = new TrackerData[16];
// Definition of the init error
EVRInitError eError = VRInitError_None;
/*
VR_Init (
arg1: Pointer to EVRInitError type (enum defined in openvr.h)
arg2: Must be of type EVRApplicationType
The type of VR Applicaion. This example uses the SteamVR instance that is already running.
Because of this, the init function will fail if SteamVR is not already running.
Other EVRApplicationTypes include:
* VRApplication_Scene - "A 3D application that will be drawing an environment.""
* VRApplication_Overlay - "An application that only interacts with overlays or the dashboard.""
* VRApplication_Utility
*/
vr_pointer = VR_Init(&eError, VRApplication_Background);
// If the init failed because of an error
if (eError != VRInitError_None)
{
vr_pointer = NULL;
printf("Unable to init VR runtime: %s \n", VR_GetVRInitErrorAsEnglishDescription(eError));
exit(EXIT_FAILURE);
}
//If the init didn't fail, init the Cylinder object array
cylinders = new Cylinder*[MAX_CYLINDERS];
for(int i = 0 ; i < MAX_CYLINDERS; i++)
{
cylinders[i] = new Cylinder();
}
}
bool LighthouseTracking::RunProcedure()
{
// Define a VREvent
VREvent_t event;
if(vr_pointer->PollNextEvent(&event, sizeof(event)))
{
/*
ProcessVREvent is a function defined in this module. It returns false if
the function determines the type of error to be fatal or signal some kind of quit.
*/
if (!ProcessVREvent(event))
{
// If ProcessVREvent determined that OpenVR quit, print quit message
printf("\nEVENT--(OpenVR) service quit");
return false;
}
}
// ParseTrackingFrame() is where the tracking and vibration code starts
ParseTrackingFrame();
return true;
}
bool LighthouseTracking::ProcessVREvent(const VREvent_t & event)
{
char* buf = new char[100];
bool ret = true;
switch (event.eventType)
{
case VREvent_TrackedDeviceActivated:
sprintf(buf, "\nEVENT--(OpenVR) Device : %d attached", event.trackedDeviceIndex);
break;
case VREvent_TrackedDeviceDeactivated:
sprintf(buf, "\nEVENT--(OpenVR) Device : %d detached", event.trackedDeviceIndex);
break;
case VREvent_TrackedDeviceUpdated:
sprintf(buf, "\nEVENT--(OpenVR) Device : %d updated", event.trackedDeviceIndex);
break;
case VREvent_DashboardActivated:
sprintf(buf, "\nEVENT--(OpenVR) Dashboard activated");
break;
case VREvent_DashboardDeactivated:
sprintf(buf, "\nEVENT--(OpenVR) Dashboard deactivated");
break;
case VREvent_ChaperoneDataHasChanged:
sprintf(buf, "\nEVENT--(OpenVR) Chaperone data has changed");
break;
case VREvent_ChaperoneSettingsHaveChanged:
sprintf(buf, "\nEVENT--(OpenVR) Chaperone settings have changed");
break;
case VREvent_ChaperoneUniverseHasChanged:
sprintf(buf, "\nEVENT--(OpenVR) Chaperone universe has changed");
break;
case VREvent_Quit:
{
sprintf(buf, "\nEVENT--(OpenVR) Received SteamVR Quit (%d%s", VREvent_Quit, ")");
ret = false;
}
break;
case VREvent_ProcessQuit:
{
sprintf(buf, "\nEVENT--(OpenVR) SteamVR Quit Process (%d%s", VREvent_ProcessQuit, ")");
ret = false;
}
break;
case VREvent_QuitAcknowledged:
{
sprintf(buf, "\nEVENT--(OpenVR) SteamVR Quit Acknowledged (%d%s", VREvent_QuitAcknowledged, ")");
ret = false;
}
break;
case VREvent_TrackedDeviceRoleChanged:
sprintf(buf, "\nEVENT--(OpenVR) TrackedDeviceRoleChanged: %d", event.trackedDeviceIndex);
break;
case VREvent_TrackedDeviceUserInteractionStarted:
sprintf(buf, "\nEVENT--(OpenVR) TrackedDeviceUserInteractionStarted: %d", event.trackedDeviceIndex);
break;
default:
if (event.eventType >= 200 && event.eventType <= 203) //Button events range from 200-203
dealWithButtonEvent(event);
else
sprintf(buf, "\nEVENT--(OpenVR) Event: %d", event.eventType);
// Check entire event list starts on line #452: https://github.com/ValveSoftware/openvr/blob/master/headers/openvr.h
}
if(flags.printEvents)
printf("%s",buf);
return ret;
}
//This method deals exclusively with button events
void LighthouseTracking::dealWithButtonEvent(VREvent_t event)
{
int controllerIndex = -1; //The index of the controllers[] array that corresponds with the controller that had a buttonEvent
for (int i = 0; i < 2; i++) //Iterates across the array of controllers
{
ControllerData* pController = &(controllers[i]);
if(flags.printBEvents && event.trackedDeviceIndex == pController->deviceId) //prints the event data to the terminal
printf("\nBUTTON-E--index=%d deviceId=%d hand=%d button=%d event=%d",i,pController->deviceId,pController->hand,event.data.controller.button,event.eventType);
if(pController->deviceId == event.trackedDeviceIndex) //This tests to see if the current controller from the loop is the same from the event
controllerIndex = i;
}
if (controllerIndex == -1) return;
ControllerData* pC = &(controllers[controllerIndex]); //The pointer to the ControllerData struct
if (event.data.controller.button == k_EButton_ApplicationMenu //Test if the ApplicationButton was pressed
&& event.eventType == VREvent_ButtonUnpress) //Test if the button is being released (the action happens on release, not press)
{
inDrawingMode = !inDrawingMode;
doRumbleNow = true;
}
if(inDrawingMode)
switch( event.data.controller.button )
{
case k_EButton_Grip: //If it is the grip button that was...
switch(event.eventType)
{
case VREvent_ButtonPress: // ...pressed...
if(cpMillis() - gripMillis > 500) // ...and it's been half a second since the grip was last released...
cylinders[cylinderIndex]->s1[1] = pC->pos.v[1]; //...then set the cylinder's y 1 to the controllers y coordinate.
break;
case VREvent_ButtonUnpress: // ...released...
if(cpMillis() - gripMillis > 500) // ...and it's been half a second since the grip was last released...
cylinders[cylinderIndex]->s2[1] = pC->pos.v[1]; //...then set the cylinder's y 2 to the controllers y coordinate.
else // ...and it' hasn't been half a second since the grip was last released...
{
if(cylinders[cylinderIndex]->s1[1] > pC->pos.v[1]) // ...if the controller's position is **below** the starting position...
cylinders[cylinderIndex]->s2[1] = -std::numeric_limits<float>::max(); // ...set the cylinder's y 2 to negative infinity.
else // ...if the controller's position is **above** the starting position...
cylinders[cylinderIndex]->s2[1] = std::numeric_limits<float>::max(); // ...set the cylinder's y 2 to positive infinity.
}
cylinders[cylinderIndex]->init();
gripMillis = cpMillis();
break;
}
break;
case k_EButton_SteamVR_Trigger:
switch(event.eventType)
{
case VREvent_ButtonPress: //If the trigger was pressed...
cylinders[cylinderIndex]->s1[0] = pC->pos.v[0]; //Set the cylinder's x 1 to the controller's x
cylinders[cylinderIndex]->s1[2] = pC->pos.v[2]; //Set the cylinder's z 1 to the controller's z
break;
case VREvent_ButtonUnpress://If the trigger was released...
cylinders[cylinderIndex]->s2[0] = pC->pos.v[0]; //Set the cylinder's x 2 to the controller's x
cylinders[cylinderIndex]->s2[2] = pC->pos.v[2]; //Set the cylinder's z 2 to the controller's z
cylinders[cylinderIndex]->init();
break;
}
break;
case k_EButton_SteamVR_Touchpad:
switch(event.eventType)
{
case VREvent_ButtonPress:
break;
case VREvent_ButtonUnpress://If the touchpad was just pressed
if(std::abs(pC->padX) > std::abs(pC->padY)) //Tests if the left or right of the pad was pressed
{
if (pC->padX < 0 && cylinderIndex != 0) //If left side of pad was pressed and there is a previous cylinder
cylinderIndex = cylinderIndex-1; //Switch index to previous cylinder
else if (pC->padX > 0 && cylinderIndex < MAX_CYLINDERS) //If the right side of the pad was pressed
cylinderIndex = cylinderIndex+1; //Switch the index to the next cylinder
doRumbleNow = true;
}
else //If the top/bottom of the pad was pressed
{
if (pC->padY > 0) //If the top was pressed
doRumbleNow = true;
else if (pC->padY < 0) //If the bottom was pressed, reset the current cylinder
cylinders[cylinderIndex] = new Cylinder();
}
break;
}
break;
}
}
HmdVector3_t LighthouseTracking::GetPosition(HmdMatrix34_t matrix)
{
HmdVector3_t vector;
vector.v[0] = matrix.m[0][3];
vector.v[1] = matrix.m[1][3];
vector.v[2] = matrix.m[2][3];
return vector;
}
long lastPRCall = 0;
HmdQuaternion_t LighthouseTracking::GetRotation(HmdMatrix34_t matrix)
{
HmdQuaternion_t q;
q.w = sqrt(fmax(0, 1 + matrix.m[0][0] + matrix.m[1][1] + matrix.m[2][2])) / 2;
q.x = sqrt(fmax(0, 1 + matrix.m[0][0] - matrix.m[1][1] - matrix.m[2][2])) / 2;
q.y = sqrt(fmax(0, 1 - matrix.m[0][0] + matrix.m[1][1] - matrix.m[2][2])) / 2;
q.z = sqrt(fmax(0, 1 - matrix.m[0][0] - matrix.m[1][1] + matrix.m[2][2])) / 2;
q.x = copysign(q.x, matrix.m[2][1] - matrix.m[1][2]);
q.y = copysign(q.y, matrix.m[0][2] - matrix.m[2][0]);
q.z = copysign(q.z, matrix.m[1][0] - matrix.m[0][1]);
return q;
}
HmdQuaternion_t LighthouseTracking::ProcessRotation(HmdQuaternion_t quat)
{
HmdQuaternion_t out;
out.w = 2 * acos(quat.w);
out.x = quat.x / sin(out.w/2);
out.y = quat.y / sin(out.w/2);
out.z = quat.z / sin(out.w/2);
printf("\nPROCESSED w:%.3f x:%.3f y:%.3f z:%.3f",out.w,out.x,out.y,out.z);
return out;
}
void LighthouseTracking::iterateAssignIds()
{
//Un-assigns the deviceIds and hands of controllers. If they are truely connected, will be re-assigned later in this function
controllers[0].deviceId = -1;
controllers[1].deviceId = -1;
controllers[0].hand = -1;
controllers[1].hand = -1;
int numTrackersInitialized = 0;
int numControllersInitialized = 0;
for (unsigned int i = 0; i < k_unMaxTrackedDeviceCount; i++) // Iterates across all of the potential device indicies
{
if (!vr_pointer->IsTrackedDeviceConnected(i))
continue; //Doesn't use the id if the device isn't connected
//vr_pointer points to the VRSystem that was in init'ed in the constructor.
ETrackedDeviceClass trackedDeviceClass = vr_pointer->GetTrackedDeviceClass(i);
//Finding the type of device
if (trackedDeviceClass == ETrackedDeviceClass::TrackedDeviceClass_HMD)
{
hmdDeviceId = i;
if(flags.printSetIds)
printf("\nSETID--Assigned hmdDeviceId=%d",hmdDeviceId);
}
else if (trackedDeviceClass == ETrackedDeviceClass::TrackedDeviceClass_Controller && numControllersInitialized < 2)
{
ControllerData* pC = &(controllers[numControllersInitialized]);
int sHand = -1;
ETrackedControllerRole role = vr_pointer->GetControllerRoleForTrackedDeviceIndex(i);
if (role == TrackedControllerRole_Invalid) //Invalid hand is actually very common, always need to test for invalid hand (lighthouses have lost tracking)
sHand = 0;
else if (role == TrackedControllerRole_LeftHand)
sHand = 1;
else if (role == TrackedControllerRole_RightHand)
sHand = 2;
pC->hand = sHand;
pC->deviceId = i;
//Used to get/store property ids for the xy of the pad and the analog reading of the trigger
for(int x=0; x<k_unControllerStateAxisCount; x++ )
{
int prop = vr_pointer->GetInt32TrackedDeviceProperty(pC->deviceId,
(ETrackedDeviceProperty)(Prop_Axis0Type_Int32 + x));
if( prop==k_eControllerAxis_Trigger )
pC->idtrigger = x;
else if( prop==k_eControllerAxis_TrackPad )
pC->idpad = x;
}
if(flags.printSetIds)
printf("\nSETID--Assigned controllers[%d] .hand=%d .deviceId=%d .idtrigger=%d .idpad=%d",numControllersInitialized,sHand, i , pC->idtrigger, pC->idpad);
numControllersInitialized++; //Increment this count so that the other controller gets initialized after initializing this one
}
else if(trackedDeviceClass == ETrackedDeviceClass::TrackedDeviceClass_GenericTracker)
{
TrackerData* pT = &(trackers[numTrackersInitialized]);
pT->deviceId = i;
if(flags.printSetIds)
printf("\nSETID--Assigned tracker[%d] .deviceId=%d",numTrackersInitialized,pT->deviceId);
numTrackersInitialized++;
}
}
}
void LighthouseTracking::setHands()
{
for (int z =0; z < 2; z++)
{
ControllerData* pC = &(controllers[z]);
if (pC->deviceId < 0 || !vr_pointer->IsTrackedDeviceConnected(pC->deviceId))
continue;
int sHand = -1;
//Invalid hand is actually very common, always need to test for invalid hand (lighthouses have lost tracking)
ETrackedControllerRole role = vr_pointer->GetControllerRoleForTrackedDeviceIndex(pC->deviceId);
if (role == TrackedControllerRole_Invalid)
sHand = 0;
else if (role == TrackedControllerRole_LeftHand)
sHand = 1;
else if (role == TrackedControllerRole_RightHand)
sHand = 2;
pC->hand = sHand;
}
}
void LighthouseTracking::ParseTrackingFrame()
{
//Runs the iterateAssignIds() method if...
if(hmdDeviceId < 0 || // HMD id not yet initialized
controllers[0].deviceId < 0 || // One of the controllers not yet initialized
controllers[1].deviceId < 0 ||
controllers[0].deviceId == controllers[1].deviceId || //Both controllerData structs store the same deviceId
controllers[0].hand == controllers[1].hand || //Both controllerData structs are the same hand
(cpMillis() / 60000) > minuteCount) //It has been a minute since last init time
{
minuteCount = (cpMillis() / 60000);
iterateAssignIds();
}
HMDCoords();
ControllerCoords();
if(flags.printCoords)
printf("\nCOORDS-- %s",coordsBuf);
if(flags.printTrack)
printf("\nTRACK-- %s",trackBuf);
if(flags.printRotation)
printf("\nROT-- %s",rotBuf);
}
void LighthouseTracking::HMDCoords()
{
if (!vr_pointer->IsTrackedDeviceConnected(hmdDeviceId))
return;
//TrackedDevicePose_t struct is a OpenVR struct. See line 180 in the openvr.h header.
TrackedDevicePose_t trackedDevicePose;
HmdVector3_t position;
HmdQuaternion_t rot;
/*if (vr_pointer->IsInputFocusCapturedByAnotherProcess())
printf( "\nINFO--Input Focus by Another Process");*/
vr_pointer->GetDeviceToAbsoluteTrackingPose(TrackingUniverseStanding, 0, &trackedDevicePose, 1);
position = GetPosition(trackedDevicePose.mDeviceToAbsoluteTracking);
rot = GetRotation(trackedDevicePose.mDeviceToAbsoluteTracking);
ViveSystem.H.setPosAndRot(position, rot);
ViveSystem.H.valid = trackedDevicePose.bPoseIsValid;
sprintf(coordsBuf,"HMD %-28.28s", getPoseXYZString(trackedDevicePose,0));
sprintf(trackBuf,"HMD: %-25.25s %-7.7s " , getEnglishTrackingResultForPose(trackedDevicePose) , getEnglishPoseValidity(trackedDevicePose));
sprintf(rotBuf,"HMD: qw:%.2f qx:%.2f qy:%.2f qz:%.2f",rot.w,rot.x,rot.y,rot.z);
}
long LighthouseTracking::cpMillis()
{
#if defined __linux
if (!clockDef)
{
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
clockDef = true;
}
struct timespec end;
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
return ((end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000) / 1000;
#elif defined _WIN32 || defined __CYGWIN__
SYSTEMTIME time;
GetSystemTime(&time);
return (time.wSecond * 1000) + time.wMilliseconds;
#else
#error Platform not supported
#endif
}
void LighthouseTracking::ControllerCoords()
{
setHands();
if(doRumbleNow)
{
rumbleMsOffset = cpMillis();
doRumbleNow = false;
}
TrackedDevicePose_t trackedDevicePose;
VRControllerState_t controllerState;
HmdQuaternion_t rot;
//Arrays to contain information about the results of the button state sprintf call
// so that the button state information can be printed all on one line for both controllers
char** bufs = new char*[2];
bool* isOk = new bool[2];
//Stores the number of times 150ms have elapsed (loops with the % operator because
// the "cylinder count" rumbling starts when indexN is one).
int indexN = ((cpMillis()-rumbleMsOffset)/150)%(125);
//Loops for each ControllerData struct
for(int i = 0; i < 2; i++)
{
isOk[i] = false;
char* buf = new char[100];
ControllerData* pC = &(controllers[i]);
if (pC->deviceId < 0 ||
!vr_pointer->IsTrackedDeviceConnected(pC->deviceId) ||
pC->hand </*= Allow printing coordinates for invalid hand? Yes.*/ 0)
continue;
vr_pointer->GetControllerStateWithPose(TrackingUniverseStanding, pC->deviceId, &controllerState, sizeof(controllerState), &trackedDevicePose);
pC->pos = GetPosition(trackedDevicePose.mDeviceToAbsoluteTracking);
rot = GetRotation(trackedDevicePose.mDeviceToAbsoluteTracking);
int t = pC->idtrigger;
int p = pC->idpad;
//This is the call to get analog button data from the controllers
pC->trigVal = controllerState.rAxis[t].x;
pC->padX = controllerState.rAxis[p].x;
pC->padY = controllerState.rAxis[p].y;
char handString[6];
ViveController& currSide = ViveController('W');
if (pC->hand == 1) {
sprintf(handString, "LEFT");
ViveSystem.L.setPosAndRot(pC->pos, rot);
ViveSystem.L.setInputs(pC->padX, pC->padY, pC->trigVal);
ViveSystem.L.valid = pC->isValid;
if (controllerState.ulButtonPressed == 2) {
Operator.calcHeadShoulderOffset(ViveSystem.L, ViveSystem.H);
ViveSystem.L.calibarated = true;
}
}
else if (pC->hand == 2) {
sprintf(handString, "RIGHT");
ViveSystem.R.setPosAndRot(pC->pos, rot);
ViveSystem.R.setInputs(pC->padX, pC->padY, pC->trigVal);
ViveSystem.R.valid = pC->isValid;
if (controllerState.ulButtonPressed == 2) {
Operator.calcHeadShoulderOffset(ViveSystem.R, ViveSystem.H);
ViveSystem.R.calibarated = true;
}
}
else if(pC->hand == 0)
sprintf(handString, "INVALID");
pC->isValid = trackedDevicePose.bPoseIsValid;
sprintf(coordsBuf,"%s %s: %-28.28s",coordsBuf, handString, getPoseXYZString(trackedDevicePose,pC->hand));
sprintf(trackBuf,"%s %s: %-25.25s %-7.7s" , trackBuf, handString, getEnglishTrackingResultForPose(trackedDevicePose), getEnglishPoseValidity(trackedDevicePose));
sprintf(rotBuf,"%s %s qw:%.2f qx:%.2f qy:%.2f qz:%.2f",rotBuf,handString,rot.w,rot.x,rot.y,rot.z);
sprintf(buf,"hand=%s handid=%d trigger=%f padx=%f pady=%f", handString, pC->hand , pC->trigVal , pC->padX , pC->padY);
bufs[i] = buf;
isOk[i] = true;
//The following block controlls the rumbling of the controllers
if(!inDrawingMode) //Will iterate across all cylinders if in sensing mode
for(int x = 0; x < MAX_CYLINDERS; x++)
{
Cylinder* currCy = cylinders[x];
if(currCy->hasInit &&
currCy->isInside(pC->pos.v[0],pC->pos.v[1],pC->pos.v[2]))
vr_pointer->TriggerHapticPulse(pC->deviceId,pC->idpad,500); //Vibrates if the controller is colliding with the cylinder bounds
}
if (inDrawingMode && indexN % 3 == 0 && indexN < (cylinderIndex+1)*3) //Vibrates the current cylinderIndex every thirty seconds or so
vr_pointer->TriggerHapticPulse(pC->deviceId,pC->idpad,300); // see the definition of indexN above before the for loop
}
if(flags.printAnalog && isOk[0] == true)
{
printf("\nANALOG-- %s", bufs[0]);
if(isOk[1] == true)
{
printf(" %s", bufs[1]);
}
}
}
char* LighthouseTracking::getEnglishTrackingResultForPose(TrackedDevicePose_t pose)
{
char* buf = new char[50];
switch (pose.eTrackingResult)
{
case vr::ETrackingResult::TrackingResult_Uninitialized:
sprintf(buf, "Invalid tracking result");
break;
case vr::ETrackingResult::TrackingResult_Calibrating_InProgress:
sprintf(buf, "Calibrating in progress");
break;
case vr::ETrackingResult::TrackingResult_Calibrating_OutOfRange:
sprintf(buf, "Calibrating Out of range");
break;
case vr::ETrackingResult::TrackingResult_Running_OK:
sprintf(buf, "Running OK");
break;
case vr::ETrackingResult::TrackingResult_Running_OutOfRange:
sprintf(buf, "WARNING: Running Out of Range");
break;
default:
sprintf(buf, "Default");
break;
}
return buf;
}
char* LighthouseTracking::getEnglishPoseValidity(TrackedDevicePose_t pose)
{
char* buf = new char[50];
if(pose.bPoseIsValid)
sprintf(buf, "Valid");
else
sprintf(buf, "Invalid");
return buf;
}
char* LighthouseTracking::getPoseXYZString(TrackedDevicePose_t pose, int hand)
{
HmdVector3_t pos = GetPosition(pose.mDeviceToAbsoluteTracking);
char* cB = new char[50];
if(pose.bPoseIsValid)
sprintf(cB, "x:%.3f y:%.3f z:%.3f",pos.v[0], pos.v[1], pos.v[2]);
else
sprintf(cB, " INVALID");
if(flags.pipeCoords)
for(int i = 0; i < 3; i++)
if(pose.bPoseIsValid)
printf("%.5f\n",pos.v[i]);
else
printf("invalid\n",pos.v[i]);
return cB;
}
| [
"32887801+aed3@users.noreply.github.com"
] | 32887801+aed3@users.noreply.github.com |
4e8a59ff8a41eaa9b93b5235fd561449d414b116 | 1f1cc05377786cc2aa480cbdfde3736dd3930f73 | /xulrunner-sdk-26/xulrunner-sdk/include/nsIDOMHistory.h | 9f2bd12dfb67ffd852ad8b50e5947d65e5958de0 | [
"Apache-2.0"
] | permissive | julianpistorius/gp-revolution-gaia | 84c3ec5e2f3b9e76f19f45badc18d5544bb76e0d | 6e27b83efb0d4fa4222eaf25fb58b062e6d9d49e | refs/heads/master | 2021-01-21T02:49:54.000389 | 2014-03-27T09:58:17 | 2014-03-27T09:58:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,862 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/m-cen-l64-xr-ntly-000000000000/build/dom/interfaces/base/nsIDOMHistory.idl
*/
#ifndef __gen_nsIDOMHistory_h__
#define __gen_nsIDOMHistory_h__
#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif
#include "jspubtd.h"
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
struct JSContext;
class nsIVariant; /* forward declaration */
/* starting interface: nsIDOMHistory */
#define NS_IDOMHISTORY_IID_STR "d5a3006b-dd6b-4ba3-81be-6559f8889e60"
#define NS_IDOMHISTORY_IID \
{0xd5a3006b, 0xdd6b, 0x4ba3, \
{ 0x81, 0xbe, 0x65, 0x59, 0xf8, 0x88, 0x9e, 0x60 }}
class NS_NO_VTABLE nsIDOMHistory : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMHISTORY_IID)
/* readonly attribute long length; */
NS_IMETHOD GetLength(int32_t *aLength) = 0;
/* readonly attribute DOMString current; */
NS_IMETHOD GetCurrent(nsAString & aCurrent) = 0;
/* readonly attribute DOMString previous; */
NS_IMETHOD GetPrevious(nsAString & aPrevious) = 0;
/* readonly attribute DOMString next; */
NS_IMETHOD GetNext(nsAString & aNext) = 0;
/* void back (); */
NS_IMETHOD Back(void) = 0;
/* void forward (); */
NS_IMETHOD Forward(void) = 0;
/* void go ([optional] in long aDelta); */
NS_IMETHOD Go(int32_t aDelta) = 0;
/* DOMString item (in unsigned long index); */
NS_IMETHOD Item(uint32_t index, nsAString & _retval) = 0;
/* [implicit_jscontext] void pushState (in nsIVariant aData, in DOMString aTitle, [optional] in DOMString aURL); */
NS_IMETHOD PushState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx) = 0;
/* [implicit_jscontext] void replaceState (in nsIVariant aData, in DOMString aTitle, [optional] in DOMString aURL); */
NS_IMETHOD ReplaceState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx) = 0;
/* readonly attribute nsIVariant state; */
NS_IMETHOD GetState(nsIVariant * *aState) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMHistory, NS_IDOMHISTORY_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMHISTORY \
NS_IMETHOD GetLength(int32_t *aLength); \
NS_IMETHOD GetCurrent(nsAString & aCurrent); \
NS_IMETHOD GetPrevious(nsAString & aPrevious); \
NS_IMETHOD GetNext(nsAString & aNext); \
NS_IMETHOD Back(void); \
NS_IMETHOD Forward(void); \
NS_IMETHOD Go(int32_t aDelta); \
NS_IMETHOD Item(uint32_t index, nsAString & _retval); \
NS_IMETHOD PushState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx); \
NS_IMETHOD ReplaceState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx); \
NS_IMETHOD GetState(nsIVariant * *aState);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMHISTORY(_to) \
NS_IMETHOD GetLength(int32_t *aLength) { return _to GetLength(aLength); } \
NS_IMETHOD GetCurrent(nsAString & aCurrent) { return _to GetCurrent(aCurrent); } \
NS_IMETHOD GetPrevious(nsAString & aPrevious) { return _to GetPrevious(aPrevious); } \
NS_IMETHOD GetNext(nsAString & aNext) { return _to GetNext(aNext); } \
NS_IMETHOD Back(void) { return _to Back(); } \
NS_IMETHOD Forward(void) { return _to Forward(); } \
NS_IMETHOD Go(int32_t aDelta) { return _to Go(aDelta); } \
NS_IMETHOD Item(uint32_t index, nsAString & _retval) { return _to Item(index, _retval); } \
NS_IMETHOD PushState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx) { return _to PushState(aData, aTitle, aURL, cx); } \
NS_IMETHOD ReplaceState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx) { return _to ReplaceState(aData, aTitle, aURL, cx); } \
NS_IMETHOD GetState(nsIVariant * *aState) { return _to GetState(aState); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMHISTORY(_to) \
NS_IMETHOD GetLength(int32_t *aLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLength(aLength); } \
NS_IMETHOD GetCurrent(nsAString & aCurrent) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCurrent(aCurrent); } \
NS_IMETHOD GetPrevious(nsAString & aPrevious) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrevious(aPrevious); } \
NS_IMETHOD GetNext(nsAString & aNext) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNext(aNext); } \
NS_IMETHOD Back(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Back(); } \
NS_IMETHOD Forward(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Forward(); } \
NS_IMETHOD Go(int32_t aDelta) { return !_to ? NS_ERROR_NULL_POINTER : _to->Go(aDelta); } \
NS_IMETHOD Item(uint32_t index, nsAString & _retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->Item(index, _retval); } \
NS_IMETHOD PushState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx) { return !_to ? NS_ERROR_NULL_POINTER : _to->PushState(aData, aTitle, aURL, cx); } \
NS_IMETHOD ReplaceState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx) { return !_to ? NS_ERROR_NULL_POINTER : _to->ReplaceState(aData, aTitle, aURL, cx); } \
NS_IMETHOD GetState(nsIVariant * *aState) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetState(aState); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMHistory : public nsIDOMHistory
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMHISTORY
nsDOMHistory();
private:
~nsDOMHistory();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMHistory, nsIDOMHistory)
nsDOMHistory::nsDOMHistory()
{
/* member initializers and constructor code */
}
nsDOMHistory::~nsDOMHistory()
{
/* destructor code */
}
/* readonly attribute long length; */
NS_IMETHODIMP nsDOMHistory::GetLength(int32_t *aLength)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString current; */
NS_IMETHODIMP nsDOMHistory::GetCurrent(nsAString & aCurrent)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString previous; */
NS_IMETHODIMP nsDOMHistory::GetPrevious(nsAString & aPrevious)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString next; */
NS_IMETHODIMP nsDOMHistory::GetNext(nsAString & aNext)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void back (); */
NS_IMETHODIMP nsDOMHistory::Back()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void forward (); */
NS_IMETHODIMP nsDOMHistory::Forward()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void go ([optional] in long aDelta); */
NS_IMETHODIMP nsDOMHistory::Go(int32_t aDelta)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* DOMString item (in unsigned long index); */
NS_IMETHODIMP nsDOMHistory::Item(uint32_t index, nsAString & _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [implicit_jscontext] void pushState (in nsIVariant aData, in DOMString aTitle, [optional] in DOMString aURL); */
NS_IMETHODIMP nsDOMHistory::PushState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [implicit_jscontext] void replaceState (in nsIVariant aData, in DOMString aTitle, [optional] in DOMString aURL); */
NS_IMETHODIMP nsDOMHistory::ReplaceState(nsIVariant *aData, const nsAString & aTitle, const nsAString & aURL, JSContext* cx)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIVariant state; */
NS_IMETHODIMP nsDOMHistory::GetState(nsIVariant * *aState)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMHistory_h__ */
| [
"luis@geeksphone.com"
] | luis@geeksphone.com |
11b4613848f15c7fb7c6214fe1c5a812056c1341 | 5cdc014e3634901e65c0e5e68d429a3184832715 | /ACM/template/STL/部分排序 partial_sort.cpp | df459ed57380e4ea85373cddbc6616822de92139 | [] | no_license | sandychn/Programming-Contest-Practice | 3d3fdb366bb8dddceb179d45a831c962e1e6e636 | b47841263671ecad0602a18c6c52acc56f69b453 | refs/heads/master | 2022-11-10T15:48:51.529764 | 2020-06-22T18:06:27 | 2020-06-22T18:06:27 | 198,926,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 645 | cpp | /*
partial_sort(first, middle, last, comp) 部分排序
将元素重新排列,使得 [first, middle) 包含排好序的, [first, last) 区间中的 middle - first 个最小元素
相等元素的相对顺序可能被破坏
剩余在 [middle, last) 区间内的元素的顺序不做任何保证
复杂度 O((last - first) * log(middle - first))
*/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {9, 8, 7, 6, 5, 4, 3, 2, 1};
partial_sort(v.begin(), v.begin() + 5, v.end());
for (int val : v) cout << val << ' ';
// Possible output: 1 2 3 4 5 9 8 7 6
return 0;
} | [
"sandychn@163.com"
] | sandychn@163.com |
a82dff72a113f59a9ce930a49b3a4a4059a17f94 | f42c638497a591c76ba5ad382372da2e129b8dfe | /Query/kdt3.pb.h | cb3e3ff0bf2118cab7ab5ab0208572b31f3d4de2 | [] | no_license | libingyao/mcatCS | 0015754f72fa6b8cf5dac13bbbf83653a0e88996 | f63d82097a15a0743178260f3c8116c3843d8dbb | refs/heads/master | 2020-03-21T14:42:06.025027 | 2018-12-10T10:56:21 | 2018-12-10T10:56:21 | 138,671,252 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 10,547 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: kdt3.proto
#ifndef PROTOBUF_kdt3_2eproto__INCLUDED
#define PROTOBUF_kdt3_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_kdt3_2eproto();
void protobuf_AssignDesc_kdt3_2eproto();
void protobuf_ShutdownFile_kdt3_2eproto();
class Node;
// ===================================================================
class Node : public ::google::protobuf::Message {
public:
Node();
virtual ~Node();
Node(const Node& from);
inline Node& operator=(const Node& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Node& default_instance();
void Swap(Node* other);
// implements Message ----------------------------------------------
Node* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Node& from);
void MergeFrom(const Node& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated int64 p_max = 1;
inline int p_max_size() const;
inline void clear_p_max();
static const int kPMaxFieldNumber = 1;
inline ::google::protobuf::int64 p_max(int index) const;
inline void set_p_max(int index, ::google::protobuf::int64 value);
inline void add_p_max(::google::protobuf::int64 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
p_max() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
mutable_p_max();
// repeated int64 son_max = 2;
inline int son_max_size() const;
inline void clear_son_max();
static const int kSonMaxFieldNumber = 2;
inline ::google::protobuf::int64 son_max(int index) const;
inline void set_son_max(int index, ::google::protobuf::int64 value);
inline void add_son_max(::google::protobuf::int64 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
son_max() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
mutable_son_max();
// repeated double x = 3;
inline int x_size() const;
inline void clear_x();
static const int kXFieldNumber = 3;
inline double x(int index) const;
inline void set_x(int index, double value);
inline void add_x(double value);
inline const ::google::protobuf::RepeatedField< double >&
x() const;
inline ::google::protobuf::RepeatedField< double >*
mutable_x();
// repeated double y = 4;
inline int y_size() const;
inline void clear_y();
static const int kYFieldNumber = 4;
inline double y(int index) const;
inline void set_y(int index, double value);
inline void add_y(double value);
inline const ::google::protobuf::RepeatedField< double >&
y() const;
inline ::google::protobuf::RepeatedField< double >*
mutable_y();
// repeated int64 son = 5;
inline int son_size() const;
inline void clear_son();
static const int kSonFieldNumber = 5;
inline ::google::protobuf::int64 son(int index) const;
inline void set_son(int index, ::google::protobuf::int64 value);
inline void add_son(::google::protobuf::int64 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
son() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
mutable_son();
// @@protoc_insertion_point(class_scope:Node)
private:
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int64 > p_max_;
::google::protobuf::RepeatedField< ::google::protobuf::int64 > son_max_;
::google::protobuf::RepeatedField< double > x_;
::google::protobuf::RepeatedField< double > y_;
::google::protobuf::RepeatedField< ::google::protobuf::int64 > son_;
friend void protobuf_AddDesc_kdt3_2eproto();
friend void protobuf_AssignDesc_kdt3_2eproto();
friend void protobuf_ShutdownFile_kdt3_2eproto();
void InitAsDefaultInstance();
static Node* default_instance_;
};
// ===================================================================
// ===================================================================
// Node
// repeated int64 p_max = 1;
inline int Node::p_max_size() const {
return p_max_.size();
}
inline void Node::clear_p_max() {
p_max_.Clear();
}
inline ::google::protobuf::int64 Node::p_max(int index) const {
// @@protoc_insertion_point(field_get:Node.p_max)
return p_max_.Get(index);
}
inline void Node::set_p_max(int index, ::google::protobuf::int64 value) {
p_max_.Set(index, value);
// @@protoc_insertion_point(field_set:Node.p_max)
}
inline void Node::add_p_max(::google::protobuf::int64 value) {
p_max_.Add(value);
// @@protoc_insertion_point(field_add:Node.p_max)
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
Node::p_max() const {
// @@protoc_insertion_point(field_list:Node.p_max)
return p_max_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
Node::mutable_p_max() {
// @@protoc_insertion_point(field_mutable_list:Node.p_max)
return &p_max_;
}
// repeated int64 son_max = 2;
inline int Node::son_max_size() const {
return son_max_.size();
}
inline void Node::clear_son_max() {
son_max_.Clear();
}
inline ::google::protobuf::int64 Node::son_max(int index) const {
// @@protoc_insertion_point(field_get:Node.son_max)
return son_max_.Get(index);
}
inline void Node::set_son_max(int index, ::google::protobuf::int64 value) {
son_max_.Set(index, value);
// @@protoc_insertion_point(field_set:Node.son_max)
}
inline void Node::add_son_max(::google::protobuf::int64 value) {
son_max_.Add(value);
// @@protoc_insertion_point(field_add:Node.son_max)
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
Node::son_max() const {
// @@protoc_insertion_point(field_list:Node.son_max)
return son_max_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
Node::mutable_son_max() {
// @@protoc_insertion_point(field_mutable_list:Node.son_max)
return &son_max_;
}
// repeated double x = 3;
inline int Node::x_size() const {
return x_.size();
}
inline void Node::clear_x() {
x_.Clear();
}
inline double Node::x(int index) const {
// @@protoc_insertion_point(field_get:Node.x)
return x_.Get(index);
}
inline void Node::set_x(int index, double value) {
x_.Set(index, value);
// @@protoc_insertion_point(field_set:Node.x)
}
inline void Node::add_x(double value) {
x_.Add(value);
// @@protoc_insertion_point(field_add:Node.x)
}
inline const ::google::protobuf::RepeatedField< double >&
Node::x() const {
// @@protoc_insertion_point(field_list:Node.x)
return x_;
}
inline ::google::protobuf::RepeatedField< double >*
Node::mutable_x() {
// @@protoc_insertion_point(field_mutable_list:Node.x)
return &x_;
}
// repeated double y = 4;
inline int Node::y_size() const {
return y_.size();
}
inline void Node::clear_y() {
y_.Clear();
}
inline double Node::y(int index) const {
// @@protoc_insertion_point(field_get:Node.y)
return y_.Get(index);
}
inline void Node::set_y(int index, double value) {
y_.Set(index, value);
// @@protoc_insertion_point(field_set:Node.y)
}
inline void Node::add_y(double value) {
y_.Add(value);
// @@protoc_insertion_point(field_add:Node.y)
}
inline const ::google::protobuf::RepeatedField< double >&
Node::y() const {
// @@protoc_insertion_point(field_list:Node.y)
return y_;
}
inline ::google::protobuf::RepeatedField< double >*
Node::mutable_y() {
// @@protoc_insertion_point(field_mutable_list:Node.y)
return &y_;
}
// repeated int64 son = 5;
inline int Node::son_size() const {
return son_.size();
}
inline void Node::clear_son() {
son_.Clear();
}
inline ::google::protobuf::int64 Node::son(int index) const {
// @@protoc_insertion_point(field_get:Node.son)
return son_.Get(index);
}
inline void Node::set_son(int index, ::google::protobuf::int64 value) {
son_.Set(index, value);
// @@protoc_insertion_point(field_set:Node.son)
}
inline void Node::add_son(::google::protobuf::int64 value) {
son_.Add(value);
// @@protoc_insertion_point(field_add:Node.son)
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
Node::son() const {
// @@protoc_insertion_point(field_list:Node.son)
return son_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
Node::mutable_son() {
// @@protoc_insertion_point(field_mutable_list:Node.son)
return &son_;
}
// @@protoc_insertion_point(namespace_scope)
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_kdt3_2eproto__INCLUDED
| [
"40571596+libingyao@users.noreply.github.com"
] | 40571596+libingyao@users.noreply.github.com |
4ec5f070e67f2bc70967b37401f123c61f1d62f3 | 8a6aa8798436d8b256099fa163249fcab9f86d89 | /C++/Operations on Relations(DS)/Operations on Relations(DS)/BinaryRelation.cpp | c34b6012c58cf6ecd37cf9af520648e7bde603d7 | [] | no_license | 12330072/C-learning | 39f2399c4c5413ef80bd62b90a4688555606dc96 | 94b92bcd5bdfe99627b46eb4f6f46d379b0b67fe | refs/heads/master | 2021-01-14T13:21:22.999905 | 2016-05-12T23:58:24 | 2016-05-12T23:58:24 | 58,739,535 | 0 | 1 | null | 2016-05-13T12:43:31 | 2016-05-13T12:43:31 | null | UTF-8 | C++ | false | false | 4,791 | cpp | #include "BinaryRelation.hpp"
BinaryRelation::BinaryRelation(BooleanMatrix const &m, Set const &s)
: Relation(m), set(s) {}
int BinaryRelation::getSetElePos(int n) {
for (int i = 1; i <= set.getSize(); i++) {
if (set.get(i) == n) {
return i;
}
}
return -1;
}
int BinaryRelation::outDegree(int n) {
if (set.isInSet(n)) {
int sum = 0;
int pos = getSetElePos(n);
for (int i = 1; i <= matrix.getColums(); i++) {
if (matrix.getElement(pos, i)) {
sum++;
}
}
return sum;
}
return -1;
}
int BinaryRelation::inDegree(int n) {
if (set.isInSet(n)) {
int sum = 0;
int pos = getSetElePos(n);
for (int i = 1; i <= matrix.getRow(); i++) {
if (matrix.getElement(i, pos)) {
sum++;
}
}
return sum;
}
return -1;
}
BinaryRelation BinaryRelation::pathOfLength(int n) {
BooleanMatrix temp1(matrix);
if (n == -1) {
while (!(temp1 == temp1.BooleanProduct(matrix))) {
temp1 = temp1.BooleanProduct(matrix);
}
} else {
for (int i = 1; i < n; i++) {
temp1 = temp1.BooleanProduct(matrix);
}
}
BinaryRelation temp2(temp1, set);
return temp2;
}
bool BinaryRelation::isReflexive() const {
for (int i = 1; i <= matrix.getRow(); i++) {
if (matrix.getElement(i, i) != true) {
return false;
}
}
return true;
}
bool BinaryRelation::isIrreflexive() const {
for (int i = 1; i <= matrix.getRow(); i++) {
if (matrix.getElement(i, i) == true) {
return false;
}
}
return true;
}
bool BinaryRelation::isSymmetric() const {
for (int i = 1; i <= matrix.getRow(); i++) {
for (int j = 1; j <= matrix.getColums(); j++) {
if (matrix.getElement(i, j) == true &&
matrix.getElement(j, i) == false) {
return false;
}
}
}
return true;
}
bool BinaryRelation::isAsymmetric() const {
for (int i = 1; i <= matrix.getRow(); i++) {
for (int j = 1; j <= matrix.getColums(); j++) {
if (matrix.getElement(i, j) == true &&
matrix.getElement(j, i) == true) {
return false;
}
}
}
return true;
}
bool BinaryRelation::isAntisymmetric() const {
for (int i = 1; i <= matrix.getRow(); i++) {
for (int j = 1; j <= matrix.getColums(); j++) {
if (i != j &&
matrix.getElement(i, j) == true &&
matrix.getElement(j, i) == true) {
return false;
}
}
}
return true;
}
bool BinaryRelation::isTransitive() const {
for (int i = 1; i <= matrix.getRow(); i++) {
for (int j = 1; j <= matrix.getColums(); j++) {
for (int k = 1; k <= matrix.getRow(); k++) {
if (matrix.getElement(i, k) == true &&
matrix.getElement(k, j) == true &&
matrix.getElement(i, j) == false) {
return false;
}
}
}
}
return true;
}
bool BinaryRelation::isEquivalence() const {
return (isReflexive() && isSymmetric() && isTransitive());
}
BinaryRelation BinaryRelation::composition(const BinaryRelation &oth) {
BooleanMatrix temp = matrix.BooleanProduct(oth.getBooleanMatrix());
BinaryRelation out(temp, set);
return out;
}
BinaryRelation BinaryRelation::reflexiveClosure() const {
BooleanMatrix temp(matrix);
for (int i = 1; i <= matrix.getRow(); i++) {
temp.replace(true, i, i);
}
BinaryRelation out(temp, set);
return out;
}
BinaryRelation BinaryRelation::symmetricClosure() const {
BooleanMatrix temp(matrix.transpose());
for (int i = 1; i <= matrix.getRow(); i++) {
for (int j = 1; j <= matrix.getColums(); j++) {
if (matrix.getElement(i, j) == true) {
temp.replace(true, i, j);
}
}
}
BinaryRelation out(temp, set);
return out;
}
BinaryRelation BinaryRelation::transitiveClosure() const {
BooleanMatrix temp(matrix);
for (int k = 1; k <= matrix.getRow() ; k++) {
for (int i = 1; i <= matrix.getRow(); i++) {
for (int j = 1; j <= matrix.getRow(); j++) {
if (temp.getElement(i, k) && temp.getElement(k, j)) {
temp.replace(true, i, j);
}
}
}
}
BinaryRelation out(temp, set);
return out;
}
| [
"“mgsweet@126.com”"
] | “mgsweet@126.com” |
6a8955331eae5c785f1b9b3185bfa76a06e61c8d | 732d2ec881faf7029c4e87a42948119572eb73e0 | /StudentDocument/main.cpp | a2094729a2fbba638339c4e8c0a19c63b4bbab0c | [] | no_license | HeranGa0/StudentDocument | 55e12bfde8ae4dd6c973871a7d2b43834acf5827 | 5eec305877260dbe309d14b36f1c595351a5286d | refs/heads/master | 2020-05-29T09:12:58.794375 | 2016-10-08T03:46:01 | 2016-10-08T03:46:01 | 70,301,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 184 | cpp | #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GaoProduct w;
int *b;
w.show();
return a.exec();
}
| [
"herangao6@gmail.com"
] | herangao6@gmail.com |
c5b935b8cd6e8f84340d0b07593de063bfd790d3 | 19185e42434b80603eb74bef4024fede5d9faf50 | /Analysis/Zhihong_Scripts/boiling/SRC/backup/XGT2_old.h | d55707dbc60d173846edb05cf416598c0fd8e98e | [] | no_license | JeffersonLab/tritium | 1f444f2931d26384599995db43b8d039a9da78c7 | a7ec4e95a22d4f255557a686784684494056521f | refs/heads/master | 2020-12-24T06:52:01.556544 | 2018-02-22T21:57:44 | 2018-02-22T21:57:44 | 73,393,148 | 1 | 2 | null | 2017-01-24T15:41:38 | 2016-11-10T15:09:52 | C | UTF-8 | C++ | false | false | 6,459 | h | #define NOCASE 1
/*C/C++ Includes{{{*/
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
/*}}}*/
/*ROOT Includes{{{*/
#include <TSystem.h>
#include <TString.h>
#include <Riostream.h>
#include "TObjString.h"
#include <TDatime.h>
#include <TPRegexp.h>
#include <TObjArray.h>
#include <TChain.h>
#include <TMath.h>
#include <TH1.h>
#include <TFile.h>
#include <TROOT.h>
#include <TF1.h>
#include <TGraph.h>
#include <TCanvas.h>
#include <TDatime.h>
#include <TError.h>
#include <TVirtualFitter.h>
#include <TSQLServer.h>
#include <TSQLResult.h>
#include <TSQLRow.h>
#include <TCut.h>
#include <TMultiGraph.h>
#include <TCutG.h>
/*}}}*/
///*ANALYZER Includes{{{*/
////#include <THaAnalysisObject.h>
//#include <THaApparatus.h>
//#include <THaHRS.h>
//#include <THaShower.h>
//#include <THaCherenkov.h>
//#include <THaScintillator.h>
//#include <THaUnRasteredBeam.h>
//#include <THaRasteredBeam.h>
//#include <THaDecData.h>
//#include <THaScalerGroup.h>
//#include <THaReactionPoint.h>
//#include <THaElectronKine.h>
//#include <THaGoldenTrack.h>
//#include <THaExtTarCor.h>
//#include <THaNormAna.h>
//#include <THaAnalyzer.h>
//#include <THaRun.h>
//#include <THaEvent.h>
///*}}}*/
using namespace std;
/*Customization{{{*/
const TString XGT2_DIR="/work/halla/e08014/disk1/yez/HRS_Cali/XGT2"; //this is for inputfiles,outfiles,logfiles
const TString ROOTFILES_DIR="/work/halla/e08014/disk1/Rootfiles";//this is for rootfiles
const Double_t GCPMT_For_1Photon=100;
/*}}}*/
Bool_t IsBackground=kFALSE;
/*Constants and enum{{{*/
const Double_t Pi=TMath::Pi();
const Double_t Na=TMath::Na();//Avogadro's Number
const Double_t Qe=TMath::Qe();
const Double_t DegToRad=TMath::DegToRad();
const Double_t RadToDeg=TMath::RadToDeg();
const Double_t PROTON_MASS=0.938272; //GeV Mass of proton
const Double_t Alpha=1/137.036;
const Int_t DQ_Name_Length=60;//for DataQuality Output Name Length
//Form("%-*s%-f",DQ_Name_Length,"Name",Value);
const Double_t HBARC=197.33; //hbar*c=197.33 MeV^2 fm^2
const Double_t FM2TONBARN=1e-7; //1 fm^2=1e7 nbarn
const Double_t MEV2SR_TO_NBARNSR=HBARC*HBARC*FM2TONBARN; //default cross section 1/(MeV^2*sr) to nbarn/sr
///////////////////////////////////
/// PreScale Factors
///////////////////////////////////
Int_t gGet_PS(const Int_t& RunNo,const TString& aArm, Int_t *aPar )
{
TString filename_ps = ROOTFILES_DIR+Form("e08014_%s_%d.root",aArm,RunNo);
TFile *file_ps = new TFile(filename_ps);
TArrayI prescales = Run_Data->GetParameters()->GetPrescales();
for(int i=0;i<8;i++){
aPar[i] = prescales[i];
}
filename_ps->Close(); return &aPar;
}
///////////////////////////////////
/// Energy Loss
///////////////////////////////////
/*inline Double_t gCal_Eloss(const Double_t& aE,const Int_t& aZ,const Double_t& aA,const Double_t& aM,const Double_t& aI,const Double_t& aDensity,const Double_t& aThickness){{{*/
inline Double_t gCal_Eloss(const Double_t& aE,const Int_t& aZ,const Double_t& aA,const Double_t& aM,const Double_t& aI,const Double_t& aDensity,const Double_t& aThickness)
{
//aE,aM,aI GeV, aA kg/mol, aDensity g/cm^3
Double_t lE=aE*1000; //GeV to MeV
Double_t lM=aM*1000; //GeV to MeV
Double_t lI=aI*1000; //GeV to MeV
Double_t lA=aA*1000; //kg/mol to g/mol
Double_t lThickness=aThickness/10; //kg/m^2 to g/cm^2
Double_t K=0.307075; //MeV cm^2/g
Double_t z=1;//electron
Double_t me=0.511; //MeV
Double_t beta,gamma,omega_p,Tmax,delta;
beta=1-me*me/(lE*lE);
gamma=1/sqrt(1-beta*beta);
omega_p=28.816*sqrt(aDensity*aZ/lA/1000)*1e-6; //MeV
Tmax=2*me*beta*beta*gamma*gamma/(1+2*gamma*me/lM+me*me/(lM*lM));
delta=log(omega_p/lI)+log(beta*gamma)-0.5;
return (K*z*z*aZ/lA/(beta*beta)*( 0.5*log(2*me*beta*beta*gamma*gamma*Tmax/lI/lI)-beta*beta-delta ))*lThickness*1e-3;//GeV
}
/*}}}*/
/*class XGT2_VAR{{{*/
class XGT2_VAR
{
public:
XGT2_VAR()
{
SetValue();
};
XGT2_VAR(XGT2_VAR const&){};
XGT2_VAR& operator=(XGT2_VAR const&){};
XGT2_VAR& operator*=(const Double_t& aNum)
{
this->Value *= aNum;
this->Stat_Err *= aNum;
this->Sys_Err *= aNum;
return *this;
};
Double_t Value;//value of this variable
Double_t Stat_Err;//statistical error of this variable
Double_t Sys_Err;//systematic error of this variable
void SetValue
(
const Double_t& aValue=0,
const Double_t& aStat_Err=0,
const Double_t& aSys_Err=0
)
{
Value=aValue;
Stat_Err=aStat_Err;
Sys_Err=aSys_Err;
};
void Print()
{
Printf("%-*s%e",20,"Value:",Value);
Printf("%-*s%e",20,"Stat_Err:",Stat_Err);
Printf("%-*s%e",20,"Sys_Err:",Sys_Err);
}
};
/*}}}*/
//////////////////////////
// Logger
/////////////////////////
/*class XGT2_Logger{{{*/
class XGT2_Logger
{
public:
/*static XGT2_Logger* Instance(){{{*/
static XGT2_Logger* Instance()
{
// Only allow one instance of class to be generated.
if (!m_pInstance)
{
Printf("Creating XGT2_Logger System.");
m_pInstance = new XGT2_Logger;
}
return m_pInstance;
}
/*}}}*/
/*static XGT2_Logger* Destroy(){{{*/
static XGT2_Logger* Destroy()
{
// Only allow one instance of class to be generated.
if ( m_pInstance)
delete m_pInstance;
Printf("Deleting XGT2_Logger System.");
m_pInstance=NULL;
}
/*}}}*/
/*const TString GetLogFileName(){{{*/
const TString GetLogFileName()
{
return LogFile_Name;
}
/*}}}*/
void SetLogFileName(const char* aLogFile_Name)
{
LogFile_Name=aLogFile_Name;
}
/*void WriteToLogFile(const char* aSrcFile, const char* aSrcLine,const char* aLog){{{*/
void WriteToLogFile(const char* aSrcFile, int aSrcLine,const char* aLog)
{
ofstream outfile(LogFile_Name.Data(),ios::app);
if ( !outfile.good() )
{
Error(__FILE__,Form("At line %d. %s cannot be appended.",__LINE__,LogFile_Name.Data()));
return;
}
TDatime stamp;
outfile<<Form("%s File-\"%s\" Line-%d: %s",stamp.AsString(),aSrcFile,aSrcLine,aLog)<<endl;
outfile.close();
}
/*}}}*/
private:
XGT2_Logger(){}; // Private so that it can not be called
XGT2_Logger(XGT2_Logger const&){}; // copy constructor is private
XGT2_Logger& operator=(XGT2_Logger const&){}; // assignment operator is private
static XGT2_Logger* m_pInstance;
TString LogFile_Name;
}
;/*}}}*/
XGT2_Logger* XGT2_Logger::m_pInstance = NULL;
| [
"yezhihong@gmail.com"
] | yezhihong@gmail.com |
e8576364606b44c80ecb2d2c99f6372d79ff3bdc | ad709325394da001d0dd77cb96c6a0624b2ea5a6 | /src/glm/core/type_int.hpp | c9aced7732ed6702e4e4cf2e824b4c3a045e7473 | [] | no_license | tiansijie/CUDA-RayTracer | e37cca0f48b36af53edc171f7cdbf412bb9a9872 | b5c98d81fc51d7d325c8b2a93c29d5c433e769ba | refs/heads/master | 2020-12-25T08:49:53.876341 | 2013-10-13T23:05:17 | 2013-10-13T23:05:17 | 12,743,053 | 18 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,548 | hpp | ///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref core
/// @file glm/core/type_int.hpp
/// @date 2008-08-22 / 2011-06-15
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////
#ifndef glm_core_type_int
#define glm_core_type_int
#include "setup.hpp"
#include "_detail.hpp"
namespace glm{
namespace detail
{
typedef signed short lowp_int_t;
typedef signed int mediump_int_t;
typedef sint64 highp_int_t;
typedef unsigned short lowp_uint_t;
typedef unsigned int mediump_uint_t;
typedef uint64 highp_uint_t;
GLM_DETAIL_IS_INT(signed char);
GLM_DETAIL_IS_INT(signed short);
GLM_DETAIL_IS_INT(signed int);
GLM_DETAIL_IS_INT(signed long);
GLM_DETAIL_IS_INT(highp_int_t);
GLM_DETAIL_IS_UINT(unsigned char);
GLM_DETAIL_IS_UINT(unsigned short);
GLM_DETAIL_IS_UINT(unsigned int);
GLM_DETAIL_IS_UINT(unsigned long);
GLM_DETAIL_IS_UINT(highp_uint_t);
}//namespace detail
/// @addtogroup core_precision
/// @{
/// Low precision signed integer.
/// There is no guarantee on the actual precision.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef detail::lowp_int_t lowp_int;
/// Medium precision signed integer.
/// There is no guarantee on the actual precision.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef detail::mediump_int_t mediump_int;
/// High precision signed integer.
/// There is no guarantee on the actual precision.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef detail::highp_int_t highp_int;
/// Low precision unsigned integer.
/// There is no guarantee on the actual precision.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef detail::lowp_uint_t lowp_uint;
/// Medium precision unsigned integer.
/// There is no guarantee on the actual precision.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef detail::mediump_uint_t mediump_uint;
/// High precision unsigned integer.
/// There is no guarantee on the actual precision.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef detail::highp_uint_t highp_uint;
#if(!defined(GLM_PRECISION_HIGHP_INT) && !defined(GLM_PRECISION_MEDIUMP_INT) && !defined(GLM_PRECISION_LOWP_INT))
typedef mediump_int int_t;
#elif(defined(GLM_PRECISION_HIGHP_INT) && !defined(GLM_PRECISION_MEDIUMP_INT) && !defined(GLM_PRECISION_LOWP_INT))
typedef highp_int int_t;
#elif(!defined(GLM_PRECISION_HIGHP_INT) && defined(GLM_PRECISION_MEDIUMP_INT) && !defined(GLM_PRECISION_LOWP_INT))
typedef mediump_int int_t;
#elif(!defined(GLM_PRECISION_HIGHP_INT) && !defined(GLM_PRECISION_MEDIUMP_INT) && defined(GLM_PRECISION_LOWP_INT))
typedef lowp_int int_t;
#else
# error "GLM error: multiple default precision requested for signed interger types"
#endif
#if(!defined(GLM_PRECISION_HIGHP_UINT) && !defined(GLM_PRECISION_MEDIUMP_UINT) && !defined(GLM_PRECISION_LOWP_UINT))
typedef mediump_uint uint_t;
#elif(defined(GLM_PRECISION_HIGHP_UINT) && !defined(GLM_PRECISION_MEDIUMP_UINT) && !defined(GLM_PRECISION_LOWP_UINT))
typedef highp_uint uint_t;
#elif(!defined(GLM_PRECISION_HIGHP_UINT) && defined(GLM_PRECISION_MEDIUMP_UINT) && !defined(GLM_PRECISION_LOWP_UINT))
typedef mediump_uint uint_t;
#elif(!defined(GLM_PRECISION_HIGHP_UINT) && !defined(GLM_PRECISION_MEDIUMP_UINT) && defined(GLM_PRECISION_LOWP_UINT))
typedef lowp_uint uint_t;
#else
# error "GLM error: multiple default precision requested for unsigned interger types"
#endif
/// Unsigned integer type.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.3 Integers</a>
typedef uint_t uint;
/// @}
}//namespace glm
#endif//glm_core_type_int
| [
"liamboone@gmail.com"
] | liamboone@gmail.com |
114c87f93293a8e9c9e63101650e613eafbaaa38 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /media/capture/mojom/video_capture_types_mojom_traits.h | db7de92a9a050cc1aa9c45b994dd2af33c9d3935 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 7,683 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_CAPTURE_MOJOM_VIDEO_CAPTURE_TYPES_MOJOM_TRAITS_H_
#define MEDIA_CAPTURE_MOJOM_VIDEO_CAPTURE_TYPES_MOJOM_TRAITS_H_
#include "media/base/video_facing.h"
#include "media/capture/mojom/video_capture_types.mojom-shared.h"
#include "media/capture/video/video_capture_device_descriptor.h"
#include "media/capture/video/video_capture_device_info.h"
#include "media/capture/video_capture_types.h"
namespace mojo {
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::ResolutionChangePolicy,
media::ResolutionChangePolicy> {
static media::mojom::ResolutionChangePolicy ToMojom(
media::ResolutionChangePolicy policy);
static bool FromMojom(media::mojom::ResolutionChangePolicy input,
media::ResolutionChangePolicy* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::PowerLineFrequency, media::PowerLineFrequency> {
static media::mojom::PowerLineFrequency ToMojom(
media::PowerLineFrequency frequency);
static bool FromMojom(media::mojom::PowerLineFrequency input,
media::PowerLineFrequency* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoCapturePixelFormat, media::VideoPixelFormat> {
static media::mojom::VideoCapturePixelFormat ToMojom(
media::VideoPixelFormat input);
static bool FromMojom(media::mojom::VideoCapturePixelFormat input,
media::VideoPixelFormat* output);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoCaptureBufferType,
media::VideoCaptureBufferType> {
static media::mojom::VideoCaptureBufferType ToMojom(
media::VideoCaptureBufferType buffer_type);
static bool FromMojom(media::mojom::VideoCaptureBufferType input,
media::VideoCaptureBufferType* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoCaptureError, media::VideoCaptureError> {
static media::mojom::VideoCaptureError ToMojom(
media::VideoCaptureError buffer_type);
static bool FromMojom(media::mojom::VideoCaptureError input,
media::VideoCaptureError* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoCaptureFrameDropReason,
media::VideoCaptureFrameDropReason> {
static media::mojom::VideoCaptureFrameDropReason ToMojom(
media::VideoCaptureFrameDropReason buffer_type);
static bool FromMojom(media::mojom::VideoCaptureFrameDropReason input,
media::VideoCaptureFrameDropReason* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoFacingMode, media::VideoFacingMode> {
static media::mojom::VideoFacingMode ToMojom(media::VideoFacingMode input);
static bool FromMojom(media::mojom::VideoFacingMode input,
media::VideoFacingMode* output);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoCaptureApi, media::VideoCaptureApi> {
static media::mojom::VideoCaptureApi ToMojom(media::VideoCaptureApi input);
static bool FromMojom(media::mojom::VideoCaptureApi input,
media::VideoCaptureApi* output);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
EnumTraits<media::mojom::VideoCaptureTransportType,
media::VideoCaptureTransportType> {
static media::mojom::VideoCaptureTransportType ToMojom(
media::VideoCaptureTransportType input);
static bool FromMojom(media::mojom::VideoCaptureTransportType input,
media::VideoCaptureTransportType* output);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
StructTraits<media::mojom::VideoCaptureFormatDataView,
media::VideoCaptureFormat> {
static const gfx::Size& frame_size(const media::VideoCaptureFormat& format) {
return format.frame_size;
}
static float frame_rate(const media::VideoCaptureFormat& format) {
return format.frame_rate;
}
static media::VideoPixelFormat pixel_format(
const media::VideoCaptureFormat& format) {
return format.pixel_format;
}
static bool Read(media::mojom::VideoCaptureFormatDataView data,
media::VideoCaptureFormat* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
StructTraits<media::mojom::VideoCaptureParamsDataView,
media::VideoCaptureParams> {
static media::VideoCaptureFormat requested_format(
const media::VideoCaptureParams& params) {
return params.requested_format;
}
static media::VideoCaptureBufferType buffer_type(
const media::VideoCaptureParams& params) {
return params.buffer_type;
}
static media::ResolutionChangePolicy resolution_change_policy(
const media::VideoCaptureParams& params) {
return params.resolution_change_policy;
}
static media::PowerLineFrequency power_line_frequency(
const media::VideoCaptureParams& params) {
return params.power_line_frequency;
}
static bool enable_face_detection(
const media::VideoCaptureParams& params) {
return params.enable_face_detection;
}
static bool Read(media::mojom::VideoCaptureParamsDataView data,
media::VideoCaptureParams* out);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
StructTraits<media::mojom::VideoCaptureDeviceDescriptorDataView,
media::VideoCaptureDeviceDescriptor> {
static const std::string& display_name(
const media::VideoCaptureDeviceDescriptor& input) {
return input.display_name();
}
static const std::string& device_id(
const media::VideoCaptureDeviceDescriptor& input) {
return input.device_id;
}
static const std::string& model_id(
const media::VideoCaptureDeviceDescriptor& input) {
return input.model_id;
}
static media::VideoFacingMode facing_mode(
const media::VideoCaptureDeviceDescriptor& input) {
return input.facing;
}
static media::VideoCaptureApi capture_api(
const media::VideoCaptureDeviceDescriptor& input) {
return input.capture_api;
}
static bool pan_tilt_zoom_supported(
const media::VideoCaptureDeviceDescriptor& input) {
return input.pan_tilt_zoom_supported();
}
static media::VideoCaptureTransportType transport_type(
const media::VideoCaptureDeviceDescriptor& input) {
return input.transport_type;
}
static bool Read(media::mojom::VideoCaptureDeviceDescriptorDataView data,
media::VideoCaptureDeviceDescriptor* output);
};
template <>
struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS)
StructTraits<media::mojom::VideoCaptureDeviceInfoDataView,
media::VideoCaptureDeviceInfo> {
static const media::VideoCaptureDeviceDescriptor& descriptor(
const media::VideoCaptureDeviceInfo& input) {
return input.descriptor;
}
static const std::vector<media::VideoCaptureFormat>& supported_formats(
const media::VideoCaptureDeviceInfo& input) {
return input.supported_formats;
}
static bool Read(media::mojom::VideoCaptureDeviceInfoDataView data,
media::VideoCaptureDeviceInfo* output);
};
} // namespace mojo
#endif // MEDIA_CAPTURE_MOJOM_VIDEO_CAPTURE_TYPES_MOJOM_TRAITS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e5f9754fcecaec244de32f582afa64e017a136a5 | f16ca93a097425dd80012deb14fa5840b87eb650 | /ContentTools/Common/SceneExport/Utils/hctSceneExportUtils.h | 23fcb7b207779c36f526d5aac8e319985c18469a | [] | no_license | Veryzon/havok-2013 | 868a4873f5254709b77a2ed8393355b89d2398af | 45812e33f4bd92c428866e5e7c1b4d71a4762fb5 | refs/heads/master | 2021-06-25T23:48:11.919356 | 2021-04-17T02:12:06 | 2021-04-17T02:12:06 | 226,624,337 | 4 | 1 | null | 2019-12-08T06:21:56 | 2019-12-08T06:21:56 | null | UTF-8 | C++ | false | false | 4,345 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_SCENE_EXPORT_UTILS_H
#define HK_SCENE_EXPORT_UTILS_H
class hctFilterClassRegistry;
#include <Common/Base/Reflection/hkClassMemberAccessor.h>
#include <Common/SceneData/Graph/hkxNode.h>
/// Minor utilities used during export.
namespace hkSceneExportUtils
{
/// Convert RGB and alpha float values to a single 32bit ARGB.
inline unsigned floatsToARGB( const float r, const float g, const float b, const float a = 1.0f )
{
return ((unsigned char)( a * 255.0f ) << 24 ) |
((unsigned char)( r * 255.0f ) << 16 ) |
((unsigned char)( g * 255.0f ) << 8 ) |
((unsigned char)( b * 255.0f ) );
}
/// Convert RGB and alpha float values to a single 32bit ARGB and set out-of-range colors to 80% grey full opaque
inline unsigned floatsToARGB_grey( const float r, const float g, const float b, const float a = 1.0f )
{
const float rr = (r >= 0.0f) ? ( (r <= 1.0f) ? r : 0.8f ) : 0.8f;
const float gg = (g >= 0.0f) ? ( (g <= 1.0f) ? g : 0.8f ) : 0.8f;
const float bb = (b >= 0.0f) ? ( (b <= 1.0f) ? b : 0.8f ) : 0.8f;
const float aa = (a >= 0.0f) ? ( (a <= 1.0f) ? a : 1.0f ) : 1.0f;
return ((unsigned char)( aa * 255.0f ) << 24 ) |
((unsigned char)( rr * 255.0f ) << 16 ) |
((unsigned char)( gg * 255.0f ) << 8 ) |
((unsigned char)( bb * 255.0f ) );
}
/// Convert RGB and alpha float values to a single 32bit ARGB and saturate out-of-range colors while making full opaque
inline unsigned floatsToARGB_saturate( const float r, const float g, const float b, const float a = 1.0f )
{
const float rr = (r >= 0.0f) ? ( (r <= 1.0f) ? r : 1.0f ) : 0.0f;
const float gg = (g >= 0.0f) ? ( (g <= 1.0f) ? g : 1.0f ) : 0.0f;
const float bb = (b >= 0.0f) ? ( (b <= 1.0f) ? b : 1.0f ) : 0.0f;
const float aa = (a >= 0.0f) ? ( (a <= 1.0f) ? a : 1.0f ) : 1.0f;
return ((unsigned char)( aa * 255.0f ) << 24 ) |
((unsigned char)( rr * 255.0f ) << 16 ) |
((unsigned char)( gg * 255.0f ) << 8 ) |
((unsigned char)( bb * 255.0f ) );
}
/// Replaces any "<" and ">" character with underscores so the name can be part of an XML file.
inline void getSerializableName( const char* nodeName, hkStringOld& newName )
{
newName = nodeName;
newName = newName.replace('<', '_'); // no xml tag parts
newName = newName.replace('>', '_');
}
/// As getSerializableName, but also replacing spaces with underscores.
inline void getReducedName( const char* nodeName, hkStringOld& newName )
{
getSerializableName(nodeName, newName);
newName = newName.replace(' ', '_'); // no spaces
}
inline void reportSceneData (const hkxScene* scene)
{
const int totalNodes = scene->m_rootNode ? (1 + scene->m_rootNode->getNumDescendants()) : 0;
HK_REPORT2 (0xabba1441, "Exported "<<totalNodes<<" nodes, "<<scene->m_selectionSets.getSize() <<" node selection sets, "
<<scene->m_materials.getSize() <<" materials, " <<scene->m_meshes.getSize() <<" meshes, "
<<scene->m_lights.getSize() <<" lights, "<< scene->m_cameras.getSize() <<" cameras, "<<scene->m_skinBindings.getSize() <<" skin bindings.");
}
}
#endif //HK_SCENE_EXPORT_UTILS_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"veryzon@outlook.com.br"
] | veryzon@outlook.com.br |
2bf159985bac796d23107bfe2b5597f55e734552 | 9bffa3dbbb768c6d82290efeeae9ac95d5fd4aa9 | /src/test_canvas.cpp | 96b5c04544cafff8e1b20970dc75c09778de10e4 | [] | no_license | chenchengwork/tidy-webAssembly | 0adf8ef2751487fa470609c1aab3149e45b0fd77 | 91ffb05e4a1a815c32118ac61b33d87a79da4b45 | refs/heads/master | 2020-08-10T17:28:30.795209 | 2019-10-17T01:32:50 | 2019-10-17T01:32:50 | 214,385,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,292 | cpp | //
// Created by chencheng on 19-10-16.
//
#include "macro.h"
#include <malloc.h>
#include <stdint.h>
uint8_t *img_buf = NULL;
int img_width = 0, img_height = 0;
EM_PORT_API(uint8_t*) get_img_buf(int w, int h) {
if (img_buf == NULL || w != img_width || h != img_height) {
if (img_buf) {
free(img_buf);
}
img_buf = (uint8_t*)malloc(w * h * 4);
img_width = w;
img_height = h;
}
return img_buf;
}
EM_PORT_API(void) draw_circle(int cx, int cy, int radii) {
int sq = radii * radii;
for (int y = 0; y < img_height; y++) {
for (int x = 0; x < img_width; x++) {
int d = (y - cy) * (y - cy) + (x - cx) * (x - cx);
if (d < sq) {
img_buf[(y * img_width + x) * 4] = 255; //r
img_buf[(y * img_width + x) * 4 + 1] = 0; //g
img_buf[(y * img_width + x) * 4 + 2] = 0; //b
img_buf[(y * img_width + x) * 4 + 3] = 255; //a
}
else {
img_buf[(y * img_width + x) * 4] = 0; //r
img_buf[(y * img_width + x) * 4 + 1] = 255; //g
img_buf[(y * img_width + x) * 4 + 2] = 255; //b
img_buf[(y * img_width + x) * 4 + 3] = 255; //a
}
}
}
} | [
"dainel_txy@163.com"
] | dainel_txy@163.com |
8d42a59db61a2147fbe849f7a59e28cec4a190ca | 7b75745b529f5fdaab87defe96310199428b4f36 | /qt-myqq/senderform.h | cd8a1ffd96db7ec6672610e115dc84bcac175b8e | [] | no_license | NonlinearTime/NetLab_1 | a6a97d78d02014719744b7acf02787b86c30da3d | 7026c17f5fbdad30c7078596cae102f094f3e432 | refs/heads/master | 2021-07-24T15:05:45.149563 | 2017-11-05T15:27:07 | 2017-11-05T15:27:07 | 109,590,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | h | #ifndef SENDERFORM_H
#define SENDERFORM_H
#include <QWidget>
#include "sendedfile.h"
#include <QTimer>
#include <QMessageBox>
namespace Ui {
class SenderForm;
}
class SenderForm : public QWidget
{
Q_OBJECT
public:
explicit SenderForm(QWidget *parent = 0);
~SenderForm();
public slots:
void setFileMaxSize();
void updateProgressBar();
private slots:
void onButtonCloseClicked();
void sendFinished();
void on_cancelButton_clicked();
private:
Ui::SenderForm *ui;
double fileSended;
double filePerSecond;
signals:
void cancelFile();
void finished();
};
#endif // SENDERFORM_H
| [
"hainesluo@gmail.com"
] | hainesluo@gmail.com |
9ecd15f3cff5d48bac6f4cb46f980b6892ad71f3 | 2530496d99f7f3829f876ee8a55c4f2ff44501d9 | /main.cpp | 2728de3cecd4928b67efb469f27034383c20d837 | [] | no_license | AlexanderMoran1995/Gunship | a9280e8ef98dcbb913545e590e027f43dc117a8b | bedae80087fe4ff98166330e6e4a2f5be88d4257 | refs/heads/master | 2020-03-19T17:55:07.399355 | 2018-10-05T19:19:36 | 2018-10-05T19:19:36 | 136,784,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | #include"Gunship.h"
using namespace std;
int main()
{
srand((int)time(0));///for generation of random numbers
GunShip gunship;///class instance
///Function calls
gunship.NumOfThreats(0);
gunship.ThreatLevel(0);
gunship.print(0,0);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
f4997c9ad2f63e08dc81b288c479a6e897819f5a | 00dabc96113f0ca620c5e7896c73b6394b54aabb | /src/lang_models.cpp | db5dd4867726b521ca5e05475305c4df646449d5 | [] | no_license | tykangler/searcher | cca42c66fe43abfee4ee081706e0cea29d767456 | 5681386cfd4bd1873697c6579a483b990e038d51 | refs/heads/master | 2021-02-08T00:06:19.941677 | 2020-03-01T04:58:13 | 2020-03-01T04:58:13 | 244,089,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | #include "search/lang_models.hpp"
namespace enigma {
namespace search {
double basic_model::operator()(const std::string &text) const {
return 1;
}
} // search
} // enigma | [
"tykang8402@outlook.com"
] | tykang8402@outlook.com |
08669bc3a4269f7fd2fa605a80721dc0979a1503 | 3729961e9a789ed6fc1e128b77e34e43aaa9dbdc | /out/euler36.cc | 734fc8929b8d11256a78d9c854b173d00be2b391 | [] | no_license | Nicolas-Reyland/metalang | 60daca09e403c5390288dec4820a486fe08b913a | 431f0baa8ada74d6cfcdb09d465ab3a843c17088 | refs/heads/master | 2021-09-29T00:14:42.956123 | 2018-11-20T21:33:17 | 2018-11-21T20:15:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | cc | #include <iostream>
#include <vector>
bool palindrome2(std::vector<int> * pow2, int n) {
std::vector<bool> *t = new std::vector<bool>( 20 );
for (int i = 0; i < 20; i++)
t->at(i) = n / pow2->at(i) % 2 == 1;
int nnum = 0;
for (int j = 1; j < 20; j++)
if (t->at(j))
nnum = j;
for (int k = 0; k <= nnum / 2; k++)
if (t->at(k) != t->at(nnum - k))
return false;
return true;
}
int main() {
int p = 1;
std::vector<int> *pow2 = new std::vector<int>( 20 );
for (int i = 0; i < 20; i++)
{
p *= 2;
pow2->at(i) = p / 2;
}
int sum = 0;
for (int d = 1; d < 10; d++)
{
if (palindrome2(pow2, d))
{
std::cout << d << "\n";
sum += d;
}
if (palindrome2(pow2, d * 10 + d))
{
std::cout << d * 10 + d << "\n";
sum += d * 10 + d;
}
}
for (int a0 = 0; a0 < 5; a0++)
{
int a = a0 * 2 + 1;
for (int b = 0; b < 10; b++)
{
for (int c = 0; c < 10; c++)
{
int num0 = a * 100000 + b * 10000 + c * 1000 + c * 100 + b * 10 + a;
if (palindrome2(pow2, num0))
{
std::cout << num0 << "\n";
sum += num0;
}
int num1 = a * 10000 + b * 1000 + c * 100 + b * 10 + a;
if (palindrome2(pow2, num1))
{
std::cout << num1 << "\n";
sum += num1;
}
}
int num2 = a * 100 + b * 10 + a;
if (palindrome2(pow2, num2))
{
std::cout << num2 << "\n";
sum += num2;
}
int num3 = a * 1000 + b * 100 + b * 10 + a;
if (palindrome2(pow2, num3))
{
std::cout << num3 << "\n";
sum += num3;
}
}
}
std::cout << "sum=" << sum << "\n";
}
| [
"coucou747@gmail.com"
] | coucou747@gmail.com |
6f8bd1bab10b12526c3d9356c5717d6614ff60ca | cced6b750d5209fa824a2c0f785c7248b33c2ade | /bserver/server/src/event_manager.h | 8235993c4ce87b9d61ef85629a78e0f639d21147 | [] | no_license | chenbk85/mySoft | 41fbd689cccac5d72f412a8a00c22d89a8d6693d | 91d8ca159d22f2a6e95b545e061b88d80b5acc4a | refs/heads/master | 2020-12-28T22:53:32.871009 | 2013-11-20T08:27:38 | 2013-11-20T08:27:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | h | #ifndef __EVENT_MANAGER__H
#define __EVENT_MANAGER__H
#include <sys/epoll.h>
#include "connection.h"
class EventManager {
public:
EventManager(int tcnt, size_t esize = 1024);
~EventManager();
public:
int add_poller(pollable* conn, uint32_t event);
int mod_poller(pollable* conn, uint32_t event);
int del_poller(pollable* conn);
int add_timer();
int mod_timer();
int del_timer();
int loop(long ms);
flow_t next_flow();
private:
void handle_events(struct epoll_event *events, int count);
void handle_event(struct epoll_event *event);
void close_pollable(pollable* p);
void *thread_entry(void *p);
private:
int epoll_fd_;
flow_t next_flow_;
std::vector<pthread_t> threads;
size_t epoll_size_;
size_t epoll_next_;
struct epoll_event *epoll_events_;
struct list_head phead_;
beyondy::thread_cond_t tcond_;
};
#endif /* __EVENT_MANAGER__H */
| [
"robert.yu@morningstar.com"
] | robert.yu@morningstar.com |
d99aa8be65878839a69341c2fd21bf5eb52be414 | cff36093de78fbddc5d579fa3a25c7c66aa23998 | /rest/208474544-305026882/include/Customer.h | f9412816da02f4f0a73f89205d4b464a004eb636 | [] | no_license | barPerlman/Restaurant | d8d79eedbe31a60c4c3025716c64679a2a38843b | 5833ac4102ec19ada58c56a3a61601c9d684bc13 | refs/heads/master | 2020-04-04T15:20:39.905816 | 2018-11-19T11:04:40 | 2018-11-19T11:04:40 | 156,033,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,562 | h | #ifndef CUSTOMER_H_
#define CUSTOMER_H_
#include <vector>
#include <string>
#include "Dish.h"
class Customer{
public:
virtual Customer* getCustomerInstance()=0; //returns a pointer to a copy of the actual customer
Customer(const Customer &other);
bool findInMenu(std::string type,std::vector<Dish> menu);
Customer(std::string c_name, int c_id);
virtual std::vector<int> order(const std::vector<Dish> &menu)=0;
virtual std::string toString() const = 0;
std::string getName() const;
int getId() const;
std::string castDishType(DishType dishType);
virtual ~Customer(); // Destructor
private:
const std::string name;
const int id;
};
class VegetarianCustomer : public Customer {
public:
Customer* getCustomerInstance(); //returns a pointer to a copy of the actual customer
std::string findType();
VegetarianCustomer(std::string name, int id);
std::vector<int> order(const std::vector<Dish> &menu);
std::string toString() const;
virtual ~VegetarianCustomer();
private:
};
class CheapCustomer : public Customer {
public:
Customer* getCustomerInstance(); //returns a pointer to a copy of the actual customer
std::string findType();
CheapCustomer(std::string name, int id);
std::vector<int> order(const std::vector<Dish> &menu);
std::string toString() const;
virtual ~CheapCustomer();
private:
bool flag; // check if the customer already ordered before
};
class SpicyCustomer : public Customer {
public:
Customer* getCustomerInstance(); //returns a pointer to a copy of the actual customer
std::string findType();
SpicyCustomer(std::string name, int id);
std::vector<int> order(const std::vector<Dish> &menu);
std::string toString() const;
virtual ~SpicyCustomer();
private:
bool flag;// checks if this is the first time he order something
};
class AlchoholicCustomer : public Customer {
public:
Customer* getCustomerInstance(); //returns a pointer to a copy of the actual customer
std::string findType();
AlchoholicCustomer(std::string name, int id);
std::vector<int> order(const std::vector<Dish> &menu);
std::string toString() const;
virtual ~AlchoholicCustomer();
private:
int numOfOrders;// count the number of times he ordered
std::vector<Dish> sortAlcDish(const std::vector<Dish> &menu);// sort the alc dishes from the menu
std::vector<int> exportParameter(std::vector<Dish> alcMenu,int para);// returns a vector with : prices if para=0,indexes if para=1
};
#endif
| [
"barper@post.bgu.ac.il"
] | barper@post.bgu.ac.il |
e4fc80321df437954ccd69bab08a0e39d0031af5 | d2d4821ca589dee366b0a5ed9c13278786577c57 | /pta/7-2.cpp | c437e611d3c7b4fd28b5e072a7251007b5f62468 | [] | no_license | kb1875885205/ACM_ICPC_practice | 834a33f7e58b0f91bd8f6a21fcf759e0e9ef4698 | b3be1f6264b150e5e5de9192b5664d487825de72 | refs/heads/master | 2022-04-19T21:04:07.236574 | 2020-04-13T11:02:09 | 2020-04-13T11:02:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,332 | cpp | #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct unit
{
int a, squ;
unit* next;
};
unit* push_back(unit data,unit *head)
{
unit *tmp = new unit, *p = head;
*tmp = data;
if (p == NULL)
{
head = tmp;
return head;
}
while (p->next != NULL)
p = p->next;
p->next = tmp;
return head;
}
unit* insert(unit *head, unit data)
{
unit *tmp = new unit, *p = head, *pre = NULL;
*tmp = data;
if (p == NULL)
{
head = tmp;
return head;
}
else
{
while (p != NULL && p->squ> data.squ)
pre = p, p = p->next;
if (pre == NULL)
head = tmp, head->next = p;
else if (p && p->squ == data.squ)
p->a += data.a;
else
pre->next = tmp, tmp->next = p;
}
return head;
}
void del(unit *head)
{
unit *pre;
while (head != NULL)
{
pre = head;
head = head->next;
delete pre;
}
}
int main()
{
unit *l_1 = NULL, *l_2 = NULL, tmp;
int n, m;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> tmp.a >> tmp.squ, tmp.next = NULL;
l_1 = push_back(tmp, l_1);
}
cin >> m;
for (int i = 0; i < m; ++i)
{
cin >> tmp.a >> tmp.squ, tmp.next = NULL;
l_2 = push_back(tmp, l_2);
}
unit *l_3 = NULL, *pp = l_1;
while (pp != NULL)
{
unit *p = l_2, res;
while (p != NULL)
{
res.a = pp->a*p->a;
res.squ = pp->squ + p->squ;
res.next = NULL;
l_3 = insert(l_3, res);
p = p->next;
}
pp = pp->next;
}
unit *p = l_3;
bool f = false;
while (p != NULL)
{
if (p->a)
{
if (f)
cout << " ";
f = 1;
cout << p->a << " " << p->squ;
}
p = p->next;
}
if (!f)
cout << 0 << " " << 0;
cout << endl;
del(l_3);
l_3 = NULL;
unit *p1 = l_1, *p2 = l_2;
unit res;
while (p1 != NULL && p2 != NULL)
{
if (p1->squ == p2->squ)
{
res.a = p1->a + p2->a;
res.squ = p1->squ;
p1 = p1->next, p2 = p2->next;
}
else if (p1->squ > p2->squ)
{
res.a = p1->a;
res.squ = p1->squ;
p1 = p1->next;
}
else
{
res.a = p2->a;
res.squ = p2->squ;
p2 = p2->next;
}
res.next = NULL;
l_3 = insert(l_3, res);
}
if (p1)
l_3 = insert(l_3, *p1);
else if (p2)
l_3 = insert(l_3, *p2);
p = l_3;
f = false;
while (p != NULL)
{
if (p->a)
{
if(f)
cout << " ";
f = 1;
cout << p->a << " " << p->squ;
}
p = p->next;
}
if (!f)
cout << 0 << " " << 0;
cout << endl;
del(l_3);
l_3 = NULL;
return 0;
} | [
"organic_chemistry@foxmail.com"
] | organic_chemistry@foxmail.com |
c12f3ccad4c79b8da878e7d4323d07440ae98e32 | fbc6b48d01ae2a9bcef7b78bd188912e4419b0eb | /src/examples/04_module/01_bank/bank_account.cpp | b0a2a1b901afead6ad4b4ba40b33c6fd7f85b3b4 | [
"MIT"
] | permissive | acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-KrisCplusplus | fdef57571ac44ea72e4ea2bbdf57b754f56f12c9 | f6555cab27fb62c18e5a84316d984b30e9860174 | refs/heads/master | 2020-07-13T07:56:14.449441 | 2019-10-22T00:21:18 | 2019-10-22T00:21:18 | 205,038,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | cpp | #include "bank_account.h"
#include<iostream>
//bank_account.cpp
BankAccount::BankAccount() //constructor
{
//code to read balance from database
balance = 500;
}
void BankAccount::deposit(int amount)
{
if (amount > 0)
{
balance += amount;
}
}
void BankAccount::withdraw(int amount)
{
{
if (balance > amount)
{
balance -= amount;
}
}
}
BankAccount BankAccount::operator+(const BankAccount & b)
{
BankAccount account;
account.balance = balance + b.balance;
return BankAccount();
}
int BankAccount::get_balance() const
{
return balance;
}
void display(const BankAccount& account)
{
std::cout << "Balance: " << account.get_balance << "\n"
}
std::ostream & operator << (std::ostream & out, const BankAccount & b)
{
out << "Balance: " << b.balance << "\n";
return out;
}
std::istream & operator >> (std::istream & in, BankAccount & b)
{
std::cout << "\nEnter amount: ";
in >> b;
b.deposit(b);
return in;
} | [
"8584003@RRC2220-06"
] | 8584003@RRC2220-06 |
ccf9e99c8bc2ef4b5093bbdefb66d20417cd9f2f | 03b742676a43b52aba1ba29b1bb9bdf9d52f7e62 | /code/SRT.cpp | 9605617f5e4b18dbae507bcbad35a1510dfae2aa | [] | no_license | pedjamitrovic/subtitle-editor | 4a95d2882291d463870d5ab730363d6904315e6d | 1c221d9b7e7abdd72459a8b7aba72123e2224a0c | refs/heads/master | 2020-04-05T16:52:14.331076 | 2018-11-10T23:51:37 | 2018-11-10T23:51:37 | 157,032,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,644 | cpp | #include "SRT.h"
#include <QApplication>
SRT::SRT() {
expr = "([0-9][0-9]):([0-5][0-9]):([0-5][0-9]),([0-9]{3})\\s-->\\s([0-9][0-9]):([0-5][0-9]):([0-5][0-9]),([0-9]{3})";
timeconvert = [](string x) -> int { return atoi(x.c_str()); };
}
SRT::SRT(const string& filename) {
input.open(filename);
if (!input.is_open()) throw GreskaOtvaranje();
expr = "([0-9][0-9]):([0-5][0-9]):([0-5][0-9]),([0-9]{3})\\s-->\\s([0-9][0-9]):([0-5][0-9]):([0-5][0-9]),([0-9]{3})";
timeconvert = [](string x) -> int { return atoi(x.c_str()); };
readFile();
input.close();
inputinfo = new FileInfo(filename, titlesDuration(), FileInfo::SubtitleFormat::SRT, (int)titles->numberOfSubtitles(), fileSize(filename));
}
void SRT::readFile() {
int title_counter;
string line, text, time;
smatch sm;
while (!input.eof()) {
text = "";
input >> title_counter;
getline(input, line);
getline(input, time);
bool match = regex_search(time, sm, expr);
if (!match) throw GreskaFormat(title_counter);
getline(input, line);
while (line != "\r" && line != "") {
text.append(line);
text.append("\n");
getline(input, line);
}
text.erase(text.length() - 1, 1);
TimeStamp key_temp(timeconvert(sm[1]), timeconvert(sm[2]), timeconvert(sm[3]), timeconvert(sm[4]));
long long int key = key_temp.hashKey();
titles->add(key, new Subtitle(new TimeStamp(timeconvert(sm[1]), timeconvert(sm[2]), timeconvert(sm[3]), timeconvert(sm[4])), new TimeStamp(timeconvert(sm[5]), timeconvert(sm[6]), timeconvert(sm[7]), timeconvert(sm[8])), text));
}
}
void SRT::writeFile(const string& filename) {
int i = 1;
string x = filename + ".srt";
output.open(x);
if (!output.is_open()) throw GreskaOtvaranje();
for (map<long long int, Subtitle*>::const_iterator it = titles->getMap().cbegin(); it != titles->getMap().cend(); i++) {
output << i << endl;
output << setfill('0') << setw(2) << (*it).second->dohPocetak()->geth() << ":" << setfill('0') << setw(2) << (*it).second->dohPocetak()->getm() << ":" << setfill('0') << setw(2) << (*it).second->dohPocetak()->gets() << "," << setfill('0') << setw(3) << (*it).second->dohPocetak()->getms();
output << " --> ";
output << setfill('0') << setw(2) << (*it).second->dohKraj()->geth() << ":" << setfill('0') << setw(2) << (*it).second->dohKraj()->getm() << ":" << setfill('0') << setw(2) << (*it).second->dohKraj()->gets() << "," << setfill('0') << setw(3) << (*it).second->dohKraj()->getms() << endl;
output << (*it).second->dohTekst() << endl;
if (++it != titles->getMap().cend()) output << endl;
}
output.close();
}
| [
"pre11mit@yahoo.com"
] | pre11mit@yahoo.com |
32024e4e7253ed386568eda7c61695d4b234dc10 | b999e8c802019a6eaa1ce4bb8d054349a37eee25 | /win10/Include/10.0.17763.0/winrt/windows.devices.scanners.h | 58955849df9644f8050d643a4a5299a27ba799a9 | [
"BSD-3-Clause"
] | permissive | kniefliu/skia | a647dd2011660f72c946362aad24f8d44836f928 | f7d3ea6d9ec7a3d8ef17456cc23da7291737c680 | refs/heads/master | 2021-06-09T02:42:35.989816 | 2020-03-22T09:28:02 | 2020-03-22T09:28:02 | 150,810,052 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 188,635 | h | /* Header file automatically generated from windows.devices.scanners.idl */
/*
* File built with Microsoft(R) MIDLRT Compiler Engine Version 10.00.0223
*/
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 500
#endif
/* verify that the <rpcsal.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCSAL_H_VERSION__
#define __REQUIRED_RPCSAL_H_VERSION__ 100
#endif
#include <rpc.h>
#include <rpcndr.h>
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif /* __RPCNDR_H_VERSION__ */
#ifndef COM_NO_WINDOWS_H
#include <windows.h>
#include <ole2.h>
#endif /*COM_NO_WINDOWS_H*/
#ifndef __windows2Edevices2Escanners_h__
#define __windows2Edevices2Escanners_h__
#ifndef __windows2Edevices2Escanners_p_h__
#define __windows2Edevices2Escanners_p_h__
#pragma once
//
// Deprecated attribute support
//
#pragma push_macro("DEPRECATED")
#undef DEPRECATED
#if !defined(DISABLE_WINRT_DEPRECATION)
#if defined(__cplusplus)
#if __cplusplus >= 201402
#define DEPRECATED(x) [[deprecated(x)]]
#define DEPRECATEDENUMERATOR(x) [[deprecated(x)]]
#elif defined(_MSC_VER)
#if _MSC_VER >= 1900
#define DEPRECATED(x) [[deprecated(x)]]
#define DEPRECATEDENUMERATOR(x) [[deprecated(x)]]
#else
#define DEPRECATED(x) __declspec(deprecated(x))
#define DEPRECATEDENUMERATOR(x)
#endif // _MSC_VER >= 1900
#else // Not Standard C++ or MSVC, ignore the construct.
#define DEPRECATED(x)
#define DEPRECATEDENUMERATOR(x)
#endif // C++ deprecation
#else // C - disable deprecation
#define DEPRECATED(x)
#define DEPRECATEDENUMERATOR(x)
#endif
#else // Deprecation is disabled
#define DEPRECATED(x)
#define DEPRECATEDENUMERATOR(x)
#endif /* DEPRECATED */
// Disable Deprecation for this header, MIDL verifies that cross-type access is acceptable
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#else
#pragma warning(push)
#pragma warning(disable: 4996)
#endif
// Ensure that the setting of the /ns_prefix command line switch is consistent for all headers.
// If you get an error from the compiler indicating "warning C4005: 'CHECK_NS_PREFIX_STATE': macro redefinition", this
// indicates that you have included two different headers with different settings for the /ns_prefix MIDL command line switch
#if !defined(DISABLE_NS_PREFIX_CHECKS)
#define CHECK_NS_PREFIX_STATE "always"
#endif // !defined(DISABLE_NS_PREFIX_CHECKS)
#pragma push_macro("MIDL_CONST_ID")
#undef MIDL_CONST_ID
#define MIDL_CONST_ID const __declspec(selectany)
// API Contract Inclusion Definitions
#if !defined(SPECIFIC_API_CONTRACT_DEFINITIONS)
#if !defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_ACTIVATEDEVENTSCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_ACTIVATION_ACTIVATEDEVENTSCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_ACTIVATEDEVENTSCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_ACTIVATIONCAMERASETTINGSCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_ACTIVATION_ACTIVATIONCAMERASETTINGSCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_ACTIVATIONCAMERASETTINGSCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_CONTACTACTIVATEDEVENTSCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_ACTIVATION_CONTACTACTIVATEDEVENTSCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_CONTACTACTIVATEDEVENTSCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_WEBUISEARCHACTIVATEDEVENTSCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_ACTIVATION_WEBUISEARCHACTIVATEDEVENTSCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_ACTIVATION_WEBUISEARCHACTIVATEDEVENTSCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_BACKGROUND_BACKGROUNDALARMAPPLICATIONCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_BACKGROUND_BACKGROUNDALARMAPPLICATIONCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_BACKGROUND_BACKGROUNDALARMAPPLICATIONCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_CALLS_BACKGROUND_CALLSBACKGROUNDCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_CALLS_BACKGROUND_CALLSBACKGROUNDCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_CALLS_BACKGROUND_CALLSBACKGROUNDCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_CALLS_CALLSPHONECONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_CALLS_CALLSPHONECONTRACT_VERSION 0x40000
#endif // defined(WINDOWS_APPLICATIONMODEL_CALLS_CALLSPHONECONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_CALLS_CALLSVOIPCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_CALLS_CALLSVOIPCONTRACT_VERSION 0x40000
#endif // defined(WINDOWS_APPLICATIONMODEL_CALLS_CALLSVOIPCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_CALLS_LOCKSCREENCALLCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_CALLS_LOCKSCREENCALLCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_CALLS_LOCKSCREENCALLCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_COMMUNICATIONBLOCKING_COMMUNICATIONBLOCKINGCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_COMMUNICATIONBLOCKING_COMMUNICATIONBLOCKINGCONTRACT_VERSION 0x20000
#endif // defined(WINDOWS_APPLICATIONMODEL_COMMUNICATIONBLOCKING_COMMUNICATIONBLOCKINGCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_FULLTRUSTAPPCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_FULLTRUSTAPPCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_FULLTRUSTAPPCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_SEARCH_SEARCHCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_SEARCH_SEARCHCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_SEARCH_SEARCHCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_STARTUPTASKCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_STARTUPTASKCONTRACT_VERSION 0x30000
#endif // defined(WINDOWS_APPLICATIONMODEL_STARTUPTASKCONTRACT_VERSION)
#if !defined(WINDOWS_APPLICATIONMODEL_WALLET_WALLETCONTRACT_VERSION)
#define WINDOWS_APPLICATIONMODEL_WALLET_WALLETCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_APPLICATIONMODEL_WALLET_WALLETCONTRACT_VERSION)
#if !defined(WINDOWS_DEVICES_PRINTERS_EXTENSIONS_EXTENSIONSCONTRACT_VERSION)
#define WINDOWS_DEVICES_PRINTERS_EXTENSIONS_EXTENSIONSCONTRACT_VERSION 0x20000
#endif // defined(WINDOWS_DEVICES_PRINTERS_EXTENSIONS_EXTENSIONSCONTRACT_VERSION)
#if !defined(WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION)
#define WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION)
#if !defined(WINDOWS_DEVICES_SMARTCARDS_SMARTCARDBACKGROUNDTRIGGERCONTRACT_VERSION)
#define WINDOWS_DEVICES_SMARTCARDS_SMARTCARDBACKGROUNDTRIGGERCONTRACT_VERSION 0x30000
#endif // defined(WINDOWS_DEVICES_SMARTCARDS_SMARTCARDBACKGROUNDTRIGGERCONTRACT_VERSION)
#if !defined(WINDOWS_DEVICES_SMARTCARDS_SMARTCARDEMULATORCONTRACT_VERSION)
#define WINDOWS_DEVICES_SMARTCARDS_SMARTCARDEMULATORCONTRACT_VERSION 0x60000
#endif // defined(WINDOWS_DEVICES_SMARTCARDS_SMARTCARDEMULATORCONTRACT_VERSION)
#if !defined(WINDOWS_DEVICES_SMS_LEGACYSMSAPICONTRACT_VERSION)
#define WINDOWS_DEVICES_SMS_LEGACYSMSAPICONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_DEVICES_SMS_LEGACYSMSAPICONTRACT_VERSION)
#if !defined(WINDOWS_FOUNDATION_FOUNDATIONCONTRACT_VERSION)
#define WINDOWS_FOUNDATION_FOUNDATIONCONTRACT_VERSION 0x30000
#endif // defined(WINDOWS_FOUNDATION_FOUNDATIONCONTRACT_VERSION)
#if !defined(WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION)
#define WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION 0x70000
#endif // defined(WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION)
#if !defined(WINDOWS_GAMING_INPUT_GAMINGINPUTPREVIEWCONTRACT_VERSION)
#define WINDOWS_GAMING_INPUT_GAMINGINPUTPREVIEWCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_GAMING_INPUT_GAMINGINPUTPREVIEWCONTRACT_VERSION)
#if !defined(WINDOWS_GLOBALIZATION_GLOBALIZATIONJAPANESEPHONETICANALYZERCONTRACT_VERSION)
#define WINDOWS_GLOBALIZATION_GLOBALIZATIONJAPANESEPHONETICANALYZERCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_GLOBALIZATION_GLOBALIZATIONJAPANESEPHONETICANALYZERCONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_CAPTURE_APPBROADCASTCONTRACT_VERSION)
#define WINDOWS_MEDIA_CAPTURE_APPBROADCASTCONTRACT_VERSION 0x20000
#endif // defined(WINDOWS_MEDIA_CAPTURE_APPBROADCASTCONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_CAPTURE_APPCAPTURECONTRACT_VERSION)
#define WINDOWS_MEDIA_CAPTURE_APPCAPTURECONTRACT_VERSION 0x40000
#endif // defined(WINDOWS_MEDIA_CAPTURE_APPCAPTURECONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_CAPTURE_APPCAPTUREMETADATACONTRACT_VERSION)
#define WINDOWS_MEDIA_CAPTURE_APPCAPTUREMETADATACONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_MEDIA_CAPTURE_APPCAPTUREMETADATACONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_CAPTURE_CAMERACAPTUREUICONTRACT_VERSION)
#define WINDOWS_MEDIA_CAPTURE_CAMERACAPTUREUICONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_MEDIA_CAPTURE_CAMERACAPTUREUICONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_CAPTURE_GAMEBARCONTRACT_VERSION)
#define WINDOWS_MEDIA_CAPTURE_GAMEBARCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_MEDIA_CAPTURE_GAMEBARCONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_DEVICES_CALLCONTROLCONTRACT_VERSION)
#define WINDOWS_MEDIA_DEVICES_CALLCONTROLCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_MEDIA_DEVICES_CALLCONTROLCONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_MEDIACONTROLCONTRACT_VERSION)
#define WINDOWS_MEDIA_MEDIACONTROLCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_MEDIA_MEDIACONTROLCONTRACT_VERSION)
#if !defined(WINDOWS_MEDIA_PROTECTION_PROTECTIONRENEWALCONTRACT_VERSION)
#define WINDOWS_MEDIA_PROTECTION_PROTECTIONRENEWALCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_MEDIA_PROTECTION_PROTECTIONRENEWALCONTRACT_VERSION)
#if !defined(WINDOWS_NETWORKING_CONNECTIVITY_WWANCONTRACT_VERSION)
#define WINDOWS_NETWORKING_CONNECTIVITY_WWANCONTRACT_VERSION 0x20000
#endif // defined(WINDOWS_NETWORKING_CONNECTIVITY_WWANCONTRACT_VERSION)
#if !defined(WINDOWS_NETWORKING_SOCKETS_CONTROLCHANNELTRIGGERCONTRACT_VERSION)
#define WINDOWS_NETWORKING_SOCKETS_CONTROLCHANNELTRIGGERCONTRACT_VERSION 0x30000
#endif // defined(WINDOWS_NETWORKING_SOCKETS_CONTROLCHANNELTRIGGERCONTRACT_VERSION)
#if !defined(WINDOWS_PHONE_PHONECONTRACT_VERSION)
#define WINDOWS_PHONE_PHONECONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_PHONE_PHONECONTRACT_VERSION)
#if !defined(WINDOWS_PHONE_PHONEINTERNALCONTRACT_VERSION)
#define WINDOWS_PHONE_PHONEINTERNALCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_PHONE_PHONEINTERNALCONTRACT_VERSION)
#if !defined(WINDOWS_SECURITY_ENTERPRISEDATA_ENTERPRISEDATACONTRACT_VERSION)
#define WINDOWS_SECURITY_ENTERPRISEDATA_ENTERPRISEDATACONTRACT_VERSION 0x50000
#endif // defined(WINDOWS_SECURITY_ENTERPRISEDATA_ENTERPRISEDATACONTRACT_VERSION)
#if !defined(WINDOWS_STORAGE_PROVIDER_CLOUDFILESCONTRACT_VERSION)
#define WINDOWS_STORAGE_PROVIDER_CLOUDFILESCONTRACT_VERSION 0x30000
#endif // defined(WINDOWS_STORAGE_PROVIDER_CLOUDFILESCONTRACT_VERSION)
#if !defined(WINDOWS_SYSTEM_ANDROMEDAPLACEHOLDERCONTRACT_VERSION)
#define WINDOWS_SYSTEM_ANDROMEDAPLACEHOLDERCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_SYSTEM_ANDROMEDAPLACEHOLDERCONTRACT_VERSION)
#if !defined(WINDOWS_SYSTEM_SYSTEMMANAGEMENTCONTRACT_VERSION)
#define WINDOWS_SYSTEM_SYSTEMMANAGEMENTCONTRACT_VERSION 0x60000
#endif // defined(WINDOWS_SYSTEM_SYSTEMMANAGEMENTCONTRACT_VERSION)
#if !defined(WINDOWS_UI_CORE_COREWINDOWDIALOGSCONTRACT_VERSION)
#define WINDOWS_UI_CORE_COREWINDOWDIALOGSCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_UI_CORE_COREWINDOWDIALOGSCONTRACT_VERSION)
#if !defined(WINDOWS_UI_VIEWMANAGEMENT_VIEWMANAGEMENTVIEWSCALINGCONTRACT_VERSION)
#define WINDOWS_UI_VIEWMANAGEMENT_VIEWMANAGEMENTVIEWSCALINGCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_UI_VIEWMANAGEMENT_VIEWMANAGEMENTVIEWSCALINGCONTRACT_VERSION)
#if !defined(WINDOWS_UI_WEBUI_CORE_WEBUICOMMANDBARCONTRACT_VERSION)
#define WINDOWS_UI_WEBUI_CORE_WEBUICOMMANDBARCONTRACT_VERSION 0x10000
#endif // defined(WINDOWS_UI_WEBUI_CORE_WEBUICOMMANDBARCONTRACT_VERSION)
#endif // defined(SPECIFIC_API_CONTRACT_DEFINITIONS)
// Header files for imported files
#include "inspectable.h"
#include "AsyncInfo.h"
#include "EventToken.h"
#include "windowscontracts.h"
#include "Windows.Foundation.h"
#include "Windows.Graphics.Printing.h"
#include "Windows.Storage.h"
#include "Windows.Storage.Streams.h"
// Importing Collections header
#include <windows.foundation.collections.h>
#if defined(__cplusplus) && !defined(CINTERFACE)
/* Forward Declarations */
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScanner;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner ABI::Windows::Devices::Scanners::IImageScanner
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScannerFeederConfiguration;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration ABI::Windows::Devices::Scanners::IImageScannerFeederConfiguration
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScannerFormatConfiguration;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration ABI::Windows::Devices::Scanners::IImageScannerFormatConfiguration
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScannerPreviewResult;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult ABI::Windows::Devices::Scanners::IImageScannerPreviewResult
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScannerScanResult;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult ABI::Windows::Devices::Scanners::IImageScannerScanResult
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScannerSourceConfiguration;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration ABI::Windows::Devices::Scanners::IImageScannerSourceConfiguration
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
interface IImageScannerStatics;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics ABI::Windows::Devices::Scanners::IImageScannerStatics
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FWD_DEFINED__
// Parameterized interface forward declarations (C++)
// Collection interface definitions
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
class ImageScannerScanResult;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE
#define DEF___FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("d1662baa-4f20-5d18-97f1-a01a6d0dd980"))
IAsyncOperationProgressHandler<ABI::Windows::Devices::Scanners::ImageScannerScanResult*,UINT32> : IAsyncOperationProgressHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScannerScanResult*, ABI::Windows::Devices::Scanners::IImageScannerScanResult*>,UINT32>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.AsyncOperationProgressHandler`2<Windows.Devices.Scanners.ImageScannerScanResult, UInt32>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperationProgressHandler<ABI::Windows::Devices::Scanners::ImageScannerScanResult*,UINT32> __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t;
#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 ABI::Windows::Foundation::__FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 ABI::Windows::Foundation::IAsyncOperationProgressHandler<ABI::Windows::Devices::Scanners::IImageScannerScanResult*,UINT32>
//#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t ABI::Windows::Foundation::IAsyncOperationProgressHandler<ABI::Windows::Devices::Scanners::IImageScannerScanResult*,UINT32>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE
#define DEF___FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("bd8bdbd8-459a-52dc-b101-75b398a61aef"))
IAsyncOperationWithProgressCompletedHandler<ABI::Windows::Devices::Scanners::ImageScannerScanResult*,UINT32> : IAsyncOperationWithProgressCompletedHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScannerScanResult*, ABI::Windows::Devices::Scanners::IImageScannerScanResult*>,UINT32>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.AsyncOperationWithProgressCompletedHandler`2<Windows.Devices.Scanners.ImageScannerScanResult, UInt32>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperationWithProgressCompletedHandler<ABI::Windows::Devices::Scanners::ImageScannerScanResult*,UINT32> __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t;
#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 ABI::Windows::Foundation::__FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 ABI::Windows::Foundation::IAsyncOperationWithProgressCompletedHandler<ABI::Windows::Devices::Scanners::IImageScannerScanResult*,UINT32>
//#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t ABI::Windows::Foundation::IAsyncOperationWithProgressCompletedHandler<ABI::Windows::Devices::Scanners::IImageScannerScanResult*,UINT32>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE
#define DEF___FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("6e6e228a-f618-5d33-8523-02d16672665b"))
IAsyncOperationWithProgress<ABI::Windows::Devices::Scanners::ImageScannerScanResult*,UINT32> : IAsyncOperationWithProgress_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScannerScanResult*, ABI::Windows::Devices::Scanners::IImageScannerScanResult*>,UINT32>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.IAsyncOperationWithProgress`2<Windows.Devices.Scanners.ImageScannerScanResult, UInt32>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperationWithProgress<ABI::Windows::Devices::Scanners::ImageScannerScanResult*,UINT32> __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t;
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 ABI::Windows::Foundation::__FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 ABI::Windows::Foundation::IAsyncOperationWithProgress<ABI::Windows::Devices::Scanners::IImageScannerScanResult*,UINT32>
//#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_t ABI::Windows::Foundation::IAsyncOperationWithProgress<ABI::Windows::Devices::Scanners::IImageScannerScanResult*,UINT32>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
class ImageScanner;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_USE
#define DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("b35ad6b4-0da0-5241-87ff-eef3a1883243"))
IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::ImageScanner*> : IAsyncOperationCompletedHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScanner*, ABI::Windows::Devices::Scanners::IImageScanner*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Scanners.ImageScanner>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::ImageScanner*> __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_t;
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner ABI::Windows::Foundation::__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner ABI::Windows::Foundation::IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::IImageScanner*>
//#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_t ABI::Windows::Foundation::IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::IImageScanner*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_USE
#define DEF___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("75d78736-6c52-551e-ab5f-50674f323431"))
IAsyncOperation<ABI::Windows::Devices::Scanners::ImageScanner*> : IAsyncOperation_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScanner*, ABI::Windows::Devices::Scanners::IImageScanner*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.IAsyncOperation`1<Windows.Devices.Scanners.ImageScanner>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperation<ABI::Windows::Devices::Scanners::ImageScanner*> __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_t;
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner ABI::Windows::Foundation::__FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner ABI::Windows::Foundation::IAsyncOperation<ABI::Windows::Devices::Scanners::IImageScanner*>
//#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_t ABI::Windows::Foundation::IAsyncOperation<ABI::Windows::Devices::Scanners::IImageScanner*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
class ImageScannerPreviewResult;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_USE
#define DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("c054a410-ac3c-5353-b1ee-e85e78faf3f1"))
IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::ImageScannerPreviewResult*> : IAsyncOperationCompletedHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScannerPreviewResult*, ABI::Windows::Devices::Scanners::IImageScannerPreviewResult*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Scanners.ImageScannerPreviewResult>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::ImageScannerPreviewResult*> __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_t;
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult ABI::Windows::Foundation::__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult ABI::Windows::Foundation::IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::IImageScannerPreviewResult*>
//#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_t ABI::Windows::Foundation::IAsyncOperationCompletedHandler<ABI::Windows::Devices::Scanners::IImageScannerPreviewResult*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef DEF___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_USE
#define DEF___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation {
template <>
struct __declspec(uuid("2f74576f-0498-5348-bc3b-a70d1a771718"))
IAsyncOperation<ABI::Windows::Devices::Scanners::ImageScannerPreviewResult*> : IAsyncOperation_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Scanners::ImageScannerPreviewResult*, ABI::Windows::Devices::Scanners::IImageScannerPreviewResult*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.IAsyncOperation`1<Windows.Devices.Scanners.ImageScannerPreviewResult>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IAsyncOperation<ABI::Windows::Devices::Scanners::ImageScannerPreviewResult*> __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_t;
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult ABI::Windows::Foundation::__FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_t
/* ABI */ } /* Windows */ } /* Foundation */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult ABI::Windows::Foundation::IAsyncOperation<ABI::Windows::Devices::Scanners::IImageScannerPreviewResult*>
//#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_t ABI::Windows::Foundation::IAsyncOperation<ABI::Windows::Devices::Scanners::IImageScannerPreviewResult*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_USE */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Storage {
class StorageFile;
} /* Windows */
} /* Storage */} /* ABI */
#ifndef ____x_ABI_CWindows_CStorage_CIStorageFile_FWD_DEFINED__
#define ____x_ABI_CWindows_CStorage_CIStorageFile_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Storage {
interface IStorageFile;
} /* Windows */
} /* Storage */} /* ABI */
#define __x_ABI_CWindows_CStorage_CIStorageFile ABI::Windows::Storage::IStorageFile
#endif // ____x_ABI_CWindows_CStorage_CIStorageFile_FWD_DEFINED__
#if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#ifndef DEF___FIIterator_1_Windows__CStorage__CStorageFile_USE
#define DEF___FIIterator_1_Windows__CStorage__CStorageFile_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation { namespace Collections {
template <>
struct __declspec(uuid("43e29f53-0298-55aa-a6c8-4edd323d9598"))
IIterator<ABI::Windows::Storage::StorageFile*> : IIterator_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Storage::StorageFile*, ABI::Windows::Storage::IStorageFile*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.Collections.IIterator`1<Windows.Storage.StorageFile>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IIterator<ABI::Windows::Storage::StorageFile*> __FIIterator_1_Windows__CStorage__CStorageFile_t;
#define __FIIterator_1_Windows__CStorage__CStorageFile ABI::Windows::Foundation::Collections::__FIIterator_1_Windows__CStorage__CStorageFile_t
/* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIIterator_1_Windows__CStorage__CStorageFile ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Storage::IStorageFile*>
//#define __FIIterator_1_Windows__CStorage__CStorageFile_t ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Storage::IStorageFile*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIIterator_1_Windows__CStorage__CStorageFile_USE */
#endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#ifndef DEF___FIIterable_1_Windows__CStorage__CStorageFile_USE
#define DEF___FIIterable_1_Windows__CStorage__CStorageFile_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation { namespace Collections {
template <>
struct __declspec(uuid("9ac00304-83ea-5688-87b6-ae38aab65d0b"))
IIterable<ABI::Windows::Storage::StorageFile*> : IIterable_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Storage::StorageFile*, ABI::Windows::Storage::IStorageFile*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.Collections.IIterable`1<Windows.Storage.StorageFile>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IIterable<ABI::Windows::Storage::StorageFile*> __FIIterable_1_Windows__CStorage__CStorageFile_t;
#define __FIIterable_1_Windows__CStorage__CStorageFile ABI::Windows::Foundation::Collections::__FIIterable_1_Windows__CStorage__CStorageFile_t
/* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIIterable_1_Windows__CStorage__CStorageFile ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Storage::IStorageFile*>
//#define __FIIterable_1_Windows__CStorage__CStorageFile_t ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Storage::IStorageFile*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIIterable_1_Windows__CStorage__CStorageFile_USE */
#endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#ifndef DEF___FIVectorView_1_Windows__CStorage__CStorageFile_USE
#define DEF___FIVectorView_1_Windows__CStorage__CStorageFile_USE
#if !defined(RO_NO_TEMPLATE_NAME)
namespace ABI { namespace Windows { namespace Foundation { namespace Collections {
template <>
struct __declspec(uuid("80646519-5e2a-595d-a8cd-2a24b4067f1b"))
IVectorView<ABI::Windows::Storage::StorageFile*> : IVectorView_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Storage::StorageFile*, ABI::Windows::Storage::IStorageFile*>>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"Windows.Foundation.Collections.IVectorView`1<Windows.Storage.StorageFile>";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef IVectorView<ABI::Windows::Storage::StorageFile*> __FIVectorView_1_Windows__CStorage__CStorageFile_t;
#define __FIVectorView_1_Windows__CStorage__CStorageFile ABI::Windows::Foundation::Collections::__FIVectorView_1_Windows__CStorage__CStorageFile_t
/* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ }
//// Define an alias for the C version of the interface for compatibility purposes.
//#define __FIVectorView_1_Windows__CStorage__CStorageFile ABI::Windows::Foundation::Collections::IVectorView<ABI::Windows::Storage::IStorageFile*>
//#define __FIVectorView_1_Windows__CStorage__CStorageFile_t ABI::Windows::Foundation::Collections::IVectorView<ABI::Windows::Storage::IStorageFile*>
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF___FIVectorView_1_Windows__CStorage__CStorageFile_USE */
#endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Foundation {
typedef struct Rect Rect;
} /* Windows */
} /* Foundation */} /* ABI */
namespace ABI {
namespace Windows {
namespace Foundation {
typedef struct Size Size;
} /* Windows */
} /* Foundation */} /* ABI */
namespace ABI {
namespace Windows {
namespace Graphics {
namespace Printing {
typedef enum PrintMediaSize : int PrintMediaSize;
} /* Windows */
} /* Graphics */
} /* Printing */} /* ABI */
namespace ABI {
namespace Windows {
namespace Graphics {
namespace Printing {
typedef enum PrintOrientation : int PrintOrientation;
} /* Windows */
} /* Graphics */
} /* Printing */} /* ABI */
namespace ABI {
namespace Windows {
namespace Storage {
class StorageFolder;
} /* Windows */
} /* Storage */} /* ABI */
#ifndef ____x_ABI_CWindows_CStorage_CIStorageFolder_FWD_DEFINED__
#define ____x_ABI_CWindows_CStorage_CIStorageFolder_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Storage {
interface IStorageFolder;
} /* Windows */
} /* Storage */} /* ABI */
#define __x_ABI_CWindows_CStorage_CIStorageFolder ABI::Windows::Storage::IStorageFolder
#endif // ____x_ABI_CWindows_CStorage_CIStorageFolder_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream_FWD_DEFINED__
#define ____x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Storage {
namespace Streams {
interface IRandomAccessStream;
} /* Windows */
} /* Storage */
} /* Streams */} /* ABI */
#define __x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream ABI::Windows::Storage::Streams::IRandomAccessStream
#endif // ____x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream_FWD_DEFINED__
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
typedef enum ImageScannerAutoCroppingMode : int ImageScannerAutoCroppingMode;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
typedef enum ImageScannerColorMode : int ImageScannerColorMode;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
typedef enum ImageScannerFormat : int ImageScannerFormat;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
typedef enum ImageScannerScanSource : int ImageScannerScanSource;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
typedef struct ImageScannerResolution ImageScannerResolution;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
class ImageScannerAutoConfiguration;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
class ImageScannerFeederConfiguration;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
class ImageScannerFlatbedConfiguration;
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
/*
*
* Struct Windows.Devices.Scanners.ImageScannerAutoCroppingMode
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [v1_enum, contract] */
enum ImageScannerAutoCroppingMode : int
{
ImageScannerAutoCroppingMode_Disabled = 0,
ImageScannerAutoCroppingMode_SingleRegion = 1,
ImageScannerAutoCroppingMode_MultipleRegion = 2,
};
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerColorMode
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [v1_enum, contract] */
enum ImageScannerColorMode : int
{
ImageScannerColorMode_Color = 0,
ImageScannerColorMode_Grayscale = 1,
ImageScannerColorMode_Monochrome = 2,
ImageScannerColorMode_AutoColor = 3,
};
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerFormat
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [v1_enum, contract] */
enum ImageScannerFormat : int
{
ImageScannerFormat_Jpeg = 0,
ImageScannerFormat_Png = 1,
ImageScannerFormat_DeviceIndependentBitmap = 2,
ImageScannerFormat_Tiff = 3,
ImageScannerFormat_Xps = 4,
ImageScannerFormat_OpenXps = 5,
ImageScannerFormat_Pdf = 6,
};
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerScanSource
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [v1_enum, contract] */
enum ImageScannerScanSource : int
{
ImageScannerScanSource_Default = 0,
ImageScannerScanSource_Flatbed = 1,
ImageScannerScanSource_Feeder = 2,
ImageScannerScanSource_AutoConfigured = 3,
};
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerResolution
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [contract] */
struct ImageScannerResolution
{
FLOAT DpiX;
FLOAT DpiY;
};
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScanner
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScanner
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScanner[] = L"Windows.Devices.Scanners.IImageScanner";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("53A88F78-5298-48A0-8DA3-8087519665E0"), exclusiveto, contract] */
MIDL_INTERFACE("53A88F78-5298-48A0-8DA3-8087519665E0")
IImageScanner : public IInspectable
{
public:
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DeviceId(
/* [retval, out] */__RPC__deref_out_opt HSTRING * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DefaultScanSource(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerScanSource * value
) = 0;
virtual HRESULT STDMETHODCALLTYPE IsScanSourceSupported(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerScanSource value,
/* [retval, out] */__RPC__out boolean * result
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_FlatbedConfiguration(
/* [retval, out] */__RPC__deref_out_opt ABI::Windows::Devices::Scanners::IImageScannerFormatConfiguration * * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_FeederConfiguration(
/* [retval, out] */__RPC__deref_out_opt ABI::Windows::Devices::Scanners::IImageScannerFormatConfiguration * * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_AutoConfiguration(
/* [retval, out] */__RPC__deref_out_opt ABI::Windows::Devices::Scanners::IImageScannerFormatConfiguration * * value
) = 0;
virtual HRESULT STDMETHODCALLTYPE IsPreviewSupported(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerScanSource scanSource,
/* [retval, out] */__RPC__out boolean * result
) = 0;
virtual HRESULT STDMETHODCALLTYPE ScanPreviewToStreamAsync(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerScanSource scanSource,
/* [in] */__RPC__in_opt ABI::Windows::Storage::Streams::IRandomAccessStream * targetStream,
/* [retval, out] */__RPC__deref_out_opt __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * * operation
) = 0;
virtual HRESULT STDMETHODCALLTYPE ScanFilesToFolderAsync(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerScanSource scanSource,
/* [in] */__RPC__in_opt ABI::Windows::Storage::IStorageFolder * storageFolder,
/* [retval, out] */__RPC__deref_out_opt __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * * operation
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScanner=_uuidof(IImageScanner);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScanner;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerFeederConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScannerFeederConfiguration
*
*
* Any object which implements this interface must also implement the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration
* Windows.Devices.Scanners.IImageScannerSourceConfiguration
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerFeederConfiguration[] = L"Windows.Devices.Scanners.IImageScannerFeederConfiguration";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("74BDACEE-FA97-4C17-8280-40E39C6DCC67"), exclusiveto, contract] */
MIDL_INTERFACE("74BDACEE-FA97-4C17-8280-40E39C6DCC67")
IImageScannerFeederConfiguration : public IInspectable
{
public:
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_CanAutoDetectPageSize(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_AutoDetectPageSize(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_AutoDetectPageSize(
/* [in] */boolean value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_PageSize(
/* [retval, out] */__RPC__out ABI::Windows::Graphics::Printing::PrintMediaSize * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_PageSize(
/* [in] */ABI::Windows::Graphics::Printing::PrintMediaSize value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_PageOrientation(
/* [retval, out] */__RPC__out ABI::Windows::Graphics::Printing::PrintOrientation * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_PageOrientation(
/* [in] */ABI::Windows::Graphics::Printing::PrintOrientation value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_PageSizeDimensions(
/* [retval, out] */__RPC__out ABI::Windows::Foundation::Size * value
) = 0;
virtual HRESULT STDMETHODCALLTYPE IsPageSizeSupported(
/* [in] */ABI::Windows::Graphics::Printing::PrintMediaSize pageSize,
/* [in] */ABI::Windows::Graphics::Printing::PrintOrientation pageOrientation,
/* [retval, out] */__RPC__out boolean * result
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MaxNumberOfPages(
/* [retval, out] */__RPC__out UINT32 * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_MaxNumberOfPages(
/* [in] */UINT32 value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_CanScanDuplex(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_Duplex(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_Duplex(
/* [in] */boolean value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_CanScanAhead(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_ScanAhead(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_ScanAhead(
/* [in] */boolean value
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScannerFeederConfiguration=_uuidof(IImageScannerFeederConfiguration);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerFormatConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerFormatConfiguration[] = L"Windows.Devices.Scanners.IImageScannerFormatConfiguration";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("AE275D11-DADF-4010-BF10-CCA5C83DCBB0"), contract] */
MIDL_INTERFACE("AE275D11-DADF-4010-BF10-CCA5C83DCBB0")
IImageScannerFormatConfiguration : public IInspectable
{
public:
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DefaultFormat(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerFormat * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_Format(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerFormat * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_Format(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerFormat value
) = 0;
virtual HRESULT STDMETHODCALLTYPE IsFormatSupported(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerFormat value,
/* [retval, out] */__RPC__out boolean * result
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScannerFormatConfiguration=_uuidof(IImageScannerFormatConfiguration);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerPreviewResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScannerPreviewResult
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerPreviewResult[] = L"Windows.Devices.Scanners.IImageScannerPreviewResult";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("08B7FE8E-8891-441D-BE9C-176FA109C8BB"), exclusiveto, contract] */
MIDL_INTERFACE("08B7FE8E-8891-441D-BE9C-176FA109C8BB")
IImageScannerPreviewResult : public IInspectable
{
public:
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_Succeeded(
/* [retval, out] */__RPC__out boolean * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_Format(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerFormat * value
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScannerPreviewResult=_uuidof(IImageScannerPreviewResult);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerScanResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScannerScanResult
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerScanResult[] = L"Windows.Devices.Scanners.IImageScannerScanResult";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("C91624CD-9037-4E48-84C1-AC0975076BC5"), exclusiveto, contract] */
MIDL_INTERFACE("C91624CD-9037-4E48-84C1-AC0975076BC5")
IImageScannerScanResult : public IInspectable
{
public:
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_ScannedFiles(
/* [retval, out] */__RPC__deref_out_opt __FIVectorView_1_Windows__CStorage__CStorageFile * * value
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScannerScanResult=_uuidof(IImageScannerScanResult);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerSourceConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Any object which implements this interface must also implement the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerSourceConfiguration[] = L"Windows.Devices.Scanners.IImageScannerSourceConfiguration";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("BFB50055-0B44-4C82-9E89-205F9C234E59"), contract] */
MIDL_INTERFACE("BFB50055-0B44-4C82-9E89-205F9C234E59")
IImageScannerSourceConfiguration : public IInspectable
{
public:
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MinScanArea(
/* [retval, out] */__RPC__out ABI::Windows::Foundation::Size * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MaxScanArea(
/* [retval, out] */__RPC__out ABI::Windows::Foundation::Size * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_SelectedScanRegion(
/* [retval, out] */__RPC__out ABI::Windows::Foundation::Rect * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_SelectedScanRegion(
/* [in] */ABI::Windows::Foundation::Rect value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_AutoCroppingMode(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerAutoCroppingMode * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_AutoCroppingMode(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerAutoCroppingMode value
) = 0;
virtual HRESULT STDMETHODCALLTYPE IsAutoCroppingModeSupported(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerAutoCroppingMode value,
/* [retval, out] */__RPC__out boolean * result
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MinResolution(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerResolution * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MaxResolution(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerResolution * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_OpticalResolution(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerResolution * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DesiredResolution(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerResolution * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_DesiredResolution(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerResolution value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_ActualResolution(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerResolution * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DefaultColorMode(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerColorMode * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_ColorMode(
/* [retval, out] */__RPC__out ABI::Windows::Devices::Scanners::ImageScannerColorMode * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_ColorMode(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerColorMode value
) = 0;
virtual HRESULT STDMETHODCALLTYPE IsColorModeSupported(
/* [in] */ABI::Windows::Devices::Scanners::ImageScannerColorMode value,
/* [retval, out] */__RPC__out boolean * result
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MinBrightness(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MaxBrightness(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_BrightnessStep(
/* [retval, out] */__RPC__out UINT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DefaultBrightness(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_Brightness(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_Brightness(
/* [in] */INT32 value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MinContrast(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_MaxContrast(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_ContrastStep(
/* [retval, out] */__RPC__out UINT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_DefaultContrast(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propget] */virtual HRESULT STDMETHODCALLTYPE get_Contrast(
/* [retval, out] */__RPC__out INT32 * value
) = 0;
/* [propput] */virtual HRESULT STDMETHODCALLTYPE put_Contrast(
/* [in] */INT32 value
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScannerSourceConfiguration=_uuidof(IImageScannerSourceConfiguration);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerStatics
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScanner
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerStatics[] = L"Windows.Devices.Scanners.IImageScannerStatics";
namespace ABI {
namespace Windows {
namespace Devices {
namespace Scanners {
/* [object, uuid("BC57E70E-D804-4477-9FB5-B911B5473897"), exclusiveto, contract] */
MIDL_INTERFACE("BC57E70E-D804-4477-9FB5-B911B5473897")
IImageScannerStatics : public IInspectable
{
public:
virtual HRESULT STDMETHODCALLTYPE FromIdAsync(
/* [in] */__RPC__in HSTRING deviceId,
/* [retval, out] */__RPC__deref_out_opt __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * * asyncInfo
) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDeviceSelector(
/* [retval, out] */__RPC__deref_out_opt HSTRING * selector
) = 0;
};
extern MIDL_CONST_ID IID & IID_IImageScannerStatics=_uuidof(IImageScannerStatics);
} /* Windows */
} /* Devices */
} /* Scanners */} /* ABI */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScanner
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* RuntimeClass contains static methods.
* Static Methods exist on the Windows.Devices.Scanners.IImageScannerStatics interface starting with version 1.0 of the Windows.Devices.Scanners.ScannerDeviceContract API contract
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScanner ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScanner_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScanner_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScanner[] = L"Windows.Devices.Scanners.ImageScanner";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerAutoConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerAutoConfiguration_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerAutoConfiguration_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerAutoConfiguration[] = L"Windows.Devices.Scanners.ImageScannerAutoConfiguration";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerFeederConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration ** Default Interface **
* Windows.Devices.Scanners.IImageScannerSourceConfiguration
* Windows.Devices.Scanners.IImageScannerFeederConfiguration
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFeederConfiguration_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFeederConfiguration_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerFeederConfiguration[] = L"Windows.Devices.Scanners.ImageScannerFeederConfiguration";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerFlatbedConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration ** Default Interface **
* Windows.Devices.Scanners.IImageScannerSourceConfiguration
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFlatbedConfiguration_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFlatbedConfiguration_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerFlatbedConfiguration[] = L"Windows.Devices.Scanners.ImageScannerFlatbedConfiguration";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerPreviewResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerPreviewResult ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerPreviewResult_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerPreviewResult_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerPreviewResult[] = L"Windows.Devices.Scanners.ImageScannerPreviewResult";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerScanResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerScanResult ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerScanResult_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerScanResult_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerScanResult[] = L"Windows.Devices.Scanners.ImageScannerScanResult";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#else // !defined(__cplusplus)
/* Forward Declarations */
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScanner __x_ABI_CWindows_CDevices_CScanners_CIImageScanner;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FWD_DEFINED__
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics;
#endif // ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FWD_DEFINED__
// Parameterized interface forward declarations (C)
// Collection interface definitions
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__)
#define ____FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__
typedef interface __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
typedef interface __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
typedef struct __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This);
HRESULT ( STDMETHODCALLTYPE *Invoke )(__RPC__in __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [in] */ __RPC__in_opt __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 *asyncInfo, /* [in] */ UINT64 progressInfo);
END_INTERFACE
} __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl;
interface __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32
{
CONST_VTBL struct __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_Invoke(This,asyncInfo,progressInfo) \
( (This)->lpVtbl -> Invoke(This,asyncInfo,progressInfo) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__)
#define ____FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__
typedef interface __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
// Forward declare the async operation.
typedef interface __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
typedef struct __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This);
HRESULT ( STDMETHODCALLTYPE *Invoke )(__RPC__in __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [in] */ __RPC__in_opt __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 *asyncInfo, /* [in] */ AsyncStatus status);
END_INTERFACE
} __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl;
interface __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32
{
CONST_VTBL struct __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_Invoke(This,asyncInfo,status) \
( (This)->lpVtbl -> Invoke(This,asyncInfo,status) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__)
#define ____FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__
typedef interface __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32;
typedef struct __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This);
HRESULT ( STDMETHODCALLTYPE *GetIids )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [out] */ __RPC__deref_out_opt HSTRING *className);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [out] */ __RPC__out TrustLevel *trustLevel);
/* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_Progress )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [in] */ __RPC__in_opt __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 *handler);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Progress )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [retval][out] */ __RPC__deref_out_opt __FIAsyncOperationProgressHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 **handler);
/* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_Completed )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [in] */ __RPC__in_opt __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 *handler);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Completed )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [retval][out] */ __RPC__deref_out_opt __FIAsyncOperationWithProgressCompletedHandler_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 **handler);
HRESULT ( STDMETHODCALLTYPE *GetResults )(__RPC__in __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * This, /* [retval][out] */ __RPC__deref_out_opt __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * *results);
END_INTERFACE
} __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl;
interface __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32
{
CONST_VTBL struct __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_GetIids(This,iidCount,iids) \
( (This)->lpVtbl -> GetIids(This,iidCount,iids) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_GetRuntimeClassName(This,className) \
( (This)->lpVtbl -> GetRuntimeClassName(This,className) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_put_Progress(This,handler) \
( (This)->lpVtbl -> put_Progress(This,handler) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_get_Progress(This,handler) \
( (This)->lpVtbl -> get_Progress(This,handler) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_put_Completed(This,handler) \
( (This)->lpVtbl -> put_Completed(This,handler) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_get_Completed(This,handler) \
( (This)->lpVtbl -> get_Completed(This,handler) )
#define __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_GetResults(This,results) \
( (This)->lpVtbl -> GetResults(This,results) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_INTERFACE_DEFINED__)
#define ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_INTERFACE_DEFINED__
typedef interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner;
// Forward declare the async operation.
typedef interface __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner;
typedef struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner * This);
HRESULT ( STDMETHODCALLTYPE *Invoke )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner * This,/* [in] */ __RPC__in_opt __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner *asyncInfo, /* [in] */ AsyncStatus status);
END_INTERFACE
} __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerVtbl;
interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner
{
CONST_VTBL struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_Invoke(This,asyncInfo,status) \
( (This)->lpVtbl -> Invoke(This,asyncInfo,status) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_INTERFACE_DEFINED__)
#define ____FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_INTERFACE_DEFINED__
typedef interface __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner;
typedef struct __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This);
HRESULT ( STDMETHODCALLTYPE *GetIids )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This, /* [out] */ __RPC__deref_out_opt HSTRING *className);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This, /* [out] */ __RPC__out TrustLevel *trustLevel);
/* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_Completed )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This, /* [in] */ __RPC__in_opt __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner *handler);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Completed )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This, /* [retval][out] */ __RPC__deref_out_opt __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScanner **handler);
HRESULT ( STDMETHODCALLTYPE *GetResults )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * This, /* [retval][out] */ __RPC__out __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * *results);
END_INTERFACE
} __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerVtbl;
interface __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner
{
CONST_VTBL struct __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_GetIids(This,iidCount,iids) \
( (This)->lpVtbl -> GetIids(This,iidCount,iids) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_GetRuntimeClassName(This,className) \
( (This)->lpVtbl -> GetRuntimeClassName(This,className) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_put_Completed(This,handler) \
( (This)->lpVtbl -> put_Completed(This,handler) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_get_Completed(This,handler) \
( (This)->lpVtbl -> get_Completed(This,handler) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_GetResults(This,results) \
( (This)->lpVtbl -> GetResults(This,results) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_INTERFACE_DEFINED__)
#define ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_INTERFACE_DEFINED__
typedef interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult;
// Forward declare the async operation.
typedef interface __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult;
typedef struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResultVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This);
HRESULT ( STDMETHODCALLTYPE *Invoke )(__RPC__in __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This,/* [in] */ __RPC__in_opt __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult *asyncInfo, /* [in] */ AsyncStatus status);
END_INTERFACE
} __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResultVtbl;
interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult
{
CONST_VTBL struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResultVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_Invoke(This,asyncInfo,status) \
( (This)->lpVtbl -> Invoke(This,asyncInfo,status) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_INTERFACE_DEFINED__)
#define ____FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_INTERFACE_DEFINED__
typedef interface __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult;
typedef struct __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResultVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This);
HRESULT ( STDMETHODCALLTYPE *GetIids )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This, /* [out] */ __RPC__deref_out_opt HSTRING *className);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This, /* [out] */ __RPC__out TrustLevel *trustLevel);
/* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_Completed )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This, /* [in] */ __RPC__in_opt __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult *handler);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Completed )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This, /* [retval][out] */ __RPC__deref_out_opt __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CScanners__CImageScannerPreviewResult **handler);
HRESULT ( STDMETHODCALLTYPE *GetResults )(__RPC__in __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * This, /* [retval][out] */ __RPC__out __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * *results);
END_INTERFACE
} __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResultVtbl;
interface __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult
{
CONST_VTBL struct __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResultVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_GetIids(This,iidCount,iids) \
( (This)->lpVtbl -> GetIids(This,iidCount,iids) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_GetRuntimeClassName(This,className) \
( (This)->lpVtbl -> GetRuntimeClassName(This,className) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_put_Completed(This,handler) \
( (This)->lpVtbl -> put_Completed(This,handler) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_get_Completed(This,handler) \
( (This)->lpVtbl -> get_Completed(This,handler) )
#define __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_GetResults(This,results) \
( (This)->lpVtbl -> GetResults(This,results) )
#endif /* COBJMACROS */
#endif // ____FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult_INTERFACE_DEFINED__
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef ____x_ABI_CWindows_CStorage_CIStorageFile_FWD_DEFINED__
#define ____x_ABI_CWindows_CStorage_CIStorageFile_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CStorage_CIStorageFile __x_ABI_CWindows_CStorage_CIStorageFile;
#endif // ____x_ABI_CWindows_CStorage_CIStorageFile_FWD_DEFINED__
#if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if !defined(____FIIterator_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__)
#define ____FIIterator_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__
typedef interface __FIIterator_1_Windows__CStorage__CStorageFile __FIIterator_1_Windows__CStorage__CStorageFile;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIIterator_1_Windows__CStorage__CStorageFile;
typedef struct __FIIterator_1_Windows__CStorage__CStorageFileVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This);
HRESULT ( STDMETHODCALLTYPE *GetIids )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This, /* [out] */ __RPC__deref_out_opt HSTRING *className);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This, /* [out] */ __RPC__out TrustLevel *trustLevel);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Current )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This, /* [retval][out] */ __RPC__out __x_ABI_CWindows_CStorage_CIStorageFile * *current);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HasCurrent )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This, /* [retval][out] */ __RPC__out boolean *hasCurrent);
HRESULT ( STDMETHODCALLTYPE *MoveNext )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This, /* [retval][out] */ __RPC__out boolean *hasCurrent);
HRESULT ( STDMETHODCALLTYPE *GetMany )(__RPC__in __FIIterator_1_Windows__CStorage__CStorageFile * This,
/* [in] */ unsigned int capacity,
/* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CStorage_CIStorageFile * *items,
/* [retval][out] */ __RPC__out unsigned int *actual);
END_INTERFACE
} __FIIterator_1_Windows__CStorage__CStorageFileVtbl;
interface __FIIterator_1_Windows__CStorage__CStorageFile
{
CONST_VTBL struct __FIIterator_1_Windows__CStorage__CStorageFileVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIIterator_1_Windows__CStorage__CStorageFile_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_GetIids(This,iidCount,iids) \
( (This)->lpVtbl -> GetIids(This,iidCount,iids) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_GetRuntimeClassName(This,className) \
( (This)->lpVtbl -> GetRuntimeClassName(This,className) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_get_Current(This,current) \
( (This)->lpVtbl -> get_Current(This,current) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_get_HasCurrent(This,hasCurrent) \
( (This)->lpVtbl -> get_HasCurrent(This,hasCurrent) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_MoveNext(This,hasCurrent) \
( (This)->lpVtbl -> MoveNext(This,hasCurrent) )
#define __FIIterator_1_Windows__CStorage__CStorageFile_GetMany(This,capacity,items,actual) \
( (This)->lpVtbl -> GetMany(This,capacity,items,actual) )
#endif /* COBJMACROS */
#endif // ____FIIterator_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__
#endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if !defined(____FIIterable_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__)
#define ____FIIterable_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__
typedef interface __FIIterable_1_Windows__CStorage__CStorageFile __FIIterable_1_Windows__CStorage__CStorageFile;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIIterable_1_Windows__CStorage__CStorageFile;
typedef struct __FIIterable_1_Windows__CStorage__CStorageFileVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This);
ULONG ( STDMETHODCALLTYPE *Release )(__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This);
HRESULT ( STDMETHODCALLTYPE *GetIids )(__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This, /* [out] */ __RPC__deref_out_opt HSTRING *className);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This, /* [out] */ __RPC__out TrustLevel *trustLevel);
HRESULT ( STDMETHODCALLTYPE *First )(__RPC__in __FIIterable_1_Windows__CStorage__CStorageFile * This, /* [retval][out] */ __RPC__deref_out_opt __FIIterator_1_Windows__CStorage__CStorageFile **first);
END_INTERFACE
} __FIIterable_1_Windows__CStorage__CStorageFileVtbl;
interface __FIIterable_1_Windows__CStorage__CStorageFile
{
CONST_VTBL struct __FIIterable_1_Windows__CStorage__CStorageFileVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIIterable_1_Windows__CStorage__CStorageFile_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIIterable_1_Windows__CStorage__CStorageFile_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIIterable_1_Windows__CStorage__CStorageFile_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIIterable_1_Windows__CStorage__CStorageFile_GetIids(This,iidCount,iids) \
( (This)->lpVtbl -> GetIids(This,iidCount,iids) )
#define __FIIterable_1_Windows__CStorage__CStorageFile_GetRuntimeClassName(This,className) \
( (This)->lpVtbl -> GetRuntimeClassName(This,className) )
#define __FIIterable_1_Windows__CStorage__CStorageFile_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) )
#define __FIIterable_1_Windows__CStorage__CStorageFile_First(This,first) \
( (This)->lpVtbl -> First(This,first) )
#endif /* COBJMACROS */
#endif // ____FIIterable_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__
#endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
#if !defined(____FIVectorView_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__)
#define ____FIVectorView_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__
typedef interface __FIVectorView_1_Windows__CStorage__CStorageFile __FIVectorView_1_Windows__CStorage__CStorageFile;
// Declare the parameterized interface IID.
EXTERN_C const IID IID___FIVectorView_1_Windows__CStorage__CStorageFile;
typedef struct __FIVectorView_1_Windows__CStorage__CStorageFileVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This);
ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This);
HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [out] */ __RPC__out TrustLevel *trustLevel);
HRESULT ( STDMETHODCALLTYPE *GetAt )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [in] */ unsigned int index,
/* [retval][out] */ __RPC__out __x_ABI_CWindows_CStorage_CIStorageFile * *item);
/* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [retval][out] */ __RPC__out unsigned int *size);
HRESULT ( STDMETHODCALLTYPE *IndexOf )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [in] */ __x_ABI_CWindows_CStorage_CIStorageFile * item,
/* [out] */ __RPC__out unsigned int *index,
/* [retval][out] */ __RPC__out boolean *found);
HRESULT ( STDMETHODCALLTYPE *GetMany )(
__RPC__in __FIVectorView_1_Windows__CStorage__CStorageFile * This,
/* [in] */ unsigned int startIndex,
/* [in] */ unsigned int capacity,
/* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CStorage_CIStorageFile * *items,
/* [retval][out] */ __RPC__out unsigned int *actual);
END_INTERFACE
} __FIVectorView_1_Windows__CStorage__CStorageFileVtbl;
interface __FIVectorView_1_Windows__CStorage__CStorageFile
{
CONST_VTBL struct __FIVectorView_1_Windows__CStorage__CStorageFileVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __FIVectorView_1_Windows__CStorage__CStorageFile_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_GetIids(This,iidCount,iids) \
( (This)->lpVtbl -> GetIids(This,iidCount,iids) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_GetRuntimeClassName(This,className) \
( (This)->lpVtbl -> GetRuntimeClassName(This,className) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_GetAt(This,index,item) \
( (This)->lpVtbl -> GetAt(This,index,item) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_get_Size(This,size) \
( (This)->lpVtbl -> get_Size(This,size) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_IndexOf(This,item,index,found) \
( (This)->lpVtbl -> IndexOf(This,item,index,found) )
#define __FIVectorView_1_Windows__CStorage__CStorageFile_GetMany(This,startIndex,capacity,items,actual) \
( (This)->lpVtbl -> GetMany(This,startIndex,capacity,items,actual) )
#endif /* COBJMACROS */
#endif // ____FIVectorView_1_Windows__CStorage__CStorageFile_INTERFACE_DEFINED__
#endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000
typedef struct __x_ABI_CWindows_CFoundation_CRect __x_ABI_CWindows_CFoundation_CRect;
typedef struct __x_ABI_CWindows_CFoundation_CSize __x_ABI_CWindows_CFoundation_CSize;
typedef enum __x_ABI_CWindows_CGraphics_CPrinting_CPrintMediaSize __x_ABI_CWindows_CGraphics_CPrinting_CPrintMediaSize;
typedef enum __x_ABI_CWindows_CGraphics_CPrinting_CPrintOrientation __x_ABI_CWindows_CGraphics_CPrinting_CPrintOrientation;
#ifndef ____x_ABI_CWindows_CStorage_CIStorageFolder_FWD_DEFINED__
#define ____x_ABI_CWindows_CStorage_CIStorageFolder_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CStorage_CIStorageFolder __x_ABI_CWindows_CStorage_CIStorageFolder;
#endif // ____x_ABI_CWindows_CStorage_CIStorageFolder_FWD_DEFINED__
#ifndef ____x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream_FWD_DEFINED__
#define ____x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream_FWD_DEFINED__
typedef interface __x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream __x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream;
#endif // ____x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream_FWD_DEFINED__
typedef enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerAutoCroppingMode __x_ABI_CWindows_CDevices_CScanners_CImageScannerAutoCroppingMode;
typedef enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode __x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode;
typedef enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat __x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat;
typedef enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource __x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource;
typedef struct __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution;
/*
*
* Struct Windows.Devices.Scanners.ImageScannerAutoCroppingMode
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/* [v1_enum, contract] */
enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerAutoCroppingMode
{
ImageScannerAutoCroppingMode_Disabled = 0,
ImageScannerAutoCroppingMode_SingleRegion = 1,
ImageScannerAutoCroppingMode_MultipleRegion = 2,
};
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerColorMode
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/* [v1_enum, contract] */
enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode
{
ImageScannerColorMode_Color = 0,
ImageScannerColorMode_Grayscale = 1,
ImageScannerColorMode_Monochrome = 2,
ImageScannerColorMode_AutoColor = 3,
};
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerFormat
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/* [v1_enum, contract] */
enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat
{
ImageScannerFormat_Jpeg = 0,
ImageScannerFormat_Png = 1,
ImageScannerFormat_DeviceIndependentBitmap = 2,
ImageScannerFormat_Tiff = 3,
ImageScannerFormat_Xps = 4,
ImageScannerFormat_OpenXps = 5,
ImageScannerFormat_Pdf = 6,
};
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerScanSource
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/* [v1_enum, contract] */
enum __x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource
{
ImageScannerScanSource_Default = 0,
ImageScannerScanSource_Flatbed = 1,
ImageScannerScanSource_Feeder = 2,
ImageScannerScanSource_AutoConfigured = 3,
};
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Struct Windows.Devices.Scanners.ImageScannerResolution
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/* [contract] */
struct __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution
{
FLOAT DpiX;
FLOAT DpiY;
};
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScanner
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScanner
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScanner[] = L"Windows.Devices.Scanners.IImageScanner";
/* [object, uuid("53A88F78-5298-48A0-8DA3-8087519665E0"), exclusiveto, contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DeviceId )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [retval, out] */__RPC__deref_out_opt HSTRING * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DefaultScanSource )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource * value
);
HRESULT ( STDMETHODCALLTYPE *IsScanSourceSupported )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource value,
/* [retval, out] */__RPC__out boolean * result
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_FlatbedConfiguration )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [retval, out] */__RPC__deref_out_opt __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_FeederConfiguration )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [retval, out] */__RPC__deref_out_opt __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_AutoConfiguration )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [retval, out] */__RPC__deref_out_opt __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * * value
);
HRESULT ( STDMETHODCALLTYPE *IsPreviewSupported )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource scanSource,
/* [retval, out] */__RPC__out boolean * result
);
HRESULT ( STDMETHODCALLTYPE *ScanPreviewToStreamAsync )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource scanSource,
/* [in] */__RPC__in_opt __x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStream * targetStream,
/* [retval, out] */__RPC__deref_out_opt __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScannerPreviewResult * * operation
);
HRESULT ( STDMETHODCALLTYPE *ScanFilesToFolderAsync )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScanner * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerScanSource scanSource,
/* [in] */__RPC__in_opt __x_ABI_CWindows_CStorage_CIStorageFolder * storageFolder,
/* [retval, out] */__RPC__deref_out_opt __FIAsyncOperationWithProgress_2_Windows__CDevices__CScanners__CImageScannerScanResult_UINT32 * * operation
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScanner
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_get_DeviceId(This,value) \
( (This)->lpVtbl->get_DeviceId(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_get_DefaultScanSource(This,value) \
( (This)->lpVtbl->get_DefaultScanSource(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_IsScanSourceSupported(This,value,result) \
( (This)->lpVtbl->IsScanSourceSupported(This,value,result) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_get_FlatbedConfiguration(This,value) \
( (This)->lpVtbl->get_FlatbedConfiguration(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_get_FeederConfiguration(This,value) \
( (This)->lpVtbl->get_FeederConfiguration(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_get_AutoConfiguration(This,value) \
( (This)->lpVtbl->get_AutoConfiguration(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_IsPreviewSupported(This,scanSource,result) \
( (This)->lpVtbl->IsPreviewSupported(This,scanSource,result) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_ScanPreviewToStreamAsync(This,scanSource,targetStream,operation) \
( (This)->lpVtbl->ScanPreviewToStreamAsync(This,scanSource,targetStream,operation) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScanner_ScanFilesToFolderAsync(This,scanSource,storageFolder,operation) \
( (This)->lpVtbl->ScanFilesToFolderAsync(This,scanSource,storageFolder,operation) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScanner;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScanner_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerFeederConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScannerFeederConfiguration
*
*
* Any object which implements this interface must also implement the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration
* Windows.Devices.Scanners.IImageScannerSourceConfiguration
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerFeederConfiguration[] = L"Windows.Devices.Scanners.IImageScannerFeederConfiguration";
/* [object, uuid("74BDACEE-FA97-4C17-8280-40E39C6DCC67"), exclusiveto, contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfigurationVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_CanAutoDetectPageSize )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_AutoDetectPageSize )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_AutoDetectPageSize )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */boolean value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_PageSize )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CGraphics_CPrinting_CPrintMediaSize * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_PageSize )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */__x_ABI_CWindows_CGraphics_CPrinting_CPrintMediaSize value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_PageOrientation )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CGraphics_CPrinting_CPrintOrientation * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_PageOrientation )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */__x_ABI_CWindows_CGraphics_CPrinting_CPrintOrientation value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_PageSizeDimensions )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CFoundation_CSize * value
);
HRESULT ( STDMETHODCALLTYPE *IsPageSizeSupported )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */__x_ABI_CWindows_CGraphics_CPrinting_CPrintMediaSize pageSize,
/* [in] */__x_ABI_CWindows_CGraphics_CPrinting_CPrintOrientation pageOrientation,
/* [retval, out] */__RPC__out boolean * result
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MaxNumberOfPages )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out UINT32 * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_MaxNumberOfPages )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */UINT32 value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_CanScanDuplex )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_Duplex )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_Duplex )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */boolean value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_CanScanAhead )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_ScanAhead )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_ScanAhead )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration * This,
/* [in] */boolean value
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfigurationVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfigurationVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_CanAutoDetectPageSize(This,value) \
( (This)->lpVtbl->get_CanAutoDetectPageSize(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_AutoDetectPageSize(This,value) \
( (This)->lpVtbl->get_AutoDetectPageSize(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_put_AutoDetectPageSize(This,value) \
( (This)->lpVtbl->put_AutoDetectPageSize(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_PageSize(This,value) \
( (This)->lpVtbl->get_PageSize(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_put_PageSize(This,value) \
( (This)->lpVtbl->put_PageSize(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_PageOrientation(This,value) \
( (This)->lpVtbl->get_PageOrientation(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_put_PageOrientation(This,value) \
( (This)->lpVtbl->put_PageOrientation(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_PageSizeDimensions(This,value) \
( (This)->lpVtbl->get_PageSizeDimensions(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_IsPageSizeSupported(This,pageSize,pageOrientation,result) \
( (This)->lpVtbl->IsPageSizeSupported(This,pageSize,pageOrientation,result) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_MaxNumberOfPages(This,value) \
( (This)->lpVtbl->get_MaxNumberOfPages(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_put_MaxNumberOfPages(This,value) \
( (This)->lpVtbl->put_MaxNumberOfPages(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_CanScanDuplex(This,value) \
( (This)->lpVtbl->get_CanScanDuplex(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_Duplex(This,value) \
( (This)->lpVtbl->get_Duplex(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_put_Duplex(This,value) \
( (This)->lpVtbl->put_Duplex(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_CanScanAhead(This,value) \
( (This)->lpVtbl->get_CanScanAhead(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_get_ScanAhead(This,value) \
( (This)->lpVtbl->get_ScanAhead(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_put_ScanAhead(This,value) \
( (This)->lpVtbl->put_ScanAhead(This,value) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFeederConfiguration_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerFormatConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerFormatConfiguration[] = L"Windows.Devices.Scanners.IImageScannerFormatConfiguration";
/* [object, uuid("AE275D11-DADF-4010-BF10-CCA5C83DCBB0"), contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfigurationVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DefaultFormat )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_Format )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_Format )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat value
);
HRESULT ( STDMETHODCALLTYPE *IsFormatSupported )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat value,
/* [retval, out] */__RPC__out boolean * result
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfigurationVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfigurationVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_get_DefaultFormat(This,value) \
( (This)->lpVtbl->get_DefaultFormat(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_get_Format(This,value) \
( (This)->lpVtbl->get_Format(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_put_Format(This,value) \
( (This)->lpVtbl->put_Format(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_IsFormatSupported(This,value,result) \
( (This)->lpVtbl->IsFormatSupported(This,value,result) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerFormatConfiguration_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerPreviewResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScannerPreviewResult
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerPreviewResult[] = L"Windows.Devices.Scanners.IImageScannerPreviewResult";
/* [object, uuid("08B7FE8E-8891-441D-BE9C-176FA109C8BB"), exclusiveto, contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResultVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_Succeeded )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This,
/* [retval, out] */__RPC__out boolean * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_Format )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerFormat * value
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResultVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResultVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_get_Succeeded(This,value) \
( (This)->lpVtbl->get_Succeeded(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_get_Format(This,value) \
( (This)->lpVtbl->get_Format(This,value) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerPreviewResult_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerScanResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScannerScanResult
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerScanResult[] = L"Windows.Devices.Scanners.IImageScannerScanResult";
/* [object, uuid("C91624CD-9037-4E48-84C1-AC0975076BC5"), exclusiveto, contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResultVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_ScannedFiles )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult * This,
/* [retval, out] */__RPC__deref_out_opt __FIVectorView_1_Windows__CStorage__CStorageFile * * value
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResultVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResultVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_get_ScannedFiles(This,value) \
( (This)->lpVtbl->get_ScannedFiles(This,value) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerScanResult_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerSourceConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Any object which implements this interface must also implement the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerSourceConfiguration[] = L"Windows.Devices.Scanners.IImageScannerSourceConfiguration";
/* [object, uuid("BFB50055-0B44-4C82-9E89-205F9C234E59"), contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfigurationVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MinScanArea )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CFoundation_CSize * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MaxScanArea )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CFoundation_CSize * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_SelectedScanRegion )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CFoundation_CRect * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_SelectedScanRegion )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */__x_ABI_CWindows_CFoundation_CRect value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_AutoCroppingMode )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerAutoCroppingMode * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_AutoCroppingMode )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerAutoCroppingMode value
);
HRESULT ( STDMETHODCALLTYPE *IsAutoCroppingModeSupported )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerAutoCroppingMode value,
/* [retval, out] */__RPC__out boolean * result
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MinResolution )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MaxResolution )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_OpticalResolution )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DesiredResolution )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_DesiredResolution )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_ActualResolution )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerResolution * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DefaultColorMode )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_ColorMode )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out __x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_ColorMode )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode value
);
HRESULT ( STDMETHODCALLTYPE *IsColorModeSupported )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */__x_ABI_CWindows_CDevices_CScanners_CImageScannerColorMode value,
/* [retval, out] */__RPC__out boolean * result
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MinBrightness )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MaxBrightness )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_BrightnessStep )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out UINT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DefaultBrightness )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_Brightness )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_Brightness )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */INT32 value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MinContrast )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_MaxContrast )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_ContrastStep )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out UINT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_DefaultContrast )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propget] */HRESULT ( STDMETHODCALLTYPE *get_Contrast )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [retval, out] */__RPC__out INT32 * value
);
/* [propput] */HRESULT ( STDMETHODCALLTYPE *put_Contrast )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration * This,
/* [in] */INT32 value
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfigurationVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfigurationVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MinScanArea(This,value) \
( (This)->lpVtbl->get_MinScanArea(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MaxScanArea(This,value) \
( (This)->lpVtbl->get_MaxScanArea(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_SelectedScanRegion(This,value) \
( (This)->lpVtbl->get_SelectedScanRegion(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_put_SelectedScanRegion(This,value) \
( (This)->lpVtbl->put_SelectedScanRegion(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_AutoCroppingMode(This,value) \
( (This)->lpVtbl->get_AutoCroppingMode(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_put_AutoCroppingMode(This,value) \
( (This)->lpVtbl->put_AutoCroppingMode(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_IsAutoCroppingModeSupported(This,value,result) \
( (This)->lpVtbl->IsAutoCroppingModeSupported(This,value,result) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MinResolution(This,value) \
( (This)->lpVtbl->get_MinResolution(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MaxResolution(This,value) \
( (This)->lpVtbl->get_MaxResolution(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_OpticalResolution(This,value) \
( (This)->lpVtbl->get_OpticalResolution(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_DesiredResolution(This,value) \
( (This)->lpVtbl->get_DesiredResolution(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_put_DesiredResolution(This,value) \
( (This)->lpVtbl->put_DesiredResolution(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_ActualResolution(This,value) \
( (This)->lpVtbl->get_ActualResolution(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_DefaultColorMode(This,value) \
( (This)->lpVtbl->get_DefaultColorMode(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_ColorMode(This,value) \
( (This)->lpVtbl->get_ColorMode(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_put_ColorMode(This,value) \
( (This)->lpVtbl->put_ColorMode(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_IsColorModeSupported(This,value,result) \
( (This)->lpVtbl->IsColorModeSupported(This,value,result) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MinBrightness(This,value) \
( (This)->lpVtbl->get_MinBrightness(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MaxBrightness(This,value) \
( (This)->lpVtbl->get_MaxBrightness(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_BrightnessStep(This,value) \
( (This)->lpVtbl->get_BrightnessStep(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_DefaultBrightness(This,value) \
( (This)->lpVtbl->get_DefaultBrightness(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_Brightness(This,value) \
( (This)->lpVtbl->get_Brightness(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_put_Brightness(This,value) \
( (This)->lpVtbl->put_Brightness(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MinContrast(This,value) \
( (This)->lpVtbl->get_MinContrast(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_MaxContrast(This,value) \
( (This)->lpVtbl->get_MaxContrast(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_ContrastStep(This,value) \
( (This)->lpVtbl->get_ContrastStep(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_DefaultContrast(This,value) \
( (This)->lpVtbl->get_DefaultContrast(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_get_Contrast(This,value) \
( (This)->lpVtbl->get_Contrast(This,value) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_put_Contrast(This,value) \
( (This)->lpVtbl->put_Contrast(This,value) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerSourceConfiguration_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Interface Windows.Devices.Scanners.IImageScannerStatics
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Interface is a part of the implementation of type Windows.Devices.Scanners.ImageScanner
*
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#if !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_INTERFACE_DEFINED__)
#define ____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Scanners_IImageScannerStatics[] = L"Windows.Devices.Scanners.IImageScannerStatics";
/* [object, uuid("BC57E70E-D804-4477-9FB5-B911B5473897"), exclusiveto, contract] */
typedef struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStaticsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface)(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject
);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This
);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This
);
HRESULT ( STDMETHODCALLTYPE *GetIids )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This,
/* [out] */ __RPC__out ULONG *iidCount,
/* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids
);
HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This,
/* [out] */ __RPC__deref_out_opt HSTRING *className
);
HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )(
__RPC__in __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This,
/* [OUT ] */ __RPC__out TrustLevel *trustLevel
);
HRESULT ( STDMETHODCALLTYPE *FromIdAsync )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This,
/* [in] */__RPC__in HSTRING deviceId,
/* [retval, out] */__RPC__deref_out_opt __FIAsyncOperation_1_Windows__CDevices__CScanners__CImageScanner * * asyncInfo
);
HRESULT ( STDMETHODCALLTYPE *GetDeviceSelector )(
__x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics * This,
/* [retval, out] */__RPC__deref_out_opt HSTRING * selector
);
END_INTERFACE
} __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStaticsVtbl;
interface __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics
{
CONST_VTBL struct __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStaticsVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_AddRef(This) \
( (This)->lpVtbl->AddRef(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_Release(This) \
( (This)->lpVtbl->Release(This) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_GetIids(This,iidCount,iids) \
( (This)->lpVtbl->GetIids(This,iidCount,iids) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_GetRuntimeClassName(This,className) \
( (This)->lpVtbl->GetRuntimeClassName(This,className) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_GetTrustLevel(This,trustLevel) \
( (This)->lpVtbl->GetTrustLevel(This,trustLevel) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_FromIdAsync(This,deviceId,asyncInfo) \
( (This)->lpVtbl->FromIdAsync(This,deviceId,asyncInfo) )
#define __x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_GetDeviceSelector(This,selector) \
( (This)->lpVtbl->GetDeviceSelector(This,selector) )
#endif /* COBJMACROS */
EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics;
#endif /* !defined(____x_ABI_CWindows_CDevices_CScanners_CIImageScannerStatics_INTERFACE_DEFINED__) */
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScanner
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* RuntimeClass contains static methods.
* Static Methods exist on the Windows.Devices.Scanners.IImageScannerStatics interface starting with version 1.0 of the Windows.Devices.Scanners.ScannerDeviceContract API contract
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScanner ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScanner_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScanner_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScanner[] = L"Windows.Devices.Scanners.ImageScanner";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerAutoConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerAutoConfiguration_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerAutoConfiguration_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerAutoConfiguration[] = L"Windows.Devices.Scanners.ImageScannerAutoConfiguration";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerFeederConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration ** Default Interface **
* Windows.Devices.Scanners.IImageScannerSourceConfiguration
* Windows.Devices.Scanners.IImageScannerFeederConfiguration
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFeederConfiguration_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFeederConfiguration_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerFeederConfiguration[] = L"Windows.Devices.Scanners.ImageScannerFeederConfiguration";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerFlatbedConfiguration
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerFormatConfiguration ** Default Interface **
* Windows.Devices.Scanners.IImageScannerSourceConfiguration
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFlatbedConfiguration_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerFlatbedConfiguration_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerFlatbedConfiguration[] = L"Windows.Devices.Scanners.ImageScannerFlatbedConfiguration";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerPreviewResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerPreviewResult ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerPreviewResult_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerPreviewResult_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerPreviewResult[] = L"Windows.Devices.Scanners.ImageScannerPreviewResult";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
/*
*
* Class Windows.Devices.Scanners.ImageScannerScanResult
*
* Introduced to Windows.Devices.Scanners.ScannerDeviceContract in version 1.0
*
*
* Class implements the following interfaces:
* Windows.Devices.Scanners.IImageScannerScanResult ** Default Interface **
*
* Class Threading Model: Both Single and Multi Threaded Apartment
*
* Class Marshaling Behavior: Agile - Class is agile
*
*/
#if WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#ifndef RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerScanResult_DEFINED
#define RUNTIMECLASS_Windows_Devices_Scanners_ImageScannerScanResult_DEFINED
extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Scanners_ImageScannerScanResult[] = L"Windows.Devices.Scanners.ImageScannerScanResult";
#endif
#endif // WINDOWS_DEVICES_SCANNERS_SCANNERDEVICECONTRACT_VERSION >= 0x10000
#endif // defined(__cplusplus)
#pragma pop_macro("MIDL_CONST_ID")
// Restore the original value of the 'DEPRECATED' macro
#pragma pop_macro("DEPRECATED")
#ifdef __clang__
#pragma clang diagnostic pop // deprecated-declarations
#else
#pragma warning(pop)
#endif
#endif // __windows2Edevices2Escanners_p_h__
#endif // __windows2Edevices2Escanners_h__
| [
"kniefliu@outlook.com"
] | kniefliu@outlook.com |
818e3c52d527bd0e992ae1bc817381a17bede7a3 | 24db4c37d534030a7a34f6aedf16b845c20fed63 | /tick42rmds/RMDSSource.h | 7088e52e74a90376de1fb9a7a35653476594a810 | [] | no_license | parrondo/rmds-bridge | 06c84add920b2be564e61a3ee567ad746a10d9d9 | b07d819b29e0d4b17acacbddc99b5ffd868be17b | refs/heads/master | 2020-12-11T04:19:13.202096 | 2015-03-25T11:10:40 | 2015-03-25T11:10:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,903 | h | /*
* Tick42RMDS: The Reuters RMDS Bridge for OpenMama
* Copyright (C) 2013-2015 Tick42 Ltd.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*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
#ifndef __RMDS_SOURCE_H__
#define __RMDS_SOURCE_H__
#include "UPASubscription.h"
#include "RMDSBridgeSubscription.h"
#include <utils/thread/lock.h>
struct ServiceState
{
bool state;
bool acceptConnections;
ServiceState() : state(false), acceptConnections(false) {}
ServiceState(bool state, bool acceptConnections) : state(state), acceptConnections(acceptConnections) {}
inline ServiceState &operator =(const ServiceState &rhs)
{
if (this != &rhs)
{
state = rhs.state;
acceptConnections = rhs.acceptConnections;
}
return *this;
}
ServiceState(const ServiceState &rhs)
{
*this = rhs;
}
bool operator==(const ServiceState &rhs) const
{
return (this == &rhs) || (state == rhs.state && acceptConnections == rhs.acceptConnections);
}
};
//////////////////////////////////////////////////////////////////////////
//
// represents an RMDS subscription source
//
// Its created from the RMDS source directory update (i.e. dynamically from data delivered by the RMDS) and tracks the state of the RMDS source
//
// all the subscribed items are managed through the source so that state changes on the source can be reflected onto the individual items
class RMDSSource
{
public:
RMDSSource(const std::string & serviceName, const RsslUInt64 serviceId, UPAConsumer_ptr_t consumer);
virtual ~RMDSSource(void);
// properties
std::string ServiceName() const { return serviceName_; }
RsslUInt64 ServiceId() const { return serviceId_; }
ServiceState State() const { return state_; }
// add/remove subscriptions
virtual UPASubscription_ptr_t CreateSubscription(const std::string &symbol, bool logRmdsValues);
bool AddSubscription(UPASubscription_ptr_t sub);
bool RemoveSubscription( const std::string & symbol);
bool FindSubscription(const std::string & symbol, UPASubscription_ptr_t & sub);
// manage the state
void SetState(ServiceState state);
bool SetStale();
bool SetLive();
bool ReSubscribe();
// pause / resume updates
bool IsPausedUpdates() const
{
return pausedUpdates_;
}
void PauseUpdates()
{
pausedUpdates_ = true;
}
void ResumeUpdates()
{
pausedUpdates_ = false;
}
// OMM domain for the source
// This is either set by config or implied by the symbol name
UPASubscription::UPASubscriptionType SourceDomain() const { return sourceDomain_; }
private:
RsslUInt64 serviceId_;
std::string serviceName_;
bool pausedUpdates_;
ServiceState state_;
UPAConsumer_ptr_t consumer_;
typedef std::map<std::string, UPASubscription_ptr_t> SubscriptionMap_t;
SubscriptionMap_t subscriptions_;
typedef std::list<UPASubscription_ptr_t> SubscriptionList_t;
// park any bad subscriptions here to keep the ref count up until mama destroys them
SubscriptionList_t badSubscriptionsPark_;
mutable utils::thread::lock_t subscriptionMapLock_;
UPASubscription::UPASubscriptionType sourceDomain_;
};
#endif //__RMDS_SOURCE_H__ | [
"tom.doust@tick42.com"
] | tom.doust@tick42.com |
fb84a2bc4e57e395b020672b82f450bec724865c | 1e5808d06eb3f7b3663b2453f78b459a11dc4ee2 | /Game/include/MagixObject.h | f1ead5856ca8287d0b87938c4753d161da0b4b3e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Lamina022/RetroIT | 59fc99b4a822dcb57ca11d620b302c70e745815d | d5c6f6bbc36b4120f717e47221d5115179567cde | refs/heads/master | 2023-06-09T00:29:18.833385 | 2021-07-03T04:26:15 | 2021-07-03T04:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | h | #pragma once
#include "Ogre.h"
using namespace Ogre;
#define FRICTION 3
#define GRAVITY 3
#define JUMP_ACCEL 2
#define TERMINAL_VEL 800
#define GROUND_THRESHOLD 2
#define ALLIANCE_PLAYER 1
#define ALLIANCE_FRIEND 2
#define ALLIANCE_ENEMY 3
enum OBJECT_TYPE
{
OBJECT_BASIC,
OBJECT_ANIMATED,
OBJECT_LIVING,
OBJECT_UNIT,
OBJECT_PLAYER,
OBJECT_ITEM,
OBJECT_CRITTER
};
struct HitInfo
{
unsigned short ID;
Real hp;
Vector3 force;
bool isMine;
HitInfo(const unsigned short &i, const Real &h, const Vector3 &f, bool iM=false)
{
ID = i;
hp = h;
force = f;
isMine = iM;
}
};
using namespace Ogre;
class MagixObject
{
protected:
SceneNode *mObjectNode;
public:
MagixObject();
~MagixObject();
virtual const OBJECT_TYPE getType();
virtual const Vector3 getPosition();
virtual SceneNode* getObjectNode();
};
| [
"dylan_the_cheetah@outlook.com"
] | dylan_the_cheetah@outlook.com |
22580e50e1c4bcb3c1ede4e56da59d5ab344fa0a | 7e588732dffa27e88e88fe6102ee57d4e0ff2231 | /src/Core/TundraCore/Tests/TestMath.cpp | aa5b0cc56b2b16177617a568d3c70120810c3b81 | [
"Apache-2.0"
] | permissive | Adminotech/tundra | 57eba52645b93d0933a1ce4b5025a42f43ad6707 | 8270097dbf79c3ec1935cf66c7979eeef9c24c0e | refs/heads/admino_tundra | 2023-04-14T03:05:27.603113 | 2016-03-01T13:56:01 | 2016-03-01T13:56:01 | 2,701,928 | 1 | 2 | null | 2013-05-22T08:15:00 | 2011-11-03T12:50:38 | C++ | UTF-8 | C++ | false | false | 5,127 | cpp |
#include "DebugOperatorNew.h"
#include "TestMath.h"
#include "Framework.h"
#include "Math/MathFunc.h"
#include "Math/float3.h"
#include "Math/float4.h"
#include "Scene.h"
#include "Entity.h"
//#include "EC_Placeable.h"
#include <QtTest/QtTest>
#include "MemoryLeakCheck.h"
namespace TundraTest
{
Math::Math()
{
}
void Math::initTestCase()
{
test_.Initialize();
}
void Math::cleanupTestCase()
{
test_.ProcessEvents();
test_.scene->RemoveAllEntities();
test_.ProcessEvents();
}
void Math::cleanup()
{
test_.ProcessEvents();
}
void Math::float3Data()
{
QTest::addColumn<QString>("op");
QTest::addColumn<float3>("a");
QTest::addColumn<float3>("b");
foreach(const QString &op, QStringList() << "+" << "-" << "/" << "*")
{
for (int i=0; i<=1000000; i+=100000)
{
float f = static_cast<float>(i);
QTest::newRow(qPrintable(op)) << op << float3(-f*2.f, f, -f) << float3(f, -f*2.f, f);
}
}
}
void Math::float4Data()
{
QTest::addColumn<QString>("op");
QTest::addColumn<float4>("a");
QTest::addColumn<float4>("b");
foreach(const QString &op, QStringList() << "+" << "-" << "/" << "*")
{
for (int i=0; i<=1000000; i+=100000)
{
float f = static_cast<float>(i);
QTest::newRow(qPrintable(op)) << op << float4(-f*2.f, f, -f*2.f, f) << float4(f, -f*2.f, f, -f*2.f);
}
}
}
void Math::Op_float3_data()
{
float3Data();
}
void Math::Op_float3()
{
QFETCH(QString, op);
QFETCH(float3, a);
QFETCH(float3, b);
if (op == "+")
{
QBENCHMARK { a.Add(b); }
}
else if (op == "-")
{
QBENCHMARK { a.Sub(b); }
}
else if (op == "/")
{
QBENCHMARK { a.Div(b); }
}
else if (op == "*")
{
QBENCHMARK { a.Mul(b); }
}
}
void Math::Op_float4_data()
{
float4Data();
}
void Math::Op_float4()
{
QFETCH(QString, op);
QFETCH(float4, a);
QFETCH(float4, b);
if (op == "+")
{
QBENCHMARK { a.Add(b); }
}
else if (op == "-")
{
QBENCHMARK { a.Sub(b); }
}
else if (op == "/")
{
QBENCHMARK { a.Div(b); }
}
else if (op == "*")
{
QBENCHMARK { a.Mul(b); }
}
}
void Math::MathFunc_data()
{
float3Data();
}
void Math::MathFunc()
{
QFETCH(QString, op);
QFETCH(float3, a);
QFETCH(float3, b);
if (op == "+")
{
QBENCHMARK { Max(a.x, b.x); }
}
else if (op == "-")
{
QBENCHMARK { Min(a.x, b.x); }
}
}
/* See header...
void Math::ParentChildData()
{
QTest::addColumn<entity_id_t>("parentEntityId");
QTest::addColumn<entity_id_t>("childEntityId");
EntityPtr parent = test_.scene->CreateLocalEntity(QStringList() << EC_Placeable::TypeNameStatic(), AttributeChange::LocalOnly, false, true);
PlaceablePtr parentPlaceable = parent->Component<EC_Placeable>();
test_.ProcessEvents();
EntityPtr child = test_.scene->CreateLocalEntity(QStringList() << EC_Placeable::TypeNameStatic(), AttributeChange::LocalOnly, false, true);
PlaceablePtr childPlaceable = child->Component<EC_Placeable>();
test_.ProcessEvents();
child->SetParent(parent);
test_.ProcessEvents();
Transform t = parentPlaceable->transform.Get();
t.pos.Set(10, -20, 30);
t.rot.Set(-10, 20, -30);
t.scale.Set(1, 2, 3);
parentPlaceable->transform.Set(t, AttributeChange::LocalOnly);
t = childPlaceable->transform.Get();
t.pos.Set(30, -10, 20);
t.rot.Set(-30, 10, -20);
t.scale.Set(3, 1, 2);
childPlaceable->transform.Set(t, AttributeChange::LocalOnly);
test_.ProcessEvents();
QTest::newRow("Entity level parented Entity pair") << parent->Id() << child->Id();
}
void Math::Placeable_LocalToWorld_data()
{
ParentChildData();
}
void Math::Placeable_LocalToWorld()
{
QFETCH(entity_id_t, parentEntityId);
QFETCH(entity_id_t, childEntityId);
EntityPtr parent = test_.scene->EntityById(parentEntityId);
QVERIFY(parent);
PlaceablePtr parentPlaceable = parent->Component<EC_Placeable>();
QVERIFY(parentPlaceable);
EntityPtr child = test_.scene->EntityById(childEntityId);
QVERIFY(child);
PlaceablePtr childPlaceable = child->Component<EC_Placeable>();
QVERIFY(childPlaceable);
QBENCHMARK
{
childPlaceable->LocalToWorld();
}
}
*/
}
// QTest entry point
QTEST_APPLESS_MAIN(TundraTest::Math);
| [
"jonne@adminotech.com"
] | jonne@adminotech.com |
4c4991152f0df4af980b01c53a85699359e178ca | 613a82f6ee09d69d8e5d35c705797dd1faa1f95c | /Engine/Math/MathUtilNeon.inl | c94d41a3eebeea5993061f9e6549f2d63921b467 | [] | no_license | happydpc/Atlas | d587d5820ae45a0bdfd8c7ca76c91185f48b23fe | c93434ce530ad62a8ab61877a49ebc9356308185 | refs/heads/master | 2020-08-03T04:58:09.262142 | 2019-09-10T12:54:35 | 2019-09-10T12:54:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,405 | inl | namespace math
{
inline void MathUtil::addMatrix(const float* m, float scalar, float* dst)
{
asm volatile(
"vld1.32 {q0, q1}, [%1]! \n\t" // M[m0-m7]
"vld1.32 {q2, q3}, [%1] \n\t" // M[m8-m15]
"vld1.32 {d8[0]}, [%2] \n\t" // s
"vmov.f32 s17, s16 \n\t" // s
"vmov.f32 s18, s16 \n\t" // s
"vmov.f32 s19, s16 \n\t" // s
"vadd.f32 q8, q0, q4 \n\t" // DST->M[m0-m3] = M[m0-m3] + s
"vadd.f32 q9, q1, q4 \n\t" // DST->M[m4-m7] = M[m4-m7] + s
"vadd.f32 q10, q2, q4 \n\t" // DST->M[m8-m11] = M[m8-m11] + s
"vadd.f32 q11, q3, q4 \n\t" // DST->M[m12-m15] = M[m12-m15] + s
"vst1.32 {q8, q9}, [%0]! \n\t" // DST->M[m0-m7]
"vst1.32 {q10, q11}, [%0] \n\t" // DST->M[m8-m15]
:
: "r"(dst), "r"(m), "r"(&scalar)
: "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "memory"
);
}
inline void MathUtil::addMatrix(const float* m1, const float* m2, float* dst)
{
asm volatile(
"vld1.32 {q0, q1}, [%1]! \n\t" // M1[m0-m7]
"vld1.32 {q2, q3}, [%1] \n\t" // M1[m8-m15]
"vld1.32 {q8, q9}, [%2]! \n\t" // M2[m0-m7]
"vld1.32 {q10, q11}, [%2] \n\t" // M2[m8-m15]
"vadd.f32 q12, q0, q8 \n\t" // DST->M[m0-m3] = M1[m0-m3] + M2[m0-m3]
"vadd.f32 q13, q1, q9 \n\t" // DST->M[m4-m7] = M1[m4-m7] + M2[m4-m7]
"vadd.f32 q14, q2, q10 \n\t" // DST->M[m8-m11] = M1[m8-m11] + M2[m8-m11]
"vadd.f32 q15, q3, q11 \n\t" // DST->M[m12-m15] = M1[m12-m15] + M2[m12-m15]
"vst1.32 {q12, q13}, [%0]! \n\t" // DST->M[m0-m7]
"vst1.32 {q14, q15}, [%0] \n\t" // DST->M[m8-m15]
:
: "r"(dst), "r"(m1), "r"(m2)
: "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15", "memory"
);
}
inline void MathUtil::subtractMatrix(const float* m1, const float* m2, float* dst)
{
asm volatile(
"vld1.32 {q0, q1}, [%1]! \n\t" // M1[m0-m7]
"vld1.32 {q2, q3}, [%1] \n\t" // M1[m8-m15]
"vld1.32 {q8, q9}, [%2]! \n\t" // M2[m0-m7]
"vld1.32 {q10, q11}, [%2] \n\t" // M2[m8-m15]
"vsub.f32 q12, q0, q8 \n\t" // DST->M[m0-m3] = M1[m0-m3] - M2[m0-m3]
"vsub.f32 q13, q1, q9 \n\t" // DST->M[m4-m7] = M1[m4-m7] - M2[m4-m7]
"vsub.f32 q14, q2, q10 \n\t" // DST->M[m8-m11] = M1[m8-m11] - M2[m8-m11]
"vsub.f32 q15, q3, q11 \n\t" // DST->M[m12-m15] = M1[m12-m15] - M2[m12-m15]
"vst1.32 {q12, q13}, [%0]! \n\t" // DST->M[m0-m7]
"vst1.32 {q14, q15}, [%0] \n\t" // DST->M[m8-m15]
:
: "r"(dst), "r"(m1), "r"(m2)
: "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15", "memory"
);
}
inline void MathUtil::multiplyMatrix(const float* m, float scalar, float* dst)
{
asm volatile(
"vld1.32 {d0[0]}, [%2] \n\t" // M[m0-m7]
"vld1.32 {q4-q5}, [%1]! \n\t" // M[m8-m15]
"vld1.32 {q6-q7}, [%1] \n\t" // s
"vmul.f32 q8, q4, d0[0] \n\t" // DST->M[m0-m3] = M[m0-m3] * s
"vmul.f32 q9, q5, d0[0] \n\t" // DST->M[m4-m7] = M[m4-m7] * s
"vmul.f32 q10, q6, d0[0] \n\t" // DST->M[m8-m11] = M[m8-m11] * s
"vmul.f32 q11, q7, d0[0] \n\t" // DST->M[m12-m15] = M[m12-m15] * s
"vst1.32 {q8-q9}, [%0]! \n\t" // DST->M[m0-m7]
"vst1.32 {q10-q11}, [%0] \n\t" // DST->M[m8-m15]
:
: "r"(dst), "r"(m), "r"(&scalar)
: "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "memory"
);
}
inline void MathUtil::multiplyMatrix(const float* m1, const float* m2, float* dst)
{
asm volatile(
"vld1.32 {d16 - d19}, [%1]! \n\t" // M1[m0-m7]
"vld1.32 {d20 - d23}, [%1] \n\t" // M1[m8-m15]
"vld1.32 {d0 - d3}, [%2]! \n\t" // M2[m0-m7]
"vld1.32 {d4 - d7}, [%2] \n\t" // M2[m8-m15]
"vmul.f32 q12, q8, d0[0] \n\t" // DST->M[m0-m3] = M1[m0-m3] * M2[m0]
"vmul.f32 q13, q8, d2[0] \n\t" // DST->M[m4-m7] = M1[m4-m7] * M2[m4]
"vmul.f32 q14, q8, d4[0] \n\t" // DST->M[m8-m11] = M1[m8-m11] * M2[m8]
"vmul.f32 q15, q8, d6[0] \n\t" // DST->M[m12-m15] = M1[m12-m15] * M2[m12]
"vmla.f32 q12, q9, d0[1] \n\t" // DST->M[m0-m3] += M1[m0-m3] * M2[m1]
"vmla.f32 q13, q9, d2[1] \n\t" // DST->M[m4-m7] += M1[m4-m7] * M2[m5]
"vmla.f32 q14, q9, d4[1] \n\t" // DST->M[m8-m11] += M1[m8-m11] * M2[m9]
"vmla.f32 q15, q9, d6[1] \n\t" // DST->M[m12-m15] += M1[m12-m15] * M2[m13]
"vmla.f32 q12, q10, d1[0] \n\t" // DST->M[m0-m3] += M1[m0-m3] * M2[m2]
"vmla.f32 q13, q10, d3[0] \n\t" // DST->M[m4-m7] += M1[m4-m7] * M2[m6]
"vmla.f32 q14, q10, d5[0] \n\t" // DST->M[m8-m11] += M1[m8-m11] * M2[m10]
"vmla.f32 q15, q10, d7[0] \n\t" // DST->M[m12-m15] += M1[m12-m15] * M2[m14]
"vmla.f32 q12, q11, d1[1] \n\t" // DST->M[m0-m3] += M1[m0-m3] * M2[m3]
"vmla.f32 q13, q11, d3[1] \n\t" // DST->M[m4-m7] += M1[m4-m7] * M2[m7]
"vmla.f32 q14, q11, d5[1] \n\t" // DST->M[m8-m11] += M1[m8-m11] * M2[m11]
"vmla.f32 q15, q11, d7[1] \n\t" // DST->M[m12-m15] += M1[m12-m15] * M2[m15]
"vst1.32 {d24 - d27}, [%0]! \n\t" // DST->M[m0-m7]
"vst1.32 {d28 - d31}, [%0] \n\t" // DST->M[m8-m15]
: // output
: "r"(dst), "r"(m1), "r"(m2) // input - note *value* of pointer doesn't change.
: "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
inline void MathUtil::negateMatrix(const float* m, float* dst)
{
asm volatile(
"vld1.32 {q0-q1}, [%1]! \n\t" // load m0-m7
"vld1.32 {q2-q3}, [%1] \n\t" // load m8-m15
"vneg.f32 q4, q0 \n\t" // negate m0-m3
"vneg.f32 q5, q1 \n\t" // negate m4-m7
"vneg.f32 q6, q2 \n\t" // negate m8-m15
"vneg.f32 q7, q3 \n\t" // negate m8-m15
"vst1.32 {q4-q5}, [%0]! \n\t" // store m0-m7
"vst1.32 {q6-q7}, [%0] \n\t" // store m8-m15
:
: "r"(dst), "r"(m)
: "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "memory"
);
}
inline void MathUtil::transposeMatrix(const float* m, float* dst)
{
asm volatile(
"vld4.32 {d0[0], d2[0], d4[0], d6[0]}, [%1]! \n\t" // DST->M[m0, m4, m8, m12] = M[m0-m3]
"vld4.32 {d0[1], d2[1], d4[1], d6[1]}, [%1]! \n\t" // DST->M[m1, m5, m9, m12] = M[m4-m7]
"vld4.32 {d1[0], d3[0], d5[0], d7[0]}, [%1]! \n\t" // DST->M[m2, m6, m10, m12] = M[m8-m11]
"vld4.32 {d1[1], d3[1], d5[1], d7[1]}, [%1] \n\t" // DST->M[m3, m7, m11, m12] = M[m12-m15]
"vst1.32 {q0-q1}, [%0]! \n\t" // DST->M[m0-m7]
"vst1.32 {q2-q3}, [%0] \n\t" // DST->M[m8-m15]
:
: "r"(dst), "r"(m)
: "q0", "q1", "q2", "q3", "memory"
);
}
inline void MathUtil::transformVector4(const float* m, float x, float y, float z, float w, float* dst)
{
asm volatile(
"vld1.32 {d0[0]}, [%1] \n\t" // V[x]
"vld1.32 {d0[1]}, [%2] \n\t" // V[y]
"vld1.32 {d1[0]}, [%3] \n\t" // V[z]
"vld1.32 {d1[1]}, [%4] \n\t" // V[w]
"vld1.32 {d18 - d21}, [%5]! \n\t" // M[m0-m7]
"vld1.32 {d22 - d25}, [%5] \n\t" // M[m8-m15]
"vmul.f32 q13, q9, d0[0] \n\t" // DST->V = M[m0-m3] * V[x]
"vmla.f32 q13, q10, d0[1] \n\t" // DST->V += M[m4-m7] * V[y]
"vmla.f32 q13, q11, d1[0] \n\t" // DST->V += M[m8-m11] * V[z]
"vmla.f32 q13, q12, d1[1] \n\t" // DST->V += M[m12-m15] * V[w]
"vst1.32 {d26}, [%0]! \n\t" // DST->V[x, y]
"vst1.32 {d27[0]}, [%0] \n\t" // DST->V[z]
:
: "r"(dst), "r"(&x), "r"(&y), "r"(&z), "r"(&w), "r"(m)
: "q0", "q9", "q10","q11", "q12", "q13", "memory"
);
}
inline void MathUtil::transformVector4(const float* m, const float* v, float* dst)
{
asm volatile
(
"vld1.32 {d0, d1}, [%1] \n\t" // V[x, y, z, w]
"vld1.32 {d18 - d21}, [%2]! \n\t" // M[m0-m7]
"vld1.32 {d22 - d25}, [%2] \n\t" // M[m8-m15]
"vmul.f32 q13, q9, d0[0] \n\t" // DST->V = M[m0-m3] * V[x]
"vmla.f32 q13, q10, d0[1] \n\t" // DST->V = M[m4-m7] * V[y]
"vmla.f32 q13, q11, d1[0] \n\t" // DST->V = M[m8-m11] * V[z]
"vmla.f32 q13, q12, d1[1] \n\t" // DST->V = M[m12-m15] * V[w]
"vst1.32 {d26, d27}, [%0] \n\t" // DST->V
:
: "r"(dst), "r"(v), "r"(m)
: "q0", "q9", "q10","q11", "q12", "q13", "memory"
);
}
inline void MathUtil::crossVector3(const float* v1, const float* v2, float* dst)
{
asm volatile(
"vld1.32 {d1[1]}, [%1] \n\t" //
"vld1.32 {d0}, [%2] \n\t" //
"vmov.f32 s2, s1 \n\t" // q0 = (v1y, v1z, v1z, v1x)
"vld1.32 {d2[1]}, [%3] \n\t" //
"vld1.32 {d3}, [%4] \n\t" //
"vmov.f32 s4, s7 \n\t" // q1 = (v2z, v2x, v2y, v2z)
"vmul.f32 d4, d0, d2 \n\t" // x = v1y * v2z, y = v1z * v2x
"vmls.f32 d4, d1, d3 \n\t" // x -= v1z * v2y, y-= v1x - v2z
"vmul.f32 d5, d3, d1[1] \n\t" // z = v1x * v2y
"vmls.f32 d5, d0, d2[1] \n\t" // z-= v1y * vx
"vst1.32 {d4}, [%0]! \n\t" // V[x, y]
"vst1.32 {d5[0]}, [%0] \n\t" // V[z]
:
: "r"(dst), "r"(v1), "r"((v1+1)), "r"(v2), "r"((v2+1))
: "q0", "q1", "q2", "memory"
);
}
}
| [
"moldovan.catalin@gmail.com"
] | moldovan.catalin@gmail.com |
01c7f6e896269d9172091db25fbce016e5586b09 | 050ebbbc7d5f89d340fd9f2aa534eac42d9babb7 | /grupa1/aerbel/p2/DWA.cpp | 215503f730fc2352ca0dc8c80302ed16968f8e76 | [] | no_license | anagorko/zpk2015 | 83461a25831fa4358366ec15ab915a0d9b6acdf5 | 0553ec55d2617f7bea588d650b94828b5f434915 | refs/heads/master | 2020-04-05T23:47:55.299547 | 2016-09-14T11:01:46 | 2016-09-14T11:01:46 | 52,429,626 | 0 | 13 | null | 2016-03-22T09:35:25 | 2016-02-24T09:19:07 | C++ | UTF-8 | C++ | false | false | 541 | cpp | #include <iostream>
using namespace std;
int main() {
int i,j,n, m,k, mi,su, su1;
su=0;
su1=0;
cin >> n >> m;
int a[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; ++j)
cin >> a[i][j];
su1=0;
for(i=0;i<m;i++) su1=su1+a[1][i];
for(i=0;i<n;i++){
for(j=i+1;j<n;j++)
{ for(k=0;k<m;k++) {
if(a[i][k]<a[j][k]){ su=su+a[i][k];}
else { su=su+a[j][k];}
}
if (su<su1) {su1=su;} su=0;
}
}
cout<<su1;
}
| [
"a.erbel@student.uw.edu.pl"
] | a.erbel@student.uw.edu.pl |
efcdb65e7b2cbaa82da285ffdb9ca7e19a4c33a2 | 7cdbac97437657022daa0b97b27b9fa3dea2a889 | /engine/source/platformWin32/winExec.cc | 1b87f3ed45c13a3d75ca6505a3794457401d9681 | [] | no_license | lineCode/3SS | 36617d2b6e35b913e342d26fd2be238dbb4b4f3f | 51c702bbaee8239c02db58f6c974b2c6cd2271d1 | refs/heads/master | 2020-09-30T18:43:27.358305 | 2015-03-04T00:14:23 | 2015-03-04T00:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,580 | cc | //-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
#include "platformWin32/platformWin32.h"
#include "console/console.h"
#include "sim/simBase.h"
#include "string/unicode.h"
#include "platform/threads/thread.h"
#include "platform/threads/mutex.h"
#include "memory/safeDelete.h"
//////////////////////////////////////////////////////////////////////////
// Thread for executing in
//////////////////////////////////////////////////////////////////////////
class ExecuteThread : public Thread
{
// [tom, 12/14/2006] mProcess is only used in the constructor before the thread
// is started and in the thread itself so we should be OK without a mutex.
HANDLE mProcess;
public:
ExecuteThread(const char *executable, const char *args = NULL, const char *directory = NULL);
virtual void run(void *arg = 0);
};
//////////////////////////////////////////////////////////////////////////
// Event for cleanup
//////////////////////////////////////////////////////////////////////////
class ExecuteCleanupEvent : public SimEvent
{
ExecuteThread *mThread;
bool mOK;
public:
ExecuteCleanupEvent(ExecuteThread *thread, bool ok)
{
mThread = thread;
mOK = ok;
}
virtual void process(SimObject *object)
{
Con::executef(2, "onExecuteDone", Con::getIntArg(mOK));
SAFE_DELETE(mThread);
}
};
//////////////////////////////////////////////////////////////////////////
ExecuteThread::ExecuteThread(const char *executable, const char *args /* = NULL */, const char *directory /* = NULL */) : Thread(0, NULL, false)
{
//#pragma message("Implement UNICODE support for ExecuteThread [12/14/2006 tom]" )
SHELLEXECUTEINFOA shl;
dMemset(&shl, 0, sizeof(shl));
shl.cbSize = sizeof(shl);
shl.fMask = SEE_MASK_NOCLOSEPROCESS;
char exeBuf[1024];
Platform::makeFullPathName(executable, exeBuf, sizeof(exeBuf));
shl.lpVerb = "open";
shl.lpFile = exeBuf;
shl.lpParameters = args;
shl.lpDirectory = directory;
shl.nShow = SW_SHOWNORMAL;
if(ShellExecuteExA(&shl) && shl.hProcess)
{
mProcess = shl.hProcess;
start();
}
}
void ExecuteThread::run(void *arg /* = 0 */)
{
if(mProcess == NULL)
return;
DWORD wait;
while(! checkForStop() && (wait = WaitForSingleObject(mProcess, 200)) != WAIT_OBJECT_0) ;
Sim::postEvent(Sim::getRootGroup(), new ExecuteCleanupEvent(this, wait == WAIT_OBJECT_0), -1);
}
//////////////////////////////////////////////////////////////////////////
// Console Functions
//////////////////////////////////////////////////////////////////////////
ConsoleFunction(shellExecute, bool, 2, 4, "(executable, [args], [directory]) Executes a process"
"@param executable The program to execute\n"
"@param args Arguments to pass to the executable\n"
"@param directory The directory in which the program is located\n"
"@return Returns true on success, false otherwise")
{
ExecuteThread *et = new ExecuteThread(argv[1], argc > 2 ? argv[2] : NULL, argc > 3 ? argv[3] : NULL);
if(! et->isAlive())
{
delete et;
return false;
}
return true;
}
ConsoleFunction(shellExecuteBlocking, int, 2, 6, "(executable, [args], [directory])"
"@param executable The program to execute\n"
"@param args Arguments to pass to the executable\n"
"@param directory The directory in which the program is located\n"
"@return Returns true on success, false otherwise")
{
const char* executable = argv[1];
const char* args = argc > 2 ? argv[2] : NULL;
const char* directory = argc > 3 ? argv[3] : NULL;
SHELLEXECUTEINFOA shl;
dMemset(&shl, 0, sizeof(shl));
shl.cbSize = sizeof(shl);
shl.fMask = SEE_MASK_NOCLOSEPROCESS;
char exeBuf[1024];
Platform::makeFullPathName(executable, exeBuf, sizeof(exeBuf));
shl.lpVerb = "open";
shl.lpFile = exeBuf;
shl.lpParameters = args;
shl.lpDirectory = directory;
shl.nShow = SW_HIDE;
ShellExecuteExA(&shl);
if ( shl.hProcess == NULL )
return false;
return ( WaitForSingleObject( shl.hProcess, INFINITE) == WAIT_OBJECT_0 );
}
void Platform::openFolder(const char* path )
{
char filePath[1024];
Platform::makeFullPathName(path, filePath, sizeof(filePath));
::ShellExecuteA( NULL,"explore",filePath, NULL, NULL, SW_SHOWNORMAL);
} | [
"kylem@garagegames.com"
] | kylem@garagegames.com |
ed298ac50b5101c4c458029871f87f0e63ede14e | 4bcc9806152542ab43fc2cf47c499424f200896c | /tensorflow/lite/acceleration/configuration/stable_delegate_plugin.cc | 5e43386a3257d4a1e98a3d876bb84c064443f525 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | tensorflow/tensorflow | 906276dbafcc70a941026aa5dc50425ef71ee282 | a7f3934a67900720af3d3b15389551483bee50b8 | refs/heads/master | 2023-08-25T04:24:41.611870 | 2023-08-25T04:06:24 | 2023-08-25T04:14:08 | 45,717,250 | 208,740 | 109,943 | Apache-2.0 | 2023-09-14T20:55:50 | 2015-11-07T01:19:20 | C++ | UTF-8 | C++ | false | false | 1,052 | cc | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file implements the TFLite Delegate Plugin for the NNAPI Delegate.
#include "tensorflow/lite/acceleration/configuration/stable_delegate_plugin.h"
namespace tflite {
namespace delegates {
TFLITE_REGISTER_DELEGATE_FACTORY_FUNCTION(StableDelegatePlugin,
StableDelegatePlugin::New);
} // namespace delegates
} // namespace tflite
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.