hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fea8d82ec9e16d7ea097b3b455dca6a25ec14ef1 | 93,369 | cpp | C++ | Source/MediaInfo/Audio/File_Mpegh3da.cpp | ValZapod/MediaInfoLib | 5ecc69a60264ab9684e0c5839c22be597c9837a3 | [
"BSD-2-Clause"
] | 446 | 2015-01-28T05:19:34.000Z | 2022-03-27T13:44:39.000Z | Source/MediaInfo/Audio/File_Mpegh3da.cpp | ValZapod/MediaInfoLib | 5ecc69a60264ab9684e0c5839c22be597c9837a3 | [
"BSD-2-Clause"
] | 580 | 2015-03-31T13:36:50.000Z | 2022-03-20T02:44:15.000Z | Source/MediaInfo/Audio/File_Mpegh3da.cpp | ValZapod/MediaInfoLib | 5ecc69a60264ab9684e0c5839c22be597c9837a3 | [
"BSD-2-Clause"
] | 171 | 2015-01-08T07:57:09.000Z | 2022-03-30T11:40:06.000Z | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_MPEGH3DA_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Mpegh3da.h"
#include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#include <cmath>
using namespace ZenLib;
using namespace std;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Info
//***************************************************************************
extern const size_t Aac_sampling_frequency_Size_Usac; // USAC expands Aac_sampling_frequency[]
extern const int32u Aac_sampling_frequency[];
struct coreSbrFrameLengthIndex_mapping
{
int8u sbrRatioIndex;
int8u outputFrameLengthDivided256;
};
extern const size_t coreSbrFrameLengthIndex_Mapping_Size;
extern coreSbrFrameLengthIndex_mapping coreSbrFrameLengthIndex_Mapping[];
extern int8u Aac_Channels_Get(int8u ChannelLayout);
extern string Aac_Channels_GetString(int8u ChannelLayout);
extern string Aac_ChannelConfiguration_GetString(int8u ChannelLayout);
extern string Aac_ChannelConfiguration2_GetString(int8u ChannelLayout);
extern string Aac_ChannelLayout_GetString(const Aac_OutputChannel* const OutputChannels, size_t OutputChannels_Size);
extern string Aac_ChannelLayout_GetString(int8u ChannelLayout, bool IsMpegh3da=false);
extern string Aac_ChannelLayout_GetString(const vector<Aac_OutputChannel>& OutputChannels);
extern string Aac_ChannelMode_GetString(int8u ChannelLayout, bool IsMpegh3da=false);
extern string Aac_ChannelMode_GetString(const vector<Aac_OutputChannel>& OutputChannels);
extern string Aac_OutputChannelPosition_GetString(int8u OutputChannelPosition);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_Profile[]=
{
"Main",
"High",
"LC",
"BL",
};
static size_t Mpegh3da_Profile_Size=sizeof(Mpegh3da_Profile)/sizeof(const char* const);
extern string Mpegh3da_Profile_Get(int8u mpegh3daProfileLevelIndication)
{
if (!mpegh3daProfileLevelIndication)
return string();
if (mpegh3daProfileLevelIndication>=5*Mpegh3da_Profile_Size)
return Ztring::ToZtring(mpegh3daProfileLevelIndication).To_UTF8(); // Raw value
return string(Mpegh3da_Profile[(mpegh3daProfileLevelIndication-1)/5])+"@L"+char('1'+((mpegh3daProfileLevelIndication-1)%5));
}
//---------------------------------------------------------------------------
static const char* const Mpegh3da_MHASPacketType[]=
{
"FILLDATA",
"MPEGH3DACFG",
"MPEGH3DAFRAME",
"AUDIOSCENEINFO",
"",
"",
"SYNC",
"SYNCGAP",
"MARKER",
"CRC16",
"CRC32",
"DESCRIPTOR",
"USERINTERACTION",
"LOUDNESS_DRC",
"BUFFERINFO",
"GLOBAL_CRC16",
"GLOBAL_CRC32",
"AUDIOTRUNCATION",
"GENDATA",
};
static const size_t Mpegh3da_MHASPacketType_Size=sizeof(Mpegh3da_MHASPacketType)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_contentKind[]=
{
"",
"Complete Main",
"Dialogue",
"Music",
"Effect",
"Mixed",
"LFE",
"Voiceover",
"Spoken Subtitle",
"Visually Impaired or Audio Description",
"Commentary",
"Hearing Impaired",
"Emergency",
};
static const size_t Mpegh3da_contentKind_Size=sizeof(Mpegh3da_contentKind)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_groupPresetKind[]=
{
"",
"Integrated TV Loudspeaker",
"High Quality Loudspeaker",
"Mobile Loudspeakers",
"Mobile Headphones",
"Hearing Impaired (light)",
"Hearing Impaired (heavy)",
"Visually Impaired or Audio Description",
"Spoken Subtitles",
"Loudness or DRC",
};
static const size_t Mpegh3da_groupPresetKind_Size=sizeof(Mpegh3da_groupPresetKind)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_signalGroupType[]=
{
"Channels",
"Object",
"SAOC",
"HOA",
};
static const size_t Mpegh3da_signalGroupType_Size=sizeof(Mpegh3da_signalGroupType)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_marker_byte[]=
{
"",
"Configuration change marker",
"Random access or Immediate playout marker",
"Program boundary marker",
};
static const size_t Mpegh3da_marker_byte_Size=sizeof(Mpegh3da_marker_byte)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_usacElementType[4]=
{
"SCE",
"CPE",
"LFE",
"EXT",
};
//---------------------------------------------------------------------------
static const char* const Mpegh3da_usacExtElementType[]=
{
"FILL",
"MPEGS",
"SAOC",
"AUDIOPREROLL",
"UNI_DRC",
"OBJ_METADATA",
"SAOC_3D",
"HOA",
"FMT_CNVRTR",
"MCT",
"TCC",
"HOA_ENH_LAYER",
"HREP",
"ENHANCED_OBJ_METADATA",
};
static const size_t Mpegh3da_usacExtElementType_Size=sizeof(Mpegh3da_usacExtElementType)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const char* const Mpegh3da_usacConfigExtType[]=
{
"FILL",
"DOWNMIX",
"LOUDNESS_INFO",
"AUDIOSCENE_INFO",
"HOA_MATRIX",
"ICG",
"SIG_GROUP_INFO",
"COMPATIBLE_PROFILE_LEVEL_SET",
};
static const size_t Mpegh3da_usacConfigExtType_Size=sizeof(Mpegh3da_usacConfigExtType)/sizeof(const char* const);
//---------------------------------------------------------------------------
static const size_t Mpegh3da_SpeakerInfo_Size=43;
static const speaker_info Mpegh3da_SpeakerInfo[Mpegh3da_SpeakerInfo_Size]=
{
{CH_M_L030, 30, false, 0, false, false},
{CH_M_R030, 30, true , 0, false, false},
{CH_M_000 , 0, false, 0, false, false},
{CH_LFE , 0, false, 15, true , true},
{CH_M_L110, 110, false, 0, false, false},
{CH_M_R110, 110, true , 0, false, false},
{CH_M_L022, 22, false, 0, false, false},
{CH_M_R022, 22, true , 0, false, false},
{CH_M_L135, 135, false, 0, false, false},
{CH_M_R135, 135, true , 0, false, false},
{CH_M_180 , 180, false, 0, false, false},
{CH_M_LSD , 135, false, 0, false, false},
{CH_M_RSD , 135, true , 0, false, false},
{CH_M_L090, 90, false, 0, false, false},
{CH_M_R090, 90, true , 0, false, false},
{CH_M_L060, 60, false, 0, false, false},
{CH_M_R060, 60, true , 0, false, false},
{CH_U_L030, 30, false, 35, false, false},
{CH_U_R030, 30, true , 35, false, false},
{CH_U_000 , 0, false, 35, false, false},
{CH_U_L135, 135, false, 35, false, false},
{CH_U_R135, 135, true , 35, false, false},
{CH_U_180 , 180, false, 35, false, false},
{CH_U_L090, 90, false, 35, false, false},
{CH_U_R090, 90, true , 35, false, false},
{CH_T_000 , 0, false, 90, false, false},
{CH_LFE2 , 45, false, 15, true , true},
{CH_L_L045, 45, false, 15, true , false},
{CH_L_R045, 45, true , 15, true , false},
{CH_L_000 , 0, false, 15, true , false},
{CH_U_L110, 110, false, 35, false, false},
{CH_U_R110, 110, true , 35, false, false},
{CH_U_L045, 45, false, 35, false, false},
{CH_U_R045, 45, true , 35, false, false},
{CH_M_L045, 45, false, 0, false, false},
{CH_M_R045, 45, true , 0, false, false},
{CH_LFE3 , 45, true , 15, true , true},
{CH_M_LSCR, 2, false, 0, false, false},
{CH_M_RSCR, 2, true , 0, false, false},
{CH_M_LSCH, 1, false, 0, false, false},
{CH_M_RSCH, 1, true , 0, false, false},
{CH_M_L150, 150, false, 0, false, false},
{CH_M_R150, 150, true , 0, false, false},
};
//***************************************************************************
// Constructor/Destructor
//***************************************************************************
//---------------------------------------------------------------------------
File_Mpegh3da::File_Mpegh3da()
:File_Usac()
{
//Configuration
#if MEDIAINFO_TRACE
Trace_Layers_Update(8); //Stream
#endif //MEDIAINFO_TRACE
//In
MustParse_mhaC=false;
MustParse_mpegh3daFrame=false;
//Temp
audioSceneInfoID=0;
isMainStream=(int8u)-1;
}
//***************************************************************************
// Streams management
//***************************************************************************
//---------------------------------------------------------------------------
void File_Mpegh3da::Streams_Fill()
{
Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, 0, Audio_Format, "MPEG-H 3D Audio");
string Format_Profile=Mpegh3da_Profile_Get(mpegh3daProfileLevelIndication);
for (size_t Pos=0; Pos<mpegh3daCompatibleProfileLevelSet.size(); Pos++)
{
Format_Profile+=", ";
Format_Profile+=Mpegh3da_Profile_Get(mpegh3daCompatibleProfileLevelSet[Pos]);
}
Fill(Stream_Audio, 0, Audio_Format_Profile, Format_Profile);
Fill(Stream_Audio, 0, Audio_SamplingRate, usacSamplingFrequency);
Fill(Stream_Audio, 0, Audio_SamplesPerFrame, coreSbrFrameLengthIndex_Mapping[coreSbrFrameLengthIndex].outputFrameLengthDivided256<<8);
if (isMainStream!=(int8u)-1)
Fill(Stream_Audio, 0, "Type", isMainStream?"Main":"Auxiliary");
Fill_SetOptions(Stream_Audio, 0, "Type", "N NTY");
for (set<int32u>::iterator Label=MHASPacketLabels.begin(); Label!=MHASPacketLabels.end(); ++Label)
Fill(Stream_Audio, 0, "Label", *Label);
Fill_SetOptions(Stream_Audio, 0, "Label", "N NTY");
Ztring LabelString=Retrieve(Stream_Audio, 0, "Label");
const Ztring& Type=Retrieve_Const(Stream_Audio, 0, "Type");
if (!LabelString.empty() && !Type.empty())
{
if (!LabelString.empty())
LabelString+=__T(' ');
LabelString+=__T('(')+Type+__T(')');
}
if (LabelString.empty())
Fill(Stream_Audio, 0, "Label/String", LabelString);
Fill_SetOptions(Stream_Audio, 0, "Label/String", "Y NTN");
if (audioSceneInfoID)
Fill(Stream_Audio, 0, "AudioSceneInfoID", audioSceneInfoID);
Streams_Fill_ChannelLayout(string(), referenceLayout);
if (!GroupPresets.empty())
{
Fill(Stream_Audio, 0, "GroupPresetCount", GroupPresets.size());
Fill_SetOptions(Stream_Audio, 0, "GroupPresetCount", "N NIY");
}
if (!SwitchGroups.empty())
{
Fill(Stream_Audio, 0, "SwitchGroupCount", SwitchGroups.size());
Fill_SetOptions(Stream_Audio, 0, "SwitchGroupCount", "N NIY");
}
if (!Groups.empty())
{
Fill(Stream_Audio, 0, "GroupCount", Groups.size());
Fill_SetOptions(Stream_Audio, 0, "GroupCount", "N NIY");
}
if (!SignalGroups.empty())
{
Fill(Stream_Audio, 0, "SignalGroupCount", SignalGroups.size());
Fill_SetOptions(Stream_Audio, 0, "SignalGroupCount", "N NIY");
}
// Filling
if (!Mpegh3da_drcInstructionsUniDrc_Data[0].empty())
{
drcInstructionsUniDrc_Data=Mpegh3da_drcInstructionsUniDrc_Data[0].begin()->second;
Fill_DRC();
drcInstructionsUniDrc_Data.clear();
}
/*
if (!Mpegh3da_loudnessInfo_Data[0].empty() && !GroupPresets.empty())
{
int8u ID=(int8u)-1;
for (size_t i=0; i<GroupPresets.size(); i++)
{
const group_preset& P=GroupPresets[i];
if (P.ID<ID)
ID=P.ID;
if (Mpegh3da_loudnessInfo_Data[3][ID].Data[0].empty())
{
Mpegh3da_loudnessInfo_Data[3][ID].Data[0]=Mpegh3da_loudnessInfo_Data[0].begin()->second.Data[0];
Mpegh3da_loudnessInfo_Data[0].begin()->second.Data[0].clear();
}
}
}
*/
bool NoLoudnesConch;
if (!Mpegh3da_loudnessInfo_Data[0].empty())
{
loudnessInfo_Data[0]=Mpegh3da_loudnessInfo_Data[0].begin()->second.Data[0];
loudnessInfo_Data[1]=Mpegh3da_loudnessInfo_Data[0].begin()->second.Data[1];
loudnessInfoSet_Present=true;
Fill_Loudness(NULL);
loudnessInfo_Data[0].clear();
loudnessInfo_Data[1].clear();
NoLoudnesConch=true;
}
else
NoLoudnesConch=false;
for (size_t i=0; i<GroupPresets.size(); i++)
{
const group_preset& P=GroupPresets[i];
string Summary;
if (!P.Description.empty())
Summary+=P.Description.begin()->second;
if (Summary.empty())
Summary="Yes";
string p=string("GroupPreset")+Ztring::ToZtring(i).To_UTF8();
Fill(Stream_Audio, 0, p.c_str(), Summary);
Fill(Stream_Audio, 0, (p+" Pos").c_str(), i);
Fill_SetOptions(Stream_Audio, 0, (p+" Pos").c_str(), "N NIY");
Fill(Stream_Audio, 0, (p+" ID").c_str(), P.ID);
for (map<string, string>::const_iterator Desc=P.Description.begin(); Desc!=P.Description.end(); ++Desc)
{
Ztring Language=MediaInfoLib::Config.Iso639_1_Get(Ztring().From_UTF8(Desc->first));
if (Language.empty())
Language=Ztring().From_UTF8(Desc->first);
Fill(Stream_Audio, 0, (p+" Title").c_str(), '('+MediaInfoLib::Config.Language_Get_Translate(__T("Language_"), Language).To_UTF8() + ") "+Desc->second);
}
if (P.Kind<Mpegh3da_groupPresetKind_Size)
Fill(Stream_Audio, 0, (p+" Kind").c_str(), Mpegh3da_groupPresetKind[P.Kind]);
if (!Mpegh3da_drcInstructionsUniDrc_Data[3].empty())
{
std::map<int8u, std::map<int16u, drc_info> >::iterator drcInstructionsUniDrc=Mpegh3da_drcInstructionsUniDrc_Data[3].find(P.ID);
if (drcInstructionsUniDrc!=Mpegh3da_drcInstructionsUniDrc_Data[3].end())
{
drcInstructionsUniDrc_Data=drcInstructionsUniDrc->second;
Fill_DRC(p.c_str());
drcInstructionsUniDrc_Data.clear();
}
}
if (!Mpegh3da_loudnessInfo_Data[3].empty())
{
std::map<int8u, loudness_info_data>::iterator Loudness=Mpegh3da_loudnessInfo_Data[3].find(P.ID);
if (Loudness!=Mpegh3da_loudnessInfo_Data[3].end())
{
loudnessInfo_Data[0]=Loudness->second.Data[0];
loudnessInfoSet_Present=true;
Fill_Loudness(p.c_str(), NoLoudnesConch);
loudnessInfo_Data[0].clear();
}
}
/* Disabled for the moment, need more details about how to show it
ZtringList IDs;
if (P.Conditions.size()==1 && P.Conditions[0].ReferenceID==127 && !P.Conditions[0].ConditionOnOff)
{
Fill(Stream_Audio, 0, (p+" LinkedTo_Group_Pos").c_str(), "Full user interactivity");
Fill_SetOptions(Stream_Audio, 0, (p+" LinkedTo_Group_Pos").c_str(), "N NTY");
Fill(Stream_Audio, 0, (p+" LinkedTo_Group_Pos/String").c_str(), "Full user interactivity");
Fill_SetOptions(Stream_Audio, 0, (p+" LinkedTo_Group_Pos/String").c_str(), "Y NTN");
}
else
{
ZtringList GroupPos, GroupNum;
for (size_t i=0; i<P.Conditions.size(); i++)
{
for (size_t j=0; j<Groups.size(); j++)
if (Groups[j].ID==P.Conditions[i].ReferenceID)
{
GroupPos.push_back(Ztring::ToZtring(j));
GroupNum.push_back(Ztring::ToZtring(j+1));
}
}
GroupPos.Separator_Set(0, __T(" + "));
Fill(Stream_Audio, 0, (p+" LinkedTo_Group_Pos").c_str(), GroupPos.Read());
Fill_SetOptions(Stream_Audio, 0, (p+" LinkedTo_Group_Pos").c_str(), "N NTY");
GroupNum.Separator_Set(0, __T(" + "));
Fill(Stream_Audio, 0, (p+" LinkedTo_Group_Pos/String").c_str(), GroupNum.Read());
Fill_SetOptions(Stream_Audio, 0, (p+" LinkedTo_Group_Pos/String").c_str(), "Y NTN");
}
*/
}
for (size_t i=0; i<SwitchGroups.size(); i++)
{
const switch_group& S=SwitchGroups[i];
string Summary;
if (!S.Description.empty())
Summary+=S.Description.begin()->second;
if (Summary.empty())
Summary="Yes";
string s=string("SwitchGroup")+Ztring::ToZtring(i).To_UTF8();
Fill(Stream_Audio, 0, s.c_str(), Summary);
Fill(Stream_Audio, 0, (s+" Pos").c_str(), i);
Fill_SetOptions(Stream_Audio, 0, (s+" Pos").c_str(), "N NIY");
Fill(Stream_Audio, 0, (s+" ID").c_str(), S.ID);
for (map<string, string>::const_iterator Desc=S.Description.begin(); Desc!=S.Description.end(); ++Desc)
{
Ztring Language=MediaInfoLib::Config.Iso639_1_Get(Ztring().From_UTF8(Desc->first));
if (Language.empty())
Language=Ztring().From_UTF8(Desc->first);
Fill(Stream_Audio, 0, (s+" Title").c_str(), '('+MediaInfoLib::Config.Language_Get_Translate(__T("Language_"), Language).To_UTF8() + ") "+Desc->second);
}
Fill(Stream_Audio, 0, (s+" Allow").c_str(), S.allowOnOff?"Yes":"No");
if (S.allowOnOff)
Fill(Stream_Audio, 0, (s+" Default").c_str(), S.defaultOnOff?"Yes":"No");
Fill(Stream_Audio, 0, (s+" DefaultGroupID").c_str(), S.DefaultGroupID);
ZtringList GroupPos, GroupNum;
for (size_t i=0; i<S.MemberID.size(); i++)
{
for (size_t j=0; j<Groups.size(); j++)
if (Groups[j].ID==S.MemberID[i])
{
GroupPos.push_back(Ztring::ToZtring(j));
GroupNum.push_back(Ztring::ToZtring(j+1));
}
}
GroupPos.Separator_Set(0, __T(" + "));
Fill(Stream_Audio, 0, (s+" LinkedTo_Group_Pos").c_str(), GroupPos.Read());
Fill_SetOptions(Stream_Audio, 0, (s+" LinkedTo_Group_Pos").c_str(), "N NTY");
GroupNum.Separator_Set(0, __T(" + "));
Fill(Stream_Audio, 0, (s+" LinkedTo_Group_Pos/String").c_str(), GroupNum.Read());
Fill_SetOptions(Stream_Audio, 0, (s+" LinkedTo_Group_Pos/String").c_str(), "Y NTN");
}
for (size_t i=0; i<Groups.size(); i++)
{
const group& G=Groups[i];
string Summary;
if (!G.Description.empty())
Summary+=G.Description.begin()->second;
if (Summary.empty())
Summary="Yes";
string g=string("Group")+Ztring::ToZtring(i).To_UTF8();
Fill(Stream_Audio, 0, g.c_str(), Summary);
Fill(Stream_Audio, 0, (g+" Pos").c_str(), i);
Fill_SetOptions(Stream_Audio, 0, (g+" Pos").c_str(), "N NIY");
Fill(Stream_Audio, 0, (g+" ID").c_str(), G.ID);
for (map<string, string>::const_iterator Desc=G.Description.begin(); Desc!=G.Description.end(); ++Desc)
{
Ztring Language=MediaInfoLib::Config.Iso639_1_Get(Ztring().From_UTF8(Desc->first));
if (Language.empty())
Language=Ztring().From_UTF8(Desc->first);
Fill(Stream_Audio, 0, (g+" Title").c_str(), '('+MediaInfoLib::Config.Language_Get_Translate(__T("Language_"), Language).To_UTF8() + ") "+Desc->second);
}
if (!G.Language.empty())
{
Fill(Stream_Audio, 0, (g+" Language").c_str(), G.Language);
Fill(Stream_Audio, 0, (g+" Language/String").c_str(), MediaInfoLib::Config.Iso639_Translate(Ztring().From_UTF8(G.Language)));
Fill_SetOptions(Stream_Audio, 0, (g+" Language").c_str(), "N NTY");
Fill_SetOptions(Stream_Audio, 0, (g+" Language/String").c_str(), "Y NTN");
}
if (G.Kind<Mpegh3da_contentKind_Size)
Fill(Stream_Audio, 0, (g+" Kind").c_str(), Mpegh3da_contentKind[G.Kind]);
Fill(Stream_Audio, 0, (g+" Allow").c_str(), G.allowOnOff?"Yes":"No");
if (G.allowOnOff)
Fill(Stream_Audio, 0, (g+" Default").c_str(), G.defaultOnOff?"Yes":"No");
if (!Mpegh3da_drcInstructionsUniDrc_Data[1].empty())
{
std::map<int8u, std::map<int16u, drc_info> >::iterator drcInstructionsUniDrc=Mpegh3da_drcInstructionsUniDrc_Data[1].find(G.ID);
if (drcInstructionsUniDrc!=Mpegh3da_drcInstructionsUniDrc_Data[1].end())
{
drcInstructionsUniDrc_Data=drcInstructionsUniDrc->second;
Fill_DRC(g.c_str());
drcInstructionsUniDrc_Data.clear();
}
}
if (!Mpegh3da_loudnessInfo_Data[1].empty())
{
std::map<int8u, loudness_info_data>::iterator Loudness=Mpegh3da_loudnessInfo_Data[1].find(G.ID);
if (Loudness!=Mpegh3da_loudnessInfo_Data[1].end())
{
loudnessInfo_Data[0]=Loudness->second.Data[0];
loudnessInfoSet_Present=true;
Fill_Loudness(g.c_str(), NoLoudnesConch);
loudnessInfo_Data[0].clear();
}
}
if (!Mpegh3da_drcInstructionsUniDrc_Data[2].empty()) // Not sure
{
std::map<int8u, std::map<int16u, drc_info> >::iterator drcInstructionsUniDrc=Mpegh3da_drcInstructionsUniDrc_Data[2].find(G.ID);
if (drcInstructionsUniDrc!=Mpegh3da_drcInstructionsUniDrc_Data[2].end())
{
drcInstructionsUniDrc_Data=drcInstructionsUniDrc->second;
Fill_DRC(g.c_str());
drcInstructionsUniDrc_Data.clear();
}
}
if (!Mpegh3da_loudnessInfo_Data[2].empty()) // Not sure
{
std::map<int8u, loudness_info_data>::iterator Loudness=Mpegh3da_loudnessInfo_Data[2].find(G.ID);
if (Loudness!=Mpegh3da_loudnessInfo_Data[2].end())
{
loudnessInfo_Data[0]=Loudness->second.Data[0];
loudnessInfoSet_Present=true;
Fill_Loudness(g.c_str(), NoLoudnesConch);
loudnessInfo_Data[0].clear();
}
}
ZtringList GroupPos, GroupNum;
for (size_t i=0; i<G.MemberID.size(); i++)
{
size_t Signal_Count=0;
for (size_t j=0; j<SignalGroups.size(); j++)
{
const signal_group& E=SignalGroups[j];
if (Signal_Count==G.MemberID[i])
{
GroupPos.push_back(Ztring::ToZtring(j));
GroupNum.push_back(Ztring::ToZtring(j+1));
}
if (Aac_Channels_Get(E.Layout.ChannelLayout))
Signal_Count+=Aac_Channels_Get(E.Layout.ChannelLayout);
else if (E.Layout.numSpeakers)
Signal_Count+=E.Layout.numSpeakers;
}
}
GroupPos.Separator_Set(0, __T(" + "));
Fill(Stream_Audio, 0, (g+" LinkedTo_SignalGroup_Pos").c_str(), GroupPos.Read());
Fill_SetOptions(Stream_Audio, 0, (g+" LinkedTo_SignalGroup_Pos").c_str(), "N NTY");
GroupNum.Separator_Set(0, __T(" + "));
Fill(Stream_Audio, 0, (g+" LinkedTo_SignalGroup_Pos/String").c_str(), GroupNum.Read());
Fill_SetOptions(Stream_Audio, 0, (g+" LinkedTo_SignalGroup_Pos/String").c_str(), "Y NTN");
}
for (size_t i=0; i<SignalGroups.size(); i++)
{
const signal_group& E=SignalGroups[i];
string e=string("SignalGroup")+Ztring::ToZtring(i).To_UTF8();
Fill(Stream_Audio, 0, e.c_str(), "Yes");
Fill(Stream_Audio, 0, (e+" Pos").c_str(), i);
Fill_SetOptions(Stream_Audio, 0, (e+" Pos").c_str(), "N NIY");
if (E.Type<Mpegh3da_signalGroupType_Size)
Fill(Stream_Audio, 0, (e+" Type").c_str(), Mpegh3da_signalGroupType[E.Type]);
Streams_Fill_ChannelLayout(e+' ', E.Layout, E.Type);
string Summary;
switch (E.Type)
{
case 0 : //Channels
Summary+=Retrieve_Const(Stream_Audio, 0, (e+" Channel(s)/String").c_str()).To_UTF8();
break;
case 1 : // Objects
Summary+=Retrieve_Const(Stream_Audio, 0, (e+" NumberOfObjects/String").c_str()).To_UTF8();
break;
default:
Summary+=Mpegh3da_signalGroupType[E.Type];
}
if (!Summary.empty())
Fill(Stream_Audio, 0, e.c_str(), Summary, true, true);
}
}
//---------------------------------------------------------------------------
void File_Mpegh3da::Streams_Finish()
{
}
//***************************************************************************
// Buffer - Global
//***************************************************************************
//---------------------------------------------------------------------------
void File_Mpegh3da::Read_Buffer_Continue()
{
if (MustParse_mhaC)
{
mhaC();
MustParse_mhaC=false;
MustParse_mpegh3daFrame=true;
Skip_XX(Element_Size-Element_Offset, "Unknown");
return;
}
if (MustParse_mpegh3daFrame)
{
mpegh3daFrame();
}
}
//***************************************************************************
// Buffer - Per element
//***************************************************************************
//---------------------------------------------------------------------------
void File_Mpegh3da::Header_Parse()
{
//Parsing
int32u MHASPacketType, MHASPacketLabel, MHASPacketLength;
BS_Begin();
escapedValue(MHASPacketType, 3, 8, 8, "MHASPacketType");
escapedValue(MHASPacketLabel, 2, 8, 32, "MHASPacketLabel");
escapedValue(MHASPacketLength, 11, 24, 24, "MHASPacketLength");
BS_End();
FILLING_BEGIN();
if (MHASPacketLabel)
MHASPacketLabels.insert(MHASPacketLabel);
Header_Fill_Code(MHASPacketType, MHASPacketType<Mpegh3da_MHASPacketType_Size?Ztring().From_UTF8(Mpegh3da_MHASPacketType[MHASPacketType]):Ztring().From_CC3(MHASPacketType));
Header_Fill_Size(Element_Offset+MHASPacketLength);
FILLING_END();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::Data_Parse()
{
//Parsing
switch (Element_Code)
{
case 1 : mpegh3daConfig(); break;
case 2 : mpegh3daFrame(); break;
case 3 : BS_Begin(); mae_AudioSceneInfo(); BS_End(); break;
case 6 : Sync(); break;
case 8 : Marker(); break;
case 9 : Crc16(); break;
case 14 : BufferInfo(); break;
case 17 : audioTruncationInfo(); break;
default : Skip_XX(Element_Size-Element_Offset, "Data");
}
if (!Trusted_Get())
Fill(Stream_Audio, 0, "NOK", "NOK", Unlimited, true, true);
}
//***************************************************************************
// Elements
//***************************************************************************
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daConfig()
{
Element_Begin1("mpegh3daConfig");
BS_Begin();
int8u usacSamplingFrequencyIndex;
Get_S1(8, mpegh3daProfileLevelIndication, "mpegh3daProfileLevelIndication"); Param_Info1(Mpegh3da_Profile_Get(mpegh3daProfileLevelIndication));
Get_S1 (5, usacSamplingFrequencyIndex, "usacSamplingFrequencyIndex");
if (usacSamplingFrequencyIndex==0x1f)
Get_S3 (24, usacSamplingFrequency, "usacSamplingFrequency");
else
{
if (usacSamplingFrequencyIndex<Aac_sampling_frequency_Size_Usac)
usacSamplingFrequency=Aac_sampling_frequency[usacSamplingFrequencyIndex];
else
usacSamplingFrequency=0;
}
Get_S1 (3, coreSbrFrameLengthIndex, "coreSbrFrameLengthIndex");
Skip_SB( "cfg_reserved");
Skip_SB( "receiverDelayCompensation");
SpeakerConfig3d(referenceLayout);
FrameworkConfig3d();
mpegh3daDecoderConfig();
TEST_SB_SKIP( "usacConfigExtensionPresent");
mpegh3daConfigExtension();
TEST_SB_END();
BS_End();
Element_End0();
FILLING_BEGIN();
//Filling
if (!Status[IsAccepted])
Accept("MPEG-H 3D Audio");
FILLING_END();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::SpeakerConfig3d(speaker_layout& Layout)
{
int8u speakerLayoutType;
Element_Begin1("SpeakerConfig3d");
Get_S1(2, speakerLayoutType, "speakerLayoutType");
if (speakerLayoutType==0)
{
Get_S1 (6, Layout.ChannelLayout, "CICPspeakerLayoutIdx"); Param_Info2(Aac_Channels_Get(Layout.ChannelLayout), " channels");
}
else
{
int32u numSpeakers;
escapedValue(numSpeakers, 5, 8, 16, "numSpeakers");
numSpeakers++;
Layout.numSpeakers=numSpeakers;
if (speakerLayoutType==1)
{
Layout.CICPspeakerIdxs.resize(numSpeakers);
for (size_t Pos=0; Pos<numSpeakers; Pos++)
{
int8u CICPspeakerIdx;
Get_S1(7, CICPspeakerIdx, "CICPspeakerIdx");
Layout.CICPspeakerIdxs[Pos]=(Aac_OutputChannel)CICPspeakerIdx;
}
}
else if (speakerLayoutType==2)
{
mpegh3daFlexibleSpeakerConfig(Layout);
}
}
Element_End0();
FILLING_BEGIN();
//Finish
if (Status[IsAccepted])
Finish("MPEG-H 3D Audio");
FILLING_END();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daFlexibleSpeakerConfig(speaker_layout& Layout)
{
bool angularPrecision;
Element_Begin1("mpegh3daFlexibleSpeakerConfig");
Get_SB(angularPrecision, "angularPrecision");
for (size_t Pos=0; Pos<Layout.numSpeakers; Pos++)
{
Layout.SpeakersInfo.push_back(speaker_info());
speaker_info& SpeakerInfo=Layout.SpeakersInfo[Layout.SpeakersInfo.size()-1];
mpegh3daSpeakerDescription(SpeakerInfo, angularPrecision);
if (SpeakerInfo.AzimuthAngle && SpeakerInfo.AzimuthAngle!=180)
{
bool alsoAddSymmetricPair;
Get_SB (alsoAddSymmetricPair, "alsoAddSymmetricPair");
if (alsoAddSymmetricPair)
Pos++;
}
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daSpeakerDescription(speaker_info& SpeakerInfo, bool angularPrecision)
{
Element_Begin1("mpegh3daSpeakerDescription");
TESTELSE_SB_SKIP( "isCICPspeakerIdx");
{
int8u CICPspeakerIdx;
Get_S1 (7, CICPspeakerIdx, "CICPspeakerIdx");
if (CICPspeakerIdx<Mpegh3da_SpeakerInfo_Size)
SpeakerInfo=Mpegh3da_SpeakerInfo[CICPspeakerIdx];
else
SpeakerInfo.CICPspeakerIdx=(Aac_OutputChannel)CICPspeakerIdx;
}
TESTELSE_SB_ELSE( "isCICPspeakerIdx");
int8u ElevationClass;
Get_S1(2, ElevationClass, "ElevationClass");
switch (ElevationClass)
{
case 0:
SpeakerInfo.ElevationAngle=0;
break;
case 1:
SpeakerInfo.ElevationAngle=35;
SpeakerInfo.ElevationDirection=false;
break;
case 2:
SpeakerInfo.ElevationAngle=15;
SpeakerInfo.ElevationDirection=true;
break;
case 3:
int8u ElevationAngleIdx;
Get_S1(angularPrecision?7:5, ElevationAngleIdx, "ElevationAngleIdx");
SpeakerInfo.ElevationAngle=ElevationAngleIdx*(angularPrecision?1:5);
if (SpeakerInfo.ElevationAngle)
Get_SB(SpeakerInfo.ElevationDirection, "ElevationDirection");
break;
}
int8u AzimuthAngleIdx;
Get_S1(angularPrecision?8:6, AzimuthAngleIdx, "AzimuthAngleIdx");
SpeakerInfo.AzimuthAngle=AzimuthAngleIdx*(angularPrecision?1:5);
if (SpeakerInfo.AzimuthAngle && SpeakerInfo.AzimuthAngle!=180)
Get_SB(SpeakerInfo.AzimuthDirection, "AzimuthDirection");
Get_SB(SpeakerInfo.isLFE, "isLFE");
SpeakerInfo.CICPspeakerIdx=(Aac_OutputChannel)-1;
TESTELSE_SB_END();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daFrame()
{
Skip_XX(Element_Size, "mpegh3daFrame");
FILLING_BEGIN();
//Filling
if (Status[IsAccepted])
Finish("MPEG-H 3D Audio");
FILLING_END();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::Sync()
{
//Parsing
Skip_B1( "syncword");
}
//---------------------------------------------------------------------------
void File_Mpegh3da::Marker()
{
//Parsing
Info_B1(marker_byte, "marker_byte"); Param_Info1C(marker_byte<Mpegh3da_marker_byte_Size, Mpegh3da_marker_byte[marker_byte]);
}
//---------------------------------------------------------------------------
void File_Mpegh3da::Crc16()
{
//Parsing
Skip_B2( "mhasParity16Data");
}
//---------------------------------------------------------------------------
void File_Mpegh3da::BufferInfo()
{
//Parsing
BS_Begin();
bool mhas_buffer_fullness_present;
Get_SB (mhas_buffer_fullness_present, "mhas_buffer_fullness_present");
if (mhas_buffer_fullness_present)
{
int32u mhas_buffer_fullness;
escapedValue(mhas_buffer_fullness, 15, 39, 71, "mhas_buffer_fullness");
}
BS_End();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::FrameworkConfig3d()
{
numAudioChannels=0;
numAudioObjects=0;
numSAOCTransportChannels=0;
numHOATransportChannels=0;
Element_Begin1("FrameworkConfig3d");
Element_Begin1("Signals3d");
Get_S1(5, bsNumSignalGroups, "bsNumSignalGroups");
bsNumSignalGroups++; Param_Info2(bsNumSignalGroups, " signals");
SignalGroups.resize(bsNumSignalGroups);
for (int8u Pos=0; Pos<bsNumSignalGroups; Pos++)
{
signal_group& E=SignalGroups[Pos];
Element_Begin1("signalGroup");
Get_S1(3, E.Type, "signalGroupType");
escapedValue(E.bsNumberOfSignals, 5, 8, 16, "bsNumberOfSignals");
E.bsNumberOfSignals++;
if (E.Type==SignalGroupTypeChannels)
{
numAudioChannels+=E.bsNumberOfSignals;
TESTELSE_SB_SKIP( "differsFromReferenceLayout");
SpeakerConfig3d(E.Layout);
TESTELSE_SB_ELSE( "differsFromReferenceLayout");
E.Layout=referenceLayout;
TESTELSE_SB_END();
}
else if (E.Type==SignalGroupTypeObject)
{
numAudioObjects+=E.bsNumberOfSignals;
E.Layout.numSpeakers=E.bsNumberOfSignals;
}
else if (E.Type==SignalGroupTypeSAOC)
{
numSAOCTransportChannels+=E.bsNumberOfSignals;
TEST_SB_SKIP( "saocDmxLayoutPresent");
SpeakerConfig3d(E.Layout);
TEST_SB_END();
}
else if (E.Type==SignalGroupTypeHOA)
{
numHOATransportChannels+=E.bsNumberOfSignals;
E.Layout.numSpeakers=E.bsNumberOfSignals;
}
Element_End0();
}
Element_End0();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daDecoderConfig()
{
Elements.clear();
Element_Begin1("mpegh3daDecoderConfig");
escapedValue(numElements, 4, 8, 16, "numElements");
numElements++;
bool elementLengthPresent;
Get_SB (elementLengthPresent, "elementLengthPresent");
for (size_t Pos=0; Pos<numElements; Pos++)
{
Element_Begin1("Element");
int8u usacElementType;
Get_S1(2, usacElementType, "usacElementType"); Element_Info1(Mpegh3da_usacElementType[usacElementType]);
switch (usacElementType)
{
case ID_USAC_SCE:
mpegh3daSingleChannelElementConfig(coreSbrFrameLengthIndex_Mapping[coreSbrFrameLengthIndex].sbrRatioIndex);
Elements.push_back(usac_element(ID_USAC_SCE));
break;
case ID_USAC_CPE:
mpegh3daChannelPairElementConfig(coreSbrFrameLengthIndex_Mapping[coreSbrFrameLengthIndex].sbrRatioIndex);
Elements.push_back(usac_element(ID_USAC_CPE));
break;
case ID_USAC_LFE:
Elements.push_back(usac_element(ID_USAC_LFE));
break;
case ID_USAC_EXT:
mpegh3daExtElementConfig();
Elements.push_back(usac_element(ID_USAC_EXT));
break;
}
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daSingleChannelElementConfig(int8u sbrRatioIndex)
{
Element_Begin1("mpegh3daSingleChannelElementConfig");
mpegh3daCoreConfig();
if (sbrRatioIndex)
SbrConfig();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daChannelPairElementConfig(int8u sbrRatioIndex)
{
int32u nBits=floor(log2(numAudioChannels+numAudioObjects+numHOATransportChannels+numSAOCTransportChannels-1))+1;
int8u stereoConfigIndex=0;
int8u qceIndex;
Element_Begin1("mpegh3daChannelPairElementConfig");
bool enhancedNoiseFilling=mpegh3daCoreConfig();
if(enhancedNoiseFilling)
Skip_SB( "igfIndependentTiling");
if (sbrRatioIndex)
{
SbrConfig();
Get_S1(2, stereoConfigIndex, "stereoConfigIndex");
}
if (stereoConfigIndex) {
Mps212Config(stereoConfigIndex);
}
Get_S1(2, qceIndex, "qceIndex");
if (qceIndex)
{
TEST_SB_SKIP( "shiftIndex0");
Skip_BS(nBits, "shiftChannel0");
TEST_SB_END();
}
TEST_SB_SKIP( "shiftIndex1");
Skip_BS(nBits, "shiftChannel1");
TEST_SB_END();
if (sbrRatioIndex==0 && qceIndex==0)
Skip_SB( "lpdStereoIndex");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daExtElementConfig()
{
Element_Begin1("mpegh3daExtElementConfig");
int32u usacExtElementType;
escapedValue(usacExtElementType, 4, 8, 16, "usacExtElementType"); Element_Level--; Element_Info1C(usacExtElementType<Mpegh3da_usacExtElementType_Size, Mpegh3da_usacExtElementType[usacExtElementType]); Element_Level++;
int32u usacExtElementConfigLength;
escapedValue(usacExtElementConfigLength, 4, 8, 16, "usacExtElementConfigLength");
int32u usacExtElementDefaultLength=0;
TEST_SB_SKIP( "usacExtElementDefaultLengthPresent");
escapedValue(usacExtElementDefaultLength, 8, 16, 0, "usacExtElementDefaultLength"); //TODO: check if call is valid
usacExtElementDefaultLength++;
TEST_SB_END();
Skip_SB( "usacExtElementPayloadFrag");
size_t Remain_Before=BS->Remain();
switch (usacExtElementType)
{
case ID_EXT_ELE_FILL:
break; // No configuration element
//case ID_EXT_ELE_MPEGS:
//TODO: SpatialSpecificConfig();
//break;
//case ID_EXT_ELE_SAOC:
//TODO: SAOCSpecificConfig();
//break;
case ID_EXT_ELE_AUDIOPREROLL:
break; // No configuration element
case ID_EXT_ELE_UNI_DRC:
//if (referenceLayout.ChannelLayout!=19) //TEMP
mpegh3daUniDrcConfig();
break;
case ID_EXT_ELE_OBJ_METADATA:
ObjectMetadataConfig();
break;
//case ID_EXT_ELE_SAOC_3D:
// SAOC3DSpecificConfig();
// break;
//case ID_EXT_ELE_HOA:
//HOAConfig();
//break;
case ID_EXT_ELE_FMT_CNVRTR:
break; // No configuration element
//case ID_EXT_ELE_MCT:
//MCTConfig();
//break;
case ID_EXT_ELE_TCC:
TccConfig();
break;
//case ID_EXT_ELE_HOA_ENH_LAYER:
//HOAEnhConfig();
//break;
//case ID_EXT_ELE_HREP:
//HREPConfig(current_signal_group);
//break;
//case ID_EXT_ELE_ENHANCED_OBJ_METADATA:
//EnhancedObjectMetadataConfig();
//break;
break;
default:
if (usacExtElementConfigLength)
Skip_BS(usacExtElementConfigLength*8, "reserved");
break;
}
if (BS->Remain()+usacExtElementConfigLength*8>Remain_Before)
{
size_t Size=BS->Remain()+usacExtElementConfigLength*8-Remain_Before;
int8u Padding=1;
if (Size<8)
Peek_S1((int8u)Size, Padding);
if (Padding && Remain_Before!=BS->Remain() && usacExtElementType!=ID_EXT_ELE_OBJ_METADATA)
Fill(Stream_Audio, 0, "NOK", "NOK", Unlimited, true, true);
Skip_BS(Size, Padding?"(Unknown)":"Padding");
}
Element_End0();
}
//---------------------------------------------------------------------------
bool File_Mpegh3da::mpegh3daCoreConfig()
{
bool enhancedNoiseFilling;
Element_Begin1("mpegh3daCoreConfig");
Skip_SB( "tw_mdct");
Skip_SB( "fullbandLpd");
Skip_SB( "noiseFilling");
TEST_SB_GET(enhancedNoiseFilling, "enhancedNoiseFilling");
Skip_SB( "igfUseEnf");
Skip_SB( "igfUseHighRes");
Skip_SB( "igfUseWhitening");
Skip_SB( "igfAfterTnsSynth");
Skip_S1(5, "igfStartIndex");
Skip_S1(4, "igfStopIndex");
TEST_SB_END();
Element_End0();
return enhancedNoiseFilling;
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daUniDrcConfig()
{
Element_Begin1("mpegh3daUniDrcConfig");
int8u drcCoefficientsUniDrcCount;
Get_S1(3, drcCoefficientsUniDrcCount, "drcCoefficientsUniDrcCount");
int8u drcInstructionsUniDrcCount;
Get_S1(6, drcInstructionsUniDrcCount, "drcInstructionsUniDrcCount");
Element_Begin1("mpegh3daUniDrcChannelLayout");
Get_S1 (7, baseChannelCount, "baseChannelCount");
Element_End0();
if (!drcCoefficientsUniDrcCount)
Fill(Stream_Audio, 0, "TEMP_drcCoefficientsUniDrcCount", drcCoefficientsUniDrcCount); //TEMP
for (int8u Pos=0; Pos<drcCoefficientsUniDrcCount; Pos++)
drcCoefficientsUniDrc(); // in File_USAC.cpp
for (int8u Pos=0; Pos<drcInstructionsUniDrcCount; Pos++)
{
int8u drcInstructionsType;
Get_S1(Peek_SB()?2:1, drcInstructionsType, "drcInstructionsType");
int8u ID;
if (drcInstructionsType==2)
Get_S1 (7, ID, "mae_groupID");
else if (drcInstructionsType==3)
Get_S1 (5, ID, "mae_groupPresetID");
else
ID=0;
drcInstructionsUniDrc(false, true); // in File_USAC.cpp
Mpegh3da_drcInstructionsUniDrc_Data[drcInstructionsType][ID][drcInstructionsUniDrc_Data.begin()->first]=drcInstructionsUniDrc_Data.begin()->second;
drcInstructionsUniDrc_Data.clear();
}
TEST_SB_SKIP( "uniDrcConfigExtPresent");
uniDrcConfigExtension(); // in File_USAC.cpp
TEST_SB_END();
TEST_SB_SKIP( "loudnessInfoSetPresent");
mpegh3daLoudnessInfoSet();
TEST_SB_END();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::downmixConfig()
{
Element_Begin1("downmixConfig");
int8u downmixConfigType;
Get_S1 (2, downmixConfigType, "downmixConfigType");
switch (downmixConfigType)
{
case 0:
case 2:
{
bool passiveDownmixFlag;
Get_SB (passiveDownmixFlag, "passiveDownmixFlag");
if (!passiveDownmixFlag)
Skip_S1(3, "phaseAlignStrength");
Skip_SB( "immersiveDownmixFlag");
}
break;
}
switch (downmixConfigType)
{
case 1:
case 2:
{
Skip_S1(5, "DownmixMatrixSet - TODO");
}
break;
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daLoudnessInfoSet()
{
Element_Begin1("mpegh3daLoudnessInfoSet");
int8u loudnessInfoCount;
Get_S1(6, loudnessInfoCount, "loudnessInfoCount");
for(int8u Pos=0; Pos<loudnessInfoCount; Pos++)
{
int8u loudnessInfoType;
Get_S1(2, loudnessInfoType, "loudnessInfoType");
int8u ID;
if (loudnessInfoType==1 || loudnessInfoType==2)
Get_S1 (7, ID, "mae_groupID");
else if (loudnessInfoType==3)
Get_S1 (5, ID, "mae_groupPresetID");
else
ID=0;
bool IsNOK=loudnessInfo(false); // in File_USAC.cpp
Mpegh3da_loudnessInfo_Data[loudnessInfoType][ID].Data[0][loudnessInfo_Data[0].begin()->first]=loudnessInfo_Data[0].begin()->second;
loudnessInfo_Data[0].clear();
if (IsNOK)
{
Element_End0();
return;
}
}
TEST_SB_SKIP( "loudnessInfoAlbumPresent");
int8u loudnessInfoAlbumCount;
Get_S1(6, loudnessInfoAlbumCount, "loudnessInfoAlbumCount");
for (int8u Pos=0; Pos<loudnessInfoAlbumCount; Pos++)
{
loudnessInfo(true); // in File_USAC.cpp
Mpegh3da_loudnessInfo_Data[0][0].Data[1][loudnessInfo_Data[1].begin()->first]=loudnessInfo_Data[1].begin()->second;
loudnessInfo_Data[1].clear();
}
TEST_SB_END();
TEST_SB_SKIP( "loudnessInfoSetExtensionPresent");
loudnessInfoSetExtension(); // in File_USAC.cpp
TEST_SB_END();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::ObjectMetadataConfig()
{
Element_Begin1("ObjectMetadataConfig");
Skip_SB( "lowDelayMetadataCoding");
TESTELSE_SB_SKIP( "hasCoreLength");
TESTELSE_SB_ELSE( "hasCoreLength");
Skip_S1(6, "frameLength");
TESTELSE_SB_END();
TEST_SB_SKIP("hasScreenRelativeObjects");
size_t num_objects=num_objects_Get();
for (int16u Pos=0; Pos<num_objects; Pos++)
{
Skip_SB( "isScreenRelativeObject");
}
TEST_SB_END();
Skip_SB( "hasDynamicObjectPriority");
Skip_SB( "hasUniformSpread");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::SAOC3DSpecificConfig()
{
int8u bsSamplingFrequencyIndex, bsNumSaocDmxChannels, bsNumSaocDmxObjects, bsNumSaocObjects;
int32u NumSaocChannels=0, NumInputSignals=0;
Element_Begin1("SAOC3DSpecificConfig");
Get_S1(4, bsSamplingFrequencyIndex, "bsSamplingFrequencyIndex");
if (bsSamplingFrequencyIndex==15)
Skip_S3(24, "bsSamplingFrequency");
Skip_S1(3, "bsFreqRes");
Skip_SB( "bsDoubleFrameLengthFlag");
Get_S1(5, bsNumSaocDmxChannels, "bsNumSaocDmxChannels");
Get_S1(5, bsNumSaocDmxObjects, "bsNumSaocDmxObjects");
Skip_SB( "bsDecorrelationMethod");
if (bsNumSaocDmxChannels)
{
speaker_layout saocChannelLayout;
SpeakerConfig3d(saocChannelLayout);
NumSaocChannels=SAOC3DgetNumChannels(saocChannelLayout);
NumInputSignals+=NumSaocChannels;
}
Get_S1(8, bsNumSaocObjects , "bsNumSaocObjects");
NumInputSignals+=bsNumSaocObjects;
for (int8u Pos=0; Pos<NumSaocChannels; Pos++)
{
for(int8u Pos2=Pos+1; Pos2<NumSaocChannels; Pos2++)
Skip_SB( "bsRelatedTo");
}
for (int8u Pos=NumSaocChannels; Pos<NumInputSignals; Pos++)
{
for(int8u Pos2=Pos+1; Pos2<NumInputSignals; Pos2++)
Skip_SB( "bsRelatedTo");
}
Skip_SB( "bsOneIOC");
TEST_SB_SKIP( "bsSaocDmxMethod");
SAOC3DgetNumChannels(referenceLayout);
TEST_SB_END();
TEST_SB_SKIP( "bsDualMode");
Skip_S1(5, "bsBandsLow");
TEST_SB_END();
TEST_SB_SKIP( "bsDcuFlag");
Skip_SB( "bsDcuMandatory");
TEST_SB_SKIP( "bsDcuDynamic");
Skip_SB( "bsDcuMode");
Skip_S1(4, "bsDcuParam");
TEST_SB_END();
TEST_SB_END();
Skip_S1(BS->Remain()%8, "byte_align");
//TODO: SAOC3DExtensionConfig();
Element_End0();
}
//---------------------------------------------------------------------------
int32u File_Mpegh3da::SAOC3DgetNumChannels(speaker_layout Layout)
{
int32u ToReturn=Layout.numSpeakers;
for (int32u Pos=0; Pos<Layout.numSpeakers; Pos++)
{
if (Layout.SpeakersInfo.size()>Pos && Layout.SpeakersInfo[Pos].isLFE)
ToReturn--;
}
return ToReturn;
}
//---------------------------------------------------------------------------
void File_Mpegh3da::MCTConfig()
{
Element_Begin1("MCTConfig");
for(int32u chan=0; chan<numAudioChannels; ++chan) // bsNumberOfSignals[grp] but which grp?
{
Skip_SB( "mctChanMask");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::TccConfig()
{
Element_Begin1("TccConfig");
for(int32u Pos=0; Pos<numElements; Pos++)
{
if(Elements.size()>Pos && (Elements[Pos].Type==ID_USAC_SCE || Elements[Pos].Type==ID_USAC_CPE))
Skip_S1(2, "tccMode");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::EnhancedObjectMetadataConfig()
{
Element_Begin1("EnhancedObjectMetadataConfig");
bool hasCommonGroupExcludedSectors=false;
TEST_SB_SKIP( "hasDiffuseness");
Skip_SB( "hasCommonGroupDiffuseness");
TEST_SB_END();
TEST_SB_SKIP( "hasExcludedSectors");
TEST_SB_GET(hasCommonGroupExcludedSectors, "hasCommonGroupExcludedSectors");
Skip_SB( "useOnlyPredefinedSectors");
TEST_SB_END();
TEST_SB_END();
TEST_SB_SKIP( "hasClosestSpeakerCondition");
Skip_S1(7, "closestSpeakerThresholdAngle");
TEST_SB_END();
size_t num_objects=num_objects_Get();
for (int8u Pos=0; Pos<num_objects; Pos++)
{
TEST_SB_SKIP( "hasDivergence");
Skip_S1(6, "divergenceAzimuthRange");
TEST_SB_END();
if (!hasCommonGroupExcludedSectors)
Skip_SB( "useOnlyPredefinedSectors");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mpegh3daConfigExtension()
{
Element_Begin1("mpegh3daConfigExtension");
int32u numConfigExtensions;
escapedValue(numConfigExtensions, 2, 4, 8, "numConfigExtensions");
numConfigExtensions++;
for (int32u Pos=0; Pos<numConfigExtensions; Pos++)
{
Element_Begin1("configExtension");
int32u usacConfigExtType;
escapedValue(usacConfigExtType, 4, 8, 16, "usacConfigExtType"); Element_Info1C(usacConfigExtType<Mpegh3da_usacConfigExtType_Size, Mpegh3da_usacConfigExtType[usacConfigExtType]);
int32u usacConfigExtLength;
escapedValue(usacConfigExtLength, 4, 8, 16, "usacConfigExtLength");
if (!usacConfigExtLength)
{
Element_End0();
continue;
}
size_t Remain_Before=BS->Remain();
switch ((UsacConfigExtType)usacConfigExtType)
{
case ID_CONFIG_EXT_FILL:
while (usacConfigExtLength)
{
usacConfigExtLength--;
Skip_S1(8, "fill_byte"); // should be '10100101'
}
break;
case ID_CONFIG_EXT_DOWNMIX:
downmixConfig();
break;
case ID_CONFIG_EXT_LOUDNESS_INFO:
mpegh3daLoudnessInfoSet();
break;
case ID_CONFIG_EXT_AUDIOSCENE_INFO:
mae_AudioSceneInfo();
break;
//case ID_CONFIG_EXT_HOA_MATRIX:
// HoaRenderingMatrixSet();
// break;
case ID_CONFIG_EXT_ICG:
ICGConfig();
break;
case ID_CONFIG_EXT_SIG_GROUP_INFO:
SignalGroupInformation();
break;
case ID_CONFIG_EXT_COMPATIBLE_PROFILE_LEVEL_SET:
CompatibleProfileLevelSet();
break;
default:
Skip_BS(usacConfigExtLength*8, "reserved");
}
if (BS->Remain()+usacConfigExtLength*8>Remain_Before)
{
size_t Size=BS->Remain()+usacConfigExtLength*8-Remain_Before;
int8u Padding=1;
if (Size<8)
Peek_S1((int8u)Size, Padding);
if (Padding && Remain_Before!=BS->Remain() && usacConfigExtType!=ID_CONFIG_EXT_DOWNMIX && usacConfigExtType!=ID_CONFIG_EXT_HOA_MATRIX)
Fill(Stream_Audio, 0, "NOK", "NOK", Unlimited, true, true);
Skip_BS(Size, Padding?"(Unknown)":"Padding");
}
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::SignalGroupInformation()
{
Element_Begin1("SignalGroupInformation");
for (int8u Pos=0; Pos<bsNumSignalGroups+1; Pos++)
{
Skip_S1(3, "groupPriority");
Skip_SB( "fixedPosition");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::CompatibleProfileLevelSet()
{
Element_Begin1("CompatibleProfileLevelSet");
int8u bsNumCompatibleSets;
Get_S1 (4, bsNumCompatibleSets, "bsNumCompatibleSets");
Skip_S1(4, "reserved");
mpegh3daCompatibleProfileLevelSet.resize(bsNumCompatibleSets+1);
for (int8u Pos=0; Pos<=bsNumCompatibleSets; Pos++)
{
Get_S1(8, mpegh3daCompatibleProfileLevelSet[Pos], "CompatibleSetIndication"); Param_Info1(Mpegh3da_Profile_Get(mpegh3daCompatibleProfileLevelSet[Pos]));
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::HoaRenderingMatrixSet()
{
Element_Begin1("HoaRenderingMatrixSet - TODO");
Skip_S1(5, "numOfHoaRenderingMatrices");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::ICGConfig()
{
Element_Begin1("ICGConfig");
TEST_SB_SKIP( "ICPresent");
for (int32u Pos=0; Pos<numElements; Pos++)
{
if (Elements.size()>Pos && Elements[Pos].Type==ID_USAC_CPE)
Skip_SB( "ICinCPE");
}
TEST_SB_SKIP( "ICGPreAppliedPresent");
for (int32u Pos=0; Pos<numElements; Pos++)
{
if (Elements.size()>Pos && Elements[Pos].Type==ID_USAC_CPE)
Skip_SB( "ICGPreAppliedCPE");
}
TEST_SB_END();
TEST_SB_END();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_AudioSceneInfo()
{
Groups.clear();
SwitchGroups.clear();
GroupPresets.clear();
Element_Begin1("mae_AudioSceneInfo");
bool mae_isMainStream;
TESTELSE_SB_GET (mae_isMainStream, "mae_isMainStream");
TEST_SB_SKIP( "mae_audioSceneInfoIDPresent");
Get_S1 (8, audioSceneInfoID, "mae_audioSceneInfoID");
TEST_SB_END();
int8u mae_numGroups;
Get_S1(7, mae_numGroups, "mae_numGroups");
mae_GroupDefinition(mae_numGroups);
int8u mae_numSwitchGroups;
Get_S1(5, mae_numSwitchGroups, "mae_numSwitchGroups");
mae_SwitchGroupDefinition(mae_numSwitchGroups);
int8u mae_numGroupPresets;
Get_S1(5, mae_numGroupPresets, "mae_numGroupPresets");
mae_GroupPresetDefinition(mae_numGroupPresets);
mae_Data(mae_numGroups, mae_numGroupPresets);
Skip_S1(7, "mae_metaDataElementIDmaxAvail");
TESTELSE_SB_ELSE( "mae_isMainStream");
Skip_S1(7, "mae_bsMetaDataElementIDoffset");
Skip_S1(7, "mae_metaDataElementIDmaxAvail");
TESTELSE_SB_END();
Element_End0();
isMainStream=mae_isMainStream;
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_GroupDefinition(int8u numGroups)
{
Element_Begin1("mae_GroupDefinition");
Groups.resize(numGroups);
for (int8u Pos=0; Pos<numGroups; Pos++)
{
Element_Begin1("mae_group");
group& G=Groups[Pos];
Get_S1 (7, G.ID, "mae_groupID");
Element_Info1(Ztring::ToZtring(G.ID));
Get_SB (G.allowOnOff, "mae_allowOnOff");
Get_SB (G.defaultOnOff, "mae_defaultOnOff");
TEST_SB_SKIP( "mae_allowPositionInteractivity");
Skip_S1(7, "mae_interactivityMinAzOffset");
Skip_S1(7, "mae_interactivityMaxAzOffset");
Skip_S1(5, "mae_interactivityMinElOffset");
Skip_S1(5, "mae_interactivityMaxElOffset");
Skip_S1(4, "mae_interactivityMinDistFactor");
Skip_S1(4, "mae_interactivityMaxDistFactor");
TEST_SB_END();
TEST_SB_SKIP( "mae_allowGainInteractivity");
Skip_S1(6, "mae_interactivityMinGain");
Skip_S1(5, "mae_interactivityMaxGain");
TEST_SB_END();
int8u mae_bsGroupNumMembers;
Get_S1(7, mae_bsGroupNumMembers, "mae_bsGroupNumMembers");
mae_bsGroupNumMembers++;
G.MemberID.resize(mae_bsGroupNumMembers);
TESTELSE_SB_SKIP( "mae_hasConjunctMembers");
int8u mae_startID;
Get_S1 (7, mae_startID, "mae_startID");
for (int8u Pos2=0; Pos2<mae_bsGroupNumMembers; Pos2++)
G.MemberID[Pos2]=mae_startID++;
TESTELSE_SB_ELSE( "mae_hasConjunctMembers");
for (int8u Pos2=0; Pos2<mae_bsGroupNumMembers; Pos2++)
Get_S1 (7, G.MemberID[Pos2], "mae_metaDataElementID");
TESTELSE_SB_END();
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_SwitchGroupDefinition(int8u numSwitchGroups)
{
Element_Begin1("mae_SwitchGroupDefinition");
SwitchGroups.resize(numSwitchGroups);
for(int8u Pos=0; Pos<numSwitchGroups; Pos++)
{
Element_Begin1("mae_switchGroup");
switch_group& S=SwitchGroups[Pos];
Get_S1 (5, S.ID, "mae_switchGroupID");
Element_Info1(Ztring::ToZtring(S.ID));
TESTELSE_SB_GET(S.allowOnOff, "mae_switchGroupAllowOnOff");
Get_SB (S.defaultOnOff, "mae_switchGroupDefaultOnOff");
TESTELSE_SB_ELSE( "mae_switchGroupAllowOnOff");
S.defaultOnOff=false;
TESTELSE_SB_END();
int8u mae_bsSwitchGroupNumMembers;
Get_S1(5, mae_bsSwitchGroupNumMembers, "mae_bsSwitchGroupNumMembers");
mae_bsSwitchGroupNumMembers++;
S.MemberID.resize(mae_bsSwitchGroupNumMembers);
for (int8u Pos2=0; Pos2<mae_bsSwitchGroupNumMembers; Pos2++)
Get_S1 (7, S.MemberID[Pos2], "mae_switchGroupMemberID");
Get_S1 (7, S.DefaultGroupID, "mae_switchGroupDefaultGroupID");
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_GroupPresetDefinition(int8u numGroupPresets)
{
Element_Begin1("mae_GroupPresetDefinition");
GroupPresets.resize(numGroupPresets);
for (int8u Pos=0; Pos<numGroupPresets; Pos++)
{
Element_Begin1("mae_groupPreset");
group_preset& P=GroupPresets[Pos];
Get_S1 (5, P.ID, "mae_groupPresetID");
Element_Info1(Ztring::ToZtring(P.ID));
Get_S1 (5, P.Kind, "mae_groupPresetKind");
int8u mae_bsGroupPresetNumConditions;
Get_S1 (4, mae_bsGroupPresetNumConditions, "mae_bsGroupPresetNumConditions");
mae_bsGroupPresetNumConditions++;
P.Conditions.resize(mae_bsGroupPresetNumConditions);
for (int8u Pos2=0; Pos2<mae_bsGroupPresetNumConditions; Pos2++)
{
Element_Begin1("mae_groupPreset");
Get_S1 (7, P.Conditions[Pos2].ReferenceID, "mae_groupPresetReferenceID");
Element_Info1(P.Conditions[Pos2].ReferenceID);
TEST_SB_GET (P.Conditions[Pos2].ConditionOnOff, "mae_groupPresetConditionOnOff");
Skip_SB( "mae_groupPresetDisableGainInteractivity");
TEST_SB_SKIP( "mae_groupPresetGainFlag");
Skip_S1(8, "mae_groupPresetGain");
TEST_SB_END();
Skip_SB( "mae_groupPresetDisablePositionInteractivity");
TEST_SB_SKIP( "mae_groupPresetPositionFlag");
Skip_S1(8, "mae_groupPresetAzOffset");
Skip_S1(6, "mae_groupPresetElOffset");
Skip_S1(4, "mae_groupPresetDistFactor");
TEST_SB_END();
TEST_SB_END();
Element_End0();
}
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_Data(int8u numGroups, int8u numGroupPresets)
{
Element_Begin1("mae_Data");
int8u mae_numDataSets;
Get_S1(4, mae_numDataSets, "mae_numDataSets");
for (int8u Pos=0; Pos<mae_numDataSets; Pos++)
{
Element_Begin1("mae_data");
int8u mae_dataType;
Get_S1(4, mae_dataType, "mae_dataType");
int16u mae_dataLength;
Get_S2(16, mae_dataLength, "mae_dataLength");
size_t Remain_Before=BS->Remain();
switch ((MaeDataType)mae_dataType)
{
case ID_MAE_GROUP_DESCRIPTION:
case ID_MAE_SWITCHGROUP_DESCRIPTION:
case ID_MAE_GROUP_PRESET_DESCRIPTION:
mae_Description((MaeDataType)mae_dataType);
break;
case ID_MAE_GROUP_CONTENT:
mae_ContentData();
break;
case ID_MAE_GROUP_COMPOSITE:
mae_CompositePair();
break;
case ID_MAE_SCREEN_SIZE:
mae_ProductionScreenSizeData();
break;
case ID_MAE_DRC_UI_INFO:
mae_DrcUserInterfaceInfo(mae_dataLength);
break;
case ID_MAE_SCREEN_SIZE_EXTENSION:
mae_ProductionScreenSizeDataExtension();
break;
case ID_MAE_GROUP_PRESET_EXTENSION:
mae_GroupPresetDefinitionExtension(numGroupPresets);
break;
case ID_MAE_LOUDNESS_COMPENSATION:
mae_LoudnessCompensationData(numGroups, numGroupPresets);
break;
default:
Skip_BS(mae_dataLength*8, "reserved");
}
if (BS->Remain()+mae_dataLength*8>Remain_Before)
{
size_t Size=BS->Remain()+mae_dataLength*8-Remain_Before;
int8u Padding=1;
if (Size<8)
Peek_S1((int8u)Size, Padding);
if (Padding)
Fill(Stream_Audio, 0, "NOK", "NOK", Unlimited, true, true);
Skip_BS(Size, Padding?"(Unknown)":"Padding");
}
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_Description(MaeDataType type)
{
Element_Info1("mae_Description");
Element_Begin1("mae_Description");
int8u mae_bsNumDescriptionBlocks;
Get_S1(7, mae_bsNumDescriptionBlocks, "mae_bsNumDescriptionBlocks");
mae_bsNumDescriptionBlocks++;
for (int8u Pos=0; Pos<mae_bsNumDescriptionBlocks; Pos++)
{
Element_Begin1("mae_descriptionGroup");
int8u ID;
switch (type)
{
case ID_MAE_GROUP_DESCRIPTION:
Get_S1 (7, ID, "mae_descriptionGroupID");
break;
case ID_MAE_SWITCHGROUP_DESCRIPTION:
Get_S1 (5, ID, "mae_descriptionSwitchGroupID");
break;
case ID_MAE_GROUP_PRESET_DESCRIPTION:
Get_S1 (5, ID, "mae_descriptionGroupPresetID");
break;
default:;
}
Element_Info1(ID);
int8u mae_bsNumDescLanguages;
Get_S1(4, mae_bsNumDescLanguages, "mae_bsNumDescLanguages");
mae_bsNumDescLanguages++;
for (int8u Pos2=0; Pos2<mae_bsNumDescLanguages; Pos2++)
{
Element_Begin1("mae_bsDescription");
int32u mae_bsDescriptionLanguage;
Get_S3 (24, mae_bsDescriptionLanguage, "mae_bsDescriptionLanguage");
string Language;
for (int i=16; i>=0; i-=8)
{
char LanguageChar=char(mae_bsDescriptionLanguage>>i);
if (LanguageChar)
Language+=LanguageChar;
}
Param_Info1(Language);
Element_Info1(Language);
int8u mae_bsDescriptionDataLength;
Get_S1(8, mae_bsDescriptionDataLength, "mae_bsDescriptionDataLength");
mae_bsDescriptionDataLength++;
string Description;
Description.reserve(mae_bsDescriptionDataLength);
for (int8u Pos3=0; Pos3<mae_bsDescriptionDataLength; Pos3++)
{
int8u mae_descriptionData;
Get_S1 (8, mae_descriptionData, "mae_descriptionData");
Description+=(char)mae_descriptionData;
}
Param_Info1(Ztring().From_UTF8(Description));
Element_Info1(Ztring().From_UTF8(Description));
switch (type)
{
case ID_MAE_GROUP_DESCRIPTION:
for (size_t i=0; i<Groups.size(); i++)
if (Groups[i].ID==ID)
Groups[i].Description[Language]=Description;
break;
case ID_MAE_SWITCHGROUP_DESCRIPTION:
for (size_t i=0; i<SwitchGroups.size(); i++)
if (SwitchGroups[i].ID==ID)
SwitchGroups[i].Description[Language]=Description;
break;
case ID_MAE_GROUP_PRESET_DESCRIPTION:
for (size_t i=0; i<GroupPresets.size(); i++)
if (GroupPresets[i].ID==ID)
GroupPresets[i].Description[Language]=Description;
break;
default: ;
}
Element_End0();
}
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_ContentData()
{
Element_Info1("mae_ContentData");
Element_Begin1("mae_ContentData");
int8u mae_bsNumContentDataBlocks;
Get_S1(7, mae_bsNumContentDataBlocks, "mae_bsNumContentDataBlocks");
for (int8u Pos=0; Pos<mae_bsNumContentDataBlocks+1; Pos++)
{
Element_Begin1("mae_ContentDataGroup");
int8u ID, Kind;
Get_S1 (7, ID, "mae_ContentDataGroupID");
Element_Info1(ID);
Get_S1 (4, Kind, "mae_contentKind");
Param_Info1C(Kind<Mpegh3da_contentKind_Size, Mpegh3da_contentKind[Kind]);
Element_Info1C(Kind<Mpegh3da_contentKind_Size, Mpegh3da_contentKind[Kind]);
string Language;
TEST_SB_SKIP( "mae_hasContentLanguage");
int32u mae_contentLanguage;
Get_S3 (24, mae_contentLanguage, "mae_contentLanguage");
for (int i=16; i>=0; i-=8)
{
char LanguageChar=char(mae_contentLanguage>>i);
if (LanguageChar)
Language+=LanguageChar;
}
Param_Info1(Language);
Element_Info1(Language);
TEST_SB_END();
for (size_t i=0; i<Groups.size(); i++)
if (Groups[i].ID==ID)
{
Groups[i].Language=Language;
Groups[i].Kind=Kind;
}
Element_End0();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_CompositePair()
{
Element_Begin1("mae_CompositePair");
int8u mae_bsNumCompositePairs;
Get_S1(7, mae_bsNumCompositePairs, "mae_bsNumCompositePairs");
for (int8u Pos=0; Pos<mae_bsNumCompositePairs+1; Pos++)
{
Skip_S1(7, "mae_CompositeElementID0");
Skip_S1(7, "mae_CompositeElementID1");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_ProductionScreenSizeData()
{
Element_Begin1("mae_ProductionScreenSizeData");
TEST_SB_SKIP( "hasNonStandardScreenSize");
Skip_S2(9, "bsScreenSizeAz");
Skip_S2(9, "bsScreenSizeTopEl");
Skip_S2(9, "bsScreenSizeBottomEl");
TEST_SB_END();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_DrcUserInterfaceInfo(int16u dataLength)
{
Element_Begin1("mae_DrcUserInterfaceInfo");
int8u version;
Get_S1(2, version, "version");
if (version==0)
{
int8u bsNumTargetLoudnessConditions;
Get_S1(3, bsNumTargetLoudnessConditions, "bsNumTargetLoudnessConditions");
int16u bsNumTargetLoudnessConditions_Real;
if (dataLength>2)
bsNumTargetLoudnessConditions_Real=(dataLength*8-(2+3))/(6+16);
else
bsNumTargetLoudnessConditions_Real=0;
if (bsNumTargetLoudnessConditions!=bsNumTargetLoudnessConditions_Real)
Param_Info1("Error");
for (int16u Pos=0; Pos<bsNumTargetLoudnessConditions_Real; Pos++)
{
Skip_S1(6, "bsTargetLoudnessValueUpper");
Skip_S2(16, "drcSetEffectAvailable");
}
}
else
{
Skip_BS((dataLength-2)*8, "reserved");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_ProductionScreenSizeDataExtension()
{
Element_Begin1("mae_ProductionScreenSizeDataExtension");
TEST_SB_SKIP( "mae_overwriteProductionScreenSizeData");
Skip_S2(10, "bsScreenSizeLeftAz");
Skip_S2(10, "bsScreenSizeRightAz");
TEST_SB_END();
int8u mae_NumPresetProductionScreens;
Get_S1(5, mae_NumPresetProductionScreens, "mae_NumPresetProductionScreens");
for (int8u Pos=0; Pos< mae_NumPresetProductionScreens; Pos++)
{
Skip_S1(5, "mae_productionScreenGroupPresetID");
TEST_SB_SKIP( "mae_hasNonStandardScreenSize");
TESTELSE_SB_SKIP( "isCenteredInAzimuth");
Skip_S2(9, "bsScreenSizeAz");
TESTELSE_SB_ELSE( "isCenteredInAzimuth");
Skip_S2(10, "bsScreenSizeLeftAz");
Skip_S2(10, "bsScreenSizeRightAz");
TESTELSE_SB_END();
Skip_S2(9, "bsScreenSizeTopEl");
Skip_S2(9, "bsScreenSizeBottomEl");
TEST_SB_END();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_GroupPresetDefinitionExtension(int8u numGroupPresets)
{
Element_Begin1("mae_GroupPresetDefinitionExtension");
for (int8u Pos=0; Pos<numGroupPresets; Pos++)
{
TEST_SB_SKIP( "mae_hasSwitchGroupConditions");
int8u Temp=Pos<GroupPresets.size()?GroupPresets[Pos].Conditions.size():0;
for(int8u Pos2=0; Pos2<Temp; Pos2++)
Skip_SB( "mae_isSwitchGroupCondition");
TEST_SB_END();
TEST_SB_SKIP( "mae_hasDownmixIdGroupPresetExtensions");
int8u mae_numDownmixIdGroupPresetExtensions;
Get_S1(5, mae_numDownmixIdGroupPresetExtensions, "mae_numDownmixIdGroupPresetExtensions");
for (int8u Pos2=1; Pos2<mae_numDownmixIdGroupPresetExtensions+1; Pos2++)
{
Skip_S1(7, "mae_groupPresetDownmixId");
int8u mae_bsGroupPresetNumConditions;
Get_S1(4, mae_bsGroupPresetNumConditions, "mae_bsGroupPresetNumConditions");
for (int8u Pos3=0; Pos3<mae_bsGroupPresetNumConditions+1; Pos3++)
{
TESTELSE_SB_SKIP( "mae_isSwitchGroupCondition");
Skip_S1(5, "mae_groupPresetSwitchGroupID");
TESTELSE_SB_ELSE( "mae_isSwitchGroupCondition");
Skip_S1(7, "mae_groupPresetGroupID");
TESTELSE_SB_END();
TEST_SB_SKIP( "mae_groupPresetConditionOnOff");
Skip_SB( "mae_groupPresetDisableGainInteractivity");
TEST_SB_SKIP( "mae_groupPresetGainFlag");
Skip_S1(8, "mae_groupPresetGain");
TEST_SB_END();
Skip_SB( "mae_groupPresetDisablePositionInteractivity");
TEST_SB_SKIP( "mae_groupPresetPositionFlag");
Skip_S1(8, "mae_groupPresetAzOffset");
Skip_S1(6, "mae_groupPresetElOffset");
Skip_S1(4, "mae_groupPresetDistFactor");
TEST_SB_END();
TEST_SB_END();
}
}
TEST_SB_END();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mae_LoudnessCompensationData(int8u numGroups, int8u numGroupPresets)
{
Element_Begin1("mae_LoudnessCompensationData");
TEST_SB_SKIP( "mae_loudnessCompGroupLoudnessPresent");
for (int8u Pos=0; Pos<numGroups; Pos++)
Skip_S1(8, "mae_bsLoudnessCompGroupLoudness");
TEST_SB_END();
TEST_SB_SKIP( "mae_loudnessCompDefaultParamsPresent");
for (int8u Pos=0; Pos<numGroups; Pos++)
Skip_SB( "mae_loudnessCompDefaultIncludeGroup");
TEST_SB_SKIP( "mae_loudnessCompDefaultMinMaxGainPresent");
Skip_S1(4, "mae_bsLoudnessCompDefaultMinGain");
Skip_S1(4, "mae_bsLoudnessCompDefaultMaxGain");
TEST_SB_END();
TEST_SB_END();
for (int8u Pos=0; Pos<numGroupPresets; Pos++)
{
TEST_SB_SKIP( "mae_loudnessCompPresetParamsPresent");
for (int8u Pos2=0; Pos2<numGroups; Pos2++)
Skip_SB( "mae_loudnessCompPresetIncludeGroup");
TEST_SB_SKIP( "mae_loudnessCompPresetMinMaxGainPresent");
Skip_S1(4, "mae_bsLoudnessCompPresetMinGain");
Skip_S1(4, "mae_bsLoudnessCompPresetMaxGain");
TEST_SB_END();
TEST_SB_END();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::audioTruncationInfo()
{
Element_Begin1("audioTruncationInfo");
BS_Begin();
Skip_SB( "isActive");
Skip_SB( "ati_reserved");
Skip_SB( "truncFromBegin");
Skip_S2(13, "nTruncSamples");
BS_End();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Mpegh3da::mhaC()
{
Element_Begin1("MHADecoderConfigurationRecord");
Skip_B1( "configurationVersion");
Skip_B1( "mpegh3daProfileLevelIndication");
Skip_B1( "referenceChannelLayout");
Skip_B2( "mpegh3daConfigLength");
mpegh3daConfig();
Element_End0();
}
//***************************************************************************
// Helpers
//***************************************************************************
//---------------------------------------------------------------------------
size_t File_Mpegh3da::num_objects_Get()
{
size_t num_signals_InElements=0;
for (size_t i=0; i<Elements.size(); i++)
if (Elements[i].Type==ID_USAC_SCE || Elements[i].Type==ID_USAC_CPE)
num_signals_InElements++;
size_t num_signals_InSignals=0;
for (size_t i=0; i<SignalGroups.size(); i++)
{
if (num_signals_InElements==num_signals_InSignals)
{
return SignalGroups[i].bsNumberOfSignals;
break;
}
num_signals_InSignals+=SignalGroups[i].bsNumberOfSignals;
}
return 0; //Problem
}
//---------------------------------------------------------------------------
void File_Mpegh3da::Streams_Fill_ChannelLayout(const string& Prefix, const speaker_layout& Layout, int8u speakerLayoutType)
{
if (Aac_Channels_Get(Layout.ChannelLayout))
{
Fill(Stream_Audio, 0, (Prefix+"Channel(s)").c_str(), Aac_Channels_GetString(Layout.ChannelLayout));
if (!Prefix.empty())
Fill_SetOptions(Stream_Audio, 0, (Prefix + "Channel(s)").c_str(), "N NTY");
if (!Prefix.empty())
{
string ChannelString=MediaInfoLib::Config.Language_Get(Ztring().From_UTF8(Aac_Channels_GetString(Layout.ChannelLayout)), __T(" channel")).To_UTF8();
string ChannelMode=Aac_ChannelMode_GetString(Layout.ChannelLayout, true);
if (ChannelMode.size()>3 || (ChannelMode.size()==3 && ChannelMode[2]!='0'))
ChannelString+=" ("+Aac_ChannelMode_GetString(Layout.ChannelLayout, true)+")";
Fill(Stream_Audio, 0, (Prefix+"Channel(s)/String").c_str(), ChannelString);
Fill_SetOptions(Stream_Audio, 0, (Prefix + "Channel(s)/String").c_str(), "Y NTN");
}
Fill(Stream_Audio, 0, (Prefix+"ChannelPositions").c_str(), Aac_ChannelConfiguration_GetString(Layout.ChannelLayout));
if (!Prefix.empty())
Fill_SetOptions(Stream_Audio, 0, (Prefix+"ChannelPositions").c_str(), "N YTY");
Fill(Stream_Audio, 0, (Prefix+"ChannelPositions/String2").c_str(), Aac_ChannelConfiguration2_GetString(Layout.ChannelLayout));
if (!Prefix.empty())
Fill_SetOptions(Stream_Audio, 0, (Prefix+"ChannelPositions/String2").c_str(), "N YTY");
Fill(Stream_Audio, 0, (Prefix+"ChannelMode").c_str(), Aac_ChannelMode_GetString(Layout.ChannelLayout, true));
Fill_SetOptions(Stream_Audio, 0, (Prefix+"ChannelMode").c_str(), "N NTY");
Fill(Stream_Audio, 0, (Prefix+"ChannelLayout").c_str(), Aac_ChannelLayout_GetString(Layout.ChannelLayout, true));
}
else if (Layout.numSpeakers)
{
if (speakerLayoutType==1) // Objects
{
Fill(Stream_Audio, 0, (Prefix+"NumberOfObjects").c_str(), Layout.numSpeakers);
Fill_SetOptions(Stream_Audio, 0, (Prefix+"NumberOfObjects").c_str(), "N YTY");
Fill(Stream_Audio, 0, (Prefix + "NumberOfObjects/String").c_str(), MediaInfoLib::Config.Language_Get(Ztring::ToZtring(Layout.numSpeakers), __T(" object")));
Fill_SetOptions(Stream_Audio, 0, (Prefix+"NumberOfObjects/String").c_str(), "Y YTN");
}
else
{
Fill(Stream_Audio, 0, (Prefix+"Channel(s)").c_str(), Layout.numSpeakers);
Fill_SetOptions(Stream_Audio, 0, (Prefix+"Channel(s)").c_str(), "N YTY");
Fill(Stream_Audio, 0, (Prefix + "Channel(s)/String").c_str(), MediaInfoLib::Config.Language_Get(Ztring::ToZtring(Layout.numSpeakers), __T(" channel")));
Fill_SetOptions(Stream_Audio, 0, (Prefix+"Channel(s)/String").c_str(), "Y YTN");
}
if (!Layout.CICPspeakerIdxs.empty())
{
Fill(Stream_Audio, 0, (Prefix+"ChannelMode").c_str(), Aac_ChannelMode_GetString(Layout.CICPspeakerIdxs));
Fill(Stream_Audio, 0, (Prefix+"ChannelLayout").c_str(), Aac_ChannelLayout_GetString(Layout.CICPspeakerIdxs));
}
else
{
vector<Aac_OutputChannel> CICPspeakerIdxs;
string ChannelLayout;
for (size_t i=0; i<Layout.SpeakersInfo.size(); i++)
{
if (i)
ChannelLayout+=' ';
if (Layout.SpeakersInfo[i].CICPspeakerIdx!=(Aac_OutputChannel)-1)
{
ChannelLayout+=Aac_ChannelLayout_GetString(&Layout.SpeakersInfo[i].CICPspeakerIdx, 1);
CICPspeakerIdxs.push_back(Layout.SpeakersInfo[i].CICPspeakerIdx);
}
else
{
if (Layout.SpeakersInfo[i].ElevationAngle==0)
ChannelLayout+='M';
else
ChannelLayout+=Layout.SpeakersInfo[i].ElevationDirection?'B':'U';
ChannelLayout+='_';
if (Layout.SpeakersInfo[i].AzimuthAngle!=0 && Layout.SpeakersInfo[i].AzimuthAngle!=180)
ChannelLayout+=Layout.SpeakersInfo[i].AzimuthDirection?'L':'R';
string AzimuthAngleString=Ztring::ToZtring(Layout.SpeakersInfo[i].AzimuthAngle).To_UTF8();
AzimuthAngleString.insert(0, 3-AzimuthAngleString.size(), '0');
ChannelLayout.append(AzimuthAngleString);
}
}
if (CICPspeakerIdxs.size()==Layout.SpeakersInfo.size())
{
Fill(Stream_Audio, 0, (Prefix+"ChannelMode").c_str(), Aac_ChannelMode_GetString(CICPspeakerIdxs));
Fill(Stream_Audio, 0, (Prefix+"ChannelLayout").c_str(), Aac_ChannelLayout_GetString(CICPspeakerIdxs));
}
else
Fill(Stream_Audio, 0, (Prefix+"ChannelLayout").c_str(), ChannelLayout);
}
}
else if (Layout.ChannelLayout)
{
Fill(Stream_Audio, 0, (Prefix+"ChannelLayout").c_str(), Layout.ChannelLayout);
}
}
//***************************************************************************
// C++
//***************************************************************************
} //NameSpace
#endif //MEDIAINFO_MPEGH3DA_YES
| 42.51776 | 239 | 0.50927 | [
"object",
"vector",
"3d"
] |
fea960f2767a99ab73c6ab1a386e2cfffb70041c | 15,293 | hpp | C++ | libgbc/util/delegate.hpp | fwsGonzo/gamebro | 3a06535b5c401788fb5428f2d2aafcd7421c5d18 | [
"MIT"
] | 20 | 2018-11-05T21:59:46.000Z | 2022-01-24T10:45:54.000Z | libgbc/util/delegate.hpp | dendisuhubdy/gamebro | beebf7fd2c756d52188c8c378d077717516b655f | [
"MIT"
] | null | null | null | libgbc/util/delegate.hpp | dendisuhubdy/gamebro | beebf7fd2c756d52188c8c378d077717516b655f | [
"MIT"
] | 5 | 2018-11-10T22:45:36.000Z | 2022-01-14T14:44:17.000Z | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 DELEGATE_HPP_INCLUDED
#define DELEGATE_HPP_INCLUDED
#include <functional>
#include <memory>
#include <type_traits>
// ----- SYNOPSIS -----
namespace spec
{
template <size_t, size_t, typename, typename...>
class pure;
template <size_t, size_t, typename, typename...>
class inplace_triv;
template <size_t, size_t, typename, typename...>
class inplace;
} // namespace spec
namespace detail
{
constexpr size_t default_capacity = sizeof(size_t) * 4;
template <typename T>
using default_alignment = std::alignment_of<std::function<T>>;
} // namespace detail
template <typename T, template <size_t, size_t, typename, typename...> class Spec = spec::inplace,
size_t size = detail::default_capacity,
size_t align = detail::default_alignment<T>::value>
class delegate; // unspecified
template <typename R, typename... Args, template <size_t, size_t, typename, typename...> class Spec,
size_t size, size_t align>
class delegate<R(Args...), Spec, size, align>;
class empty_delegate_error : public std::bad_function_call
{
public:
const char* what() const throw() { return "Empty delegate called"; }
};
// ----- IMPLEMENTATION -----
namespace detail
{
template <typename R, typename... Args>
static R empty_pure(Args...)
{
throw empty_delegate_error();
}
template <typename R, typename S, typename... Args>
static R empty_inplace(S&, Args&&... args)
{
return empty_pure<R, Args...>(std::forward<Args>(args)...);
}
template <typename T, typename R, typename... Args>
using closure_decay = std::conditional<std::is_convertible<T, R (*)(Args...)>::value,
R (*)(Args...), typename std::decay<T>::type>;
template <typename T = void, typename...>
struct pack_first
{
using type = std::remove_cv_t<T>;
};
template <typename... Ts>
using pack_first_t = typename pack_first<Ts...>::type;
} // namespace detail
namespace spec
{
// --- pure ---
template <size_t, size_t, typename R, typename... Args>
class pure
{
public:
using invoke_ptr_t = R (*)(Args...);
explicit pure() noexcept : invoke_ptr_{detail::empty_pure<R, Args...>} {}
template <typename T>
explicit pure(T&& func_ptr) noexcept : invoke_ptr_{func_ptr}
{
static_assert(std::is_convertible<T, invoke_ptr_t>::value,
"object not convertible to pure function pointer!");
}
pure(const pure&) noexcept = default;
pure(pure&&) noexcept = default;
pure& operator=(const pure&) noexcept = default;
pure& operator=(pure&&) noexcept = default;
~pure() = default;
R operator()(Args&&... args) const { return invoke_ptr_(std::forward<Args>(args)...); }
bool empty() const noexcept
{
return invoke_ptr_ == static_cast<invoke_ptr_t>(detail::empty_pure<R, Args...>);
}
template <typename T>
T* target() const noexcept
{
return static_cast<T*>(invoke_ptr_);
}
private:
invoke_ptr_t invoke_ptr_;
};
// --- inplace_triv ---
template <size_t size, size_t align, typename R, typename... Args>
class inplace_triv
{
public:
using storage_t = std::aligned_storage_t<size, align>;
using invoke_ptr_t = R (*)(storage_t&, Args&&...);
explicit inplace_triv() noexcept : invoke_ptr_{detail::empty_inplace<R, storage_t, Args...>}
{
new (&storage_) std::nullptr_t{nullptr};
}
template <typename T, typename C = typename detail::closure_decay<T, R, Args...>::type>
explicit inplace_triv(T&& closure)
: invoke_ptr_{static_cast<invoke_ptr_t>([](storage_t& storage, Args&&... args) -> R {
return reinterpret_cast<C&>(storage)(std::forward<Args>(args)...);
})}
{
static_assert(sizeof(C) <= size, "inplace_triv delegate closure too large!");
static_assert(std::alignment_of<C>::value <= align,
"inplace_triv delegate closure alignment too large");
static_assert(std::is_trivially_copyable<C>::value,
"inplace_triv delegate closure not trivially copyable!");
static_assert(std::is_trivially_destructible<C>::value,
"inplace_triv delegate closure not trivially destructible!");
new (&storage_) C{std::forward<T>(closure)};
}
inplace_triv(const inplace_triv&) noexcept = default;
inplace_triv(inplace_triv&&) noexcept = default;
inplace_triv& operator=(const inplace_triv&) noexcept = default;
inplace_triv& operator=(inplace_triv&&) noexcept = default;
~inplace_triv() = default;
R operator()(Args&&... args) const
{
return invoke_ptr_(storage_, std::forward<Args>(args)...);
}
bool empty() const noexcept { return reinterpret_cast<std::nullptr_t&>(storage_) == nullptr; }
template <typename T>
T* target() const noexcept
{
return reinterpret_cast<T*>(&storage_);
}
private:
invoke_ptr_t invoke_ptr_;
mutable storage_t storage_;
};
// --- inplace ---
template <size_t size, size_t align, typename R, typename... Args>
class inplace
{
public:
using storage_t = std::aligned_storage_t<size, align>;
using invoke_ptr_t = R (*)(storage_t&, Args&&...);
using copy_ptr_t = void (*)(storage_t&, storage_t&);
using destructor_ptr_t = void (*)(storage_t&);
explicit inplace() noexcept
: invoke_ptr_{detail::empty_inplace<R, storage_t, Args...>}
, copy_ptr_{copy_op<std::nullptr_t, storage_t>()}
, destructor_ptr_{nullptr}
{}
template <typename T, typename C = typename detail::closure_decay<T, R, Args...>::type>
explicit inplace(T&& closure) noexcept
: invoke_ptr_{static_cast<invoke_ptr_t>([](storage_t& storage, Args&&... args) -> R {
return reinterpret_cast<C&>(storage)(std::forward<Args>(args)...);
})}
, copy_ptr_{copy_op<C, storage_t>()}
, destructor_ptr_{static_cast<destructor_ptr_t>(
[](storage_t & storage) noexcept->void { reinterpret_cast<C&>(storage).~C(); })}
{
static_assert(sizeof(C) <= size, "inplace delegate closure too large");
static_assert(std::alignment_of<C>::value <= align,
"inplace delegate closure alignment too large");
new (&storage_) C{std::forward<T>(closure)};
}
inplace(const inplace& other)
: invoke_ptr_{other.invoke_ptr_}
, copy_ptr_{other.copy_ptr_}
, destructor_ptr_{other.destructor_ptr_}
{
copy_ptr_(storage_, other.storage_);
}
inplace(inplace&& other)
: storage_{std::move(other.storage_)}
, invoke_ptr_{other.invoke_ptr_}
, copy_ptr_{other.copy_ptr_}
, destructor_ptr_{other.destructor_ptr_}
{
other.destructor_ptr_ = nullptr;
}
inplace& operator=(const inplace& other)
{
if (this != std::addressof(other))
{
invoke_ptr_ = other.invoke_ptr_;
copy_ptr_ = other.copy_ptr_;
if (destructor_ptr_) destructor_ptr_(storage_);
copy_ptr_(storage_, other.storage_);
destructor_ptr_ = other.destructor_ptr_;
}
return *this;
}
inplace& operator=(inplace&& other)
{
if (this != std::addressof(other))
{
if (destructor_ptr_) destructor_ptr_(storage_);
storage_ = std::move(other.storage_);
invoke_ptr_ = other.invoke_ptr_;
copy_ptr_ = other.copy_ptr_;
destructor_ptr_ = other.destructor_ptr_;
other.destructor_ptr_ = nullptr;
}
return *this;
}
~inplace()
{
if (destructor_ptr_) destructor_ptr_(storage_);
}
R operator()(Args&&... args) const
{
return invoke_ptr_(storage_, std::forward<Args>(args)...);
}
bool empty() const noexcept { return destructor_ptr_ == nullptr; }
template <typename T>
T* target() const noexcept
{
return reinterpret_cast<T*>(&storage_);
}
private:
mutable storage_t storage_{};
invoke_ptr_t invoke_ptr_;
copy_ptr_t copy_ptr_;
destructor_ptr_t destructor_ptr_;
template <typename T, typename S,
typename std::enable_if_t<std::is_copy_constructible<T>::value, int> = 0>
copy_ptr_t copy_op()
{
return [](S & dst, S & src) noexcept->void { new (&dst) T{reinterpret_cast<T&>(src)}; };
}
template <typename T, typename S,
typename std::enable_if_t<!std::is_copy_constructible<T>::value, int> = 0>
copy_ptr_t copy_op()
{
static_assert(std::is_copy_constructible<T>::value,
"constructing delegate with move only type is invalid!");
}
};
} // namespace spec
template <typename R, typename... Args, template <size_t, size_t, typename, typename...> class Spec,
size_t size, size_t align>
class delegate<R(Args...), Spec, size, align>
{
public:
using result_type = R;
using storage_t = Spec<size, align, R, Args...>;
explicit delegate() noexcept : storage_{} {}
template <typename T,
typename = std::enable_if_t<!std::is_same<std::decay_t<T>, delegate>::value>
/*&& std::is_same<
decltype(std::declval<T&>()(std::declval<Args>()...)),
R
>::value>*/
>
delegate(T&& val) : storage_{std::forward<T>(val)}
{}
// delegating constructors
delegate(std::nullptr_t) noexcept : delegate() {}
// construct with member function pointer
// object pointer capture
template <typename C>
delegate(C* const object_ptr, R (C::*const method_ptr)(Args...)) noexcept
: delegate([object_ptr, method_ptr](Args&&... args) -> R {
return (object_ptr->*method_ptr)(std::forward<Args>(args)...);
})
{}
template <typename C>
delegate(C* const object_ptr, R (C::*const method_ptr)(Args...) const) noexcept
: delegate([object_ptr, method_ptr](Args&&... args) -> R {
return (object_ptr->*method_ptr)(std::forward<Args>(args)...);
})
{}
// object reference capture
template <typename C>
delegate(C& object_ref, R (C::*const method_ptr)(Args...)) noexcept
: delegate([&object_ref, method_ptr](Args&&... args) -> R {
return (object_ref.*method_ptr)(std::forward<Args>(args)...);
})
{}
template <typename C>
delegate(C& object_ref, R (C::*const method_ptr)(Args...) const) noexcept
: delegate([&object_ref, method_ptr](Args&&... args) -> R {
return (object_ref.*method_ptr)(std::forward<Args>(args)...);
})
{}
// object pointer as parameter
template <
typename C, typename... MemArgs,
typename std::enable_if_t<std::is_same<detail::pack_first_t<Args...>, C*>::value, int> = 0>
delegate(R (C::*const method_ptr)(MemArgs...)) noexcept
: delegate([method_ptr](C* object_ptr, MemArgs... args) -> R {
return (object_ptr->*method_ptr)(std::forward<MemArgs>(args)...);
})
{}
template <
typename C, typename... MemArgs,
typename std::enable_if_t<std::is_same<detail::pack_first_t<Args...>, C*>::value, int> = 0>
delegate(R (C::*const method_ptr)(MemArgs...) const) noexcept
: delegate([method_ptr](C* object_ptr, MemArgs... args) -> R {
return (object_ptr->*method_ptr)(std::forward<MemArgs>(args)...);
})
{}
// object reference as parameter
template <
typename C, typename... MemArgs,
typename std::enable_if_t<std::is_same<detail::pack_first_t<Args...>, C&>::value, int> = 0>
delegate(R (C::*const method_ptr)(MemArgs...)) noexcept
: delegate([method_ptr](C& object, MemArgs... args) -> R {
return (object.*method_ptr)(std::forward<MemArgs>(args)...);
})
{}
template <
typename C, typename... MemArgs,
typename std::enable_if_t<std::is_same<detail::pack_first_t<Args...>, C&>::value, int> = 0>
delegate(R (C::*const method_ptr)(MemArgs...) const) noexcept
: delegate([method_ptr](C& object, MemArgs... args) -> R {
return (object.*method_ptr)(std::forward<MemArgs>(args)...);
})
{}
// object copy as parameter
template <
typename C, typename... MemArgs,
typename std::enable_if_t<std::is_same<detail::pack_first_t<Args...>, C>::value, int> = 0>
delegate(R (C::*const method_ptr)(MemArgs...)) noexcept
: delegate([method_ptr](C object, MemArgs... args) -> R {
return (object.*method_ptr)(std::forward<MemArgs>(args)...);
})
{}
template <
typename C, typename... MemArgs,
typename std::enable_if_t<std::is_same<detail::pack_first_t<Args...>, C>::value, int> = 0>
delegate(R (C::*const method_ptr)(MemArgs...) const) noexcept
: delegate([method_ptr](C object, MemArgs... args) -> R {
return (object.*method_ptr)(std::forward<MemArgs>(args)...);
})
{}
delegate(const delegate&) = default;
delegate(delegate&&) = default;
delegate& operator=(const delegate&) = default;
delegate& operator=(delegate&&) = default;
~delegate() = default;
R operator()(Args... args) const { return storage_(std::forward<Args>(args)...); }
bool operator==(std::nullptr_t) const noexcept { return storage_.empty(); }
bool operator!=(std::nullptr_t) const noexcept { return !storage_.empty(); }
explicit operator bool() const noexcept { return !storage_.empty(); }
void swap(delegate& other)
{
storage_t tmp = storage_;
storage_ = other.storage_;
other.storage_ = tmp;
}
void reset()
{
storage_t empty;
storage_ = empty;
}
template <typename T>
T* target() const noexcept
{
return storage_.template target<T>();
}
template <typename T, typename D = std::shared_ptr<T>,
typename std::enable_if_t<size >= sizeof(D), int> = 0>
static delegate make_packed(T&& closure)
{
D ptr = std::make_shared<T>(std::forward<T>(closure));
return [ptr](Args&&... args) -> R { return (*ptr)(std::forward<Args>(args)...); };
}
template <typename T, typename D = std::shared_ptr<T>,
typename std::enable_if_t<!(size >= sizeof(D)), int> = 0>
static delegate make_packed(T&&)
{
static_assert(size >= sizeof(D), "Cannot pack into delegate");
}
private:
storage_t storage_;
};
#endif // DELEGATE_HPP_INCLUDED
| 31.402464 | 100 | 0.621003 | [
"object"
] |
feb30fab7c840902475104abf8291665f6a68653 | 33,487 | cpp | C++ | mcsema/CFG/CFG.cpp | FFengIll/mcsema | 2edb800f1de4ae9ce5839df11faeab34c6cfb353 | [
"BSD-3-Clause"
] | null | null | null | mcsema/CFG/CFG.cpp | FFengIll/mcsema | 2edb800f1de4ae9ce5839df11faeab34c6cfb353 | [
"BSD-3-Clause"
] | null | null | null | mcsema/CFG/CFG.cpp | FFengIll/mcsema | 2edb800f1de4ae9ce5839df11faeab34c6cfb353 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2014, Trail of Bits
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Trail of Bits nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <utility>
#include <mcsema_generated/CFG.pb.h> // Auto-generated.
#include "mcsema/Arch/Arch.h"
#include "mcsema/CFG/CFG.h"
#include "mcsema/cfgToLLVM/TransExcn.h"
#include "mcsema/CFG/Externals.h"
#include "mcsema/cfgToLLVM/JumpTables.h"
bool NativeInst::terminator(void) const {
return this->is_terminator;
}
void NativeInst::set_terminator(void) {
this->is_terminator = true;
}
void NativeInst::set_system_call_number(int cn) {
this->system_call_number = cn;
}
int NativeInst::get_system_call_number(void) const {
return this->system_call_number;
}
bool NativeInst::has_system_call_number(void) const {
return this->system_call_number != -1;
}
void NativeInst::set_local_noreturn(void) {
this->local_noreturn = true;
}
bool NativeInst::has_local_noreturn(void) const {
return this->local_noreturn;
}
uint8_t NativeInst::get_reloc_offset(CFGOpType op) const {
if (op == MEMRef) {
return this->mem_reloc_offset;
} else if (op == IMMRef) {
return this->imm_reloc_offset;
} else {
return -1;
}
}
void NativeInst::set_reloc_offset(CFGOpType op, uint8_t ro) {
if (op == MEMRef) {
this->mem_reloc_offset = ro;
} else if (op == IMMRef) {
this->imm_reloc_offset = ro;
} else {
//
}
}
void NativeInst::set_reference(CFGOpType op, uint64_t ref) {
if (op == MEMRef) {
this->mem_reference = ref;
this->has_mem_reference = true;
} else if (op == IMMRef) {
this->imm_reference = ref;
this->has_imm_reference = true;
} else {
// void
}
}
void NativeInst::set_ref_type(CFGOpType op, CFGRefType rt) {
if (op == MEMRef) {
this->mem_ref_type = rt;
} else if (op == IMMRef) {
this->imm_ref_type = rt;
} else {
// void
}
}
void NativeInst::set_ref_reloc_type(CFGOpType op, uint64_t ref, uint64_t ro,
CFGRefType rt) {
const char *ops = op == MEMRef ? "MEM" : "IMM";
const char *rts = rt == CFGCodeRef ? "CODE" : "DATA";
std::cerr << __FUNCTION__ << ": Adding ref: " << ops << ", to: " << std::hex
<< ref << ", ro: " << ro << ", rt: " << rts << std::endl;
this->set_reference(op, ref);
this->set_reloc_offset(op, ro);
this->set_ref_type(op, rt);
}
bool NativeInst::has_reference(CFGOpType op) const {
if (op == MEMRef) {
return this->has_mem_reference;
} else if (op == IMMRef) {
return this->has_imm_reference;
} else {
return false;
}
}
uint64_t NativeInst::get_reference(CFGOpType op) const {
if (op == MEMRef) {
return this->mem_reference;
} else if (op == IMMRef) {
return this->imm_reference;
} else {
return -1;
}
}
NativeInst::CFGRefType NativeInst::get_ref_type(CFGOpType op) const {
if (op == MEMRef) {
return this->mem_ref_type;
} else if (op == IMMRef) {
return this->imm_ref_type;
} else {
//TODO throw exception?
//return -1;
return this->mem_ref_type;
}
}
bool NativeInst::has_code_ref(void) const {
if (this->has_mem_reference && this->mem_ref_type == CFGCodeRef) {
return true;
}
if (this->has_imm_reference && this->imm_ref_type == CFGCodeRef) {
return true;
}
return false;
}
bool NativeInst::get_is_call_external(void) const {
return this->is_call_external;
}
void NativeInst::set_is_call_external(void) {
this->is_call_external = true;
}
llvm::MCInst &NativeInst::get_inst(void) {
return this->decoded_inst;
}
void NativeInst::set_inst(const llvm::MCInst &i) {
this->decoded_inst = i;
}
VA NativeInst::get_loc(void) const {
return this->loc;
}
void NativeInst::set_tr(VA a) {
this->tgtIfTrue = a;
}
void NativeInst::set_fa(VA a) {
this->tgtIfFalse = a;
}
VA NativeInst::get_tr(void) const {
return this->tgtIfTrue;
}
VA NativeInst::get_fa(void) const {
return this->tgtIfFalse;
}
uint8_t NativeInst::get_len(void) const {
return this->len;
}
void NativeInst::set_call_tgt(VA addr) {
this->targets.push_back(addr);
return;
}
bool NativeInst::has_call_tgt(void) const {
return !this->targets.empty();
}
VA NativeInst::get_call_tgt(int index) const {
return this->targets.at(index);
}
void NativeInst::set_ext_call_target(ExternalCodeRefPtr t) {
this->extCallTgt = t;
this->ext_call_target = true;
return;
}
void NativeInst::set_ext_data_ref(ExternalDataRefPtr t) {
this->extDataRef = t;
this->ext_data_ref = true;
return;
}
bool NativeInst::has_ext_data_ref(void) const {
return this->ext_data_ref;
}
bool NativeInst::has_ext_call_target(void) const {
return this->ext_call_target;
}
bool NativeInst::has_external_ref(void) const {
return this->has_ext_call_target() || this->has_ext_data_ref();
}
bool NativeInst::has_rip_relative(void) const {
return this->hasRIP;
}
VA NativeInst::get_rip_relative(void) const {
return this->rip_target;
}
void NativeInst::set_rip_relative(unsigned i) {
const llvm::MCOperand &base = decoded_inst.getOperand(i + 0);
const llvm::MCOperand &scale = decoded_inst.getOperand(i + 1);
const llvm::MCOperand &index = decoded_inst.getOperand(i + 2);
const llvm::MCOperand &disp = decoded_inst.getOperand(i + 3);
rip_target = loc + len + disp.getImm();
//const
this->hasRIP = true;
}
// accessors for JumpTable
void NativeInst::set_jump_table(MCSJumpTablePtr p) {
this->jump_table = true;
this->jumpTable = p;
}
MCSJumpTablePtr NativeInst::get_jump_table(void) const {
return this->jumpTable;
}
bool NativeInst::has_jump_table(void) const {
return this->jump_table;
}
// accessors for JumpIndexTable
void NativeInst::set_jump_index_table(JumpIndexTablePtr p) {
this->jump_index_table = true;
this->jumpIndexTable = p;
}
JumpIndexTablePtr NativeInst::get_jump_index_table(void) const {
return this->jumpIndexTable;
}
bool NativeInst::has_jump_index_table(void) const {
return this->jump_index_table;
}
NativeInst::Prefix NativeInst::get_prefix(void) const {
return this->pfx;
}
unsigned int NativeInst::get_addr_space(void) const {
if (this->pfx == NativeInst::FSPrefix) {
return 257;
} else if (this->pfx == NativeInst::GSPrefix) {
return 256;
} else {
return 0;
}
}
unsigned int NativeInst::get_opcode(void) const {
return this->decoded_inst.getOpcode();
}
ExternalCodeRefPtr NativeInst::get_ext_call_target(void) const {
return this->extCallTgt;
}
ExternalDataRefPtr NativeInst::get_ext_data_ref(void) const {
return this->extDataRef;
}
NativeInst::NativeInst(VA v, uint8_t l, const llvm::MCInst &inst, Prefix k)
: tgtIfTrue(0),
tgtIfFalse(0),
loc(v),
decoded_inst(inst),
pfx(k),
ext_call_target(false),
is_call_external(false),
is_terminator(false),
imm_reloc_offset(0),
imm_reference(0),
imm_ref_type(CFGDataRef),
has_imm_reference(false),
mem_reloc_offset(0),
mem_reference(0),
mem_ref_type(CFGDataRef),
has_mem_reference(false),
len(l),
jump_table(false),
jump_index_table(false),
ext_data_ref(false),
arch(0),
system_call_number( -1),
local_noreturn(false),
hasRIP(false),
rip_target(0),
offset_table( -1) {}
DataSectionEntry::DataSectionEntry(uint64_t base, const std::vector<uint8_t> &b)
: base(base),
bytes(b),
is_symbol(false) {}
DataSectionEntry::DataSectionEntry(uint64_t base, const std::string &sname)
: base(base),
sym_name(sname),
is_symbol(true) {
this->bytes.push_back(0x0);
this->bytes.push_back(0x0);
this->bytes.push_back(0x0);
this->bytes.push_back(0x0);
}
DataSectionEntry::DataSectionEntry(uint64_t base, const std::string &sname,
uint64_t symbol_size)
: base(base),
bytes(symbol_size),
sym_name(sname),
is_symbol(true) {}
uint64_t DataSectionEntry::getBase(void) const {
return this->base;
}
uint64_t DataSectionEntry::getSize(void) const {
return this->bytes.size();
}
const std::vector<uint8_t> &DataSectionEntry::getBytes(void) const {
return this->bytes;
}
bool DataSectionEntry::getSymbol(std::string &sname) const {
if (this->is_symbol) {
sname = this->sym_name;
return true;
} else {
return false;
}
}
DataSectionEntry::~DataSectionEntry(void) {}
DataSection::DataSection(void)
: base(NO_BASE),
read_only(false) {}
DataSection::~DataSection(void) {}
void DataSection::setReadOnly(bool isro) {
this->read_only = isro;
}
bool DataSection::isReadOnly(void) const {
return this->read_only;
}
uint64_t DataSection::getBase(void) const {
return this->base;
}
const std::list<DataSectionEntry> &DataSection::getEntries(void) const {
return this->entries;
}
void DataSection::addEntry(const DataSectionEntry &dse) {
this->entries.push_back(dse);
if (this->base == NO_BASE || this->base > dse.getBase()) {
this->base = dse.getBase();
}
}
uint64_t DataSection::getSize(void) const {
uint64_t size_sum = 0;
for (std::list<DataSectionEntry>::const_iterator itr = entries.begin();
itr != entries.end(); itr++) {
size_sum += itr->getSize();
}
return size_sum;
}
std::vector<uint8_t> DataSection::getBytes(void) const {
std::vector<uint8_t> all_bytes;
for (const auto entry : entries) {
const auto &vec = entry.getBytes();
all_bytes.insert(all_bytes.end(), vec.begin(), vec.end());
}
return all_bytes;
}
NativeEntrySymbol::NativeEntrySymbol(const std::string &name_, VA addr_)
: addr(addr_),
name(name_),
has_extra(false),
num_args(0),
does_return(false),
calling_conv(ExternalCodeRef::CallerCleanup) {}
NativeEntrySymbol::NativeEntrySymbol(VA addr_)
: addr(addr_),
has_extra(false),
num_args(0),
does_return(false),
calling_conv(ExternalCodeRef::CallerCleanup) {
std::stringstream ss;
ss << "sub_" << std::hex << this->addr;
this->name = ss.str();
}
const std::string &NativeEntrySymbol::getName(void) const {
return this->name;
}
VA NativeEntrySymbol::getAddr(void) const {
return this->addr;
}
bool NativeEntrySymbol::hasExtra(void) const {
return this->has_extra;
}
int NativeEntrySymbol::getArgc(void) const {
return this->num_args;
}
bool NativeEntrySymbol::doesReturn(void) const {
return this->does_return;
}
ExternalCodeRef::CallingConvention NativeEntrySymbol::getConv(void) const {
return this->calling_conv;
}
void NativeEntrySymbol::setExtra(int argc_, bool does_ret,
ExternalCodeRef::CallingConvention conv) {
this->num_args = argc_;
this->does_return = does_ret;
this->calling_conv = conv;
this->has_extra = true;
}
NativeModule::NativeModule(
const std::string &module_name_,
const std::unordered_map<VA, NativeFunctionPtr> &funcs_,
const std::string &triple_)
: funcs(funcs_),
module_name(module_name_),
triple(triple_) {}
VA NativeFunction::get_start(void) {
return this->funcEntryVA;
}
uint64_t NativeFunction::num_blocks(void) {
return this->blocks.size();
}
const std::map<VA, NativeBlockPtr> &NativeFunction::get_blocks(void) const {
return this->blocks;
}
NativeBlockPtr NativeFunction::block_from_base(VA base) {
auto block_it = blocks.find(base);
TASSERT(block_it != blocks.end(), "Block not found");
return block_it->second;
}
NativeBlock::NativeBlock(VA b)
: baseAddr(b) {}
void NativeBlock::add_inst(NativeInstPtr p) {
this->instructions.push_back(p);
}
VA NativeBlock::get_base(void) {
return this->baseAddr;
}
void NativeBlock::add_follow(VA f) {
this->follows.push_back(f);
}
std::list<VA> &NativeBlock::get_follows(void) {
return this->follows;
}
const std::list<NativeInstPtr> &NativeBlock::get_insts(void) {
return this->instructions;
}
void NativeFunction::add_block(NativeBlockPtr b) {
auto blockBase = b->get_base();
TASSERT( !this->blocks.count(blockBase), "Added duplicate block!");
this->blocks[blockBase] = b;
}
std::string NativeFunction::get_name(void) {
std::stringstream ss;
ss << "sub_" << std::hex << this->funcEntryVA;
return ss.str();
}
const std::string &NativeFunction::get_symbol_name(void) {
return this->funcSymName;
}
std::string NativeBlock::get_name(void) {
std::stringstream ss;
ss << "block_" << std::hex << this->baseAddr;
return ss.str();
}
void NativeModule::addDataSection(VA base, std::vector<uint8_t> &bytes) {
DataSection ds;
DataSectionEntry dse(base, bytes);
ds.addEntry(dse);
this->data_sections.push_back(ds);
}
void NativeModule::addDataSection(const DataSection &d) {
this->data_sections.push_back(d);
}
void NativeModule::add_func(NativeFunctionPtr f) {
this->funcs[f->get_start()] = f;
}
const std::unordered_map<VA, NativeFunctionPtr> &NativeModule::get_funcs(
void) const {
return this->funcs;
}
const std::string &NativeModule::name(void) const {
return this->module_name;
}
const std::list<DataSection> &NativeModule::getData(void) const {
return this->data_sections;
}
//add an external reference
void NativeModule::addExtCall(ExternalCodeRefPtr p) {
this->external_code_refs.push_back(p);
}
const std::list<ExternalCodeRefPtr> &NativeModule::getExtCalls(void) const {
return this->external_code_refs;
}
//external data ref
void NativeModule::addExtDataRef(ExternalDataRefPtr p) {
this->external_data_refs.push_back(p);
}
const std::list<ExternalDataRefPtr> &NativeModule::getExtDataRefs(void) const {
return this->external_data_refs;
}
const std::vector<NativeEntrySymbol> &NativeModule::getEntryPoints(void) const {
return this->entries;
}
void NativeModule::addEntryPoint(const NativeEntrySymbol &ep) {
this->entries.push_back(ep);
}
bool NativeModule::is64Bit(void) const {
return 64 == ArchAddressSize();
}
void NativeModule::addOffsetTables(
const std::list<MCSOffsetTablePtr> & tables) {
for (const auto &table : tables) {
std::cerr
<< "Adding offset table at " << std::hex
<< table->getStartAddr() << std::endl;
this->offset_tables.insert( {table->getStartAddr(), table});
}
}
NativeInst::CFGRefType deserRefType(::Instruction::RefType k) {
switch (k) {
case ::Instruction::CodeRef:
return NativeInst::CFGCodeRef;
case ::Instruction::DataRef:
return NativeInst::CFGDataRef;
default:
throw TErr(__LINE__, __FILE__, "Unsupported Ref Type");
}
}
static ExternalCodeRefPtr getExternal(
const std::string &s, const std::list<ExternalCodeRefPtr> &extcode) {
for (auto e : extcode) {
if (s == e->getSymbolName()) {
return e;
}
}
return ExternalCodeRefPtr();
}
enum : size_t {
kMaxNumInstrBytes = 16ULL // 15 on x86 and amd64.
};
static NativeInst::Prefix GetPrefix(const llvm::MCInst &inst) {
switch (inst.getOpcode()) {
case llvm::X86::REP_MOVSB_32:
case llvm::X86::REP_MOVSB_64:
case llvm::X86::REP_MOVSW_32:
case llvm::X86::REP_MOVSW_64:
case llvm::X86::REP_MOVSD_32:
case llvm::X86::REP_MOVSD_64:
case llvm::X86::REP_MOVSQ_64:
case llvm::X86::REP_LODSB_32:
case llvm::X86::REP_LODSB_64:
case llvm::X86::REP_LODSW_32:
case llvm::X86::REP_LODSW_64:
case llvm::X86::REP_LODSD_32:
case llvm::X86::REP_LODSD_64:
case llvm::X86::REP_LODSQ_64:
case llvm::X86::REP_STOSB_32:
case llvm::X86::REP_STOSB_64:
case llvm::X86::REP_STOSW_32:
case llvm::X86::REP_STOSW_64:
case llvm::X86::REP_STOSD_32:
case llvm::X86::REP_STOSD_64:
case llvm::X86::REP_STOSQ_64:
return NativeInst::RepPrefix;
case llvm::X86::REPE_CMPSB_32:
case llvm::X86::REPE_CMPSB_64:
case llvm::X86::REPE_CMPSW_32:
case llvm::X86::REPE_CMPSW_64:
case llvm::X86::REPE_CMPSD_32:
case llvm::X86::REPE_CMPSD_64:
case llvm::X86::REPE_CMPSQ_64:
return NativeInst::RepPrefix;
case llvm::X86::REPNE_CMPSB_32:
case llvm::X86::REPNE_CMPSB_64:
case llvm::X86::REPNE_CMPSW_32:
case llvm::X86::REPNE_CMPSW_64:
case llvm::X86::REPNE_CMPSD_32:
case llvm::X86::REPNE_CMPSD_64:
case llvm::X86::REPNE_CMPSQ_64:
return NativeInst::RepNePrefix;
case llvm::X86::REPE_SCASB_32:
case llvm::X86::REPE_SCASB_64:
case llvm::X86::REPE_SCASW_32:
case llvm::X86::REPE_SCASW_64:
case llvm::X86::REPE_SCASD_32:
case llvm::X86::REPE_SCASD_64:
case llvm::X86::REPE_SCASQ_64:
return NativeInst::RepPrefix;
case llvm::X86::REPNE_SCASB_32:
case llvm::X86::REPNE_SCASB_64:
case llvm::X86::REPNE_SCASW_32:
case llvm::X86::REPNE_SCASW_64:
case llvm::X86::REPNE_SCASD_32:
case llvm::X86::REPNE_SCASD_64:
case llvm::X86::REPNE_SCASQ_64:
return NativeInst::RepNePrefix;
}
for (const auto &op : inst) {
if (op.isReg()) {
if (op.getReg() == llvm::X86::GS) {
return NativeInst::GSPrefix;
} else if (op.getReg() == llvm::X86::FS) {
return NativeInst::FSPrefix;
}
}
}
return NativeInst::NoPrefix;
}
static NativeInstPtr DecodeInst(
uintptr_t addr, const std::vector<uint8_t> &bytes) {
VA nextVA = addr;
// Get the maximum number of bytes for decoding.
uint8_t decodable_bytes[kMaxNumInstrBytes] = {};
std::copy(bytes.begin(), bytes.end(), decodable_bytes);
auto max_size = bytes.size();
// Try to decode the instruction.
llvm::MCInst mcInst;
auto num_decoded_bytes = ArchDecodeInstruction(
decodable_bytes, decodable_bytes + max_size, addr, mcInst);
if (!num_decoded_bytes) {
std::cerr
<< "Failed to decode instruction at address "
<< std::hex << addr << std::endl;
return nullptr;
}
NativeInstPtr inst = new NativeInst(
addr, num_decoded_bytes, mcInst, GetPrefix(mcInst));
// Mark some operands as being RIP-relative.
for (auto i = 0U; i < mcInst.getNumOperands(); ++i) {
const auto &Op = mcInst.getOperand(i);
if (Op.isReg() && Op.getReg() == llvm::X86::RIP) {
inst->set_rip_relative(i);
}
}
llvm::MCOperand oper;
//ask if this is a jmp, and figure out what the true / false follows are
switch (mcInst.getOpcode()) {
case llvm::X86::JMP32m:
case llvm::X86::JMP32r:
case llvm::X86::JMP64m:
case llvm::X86::JMP64r:
inst->set_terminator();
break;
case llvm::X86::RETL:
case llvm::X86::RETIL:
case llvm::X86::RETIQ:
case llvm::X86::RETIW:
case llvm::X86::RETQ:
inst->set_terminator();
break;
case llvm::X86::JMP_4:
case llvm::X86::JMP_1:
oper = mcInst.getOperand(0);
if (oper.isImm()) {
nextVA += oper.getImm() + num_decoded_bytes;
inst->set_tr(nextVA);
} else {
std::cerr << "Unhandled indirect branch at 0x" << std::hex << addr;
return nullptr;
}
break;
case llvm::X86::LOOP:
case llvm::X86::LOOPE:
case llvm::X86::LOOPNE:
case llvm::X86::JO_4:
case llvm::X86::JO_1:
case llvm::X86::JNO_4:
case llvm::X86::JNO_1:
case llvm::X86::JB_4:
case llvm::X86::JB_1:
case llvm::X86::JAE_4:
case llvm::X86::JAE_1:
case llvm::X86::JE_4:
case llvm::X86::JE_1:
case llvm::X86::JNE_4:
case llvm::X86::JNE_1:
case llvm::X86::JBE_4:
case llvm::X86::JBE_1:
case llvm::X86::JA_4:
case llvm::X86::JA_1:
case llvm::X86::JS_4:
case llvm::X86::JS_1:
case llvm::X86::JNS_4:
case llvm::X86::JNS_1:
case llvm::X86::JP_4:
case llvm::X86::JP_1:
case llvm::X86::JNP_4:
case llvm::X86::JNP_1:
case llvm::X86::JL_4:
case llvm::X86::JL_1:
case llvm::X86::JGE_4:
case llvm::X86::JGE_1:
case llvm::X86::JLE_4:
case llvm::X86::JLE_1:
case llvm::X86::JG_4:
case llvm::X86::JG_1:
case llvm::X86::JCXZ:
case llvm::X86::JECXZ:
case llvm::X86::JRCXZ:
oper = mcInst.getOperand(0);
inst->set_tr(addr + oper.getImm() + num_decoded_bytes);
inst->set_fa(addr + num_decoded_bytes);
break;
}
return inst;
}
static NativeInstPtr DeserializeInst(
const ::Instruction &inst,
const std::list<ExternalCodeRefPtr> &extcode) {
VA addr = inst.inst_addr();
auto tr_tgt = static_cast<VA>(inst.true_target());
auto fa_tgt = static_cast<VA>(inst.false_target());
const auto &bytes_str = inst.inst_bytes();
std::vector<uint8_t> bytes(bytes_str.begin(), bytes_str.end());
//produce an MCInst from the instruction buffer using the ByteDecoder
NativeInstPtr ip = DecodeInst(addr, bytes);
if (!ip) {
std::cerr
<< "Unable to deserialize inst at " << std::hex << addr << std::endl;
return nullptr;
}
if (tr_tgt > 0) {
ip->set_tr(tr_tgt);
}
if (fa_tgt > 0) {
ip->set_fa(fa_tgt);
}
if (inst.has_ext_call_name()) {
ExternalCodeRefPtr p = getExternal(inst.ext_call_name(), extcode);
if (!p) {
std::cerr
<< "Unable to find external call " << inst.ext_call_name()
<< " for inst at " << std::hex << addr << std::endl;
return nullptr;
}
ip->set_ext_call_target(p);
}
if (inst.has_ext_data_name()) {
ExternalDataRefPtr p(new ExternalDataRef(inst.ext_data_name()));
ip->set_ext_data_ref(p);
}
if (inst.has_imm_reference()) {
auto ref = static_cast<uint64_t>(inst.imm_reference());
uint64_t ro = 0;
NativeInst::CFGRefType rt;
if (inst.has_imm_reloc_offset()) {
ro = static_cast<VA>(inst.imm_reloc_offset());
}
if (inst.has_imm_ref_type()) {
rt = deserRefType(inst.imm_ref_type());
}
ip->set_ref_reloc_type(NativeInst::IMMRef, ref, ro, rt);
}
if (inst.has_mem_reference()) {
uint64_t ref = inst.mem_reference();
uint64_t ro = 0;
NativeInst::CFGRefType rt;
if (inst.has_mem_reloc_offset()) {
ro = inst.mem_reloc_offset();
}
if (inst.has_mem_ref_type()) {
rt = deserRefType(inst.mem_ref_type());
}
ip->set_ref_reloc_type(NativeInst::MEMRef, ref, ro, rt);
}
if (inst.has_jump_table()) {
// create new jump table
const ::JumpTbl &jmp_tbl = inst.jump_table();
std::vector<VA> table_entries;
for (int i = 0; i < jmp_tbl.table_entries_size(); i++) {
table_entries.push_back(jmp_tbl.table_entries(i));
}
VA data_offset = (VA) ( -1);
if (jmp_tbl.has_offset_from_data()) {
data_offset = jmp_tbl.offset_from_data();
}
auto jmp = new MCSJumpTable(table_entries, jmp_tbl.zero_offset(),
data_offset);
ip->set_jump_table(MCSJumpTablePtr(jmp));
}
if (inst.has_jump_index_table()) {
// create new jump table
const ::JumpIndexTbl &idx_tbl = inst.jump_index_table();
const auto &serialized_tbl = idx_tbl.table_entries();
std::vector<uint8_t> tbl_bytes(serialized_tbl.begin(),
serialized_tbl.end());
auto idx = new JumpIndexTable(tbl_bytes, idx_tbl.zero_offset());
ip->set_jump_index_table(JumpIndexTablePtr(idx));
}
if (inst.has_system_call_number()) {
ip->set_system_call_number(inst.system_call_number());
}
if (inst.has_local_noreturn()) {
ip->set_local_noreturn();
}
if (inst.has_offset_table_addr()) {
ip->offset_table = inst.offset_table_addr();
}
return ip;
}
static NativeBlockPtr DeserializeBlock(
const ::Block &block,
const std::list<ExternalCodeRefPtr> &extcode) {
auto block_va = static_cast<VA>(block.base_address());
NativeBlockPtr natB = NativeBlockPtr(new NativeBlock(block_va));
for (auto &inst : block.insts()) {
auto native_inst = DeserializeInst(inst, extcode);
if (!native_inst) {
std::cerr
<< "Unable to deserialize block at " << std::hex
<< block_va << std::endl;
return nullptr;
}
natB->add_inst(native_inst);
}
/* add the follows */
for (auto &succ : block.block_follows()) {
natB->add_follow(succ);
}
return natB;
}
static NativeFunctionPtr DeserializeNativeFunc(
const ::Function &func,
const std::list<ExternalCodeRefPtr> &extcode) {
NativeFunction *nf = nullptr;
if (func.has_symbol_name() && !func.symbol_name().empty()) {
nf = new NativeFunction(func.entry_address(), func.symbol_name());
} else {
nf = new NativeFunction(func.entry_address());
}
//read all the blocks from this function
for (auto &block : func.blocks()) {
auto native_block = DeserializeBlock(block, extcode);
if (!native_block) {
std::cerr
<< "Unable to deserialize function at " << std::hex
<< func.entry_address() << std::endl;
return nullptr;
}
nf->add_block(native_block);
}
return NativeFunctionPtr(nf);
}
static ExternalCodeRef::CallingConvention DeserializeCallingConvention(
::ExternalFunction::CallingConvention k) {
switch (k) {
case ::ExternalFunction::CallerCleanup:
return ExternalCodeRef::CallerCleanup;
break;
case ::ExternalFunction::CalleeCleanup:
return ExternalCodeRef::CalleeCleanup;
break;
case ::ExternalFunction::FastCall:
return ExternalCodeRef::FastCall;
break;
case ::ExternalFunction::McsemaCall:
return ExternalCodeRef::McsemaCall;
break;
default:
throw TErr(__LINE__, __FILE__, "Unsupported CC");
}
}
static ExternalCodeRefPtr DeserializeExternFunc(const ::ExternalFunction &f) {
auto c = DeserializeCallingConvention(f.calling_convention());
const auto &symName = f.symbol_name();
ExternalCodeRef::ReturnType retTy;
auto argCount = f.argument_count();
if (f.has_return()) {
retTy = ExternalCodeRef::IntTy;
} else {
retTy = ExternalCodeRef::VoidTy;
}
if (f.no_return()) {
retTy = ExternalCodeRef::NoReturn;
}
ExternalCodeRefPtr ext = ExternalCodeRefPtr(
new ExternalCodeRef(symName, argCount, c, retTy));
ext->setWeak(f.is_weak());
return ext;
}
static ExternalDataRefPtr DeserializeExternData(const ::ExternalData &ed) {
ExternalDataRefPtr ext = ExternalDataRefPtr(
new ExternalDataRef(ed.symbol_name(),
static_cast<size_t>(ed.data_size())));
ext->setWeak(ed.is_weak());
return ext;
}
static DataSectionEntry DeserializeDataSymbol(const ::DataSymbol &ds) {
std::cerr
<< "Deserializing symbol at: " << std::hex << ds.base_address() << ", "
<< ds.symbol_name() << ", " << ds.symbol_size() << std::endl;
return DataSectionEntry(ds.base_address(), ds.symbol_name(), ds.symbol_size());
}
static DataSectionEntry makeDSEBlob(const std::vector<uint8_t> &bytes,
uint64_t start, // offset in bytes vector
uint64_t end, // offset in bytes vector
uint64_t base_va) // virtual address these bytes are based at
{
std::vector<uint8_t> blob_bytes(bytes.begin() + (start),
bytes.begin() + (end));
return DataSectionEntry(base_va, blob_bytes);
}
static void DeserializeData(const ::Data &d, DataSection &ds) {
const auto &dt = d.data();
std::vector<uint8_t> bytes(dt.begin(), dt.end());
uint64_t base_address = d.base_address();
uint64_t cur_pos = base_address;
ds.setReadOnly(d.read_only());
//DataSectionEntry dse(d.base_address(), bytes);
std::vector<uint8_t>::iterator bytepos = bytes.begin();
// assumes symbols are in-order
for (int i = 0; i < d.symbols_size(); i++) {
DataSectionEntry dse_sym = DeserializeDataSymbol(d.symbols(i));
auto dse_base = dse_sym.getBase();
std::cerr
<< "cur_pos: " << std::hex << cur_pos << std::endl
<< "dse_base: " << std::hex << dse_base << std::endl;
// symbol next to blob
if (dse_base > cur_pos) {
ds.addEntry(
makeDSEBlob(bytes, cur_pos - base_address, dse_base - base_address,
cur_pos));
ds.addEntry(dse_sym);
cur_pos = dse_base + dse_sym.getSize();
std::cerr
<< "new_cur_pos: " << std::hex << cur_pos << std::endl;
// symbols next to each other
} else if (dse_base == cur_pos) {
ds.addEntry(dse_sym);
cur_pos = dse_base + dse_sym.getSize();
std::cerr
<< "new_cur_pos2: " << std::hex << cur_pos << std::endl;
} else {
std::cerr
<< __FILE__ << ":" << __LINE__ << std::endl
<< "Deserialized an out-of-order symbol!" << std::endl;
throw TErr(__LINE__, __FILE__, "Deserialized an out-of-order symbol!");
}
}
// there is a data blob after the last symbol
// or there are no symbols
if (cur_pos < base_address + bytes.size()) {
ds.addEntry(
makeDSEBlob(bytes, cur_pos - base_address, bytes.size(), cur_pos));
}
}
NativeModulePtr ReadProtoBuf(const std::string &file_name) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
NativeModulePtr m = nullptr;
::Module proto;
std::ifstream fstream(file_name, std::ios::binary);
if (!fstream.good()) {
std::cerr << "Failed to open file " << file_name << std::endl;
return m;
}
//read the protobuf object in
if (!proto.ParseFromIstream(&fstream)) {
std::cerr << "Failed to deserialize protobuf module" << std::endl;
return m;
}
std::unordered_map<VA, NativeFunctionPtr> native_funcs;
std::list<ExternalCodeRefPtr> extern_funcs;
std::list<ExternalDataRefPtr> extern_data;
std::list<DataSection> data_sections;
std::list<MCSOffsetTablePtr> offset_tables;
std::cerr << "Deserializing externs..." << std::endl;
for (const auto &external_func : proto.external_funcs()) {
extern_funcs.push_back(DeserializeExternFunc(external_func));
}
std::cerr << "Deserializing functions..." << std::endl;
for (const auto &internal_func : proto.internal_funcs()) {
auto natf = DeserializeNativeFunc(internal_func, extern_funcs);
if (!natf) {
std::cerr << "Unable to deserialize module." << std::endl;
return nullptr;
}
native_funcs[static_cast<VA>(internal_func.entry_address())] = natf;
}
std::cerr << "Deserializing data..." << std::endl;
for (auto &internal_data_elem : proto.internal_data()) {
DataSection ds;
DeserializeData(internal_data_elem, ds);
data_sections.push_back(ds);
}
std::cerr << "Deserializing external data..." << std::endl;
for (const auto &exteral_data_elem : proto.external_data()) {
extern_data.push_back(DeserializeExternData(exteral_data_elem));
}
for (const auto &offset_table : proto.offset_tables()) {
std::vector<std::pair<VA, VA>> v;
for (auto j = 0; j < offset_table.table_offsets_size(); j++) {
v.push_back(
std::make_pair<VA, VA>(offset_table.table_offsets(j),
offset_table.destinations(j)));
}
MCSOffsetTablePtr t(new MCSOffsetTable(v, 0, offset_table.start_addr()));
offset_tables.push_back(t);
}
std::cerr << "Creating module..." << std::endl;
m = NativeModulePtr(
new NativeModule(proto.module_name(), native_funcs, ArchTriple()));
//populate the module with externals calls
std::cerr << "Adding external funcs..." << std::endl;
for (auto &extern_func_call : extern_funcs) {
m->addExtCall(extern_func_call);
}
//populate the module with externals data
std::cerr << "Adding external data..." << std::endl;
for (auto &extern_data_ref : extern_data) {
m->addExtDataRef(extern_data_ref);
}
//populate the module with internal data
std::cerr << "Adding internal data..." << std::endl;
for (auto &data_section : data_sections) {
m->addDataSection(data_section);
}
std::cerr << "Adding Offset Tables..." << std::endl;
m->addOffsetTables(offset_tables);
// set entry points for the module
std::cerr << "Adding entry points..." << std::endl;
for (const auto &entry_symbol : proto.entries()) {
NativeEntrySymbol native_es(
entry_symbol.entry_name(),
entry_symbol.entry_address());
if (entry_symbol.has_entry_extra()) {
const auto &ese = entry_symbol.entry_extra();
auto c = DeserializeCallingConvention(ese.entry_cconv());
native_es.setExtra(ese.entry_argc(), ese.does_return(), c);
}
m->addEntryPoint(native_es);
}
std::cerr << "Returning module..." << std::endl;
return m;
}
| 26.875602 | 81 | 0.671066 | [
"object",
"vector"
] |
feb3c97a3717c919653c431040eeb823b8e67775 | 290 | cpp | C++ | src/0168.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0168.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0168.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
class Solution {
public:
string convertToTitle(int n) {
string s;
if (n > 26)s += convertToTitle((n - 1) / 26);
s += 'A' + (n - 1) % 26;
return s;
}
}; | 17.058824 | 49 | 0.603448 | [
"vector"
] |
feb41b495c592421aae1ea22b78d78e5bbaa4ef1 | 34,204 | cpp | C++ | EU4toV2/Source/V2World/Province/Province.cpp | ParadoxGameConverters/EU4toVic2 | 17a61d5662da02abcb976403cb50da365ef7061d | [
"MIT"
] | 42 | 2018-12-22T03:59:43.000Z | 2022-02-03T10:45:42.000Z | EU4toV2/Source/V2World/Province/Province.cpp | DrDudelsack/EU4toVic2 | 06da665b3eaa6e14d240f65f02caf9ffb7085b5b | [
"MIT"
] | 336 | 2018-12-22T17:15:27.000Z | 2022-03-02T11:19:32.000Z | EU4toV2/Source/V2World/Province/Province.cpp | DrDudelsack/EU4toVic2 | 06da665b3eaa6e14d240f65f02caf9ffb7085b5b | [
"MIT"
] | 56 | 2018-12-22T19:13:23.000Z | 2022-01-01T23:08:53.000Z | #include "Province.h"
#include "../../Configuration.h"
#include "../../EU4World/Regions/Regions.h"
#include "../../Mappers/CountryMappings/CountryMappings.h"
#include "../../Mappers/CultureMapper/CultureMapper.h"
#include "../../Mappers/Geography/Continents.h"
#include "../../Mappers/ReligionMapper/ReligionMapper.h"
#include "../Army/Regiment.h"
#include "../Country/Country.h"
#include "CommonFunctions.h"
#include "Log.h"
#include "OSCompatibilityLayer.h"
#include <algorithm>
#include <cmath>
V2::Province::Province(std::string _filename,
const mappers::ClimateMapper& climateMapper,
const mappers::TerrainDataMapper& terrainDataMapper,
const ProvinceNameParser& provinceNameParser,
const mappers::NavalBaseMapper& navalBaseMapper):
filename(std::move(_filename))
{
const auto temp = trimPath(filename);
try
{
provinceID = std::stoi(temp);
}
catch (std::exception& e)
{
Log(LogLevel::Error) << "Failed to extract province number from file name: " << filename << " " << e.what();
throw std::runtime_error("Failed to extract province number from file name: " + filename + " " + e.what());
}
// In case we're overriding provinces (not true by default)
if (commonItems::DoesFileExist("blankMod/output/history/provinces/" + filename))
{
details = mappers::ProvinceDetailsMapper("blankMod/output/history/provinces/" + filename).getProvinceDetails();
}
else
{
details = mappers::ProvinceDetailsMapper(theConfiguration.getVic2Path() + "/history/provinces/" + filename).getProvinceDetails();
}
for (const auto& climate: climateMapper.getClimateMap())
{
if (count(climate.second.begin(), climate.second.end(), provinceID))
{
details.climate = climate.first;
break;
}
}
if (details.terrain.empty() && !theConfiguration.isHpmEnabled())
{
auto terrain = terrainDataMapper.getTerrainForID(provinceID);
if (terrain)
details.terrain = *terrain;
}
auto potentialName = provinceNameParser.getProvinceName(provinceID);
if (potentialName)
name = *potentialName;
if (navalBaseMapper.isProvinceCoastal(provinceID))
coastal = true;
}
std::optional<std::string> V2::Province::getDominantCulture()
{
if (pops.empty())
return std::nullopt;
std::map<std::string, long> census;
for (const auto& pop: pops)
census[pop->getCulture()] += pop->getSize();
using pair_type = decltype(census)::value_type;
const auto pr = std::max_element(std::begin(census), std::end(census), [](const pair_type& p1, const pair_type& p2) {
return p1.second < p2.second;
});
return pr->first;
}
void V2::Province::addVanillaPop(std::shared_ptr<Pop> vanillaPop)
{
vanillaPops.push_back(vanillaPop);
vanillaPopulation += vanillaPop->getSize();
}
void V2::Province::addMinorityPop(std::shared_ptr<Pop> minorityPop)
{
minorityPops.push_back(minorityPop);
}
void V2::Province::addCore(const std::string& newCore)
{
// only add if not a territorial core/colony of the current owner
if (!(newCore == details.owner && territorialCore))
{
details.cores.insert(newCore);
}
}
void V2::Province::convertFromOldProvince(const std::vector<std::shared_ptr<EU4::Province>>& provinceSources,
const std::map<std::string, std::shared_ptr<EU4::Country>>& theEU4Countries,
const EU4::Regions& eu4Regions,
mappers::CultureMapper& cultureMapper,
const mappers::CultureMapper& slaveCultureMapper,
const mappers::Continents& continentsMapper,
const mappers::ReligionMapper& religionMapper,
const mappers::CountryMappings& countryMapper,
const mappers::ProvinceMapper& provinceMapper,
bool hreDecentralized,
const std::optional<std::string>& v2HreTag)
{
// Drop vanilla cores
details.cores.clear();
if (provinceSources.empty())
return; // Let's not do damage.
// Store the numbers.
for (const auto& oldProvince: provinceSources)
eu4IDs.insert(oldProvince->getNum());
// Single HRE province is enough
for (const auto& oldProvince: provinceSources)
{
if (oldProvince->inHre())
{
inHRE = true;
if (!hreDecentralized)
{
if (v2HreTag)
{
addCore(*v2HreTag);
}
else
{
addCore("HLR");
}
}
}
}
territorialCore = false; // A single territorial core will be sufficient to trip this.
for (const auto& oldProvince: provinceSources)
{
if (!oldProvince->isCity())
{
colonial = 1;
territorialCore = true;
}
else if (oldProvince->isTerritorialCore())
{
colonial = 2;
territorialCore = true;
}
else
{
colonial = 0;
}
}
// Single colonized province is enough
for (const auto& oldProvince: provinceSources)
if (oldProvince->wasColonized())
wasColonised = true;
// For buildings, we go with averages.
for (const auto& oldProvince: provinceSources)
{
// TODO: Dump buildings and values into own parser - duplication at EU4::Country
if (oldProvince->hasBuilding("weapons"))
++mfgCount;
if (oldProvince->hasBuilding("wharf"))
++mfgCount;
if (oldProvince->hasBuilding("textile"))
++mfgCount;
if (oldProvince->hasBuilding("plantations"))
++mfgCount;
if (oldProvince->hasBuilding("tradecompany"))
++mfgCount;
if (oldProvince->hasBuilding("farm_estate"))
++mfgCount;
if (oldProvince->hasBuilding("mills"))
++mfgCount;
if (oldProvince->hasBuilding("furnace"))
mfgCount += 3;
// Shipyard and dock are worthless in terms of 19th century. However, grand shipyard and dry-dock are cumulative.
if (oldProvince->hasBuilding("grand_shipyard"))
++navalBaseLevel;
if (oldProvince->hasBuilding("naval_base") && !oldProvince->hasBuilding("grand_shipyard"))
++navalBaseLevel; // obsolete, but not cumulative if it appears
if (oldProvince->hasBuilding("drydock"))
++navalBaseLevel;
// castle, bastion and star fort are worthless against 19th century artillery.
if (oldProvince->hasBuilding("fort_18th"))
++fortLevel;
if (oldProvince->hasBuilding("fort6"))
++fortLevel; // obsolete, exclusive with fort_18th_century
// Add up different building types.
auto provinceBuildings = oldProvince->getBuildings();
importedBuildings.insert(provinceBuildings.begin(), provinceBuildings.end());
}
mfgCount = lround(mfgCount / provinceSources.size()); // Since these are built everywhere, use average.
navalBaseLevel = std::min(navalBaseLevel, 2); // Don't go over 2 for naval bases.
fortLevel = std::min(fortLevel, 1); // Don't go over 1 for forts.
const auto& countryItr = theEU4Countries.find(provinceSources[0]->getOwnerString());
if (countryItr != theEU4Countries.end())
{
importedIdeas = countryItr->second->exportNationalIdeas();
}
for (const auto& oldProvince: provinceSources)
for (const auto& core: oldProvince->getCores())
{
auto potentialCore = countryMapper.getV2Tag(core);
if (potentialCore)
addCore(*potentialCore);
}
determineColonial(); // Sanity check at most, we would probably be ok without it.
// onto development and weight data
// Extreme rebalancing note:
// When mapping M-to-N, generally speaking, we're summing up all incoming development, and distributing
// it across target provinces. This way we maintain total investment and aren't wasting dev.
//
// Devpush shaping note:
// For devpush we're averaging our investment factor from the incoming provinces, without regard to other
// provinces around us.
std::set<int> coTargets; // These would be all the target provinces in the same mapping link.
for (const auto& oldProvince: provinceSources)
{
const auto& targets = provinceMapper.getVic2ProvinceNumbers(oldProvince->getNum());
coTargets.insert(targets.begin(), targets.end());
investmentFactor += oldProvince->getInvestmentFactor() / 100.0;
provinceWeight += oldProvince->getProvinceWeight();
}
investmentFactor /= static_cast<double>(provinceSources.size());
const auto totalSourceDevelopmentWeight = provinceWeight;
provinceWeight /= static_cast<double>(coTargets.size()); // dividing by target provinces.
// And finally, demographics
for (const auto& oldProvince: provinceSources)
{
const auto provincePopulationWeight = oldProvince->getProvinceWeight() / totalSourceDevelopmentWeight;
auto popRatios = oldProvince->getPopRatios();
determineDemographics(eu4Regions,
popRatios,
oldProvince->getNum(),
oldProvince->getOwnerString(),
provinceID,
provincePopulationWeight,
cultureMapper,
slaveCultureMapper,
continentsMapper,
religionMapper);
}
}
void V2::Province::sterilizeProvince()
{
details.owner = "";
details.controller = "";
details.cores.clear();
details.colonial = 0;
details.colonyLevel = 0;
details.navalBaseLevel = 0;
details.fortLevel = 0;
details.railLevel = 0;
}
void V2::Province::determineDemographics(const EU4::Regions& eu4Regions,
std::vector<EU4::PopRatio>& popRatios,
int eu4ProvID,
const std::string& oldOwnerTag,
int destNum,
double provPopRatio,
mappers::CultureMapper& cultureMapper,
const mappers::CultureMapper& slaveCultureMapper,
const mappers::Continents& continentsMapper,
const mappers::ReligionMapper& religionMapper)
{
for (const auto& popRatio: popRatios)
{
auto dstCulture = cultureMapper.cultureMatch(eu4Regions, popRatio.getCulture(), popRatio.getReligion(), eu4ProvID, oldOwnerTag);
if (!dstCulture)
{
// No panic, yet. We may be dealing with a neoculture.
if (!popRatio.getOriginalCulture().empty())
{
// This is a neoculture. Failure to map is not an option. Locate a mapping based on original culture if one exists, but ping for
// area, region or superregion. We're not interested in general mappings.
dstCulture = cultureMapper.cultureRegionalMatch(eu4Regions, popRatio.getOriginalCulture(), popRatio.getReligion(), eu4ProvID, oldOwnerTag);
if (!dstCulture)
{
// There is no overriding rule. We're good to force neoculture.
generatedNeoCultures.insert(std::make_pair(popRatio.getOriginalCulture(), popRatio.getCulture()));
superRegion = popRatio.getSuperRegion();
dstCulture.emplace(popRatio.getCulture());
}
}
}
if (!dstCulture)
{
Log(LogLevel::Warning) << "Could not convert eu4 culture " << popRatio.getCulture() << " for pops in Vic2 province " << destNum
<< "! Check mappings, substituting noculture.";
dstCulture.emplace("noculture");
}
else if (*dstCulture == "noculture")
{
Log(LogLevel::Warning) << "Incoming eu4 noculture pops for Vic2 province " << destNum
<< "! Your EU4 save seems borked there, troubles with CK2 import?";
}
auto religion = religionMapper.getVic2Religion(popRatio.getReligion());
if (!religion)
{
Log(LogLevel::Warning) << "Could not convert eu4 religion " << popRatio.getReligion() << " for pops in Vic2 province " << destNum
<< "! Check mappings, substituting no_religion.";
religion.emplace("noreligion");
}
else if (*religion == "noreligion")
{
Log(LogLevel::Warning) << "Incoming eu4 noreligion pops for Vic2 province " << destNum
<< "! Your EU4 save seems borked there, troubles with CK2 import?";
}
auto slaveCulture = slaveCultureMapper.cultureMatch(eu4Regions, popRatio.getCulture(), popRatio.getReligion(), eu4ProvID, oldOwnerTag);
auto thisContinent = continentsMapper.getEU4Continent(eu4ProvID);
if (!slaveCulture && !popRatio.getOriginalCulture().empty())
slaveCulture = slaveCultureMapper.cultureMatch(eu4Regions, popRatio.getOriginalCulture(), popRatio.getReligion(), eu4ProvID, oldOwnerTag);
if (!slaveCulture)
{
if (thisContinent && (*thisContinent == "asia" || *thisContinent == "africa" || *thisContinent == "oceania"))
{
Log(LogLevel::Warning) << "No mapping for slave culture " << popRatio.getCulture() << "(" << popRatio.getOriginalCulture() << ")/"
<< popRatio.getReligion() << " in province " << destNum << "/" << *thisContinent << " - using native culture ("
<< popRatio.getCulture() << ").";
slaveCulture.emplace(popRatio.getCulture());
}
else
{
Log(LogLevel::Warning) << "No mapping for slave culture " << popRatio.getCulture() << "(" << popRatio.getOriginalCulture() << ")/"
<< popRatio.getReligion() << " for pops in Vic2 province " << destNum << "/" << *thisContinent << " - using african_minor.";
slaveCulture.emplace("african_minor");
}
}
Demographic demographic;
demographic.culture = *dstCulture;
demographic.slaveCulture = *slaveCulture;
demographic.religion = *religion;
demographic.upperRatio = popRatio.getUpperRatio() * provPopRatio;
demographic.middleRatio = popRatio.getMiddleRatio() * provPopRatio;
demographic.lowerRatio = popRatio.getLowerRatio() * provPopRatio;
if (theConfiguration.getDebug())
{
Log(LogLevel::Info) << "EU4 Province " << eu4ProvID << ", "
<< "Vic2 Province " << provinceID << ", "
<< "Culture: " << demographic.culture << ", "
<< "Religion: " << demographic.religion << ", "
<< "upperPopRatio: " << popRatio.getUpperRatio() << ", "
<< "middlePopRatio: " << popRatio.getMiddleRatio() << ", "
<< "lowerPopRatio: " << popRatio.getLowerRatio() << ", "
<< "provPopRatio: " << provPopRatio << ", "
<< "upperRatio: " << demographic.upperRatio << ", "
<< "middleRatio: " << demographic.middleRatio << ", "
<< "lowerRatio: " << demographic.lowerRatio;
}
demographics.push_back(demographic);
}
}
std::optional<std::shared_ptr<V2::Factory>> V2::Province::addFactory(std::shared_ptr<Factory> factory)
{
auto itr = factories.find(factory->getTypeName());
if (itr == factories.end())
{
factories.insert(std::make_pair(factory->getTypeName(), factory));
return std::move(factory);
}
itr->second->increaseLevel();
return std::nullopt;
}
void V2::Province::addPopDemographic(const Demographic& d)
{
auto combined = false;
for (auto& demographic: demographics)
{
if (demographic.culture == d.culture && demographic.religion == d.religion)
{
combined = true;
demographic.upperRatio += d.upperRatio;
demographic.middleRatio += d.middleRatio;
demographic.lowerRatio += d.lowerRatio;
}
}
if (!combined)
{
demographics.push_back(d);
}
}
void V2::Province::determineColonial()
{
if (territorialCore && colonial == 0)
colonial = 2;
}
int V2::Province::getTotalPopulation() const
{
auto total = 0;
for (const auto& pop: pops)
total += pop->getSize();
return total;
}
std::vector<std::string> V2::Province::getCulturesOverThreshold(double percentOfPopulation) const
{
const auto totalPopulation = getTotalPopulation();
if (!totalPopulation)
return std::vector<std::string>();
std::map<std::string, int> cultureTotals;
for (const auto& pop: pops)
cultureTotals[pop->getCulture()] += pop->getSize();
std::vector<std::string> culturesOverThreshold;
for (const auto& cultureAmount: cultureTotals)
{
if (static_cast<double>(cultureAmount.second) / totalPopulation >= percentOfPopulation)
{
culturesOverThreshold.push_back(cultureAmount.first);
}
}
return culturesOverThreshold;
}
std::optional<std::pair<int, std::vector<std::shared_ptr<V2::Pop>>>> V2::Province::getPopsForOutput() const
{
// TODO: This functionality is wrong. We don't need vanilla pops but customized pops from surrounding areas.
if (resettable && theConfiguration.getResetProvinces() == "yes" && !vanillaPops.empty())
{
return std::pair(provinceID, vanillaPops);
}
if (!pops.empty())
return std::pair(provinceID, pops);
if (!vanillaPops.empty())
return std::pair(provinceID, vanillaPops);
return std::nullopt;
}
void V2::Province::doCreatePops(const double popWeightRatio,
Country* _owner,
const CIV_ALGORITHM popConversionAlgorithm,
const mappers::ProvinceMapper& provinceMapper)
{
// Override for VN and provinces that don't exist in the mapper, we are moving vanilla pops into actual pops.
if (theConfiguration.isVN() && provinceMapper.getEU4ProvinceNumbers(provinceID).empty())
{
pops = vanillaPops;
return;
}
// convert pops
for (const auto& demographic: demographics)
{
createPops(demographic, popWeightRatio, _owner, popConversionAlgorithm, provinceMapper);
}
combinePops();
// organize pops for adding minorities
std::map<std::string, int> totals;
std::map<std::string, std::vector<std::shared_ptr<Pop>>> thePops;
for (const auto& pop: pops)
{
auto type = pop->getType();
totals[type] += pop->getSize();
thePops[type].push_back(pop);
}
// decrease non-minority pops and create the minorities
std::vector<std::shared_ptr<Pop>> actualMinorities;
for (const auto& minority: minorityPops)
{
const auto totalTypePopulation = totals[minority->getType()];
auto thePopsItr = thePops.find(minority->getType());
if (thePopsItr != thePops.end())
{
for (const auto& popsItr: thePopsItr->second)
{
auto newCulture = minority->getCulture();
auto newReligion = minority->getReligion();
if (newCulture.empty())
newCulture = popsItr->getCulture();
if (newReligion.empty())
newReligion = popsItr->getReligion();
auto newMinority =
std::make_shared<Pop>(minority->getType(), lround(popsItr->getSize() / totalTypePopulation * minority->getSize()), newCulture, newReligion);
actualMinorities.push_back(newMinority);
popsItr->changeSize(static_cast<int>(-1.0 * popsItr->getSize() / totalTypePopulation * minority->getSize()));
}
}
}
// add minority pops to the main pops
for (const auto& minority: actualMinorities)
{
pops.push_back(minority);
}
combinePops();
}
V2::Province::pop_points V2::Province::getPopPoints_1(const Demographic& demographic, const double newPopulation, const Country* _owner) const
{
pop_points pts;
auto govBuilding = 0;
if (importedBuildings.count("temple"))
{
govBuilding = 1;
}
else if (importedBuildings.count("courthouse"))
{
govBuilding = 2;
}
else if (importedBuildings.count("spy_agency"))
{
govBuilding = 3;
}
else if (importedBuildings.count("town_hall"))
{
govBuilding = 4;
}
else if (importedBuildings.count("college"))
{
govBuilding = 6;
}
else if (importedBuildings.count("cathedral"))
{
govBuilding = 8;
}
auto armyBuilding = 0;
if (importedBuildings.count("armory"))
{
armyBuilding = 1;
}
else if (importedBuildings.count("training_fields"))
{
armyBuilding = 2;
}
else if (importedBuildings.count("barracks"))
{
armyBuilding = 3;
}
else if (importedBuildings.count("regimental_camp"))
{
armyBuilding = 4;
}
else if (importedBuildings.count("arsenal"))
{
armyBuilding = 6;
}
else if (importedBuildings.count("conscription_center"))
{
armyBuilding = 8;
}
if (importedBuildings.count("ramparts"))
armyBuilding += 4;
if (importedBuildings.count("soldier_households"))
armyBuilding += 8;
if (importedBuildings.count("impressment_offices"))
armyBuilding += 4;
if (importedBuildings.count("coastal_defence"))
armyBuilding += 4;
auto productionBuilding = 0;
if (importedBuildings.count("constable"))
{
productionBuilding = 1;
}
else if (importedBuildings.count("workshop"))
{
productionBuilding = 2;
}
else if (importedBuildings.count("counting_house"))
{
productionBuilding = 3;
}
else if (importedBuildings.count("treasury_office"))
{
productionBuilding = 4;
}
else if (importedBuildings.count("mint"))
{
productionBuilding = 6;
}
else if (importedBuildings.count("stock_exchange"))
{
productionBuilding = 8;
}
auto tradeBuilding = 0;
if (importedBuildings.count("marketplace"))
{
tradeBuilding = 1;
}
else if (importedBuildings.count("trade_depot"))
{
tradeBuilding = 2;
}
else if (importedBuildings.count("canal"))
{
tradeBuilding = 3;
}
else if (importedBuildings.count("road_network"))
{
tradeBuilding = 4;
}
else if (importedBuildings.count("post_office"))
{
tradeBuilding = 6;
}
else if (importedBuildings.count("customs_house"))
{
tradeBuilding = 8;
}
pts.artisans += 400;
pts.artisans += static_cast<double>(productionBuilding) * 125;
pts.soldiers += 100;
pts.soldiers += static_cast<double>(armyBuilding) * 45;
if (importedIdeas.count("quantity_ideas"))
pts.soldiers *= 2;
pts.officers += 2 * (static_cast<double>(armyBuilding) + 2);
if (importedIdeas.count("quality_ideas"))
pts.officers += 5;
pts.clergymen += 95;
if (importedIdeas.count("religious_ideas"))
pts.clergymen += 10;
if (importedIdeas.count("innovative_ideas"))
pts.clergymen += 10;
pts.bureaucrats += 10;
pts.bureaucrats += static_cast<double>(govBuilding) * 2;
if (importedIdeas.count("administrative_ideas"))
pts.bureaucrats += 10;
if (importedIdeas.count("expansion_ideas") && wasColonised)
pts.bureaucrats += 10;
if (importedBuildings.count("state_house"))
pts.bureaucrats *= 2;
pts.aristocrats += 7 * (static_cast<double>(tradeBuilding) + 11);
if (importedBuildings.count("farm_estate") || importedBuildings.count("plantations"))
pts.aristocrats *= 2;
if (importedIdeas.count("aristocracy_ideas"))
pts.aristocrats *= 2;
if (!factories.empty())
{
const auto capsPerFactory = 40 + static_cast<double>(_owner->getNumFactories()) * 2;
const auto actualCapitalists =
static_cast<double>(factories.size()) * static_cast<double>(_owner->getNumFactories()) * capsPerFactory * demographic.upperRatio;
pts.capitalists += 10000 * actualCapitalists / (demographic.upperRatio * newPopulation);
const auto actualClerks = 181 * static_cast<double>(factories.size()) * demographic.middleRatio;
pts.clerks += 10000 * actualClerks / (demographic.middleRatio * newPopulation);
const auto actualCraftsmen = 2639 * static_cast<double>(factories.size()) * demographic.lowerRatio;
pts.craftsmen += 10000 * actualCraftsmen / (demographic.lowerRatio * newPopulation);
}
return pts;
}
V2::Province::pop_points V2::Province::getPopPoints_2(const Demographic& demographic, const double newPopulation, const Country* _owner) const
{
pop_points pts;
auto adminBuilding = 0;
if (importedBuildings.count("courthouse"))
{
adminBuilding = 1;
}
else if (importedBuildings.count("town_hall"))
{
adminBuilding = 2;
}
auto taxBuilding = 0;
if (importedBuildings.count("temple"))
{
taxBuilding = 1;
}
else if (importedBuildings.count("cathedral"))
{
taxBuilding = 2;
}
auto manpowerBuilding = 0;
if (importedBuildings.count("barracks"))
{
manpowerBuilding = 1;
}
else if (importedBuildings.count("training_fields"))
{
manpowerBuilding = 2;
}
auto armyBuilding = 0;
if (importedBuildings.count("regimental_camp"))
{
armyBuilding = 1;
}
else if (importedBuildings.count("conscription_center"))
{
armyBuilding = 2;
}
auto productionBuilding = 0;
if (importedBuildings.count("workshop"))
{
productionBuilding = 1;
}
else if (importedBuildings.count("counting_house"))
{
productionBuilding = 2;
}
auto tradeBuilding = 0;
if (importedBuildings.count("marketplace"))
{
tradeBuilding = 1;
}
else if (importedBuildings.count("trade_depot"))
{
tradeBuilding = 2;
}
else if (importedBuildings.count("stock_exchange"))
{
tradeBuilding = 3;
}
pts.artisans += 400;
pts.artisans += static_cast<double>(productionBuilding) * 500;
pts.soldiers += 100;
pts.soldiers += (static_cast<double>(manpowerBuilding) + static_cast<double>(armyBuilding)) * 90;
if (importedIdeas.count("quantity_ideas"))
pts.soldiers *= 2;
pts.officers += 4 * (static_cast<double>(manpowerBuilding) + static_cast<double>(armyBuilding) + 2.0);
if (importedIdeas.count("quality_ideas"))
pts.officers += 5;
pts.clergymen += 65;
if (importedIdeas.count("religious_ideas"))
pts.clergymen += 10;
if (importedIdeas.count("innovative_ideas"))
pts.clergymen += 10;
if (importedBuildings.count("university"))
pts.clergymen *= 2;
pts.bureaucrats += 10;
pts.bureaucrats += (static_cast<double>(adminBuilding) + static_cast<double>(taxBuilding)) * 4;
if (importedIdeas.count("administrative_ideas"))
pts.bureaucrats += 10;
if (importedIdeas.count("expansion_ideas") && wasColonised)
pts.bureaucrats += 10;
pts.aristocrats += 14 * (static_cast<double>(tradeBuilding) + 6.0);
if (importedBuildings.count("farm_estate") || importedBuildings.count("plantations"))
pts.aristocrats *= 2;
if (importedIdeas.count("aristocracy_ideas"))
pts.aristocrats *= 2;
if (!factories.empty())
{
auto const capsPerFactory = 40 + static_cast<double>(_owner->getNumFactories()) * 2;
auto const actualCapitalists =
static_cast<double>(factories.size()) * static_cast<double>(_owner->getNumFactories()) * capsPerFactory * demographic.upperRatio;
pts.capitalists += 10000 * actualCapitalists / (demographic.upperRatio * newPopulation);
auto const actualClerks = 493 * static_cast<double>(factories.size()) * demographic.middleRatio;
pts.clerks += 10000 * actualClerks / (demographic.middleRatio * newPopulation);
auto const actualCraftsmen = 8170 * static_cast<double>(factories.size()) * demographic.lowerRatio;
pts.craftsmen += 10000 * actualCraftsmen / (demographic.lowerRatio * newPopulation);
}
return pts;
}
void V2::Province::createPops(const Demographic& demographic,
double popWeightRatio,
const Country* _owner,
CIV_ALGORITHM popConversionAlgorithm,
const mappers::ProvinceMapper& provinceMapper)
{
long newPopulation = 0;
const auto shapeFactor = theConfiguration.getPopShapingFactor() / 100.0;
const auto lifeRatingMod = (static_cast<double>(details.lifeRating) - 35.0) / 200.0;
const auto provinceDevModifier = 1 + (lifeRatingMod + investmentFactor * shapeFactor);
switch (theConfiguration.getPopShaping())
{
case Configuration::POPSHAPES::Vanilla:
newPopulation = vanillaPopulation;
break;
case Configuration::POPSHAPES::PopShaping:
newPopulation = static_cast<long>(vanillaPopulation * provinceDevModifier);
break;
case Configuration::POPSHAPES::Extreme:
newPopulation = static_cast<long>(popWeightRatio * provinceWeight);
newPopulation = vanillaPopulation + static_cast<long>((newPopulation - vanillaPopulation) * shapeFactor);
break;
}
pop_points pts;
switch (popConversionAlgorithm)
{
case CIV_ALGORITHM::older:
pts = getPopPoints_1(demographic, newPopulation, _owner);
break;
case CIV_ALGORITHM::newer:
pts = getPopPoints_2(demographic, newPopulation, _owner);
break;
}
// Uncivilized cannot have capitalists, clerks, or craftsmen, and get fewer bureaucrats
if (!_owner->isCivilized())
{
pts.capitalists = 0;
pts.clerks = 0;
pts.craftsmen = 0;
pts.bureaucrats -= 5;
}
int farmers = lround(demographic.lowerRatio * newPopulation);
if (slaveProportion > 0.0)
{
int size = lround(demographic.lowerRatio * newPopulation * slaveProportion);
farmers -= size;
auto slavesPop = std::make_shared<Pop>("slaves", size, demographic.slaveCulture, demographic.religion);
pops.push_back(slavesPop);
}
if (pts.soldiers > 0)
{
int size = lround(demographic.lowerRatio * newPopulation * (pts.soldiers / 10000));
farmers -= size;
auto soldiersPop = std::make_shared<Pop>("soldiers", size, demographic.culture, demographic.religion);
pops.push_back(soldiersPop);
}
if (pts.craftsmen > 0)
{
int size = lround(demographic.lowerRatio * newPopulation * (pts.craftsmen / 10000));
farmers -= size;
auto craftsmenPop = std::make_shared<Pop>("craftsmen", size, demographic.culture, demographic.religion);
pops.push_back(craftsmenPop);
}
if (pts.artisans > 0)
{
int size = lround(demographic.middleRatio * newPopulation * (pts.artisans / 10000));
farmers -= size;
auto artisansPop = std::make_shared<Pop>("artisans", size, demographic.culture, demographic.religion);
pops.push_back(artisansPop);
}
if (pts.clergymen > 0)
{
int size = lround(demographic.middleRatio * newPopulation * (pts.clergymen / 10000));
farmers -= size;
auto clergymenPop = std::make_shared<Pop>("clergymen", size, demographic.culture, demographic.religion);
pops.push_back(clergymenPop);
}
if (pts.clerks > 0)
{
int size = lround(demographic.middleRatio * newPopulation * (pts.clerks / 10000));
farmers -= size;
auto clerksPop = std::make_shared<Pop>("clerks", size, demographic.culture, demographic.religion);
pops.push_back(clerksPop);
}
if (pts.bureaucrats > 0)
{
int size = lround(demographic.middleRatio * newPopulation * (pts.bureaucrats / 10000));
farmers -= size;
auto bureaucratsPop = std::make_shared<Pop>("bureaucrats", size, demographic.culture, demographic.religion);
pops.push_back(bureaucratsPop);
}
if (pts.officers > 0)
{
int size = lround(demographic.middleRatio * newPopulation * (pts.officers / 10000));
farmers -= size;
auto officersPop = std::make_shared<Pop>("officers", size, demographic.culture, demographic.religion);
pops.push_back(officersPop);
}
if (pts.capitalists > 0)
{
int size = lround(demographic.upperRatio * newPopulation * (pts.capitalists / 10000));
farmers -= size;
auto capitalistsPop = std::make_shared<Pop>("capitalists", size, demographic.culture, demographic.religion);
pops.push_back(capitalistsPop);
}
if (pts.aristocrats > 0)
{
int size = lround(demographic.upperRatio * newPopulation * (pts.aristocrats / 10000));
farmers -= size;
auto aristocratsPop = std::make_shared<Pop>("aristocrats", size, demographic.culture, demographic.religion);
pops.push_back(aristocratsPop);
}
auto farmersPop = std::make_shared<Pop>("farmers", farmers, demographic.culture, demographic.religion);
pops.push_back(farmersPop);
}
void V2::Province::combinePops()
{
for (auto lhs = pops.begin(); lhs != pops.end(); ++lhs)
{
if ((*lhs)->isTrashed())
continue;
auto rhs = lhs;
for (++rhs; rhs != pops.end(); ++rhs)
{
if ((*rhs)->isTrashed())
continue;
if ((*lhs)->combine(**rhs))
{
(*rhs)->setTrashed();
continue;
}
if ((*rhs)->getSize() < 1)
{
(*rhs)->setTrashed();
}
}
}
std::vector<std::shared_ptr<Pop>> consolidatedPops;
for (const auto& pop: pops)
{
if (pop->isTrashed())
continue;
consolidatedPops.emplace_back(pop);
}
pops.swap(consolidatedPops);
}
// pick a soldier pop to use for an army. prefer larger pops to smaller ones, and grow only if necessary.
std::shared_ptr<V2::Pop> V2::Province::getSoldierPopForArmy(const bool force)
{
auto soldierPops = getPops("soldiers");
if (soldierPops.empty())
return nullptr; // no soldier pops
std::sort(soldierPops.begin(), soldierPops.end(), popSortBySizePredicate);
// try largest to smallest, without growing
for (auto soldier: soldierPops)
{
const auto growBy = getRequiredPopForRegimentCount(soldier->getSupportedRegimentCount() + 1) - soldier->getSize();
if (growBy <= 0)
{
if (growSoldierPop(*soldier)) // won't actually grow, but will increment supported regiment count
{
return soldier;
}
}
}
// try largest to smallest, trying to grow
for (const auto& soldier: soldierPops)
{
if (growSoldierPop(*soldier)) // Will actually grow and increment supported regiment count
{
return soldier;
}
}
// no suitable pops
if (force)
return soldierPops[0];
return nullptr;
}
std::vector<std::shared_ptr<V2::Pop>> V2::Province::getPops(const std::string& type) const
{
std::vector<std::shared_ptr<Pop>> retval;
for (const auto& pop: pops)
{
if (type == "*" || pop->getType() == type)
retval.push_back(pop);
}
return retval;
}
bool V2::Province::popSortBySizePredicate(std::shared_ptr<Pop> pop1, std::shared_ptr<Pop> pop2)
{
return pop1->getSize() > pop2->getSize();
}
// V2 requires 1000 for the first regiment and 3000 thereafter
// we require an extra 1/30 to stabilize the start of the game
int V2::Province::getRequiredPopForRegimentCount(const int count)
{
if (count == 0)
return 0;
return 1033 + (count - 1) * 3100;
}
bool V2::Province::growSoldierPop(Pop& pop)
{
const auto growBy = getRequiredPopForRegimentCount(pop.getSupportedRegimentCount() + 1) - pop.getSize();
if (growBy > 0)
{
// gotta grow; find a same-culture same-religion farmer/laborer to pull from
const auto provincePop = getTotalPopulation();
auto foundSourcePop = false;
for (auto& popSource: pops)
{
if (popSource->getType() == "farmers" || popSource->getType() == "labourers")
{
if (popSource->getCulture() == pop.getCulture() && popSource->getReligion() == pop.getReligion())
{
// don't let the farmer/laborer shrink beneath 10% of the province population
if (static_cast<double>(popSource->getSize()) - growBy > provincePop * 0.10)
{
popSource->changeSize(-growBy);
pop.changeSize(growBy);
foundSourcePop = true;
break;
}
}
}
}
if (!foundSourcePop)
return false;
}
pop.incrementSupportedRegimentCount();
return true;
}
std::string V2::Province::getRegimentName(const REGIMENTTYPE chosenType)
{
std::stringstream str;
str << ++unitNameCount[chosenType] << cardinalToOrdinal(unitNameCount[chosenType]); // 1st, 2nd, etc
str << " " << name << " "; // Hamburg, Lyon, etc
switch (chosenType)
{
case REGIMENTTYPE::irregular:
str << "Irregulars";
break;
case REGIMENTTYPE::infantry:
str << "Infantry";
break;
case REGIMENTTYPE::cavalry:
str << "Cavalry";
break;
case REGIMENTTYPE::artillery:
str << "Artillery";
break;
case REGIMENTTYPE::manowar:
str << "Man'o'war";
break;
case REGIMENTTYPE::frigate:
str << "Frigate";
break;
case REGIMENTTYPE::clipper_transport:
str << "Clipper Transport";
break;
}
return str.str();
}
std::pair<int, int> V2::Province::getAvailableSoldierCapacity() const
{
auto soldierCap = 0;
auto draftCap = 0;
const auto provincePop = getTotalPopulation();
for (const auto& soldier: pops)
{
if (soldier->getType() == "soldiers")
{
// unused capacity is the size of the pop minus the capacity already used, or 0, if it's already overdrawn
soldierCap += std::max(soldier->getSize() - getRequiredPopForRegimentCount(soldier->getSupportedRegimentCount()), 0);
}
else if (soldier->getType() == "farmers" || soldier->getType() == "labourers")
{
// unused capacity is the size of the pop in excess of 10% of the province pop, or 0, if it's already too small
draftCap += std::max(soldier->getSize() - int(0.10 * provincePop), 0);
}
}
return std::pair<int, int>(soldierCap, draftCap);
}
| 30.870036 | 146 | 0.705736 | [
"vector"
] |
feb781fb2c97984209c85f0e2efcd908f707ecdb | 1,961 | cpp | C++ | source/p6_frame.cpp | Meta-chan/P6 | 2323f3f12894d2eb01a777643f69301a368f9c69 | [
"MIT"
] | null | null | null | source/p6_frame.cpp | Meta-chan/P6 | 2323f3f12894d2eb01a777643f69301a368f9c69 | [
"MIT"
] | null | null | null | source/p6_frame.cpp | Meta-chan/P6 | 2323f3f12894d2eb01a777643f69301a368f9c69 | [
"MIT"
] | null | null | null | /*
This software is distributed under MIT License, which means:
- Do whatever you want
- Please keep this notice and include the license file to your project
- I provide no warranty
Created by Kyrylo Sovailo (github.com/Meta-chan, k.sovailo@gmail.com)
Reinventing bicycles since 2020
*/
#include "../header/p6_force_bar.hpp"
#include "../header/p6_frame.hpp"
#include <wx/dcbuffer.h>
#include <wx/display.h>
void p6::Frame::_on_paint(wxPaintEvent &e)
{
wxAutoBufferedPaintDC dc(_frame);
_main_panel.render(&dc, _frame->GetClientAreaOrigin());
}
void p6::Frame::_on_size(wxSizeEvent &e)
{
_main_panel.need_refresh();
_frame->Layout();
}
p6::Frame::Frame() noexcept :
_frame(new wxFrame(nullptr, wxID_ANY, "P6")),
_sizer(new wxBoxSizer(wxHORIZONTAL)),
_menubar(this),
_toolbar(this),
_main_panel(this),
_side_panel(this),
_mouse(this)
{
//Set icon
wxIcon icon;
{
wxLogNull lognull;
icon = wxIcon("icons/icon.png", wxBITMAP_TYPE_PNG);
}
if (!icon.IsNull()) _frame->SetIcon(icon);
//Set size
wxDisplay display(wxDisplay::GetFromWindow(_frame));
wxRect rect = display.GetGeometry();
_frame->SetSize(wxRect(rect.GetPosition(), rect.GetSize() / 2));
_frame->SetPosition(rect.GetPosition() + rect.GetSize() / 4);
_frame->SetBackgroundStyle(wxBG_STYLE_PAINT);
_frame->SetSizer(_sizer);
_frame->Bind(wxEVT_PAINT, &Frame::_on_paint, this, _frame->GetId());
_frame->Bind(wxEVT_SIZE, &Frame::_on_size, this, _frame->GetId());
_frame->Show();
}
wxFrame *p6::Frame::frame() noexcept
{
return _frame;
}
wxBoxSizer *p6::Frame::sizer() noexcept
{
return _sizer;
}
p6::ToolBar *p6::Frame::toolbar() noexcept
{
return &_toolbar;
}
p6::MenuBar *p6::Frame::menubar() noexcept
{
return &_menubar;
}
p6::MainPanel *p6::Frame::main_panel() noexcept
{
return &_main_panel;
}
p6::SidePanel *p6::Frame::side_panel() noexcept
{
return &_side_panel;
}
p6::Construction *p6::Frame::construction() noexcept
{
return &_construction;
} | 21.549451 | 72 | 0.717491 | [
"render"
] |
feb9ec0a96886533d9f94202bb8be5ec557ea1a8 | 2,300 | hpp | C++ | src/Evolution/Systems/ScalarWave/Initialize.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/Evolution/Systems/ScalarWave/Initialize.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/Evolution/Systems/ScalarWave/Initialize.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/Tensor/EagerMath/Norms.hpp"
#include "DataStructures/Variables.hpp"
#include "Evolution/Initialization/Evolution.hpp"
#include "Evolution/Systems/ScalarWave/Constraints.hpp"
#include "Evolution/Systems/ScalarWave/System.hpp"
#include "Evolution/Systems/ScalarWave/Tags.hpp"
#include "NumericalAlgorithms/LinearOperators/PartialDerivatives.hpp"
#include "Parallel/GlobalCache.hpp"
#include "ParallelAlgorithms/Initialization/MutateAssign.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
namespace ScalarWave {
namespace Actions {
/// \ingroup InitializationGroup
/// \brief Initialize items related to constraints of the ScalarWave system
///
/// We add both constraints and the constraint damping parameter to the
/// evolution databox.
///
/// DataBox changes:
/// - Adds:
/// * `ScalarWave::Tags::ConstraintGamma2`
/// - Removes: nothing
/// - Modifies: nothing
///
/// \note This action relies on the `SetupDataBox` aggregated initialization
/// mechanism, so `Actions::SetupDataBox` must be present in the
/// `Initialization` phase action list prior to this action.
template <size_t Dim>
struct InitializeConstraints {
using simple_tags = tmpl::list<ScalarWave::Tags::ConstraintGamma2>;
using compute_tags = tmpl::list<>;
template <typename DbTagsList, typename... InboxTags, typename Metavariables,
typename ArrayIndex, typename ActionList,
typename ParallelComponent>
static auto apply(db::DataBox<DbTagsList>& box,
const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,
const Parallel::GlobalCache<Metavariables>& /*cache*/,
const ArrayIndex& /*array_index*/,
const ActionList /*meta*/,
const ParallelComponent* const /*meta*/) {
const auto& mesh = db::get<domain::Tags::Mesh<Dim>>(box);
Scalar<DataVector> gamma_2{mesh.number_of_grid_points(), 0.};
Initialization::mutate_assign<simple_tags>(make_not_null(&box),
std::move(gamma_2));
return std::make_tuple(std::move(box));
}
};
} // namespace Actions
} // namespace ScalarWave
| 37.704918 | 79 | 0.703478 | [
"mesh"
] |
febecaca118d50f2fc4667fdbd9230988b9d2a77 | 809 | cpp | C++ | UVa Online Judge/10128.cpp | xiezeju/ACM-Code-Archives | db135ed0953adcf5c7ab37a00b3f9458291ce0d7 | [
"MIT"
] | 1 | 2022-02-24T12:44:30.000Z | 2022-02-24T12:44:30.000Z | UVa Online Judge/10128.cpp | xiezeju/ACM-Code-Archives | db135ed0953adcf5c7ab37a00b3f9458291ce0d7 | [
"MIT"
] | null | null | null | UVa Online Judge/10128.cpp | xiezeju/ACM-Code-Archives | db135ed0953adcf5c7ab37a00b3f9458291ce0d7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define LSOne(S) ((S) & -(S))
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<ll> vll;
const int INF = 0x3f3f3f3f;
const long long LLINF = 4e18;
const double EPS = 1e-9;
const int N = 20;
ll dp[N][N][N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t; cin >> t;
while (t--) {
int n, a, b; cin >> n >> a >> b;
memset(dp, 0, sizeof dp);
dp[1][1][1] = 1;
for (int i = 2; i <= n; i++)
for (int j = 1; j <= i; j++)
for (int k = 1; k <= i-j+1; k++)
dp[i][j][k] = dp[i - 1][j - 1][k] + dp[i - 1][j][k - 1] + (i - 2) * dp[i - 1][j][k];
cout << dp[n][a][b] << endl;
}
return 0;
}
| 24.515152 | 104 | 0.473424 | [
"vector"
] |
fecccfb1b10b05a010f1b1fe0a410f3006fd5dea | 33,314 | cc | C++ | CryoMEM/cacti/memorybus.cc | SNU-HPCS/CryoModel | 07a3fbe3f3d44c7960b5aed562a90e204014eea0 | [
"MIT"
] | 2 | 2021-05-26T12:32:46.000Z | 2021-12-15T13:10:37.000Z | CryoMEM/cacti/memorybus.cc | SNU-HPCS/CryoModel | 07a3fbe3f3d44c7960b5aed562a90e204014eea0 | [
"MIT"
] | 1 | 2022-03-02T01:49:20.000Z | 2022-03-18T10:37:59.000Z | CryoMEM/cacti/memorybus.cc | SNU-HPCS/CryoModel | 07a3fbe3f3d44c7960b5aed562a90e204014eea0 | [
"MIT"
] | null | null | null | /*****************************************************************************
* CACTI 7.0
* SOFTWARE LICENSE AGREEMENT
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* All Rights Reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.”
*
***************************************************************************/
#include <iostream>
#include <cmath>
#include <cassert>
#include "memorybus.h"
#include "basic_circuit.h"
#include "input_parameter.h"
#include "dynamic_parameter.h"
#include "wire.h"
#include "decoder.h"
#include "predec.h"
#include "predec_blk.h"
#include "predec_blk_drv.h"
#include "driver.h"
#include "enum/memorybus_type.h"
using namespace std;
Memorybus::Memorybus(
enum Wire_type wire_model,
double mat_w,
double mat_h,
double subarray_w_,
double subarray_h_,
int _row_add_bits,
int _col_add_bits,
int _data_bits,
int _ndbl,
int _ndwl, /*enum Htree_type htree_type,*/
enum Memorybus_type membus_type_,
const DynamicParameter & dp_,
/*TechnologyParameter::*/ DeviceType *dt)
: dp(dp_),
in_rise_time(0),
out_rise_time(0),
is_dram(dp.is_dram),
membus_type(membus_type_),
mat_width(mat_w),
mat_height(mat_h),
subarray_width(subarray_w_),
subarray_height(subarray_h_),
data_bits(_data_bits),
ndbl(_ndbl),
ndwl(_ndwl),
wt(wire_model),
deviceType(dt)
{
if (g_ip->print_detail_debug) cout << "memorybus.cc: membus_type = " << membus_type << endl;
power.readOp.dynamic = 0;
power.readOp.leakage = 0;
power.readOp.gate_leakage = 0;
power.searchOp.dynamic = 0;
delay = 0;
cell.h = g_tp.dram.b_h;
cell.w = g_tp.dram.b_w;
if (!g_ip->is_3d_mem) assert(ndbl >= 2 && ndwl >= 2);
if (g_ip->print_detail_debug) {
cout << "burst length: " << g_ip->burst_depth << endl;
cout << "output width: " << g_ip->io_width << endl;
}
// Default value
chip_IO_width = g_ip->io_width; // g_ip->out_w; //x4, x8, x16 chip
burst_length = g_ip->burst_depth; // g_ip->burst_len; //DDR2 4, DDR3 8
data_bits = chip_IO_width * burst_length;
row_add_bits = _row_add_bits;
col_add_bits = _col_add_bits;
max_unpipelined_link_delay = 0; // TODO
min_w_nmos = g_tp.min_w_nmos_;
min_w_pmos = deviceType->n_to_p_eff_curr_drv_ratio * min_w_nmos;
semi_repeated_global_line = 0; // 1: semi-repeated global line, repeaters in decoder stripes; 0: Non-repeated global line, slower
ndwl = _ndwl / g_ip->num_tier_row_sprd;
ndbl = _ndbl / g_ip->num_tier_col_sprd;
num_subarray_global_IO = ndbl > 16 ? 16 : ndbl;
switch (membus_type)
{
case Data_path:
data_bits = chip_IO_width * burst_length;
Network();
break;
case Row_add_path:
add_bits = _row_add_bits;
num_dec_signals = dp.num_r_subarray * ndbl;
Network();
break;
case Col_add_path:
add_bits = _col_add_bits;
num_dec_signals = dp.num_c_subarray * ndwl / data_bits;
Network();
break;
default: assert(0); break;
}
assert(power.readOp.dynamic >= 0);
assert(power.readOp.leakage >= 0);
}
Memorybus::~Memorybus()
{
delete center_stripe;
delete bank_bus;
switch (membus_type)
{
case Data_path:
delete local_data;
delete global_data;
delete local_data_drv;
if (semi_repeated_global_line) delete global_data_drv;
delete out_seg;
break;
case Row_add_path:
delete global_WL;
delete add_predec;
delete add_dec;
delete lwl_drv;
break;
case Col_add_path:
delete column_sel;
delete add_predec;
delete add_dec;
break;
default: assert(0); break;
}
}
// ---For 3D DRAM, the bank height and length is reduced to 1/num_tier_row_sprd and 1/num_tier_col_sprd.
// ---As a result, ndwl and ndbl are also reduced to the same ratio, but he number of banks increase to the product of these two parameters
void Memorybus::Network()
{
// double POLY_RESISTIVITY = 0.148; //ohm-micron
double R_wire_dec_out = 0;
double C_ld_dec_out = 0;
double bank_bus_length = 0;
double area_bank_vertical_peripheral_circuitry = 0, area_bank_horizontal_peripheral_circuitry = 0;
area_sense_amp = (mat_height - subarray_height) * mat_width * ndbl * ndwl;
area_subarray = subarray_height * subarray_width * ndbl * ndwl;
// ---Because in 3D DRAM mat only has one subarray, but contains the subarray peripheral circuits such as SA. Detail see mat.cc is_3d_mem part.
subarray_height = mat_height;
subarray_width = mat_width;
if (g_ip->partition_gran == 0) // Coarse_rank_level: add/data bus around
{
height_bank = subarray_height * ndbl + (col_add_bits + row_add_bits) * g_tp.wire_outside_mat.pitch / 2 + data_bits * g_tp.wire_outside_mat.pitch;
length_bank = subarray_width * ndwl + (col_add_bits + row_add_bits) * g_tp.wire_outside_mat.pitch / 2 + data_bits * g_tp.wire_outside_mat.pitch;
area_address_bus = (row_add_bits + col_add_bits) * g_tp.wire_outside_mat.pitch * sqrt(length_bank * height_bank);
area_data_bus = data_bits * g_tp.wire_outside_mat.pitch * sqrt(length_bank * height_bank);
}
else if (g_ip->partition_gran == 1) // Fine_rank_level: add bus replaced by TSVs
{
height_bank = subarray_height * ndbl;
length_bank = subarray_width * ndwl;
area_address_bus = 0;
area_data_bus = data_bits * g_tp.wire_outside_mat.pitch * sqrt(length_bank * height_bank);
}
else if (g_ip->partition_gran == 2) // Coarse_bank_level: add/data bus replaced by TSVs
{
height_bank = subarray_height * ndbl;
length_bank = subarray_width * ndwl;
area_address_bus = 0;
area_data_bus = 0;
}
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: N subarrays per mat = " << dp.num_subarrays / dp.num_mats << endl;
cout << "memorybus.cc: g_tp.wire_local.pitch = " << g_tp.wire_local.pitch / 1e3 << " mm" << endl;
cout << "memorybus.cc: subarray_width = " << subarray_width / 1e3 << " mm" << endl;
cout << "memorybus.cc: subarray_height = " << subarray_height / 1e3 << " mm" << endl;
cout << "memorybus.cc: mat_height = " << mat_height / 1e3 << " mm" << endl;
cout << "memorybus.cc: mat_width = " << mat_width / 1e3 << " mm" << endl;
cout << "memorybus.cc: height_bank = " << height_bank / 1e3 << " mm" << endl;
cout << "memorybus.cc: length_bank = " << length_bank / 1e3 << " mm" << endl;
}
int num_banks_hor_dir = 1 << (int)ceil((double)_log2(g_ip->nbanks * g_ip->num_tier_row_sprd) / 2);
int num_banks_ver_dir = 1 << (int)ceil((double)_log2(g_ip->nbanks * g_ip->num_tier_col_sprd * g_ip->num_tier_row_sprd / num_banks_hor_dir));
if (g_ip->print_detail_debug) {
cout << "horz bank #: " << num_banks_hor_dir << endl;
cout << "vert bank #: " << num_banks_ver_dir << endl;
cout << "memorybus.cc: g_ip->nbanks = " << g_ip->nbanks << endl;
cout << "memorybus.cc: num_banks_hor_dir = " << num_banks_hor_dir << endl;
}
// ************************************* Wire Interconnections *****************************************
double center_stripe_length = 0.5 * double(num_banks_hor_dir) * height_bank;
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: center_stripe wire length = " << center_stripe_length << " um" << endl;
}
center_stripe = new Wire(wt, center_stripe_length);
area_bus = 2.0 * center_stripe_length * (row_add_bits + col_add_bits + data_bits) * g_tp.wire_outside_mat.pitch / g_ip->nbanks;
// if (g_ip->partition_gran == 0)
// area_bus = (row_add_bits + col_add_bits) *g_tp.wire_outside_mat.pitch * center_stripe_length;
if (membus_type == Row_add_path) {
int num_lwl_per_gwl = 4;
global_WL = new Wire(wt, length_bank, 1, 1, 1, inside_mat, CU_RESISTIVITY, &(g_tp.peri_global));
// local_WL = new Wire(wt, length_bank/num_lwl_drv, local_wires, POLY_RESISTIVITY, &(g_tp.dram_wl));
num_lwl_drv = ndwl;
// C_GWL = num_lwl_drv * gate_C(g_tp.min_w_nmos_+min_w_pmos,0) + c_w_metal * dp.num_c_subarray * ndwl;
if (semi_repeated_global_line) {
C_GWL
= (double)num_lwl_per_gwl * gate_C(g_tp.min_w_nmos_ + min_w_pmos, 0) + g_tp.wire_inside_mat.C_per_um * (subarray_width + g_tp.wire_local.pitch);
R_GWL = g_tp.wire_inside_mat.R_per_um * (subarray_width + g_tp.wire_local.pitch);
}
else
{
C_GWL = (double)num_lwl_drv * num_lwl_per_gwl * gate_C(g_tp.min_w_nmos_ + min_w_pmos, 0) + g_tp.wire_inside_mat.C_per_um * length_bank;
R_GWL = length_bank * g_tp.wire_inside_mat.R_per_um;
}
lwl_driver_c_gate_load = dp.num_c_subarray * gate_C_pass(g_tp.dram.cell_a_w, g_tp.dram.b_w, true, true);
// lwl_driver_c_wire_load = subarray_width * g_tp.wire_local.C_per_um;
// lwl_driver_r_wire_load = subarray_width * g_tp.wire_local.R_per_um;
if (g_ip->print_detail_debug) {
cout << "C_GWL: " << C_GWL << endl;
cout << "num_lwl_drv: " << num_lwl_drv << endl;
cout << "g_tp.wire_inside_mat.C_per_um: " << g_tp.wire_inside_mat.C_per_um << endl;
cout << "length_bank: " << length_bank << endl;
cout << "memorybus.cc: lwl single gate capacitance = " << gate_C_pass(g_tp.dram.cell_a_w, g_tp.dram.b_w, true, true) << endl;
cout << "memorybus.cc: lwl wire capacitance per single wire = " << g_tp.wire_local.C_per_um << endl;
cout << "memorybus.cc: dp.num_c_subarray = " << dp.num_c_subarray << endl;
cout << "memorybus.cc: dram.b_w = " << g_tp.dram.b_w << endl;
}
lwl_driver_c_wire_load = dp.num_c_subarray * g_tp.dram.b_w * g_tp.wire_local.C_per_um;
lwl_driver_r_wire_load = dp.num_c_subarray * g_tp.dram.b_w * g_tp.wire_local.R_per_um;
C_LWL = lwl_driver_c_gate_load + lwl_driver_c_wire_load;
lwl_drv = new Driver(lwl_driver_c_gate_load, lwl_driver_c_wire_load, lwl_driver_r_wire_load, is_dram);
lwl_drv->compute_area();
if (!g_ip->fine_gran_bank_lvl) {
C_ld_dec_out = C_GWL;
R_wire_dec_out = R_GWL;
}
else
{
C_ld_dec_out = gate_C(g_tp.min_w_nmos_ + min_w_pmos, 0);
R_wire_dec_out = 0;
}
if (g_ip->print_detail_debug) cout << "memorybus.cc: ndwl * dp.num_c_subarray * g_tp.dram.b_w = " << ndwl * dp.num_c_subarray * g_tp.dram.b_w << endl;
// bank_bus_length = double(num_banks_ver_dir) * 0.5 * (height_bank + 0.5*double(row_add_bits+col_add_bits+data_bits)*g_tp.wire_outside_mat.pitch);
bank_bus_length = double(num_banks_ver_dir) * 0.5 * MAX(length_bank, height_bank);
bank_bus = new Wire(wt, bank_bus_length);
}
else if (membus_type == Col_add_path)
{
column_sel = new Wire(wt, sqrt(length_bank * height_bank), 1, 1, 1, outside_mat, CU_RESISTIVITY, &(g_tp.peri_global));
if (semi_repeated_global_line) {
C_colsel = g_tp.wire_inside_mat.C_per_um * (subarray_height + g_tp.wire_local.pitch);
R_colsel = g_tp.wire_inside_mat.R_per_um * (subarray_height + g_tp.wire_local.pitch);
}
else
{
C_colsel = column_sel->repeater_size * gate_C(g_tp.min_w_nmos_ + min_w_pmos, 0)
+ (column_sel->repeater_spacing < height_bank ? column_sel->repeater_spacing : height_bank) * g_tp.wire_outside_mat.C_per_um;
R_colsel = (column_sel->repeater_spacing < height_bank ? column_sel->repeater_spacing : height_bank) * g_tp.wire_outside_mat.R_per_um;
}
if (!g_ip->fine_gran_bank_lvl) {
C_ld_dec_out = C_colsel;
//+ (int)(column_sel->repeater_spacing/height_bank) * ndbl*dp.num_r_subarray* gate_C(g_tp.w_nmos_sa_mux,0);
R_wire_dec_out = R_colsel;
}
else
{
C_ld_dec_out = gate_C(g_tp.min_w_nmos_ + min_w_pmos, 0);
R_wire_dec_out = 0;
}
if (g_ip->print_detail_debug) cout << "memorybus.cc: column_sel->repeater_size = " << column_sel->repeater_size << endl;
bank_bus_length = double(num_banks_ver_dir) * 0.5 * MAX(length_bank, height_bank);
bank_bus = new Wire(wt, bank_bus_length);
}
else if (membus_type == Data_path)
{
local_data = new Wire(wt, subarray_width, 1, 1, 1, inside_mat, CU_RESISTIVITY, &(g_tp.peri_global));
global_data = new Wire(wt, sqrt(length_bank * height_bank), 1, 1, 1, outside_mat, CU_RESISTIVITY, &(g_tp.peri_global));
if (semi_repeated_global_line) {
C_global_data = g_tp.wire_inside_mat.C_per_um * (subarray_height + g_tp.wire_local.pitch);
R_global_data = g_tp.wire_inside_mat.R_per_um * (subarray_height + g_tp.wire_local.pitch);
}
else
{
C_global_data = g_tp.wire_inside_mat.C_per_um * height_bank / 2;
R_global_data = g_tp.wire_inside_mat.R_per_um * height_bank / 2;
}
global_data_drv = new Driver(0, C_global_data, R_global_data, is_dram);
global_data_drv->compute_delay(0);
global_data_drv->compute_area();
//---Unrepeated local dataline
double local_data_c_gate_load = dp.num_c_subarray * drain_C_(g_tp.w_nmos_sa_mux, NCH, 1, 0, cell.w, is_dram);
// double local_data_c_gate_load = 0;
double local_data_c_wire_load = dp.num_c_subarray * g_tp.dram.b_w * g_tp.wire_inside_mat.C_per_um;
double local_data_r_wire_load = dp.num_c_subarray * g_tp.dram.b_w * g_tp.wire_inside_mat.R_per_um;
// double local_data_r_gate_load = tr_R_on(g_tp.w_nmos_sa_mux, NCH, 1, is_dram);
double local_data_r_gate_load = 0;
double tf = (local_data_c_gate_load + local_data_c_wire_load) * (local_data_r_wire_load + local_data_r_gate_load);
double this_delay = horowitz(0, tf, 0.5, 0.5, RISE);
// double local_data_outrisetime = this_delay/(1.0-0.5);
//---Unrepeated and undriven local dataline, not significant growth
// local_data->delay = this_delay;
// local_data->power.readOp.dynamic = (local_data_c_gate_load + local_data_c_wire_load) * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd;
double data_drv_c_gate_load = local_data_c_gate_load;
double data_drv_c_wire_load = local_data_c_wire_load;
double data_drv_r_wire_load = local_data_r_gate_load + local_data_r_wire_load;
//---Assume unrepeated global data path, too high RC
// double data_drv_c_wire_load = height_bank * g_tp.wire_outside_mat.C_per_um;
// double data_drv_r_wire_load = height_bank * g_tp.wire_inside_mat.R_per_um;
local_data_drv = new Driver(data_drv_c_gate_load, data_drv_c_wire_load, data_drv_r_wire_load, is_dram);
local_data_drv->compute_delay(0);
local_data_drv->compute_area();
if (g_ip->print_detail_debug) {
cout << "C: " << local_data_c_gate_load + local_data_c_wire_load << " F" << endl;
cout << "R: " << local_data_r_gate_load + local_data_r_wire_load << " Ohm" << endl;
cout << "this_delay" << this_delay * 1e9 << " ns" << endl;
cout << " local_data_drv delay: " << local_data_drv->delay * 1e9 << " ns" << endl;
}
// Not accounted for.
/*local_data_drv = new Driver(
global_data->repeater_size * gate_C(g_tp.min_w_nmos_+min_w_pmos,0),
global_data->repeater_spacing * g_tp.wire_inside_mat.C_per_um,
global_data->repeater_spacing * g_tp.wire_inside_mat.R_per_um,
is_dram);*/
// bank_bus_length = double(num_banks_ver_dir) * 0.5 * (height_bank + 0.5*double(row_add_bits+col_add_bits+data_bits)*g_tp.wire_outside_mat.pitch) -
// height_bank + length_bank;
bank_bus_length = double(num_banks_ver_dir) * 0.5 * MAX(length_bank, height_bank);
bank_bus = new Wire(wt, bank_bus_length);
if (g_ip->print_detail_debug) cout << "memorybus.cc: bank_bus_length = " << bank_bus_length << endl;
out_seg = new Wire(wt, 0.25 * num_banks_hor_dir * (length_bank + (row_add_bits + col_add_bits + data_bits) * g_tp.wire_outside_mat.pitch));
area_IOSA = (875 + 500) * g_ip->F_sz_um * g_ip->F_sz_um * data_bits; // Reference:
area_data_drv = local_data_drv->area.get_area() * data_bits;
if (ndbl > 16) {
area_IOSA *= (double)ndbl / 16.0;
area_data_drv *= (double)ndbl / 16.0;
}
area_local_dataline = data_bits * subarray_width * g_tp.wire_local.pitch * ndbl;
}
// Row decoder
if (membus_type == Row_add_path || membus_type == Col_add_path) {
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: num_dec_signals = " << num_dec_signals << endl;
cout << "memorybus.cc: C_ld_dec_out = " << C_ld_dec_out << endl;
cout << "memorybus.cc: R_wire_dec_out = " << R_wire_dec_out << endl;
cout << "memorybus.cc: is_dram = " << is_dram << endl;
cout << "memorybus.cc: cell.h = " << cell.h << endl;
}
add_dec = new Decoder(
(num_dec_signals > 16) ? num_dec_signals : 16,
false,
C_ld_dec_out,
R_wire_dec_out,
false,
is_dram,
membus_type == Row_add_path ? true : false,
cell);
// Predecoder and decoder for GWL
double C_wire_predec_blk_out;
double R_wire_predec_blk_out;
C_wire_predec_blk_out = 0; // num_subarrays_per_row * dp.num_r_subarray * g_tp.wire_inside_mat.C_per_um * cell.h;
R_wire_predec_blk_out = 0; // num_subarrays_per_row * dp.num_r_subarray * g_tp.wire_inside_mat.R_per_um * cell.h;
// int num_subarrays_per_mat = dp.num_subarrays/dp.num_mats;
int num_dec_per_predec = 1;
PredecBlk *add_predec_blk1 = new PredecBlk(num_dec_signals, add_dec, C_wire_predec_blk_out, R_wire_predec_blk_out, num_dec_per_predec, is_dram, true);
PredecBlk *add_predec_blk2 = new PredecBlk(num_dec_signals, add_dec, C_wire_predec_blk_out, R_wire_predec_blk_out, num_dec_per_predec, is_dram, false);
PredecBlkDrv *add_predec_blk_drv1 = new PredecBlkDrv(0, add_predec_blk1, is_dram);
PredecBlkDrv *add_predec_blk_drv2 = new PredecBlkDrv(0, add_predec_blk2, is_dram);
add_predec = new Predec(add_predec_blk_drv1, add_predec_blk_drv2);
if (membus_type == Row_add_path) {
area_row_predec_dec = add_predec_blk_drv1->area.get_area() + add_predec_blk_drv2->area.get_area() + add_predec_blk1->area.get_area()
+ add_predec_blk2->area.get_area() + num_dec_signals * add_dec->area.get_area();
area_lwl_drv = num_lwl_drv / 2.0 * dp.num_r_subarray * ndbl
* lwl_drv->area.get_area(); // num_lwl_drv is ndwl/the lwl driver count one gwl connects. two adjacent lwls share one driver.
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: area_bank_vertical_peripheral_circuitry = " << area_bank_vertical_peripheral_circuitry / 1e6 << " mm2" << endl;
cout << "memorybus.cc: lwl drv area = " << lwl_drv->area.get_area() / 1e6 << " mm2" << endl;
cout << "memorybus.cc: total lwl drv area = " << num_lwl_drv * dp.num_r_subarray * ndbl * lwl_drv->area.get_area() / 1e6 << " mm2" << endl;
}
}
else if (membus_type == Col_add_path)
{
area_col_predec_dec = add_predec_blk_drv1->area.get_area() + add_predec_blk_drv2->area.get_area() + add_predec_blk1->area.get_area()
+ add_predec_blk2->area.get_area() + num_dec_signals * add_dec->area.get_area();
if (ndbl > 16) {
area_col_predec_dec *= (double)ndbl / 16.0;
}
}
area_bank_vertical_peripheral_circuitry = area_row_predec_dec + area_lwl_drv + area_address_bus + area_data_bus;
area_bank_horizontal_peripheral_circuitry = area_col_predec_dec + area_data_drv + (area_bus + area_IOSA) / g_ip->nbanks;
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: add_predec_blk_drv1->area = " << add_predec_blk_drv1->area.get_area() / 1e6 << " mm2" << endl;
cout << "memorybus.cc: add_predec_blk_drv2->area = " << add_predec_blk_drv2->area.get_area() / 1e6 << " mm2" << endl;
cout << "memorybus.cc: add_predec_blk1->area = " << add_predec_blk1->area.get_area() / 1e6 << " mm2" << endl;
cout << "memorybus.cc: add_predec_blk2->area = " << add_predec_blk2->area.get_area() / 1e6 << " mm2" << endl;
cout << "memorybus.cc: total add_dec->area = " << num_dec_signals * add_dec->area.get_area() / 1e6 << " mm2" << endl;
cout << "wire bus width for one bank = " << g_tp.wire_outside_mat.pitch * double(add_bits + add_bits + data_bits);
}
area.h = (height_bank + area_bank_horizontal_peripheral_circuitry / length_bank) * num_banks_ver_dir;
area.w = (length_bank + area_bank_vertical_peripheral_circuitry / height_bank)
* num_banks_hor_dir; // bank bus, should add cmd wire and predec/decoder space
if (g_ip->partition_gran == 0) {
area.h += g_tp.wire_outside_mat.pitch * double(add_bits + add_bits + data_bits); // center_stripe, should add cmd wire and other componets
area.w += g_tp.wire_outside_mat.pitch * double(add_bits + add_bits + data_bits); // + g_tp.wire_outside_mat.pitch * add_bits * 2.5;
}
//---This coefficient comes from the extra overhead of voltage regulator,
//---control logic, bank fuse, burst logic and I/O, see
//--- A 5.6ns Random Cycle 144Mb DRAM with 1.4Gb/s/pin and DDR3-SRAM Interface
// area.w *= 1.0672;
// area.h *= 1.0672;
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: circuit height = " << area_bank_horizontal_peripheral_circuitry / length_bank / 1e3 << " mm" << endl;
cout << "memorybus.cc: circuit length = " << area_bank_vertical_peripheral_circuitry / height_bank / 1e3 << " mm" << endl;
cout << "memorybus.cc: area.h = " << area.h / 1e3 << " mm" << endl;
cout << "memorybus.cc: area.w = " << area.w / 1e3 << " mm" << endl;
cout << "memorybus.cc: area = " << area.get_area() / 1e6 << " mm2" << endl;
}
}
compute_delays(0);
compute_power_energy();
}
// This is based on the same function in mat.cc
double Memorybus::compute_delays(double inrisetime)
{
// double outrisetime = 0;
double predec_outrisetime = 0, add_dec_outrisetime = 0;
double lwl_drv_outrisetime = 0; ///, tf = 0;
// double local_data_drv_outrisetime = 0;
if (membus_type == Data_path) {
delay = 0;
delay_bus = center_stripe->delay + bank_bus->delay;
delay += delay_bus;
// outrisetime = local_data_drv->compute_delay(inrisetime);
// local_data_drv_outrisetime = local_data_drv->delay;
delay_global_data = (semi_repeated_global_line > 0) ? (global_data_drv->delay * num_subarray_global_IO) : (global_data_drv->delay + global_data->delay);
if (g_ip->partition_gran == 0 || g_ip->partition_gran == 1) delay += delay_global_data;
// delay += local_data->delay;
delay_local_data = local_data_drv->delay;
delay += delay_local_data;
delay_data_buffer = 2 * 1e-6 / (double)g_ip->sys_freq_MHz;
// delay += bank.mat.delay_subarray_out_drv_htree;
delay += delay_data_buffer;
// cout << 1e3/(double)g_ip->sys_freq_MHz<< endl;
// delay += out_seg->delay * burst_length;
if (g_ip->print_detail_debug) cout << "memorybus.cc: data path delay = " << delay << endl;
out_rise_time = 0;
}
else
{
delay = 0;
delay_bus = center_stripe->delay + bank_bus->delay;
delay += delay_bus;
predec_outrisetime = add_predec->compute_delays(inrisetime);
add_dec_outrisetime = add_dec->compute_delays(predec_outrisetime);
delay_add_predecoder = add_predec->delay;
delay += delay_add_predecoder;
if (membus_type == Row_add_path) {
if (semi_repeated_global_line) {
delay_add_decoder = add_dec->delay * ndwl;
if (g_ip->page_sz_bits > 8192) delay_add_decoder /= (double)(g_ip->page_sz_bits / 8192);
}
else
{
delay_add_decoder = add_dec->delay;
}
delay += delay_add_decoder;
// There is no function to compute_delay in wire.cc, need to double check if center_stripe->delay and bank_bus->delay is correct.
lwl_drv_outrisetime = lwl_drv->compute_delay(add_dec_outrisetime);
/// tf = (lwl_driver_c_gate_load + lwl_driver_c_wire_load) * lwl_driver_r_wire_load;
// ### no need for global_WL->delay
// delay_WL = global_WL->delay + lwl_drv->delay + horowitz(lwl_drv_outrisetime, tf, 0.5, 0.5, RISE);
delay_lwl_drv = lwl_drv->delay;
if (!g_ip->fine_gran_bank_lvl) delay += delay_lwl_drv;
if (g_ip->print_detail_debug) cout << "memorybus.cc: row add path delay = " << delay << endl;
out_rise_time = lwl_drv_outrisetime;
}
else if (membus_type == Col_add_path)
{
if (semi_repeated_global_line) {
delay_add_decoder = add_dec->delay * num_subarray_global_IO;
}
else
{
delay += column_sel->delay;
delay_add_decoder = add_dec->delay;
}
delay += delay_add_decoder;
out_rise_time = 0;
if (g_ip->print_detail_debug) {
// cout << "memorybus.cc, compute_delays col: center_stripe->delay = " << center_stripe->delay << endl;
// cout << "memorybus.cc, compute_delays col: bank_bus->delay = " << bank_bus->delay << endl;
// cout << "memorybus.cc, compute_delays col: add_predec->delay = " << add_predec->delay << endl;
// cout << "memorybus.cc, compute_delays col: add_dec->delay = " << add_dec->delay << endl;
cout << "memorybus.cc: column add path delay = " << delay << endl;
}
}
else
{
assert(0);
}
}
// Double check!
out_rise_time = delay / (1.0 - 0.5);
// Is delay_wl_reset necessary here? Is the 'false' condition appropriate? See the same code as in mat.cc
/*if (add_dec->exist == false)
{
int delay_wl_reset = MAX(add_predec->blk1->delay, add_predec->blk2->delay);
//delay += delay_wl_reset;
}*/
return out_rise_time;
}
void Memorybus::compute_power_energy()
{
double coeff1[4] = {(double)add_bits, (double)add_bits, (double)add_bits, (double)add_bits};
double coeff2[4] = {(double)data_bits, (double)data_bits, (double)data_bits, (double)data_bits};
double coeff3[4] = {(double)num_lwl_drv, (double)num_lwl_drv, (double)num_lwl_drv, (double)num_lwl_drv};
double coeff4[4] = {
(double)burst_length * chip_IO_width, (double)burst_length * chip_IO_width, (double)burst_length * chip_IO_width, (double)burst_length * chip_IO_width};
double coeff5[4] = {(double)ndwl, (double)ndwl, (double)ndwl, (double)ndwl};
double coeff6[4] = {(double)num_subarray_global_IO, (double)num_subarray_global_IO, (double)num_subarray_global_IO, (double)num_subarray_global_IO};
// double coeff4[4] = {(double)num_dec_signals, (double)num_dec_signals, (double)num_dec_signals, (double)num_dec_signals};
switch (membus_type)
{
case Data_path:
power_bus = (center_stripe->power + bank_bus->power) * coeff2;
power_local_data = local_data_drv->power * coeff2;
power_global_data = semi_repeated_global_line > 0 ? (global_data_drv->power * coeff2) : (global_data_drv->power + global_data->power);
power_global_data.readOp.dynamic = power_global_data.readOp.dynamic + 1.8 / 1e3 * deviceType->Vdd * 10.0 / 1e9 / 64 * data_bits;
power = power_bus + power_local_data;
if (!g_ip->fine_gran_bank_lvl) power = power + power_global_data;
// power += local_data->power;
power_burst = out_seg->power * coeff4; // Account for burst read, approxmate the wire length by the center stripe
// power = power + power_burst;
if (g_ip->print_detail_debug) {
cout << "memorybus.cc: data path center stripe energy = " << center_stripe->power.readOp.dynamic * 1e9 << " nJ" << endl;
cout << "memorybus.cc: data path bank bus energy = " << bank_bus->power.readOp.dynamic * 1e9 << " nJ" << endl;
cout << "memorybus.cc: data path data driver energy = " << local_data_drv->power.readOp.dynamic * 1e9 << " nJ" << endl;
}
break;
case Row_add_path:
power_bus = (center_stripe->power + bank_bus->power) * coeff1;
power_add_predecoder = add_predec->power;
if (semi_repeated_global_line) {
power_add_decoders = add_dec->power * coeff5;
// power_add_decoders.readOp.dynamic /= (g_ip->page_sz_bits > 8192)?((double)g_ip->page_sz_bits/8192):1;
if (g_ip->page_sz_bits > 8192) power_add_decoders.readOp.dynamic /= (double)(g_ip->page_sz_bits / 8192);
}
else
power_add_decoders = add_dec->power; // * (1<< add_predec->blk1->number_input_addr_bits);
power_lwl_drv = lwl_drv->power * coeff3;
// power_local_WL.readOp.dynamic = num_lwl_drv * C_LWL * deviceType->Vdd * deviceType->Vdd;
power = power_bus + power_add_predecoder + power_add_decoders + power_lwl_drv;
break;
case Col_add_path:
power_bus = (center_stripe->power + bank_bus->power) * coeff1; // + column_sel->power * double(chip_IO_width * burst_length);
power_add_predecoder = add_predec->power;
if (semi_repeated_global_line) {
power_add_decoders = add_dec->power * coeff6;
power_add_decoders.readOp.dynamic = power_add_decoders.readOp.dynamic * g_ip->page_sz_bits / data_bits;
power_col_sel.readOp.dynamic = 0;
}
else
{
power_add_decoders = add_dec->power; // * (1<< add_predec->blk1->number_input_addr_bits);
power_col_sel.readOp.dynamic = column_sel->power.readOp.dynamic * g_ip->page_sz_bits / data_bits;
}
power = power_bus + power_add_predecoder + power_add_decoders;
if (!g_ip->fine_gran_bank_lvl) power = power + power_col_sel;
break;
default: assert(0); break;
}
return;
}
| 50.475758 | 160 | 0.626283 | [
"3d"
] |
fecd55b9a36b14c4e5de5785a6f51aea3ffca9ca | 202 | cpp | C++ | oi/vijos/P1459/test.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/vijos/P1459/test.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/vijos/P1459/test.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <iostream>
#include <queue>
using namespace std;
static priority_queue<int,vector<int>,greater<int>> q;
int main(){
q.push(1);
q.push(2);
cout<<q.top()<<endl;
return 0;
}
| 14.428571 | 54 | 0.618812 | [
"vector"
] |
fed4030827075f657aa095127feb9f814c869346 | 1,688 | cpp | C++ | android-31/android/telephony/mbms/ServiceInfo.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/telephony/mbms/ServiceInfo.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/telephony/mbms/ServiceInfo.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JString.hpp"
#include "../../../JObject.hpp"
#include "../../../JString.hpp"
#include "../../../java/util/Date.hpp"
#include "../../../java/util/Locale.hpp"
#include "./ServiceInfo.hpp"
namespace android::telephony::mbms
{
// Fields
// QJniObject forward
ServiceInfo::ServiceInfo(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
jboolean ServiceInfo::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
JObject ServiceInfo::getLocales() const
{
return callObjectMethod(
"getLocales",
"()Ljava/util/List;"
);
}
JString ServiceInfo::getNameForLocale(java::util::Locale arg0) const
{
return callObjectMethod(
"getNameForLocale",
"(Ljava/util/Locale;)Ljava/lang/CharSequence;",
arg0.object()
);
}
JObject ServiceInfo::getNamedContentLocales() const
{
return callObjectMethod(
"getNamedContentLocales",
"()Ljava/util/Set;"
);
}
JString ServiceInfo::getServiceClassName() const
{
return callObjectMethod(
"getServiceClassName",
"()Ljava/lang/String;"
);
}
JString ServiceInfo::getServiceId() const
{
return callObjectMethod(
"getServiceId",
"()Ljava/lang/String;"
);
}
java::util::Date ServiceInfo::getSessionEndTime() const
{
return callObjectMethod(
"getSessionEndTime",
"()Ljava/util/Date;"
);
}
java::util::Date ServiceInfo::getSessionStartTime() const
{
return callObjectMethod(
"getSessionStartTime",
"()Ljava/util/Date;"
);
}
jint ServiceInfo::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
} // namespace android::telephony::mbms
| 19.858824 | 69 | 0.665877 | [
"object"
] |
fed4dc581c761dca37d502a4ce182b7fa97362dd | 4,707 | cpp | C++ | src/params.cpp | Treecodes/TABI-PB | fe1c237b057418fed48535db125394607040d9de | [
"BSD-3-Clause"
] | 5 | 2017-11-15T23:59:37.000Z | 2021-11-25T00:48:43.000Z | src/params.cpp | Treecodes/TABI-PB | fe1c237b057418fed48535db125394607040d9de | [
"BSD-3-Clause"
] | 3 | 2018-03-16T16:27:35.000Z | 2022-03-14T03:43:11.000Z | src/params.cpp | Treecodes/TABI-PB | fe1c237b057418fed48535db125394607040d9de | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iterator>
#include <cmath>
#include <cstdlib>
#include "constants.h"
#include "params.h"
Params::Params(char* infile)
{
std::ifstream paramfile (infile, std::ifstream::in);
if (!paramfile.good()) {
std::cout << "param file is not readable. exiting. " << std::endl;
std::exit(1);
}
output_vtk_ = false;
output_csv_ = false;
output_csv_headers_ = false;
output_timers_ = false;
precondition_ = false;
std::string line;
while (std::getline(paramfile, line)) {
std::istringstream iss(line);
std::vector<std::string> tokenized_line{std::istream_iterator<std::string> {iss},
std::istream_iterator<std::string> {} };
std::string param_token = tokenized_line[0];
std::string param_value = tokenized_line[1];
std::transform(param_token.begin(), param_token.end(), param_token.begin(),
[=](unsigned char c){ return std::tolower(c); });
std::transform(param_value.begin(), param_value.end(), param_value.begin(),
[=](unsigned char c){ return std::tolower(c); });
if (param_token == "mol" || param_token == "pqr") {
pqr_file_.open(tokenized_line[1], std::ifstream::in);
if (!pqr_file_.good()) {
std::cout << "pqr file is not readable. exiting. " << std::endl;
std::exit(1);
}
} else if (param_token == "pdie") {
phys_eps_solute_ = std::stod(param_value);
} else if (param_token == "sdie") {
phys_eps_solvent_ = std::stod(param_value);
} else if (param_token == "bulk") {
phys_bulk_strength_ = std::stod(param_value);
} else if (param_token == "temp") {
phys_temp_ = std::stod(param_value);
} else if (param_token == "tree_degree") {
tree_degree_ = std::stoi(param_value);
if (tree_degree_ <= 0) {
std::cout << "invalid tree_degree value. exiting. " << std::endl;
std::exit(1);
}
} else if (param_token == "tree_theta") {
tree_theta_ = std::stod(param_value);
if (tree_theta_ < 0. || tree_theta_ > 1.) {
std::cout << "invalid tree_theta value. exiting. " << std::endl;
std::exit(1);
}
} else if (param_token == "tree_max_per_leaf") {
tree_max_per_leaf_ = std::stoi(param_value);
if (tree_max_per_leaf_ <= 0) {
std::cout << "invalid tree_max_per_leaf value. exiting. " << std::endl;
std::exit(1);
}
} else if (param_token == "mesh") {
auto it = mesh_table_.find(param_value);
if (it == mesh_table_.end()) {
std::cout << "invalid mesh value. exiting. " << std::endl;
std::exit(1);
}
mesh_ = it->second;
} else if (param_token == "sdens") {
mesh_density_ = std::stod(param_value);
if (mesh_density_ < 0) {
std::cout << "invalid density value. exiting. " << std::endl;
std::exit(1);
}
} else if (param_token == "srad") {
mesh_probe_radius_ = std::stod(param_value);
if (mesh_probe_radius_ < 0) {
std::cout << "invalid probe radius value. exiting. " << std::endl;
std::exit(1);
}
} else if (param_token == "precondition") {
if (param_value == "true" || param_value == "on") precondition_ = true;
} else if (param_token == "nonpolar") {
if (param_value == "true") nonpolar_ = true;
} else if (param_token == "outdata") {
if (param_value == "vtk") output_vtk_ = true;
if (param_value == "csv") output_csv_ = true;
if (param_value == "csv_headers") output_csv_headers_ = true;
if (param_value == "timers") output_timers_ = true;
} else {
std::cout << "Skipping undefined token: " << param_token << std::endl;
}
}
phys_eps_ = phys_eps_solvent_ / phys_eps_solute_;
phys_kappa2_ = constants::BULK_COEFF * phys_bulk_strength_ / phys_eps_solvent_ / phys_temp_;
phys_kappa_ = std::sqrt(phys_kappa2_);
}
| 36.773438 | 96 | 0.513066 | [
"mesh",
"vector",
"transform"
] |
fedb89c8a1c2df107dca91ab68d0d7b7ce188b41 | 2,370 | inl | C++ | include/Nazara/VulkanRenderer/Wrapper/Pipeline.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11 | 2019-11-27T00:40:43.000Z | 2020-01-29T14:31:52.000Z | include/Nazara/VulkanRenderer/Wrapper/Pipeline.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T00:29:08.000Z | 2020-01-08T18:53:39.000Z | include/Nazara/VulkanRenderer/Wrapper/Pipeline.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T10:27:40.000Z | 2020-01-15T17:43:33.000Z | // Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Vulkan renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/VulkanRenderer/Wrapper/Pipeline.hpp>
#include <Nazara/VulkanRenderer/Utils.hpp>
#include <Nazara/VulkanRenderer/Debug.hpp>
namespace Nz
{
namespace Vk
{
inline Pipeline::Pipeline() :
m_handle(VK_NULL_HANDLE)
{
}
inline Pipeline::Pipeline(Pipeline&& object) noexcept :
m_device(std::move(object.m_device)),
m_allocator(object.m_allocator),
m_handle(object.m_handle),
m_lastErrorCode(object.m_lastErrorCode)
{
object.m_handle = VK_NULL_HANDLE;
}
inline Pipeline::~Pipeline()
{
Destroy();
}
inline bool Pipeline::CreateCompute(Device& device, const VkComputePipelineCreateInfo& createInfo, VkPipelineCache cache, const VkAllocationCallbacks* allocator)
{
return Create(device, device.vkCreateComputePipelines(device, cache, 1U, &createInfo, allocator, &m_handle), allocator);
}
inline bool Pipeline::CreateGraphics(Device& device, const VkGraphicsPipelineCreateInfo& createInfo, VkPipelineCache cache, const VkAllocationCallbacks* allocator)
{
return Create(device, device.vkCreateGraphicsPipelines(device, cache, 1U, &createInfo, allocator, &m_handle), allocator);
}
inline void Pipeline::Destroy()
{
if (m_handle != VK_NULL_HANDLE)
{
m_device->vkDestroyPipeline(*m_device, m_handle, (m_allocator.pfnAllocation) ? &m_allocator : nullptr);
m_handle = VK_NULL_HANDLE;
}
}
inline Device& Pipeline::GetDevice() const
{
return *m_device;
}
inline VkResult Pipeline::GetLastErrorCode() const
{
return m_lastErrorCode;
}
inline Pipeline::operator VkPipeline() const
{
return m_handle;
}
inline bool Pipeline::Create(Device& device, VkResult result, const VkAllocationCallbacks* allocator)
{
m_device = &device;
m_lastErrorCode = result;
if (m_lastErrorCode != VkResult::VK_SUCCESS)
{
NazaraError("Failed to create Vulkan object: " + TranslateVulkanError(m_lastErrorCode));
return false;
}
// Store the allocator to access them when needed
if (allocator)
m_allocator = *allocator;
else
m_allocator.pfnAllocation = nullptr;
return true;
}
}
}
#include <Nazara/VulkanRenderer/DebugOff.hpp>
| 26.931818 | 165 | 0.733333 | [
"object"
] |
fedd099301a0b8dd899a21e3ce561464343ad1c4 | 3,832 | cxx | C++ | detection.cxx | enfild/coral_object_detection_with_tflite | f8d012cf42fc589174417fcf1f1798058dece1ef | [
"MIT"
] | null | null | null | detection.cxx | enfild/coral_object_detection_with_tflite | f8d012cf42fc589174417fcf1f1798058dece1ef | [
"MIT"
] | null | null | null | detection.cxx | enfild/coral_object_detection_with_tflite | f8d012cf42fc589174417fcf1f1798058dece1ef | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <opencv2/opencv.hpp>
#include "edgetpu.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
std::unique_ptr<tflite::Interpreter> BuildEdgeTpuInterpreter(const tflite::FlatBufferModel &model,
edgetpu::EdgeTpuContext *edgetpu_context)
{
tflite::ops::builtin::BuiltinOpResolver resolver;
resolver.AddCustom(edgetpu::kCustomOp, edgetpu::RegisterCustomOp());
std::unique_ptr<tflite::Interpreter> interpreter;
if (tflite::InterpreterBuilder(model, resolver)(&interpreter) != kTfLiteOk)
{
std::cerr << "Failed to build interpreter." << std::endl;
}
// Bind given context with interpreter.
interpreter->SetExternalContext(kTfLiteEdgeTpuContext, edgetpu_context);
interpreter->SetNumThreads(1);
if (interpreter->AllocateTensors() != kTfLiteOk)
{
std::cerr << "Failed to allocate tensors." << std::endl;
}
return interpreter;
}
int main(int argc, char* argv[]) {
std::string model_path = "detect_edgetpu.tflite";
auto model = tflite::FlatBufferModel::BuildFromFile(model_path.c_str());
std::unique_ptr<edgetpu::EdgeTpuContext> tpu_context =
edgetpu::EdgeTpuManager::GetSingleton()->NewEdgeTpuContext();
std::cout << "Checking readiness of Coral device" << std::endl;
if(!tpu_context->IsReady())
{
throw -1;
}
std::cout << "EDGE TPU path: " << tpu_context->GetDeviceEnumRecord().path << std::endl;
std::unique_ptr<tflite::Interpreter> interpreter =
BuildEdgeTpuInterpreter(*model, tpu_context.get());
interpreter->SetExternalContext(kTfLiteEdgeTpuContext, tpu_context.get());
interpreter->SetNumThreads(1);
interpreter->AllocateTensors();
TfLiteTensor* input_tensor = interpreter->tensor(interpreter->inputs()[0]);
TfLiteTensor* output_locations = interpreter->tensor(interpreter->outputs()[0]);
TfLiteTensor* output_classes = interpreter->tensor(interpreter->outputs()[1]);
TfLiteTensor* output_scores = interpreter->tensor(interpreter->outputs()[2]);
TfLiteTensor* num_detections_ = interpreter->tensor(interpreter->outputs()[3]);
auto cap = cv::VideoCapture(0);
const int height = input_tensor->dims->data[1];
const int width = input_tensor->dims->data[2];
const int channels = input_tensor->dims->data[3];
const int row_elems = width * channels;
cv::Mat frame, resized;
int k = -1;
while (k == -1) {
bool ret = cap.read(frame);
if (ret) {
cv::resize(frame, resized, cv::Size(width, height));
uint8_t* dst = input_tensor->data.uint8;
for (int row = 0; row < height; row++) {
memcpy(dst, resized.ptr(row), row_elems);
dst += row_elems;
}
interpreter->Invoke();
const float* detection_locations = output_locations->data.f;
const float* detection_classes = output_classes->data.f;
const float* detection_scores = output_scores->data.f;
const int num_detections = *(num_detections_->data.f);
for (int i = 0; i < num_detections; i++) {
const float score = detection_scores[i];
const std::string label = std::to_string(uint8_t(detection_classes[i]));
const int ymin = detection_locations[4 * i + 0] * frame.rows;
const int xmin = detection_locations[4 * i + 1] * frame.cols;
const int ymax = detection_locations[4 * i + 2] * frame.rows;
const int xmax = detection_locations[4 * i + 3] * frame.cols;
if (score > .4f) {
cv::rectangle(frame, cv::Rect(xmin, ymin, xmax - xmin, ymax - ymin),
cv::Scalar(0, 0, 255), 3);
}
}
cv::imshow("Detection", frame);
}
k = cv::waitKey(1);
}
interpreter.reset();
tpu_context.reset();
return 0;
} | 37.203883 | 104 | 0.66858 | [
"model"
] |
feede0629c8c7bdbcb42af243075bf4fb234156b | 2,419 | cpp | C++ | Utilities/Open3DMotion/src/Open3DMotion/OpenORM/Branches/TreeCompound.cpp | mitkof6/BTKCore | d4c03aa9e354be16265d0efe0815c09b35abc642 | [
"Barr",
"Unlicense"
] | 61 | 2015-04-21T20:40:37.000Z | 2022-03-25T03:35:03.000Z | Utilities/Open3DMotion/src/Open3DMotion/OpenORM/Branches/TreeCompound.cpp | mitkof6/BTKCore | d4c03aa9e354be16265d0efe0815c09b35abc642 | [
"Barr",
"Unlicense"
] | 40 | 2018-03-11T15:14:50.000Z | 2022-03-23T18:13:48.000Z | Utilities/Open3DMotion/src/Open3DMotion/OpenORM/Branches/TreeCompound.cpp | mitkof6/BTKCore | d4c03aa9e354be16265d0efe0815c09b35abc642 | [
"Barr",
"Unlicense"
] | 56 | 2015-05-11T11:04:35.000Z | 2022-01-15T20:37:04.000Z | /*--
Open3DMotion
Copyright (c) 2004-2012.
All rights reserved.
See LICENSE.txt for more information.
--*/
#include "Open3DMotion/OpenORM/Branches/TreeCompound.h"
namespace Open3DMotion
{
DEFINE_CLASS_NAME(TreeCompound);
TreeCompound::TreeCompound()
{
}
TreeCompound::~TreeCompound()
{
Clear();
}
TreeCompound* TreeCompound::NewBlank() const
{
return new TreeCompound;
}
void TreeCompound::Clear()
{
for (std::vector<TreeCompoundNode*>::iterator i(contents.begin()); i != contents.end(); i++)
{
delete (*i);
}
contents.clear();
}
const TreeCompoundNode* TreeCompound::Node(size_t index) const
{
return contents[index];
}
TreeCompoundNode* TreeCompound::Node(size_t index)
{
return contents[index];
}
void TreeCompound::Set(const char* name, TreeValue* value)
{
for (std::vector<TreeCompoundNode*>::iterator i(contents.begin()); i != contents.end(); i++)
{
if ((*i)->Name().compare(name) == 0)
{
(*i)->ChangeValue(value);
return;
}
}
contents.push_back(new TreeCompoundNode(name, value));
}
void TreeCompound::Remove(const char* name)
{
for (std::vector<TreeCompoundNode*>::iterator i(contents.begin()); i != contents.end(); i++)
{
TreeCompoundNode* node = (*i);
if (node->Name().compare(name) == 0)
{
contents.erase(i);
delete node;
return;
}
}
}
const TreeValue* TreeCompound::Get(const char* name) const
{
for (std::vector<TreeCompoundNode*>::const_iterator i(contents.begin()); i != contents.end(); i++)
{
if ((*i)->Name().compare(name) == 0)
{
return (*i)->Value();
}
}
return NULL;
}
TreeValue* TreeCompound::Get(const char* name)
{
for (std::vector<TreeCompoundNode*>::iterator i(contents.begin()); i != contents.end(); i++)
{
if ((*i)->Name().compare(name) == 0)
{
return (*i)->Value();
}
}
return NULL;
}
void TreeCompound::CopyFrom(const TreeValue* v)
{
const TreeCompound* src = TreeValueCast<TreeCompound> (v);
if (src != NULL)
{
Clear();
for (std::vector<TreeCompoundNode*>::const_iterator i(src->contents.begin()); i != src->contents.end(); i++)
{
TreeValue* newvalue = (*i)->Value()->NewBlank();
newvalue->CopyFrom( (*i)->Value() );
Set((*i)->Name().c_str(), newvalue);
}
}
}
}
| 20.5 | 112 | 0.594047 | [
"vector"
] |
fef24bb070e15fca80aa33f994a7d1165d0f6df7 | 582 | cpp | C++ | debugger/register_model.cpp | hcs64/cen64 | 0902da8113cb68fdbf016717d36c87ad95ccd4a3 | [
"BSD-3-Clause"
] | 340 | 2019-01-10T23:48:47.000Z | 2022-03-27T04:06:55.000Z | debugger/register_model.cpp | hcs64/cen64 | 0902da8113cb68fdbf016717d36c87ad95ccd4a3 | [
"BSD-3-Clause"
] | 88 | 2019-01-07T04:37:12.000Z | 2022-03-30T04:17:00.000Z | debugger/register_model.cpp | hcs64/cen64 | 0902da8113cb68fdbf016717d36c87ad95ccd4a3 | [
"BSD-3-Clause"
] | 62 | 2015-01-08T00:03:40.000Z | 2019-01-02T17:43:07.000Z | //
// register_model.cpp: CEN64D register model (MVC).
//
// CEN64D: Cycle-Accurate Nintendo 64 Debugger
// Copyright (C) 2015, Tyler J. Stachecki.
//
// This file is subject to the terms and conditions defined in
// 'LICENSE', which is part of this source code package.
//
#include "register_model.h"
RegisterModel::RegisterModel(unsigned num_regs) {
data = new quint64[num_regs];
}
RegisterModel::~RegisterModel() {
delete[] data;
}
quint64 RegisterModel::getIndex(unsigned i) {
return data[i];
}
void RegisterModel::setIndex(unsigned i, quint64 d) {
data[i] = d;
}
| 20.068966 | 62 | 0.709622 | [
"model"
] |
679b259b0c1d8efdee0924ef4a84d56b9f99ad19 | 623 | cpp | C++ | abs/ABC085C.cpp | ReiRev/atcoder-cpp | 9735acac125f624e851ee888629c9795244d7f10 | [
"MIT"
] | null | null | null | abs/ABC085C.cpp | ReiRev/atcoder-cpp | 9735acac125f624e851ee888629c9795244d7f10 | [
"MIT"
] | null | null | null | abs/ABC085C.cpp | ReiRev/atcoder-cpp | 9735acac125f624e851ee888629c9795244d7f10 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++(i))
int main()
{
int n, y;
cin >> n >> y;
y /= 1000;
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= n - i; j++)
{
if (y - i * 10 - j * 5 >= 0 && y - i * 10 - j * 5 == n - i - j)
{
cout << i << " " << j << " " << y - i * 10 - j * 5 << endl;
return 0;
}
}
}
cout << -1 << " " << -1 << " " << -1 << endl;
} | 23.074074 | 75 | 0.337079 | [
"vector"
] |
67a0e8a52a947982895cf457bf85750d201ff36e | 47,556 | cpp | C++ | src/pcl/Render.cpp | kkretzschmar/PCL | 6354627260482afcb278a3f3a2bf30c26210d4fa | [
"JasPer-2.0"
] | null | null | null | src/pcl/Render.cpp | kkretzschmar/PCL | 6354627260482afcb278a3f3a2bf30c26210d4fa | [
"JasPer-2.0"
] | null | null | null | src/pcl/Render.cpp | kkretzschmar/PCL | 6354627260482afcb278a3f3a2bf30c26210d4fa | [
"JasPer-2.0"
] | null | null | null | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.11.0938
// ----------------------------------------------------------------------------
// pcl/Render.cpp - Released 2019-01-21T12:06:21Z
// ----------------------------------------------------------------------------
// This file is part of the PixInsight Class Library (PCL).
// PCL is a multiplatform C++ framework for development of PixInsight modules.
//
// Copyright (c) 2003-2019 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ----------------------------------------------------------------------------
/*
* ### TODO ###
*
* Rewrite this code to clean and organize it.
*/
#include <pcl/Bitmap.h>
#include <pcl/GlobalSettings.h>
#include <pcl/ImageVariant.h>
#include <pcl/ImageWindow.h>
#include <pcl/Thread.h>
#include <pcl/Vector.h>
#define MinZoom -32
#define MaxZoom 100
namespace pcl
{
// ----------------------------------------------------------------------------
typedef RGBColorSystem::sample
(RGBColorSystem::*single_component_func)( RGBColorSystem::sample,
RGBColorSystem::sample,
RGBColorSystem::sample ) const;
static single_component_func singleComponents[] =
{
&RGBColorSystem::CIEL, 0, 0,
&RGBColorSystem::CIEa, &RGBColorSystem::CIEb, &RGBColorSystem::CIEc, &RGBColorSystem::CIEh,
&RGBColorSystem::CIEX, &RGBColorSystem::CIEY, &RGBColorSystem::CIEZ,
&RGBColorSystem::Hue, &RGBColorSystem::HSVSaturation, &RGBColorSystem::HSISaturation,
&RGBColorSystem::Value, &RGBColorSystem::Intensity
};
// ----------------------------------------------------------------------------
struct RenderThreadData
{
Bitmap* bitmap; // target RGBA bitmap
int x0, y0; // target coordinates
int z0; // original zoom level (z0 > 0: zoom in, z0 < 0: zoom out)
int z; // absolute value of zoom level, z > 0
int channel; // source channel
int maskMode; // mask rendering mode
bool maskInverted; // invert mask ?
bool colorImage; // true if source image is RGB color
bool colorMask; // true if source mask is RGB color
const uint8** LUT; // source LUT
bool noLUT[ 4 ]; // flags for quick LUT selection
Rect r; // source rectangle
int w, h; // dimensions of source rectangle
int n; // number of source nominal channels
Point mp; // source mask origin
bool hasAlpha; // true if the source image has alpha channels
single_component_func F; // single component function
// Data used for z < 0 only
bool hq; // high-quality downsampling?
int wz, hz; // for z < 0: dimensions of target region
const int* iz; // subsample index
double _1_Pz2; // divisor for subsampled totals
double _255_Pz2; // 8-bit conversion factor / divisor for subsampled totals
double _64K_Pz2; // 16-bit conversion factor / divisor for subsampled totals
double _1_Mz2; // divisor for subsampled mask totals
// Image and mask
const AbstractImage* image; // source image
const AbstractImage* mask; // source mask
// RGBWS
const RGBColorSystem* rgbws;
};
class RenderThreadBase
{
public:
RenderThreadBase( const RenderThreadData* d, int y0, int y1 ) :
data( d ), startRow( y0 ), endRow( y1 )
{
}
template <class P, class M>
static bool InitData( RenderThreadData& data,
Bitmap& bitmap, int x0, int y0, int z, int channel,
const GenericImage<P>& image,
bool showAlpha,
const GenericImage<M>* mask, int maskMode, bool maskInverted,
const uint8** LUT,
bool fast );
protected:
const RenderThreadData* data;
int startRow, endRow; // from 0 to h or hz
template <class P> void Render( const GenericImage<P>& );
template <class M> void Mask( const GenericImage<M>& );
template <typename T, typename Ts> inline
double SubsampledTotal( const T** f, Ts& s, int x );
template <typename T>
double SubsampledTotal( const T** f, int x )
{
uint32 s;
return SubsampledTotal( f, s, x );
}
double SubsampledTotal( const uint32** f, int x )
{
uint64 s;
return SubsampledTotal( f, s, x );
}
double SubsampledTotal( const float** f, int x )
{
float s;
return SubsampledTotal( f, s, x );
}
double SubsampledTotal( const double** f, int x )
{
double s;
return SubsampledTotal( f, s, x );
}
inline void ApplyMask( uint8& pr, uint8& pg, uint8& pb, float mx );
inline void ApplyMask( uint8& pr, uint8& pg, uint8& pb, float mr, float mg, float mb );
private:
typedef GenericVector<IVector> subsample_index_list;
static subsample_index_list subsample_index;
static void InitSubsampleIndex();
};
template <class P, class M>
class RenderThread : public Thread, public RenderThreadBase
{
public:
RenderThread( const RenderThreadData* d, int y0, int y1 ) :
RenderThreadBase( d, y0, y1 )
{
}
void Run() override
{
Render( *reinterpret_cast<const GenericImage<P>*>( data->image ) );
if ( data->mask != 0 )
Mask( *reinterpret_cast<const GenericImage<M>*>( data->mask ) );
}
};
// ----------------------------------------------------------------------------
template <class P, class M>
bool RenderThreadBase::InitData( RenderThreadData& data,
Bitmap& bitmap, int x0, int y0, int z, int channel,
const GenericImage<P>& image,
bool showAlpha,
const GenericImage<M>* mask, int maskMode, bool maskInverted,
const uint8** LUT,
bool fast )
{
if ( subsample_index.IsEmpty() )
InitSubsampleIndex();
if ( image.IsEmptySelection() || bitmap.IsEmpty() )
return false;
int wq = bitmap.Width();
int hq = bitmap.Height();
if ( x0 >= wq || y0 >= hq )
return false;
data.bitmap = &bitmap;
data.x0 = x0;
data.y0 = y0;
data.z0 = z;
data.z = Abs( z );
data.channel = channel;
data.colorImage = image.IsColor();
data.LUT = LUT;
if ( mask != 0 )
{
data.maskMode = maskMode;
data.maskInverted = maskInverted;
data.colorMask = mask != 0 && mask->IsColor();
data.mp = mask->SelectedPoint();
}
if ( LUT != 0 )
{
data.noLUT[0] = LUT[0] == 0;
if ( data.colorImage )
{
data.noLUT[1] = LUT[1] == 0;
data.noLUT[2] = LUT[2] == 0;
data.noLUT[3] = LUT[3] == 0;
}
else
data.noLUT[1] = data.noLUT[2] = data.noLUT[3] = true;
}
else
data.noLUT[0] = data.noLUT[1] = data.noLUT[2] = data.noLUT[3] = true;
data.r = image.SelectedRectangle();
data.w = data.r.Width();
data.h = data.r.Height();
data.n = image.NumberOfNominalChannels();
data.hasAlpha = showAlpha && image.HasAlphaChannels();
if ( channel >= DisplayChannel::Lightness && channel <= DisplayChannel::Intensity )
data.F = singleComponents[channel - DisplayChannel::Lightness];
else
data.F = 0;
if ( z < 0 )
{
data.hq = z == -2 || !fast;
data.wz = Range( data.w/data.z, 1, wq-x0 );
data.hz = Range( data.h/data.z, 1, hq-y0 );
data.iz = subsample_index[data.z].Begin();
int z2 = data.hq ? z*z : data.z;
data._1_Pz2 = 1.0/P::MaxSampleValue()/z2;
data._255_Pz2 = 255 * data._1_Pz2;
data._64K_Pz2 = 65535 * data._1_Pz2;
if ( mask != 0 )
data._1_Mz2 = 1.0/M::MaxSampleValue()/z2;
}
data.image = ℑ
data.mask = mask;
data.rgbws = &image.RGBWorkingSpace();
return true;
}
RenderThreadBase::subsample_index_list RenderThreadBase::subsample_index;
void RenderThreadBase::InitSubsampleIndex()
{
subsample_index = subsample_index_list( 1 - MinZoom );
for ( int z = 3; z <= -MinZoom; ++z )
{
subsample_index[z] = IVector( z );
if ( z & 1 )
{
int x1 = 0;
for ( int i = 0; i < z; i += 2, x1 += 2 )
subsample_index[z][i] = x1;
x1 -= 3;
for ( int i = 1; i < z; i += 2, x1 -= 2 )
subsample_index[z][i] = x1;
}
else
{
for ( int i = 0, j = z-1, x1 = 0, x2 = j; i < j; i += 2, j -= 2, x1 += 2, x2 -= 2 )
{
subsample_index[z][i] = x1;
subsample_index[z][j] = x2;
}
for ( int i = 1, j = z-2, x1 = j, x2 = 1; i < j; i += 2, j -= 2, x1 -= 2, x2 += 2 )
{
subsample_index[z][i] = x1;
subsample_index[z][j] = x2;
}
}
}
}
#define bitmap data->bitmap
#define X0 data->x0
#define Y0 data->y0
#define Z0 data->z0
#define z data->z
#define channel data->channel
#define maskMode data->maskMode
#define maskInverted data->maskInverted
#define colorImage data->colorImage
#define colorMask data->colorMask
#define LUT data->LUT
#define noLUT data->noLUT
#define r data->r
#define w data->w
#define h data->h
#define n data->n
#define mp data->mp
#define hasAlpha data->hasAlpha
#define F data->F
#define hq data->hq
#define wz data->wz
#define hz data->hz
#define iz data->iz
#define _1_Pz2 data->_1_Pz2
#define _255_Pz2 data->_255_Pz2
#define _64K_Pz2 data->_64K_Pz2
#define _1_Mz2 data->_1_Mz2
#define rgbws data->rgbws
template <typename T, typename Ts>
double RenderThreadBase::SubsampledTotal( const T** f, Ts& s, int x )
{
s = 0;
if ( hq )
{
for ( int i = 0, xz = x*z; i < z; ++i )
for ( int j = 0, xj = xz; j < z; ++j, ++xj )
s += f[i][xj];
}
else
{
x *= z;
for ( int i = 0; i < z; ++i )
s += f[i][x + iz[i]];
/*
if ( z & 1 )
{
int x1 = x*z;
for ( int i = 0; i < z; i += 2, x1 += 2 )
s += f[i][x1];
x1 -= 3;
for ( int i = 1; i < z; i += 2, x1 -= 2 )
s += f[i][x1];
}
else
{
int x0 = x*z;
for ( int i = 0, j = z-1, x1 = x0, x2 = x0+j; i < j; i += 2, j -= 2, x1 += 2, x2 -= 2 )
{
s += f[i][x1];
s += f[j][x2];
}
for ( int i = 1, j = z-2, x1 = x0+j, x2 = x0+1; i < j; i += 2, j -= 2, x1 -= 2, x2 += 2 )
{
s += f[i][x1];
s += f[j][x2];
}
}
*/
/*
int x1 = x*z;
for ( int i = 0; i < z; ++i )
s += f[i][x1++];
for ( int i = 0; i < z; ++i )
s += f[i][--x1];
*/
/*
for ( int i = 0, x1 = x*z, x2 = x1+z; i < z; ++i )
{
s += f[i][x1++];
s += f[i][--x2];
}
*/
}
return s;
}
void RenderThreadBase::ApplyMask( uint8& pr, uint8& pg, uint8& pb, float mx )
{
if ( maskMode == MaskMode::Replace )
{
pr = pg = pb = UInt8PixelTraits::ToSample( mx );
}
else
{
UInt8PixelTraits::Mul( pr, mx );
UInt8PixelTraits::Mul( pg, mx );
UInt8PixelTraits::Mul( pb, mx );
if ( maskMode != MaskMode::Multiply )
{
mx = 1 - mx;
switch ( maskMode )
{
case MaskMode::OverlayRed:
UInt8PixelTraits::Add( pr, mx );
break;
case MaskMode::OverlayGreen:
UInt8PixelTraits::Add( pg, mx );
break;
case MaskMode::OverlayBlue:
UInt8PixelTraits::Add( pb, mx );
break;
case MaskMode::OverlayYellow:
UInt8PixelTraits::Add( pr, mx );
UInt8PixelTraits::Add( pg, mx );
break;
case MaskMode::OverlayMagenta:
UInt8PixelTraits::Add( pr, mx );
UInt8PixelTraits::Add( pb, mx );
break;
case MaskMode::OverlayCyan:
UInt8PixelTraits::Add( pg, mx );
UInt8PixelTraits::Add( pb, mx );
break;
case MaskMode::OverlayOrange:
UInt8PixelTraits::Add( pr, mx );
UInt8PixelTraits::Add( pg, mx/2 );
break;
case MaskMode::OverlayViolet:
UInt8PixelTraits::Add( pr, mx/2 );
UInt8PixelTraits::Add( pb, mx );
break;
default:
break;
}
}
}
}
void RenderThreadBase::ApplyMask( uint8& pr, uint8& pg, uint8& pb, float mr, float mg, float mb )
{
if ( maskMode == MaskMode::Replace )
{
UInt8PixelTraits::Mov( pr, mr );
UInt8PixelTraits::Mov( pg, mg );
UInt8PixelTraits::Mov( pb, mb );
}
else
{
switch ( channel )
{
// Individual RGB channels show their corresponding mask channels just like
// grayscale masks.
case DisplayChannel::Red:
ApplyMask( pr, pg, pb, mr );
break;
case DisplayChannel::Green:
ApplyMask( pr, pg, pb, mg );
break;
case DisplayChannel::Blue:
ApplyMask( pr, pg, pb, mb );
break;
// Other display modes except alpha channels.
case DisplayChannel::RGBK:
case DisplayChannel::Lightness:
case DisplayChannel::ChrominanceRG:
case DisplayChannel::ChrominanceLFixed:
case DisplayChannel::CIE_a:
case DisplayChannel::CIE_b:
case DisplayChannel::CIE_c:
case DisplayChannel::CIE_h:
case DisplayChannel::CIE_X:
case DisplayChannel::CIE_Y:
case DisplayChannel::CIE_Z:
case DisplayChannel::Hue:
case DisplayChannel::SaturationHSV:
case DisplayChannel::SaturationHSI:
case DisplayChannel::Value:
case DisplayChannel::Intensity:
if ( maskMode == MaskMode::Multiply )
{
UInt8PixelTraits::Mul( pr, mr );
UInt8PixelTraits::Mul( pg, mg );
UInt8PixelTraits::Mul( pb, mb );
}
else switch ( maskMode )
{
case MaskMode::OverlayRed:
UInt8PixelTraits::Mul( pr, mr );
UInt8PixelTraits::Add( pr, 1-mr );
break;
case MaskMode::OverlayGreen:
UInt8PixelTraits::Mul( pg, mg );
UInt8PixelTraits::Add( pg, 1-mg );
break;
case MaskMode::OverlayBlue:
UInt8PixelTraits::Mul( pb, mb );
UInt8PixelTraits::Add( pb, 1-mb );
break;
case MaskMode::OverlayYellow:
UInt8PixelTraits::Mul( pr, mr );
UInt8PixelTraits::Add( pr, 1-mr );
UInt8PixelTraits::Mul( pg, mg );
UInt8PixelTraits::Add( pg, 1-mg );
break;
case MaskMode::OverlayMagenta:
UInt8PixelTraits::Mul( pr, mr );
UInt8PixelTraits::Add( pr, 1-mr );
UInt8PixelTraits::Mul( pb, mb );
UInt8PixelTraits::Add( pb, 1-mb );
break;
case MaskMode::OverlayCyan:
UInt8PixelTraits::Mul( pg, mg );
UInt8PixelTraits::Add( pg, 1-mg );
UInt8PixelTraits::Mul( pb, mb );
UInt8PixelTraits::Add( pb, 1-mb );
break;
case MaskMode::OverlayOrange:
UInt8PixelTraits::Mul( pr, mr );
UInt8PixelTraits::Add( pr, 1-mr );
UInt8PixelTraits::Mul( pg, mg );
UInt8PixelTraits::Add( pg, 1-mg/2 );
break;
case MaskMode::OverlayViolet:
UInt8PixelTraits::Mul( pr, mr );
UInt8PixelTraits::Add( pr, 1-mr/2 );
UInt8PixelTraits::Mul( pb, mb );
UInt8PixelTraits::Add( pb, 1-mb );
break;
default:
break;
}
break;
// alpha channels don't show color masks
default:
break;
}
}
}
template <class P>
void RenderThreadBase::Render( const GenericImage<P>& image )
{
uint32 argb = 0xFF000000U;
uint8* pb = (uint8*)&argb;
uint8* pg = pb + 1;
uint8* pr = pg + 1;
uint8* pa = pr + 1;
if ( Z0 >= 0 )
{
const typename P::sample* f0, * f1, * f2, * fa, * fw;
uint32* b[ MaxZoom ];
for ( int y = startRow; y < endRow; ++y )
{
for ( int dy = 0; dy < z; ++dy )
b[dy] = ((uint32*)bitmap->ScanLine( Y0 + y*z + dy )) + X0;
switch ( channel )
{
case DisplayChannel::RGBK:
{
f0 = image.PixelAddress( r.x0, r.y0+y, 0 );
fw = f0 + w;
if ( colorImage )
{
f1 = image.PixelAddress( r.x0, r.y0+y, 1 );
f2 = image.PixelAddress( r.x0, r.y0+y, 2 );
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 3 ) : 0;
do
{
*pr = noLUT[0] ? UInt8PixelTraits::ToSample( *f0++ ) : LUT[0][UInt16PixelTraits::ToSample( *f0++ )];
*pg = noLUT[1] ? UInt8PixelTraits::ToSample( *f1++ ) : LUT[1][UInt16PixelTraits::ToSample( *f1++ )];
*pb = noLUT[2] ? UInt8PixelTraits::ToSample( *f2++ ) : LUT[2][UInt16PixelTraits::ToSample( *f2++ )];
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
else
{
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 1 ) : 0;
do
{
*pb = *pg = *pr =
noLUT[0] ? UInt8PixelTraits::ToSample( *f0++ ) : LUT[0][UInt16PixelTraits::ToSample( *f0++ )];
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
}
break;
case DisplayChannel::Red:
case DisplayChannel::Green:
case DisplayChannel::Blue:
{
int ch = channel - DisplayChannel::Red;
f0 = image.PixelAddress( r.x0, r.y0+y, ch );
fw = f0 + w;
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 3 ) : 0;
do
{
*pb = *pg = *pr =
noLUT[ch] ? UInt8PixelTraits::ToSample( *f0++ ) : LUT[ch][UInt16PixelTraits::ToSample( *f0++ )];
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
break;
default: // alpha channels
{
int ch = n + channel - DisplayChannel::Alpha;
f0 = image.PixelAddress( r.x0, r.y0+y, ch );
fw = f0 + w;
do
{
*pb = *pg = *pr = UInt8PixelTraits::ToSample( *f0++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
break;
case DisplayChannel::Lightness:
case DisplayChannel::CIE_X:
case DisplayChannel::CIE_Y:
case DisplayChannel::CIE_Z:
{
f0 = image.PixelAddress( r.x0, r.y0+y, 0 );
f1 = image.PixelAddress( r.x0, r.y0+y, 1 );
f2 = image.PixelAddress( r.x0, r.y0+y, 2 );
fw = f0 + w;
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 3 ) : 0;
do
{
RGBColorSystem::sample r0, r1, r2, L;
P::FromSample( r0, *f0++ );
P::FromSample( r1, *f1++ );
P::FromSample( r2, *f2++ );
L = (rgbws->*F)( r0, r1, r2 );
*pb = *pg = *pr = noLUT[3] ?
UInt8PixelTraits::ToSample( L ) :
LUT[3][UInt16PixelTraits::ToSample( L )];
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
break;
case DisplayChannel::ChrominanceRG:
{
f0 = image.PixelAddress( r.x0, r.y0+y, 0 );
f1 = image.PixelAddress( r.x0, r.y0+y, 1 );
f2 = image.PixelAddress( r.x0, r.y0+y, 2 );
fw = f0 + w;
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 3 ) : 0;
do
{
RGBColorSystem::sample r0, r1, r2;
P::FromSample( r0, *f0++ );
P::FromSample( r1, *f1++ );
P::FromSample( r2, *f2++ );
rgbws->RGBToCIEab( r0, r1, r0, r1, r2 );
*pr = UInt8PixelTraits::ToSample( r0 );
*pg = UInt8PixelTraits::ToSample( r1 );
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
break;
case DisplayChannel::ChrominanceLFixed:
{
f0 = image.PixelAddress( r.x0, r.y0+y, 0 );
f1 = image.PixelAddress( r.x0, r.y0+y, 1 );
f2 = image.PixelAddress( r.x0, r.y0+y, 2 );
fw = f0 + w;
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 3 ) : 0;
do
{
RGBColorSystem::sample r0, r1, r2;
P::FromSample( r0, *f0++ );
P::FromSample( r1, *f1++ );
P::FromSample( r2, *f2++ );
rgbws->RGBToCIEab( r0, r1, r0, r1, r2 );
rgbws->CIELabToRGB( r0, r1, r2, 0.5, r0, r1 );
*pr = UInt8PixelTraits::ToSample( r0 );
*pg = UInt8PixelTraits::ToSample( r1 );
*pb = UInt8PixelTraits::ToSample( r2 );
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
break;
case DisplayChannel::CIE_a:
case DisplayChannel::CIE_b:
case DisplayChannel::CIE_c:
case DisplayChannel::CIE_h:
case DisplayChannel::Hue:
case DisplayChannel::SaturationHSV:
case DisplayChannel::SaturationHSI:
case DisplayChannel::Value:
case DisplayChannel::Intensity:
{
f0 = image.PixelAddress( r.x0, r.y0+y, 0 );
f1 = image.PixelAddress( r.x0, r.y0+y, 1 );
f2 = image.PixelAddress( r.x0, r.y0+y, 2 );
fw = f0 + w;
fa = hasAlpha ? image.PixelAddress( r.x0, r.y0+y, 3 ) : 0;
do
{
RGBColorSystem::sample r0, r1, r2;
P::FromSample( r0, *f0++ );
P::FromSample( r1, *f1++ );
P::FromSample( r2, *f2++ );
*pb = *pg = *pr = UInt8PixelTraits::ToSample( (rgbws->*F)( r0, r1, r2 ) );
if ( hasAlpha )
*pa = UInt8PixelTraits::ToSample( *fa++ );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( f0 != fw );
}
break;
}
}
}
else // Z0 < 0
{
const typename P::sample* f[ 3 ][ -MinZoom ]; // R,G,B
const typename P::sample* fa[ -MinZoom ]; // alpha
// ###
/*
int SN = 4*((z*z)/4 + (((z*z)%4 != 0) ? 1 : 0));
float* S = (float*)_mm_malloc( SN*sizeof( float ), 16 );
memset( S, 0, SN*sizeof( float ) );
*/
// ###
for ( int y = startRow, qy = Y0 + startRow; y < endRow; ++y, ++qy )
{
uint32* b = ((uint32*)bitmap->ScanLine( qy )) + X0;
switch ( channel )
{
case DisplayChannel::RGBK:
for ( int c = 0; c < n; ++c )
for ( int i = 0; i < z; ++i )
f[c][i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
if ( hasAlpha )
for ( int i = 0, c = colorImage ? 3 : 1; i < z; ++i )
fa[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
for ( int x = 0; x < wz; ++x )
{
// ###
/*
for ( int c = 0; c < n; ++c )
{
float* p = S;
for ( int i = 0, xz = x*z; i < z; ++i )
for ( int j = 0, xj = xz; j < z; ++j, ++xj )
*p++ = float( f[c][i][xj] );
__m128* m = reinterpret_cast<__m128*>( S );
union { __m128 m; float f[ 4 ]; } __attribute__ ((aligned (16))) s;
s.f[0] = s.f[1] = s.f[2] = s.f[3] = 0;
for ( int i = 0; i < SN; i += 4 )
s.m = _mm_add_ps( s.m, *m++ );
float ss = s.f[0] + s.f[1] + s.f[2] + s.f[3];
bx[c] = noLUT[c] ? UInt8PixelTraits::FloatToSample( ss*_255_Pz2 ) :
LUT[c][UInt16PixelTraits::FloatToSample( ss*_64K_Pz2 )];
}
*/
// ###
double s = SubsampledTotal( f[0], x );
*pr = noLUT[0] ? UInt8PixelTraits::FloatToSample( s*_255_Pz2 ) :
LUT[0][UInt16PixelTraits::FloatToSample( s*_64K_Pz2 )];
if ( colorImage )
{
s = SubsampledTotal( f[1], x );
*pg = noLUT[1] ? UInt8PixelTraits::FloatToSample( s*_255_Pz2 ) :
LUT[1][UInt16PixelTraits::FloatToSample( s*_64K_Pz2 )];
s = SubsampledTotal( f[2], x );
*pb = noLUT[2] ? UInt8PixelTraits::FloatToSample( s*_255_Pz2 ) :
LUT[2][UInt16PixelTraits::FloatToSample( s*_64K_Pz2 )];
}
else
*pg = *pb = *pr;
if ( hasAlpha )
*pa = UInt8PixelTraits::FloatToSample( SubsampledTotal( fa, x )*_255_Pz2 );
*b++ = argb;
}
break;
case DisplayChannel::Red:
case DisplayChannel::Green:
case DisplayChannel::Blue:
{
int ch = channel - DisplayChannel::Red;
const typename P::sample** f0 = f[0];
for ( int i = 0; i < z; ++i )
f0[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, ch );
if ( hasAlpha )
for ( int i = 0, c = colorImage ? 3 : 1; i < z; ++i )
fa[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
for ( int x = 0; x < wz; ++x )
{
double s = SubsampledTotal( f0, x );
*pr = *pg = *pb = noLUT[ch] ?
UInt8PixelTraits::FloatToSample( s*_255_Pz2 ) :
LUT[ch][UInt16PixelTraits::FloatToSample( s*_64K_Pz2 )];
if ( hasAlpha )
*pa = UInt8PixelTraits::FloatToSample( SubsampledTotal( fa, x )*_255_Pz2 );
*b++ = argb;
}
}
break;
default: // alpha channels
{
int ch = n + channel - DisplayChannel::Alpha;
const typename P::sample** f0 = f[0];
for ( int i = 0; i < z; ++i )
f0[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, ch );
for ( int x = 0; x < wz; ++x )
{
*pr = *pg = *pb = UInt8PixelTraits::FloatToSample( SubsampledTotal( f0, x )*_255_Pz2 );
*b++ = argb;
}
}
break;
case DisplayChannel::Lightness:
case DisplayChannel::CIE_X:
case DisplayChannel::CIE_Y:
case DisplayChannel::CIE_Z:
for ( int c = 0; c < 3; ++c )
for ( int i = 0; i < z; ++i )
f[c][i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
if ( hasAlpha )
for ( int i = 0, c = colorImage ? 3 : 1; i < z; ++i )
fa[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
for ( int x = 0; x < wz; ++x )
{
double L = (rgbws->*F)( SubsampledTotal( f[0], x ) * _1_Pz2,
SubsampledTotal( f[1], x ) * _1_Pz2,
SubsampledTotal( f[2], x ) * _1_Pz2 );
*pr = *pg = *pb = noLUT[3] ?
UInt8PixelTraits::ToSample( L ) :
LUT[3][UInt16PixelTraits::ToSample( L )];
if ( hasAlpha )
*pa = UInt8PixelTraits::FloatToSample( SubsampledTotal( fa, x )*_255_Pz2 );
*b++ = argb;
}
break;
case DisplayChannel::ChrominanceRG:
for ( int c = 0; c < 3; ++c )
for ( int i = 0; i < z; ++i )
f[c][i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
if ( hasAlpha )
for ( int i = 0, c = colorImage ? 3 : 1; i < z; ++i )
fa[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
for ( int x = 0; x < wz; ++x )
{
RGBColorSystem::sample r0, r1;
rgbws->RGBToCIEab( r0, r1, SubsampledTotal( f[0], x ) * _1_Pz2,
SubsampledTotal( f[1], x ) * _1_Pz2,
SubsampledTotal( f[2], x ) * _1_Pz2 );
*pr = UInt8PixelTraits::ToSample( r0 );
*pg = UInt8PixelTraits::ToSample( r1 );
if ( hasAlpha )
*pa = UInt8PixelTraits::FloatToSample( SubsampledTotal( fa, x )*_255_Pz2 );
*b++ = argb;
}
break;
case DisplayChannel::ChrominanceLFixed:
for ( int c = 0; c < 3; ++c )
for ( int i = 0; i < z; ++i )
f[c][i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
if ( hasAlpha )
for ( int i = 0, c = colorImage ? 3 : 1; i < z; ++i )
fa[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
for ( int x = 0; x < wz; ++x )
{
RGBColorSystem::sample r0, r1, r2;
rgbws->RGBToCIEab( r0, r1, SubsampledTotal( f[0], x ) * _1_Pz2,
SubsampledTotal( f[1], x ) * _1_Pz2,
SubsampledTotal( f[2], x ) * _1_Pz2 );
rgbws->CIELabToRGB( r0, r1, r2, 0.5, r0, r1 );
*pr = UInt8PixelTraits::ToSample( r0 );
*pg = UInt8PixelTraits::ToSample( r1 );
*pb = UInt8PixelTraits::ToSample( r2 );
if ( hasAlpha )
*pa = UInt8PixelTraits::FloatToSample( SubsampledTotal( fa, x )*_255_Pz2 );
*b++ = argb;
}
break;
case DisplayChannel::CIE_a:
case DisplayChannel::CIE_b:
case DisplayChannel::CIE_c:
case DisplayChannel::CIE_h:
case DisplayChannel::Hue:
case DisplayChannel::SaturationHSV:
case DisplayChannel::SaturationHSI:
case DisplayChannel::Value:
case DisplayChannel::Intensity:
for ( int c = 0; c < 3; ++c )
for ( int i = 0; i < z; ++i )
f[c][i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
if ( hasAlpha )
for ( int i = 0, c = colorImage ? 3 : 1; i < z; ++i )
fa[i] = image.PixelAddress( r.x0, r.y0 + y*z + i, c );
for ( int x = 0; x < wz; ++x )
{
*pr = *pg = *pb = UInt8PixelTraits::ToSample(
(rgbws->*F)( SubsampledTotal( f[0], x ) * _1_Pz2,
SubsampledTotal( f[1], x ) * _1_Pz2,
SubsampledTotal( f[2], x ) * _1_Pz2 ) );
if ( hasAlpha )
*pa = UInt8PixelTraits::FloatToSample( SubsampledTotal( fa, x )*_255_Pz2 );
*b++ = argb;
}
break;
}
}
// ###
/*
_mm_free( S );
*/
// ###
}
}
template <class M>
void RenderThreadBase::Mask( const GenericImage<M>& mask )
{
uint32 argb = 0xFF000000U;
uint8* pb = (uint8*)&argb;
uint8* pg = pb + 1;
uint8* pr = pg + 1;
if ( Z0 >= 0 )
{
uint32* b[ MaxZoom ];
for ( int y = startRow; y < endRow; ++y )
{
for ( int dy = 0; dy < z; ++dy )
b[dy] = ((uint32*)bitmap->ScanLine( Y0 + y*z + dy )) + X0;
const typename M::sample* m0 = mask.PixelAddress( mp.x, mp.y+y, 0 );
const typename M::sample* mw = m0 + w;
if ( colorMask )
{
const typename M::sample* m1 = mask.PixelAddress( mp.x, mp.y+y, 1 );
const typename M::sample* m2 = mask.PixelAddress( mp.x, mp.y+y, 2 );
for ( ;; )
{
argb = **b;
if ( maskInverted )
ApplyMask( *pr, *pg, *pb,
FloatPixelTraits::ToSample( (typename M::sample)(M::MaxSampleValue() - *m0) ),
FloatPixelTraits::ToSample( (typename M::sample)(M::MaxSampleValue() - *m1) ),
FloatPixelTraits::ToSample( (typename M::sample)(M::MaxSampleValue() - *m2) ) );
else
ApplyMask( *pr, *pg, *pb,
FloatPixelTraits::ToSample( *m0 ),
FloatPixelTraits::ToSample( *m1 ),
FloatPixelTraits::ToSample( *m2 ) );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
if ( ++m0 == mw )
break;
++m1;
++m2;
}
}
else // !colorMask
{
do
{
argb = **b;
ApplyMask( *pr, *pg, *pb, FloatPixelTraits::ToSample(
maskInverted ? (typename M::sample)(M::MaxSampleValue() - *m0) : *m0 ) );
for ( int dy = 0; dy < z; ++dy )
for ( int dx = 0; dx < z; ++dx )
*(b[dy])++ = argb;
}
while ( ++m0 != mw );
}
}
}
else // Z0 < 0
{
for ( int y = startRow, qy = Y0 + startRow; y < endRow; ++y, ++qy )
{
uint32* b = ((uint32*)bitmap->ScanLine( qy )) + X0;
if ( colorMask )
{
const typename M::sample* m[ 3 ][ -MinZoom ];
for ( int c = 0; c < 3; ++c )
for ( int i = 0; i < z; ++i )
m[c][i] = mask.PixelAddress( mp.x, mp.y + y*z + i, c );
for ( int x = 0; x < wz; ++x, ++b )
{
float s0 = SubsampledTotal( m[0], x ) * _1_Mz2;
float s1 = SubsampledTotal( m[1], x ) * _1_Mz2;
float s2 = SubsampledTotal( m[2], x ) * _1_Mz2;
if ( maskInverted )
ApplyMask( ((uint8*)b)[2], ((uint8*)b)[1], ((uint8*)b)[0], 1-s0, 1-s1, 1-s2 );
else
ApplyMask( ((uint8*)b)[2], ((uint8*)b)[1], ((uint8*)b)[0], s0, s1, s2 );
}
}
else // !colorMask
{
const typename M::sample* m[ -MinZoom ];
for ( int i = 0; i < z; ++i )
m[i] = mask.PixelAddress( mp.x, mp.y + y*z + i, 0 );
for ( int x = 0; x < wz; ++x, ++b )
{
float s = SubsampledTotal( m, x ) * _1_Mz2;
ApplyMask( ((uint8*)b)[2], ((uint8*)b)[1], ((uint8*)b)[0], maskInverted ? 1-s : s );
}
}
}
}
}
#undef bitmap
#undef X0
#undef Y0
#undef Z0
#undef z
#undef channel
#undef maskMode
#undef maskInverted
#undef colorImage
#undef colorMask
#undef LUT
#undef noLUT
#undef r
#undef w
#undef h
#undef n
#undef mp
#undef hasAlpha
#undef F
#undef hq
#undef wz
#undef hz
#undef iz
#undef _1_Pz2
#undef _255_Pz2
#undef _64K_Pz2
#undef _1_Mz2
#undef rgbws
// ----------------------------------------------------------------------------
template <class P, class M> inline
bool __Render( Bitmap& bitmap, int x0, int y0, int z, int channel,
const GenericImage<P>& image,
bool showAlpha,
const GenericImage<M>* mask, int maskMode, bool maskInverted,
const uint8** LUT,
bool fast,
bool (*callback)() )
{
if ( z == 0 || z == -1 )
z = 1;
RenderThreadData data;
if ( !RenderThreadBase::InitData( data,
bitmap, x0, y0, z, channel, image, showAlpha,
mask, maskMode, maskInverted, LUT, fast ) )
{
return false;
}
int h = (z < 0) ? data.hz : data.h;
if ( callback == 0 )
{
int numberOfThreads = Thread::NumberOfThreads( h, 1 );
if ( numberOfThreads > 1 )
{
int rowsPerThread = h/numberOfThreads;
IndirectArray<RenderThread<P,M> > threads;
for ( int i = 0, j = 1; i < numberOfThreads; ++i, ++j )
threads.Add( new RenderThread<P,M>( &data,
i*rowsPerThread,
(j < numberOfThreads) ? j*rowsPerThread : h ) );
for ( int i = 0; i < numberOfThreads; ++i )
threads[i]->Start( ThreadPriority::DefaultMax, i );
for ( int i = 0; i < numberOfThreads; ++i )
threads[i]->Wait();
threads.Destroy();
}
else
{
RenderThread<P,M> thread( &data, 0, h );
thread.Run();
}
}
else
{
static int numberOfProcessors = 0;
if ( numberOfProcessors <= 0 )
numberOfProcessors = Max( 1, PixInsightSettings::GlobalInteger( "System/NumberOfProcessors" ) );
int rowsPerStep = Max( 1, 65536/data.w );
if ( z < 0 )
rowsPerStep = Max( 1, rowsPerStep/data.z );
rowsPerStep *= numberOfProcessors;
int numberOfSteps = Max( 1, h/rowsPerStep );
rowsPerStep = h/numberOfSteps;
for ( int step = 0; step < numberOfSteps; ++step )
{
int firstRow = step*rowsPerStep;
int numberOfRows = (step < numberOfSteps-1) ? rowsPerStep : h - firstRow;
int numberOfThreads = Thread::NumberOfThreads( numberOfRows, 1 );
if ( numberOfThreads > 1 )
{
int rowsPerThread = numberOfRows/numberOfThreads;
IndirectArray<RenderThread<P,M> > threads;
for ( int i = 0, j = 1; i < numberOfThreads; ++i, ++j )
threads.Add( new RenderThread<P,M>( &data,
firstRow + i*rowsPerThread,
firstRow + ((j < numberOfThreads) ? j*rowsPerThread : numberOfRows ) ) );
for ( int i = 0; i < numberOfThreads; ++i )
threads[i]->Start( ThreadPriority::DefaultMax, i );
for ( int i = 0; i < numberOfThreads; ++i )
threads[i]->Wait();
threads.Destroy();
}
else
{
RenderThread<P,M> thread( &data, firstRow, firstRow + numberOfRows );
thread.Run();
}
if ( !(*callback)() )
return false;
}
}
return true;
}
// ----------------------------------------------------------------------------
template <class P> inline
bool __Render( Bitmap& bitmap, int x, int y, int zoom, int channel,
const GenericImage<P>& image,
bool showAlpha,
const ImageVariant* mask, int maskMode, bool maskInverted,
const uint8** LUT,
bool fast,
bool (*callback)() )
{
if ( mask == 0 || !*mask )
return __Render( bitmap, x, y, zoom, channel, image, showAlpha,
static_cast<const GenericImage<P>*>( 0 ),
0, false, LUT, fast, callback );
else
{
if ( mask->IsFloatSample() )
switch ( mask->BitsPerSample() )
{
case 32: return __Render( bitmap, x, y, zoom, channel, image, showAlpha,
&static_cast<const Image&>( **mask ),
maskMode, maskInverted, LUT, fast, callback );
case 64: return __Render( bitmap, x, y, zoom, channel, image, showAlpha,
&static_cast<const DImage&>( **mask ),
maskMode, maskInverted, LUT, fast, callback );
}
else
switch ( mask->BitsPerSample() )
{
case 8: return __Render( bitmap, x, y, zoom, channel, image, showAlpha,
&static_cast<const UInt8Image&>( **mask ),
maskMode, maskInverted, LUT, fast, callback );
case 16: return __Render( bitmap, x, y, zoom, channel, image, showAlpha,
&static_cast<const UInt16Image&>( **mask ),
maskMode, maskInverted, LUT, fast, callback );
case 32: return __Render( bitmap, x, y, zoom, channel, image, showAlpha,
&static_cast<const UInt32Image&>( **mask ),
maskMode, maskInverted, LUT, fast, callback );
}
}
return false;
}
// ----------------------------------------------------------------------------
bool Render( Bitmap& bitmap, int x, int y, int zoom, int channel,
const ImageVariant& image,
bool showAlpha,
const ImageVariant* mask, int maskMode, bool maskInverted,
const uint8** LUT,
bool fast,
bool (*callback)() )
{
if ( image )
if ( image.IsFloatSample() )
switch ( image.BitsPerSample() )
{
case 32: return __Render( bitmap, x, y, zoom, channel,
static_cast<const Image&>( *image ),
showAlpha, mask, maskMode, maskInverted, LUT, fast, callback );
case 64: return __Render( bitmap, x, y, zoom, channel,
static_cast<const DImage&>( *image ),
showAlpha, mask, maskMode, maskInverted, LUT, fast, callback );
}
else
switch ( image.BitsPerSample() )
{
case 8: return __Render( bitmap, x, y, zoom, channel,
static_cast<const UInt8Image&>( *image ),
showAlpha, mask, maskMode, maskInverted, LUT, fast, callback );
case 16: return __Render( bitmap, x, y, zoom, channel,
static_cast<const UInt16Image&>( *image ),
showAlpha, mask, maskMode, maskInverted, LUT, fast, callback );
case 32: return __Render( bitmap, x, y, zoom, channel,
static_cast<const UInt32Image&>( *image ),
showAlpha, mask, maskMode, maskInverted, LUT, fast, callback );
}
return false;
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF pcl/Render.cpp - Released 2019-01-21T12:06:21Z
| 33.944325 | 124 | 0.462486 | [
"render",
"vector"
] |
67a0f9d12d92a6885b17e16a3a3dbffd894a8cfb | 2,934 | cpp | C++ | sorting/merge_sort.cpp | ajaybiswas22/ds-and-algo | b0330059c1e788e0f7d9feffbcf68fe505fb0c45 | [
"MIT"
] | null | null | null | sorting/merge_sort.cpp | ajaybiswas22/ds-and-algo | b0330059c1e788e0f7d9feffbcf68fe505fb0c45 | [
"MIT"
] | null | null | null | sorting/merge_sort.cpp | ajaybiswas22/ds-and-algo | b0330059c1e788e0f7d9feffbcf68fe505fb0c45 | [
"MIT"
] | null | null | null | /**
* @brief Program to implement Out-of-place Merge Sort
* @author Ajay Biswas
*
*/
#include <iostream>
#include <vector>
/**
* Swaps two values a and b
*
* @tparam a,b data to be swapped
* @return void
*/
template <class T>
void swap(T &a, T &b)
{
auto temp = a;
a = b;
b = temp;
}
/**
* Prints elements of a vector
*
* @tparam A Vector containing some elements
* @return void
*/
template <class T>
void printVector(std::vector<T> A)
{
for (auto i : A)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
/**
* Out-of-place merge function implementation
*
* @param A vector containing unsorted elements
* @param low First position of sub-array
* @param mid Middle position of sub-array
* @param high Last position of sub-array
* @return void
*/
void merge(std::vector<int> &A, int low, int mid, int high)
{
int i = low; // first element's index of sub-array 1
int j = mid; // last element's index of sub-array 1
int x = mid + 1; // first element's index of sub-array 2
int y = high; // last element's index of sub-array 2
std::vector<int> tA(high - low + 1); // extra space for both sub arrays
int count = 0;
while (i <= j && x <= y) // take smaller element of two sub arrays one-by-one
{
if (A[i] > A[x])
{
tA[count] = A[x];
x++;
}
else
{
tA[count] = A[i];
i++;
}
count++;
}
while (count < high - low + 1) // fill remaining elements
{
if (i > j) // if sub-array 1 has been inserted
{
tA[count] = A[x];
x++;
}
else // if sub-array 2 has been inserted
{
tA[count] = A[i];
i++;
}
count++;
}
for (int i = 0; i < count; i++) // copy into the original array
{
A[low + i] = tA[i];
}
//std::cout<<"Merged: "; // comment this
//printVector(A); // comment this
}
/**
* Sorts a vector of elements in ascending order using Merge Sort.
* Worst case Time Complexity: O(nlogn)
* Best case, Average case Time Complexity: O(nlogn)
* Worst case Space Complexity: O(n)
* Type: Out-of-place
*
* @param A vector containing unsorted elements
* @param low First position of sub-array
* @param high Last position of sub-array
* @return void
*/
void mergeSort(std::vector<int> &A, int low, int high)
{
if (low >= high)
return; // Returns recursivly
int mid = low + (high - low) / 2; // divide from half
// Divide and Conquer: O(n/2) at each step
mergeSort(A, low, mid);
mergeSort(A, mid + 1, high);
merge(A, low, mid, high);
}
// main function
int main(void)
{
std::vector<int> A = {7, 8, 4, 1, 9, 12, -1, 0};
std::cout << "Original: ";
printVector(A);
mergeSort(A, 0, A.size() - 1);
printVector(A);
} | 22.396947 | 81 | 0.543286 | [
"vector"
] |
67a26c34bcf73bd38d54259326fc64ed1710e0f7 | 2,692 | cc | C++ | deepmind/model_generation/transform_lua_test.cc | bfakhri/dml_custom | 1e908b10890df11e510d72c21f3125e3069a0eac | [
"CC-BY-4.0"
] | null | null | null | deepmind/model_generation/transform_lua_test.cc | bfakhri/dml_custom | 1e908b10890df11e510d72c21f3125e3069a0eac | [
"CC-BY-4.0"
] | null | null | null | deepmind/model_generation/transform_lua_test.cc | bfakhri/dml_custom | 1e908b10890df11e510d72c21f3125e3069a0eac | [
"CC-BY-4.0"
] | null | null | null | // Copyright (C) 2017 Google Inc.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
////////////////////////////////////////////////////////////////////////////////
#include "deepmind/model_generation/transform_lua.h"
#include "gtest/gtest.h"
#include "Eigen/Geometry"
#include "deepmind/lua/call.h"
#include "deepmind/lua/n_results_or_test_util.h"
#include "deepmind/lua/push_script.h"
#include "deepmind/lua/vm.h"
#include "deepmind/model_generation/geometry_util.h"
#include "deepmind/support/test_srcdir.h"
#include "deepmind/tensor/lua_tensor.h"
namespace deepmind {
namespace lab {
namespace {
using geometry::kEpsilon;
TEST(DeepmindTransformTest, PushRead) {
Eigen::Matrix4f ref_data;
ref_data << 0.0f, 1.0f, 2.0f, 3.0f, //
4.0f, 5.0f, 6.0f, 7.0f, //
8.0f, 9.0f, 10.0f, 11.0f, //
12.0f, 13.0f, 14.0f, 15.0f;
auto lua_vm = lua::CreateVm();
tensor::LuaTensorRegister(lua_vm.get());
Transform ref_xfrm;
ref_xfrm = ref_data;
Push(lua_vm.get(), ref_xfrm);
Transform tst_xfrm;
Read(lua_vm.get(), -1, &tst_xfrm);
EXPECT_NEAR((ref_data - tst_xfrm.matrix()).norm(), 0.0f, kEpsilon);
}
constexpr char kTransformWrongDims[] = R"(
local tensor = require 'dmlab.system.tensor'
local matrix = tensor.FloatTensor{
{ 0.0, 1.0, 2.0, 3.0 },
{ 4.0, 5.0, 6.0, 7.0 }
}
return matrix
)";
TEST(DeepmindTransformTest, ReadWrongDims) {
auto lua_vm = lua::CreateVm();
lua_vm.AddPathToSearchers(TestSrcDir());
lua_vm.AddCModuleToSearchers("dmlab.system.tensor",
tensor::LuaTensorConstructors);
auto* L = lua_vm.get();
deepmind::lab::tensor::LuaTensorRegister(L);
ASSERT_THAT(lua::PushScript(L, kTransformWrongDims, "kTransformWrongDims"),
lua::testing::IsOkAndHolds(1))
<< "Missing script";
ASSERT_THAT(lua::Call(L, 0), lua::testing::IsOkAndHolds(1))
<< "Missing result";
Transform tst_matrix;
EXPECT_FALSE(Read(L, -1, &tst_matrix));
}
} // namespace
} // namespace lab
} // namespace deepmind
| 33.234568 | 80 | 0.676449 | [
"geometry",
"transform"
] |
67a894912f689dabfc9298f44e061ba25ce72e10 | 111,777 | cpp | C++ | modules/gdscript/gdscript_compiler.cpp | MrSquigy/godot | 28326aec60f7f53f822a386c845507dbdc55e9e1 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2021-01-21T11:05:22.000Z | 2021-01-21T11:05:22.000Z | modules/gdscript/gdscript_compiler.cpp | MrSquigy/godot | 28326aec60f7f53f822a386c845507dbdc55e9e1 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | modules/gdscript/gdscript_compiler.cpp | MrSquigy/godot | 28326aec60f7f53f822a386c845507dbdc55e9e1 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | /*************************************************************************/
/* gdscript_compiler.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "gdscript_compiler.h"
#include "gdscript.h"
#include "gdscript_cache.h"
bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {
if (codegen.function_node && codegen.function_node->is_static) {
return false;
}
if (codegen.stack_identifiers.has(p_name)) {
return false; //shadowed
}
return _is_class_member_property(codegen.script, p_name);
}
bool GDScriptCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) {
GDScript *scr = owner;
GDScriptNativeClass *nc = nullptr;
while (scr) {
if (scr->native.is_valid()) {
nc = scr->native.ptr();
}
scr = scr->_base;
}
ERR_FAIL_COND_V(!nc, false);
return ClassDB::has_property(nc->get_name(), p_name);
}
void GDScriptCompiler::_set_error(const String &p_error, const GDScriptParser::Node *p_node) {
if (error != "") {
return;
}
error = p_error;
if (p_node) {
err_line = p_node->start_line;
err_column = p_node->leftmost_column;
} else {
err_line = 0;
err_column = 0;
}
}
bool GDScriptCompiler::_create_unary_operator(CodeGen &codegen, const GDScriptParser::UnaryOpNode *on, Variant::Operator op, int p_stack_level) {
int src_address_a = _parse_expression(codegen, on->operand, p_stack_level);
if (src_address_a < 0) {
return false;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR); // perform operator
codegen.opcodes.push_back(op); //which operator
codegen.opcodes.push_back(src_address_a); // argument 1
codegen.opcodes.push_back(src_address_a); // argument 2 (repeated)
//codegen.opcodes.push_back(GDScriptFunction::ADDR_TYPE_NIL); // argument 2 (unary only takes one parameter)
return true;
}
bool GDScriptCompiler::_create_binary_operator(CodeGen &codegen, const GDScriptParser::ExpressionNode *p_left_operand, const GDScriptParser::ExpressionNode *p_right_operand, Variant::Operator op, int p_stack_level, bool p_initializer, int p_index_addr) {
int src_address_a = _parse_expression(codegen, p_left_operand, p_stack_level, false, p_initializer, p_index_addr);
if (src_address_a < 0) {
return false;
}
if (src_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
p_stack_level++; //uses stack for return, increase stack
}
int src_address_b = _parse_expression(codegen, p_right_operand, p_stack_level, false, p_initializer);
if (src_address_b < 0) {
return false;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR); // perform operator
codegen.opcodes.push_back(op); //which operator
codegen.opcodes.push_back(src_address_a); // argument 1
codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter)
return true;
}
bool GDScriptCompiler::_create_binary_operator(CodeGen &codegen, const GDScriptParser::BinaryOpNode *on, Variant::Operator op, int p_stack_level, bool p_initializer, int p_index_addr) {
return _create_binary_operator(codegen, on->left_operand, on->right_operand, op, p_stack_level, p_initializer, p_index_addr);
}
GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype) const {
if (!p_datatype.is_set() || !p_datatype.is_hard_type()) {
return GDScriptDataType();
}
GDScriptDataType result;
result.has_type = true;
switch (p_datatype.kind) {
case GDScriptParser::DataType::VARIANT: {
result.has_type = false;
} break;
case GDScriptParser::DataType::BUILTIN: {
result.kind = GDScriptDataType::BUILTIN;
result.builtin_type = p_datatype.builtin_type;
} break;
case GDScriptParser::DataType::NATIVE: {
result.kind = GDScriptDataType::NATIVE;
result.native_type = p_datatype.native_type;
} break;
case GDScriptParser::DataType::SCRIPT: {
result.kind = GDScriptDataType::SCRIPT;
result.script_type = p_datatype.script_type;
result.native_type = result.script_type->get_instance_base_type();
} break;
case GDScriptParser::DataType::CLASS: {
// Locate class by constructing the path to it and following that path
GDScriptParser::ClassNode *class_type = p_datatype.class_type;
if (class_type) {
if (class_type->fqcn.begins_with(main_script->path) || (!main_script->name.empty() && class_type->fqcn.begins_with(main_script->name))) {
// Local class.
List<StringName> names;
while (class_type->outer) {
names.push_back(class_type->identifier->name);
class_type = class_type->outer;
}
Ref<GDScript> script = Ref<GDScript>(main_script);
while (names.back()) {
if (!script->subclasses.has(names.back()->get())) {
ERR_PRINT("Parser bug: Cannot locate datatype class.");
result.has_type = false;
return GDScriptDataType();
}
script = script->subclasses[names.back()->get()];
names.pop_back();
}
result.kind = GDScriptDataType::GDSCRIPT;
result.script_type = script;
result.native_type = script->get_instance_base_type();
} else {
result.kind = GDScriptDataType::GDSCRIPT;
result.script_type = GDScriptCache::get_shallow_script(p_datatype.script_path, main_script->path);
result.native_type = p_datatype.native_type;
}
}
} break;
case GDScriptParser::DataType::ENUM_VALUE:
result.has_type = true;
result.kind = GDScriptDataType::BUILTIN;
result.builtin_type = Variant::INT;
break;
case GDScriptParser::DataType::ENUM:
result.has_type = true;
result.kind = GDScriptDataType::BUILTIN;
result.builtin_type = Variant::DICTIONARY;
break;
case GDScriptParser::DataType::UNRESOLVED: {
ERR_PRINT("Parser bug: converting unresolved type.");
return GDScriptDataType();
}
}
return result;
}
int GDScriptCompiler::_parse_assign_right_expression(CodeGen &codegen, const GDScriptParser::AssignmentNode *p_assignment, int p_stack_level, int p_index_addr) {
Variant::Operator var_op = Variant::OP_MAX;
switch (p_assignment->operation) {
case GDScriptParser::AssignmentNode::OP_ADDITION:
var_op = Variant::OP_ADD;
break;
case GDScriptParser::AssignmentNode::OP_SUBTRACTION:
var_op = Variant::OP_SUBTRACT;
break;
case GDScriptParser::AssignmentNode::OP_MULTIPLICATION:
var_op = Variant::OP_MULTIPLY;
break;
case GDScriptParser::AssignmentNode::OP_DIVISION:
var_op = Variant::OP_DIVIDE;
break;
case GDScriptParser::AssignmentNode::OP_MODULO:
var_op = Variant::OP_MODULE;
break;
case GDScriptParser::AssignmentNode::OP_BIT_SHIFT_LEFT:
var_op = Variant::OP_SHIFT_LEFT;
break;
case GDScriptParser::AssignmentNode::OP_BIT_SHIFT_RIGHT:
var_op = Variant::OP_SHIFT_RIGHT;
break;
case GDScriptParser::AssignmentNode::OP_BIT_AND:
var_op = Variant::OP_BIT_AND;
break;
case GDScriptParser::AssignmentNode::OP_BIT_OR:
var_op = Variant::OP_BIT_OR;
break;
case GDScriptParser::AssignmentNode::OP_BIT_XOR:
var_op = Variant::OP_BIT_XOR;
break;
case GDScriptParser::AssignmentNode::OP_NONE: {
//none
} break;
default: {
ERR_FAIL_V(-1);
}
}
// bool initializer = p_expression->op == GDScriptParser::OperatorNode::OP_INIT_ASSIGN;
if (var_op == Variant::OP_MAX) {
return _parse_expression(codegen, p_assignment->assigned_value, p_stack_level, false, false);
}
if (!_create_binary_operator(codegen, p_assignment->assignee, p_assignment->assigned_value, var_op, p_stack_level, false, p_index_addr)) {
return -1;
}
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
}
bool GDScriptCompiler::_generate_typed_assign(CodeGen &codegen, int p_src_address, int p_dst_address, const GDScriptDataType &p_datatype, const GDScriptParser::DataType &p_value_type) {
if (p_datatype.has_type && p_value_type.is_variant()) {
// Typed assignment
switch (p_datatype.kind) {
case GDScriptDataType::BUILTIN: {
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN); // perform operator
codegen.opcodes.push_back(p_datatype.builtin_type); // variable type
codegen.opcodes.push_back(p_dst_address); // argument 1
codegen.opcodes.push_back(p_src_address); // argument 2
} break;
case GDScriptDataType::NATIVE: {
int class_idx;
if (GDScriptLanguage::get_singleton()->get_global_map().has(p_datatype.native_type)) {
class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_datatype.native_type];
class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
} else {
// _set_error("Invalid native class type '" + String(p_datatype.native_type) + "'.", on->arguments[0]);
return false;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE); // perform operator
codegen.opcodes.push_back(class_idx); // variable type
codegen.opcodes.push_back(p_dst_address); // argument 1
codegen.opcodes.push_back(p_src_address); // argument 2
} break;
case GDScriptDataType::SCRIPT:
case GDScriptDataType::GDSCRIPT: {
Variant script = p_datatype.script_type;
int idx = codegen.get_constant_pos(script); //make it a local constant (faster access)
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT); // perform operator
codegen.opcodes.push_back(idx); // variable type
codegen.opcodes.push_back(p_dst_address); // argument 1
codegen.opcodes.push_back(p_src_address); // argument 2
} break;
default: {
ERR_PRINT("Compiler bug: unresolved assign.");
// Shouldn't get here, but fail-safe to a regular assignment
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator
codegen.opcodes.push_back(p_dst_address); // argument 1
codegen.opcodes.push_back(p_src_address); // argument 2 (unary only takes one parameter)
}
}
} else {
if (p_datatype.kind == GDScriptDataType::BUILTIN && p_value_type.kind == GDScriptParser::DataType::BUILTIN && p_datatype.builtin_type != p_value_type.builtin_type) {
// Need conversion.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN); // perform operator
codegen.opcodes.push_back(p_datatype.builtin_type); // variable type
codegen.opcodes.push_back(p_dst_address); // argument 1
codegen.opcodes.push_back(p_src_address); // argument 2
} else {
// Either untyped assignment or already type-checked by the parser
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator
codegen.opcodes.push_back(p_dst_address); // argument 1
codegen.opcodes.push_back(p_src_address); // argument 2 (unary only takes one parameter)
}
}
return true;
}
int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser::ExpressionNode *p_expression, int p_stack_level, bool p_root, bool p_initializer, int p_index_addr) {
if (p_expression->is_constant) {
return codegen.get_constant_pos(p_expression->reduced_value);
}
switch (p_expression->type) {
//should parse variable declaration and adjust stack accordingly...
case GDScriptParser::Node::IDENTIFIER: {
//return identifier
//wait, identifier could be a local variable or something else... careful here, must reference properly
//as stack may be more interesting to work with
//This could be made much simpler by just indexing "self", but done this way (with custom self-addressing modes) increases performance a lot.
const GDScriptParser::IdentifierNode *in = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
StringName identifier = in->name;
// TRY STACK!
if (!p_initializer && codegen.stack_identifiers.has(identifier)) {
int pos = codegen.stack_identifiers[identifier];
return pos | (GDScriptFunction::ADDR_TYPE_STACK_VARIABLE << GDScriptFunction::ADDR_BITS);
}
// TRY LOCAL CONSTANTS!
if (codegen.local_named_constants.has(identifier)) {
return codegen.local_named_constants[identifier] | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS);
}
// TRY CLASS MEMBER
if (_is_class_member_property(codegen, identifier)) {
//get property
codegen.opcodes.push_back(GDScriptFunction::OPCODE_GET_MEMBER); // perform operator
codegen.opcodes.push_back(codegen.get_name_map_pos(identifier)); // argument 2 (unary only takes one parameter)
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
}
//TRY MEMBERS!
if (!codegen.function_node || !codegen.function_node->is_static) {
// TRY MEMBER VARIABLES!
//static function
if (codegen.script->member_indices.has(identifier)) {
if (codegen.script->member_indices[identifier].getter != StringName() && codegen.script->member_indices[identifier].getter != codegen.function_name) {
// Perform getter.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_RETURN);
codegen.opcodes.push_back(0); // Argument count.
codegen.opcodes.push_back(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS); // Base (self).
codegen.opcodes.push_back(codegen.get_name_map_pos(codegen.script->member_indices[identifier].getter)); // Method name.
// Destination.
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
} else {
// No getter or inside getter: direct member access.
int idx = codegen.script->member_indices[identifier].index;
return idx | (GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS); //argument (stack root)
}
}
}
//TRY CLASS CONSTANTS
GDScript *owner = codegen.script;
while (owner) {
GDScript *scr = owner;
GDScriptNativeClass *nc = nullptr;
while (scr) {
if (scr->constants.has(identifier)) {
//int idx=scr->constants[identifier];
int idx = codegen.get_name_map_pos(identifier);
return idx | (GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT << GDScriptFunction::ADDR_BITS); //argument (stack root)
}
if (scr->native.is_valid()) {
nc = scr->native.ptr();
}
scr = scr->_base;
}
// CLASS C++ Integer Constant
if (nc) {
bool success = false;
int constant = ClassDB::get_integer_constant(nc->get_name(), identifier, &success);
if (success) {
Variant key = constant;
int idx;
if (!codegen.constant_map.has(key)) {
idx = codegen.constant_map.size();
codegen.constant_map[key] = idx;
} else {
idx = codegen.constant_map[key];
}
return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //make it a local constant (faster access)
}
}
owner = owner->_owner;
}
// TRY SIGNALS AND METHODS (can be made callables)
if (codegen.class_node->members_indices.has(identifier)) {
const GDScriptParser::ClassNode::Member &member = codegen.class_node->members[codegen.class_node->members_indices[identifier]];
if (member.type == GDScriptParser::ClassNode::Member::FUNCTION || member.type == GDScriptParser::ClassNode::Member::SIGNAL) {
// Get like it was a property.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_GET_NAMED); // perform operator
codegen.opcodes.push_back(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS); // Self.
codegen.opcodes.push_back(codegen.get_name_map_pos(identifier)); // argument 2 (unary only takes one parameter)
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
}
}
if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
return idx | (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
}
/* TRY GLOBAL CLASSES */
if (ScriptServer::is_global_class(identifier)) {
const GDScriptParser::ClassNode *class_node = codegen.class_node;
while (class_node->outer) {
class_node = class_node->outer;
}
RES res;
if (class_node->identifier && class_node->identifier->name == identifier) {
res = Ref<GDScript>(main_script);
} else {
res = ResourceLoader::load(ScriptServer::get_global_class_path(identifier));
if (res.is_null()) {
_set_error("Can't load global class " + String(identifier) + ", cyclic reference?", p_expression);
return -1;
}
}
Variant key = res;
int idx;
if (!codegen.constant_map.has(key)) {
idx = codegen.constant_map.size();
codegen.constant_map[key] = idx;
} else {
idx = codegen.constant_map[key];
}
return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //make it a local constant (faster access)
}
#ifdef TOOLS_ENABLED
if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) {
int idx = codegen.named_globals.find(identifier);
if (idx == -1) {
idx = codegen.named_globals.size();
codegen.named_globals.push_back(identifier);
}
return idx | (GDScriptFunction::ADDR_TYPE_NAMED_GLOBAL << GDScriptFunction::ADDR_BITS);
}
#endif
//not found, error
_set_error("Identifier not found: " + String(identifier), p_expression);
return -1;
} break;
case GDScriptParser::Node::LITERAL: {
//return constant
const GDScriptParser::LiteralNode *cn = static_cast<const GDScriptParser::LiteralNode *>(p_expression);
int idx;
if (!codegen.constant_map.has(cn->value)) {
idx = codegen.constant_map.size();
codegen.constant_map[cn->value] = idx;
} else {
idx = codegen.constant_map[cn->value];
}
return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //argument (stack root)
} break;
case GDScriptParser::Node::SELF: {
//return constant
if (codegen.function_node && codegen.function_node->is_static) {
_set_error("'self' not present in static function!", p_expression);
return -1;
}
return (GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS);
} break;
case GDScriptParser::Node::ARRAY: {
const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
Vector<int> values;
int slevel = p_stack_level;
for (int i = 0; i < an->elements.size(); i++) {
int ret = _parse_expression(codegen, an->elements[i], slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
values.push_back(ret);
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CONSTRUCT_ARRAY);
codegen.opcodes.push_back(values.size());
for (int i = 0; i < values.size(); i++) {
codegen.opcodes.push_back(values[i]);
}
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
} break;
case GDScriptParser::Node::DICTIONARY: {
const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
Vector<int> elements;
int slevel = p_stack_level;
for (int i = 0; i < dn->elements.size(); i++) {
// Key.
int ret = -1;
switch (dn->style) {
case GDScriptParser::DictionaryNode::PYTHON_DICT:
// Python-style: key is any expression.
ret = _parse_expression(codegen, dn->elements[i].key, slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
break;
case GDScriptParser::DictionaryNode::LUA_TABLE:
// Lua-style: key is an identifier interpreted as string.
String key = static_cast<const GDScriptParser::IdentifierNode *>(dn->elements[i].key)->name;
ret = codegen.get_constant_pos(key);
break;
}
elements.push_back(ret);
ret = _parse_expression(codegen, dn->elements[i].value, slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
elements.push_back(ret);
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CONSTRUCT_DICTIONARY);
codegen.opcodes.push_back(dn->elements.size());
for (int i = 0; i < elements.size(); i++) {
codegen.opcodes.push_back(elements[i]);
}
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
} break;
case GDScriptParser::Node::CAST: {
const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
int slevel = p_stack_level;
int src_addr = _parse_expression(codegen, cn->operand, slevel);
if (src_addr < 0) {
return src_addr;
}
if (src_addr & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
GDScriptDataType cast_type = _gdtype_from_datatype(cn->cast_type->get_datatype());
switch (cast_type.kind) {
case GDScriptDataType::BUILTIN: {
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_BUILTIN);
codegen.opcodes.push_back(cast_type.builtin_type);
} break;
case GDScriptDataType::NATIVE: {
int class_idx;
if (GDScriptLanguage::get_singleton()->get_global_map().has(cast_type.native_type)) {
class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cast_type.native_type];
class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
} else {
_set_error("Invalid native class type '" + String(cast_type.native_type) + "'.", cn);
return -1;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_NATIVE); // perform operator
codegen.opcodes.push_back(class_idx); // variable type
} break;
case GDScriptDataType::SCRIPT:
case GDScriptDataType::GDSCRIPT: {
Variant script = cast_type.script_type;
int idx = codegen.get_constant_pos(script); //make it a local constant (faster access)
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_SCRIPT); // perform operator
codegen.opcodes.push_back(idx); // variable type
} break;
default: {
_set_error("Parser bug: unresolved data type.", cn);
return -1;
}
}
codegen.opcodes.push_back(src_addr); // source address
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
codegen.alloc_stack(p_stack_level);
return dst_addr;
} break;
//hell breaks loose
#define OPERATOR_RETURN \
int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS); \
codegen.opcodes.push_back(dst_addr); \
codegen.alloc_stack(p_stack_level); \
return dst_addr
case GDScriptParser::Node::CALL: {
const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression);
if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name) != Variant::VARIANT_MAX) {
//construct a basic type
Variant::Type vtype = GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name);
Vector<int> arguments;
int slevel = p_stack_level;
for (int i = 0; i < call->arguments.size(); i++) {
int ret = _parse_expression(codegen, call->arguments[i], slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
arguments.push_back(ret);
}
//push call bytecode
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CONSTRUCT); // basic type constructor
codegen.opcodes.push_back(vtype); //instance
codegen.opcodes.push_back(arguments.size()); //argument count
codegen.alloc_call(arguments.size());
for (int i = 0; i < arguments.size(); i++) {
codegen.opcodes.push_back(arguments[i]); //arguments
}
} else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_function(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name) != GDScriptFunctions::FUNC_MAX) {
//built in function
Vector<int> arguments;
int slevel = p_stack_level;
for (int i = 0; i < call->arguments.size(); i++) {
int ret = _parse_expression(codegen, call->arguments[i], slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
arguments.push_back(ret);
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptParser::get_builtin_function(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name));
codegen.opcodes.push_back(arguments.size());
codegen.alloc_call(arguments.size());
for (int i = 0; i < arguments.size(); i++) {
codegen.opcodes.push_back(arguments[i]);
}
} else {
//regular function
const GDScriptParser::ExpressionNode *callee = call->callee;
Vector<int> arguments;
int slevel = p_stack_level;
// TODO: Use callables when possible if needed.
int ret = -1;
int super_address = -1;
if (call->is_super) {
// Super call.
if (call->callee == nullptr) {
// Implicit super function call.
super_address = codegen.get_name_map_pos(codegen.function_node->identifier->name);
} else {
super_address = codegen.get_name_map_pos(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name);
}
} else {
if (callee->type == GDScriptParser::Node::IDENTIFIER) {
// Self function call.
if ((codegen.function_node && codegen.function_node->is_static) || call->function_name == "new") {
ret = (GDScriptFunction::ADDR_TYPE_CLASS << GDScriptFunction::ADDR_BITS);
} else {
ret = (GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS);
}
arguments.push_back(ret);
ret = codegen.get_name_map_pos(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name);
arguments.push_back(ret);
} else if (callee->type == GDScriptParser::Node::SUBSCRIPT) {
const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee);
if (subscript->is_attribute) {
ret = _parse_expression(codegen, subscript->base, slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
arguments.push_back(ret);
arguments.push_back(codegen.get_name_map_pos(subscript->attribute->name));
} else {
_set_error("Cannot call something that isn't a function.", call->callee);
return -1;
}
} else {
_set_error("Cannot call something that isn't a function.", call->callee);
return -1;
}
}
for (int i = 0; i < call->arguments.size(); i++) {
ret = _parse_expression(codegen, call->arguments[i], slevel);
if (ret < 0) {
return ret;
}
if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
arguments.push_back(ret);
}
int opcode = GDScriptFunction::OPCODE_CALL_RETURN;
if (call->is_super) {
opcode = GDScriptFunction::OPCODE_CALL_SELF_BASE;
} else if (within_await) {
opcode = GDScriptFunction::OPCODE_CALL_ASYNC;
} else if (p_root) {
opcode = GDScriptFunction::OPCODE_CALL;
}
codegen.opcodes.push_back(opcode); // perform operator
if (call->is_super) {
codegen.opcodes.push_back(super_address);
}
codegen.opcodes.push_back(call->arguments.size());
codegen.alloc_call(call->arguments.size());
for (int i = 0; i < arguments.size(); i++) {
codegen.opcodes.push_back(arguments[i]);
}
}
OPERATOR_RETURN;
} break;
case GDScriptParser::Node::GET_NODE: {
const GDScriptParser::GetNodeNode *get_node = static_cast<const GDScriptParser::GetNodeNode *>(p_expression);
String node_name;
if (get_node->string != nullptr) {
node_name += String(get_node->string->value);
} else {
for (int i = 0; i < get_node->chain.size(); i++) {
if (i > 0) {
node_name += "/";
}
node_name += get_node->chain[i]->name;
}
}
int arg_address = codegen.get_constant_pos(NodePath(node_name));
codegen.opcodes.push_back(p_root ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN);
codegen.opcodes.push_back(1); // number of arguments.
codegen.alloc_call(1);
codegen.opcodes.push_back(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS); // self.
codegen.opcodes.push_back(codegen.get_name_map_pos("get_node")); // function.
codegen.opcodes.push_back(arg_address); // argument (NodePath).
OPERATOR_RETURN;
} break;
case GDScriptParser::Node::PRELOAD: {
const GDScriptParser::PreloadNode *preload = static_cast<const GDScriptParser::PreloadNode *>(p_expression);
// Add resource as constant.
return codegen.get_constant_pos(preload->resource);
} break;
case GDScriptParser::Node::AWAIT: {
const GDScriptParser::AwaitNode *await = static_cast<const GDScriptParser::AwaitNode *>(p_expression);
int slevel = p_stack_level;
within_await = true;
int argument = _parse_expression(codegen, await->to_await, slevel);
within_await = false;
if (argument < 0) {
return argument;
}
if ((argument >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
//push call bytecode
codegen.opcodes.push_back(GDScriptFunction::OPCODE_AWAIT);
codegen.opcodes.push_back(argument);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_AWAIT_RESUME);
//next will be where to place the result :)
OPERATOR_RETURN;
} break;
//indexing operator
case GDScriptParser::Node::SUBSCRIPT: {
int slevel = p_stack_level;
const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);
int from = _parse_expression(codegen, subscript->base, slevel);
if (from < 0) {
return from;
}
bool named = subscript->is_attribute;
int index;
if (p_index_addr != 0) {
index = p_index_addr;
} else if (subscript->is_attribute) {
if (subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {
GDScriptParser::IdentifierNode *identifier = subscript->attribute;
const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name);
#ifdef DEBUG_ENABLED
if (MI && MI->get().getter == codegen.function_name) {
String n = identifier->name;
_set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", identifier);
return -1;
}
#endif
if (MI && MI->get().getter == "") {
// Faster than indexing self (as if no self. had been used)
return (MI->get().index) | (GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS);
}
}
index = codegen.get_name_map_pos(subscript->attribute->name);
} else {
if (subscript->index->type == GDScriptParser::Node::LITERAL && static_cast<const GDScriptParser::LiteralNode *>(subscript->index)->value.get_type() == Variant::STRING) {
//also, somehow, named (speed up anyway)
StringName name = static_cast<const GDScriptParser::LiteralNode *>(subscript->index)->value;
index = codegen.get_name_map_pos(name);
named = true;
} else {
//regular indexing
if (from & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
index = _parse_expression(codegen, subscript->index, slevel);
if (index < 0) {
return index;
}
}
}
codegen.opcodes.push_back(named ? GDScriptFunction::OPCODE_GET_NAMED : GDScriptFunction::OPCODE_GET); // perform operator
codegen.opcodes.push_back(from); // argument 1
codegen.opcodes.push_back(index); // argument 2 (unary only takes one parameter)
OPERATOR_RETURN;
} break;
case GDScriptParser::Node::UNARY_OPERATOR: {
//unary operators
const GDScriptParser::UnaryOpNode *unary = static_cast<const GDScriptParser::UnaryOpNode *>(p_expression);
switch (unary->operation) {
case GDScriptParser::UnaryOpNode::OP_NEGATIVE: {
if (!_create_unary_operator(codegen, unary, Variant::OP_NEGATE, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::UnaryOpNode::OP_POSITIVE: {
if (!_create_unary_operator(codegen, unary, Variant::OP_POSITIVE, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::UnaryOpNode::OP_LOGIC_NOT: {
if (!_create_unary_operator(codegen, unary, Variant::OP_NOT, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::UnaryOpNode::OP_COMPLEMENT: {
if (!_create_unary_operator(codegen, unary, Variant::OP_BIT_NEGATE, p_stack_level)) {
return -1;
}
} break;
}
OPERATOR_RETURN;
}
case GDScriptParser::Node::BINARY_OPERATOR: {
//binary operators (in precedence order)
const GDScriptParser::BinaryOpNode *binary = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);
switch (binary->operation) {
case GDScriptParser::BinaryOpNode::OP_LOGIC_AND: {
// AND operator with early out on failure
int res = _parse_expression(codegen, binary->left_operand, p_stack_level);
if (res < 0) {
return res;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
int jump_fail_pos = codegen.opcodes.size();
codegen.opcodes.push_back(0);
res = _parse_expression(codegen, binary->right_operand, p_stack_level);
if (res < 0) {
return res;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
int jump_fail_pos2 = codegen.opcodes.size();
codegen.opcodes.push_back(0);
codegen.alloc_stack(p_stack_level); //it will be used..
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TRUE);
codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(codegen.opcodes.size() + 3);
codegen.opcodes.write[jump_fail_pos] = codegen.opcodes.size();
codegen.opcodes.write[jump_fail_pos2] = codegen.opcodes.size();
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_FALSE);
codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
return p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
} break;
case GDScriptParser::BinaryOpNode::OP_LOGIC_OR: {
// OR operator with early out on success
int res = _parse_expression(codegen, binary->left_operand, p_stack_level);
if (res < 0) {
return res;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF);
codegen.opcodes.push_back(res);
int jump_success_pos = codegen.opcodes.size();
codegen.opcodes.push_back(0);
res = _parse_expression(codegen, binary->right_operand, p_stack_level);
if (res < 0) {
return res;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF);
codegen.opcodes.push_back(res);
int jump_success_pos2 = codegen.opcodes.size();
codegen.opcodes.push_back(0);
codegen.alloc_stack(p_stack_level); //it will be used..
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_FALSE);
codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(codegen.opcodes.size() + 3);
codegen.opcodes.write[jump_success_pos] = codegen.opcodes.size();
codegen.opcodes.write[jump_success_pos2] = codegen.opcodes.size();
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TRUE);
codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
return p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
} break;
case GDScriptParser::BinaryOpNode::OP_TYPE_TEST: {
int slevel = p_stack_level;
int src_address_a = _parse_expression(codegen, binary->left_operand, slevel);
if (src_address_a < 0) {
return -1;
}
if (src_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
slevel++; //uses stack for return, increase stack
}
int src_address_b = -1;
bool builtin = false;
if (binary->right_operand->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<const GDScriptParser::IdentifierNode *>(binary->right_operand)->name) != Variant::VARIANT_MAX) {
// `is` with builtin type
builtin = true;
src_address_b = (int)GDScriptParser::get_builtin_type(static_cast<const GDScriptParser::IdentifierNode *>(binary->right_operand)->name);
} else {
src_address_b = _parse_expression(codegen, binary->right_operand, slevel);
if (src_address_b < 0) {
return -1;
}
}
codegen.opcodes.push_back(builtin ? GDScriptFunction::OPCODE_IS_BUILTIN : GDScriptFunction::OPCODE_EXTENDS_TEST); // perform operator
codegen.opcodes.push_back(src_address_a); // argument 1
codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter)
} break;
case GDScriptParser::BinaryOpNode::OP_CONTENT_TEST: {
if (!_create_binary_operator(codegen, binary, Variant::OP_IN, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_COMP_EQUAL: {
if (!_create_binary_operator(codegen, binary, Variant::OP_EQUAL, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_COMP_NOT_EQUAL: {
if (!_create_binary_operator(codegen, binary, Variant::OP_NOT_EQUAL, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_COMP_LESS: {
if (!_create_binary_operator(codegen, binary, Variant::OP_LESS, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_COMP_LESS_EQUAL: {
if (!_create_binary_operator(codegen, binary, Variant::OP_LESS_EQUAL, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_COMP_GREATER: {
if (!_create_binary_operator(codegen, binary, Variant::OP_GREATER, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_COMP_GREATER_EQUAL: {
if (!_create_binary_operator(codegen, binary, Variant::OP_GREATER_EQUAL, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_ADDITION: {
if (!_create_binary_operator(codegen, binary, Variant::OP_ADD, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_SUBTRACTION: {
if (!_create_binary_operator(codegen, binary, Variant::OP_SUBTRACT, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_MULTIPLICATION: {
if (!_create_binary_operator(codegen, binary, Variant::OP_MULTIPLY, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_DIVISION: {
if (!_create_binary_operator(codegen, binary, Variant::OP_DIVIDE, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_MODULO: {
if (!_create_binary_operator(codegen, binary, Variant::OP_MODULE, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_BIT_AND: {
if (!_create_binary_operator(codegen, binary, Variant::OP_BIT_AND, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_BIT_OR: {
if (!_create_binary_operator(codegen, binary, Variant::OP_BIT_OR, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_BIT_XOR: {
if (!_create_binary_operator(codegen, binary, Variant::OP_BIT_XOR, p_stack_level)) {
return -1;
}
} break;
//shift
case GDScriptParser::BinaryOpNode::OP_BIT_LEFT_SHIFT: {
if (!_create_binary_operator(codegen, binary, Variant::OP_SHIFT_LEFT, p_stack_level)) {
return -1;
}
} break;
case GDScriptParser::BinaryOpNode::OP_BIT_RIGHT_SHIFT: {
if (!_create_binary_operator(codegen, binary, Variant::OP_SHIFT_RIGHT, p_stack_level)) {
return -1;
}
} break;
}
OPERATOR_RETURN;
} break;
// ternary operators
case GDScriptParser::Node::TERNARY_OPERATOR: {
// x IF a ELSE y operator with early out on failure
const GDScriptParser::TernaryOpNode *ternary = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression);
int res = _parse_expression(codegen, ternary->condition, p_stack_level);
if (res < 0) {
return res;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
int jump_fail_pos = codegen.opcodes.size();
codegen.opcodes.push_back(0);
res = _parse_expression(codegen, ternary->true_expr, p_stack_level);
if (res < 0) {
return res;
}
codegen.alloc_stack(p_stack_level); //it will be used..
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(res);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
int jump_past_pos = codegen.opcodes.size();
codegen.opcodes.push_back(0);
codegen.opcodes.write[jump_fail_pos] = codegen.opcodes.size();
res = _parse_expression(codegen, ternary->false_expr, p_stack_level);
if (res < 0) {
return res;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.opcodes.push_back(res);
codegen.opcodes.write[jump_past_pos] = codegen.opcodes.size();
return p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
} break;
//assignment operators
case GDScriptParser::Node::ASSIGNMENT: {
const GDScriptParser::AssignmentNode *assignment = static_cast<const GDScriptParser::AssignmentNode *>(p_expression);
if (assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
// SET (chained) MODE!
const GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(assignment->assignee);
#ifdef DEBUG_ENABLED
if (subscript->is_attribute) {
if (subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {
const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(subscript->attribute->name);
if (MI && MI->get().setter == codegen.function_name) {
String n = subscript->attribute->name;
_set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", subscript);
return -1;
}
}
}
#endif
int slevel = p_stack_level;
/* Find chain of sets */
StringName assign_property;
List<const GDScriptParser::SubscriptNode *> chain;
{
//create get/set chain
const GDScriptParser::SubscriptNode *n = subscript;
while (true) {
chain.push_back(n);
if (n->base->type != GDScriptParser::Node::SUBSCRIPT) {
//check for a built-in property
if (n->base->type == GDScriptParser::Node::IDENTIFIER) {
GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(n->base);
if (_is_class_member_property(codegen, identifier->name)) {
assign_property = identifier->name;
}
}
break;
}
n = static_cast<const GDScriptParser::SubscriptNode *>(n->base);
}
}
/* Chain of gets */
//get at (potential) root stack pos, so it can be returned
int prev_pos = _parse_expression(codegen, chain.back()->get()->base, slevel);
if (prev_pos < 0) {
return prev_pos;
}
int retval = prev_pos;
if (retval & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
Vector<int> setchain;
if (assign_property != StringName()) {
// recover and assign at the end, this allows stuff like
// position.x+=2.0
// in Node2D
setchain.push_back(prev_pos);
setchain.push_back(codegen.get_name_map_pos(assign_property));
setchain.push_back(GDScriptFunction::OPCODE_SET_MEMBER);
}
for (List<const GDScriptParser::SubscriptNode *>::Element *E = chain.back(); E; E = E->prev()) {
if (E == chain.front()) { //ignore first
break;
}
const GDScriptParser::SubscriptNode *subscript_elem = E->get();
int key_idx;
if (subscript_elem->is_attribute) {
key_idx = codegen.get_name_map_pos(subscript_elem->attribute->name);
//printf("named key %x\n",key_idx);
} else {
if (prev_pos & (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS)) {
slevel++;
codegen.alloc_stack(slevel);
}
GDScriptParser::ExpressionNode *key = subscript_elem->index;
key_idx = _parse_expression(codegen, key, slevel);
//printf("expr key %x\n",key_idx);
//stack was raised here if retval was stack but..
}
if (key_idx < 0) { //error
return key_idx;
}
codegen.opcodes.push_back(subscript_elem->is_attribute ? GDScriptFunction::OPCODE_GET_NAMED : GDScriptFunction::OPCODE_GET);
codegen.opcodes.push_back(prev_pos);
codegen.opcodes.push_back(key_idx);
slevel++;
codegen.alloc_stack(slevel);
int dst_pos = (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) | slevel;
codegen.opcodes.push_back(dst_pos);
//add in reverse order, since it will be reverted
setchain.push_back(dst_pos);
setchain.push_back(key_idx);
setchain.push_back(prev_pos);
setchain.push_back(subscript_elem->is_attribute ? GDScriptFunction::OPCODE_SET_NAMED : GDScriptFunction::OPCODE_SET);
prev_pos = dst_pos;
}
setchain.invert();
int set_index;
if (subscript->is_attribute) {
set_index = codegen.get_name_map_pos(subscript->attribute->name);
} else {
set_index = _parse_expression(codegen, subscript->index, slevel + 1);
}
if (set_index < 0) { //error
return set_index;
}
if (set_index & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
int set_value = _parse_assign_right_expression(codegen, assignment, slevel + 1, subscript->is_attribute ? 0 : set_index);
if (set_value < 0) { //error
return set_value;
}
codegen.opcodes.push_back(subscript->is_attribute ? GDScriptFunction::OPCODE_SET_NAMED : GDScriptFunction::OPCODE_SET);
codegen.opcodes.push_back(prev_pos);
codegen.opcodes.push_back(set_index);
codegen.opcodes.push_back(set_value);
for (int i = 0; i < setchain.size(); i++) {
codegen.opcodes.push_back(setchain[i]);
}
return retval;
} else if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER && _is_class_member_property(codegen, static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name)) {
//assignment to member property
int slevel = p_stack_level;
int src_address = _parse_assign_right_expression(codegen, assignment, slevel);
if (src_address < 0) {
return -1;
}
StringName name = static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name;
codegen.opcodes.push_back(GDScriptFunction::OPCODE_SET_MEMBER);
codegen.opcodes.push_back(codegen.get_name_map_pos(name));
codegen.opcodes.push_back(src_address);
return GDScriptFunction::ADDR_TYPE_NIL << GDScriptFunction::ADDR_BITS;
} else {
//REGULAR ASSIGNMENT MODE!!
int slevel = p_stack_level;
int dst_address_a = -1;
bool has_setter = false;
bool is_in_setter = false;
StringName setter_function;
if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
StringName var_name = static_cast<const GDScriptParser::IdentifierNode *>(assignment->assignee)->name;
if (!codegen.stack_identifiers.has(var_name) && codegen.script->member_indices.has(var_name)) {
setter_function = codegen.script->member_indices[var_name].setter;
if (setter_function != StringName()) {
has_setter = true;
is_in_setter = setter_function == codegen.function_name;
dst_address_a = codegen.script->member_indices[var_name].index;
}
}
}
if (has_setter) {
if (is_in_setter) {
// Use direct member access.
dst_address_a |= GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS;
} else {
// Store stack slot for the temp value.
dst_address_a = slevel++;
codegen.alloc_stack(slevel);
dst_address_a |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
}
} else {
dst_address_a = _parse_expression(codegen, assignment->assignee, slevel);
if (dst_address_a < 0) {
return -1;
}
if (dst_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
}
int src_address_b = _parse_assign_right_expression(codegen, assignment, slevel);
if (src_address_b < 0) {
return -1;
}
GDScriptDataType assign_type = _gdtype_from_datatype(assignment->assignee->get_datatype());
if (has_setter && !is_in_setter) {
// Call setter.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL);
codegen.opcodes.push_back(1); // Argument count.
codegen.opcodes.push_back(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS); // Base (self).
codegen.opcodes.push_back(codegen.get_name_map_pos(setter_function)); // Method name.
codegen.opcodes.push_back(dst_address_a); // Argument.
codegen.opcodes.push_back(dst_address_a); // Result address (won't be used here).
codegen.alloc_call(1);
} else if (!_generate_typed_assign(codegen, src_address_b, dst_address_a, assign_type, assignment->assigned_value->get_datatype())) {
return -1;
}
return dst_address_a; //if anything, returns wathever was assigned or correct stack position
}
} break;
#undef OPERATOR_RETURN
//TYPE_TYPE,
default: {
ERR_FAIL_V_MSG(-1, "Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); //unreachable code
} break;
}
}
Error GDScriptCompiler::_parse_match_pattern(CodeGen &codegen, const GDScriptParser::PatternNode *p_pattern, int p_stack_level, int p_value_addr, int p_type_addr, int &r_bound_variables, Vector<int> &r_patch_addresses, Vector<int> &r_block_patch_address) {
// TODO: Many "repeated" code here that could be abstracted. This compiler is going away when new VM arrives though, so...
switch (p_pattern->pattern_type) {
case GDScriptParser::PatternNode::PT_LITERAL: {
// Get literal type into constant map.
int literal_type_addr = -1;
if (!codegen.constant_map.has((int)p_pattern->literal->value.get_type())) {
literal_type_addr = codegen.constant_map.size();
codegen.constant_map[(int)p_pattern->literal->value.get_type()] = literal_type_addr;
} else {
literal_type_addr = codegen.constant_map[(int)p_pattern->literal->value.get_type()];
}
literal_type_addr |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS;
// Check type equality.
int equality_addr = p_stack_level++;
equality_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(p_stack_level);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(Variant::OP_EQUAL);
codegen.opcodes.push_back(p_type_addr);
codegen.opcodes.push_back(literal_type_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if not the same type.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Get literal.
int literal_addr = _parse_expression(codegen, p_pattern->literal, p_stack_level);
// Check value equality.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(Variant::OP_EQUAL);
codegen.opcodes.push_back(p_value_addr);
codegen.opcodes.push_back(literal_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if doesn't match.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Jump to the actual block since it matches. This is needed to take multi-pattern into account.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
r_block_patch_address.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
} break;
case GDScriptParser::PatternNode::PT_EXPRESSION: {
// Evaluate expression.
int expr_addr = _parse_expression(codegen, p_pattern->expression, p_stack_level);
if ((expr_addr >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
p_stack_level++;
codegen.alloc_stack(p_stack_level);
}
// Evaluate expression type.
int expr_type_addr = p_stack_level++;
expr_type_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(p_stack_level);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptFunctions::TYPE_OF);
codegen.opcodes.push_back(1); // One argument.
codegen.opcodes.push_back(expr_addr); // Argument is the value we want to test.
codegen.opcodes.push_back(expr_type_addr); // Address to result.
// Check type equality.
int equality_addr = p_stack_level++;
equality_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(p_stack_level);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(Variant::OP_EQUAL);
codegen.opcodes.push_back(p_type_addr);
codegen.opcodes.push_back(expr_type_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if not the same type.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Check value equality.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(Variant::OP_EQUAL);
codegen.opcodes.push_back(p_value_addr);
codegen.opcodes.push_back(expr_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if doesn't match.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Jump to the actual block since it matches. This is needed to take multi-pattern into account.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
r_block_patch_address.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
} break;
case GDScriptParser::PatternNode::PT_BIND: {
// Create new stack variable.
int bind_addr = p_stack_level | (GDScriptFunction::ADDR_TYPE_STACK_VARIABLE << GDScriptFunction::ADDR_BITS);
codegen.add_stack_identifier(p_pattern->bind->name, p_stack_level++);
codegen.alloc_stack(p_stack_level);
r_bound_variables++;
// Assign value to bound variable.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
codegen.opcodes.push_back(bind_addr); // Destination.
codegen.opcodes.push_back(p_value_addr); // Source.
// Not need to block jump because bind happens only once.
} break;
case GDScriptParser::PatternNode::PT_ARRAY: {
int slevel = p_stack_level;
// Get array type into constant map.
int array_type_addr = codegen.get_constant_pos(Variant::ARRAY);
// Check type equality.
int equality_addr = slevel++;
equality_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(slevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(Variant::OP_EQUAL);
codegen.opcodes.push_back(p_type_addr);
codegen.opcodes.push_back(array_type_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if not the same type.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Store pattern length in constant map.
int array_length_addr = codegen.get_constant_pos(p_pattern->rest_used ? p_pattern->array.size() - 1 : p_pattern->array.size());
// Get value length.
int value_length_addr = slevel++;
codegen.alloc_stack(slevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptFunctions::LEN);
codegen.opcodes.push_back(1); // One argument.
codegen.opcodes.push_back(p_value_addr); // Argument is the value we want to test.
codegen.opcodes.push_back(value_length_addr); // Address to result.
// Test length compatibility.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL);
codegen.opcodes.push_back(value_length_addr);
codegen.opcodes.push_back(array_length_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if length is not compatible.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Evaluate element by element.
for (int i = 0; i < p_pattern->array.size(); i++) {
if (p_pattern->array[i]->pattern_type == GDScriptParser::PatternNode::PT_REST) {
// Don't want to access an extra element of the user array.
break;
}
int stlevel = p_stack_level;
Vector<int> element_block_patches; // I want to internal patterns try the next element instead of going to the block.
// Add index to constant map.
int index_addr = codegen.get_constant_pos(i);
// Get the actual element from the user-sent array.
int element_addr = stlevel++;
codegen.alloc_stack(stlevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_GET);
codegen.opcodes.push_back(p_value_addr); // Source.
codegen.opcodes.push_back(index_addr); // Index.
codegen.opcodes.push_back(element_addr); // Destination.
// Also get type of element.
int element_type_addr = stlevel++;
element_type_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(stlevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptFunctions::TYPE_OF);
codegen.opcodes.push_back(1); // One argument.
codegen.opcodes.push_back(element_addr); // Argument is the value we want to test.
codegen.opcodes.push_back(element_type_addr); // Address to result.
// Try the pattern inside the element.
Error err = _parse_match_pattern(codegen, p_pattern->array[i], stlevel, element_addr, element_type_addr, r_bound_variables, r_patch_addresses, element_block_patches);
if (err != OK) {
return err;
}
// Patch jumps to block to try the next element.
for (int j = 0; j < element_block_patches.size(); j++) {
codegen.opcodes.write[element_block_patches[j]] = codegen.opcodes.size();
}
}
// Jump to the actual block since it matches. This is needed to take multi-pattern into account.
// Also here for the case of empty arrays.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
r_block_patch_address.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
} break;
case GDScriptParser::PatternNode::PT_DICTIONARY: {
int slevel = p_stack_level;
// Get dictionary type into constant map.
int dict_type_addr = codegen.get_constant_pos(Variant::DICTIONARY);
// Check type equality.
int equality_addr = slevel++;
equality_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(slevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(Variant::OP_EQUAL);
codegen.opcodes.push_back(p_type_addr);
codegen.opcodes.push_back(dict_type_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if not the same type.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Store pattern length in constant map.
int dict_length_addr = codegen.get_constant_pos(p_pattern->rest_used ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size());
// Get user's dictionary length.
int value_length_addr = slevel++;
codegen.alloc_stack(slevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptFunctions::LEN);
codegen.opcodes.push_back(1); // One argument.
codegen.opcodes.push_back(p_value_addr); // Argument is the value we want to test.
codegen.opcodes.push_back(value_length_addr); // Address to result.
// Test length compatibility.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR);
codegen.opcodes.push_back(p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL);
codegen.opcodes.push_back(value_length_addr);
codegen.opcodes.push_back(dict_length_addr);
codegen.opcodes.push_back(equality_addr); // Address to result.
// Jump away if length is not compatible.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(equality_addr);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
// Evaluate element by element.
for (int i = 0; i < p_pattern->dictionary.size(); i++) {
const GDScriptParser::PatternNode::Pair &element = p_pattern->dictionary[i];
if (element.value_pattern && element.value_pattern->pattern_type == GDScriptParser::PatternNode::PT_REST) {
// Ignore rest pattern.
continue;
}
int stlevel = p_stack_level;
Vector<int> element_block_patches; // I want to internal patterns try the next element instead of going to the block.
// Get the pattern key.
int pattern_key_addr = _parse_expression(codegen, element.key, stlevel);
if (pattern_key_addr < 0) {
return ERR_PARSE_ERROR;
}
if ((pattern_key_addr >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
stlevel++;
codegen.alloc_stack(stlevel);
}
// Create stack slot for test result.
int test_result = stlevel++;
test_result |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(stlevel);
// Check if pattern key exists in user's dictionary.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_RETURN);
codegen.opcodes.push_back(1); // Argument count.
codegen.opcodes.push_back(p_value_addr); // Base (user dictionary).
codegen.opcodes.push_back(codegen.get_name_map_pos("has")); // Function name.
codegen.opcodes.push_back(pattern_key_addr); // Argument (pattern key).
codegen.opcodes.push_back(test_result); // Return address.
// Jump away if key doesn't exist.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(test_result);
r_patch_addresses.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
if (element.value_pattern != nullptr) {
// Get actual value from user dictionary.
int value_addr = stlevel++;
codegen.alloc_stack(stlevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_GET);
codegen.opcodes.push_back(p_value_addr); // Source.
codegen.opcodes.push_back(pattern_key_addr); // Index.
codegen.opcodes.push_back(value_addr); // Destination.
// Also get type of value.
int value_type_addr = stlevel++;
value_type_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(stlevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptFunctions::TYPE_OF);
codegen.opcodes.push_back(1); // One argument.
codegen.opcodes.push_back(value_addr); // Argument is the value we want to test.
codegen.opcodes.push_back(value_type_addr); // Address to result.
// Try the pattern inside the value.
Error err = _parse_match_pattern(codegen, element.value_pattern, stlevel, value_addr, value_type_addr, r_bound_variables, r_patch_addresses, element_block_patches);
if (err != OK) {
return err;
}
}
// Patch jumps to block to try the next element.
for (int j = 0; j < element_block_patches.size(); j++) {
codegen.opcodes.write[element_block_patches[j]] = codegen.opcodes.size();
}
}
// Jump to the actual block since it matches. This is needed to take multi-pattern into account.
// Also here for the case of empty dictionaries.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
r_block_patch_address.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
} break;
case GDScriptParser::PatternNode::PT_REST:
// Do nothing.
break;
case GDScriptParser::PatternNode::PT_WILDCARD:
// This matches anything so just do the jump.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
r_block_patch_address.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be replaced.
}
return OK;
}
Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) {
codegen.push_stack_identifiers();
int new_identifiers = 0;
codegen.current_line = p_block->start_line;
for (int i = 0; i < p_block->statements.size(); i++) {
const GDScriptParser::Node *s = p_block->statements[i];
#ifdef DEBUG_ENABLED
// Add a newline before each statement, since the debugger needs those.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_LINE);
codegen.opcodes.push_back(s->start_line);
codegen.current_line = s->start_line;
#endif
switch (s->type) {
case GDScriptParser::Node::MATCH: {
const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(s);
int slevel = p_stack_level;
// First, let's save the addres of the value match.
int temp_addr = _parse_expression(codegen, match->test, slevel);
if (temp_addr < 0) {
return ERR_PARSE_ERROR;
}
if ((temp_addr >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
slevel++;
codegen.alloc_stack(slevel);
}
// Then, let's save the type of the value in the stack too, so we can reuse for later comparisons.
int type_addr = slevel++;
type_addr |= GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
codegen.alloc_stack(slevel);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
codegen.opcodes.push_back(GDScriptFunctions::TYPE_OF);
codegen.opcodes.push_back(1); // One argument.
codegen.opcodes.push_back(temp_addr); // Argument is the value we want to test.
codegen.opcodes.push_back(type_addr); // Address to result.
Vector<int> patch_match_end; // Will patch the jump to the end of match.
// Now we can actually start testing.
// For each branch.
for (int j = 0; j < match->branches.size(); j++) {
const GDScriptParser::MatchBranchNode *branch = match->branches[j];
int bound_variables = 0;
codegen.push_stack_identifiers(); // Create an extra block around for binds.
#ifdef DEBUG_ENABLED
// Add a newline before each branch, since the debugger needs those.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_LINE);
codegen.opcodes.push_back(s->start_line);
codegen.current_line = s->start_line;
#endif
Vector<int> patch_addrs; // Will patch with end of pattern to jump.
Vector<int> block_patch_addrs; // Will patch with start of block to jump.
// For each pattern in branch.
for (int k = 0; k < branch->patterns.size(); k++) {
if (k > 0) {
// Patch jumps per pattern to allow for multipattern. If a pattern fails it just tries the next.
for (int l = 0; l < patch_addrs.size(); l++) {
codegen.opcodes.write[patch_addrs[l]] = codegen.opcodes.size();
}
patch_addrs.clear();
}
Error err = _parse_match_pattern(codegen, branch->patterns[k], slevel, temp_addr, type_addr, bound_variables, patch_addrs, block_patch_addrs);
if (err != OK) {
return err;
}
}
// Patch jumps to the block.
for (int k = 0; k < block_patch_addrs.size(); k++) {
codegen.opcodes.write[block_patch_addrs[k]] = codegen.opcodes.size();
}
// Leave space for bound variables.
slevel += bound_variables;
codegen.alloc_stack(slevel);
// Parse the branch block.
_parse_block(codegen, branch->block, slevel, p_break_addr, p_continue_addr);
// Jump to end of match.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
patch_match_end.push_back(codegen.opcodes.size());
codegen.opcodes.push_back(0); // Will be patched.
// Patch the addresses of last pattern to jump to the end of the branch, into the next one.
for (int k = 0; k < patch_addrs.size(); k++) {
codegen.opcodes.write[patch_addrs[k]] = codegen.opcodes.size();
}
codegen.pop_stack_identifiers(); // Get out of extra block.
}
// Patch the addresses to jump to the end of the match statement.
for (int j = 0; j < patch_match_end.size(); j++) {
codegen.opcodes.write[patch_match_end[j]] = codegen.opcodes.size();
}
} break;
case GDScriptParser::Node::IF: {
const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s);
int ret2 = _parse_expression(codegen, if_n->condition, p_stack_level, false);
if (ret2 < 0) {
return ERR_PARSE_ERROR;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(ret2);
int else_addr = codegen.opcodes.size();
codegen.opcodes.push_back(0); //temporary
Error err = _parse_block(codegen, if_n->true_block, p_stack_level, p_break_addr, p_continue_addr);
if (err) {
return err;
}
if (if_n->false_block) {
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
int end_addr = codegen.opcodes.size();
codegen.opcodes.push_back(0);
codegen.opcodes.write[else_addr] = codegen.opcodes.size();
Error err2 = _parse_block(codegen, if_n->false_block, p_stack_level, p_break_addr, p_continue_addr);
if (err2) {
return err2;
}
codegen.opcodes.write[end_addr] = codegen.opcodes.size();
} else {
//end without else
codegen.opcodes.write[else_addr] = codegen.opcodes.size();
}
} break;
case GDScriptParser::Node::FOR: {
const GDScriptParser::ForNode *for_n = static_cast<const GDScriptParser::ForNode *>(s);
int slevel = p_stack_level;
int iter_stack_pos = slevel;
int iterator_pos = (slevel++) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
int counter_pos = (slevel++) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
int container_pos = (slevel++) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
codegen.alloc_stack(slevel);
codegen.push_stack_identifiers();
codegen.add_stack_identifier(for_n->variable->name, iter_stack_pos);
int ret2 = _parse_expression(codegen, for_n->list, slevel, false);
if (ret2 < 0) {
return ERR_COMPILATION_FAILED;
}
//assign container
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
codegen.opcodes.push_back(container_pos);
codegen.opcodes.push_back(ret2);
//begin loop
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ITERATE_BEGIN);
codegen.opcodes.push_back(counter_pos);
codegen.opcodes.push_back(container_pos);
codegen.opcodes.push_back(codegen.opcodes.size() + 4);
codegen.opcodes.push_back(iterator_pos);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP); //skip code for next
codegen.opcodes.push_back(codegen.opcodes.size() + 8);
//break loop
int break_pos = codegen.opcodes.size();
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP); //skip code for next
codegen.opcodes.push_back(0); //skip code for next
//next loop
int continue_pos = codegen.opcodes.size();
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ITERATE);
codegen.opcodes.push_back(counter_pos);
codegen.opcodes.push_back(container_pos);
codegen.opcodes.push_back(break_pos);
codegen.opcodes.push_back(iterator_pos);
Error err = _parse_block(codegen, for_n->loop, slevel, break_pos, continue_pos);
if (err) {
return err;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(continue_pos);
codegen.opcodes.write[break_pos + 1] = codegen.opcodes.size();
codegen.pop_stack_identifiers();
} break;
case GDScriptParser::Node::WHILE: {
const GDScriptParser::WhileNode *while_n = static_cast<const GDScriptParser::WhileNode *>(s);
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(codegen.opcodes.size() + 3);
int break_addr = codegen.opcodes.size();
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(0);
int continue_addr = codegen.opcodes.size();
int ret2 = _parse_expression(codegen, while_n->condition, p_stack_level, false);
if (ret2 < 0) {
return ERR_PARSE_ERROR;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(ret2);
codegen.opcodes.push_back(break_addr);
Error err = _parse_block(codegen, while_n->loop, p_stack_level, break_addr, continue_addr);
if (err) {
return err;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(continue_addr);
codegen.opcodes.write[break_addr + 1] = codegen.opcodes.size();
} break;
case GDScriptParser::Node::BREAK: {
if (p_break_addr < 0) {
_set_error("'break'' not within loop", s);
return ERR_COMPILATION_FAILED;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(p_break_addr);
} break;
case GDScriptParser::Node::CONTINUE: {
if (p_continue_addr < 0) {
_set_error("'continue' not within loop", s);
return ERR_COMPILATION_FAILED;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
codegen.opcodes.push_back(p_continue_addr);
} break;
case GDScriptParser::Node::RETURN: {
const GDScriptParser::ReturnNode *return_n = static_cast<const GDScriptParser::ReturnNode *>(s);
int ret2;
if (return_n->return_value != nullptr) {
ret2 = _parse_expression(codegen, return_n->return_value, p_stack_level, false);
if (ret2 < 0) {
return ERR_PARSE_ERROR;
}
} else {
ret2 = GDScriptFunction::ADDR_TYPE_NIL << GDScriptFunction::ADDR_BITS;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_RETURN);
codegen.opcodes.push_back(ret2);
} break;
case GDScriptParser::Node::ASSERT: {
#ifdef DEBUG_ENABLED
// try subblocks
const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s);
int ret2 = _parse_expression(codegen, as->condition, p_stack_level, false);
if (ret2 < 0) {
return ERR_PARSE_ERROR;
}
int message_ret = 0;
if (as->message) {
message_ret = _parse_expression(codegen, as->message, p_stack_level + 1, false);
if (message_ret < 0) {
return ERR_PARSE_ERROR;
}
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSERT);
codegen.opcodes.push_back(ret2);
codegen.opcodes.push_back(message_ret);
#endif
} break;
case GDScriptParser::Node::BREAKPOINT: {
#ifdef DEBUG_ENABLED
// try subblocks
codegen.opcodes.push_back(GDScriptFunction::OPCODE_BREAKPOINT);
#endif
} break;
case GDScriptParser::Node::VARIABLE: {
const GDScriptParser::VariableNode *lv = static_cast<const GDScriptParser::VariableNode *>(s);
// since we are using properties now for most class access, allow shadowing of class members to make user's life easier.
//
//if (_is_class_member_property(codegen, lv->name)) {
// _set_error("Name for local variable '" + String(lv->name) + "' can't shadow class property of the same name.", lv);
// return ERR_ALREADY_EXISTS;
//}
codegen.add_stack_identifier(lv->identifier->name, p_stack_level++);
codegen.alloc_stack(p_stack_level);
new_identifiers++;
if (lv->initializer != nullptr) {
int dst_address = codegen.stack_identifiers[lv->identifier->name];
dst_address |= GDScriptFunction::ADDR_TYPE_STACK_VARIABLE << GDScriptFunction::ADDR_BITS;
int src_address = _parse_expression(codegen, lv->initializer, p_stack_level);
if (src_address < 0) {
return ERR_PARSE_ERROR;
}
if (!_generate_typed_assign(codegen, src_address, dst_address, _gdtype_from_datatype(lv->get_datatype()), lv->initializer->get_datatype())) {
return ERR_PARSE_ERROR;
}
}
} break;
case GDScriptParser::Node::CONSTANT: {
// Local constants.
const GDScriptParser::ConstantNode *lc = static_cast<const GDScriptParser::ConstantNode *>(s);
if (!lc->initializer->is_constant) {
_set_error("Local constant must have a constant value as initializer.", lc->initializer);
return ERR_PARSE_ERROR;
}
codegen.local_named_constants[lc->identifier->name] = codegen.get_constant_pos(lc->initializer->reduced_value);
} break;
case GDScriptParser::Node::PASS:
// Nothing to do.
break;
default: {
//expression
if (s->is_expression()) {
int ret2 = _parse_expression(codegen, static_cast<const GDScriptParser::ExpressionNode *>(s), p_stack_level, true);
if (ret2 < 0) {
return ERR_PARSE_ERROR;
}
} else {
ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Bug in bytecode compiler, unexpected node in parse tree while parsing statement."); //unreachable code
}
} break;
}
}
codegen.pop_stack_identifiers();
return OK;
}
Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready) {
Vector<int> bytecode;
CodeGen codegen;
codegen.class_node = p_class;
codegen.script = p_script;
codegen.function_node = p_func;
codegen.stack_max = 0;
codegen.current_line = 0;
codegen.call_max = 0;
codegen.debug_stack = EngineDebugger::is_active();
Vector<StringName> argnames;
int stack_level = 0;
int optional_parameters = 0;
if (p_func) {
for (int i = 0; i < p_func->parameters.size(); i++) {
// since we are using properties now for most class access, allow shadowing of class members to make user's life easier.
//
//if (_is_class_member_property(p_script, p_func->arguments[i])) {
// _set_error("Name for argument '" + String(p_func->arguments[i]) + "' can't shadow class property of the same name.", p_func);
// return ERR_ALREADY_EXISTS;
//}
codegen.add_stack_identifier(p_func->parameters[i]->identifier->name, i);
#ifdef TOOLS_ENABLED
argnames.push_back(p_func->parameters[i]->identifier->name);
#endif
if (p_func->parameters[i]->default_value != nullptr) {
optional_parameters++;
}
}
stack_level = p_func->parameters.size();
}
codegen.alloc_stack(stack_level);
/* Parse initializer -if applies- */
bool is_implicit_initializer = !p_for_ready && !p_func;
bool is_initializer = p_func && String(p_func->identifier->name) == GDScriptLanguage::get_singleton()->strings._init;
if (is_implicit_initializer) {
// Initialize class fields.
for (int i = 0; i < p_class->members.size(); i++) {
if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {
continue;
}
const GDScriptParser::VariableNode *field = p_class->members[i].variable;
if (field->onready) {
// Only initialize in _ready.
continue;
}
if (field->initializer) {
// Emit proper line change.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_LINE);
codegen.opcodes.push_back(field->initializer->start_line);
int src_address = _parse_expression(codegen, field->initializer, stack_level, false, true);
if (src_address < 0) {
return ERR_PARSE_ERROR;
}
int dst_address = codegen.script->member_indices[field->identifier->name].index;
dst_address |= GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS;
if (!_generate_typed_assign(codegen, src_address, dst_address, _gdtype_from_datatype(field->get_datatype()), field->initializer->get_datatype())) {
return ERR_PARSE_ERROR;
}
}
}
}
if (p_for_ready || (p_func && String(p_func->identifier->name) == "_ready")) {
// Initialize class fields on ready.
for (int i = 0; i < p_class->members.size(); i++) {
if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {
continue;
}
const GDScriptParser::VariableNode *field = p_class->members[i].variable;
if (!field->onready) {
continue;
}
if (field->initializer) {
// Emit proper line change.
codegen.opcodes.push_back(GDScriptFunction::OPCODE_LINE);
codegen.opcodes.push_back(field->initializer->start_line);
int src_address = _parse_expression(codegen, field->initializer, stack_level, false, true);
if (src_address < 0) {
return ERR_PARSE_ERROR;
}
int dst_address = codegen.script->member_indices[field->identifier->name].index;
dst_address |= GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS;
if (!_generate_typed_assign(codegen, src_address, dst_address, _gdtype_from_datatype(field->get_datatype()), field->initializer->get_datatype())) {
return ERR_PARSE_ERROR;
}
}
}
}
/* Parse default argument code -if applies- */
Vector<int> defarg_addr;
StringName func_name;
if (p_func) {
if (optional_parameters > 0) {
codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_TO_DEF_ARGUMENT);
defarg_addr.push_back(codegen.opcodes.size());
for (int i = p_func->parameters.size() - optional_parameters; i < p_func->parameters.size(); i++) {
int src_addr = _parse_expression(codegen, p_func->parameters[i]->default_value, stack_level, true);
if (src_addr < 0) {
return ERR_PARSE_ERROR;
}
int dst_addr = codegen.stack_identifiers[p_func->parameters[i]->identifier->name] | (GDScriptFunction::ADDR_TYPE_STACK_VARIABLE << GDScriptFunction::ADDR_BITS);
if (!_generate_typed_assign(codegen, src_addr, dst_addr, _gdtype_from_datatype(p_func->parameters[i]->get_datatype()), p_func->parameters[i]->default_value->get_datatype())) {
return ERR_PARSE_ERROR;
}
defarg_addr.push_back(codegen.opcodes.size());
}
defarg_addr.invert();
}
func_name = p_func->identifier->name;
codegen.function_name = func_name;
Error err = _parse_block(codegen, p_func->body, stack_level);
if (err) {
return err;
}
} else {
if (p_for_ready) {
func_name = "_ready";
} else {
func_name = "@implicit_new";
}
}
codegen.function_name = func_name;
codegen.opcodes.push_back(GDScriptFunction::OPCODE_END);
/*
if (String(p_func->name)=="") { //initializer func
gdfunc = &p_script->initializer;
*/
//} else { //regular func
p_script->member_functions[func_name] = memnew(GDScriptFunction);
GDScriptFunction *gdfunc = p_script->member_functions[func_name];
//}
if (p_func) {
gdfunc->_static = p_func->is_static;
gdfunc->rpc_mode = p_func->rpc_mode;
gdfunc->argument_types.resize(p_func->parameters.size());
for (int i = 0; i < p_func->parameters.size(); i++) {
gdfunc->argument_types.write[i] = _gdtype_from_datatype(p_func->parameters[i]->get_datatype());
}
gdfunc->return_type = _gdtype_from_datatype(p_func->get_datatype());
} else {
gdfunc->_static = false;
gdfunc->rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
gdfunc->return_type = GDScriptDataType();
gdfunc->return_type.has_type = true;
gdfunc->return_type.kind = GDScriptDataType::BUILTIN;
gdfunc->return_type.builtin_type = Variant::NIL;
}
#ifdef TOOLS_ENABLED
gdfunc->arg_names = argnames;
#endif
//constants
if (codegen.constant_map.size()) {
gdfunc->_constant_count = codegen.constant_map.size();
gdfunc->constants.resize(codegen.constant_map.size());
gdfunc->_constants_ptr = gdfunc->constants.ptrw();
const Variant *K = nullptr;
while ((K = codegen.constant_map.next(K))) {
int idx = codegen.constant_map[*K];
gdfunc->constants.write[idx] = *K;
}
} else {
gdfunc->_constants_ptr = nullptr;
gdfunc->_constant_count = 0;
}
//global names
if (codegen.name_map.size()) {
gdfunc->global_names.resize(codegen.name_map.size());
gdfunc->_global_names_ptr = &gdfunc->global_names[0];
for (Map<StringName, int>::Element *E = codegen.name_map.front(); E; E = E->next()) {
gdfunc->global_names.write[E->get()] = E->key();
}
gdfunc->_global_names_count = gdfunc->global_names.size();
} else {
gdfunc->_global_names_ptr = nullptr;
gdfunc->_global_names_count = 0;
}
#ifdef TOOLS_ENABLED
// Named globals
if (codegen.named_globals.size()) {
gdfunc->named_globals.resize(codegen.named_globals.size());
gdfunc->_named_globals_ptr = gdfunc->named_globals.ptr();
for (int i = 0; i < codegen.named_globals.size(); i++) {
gdfunc->named_globals.write[i] = codegen.named_globals[i];
}
gdfunc->_named_globals_count = gdfunc->named_globals.size();
}
#endif
if (codegen.opcodes.size()) {
gdfunc->code = codegen.opcodes;
gdfunc->_code_ptr = &gdfunc->code[0];
gdfunc->_code_size = codegen.opcodes.size();
} else {
gdfunc->_code_ptr = nullptr;
gdfunc->_code_size = 0;
}
if (defarg_addr.size()) {
gdfunc->default_arguments = defarg_addr;
gdfunc->_default_arg_count = defarg_addr.size() - 1;
gdfunc->_default_arg_ptr = &gdfunc->default_arguments[0];
} else {
gdfunc->_default_arg_count = 0;
gdfunc->_default_arg_ptr = nullptr;
}
gdfunc->_argument_count = p_func ? p_func->parameters.size() : 0;
gdfunc->_stack_size = codegen.stack_max;
gdfunc->_call_size = codegen.call_max;
gdfunc->name = func_name;
#ifdef DEBUG_ENABLED
if (EngineDebugger::is_active()) {
String signature;
//path
if (p_script->get_path() != String()) {
signature += p_script->get_path();
}
//loc
if (p_func) {
signature += "::" + itos(p_func->body->start_line);
} else {
signature += "::0";
}
//function and class
if (p_class->identifier) {
signature += "::" + String(p_class->identifier->name) + "." + String(func_name);
} else {
signature += "::" + String(func_name);
}
gdfunc->profile.signature = signature;
}
#endif
gdfunc->_script = p_script;
gdfunc->source = source;
#ifdef DEBUG_ENABLED
{
gdfunc->func_cname = (String(source) + " - " + String(func_name)).utf8();
gdfunc->_func_cname = gdfunc->func_cname.get_data();
}
#endif
if (p_func) {
gdfunc->_initial_line = p_func->start_line;
#ifdef TOOLS_ENABLED
p_script->member_lines[func_name] = p_func->start_line;
#endif
} else {
gdfunc->_initial_line = 0;
}
if (codegen.debug_stack) {
gdfunc->stack_debug = codegen.stack_debug;
}
if (is_initializer) {
p_script->initializer = gdfunc;
}
if (is_implicit_initializer) {
p_script->implicit_initializer = gdfunc;
}
return OK;
}
Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) {
Vector<int> bytecode;
CodeGen codegen;
codegen.class_node = p_class;
codegen.script = p_script;
codegen.function_node = nullptr;
codegen.stack_max = 0;
codegen.current_line = 0;
codegen.call_max = 0;
codegen.debug_stack = EngineDebugger::is_active();
Vector<StringName> argnames;
int stack_level = 0;
if (p_is_setter) {
codegen.add_stack_identifier(p_variable->setter_parameter->name, stack_level++);
argnames.push_back(p_variable->setter_parameter->name);
}
codegen.alloc_stack(stack_level);
StringName func_name;
if (p_is_setter) {
func_name = "@" + p_variable->identifier->name + "_setter";
} else {
func_name = "@" + p_variable->identifier->name + "_getter";
}
codegen.function_name = func_name;
Error err = _parse_block(codegen, p_is_setter ? p_variable->setter : p_variable->getter, stack_level);
if (err != OK) {
return err;
}
codegen.opcodes.push_back(GDScriptFunction::OPCODE_END);
p_script->member_functions[func_name] = memnew(GDScriptFunction);
GDScriptFunction *gdfunc = p_script->member_functions[func_name];
gdfunc->_static = false;
gdfunc->rpc_mode = p_variable->rpc_mode;
gdfunc->argument_types.resize(p_is_setter ? 1 : 0);
gdfunc->return_type = _gdtype_from_datatype(p_variable->get_datatype());
#ifdef TOOLS_ENABLED
gdfunc->arg_names = argnames;
#endif
// TODO: Unify this with function compiler.
//constants
if (codegen.constant_map.size()) {
gdfunc->_constant_count = codegen.constant_map.size();
gdfunc->constants.resize(codegen.constant_map.size());
gdfunc->_constants_ptr = gdfunc->constants.ptrw();
const Variant *K = nullptr;
while ((K = codegen.constant_map.next(K))) {
int idx = codegen.constant_map[*K];
gdfunc->constants.write[idx] = *K;
}
} else {
gdfunc->_constants_ptr = nullptr;
gdfunc->_constant_count = 0;
}
//global names
if (codegen.name_map.size()) {
gdfunc->global_names.resize(codegen.name_map.size());
gdfunc->_global_names_ptr = &gdfunc->global_names[0];
for (Map<StringName, int>::Element *E = codegen.name_map.front(); E; E = E->next()) {
gdfunc->global_names.write[E->get()] = E->key();
}
gdfunc->_global_names_count = gdfunc->global_names.size();
} else {
gdfunc->_global_names_ptr = nullptr;
gdfunc->_global_names_count = 0;
}
#ifdef TOOLS_ENABLED
// Named globals
if (codegen.named_globals.size()) {
gdfunc->named_globals.resize(codegen.named_globals.size());
gdfunc->_named_globals_ptr = gdfunc->named_globals.ptr();
for (int i = 0; i < codegen.named_globals.size(); i++) {
gdfunc->named_globals.write[i] = codegen.named_globals[i];
}
gdfunc->_named_globals_count = gdfunc->named_globals.size();
}
#endif
gdfunc->code = codegen.opcodes;
gdfunc->_code_ptr = &gdfunc->code[0];
gdfunc->_code_size = codegen.opcodes.size();
gdfunc->_default_arg_count = 0;
gdfunc->_default_arg_ptr = nullptr;
gdfunc->_argument_count = argnames.size();
gdfunc->_stack_size = codegen.stack_max;
gdfunc->_call_size = codegen.call_max;
gdfunc->name = func_name;
#ifdef DEBUG_ENABLED
if (EngineDebugger::is_active()) {
String signature;
//path
if (p_script->get_path() != String()) {
signature += p_script->get_path();
}
//loc
signature += "::" + itos(p_is_setter ? p_variable->setter->start_line : p_variable->getter->start_line);
//function and class
if (p_class->identifier) {
signature += "::" + String(p_class->identifier->name) + "." + String(func_name);
} else {
signature += "::" + String(func_name);
}
gdfunc->profile.signature = signature;
}
#endif
gdfunc->_script = p_script;
gdfunc->source = source;
#ifdef DEBUG_ENABLED
{
gdfunc->func_cname = (String(source) + " - " + String(func_name)).utf8();
gdfunc->_func_cname = gdfunc->func_cname.get_data();
}
#endif
gdfunc->_initial_line = p_is_setter ? p_variable->setter->start_line : p_variable->getter->start_line;
#ifdef TOOLS_ENABLED
p_script->member_lines[func_name] = gdfunc->_initial_line;
#endif
if (codegen.debug_stack) {
gdfunc->stack_debug = codegen.stack_debug;
}
return OK;
}
Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
parsing_classes.insert(p_script);
if (p_class->outer && p_class->outer->outer) {
// Owner is not root
if (!parsed_classes.has(p_script->_owner)) {
if (parsing_classes.has(p_script->_owner)) {
_set_error("Cyclic class reference for '" + String(p_class->identifier->name) + "'.", p_class);
return ERR_PARSE_ERROR;
}
Error err = _parse_class_level(p_script->_owner, p_class->outer, p_keep_state);
if (err) {
return err;
}
}
}
p_script->native = Ref<GDScriptNativeClass>();
p_script->base = Ref<GDScript>();
p_script->_base = nullptr;
p_script->members.clear();
p_script->constants.clear();
for (Map<StringName, GDScriptFunction *>::Element *E = p_script->member_functions.front(); E; E = E->next()) {
memdelete(E->get());
}
p_script->member_functions.clear();
p_script->member_indices.clear();
p_script->member_info.clear();
p_script->_signals.clear();
p_script->initializer = nullptr;
p_script->tool = parser->is_tool();
p_script->name = p_class->identifier ? p_class->identifier->name : "";
Ref<GDScriptNativeClass> native;
GDScriptDataType base_type = _gdtype_from_datatype(p_class->base_type);
// Inheritance
switch (base_type.kind) {
case GDScriptDataType::NATIVE: {
int native_idx = GDScriptLanguage::get_singleton()->get_global_map()[base_type.native_type];
native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx];
ERR_FAIL_COND_V(native.is_null(), ERR_BUG);
p_script->native = native;
} break;
case GDScriptDataType::GDSCRIPT: {
Ref<GDScript> base = base_type.script_type;
p_script->base = base;
p_script->_base = base.ptr();
if (p_class->base_type.kind == GDScriptParser::DataType::CLASS && p_class->base_type.class_type != nullptr) {
if (p_class->base_type.script_path == main_script->path) {
if (!parsed_classes.has(p_script->_base)) {
if (parsing_classes.has(p_script->_base)) {
String class_name = p_class->identifier ? p_class->identifier->name : "<main>";
_set_error("Cyclic class reference for '" + class_name + "'.", p_class);
return ERR_PARSE_ERROR;
}
Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state);
if (err) {
return err;
}
}
} else {
Error err = OK;
base = GDScriptCache::get_full_script(p_class->base_type.script_path, err, main_script->path);
if (err) {
return err;
}
if (base.is_null() && !base->is_valid()) {
return ERR_COMPILATION_FAILED;
}
}
}
p_script->member_indices = base->member_indices;
} break;
default: {
_set_error("Parser bug: invalid inheritance.", p_class);
return ERR_BUG;
} break;
}
for (int i = 0; i < p_class->members.size(); i++) {
const GDScriptParser::ClassNode::Member &member = p_class->members[i];
switch (member.type) {
case GDScriptParser::ClassNode::Member::VARIABLE: {
const GDScriptParser::VariableNode *variable = member.variable;
StringName name = variable->identifier->name;
GDScript::MemberInfo minfo;
minfo.index = p_script->member_indices.size();
switch (variable->property) {
case GDScriptParser::VariableNode::PROP_NONE:
break; // Nothing to do.
case GDScriptParser::VariableNode::PROP_SETGET:
if (variable->setter_pointer != nullptr) {
minfo.setter = variable->setter_pointer->name;
}
if (variable->getter_pointer != nullptr) {
minfo.getter = variable->getter_pointer->name;
}
break;
case GDScriptParser::VariableNode::PROP_INLINE:
if (variable->setter != nullptr) {
minfo.setter = "@" + variable->identifier->name + "_setter";
}
if (variable->getter != nullptr) {
minfo.getter = "@" + variable->identifier->name + "_getter";
}
break;
}
minfo.rpc_mode = variable->rpc_mode;
minfo.data_type = _gdtype_from_datatype(variable->get_datatype());
PropertyInfo prop_info = minfo.data_type;
prop_info.name = name;
PropertyInfo export_info = variable->export_info;
if (variable->exported) {
if (!minfo.data_type.has_type) {
prop_info.type = export_info.type;
prop_info.class_name = export_info.class_name;
}
prop_info.hint = export_info.hint;
prop_info.hint_string = export_info.hint_string;
prop_info.usage = export_info.usage;
#ifdef TOOLS_ENABLED
if (variable->initializer != nullptr && variable->initializer->type == GDScriptParser::Node::LITERAL) {
p_script->member_default_values[name] = static_cast<const GDScriptParser::LiteralNode *>(variable->initializer)->value;
}
#endif
} else {
prop_info.usage = PROPERTY_USAGE_SCRIPT_VARIABLE;
}
p_script->member_info[name] = prop_info;
p_script->member_indices[name] = minfo;
p_script->members.insert(name);
#ifdef TOOLS_ENABLED
p_script->member_lines[name] = variable->start_line;
#endif
} break;
case GDScriptParser::ClassNode::Member::CONSTANT: {
const GDScriptParser::ConstantNode *constant = member.constant;
StringName name = constant->identifier->name;
p_script->constants.insert(name, constant->initializer->reduced_value);
#ifdef TOOLS_ENABLED
p_script->member_lines[name] = constant->start_line;
#endif
} break;
case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
const GDScriptParser::EnumNode::Value &enum_value = member.enum_value;
StringName name = enum_value.identifier->name;
p_script->constants.insert(name, enum_value.value);
#ifdef TOOLS_ENABLED
p_script->member_lines[name] = enum_value.identifier->start_line;
#endif
} break;
case GDScriptParser::ClassNode::Member::SIGNAL: {
const GDScriptParser::SignalNode *signal = member.signal;
StringName name = signal->identifier->name;
GDScript *c = p_script;
while (c) {
if (c->_signals.has(name)) {
_set_error("Signal '" + name + "' redefined (in current or parent class)", p_class);
return ERR_ALREADY_EXISTS;
}
if (c->base.is_valid()) {
c = c->base.ptr();
} else {
c = nullptr;
}
}
if (native.is_valid()) {
if (ClassDB::has_signal(native->get_name(), name)) {
_set_error("Signal '" + name + "' redefined (original in native class '" + String(native->get_name()) + "')", p_class);
return ERR_ALREADY_EXISTS;
}
}
Vector<StringName> parameters_names;
parameters_names.resize(signal->parameters.size());
for (int j = 0; j < signal->parameters.size(); j++) {
parameters_names.write[j] = signal->parameters[j]->identifier->name;
}
p_script->_signals[name] = parameters_names;
} break;
case GDScriptParser::ClassNode::Member::ENUM: {
const GDScriptParser::EnumNode *enum_n = member.m_enum;
// TODO: Make enums not be just a dictionary?
Dictionary new_enum;
for (int j = 0; j < enum_n->values.size(); j++) {
int value = enum_n->values[j].value;
// Needs to be string because Variant::get will convert to String.
new_enum[String(enum_n->values[j].identifier->name)] = value;
}
p_script->constants.insert(enum_n->identifier->name, new_enum);
#ifdef TOOLS_ENABLED
p_script->member_lines[enum_n->identifier->name] = enum_n->start_line;
#endif
} break;
default:
break; // Nothing to do here.
}
}
parsed_classes.insert(p_script);
parsing_classes.erase(p_script);
//parse sub-classes
for (int i = 0; i < p_class->members.size(); i++) {
const GDScriptParser::ClassNode::Member &member = p_class->members[i];
if (member.type != member.CLASS) {
continue;
}
const GDScriptParser::ClassNode *inner_class = member.m_class;
StringName name = inner_class->identifier->name;
Ref<GDScript> &subclass = p_script->subclasses[name];
GDScript *subclass_ptr = subclass.ptr();
// Subclass might still be parsing, just skip it
if (!parsed_classes.has(subclass_ptr) && !parsing_classes.has(subclass_ptr)) {
Error err = _parse_class_level(subclass_ptr, inner_class, p_keep_state);
if (err) {
return err;
}
}
#ifdef TOOLS_ENABLED
p_script->member_lines[name] = inner_class->start_line;
#endif
p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants
}
return OK;
}
Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
//parse methods
bool has_ready = false;
for (int i = 0; i < p_class->members.size(); i++) {
const GDScriptParser::ClassNode::Member &member = p_class->members[i];
if (member.type == member.FUNCTION) {
const GDScriptParser::FunctionNode *function = member.function;
if (!has_ready && function->identifier->name == "_ready") {
has_ready = true;
}
Error err = _parse_function(p_script, p_class, function);
if (err) {
return err;
}
} else if (member.type == member.VARIABLE) {
const GDScriptParser::VariableNode *variable = member.variable;
if (variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
if (variable->setter != nullptr) {
Error err = _parse_setter_getter(p_script, p_class, variable, true);
if (err) {
return err;
}
}
if (variable->getter != nullptr) {
Error err = _parse_setter_getter(p_script, p_class, variable, false);
if (err) {
return err;
}
}
}
}
}
{
// Create an implicit constructor in any case.
Error err = _parse_function(p_script, p_class, nullptr);
if (err) {
return err;
}
}
if (!has_ready && p_class->onready_used) {
//create a _ready constructor
Error err = _parse_function(p_script, p_class, nullptr, true);
if (err) {
return err;
}
}
#ifdef DEBUG_ENABLED
//validate instances if keeping state
if (p_keep_state) {
for (Set<Object *>::Element *E = p_script->instances.front(); E;) {
Set<Object *>::Element *N = E->next();
ScriptInstance *si = E->get()->get_script_instance();
if (si->is_placeholder()) {
#ifdef TOOLS_ENABLED
PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si);
if (p_script->is_tool()) {
//re-create as an instance
p_script->placeholders.erase(psi); //remove placeholder
GDScriptInstance *instance = memnew(GDScriptInstance);
instance->base_ref = Object::cast_to<Reference>(E->get());
instance->members.resize(p_script->member_indices.size());
instance->script = Ref<GDScript>(p_script);
instance->owner = E->get();
//needed for hot reloading
for (Map<StringName, GDScript::MemberInfo>::Element *F = p_script->member_indices.front(); F; F = F->next()) {
instance->member_indices_cache[F->key()] = F->get().index;
}
instance->owner->set_script_instance(instance);
/* STEP 2, INITIALIZE AND CONSTRUCT */
Callable::CallError ce;
p_script->initializer->call(instance, nullptr, 0, ce);
if (ce.error != Callable::CallError::CALL_OK) {
//well, tough luck, not goinna do anything here
}
}
#endif
} else {
GDScriptInstance *gi = static_cast<GDScriptInstance *>(si);
gi->reload_members();
}
E = N;
}
}
#endif
for (int i = 0; i < p_class->members.size(); i++) {
if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
continue;
}
const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;
StringName name = inner_class->identifier->name;
GDScript *subclass = p_script->subclasses[name].ptr();
Error err = _parse_class_blocks(subclass, inner_class, p_keep_state);
if (err) {
return err;
}
}
p_script->valid = true;
return OK;
}
void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
Map<StringName, Ref<GDScript>> old_subclasses;
if (p_keep_state) {
old_subclasses = p_script->subclasses;
}
p_script->subclasses.clear();
for (int i = 0; i < p_class->members.size(); i++) {
if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
continue;
}
const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;
StringName name = inner_class->identifier->name;
Ref<GDScript> subclass;
String fully_qualified_name = p_script->fully_qualified_name + "::" + name;
if (old_subclasses.has(name)) {
subclass = old_subclasses[name];
} else {
Ref<GDScript> orphan_subclass = GDScriptLanguage::get_singleton()->get_orphan_subclass(fully_qualified_name);
if (orphan_subclass.is_valid()) {
subclass = orphan_subclass;
} else {
subclass.instance();
}
}
subclass->_owner = p_script;
subclass->fully_qualified_name = fully_qualified_name;
p_script->subclasses.insert(name, subclass);
_make_scripts(subclass.ptr(), inner_class, false);
}
}
Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) {
err_line = -1;
err_column = -1;
error = "";
parser = p_parser;
main_script = p_script;
const GDScriptParser::ClassNode *root = parser->get_tree();
source = p_script->get_path();
// The best fully qualified name for a base level script is its file path
p_script->fully_qualified_name = p_script->path;
// Create scripts for subclasses beforehand so they can be referenced
_make_scripts(p_script, root, p_keep_state);
p_script->_owner = nullptr;
Error err = _parse_class_level(p_script, root, p_keep_state);
if (err) {
return err;
}
err = _parse_class_blocks(p_script, root, p_keep_state);
if (err) {
return err;
}
return GDScriptCache::finish_compiling(p_script->get_path());
}
String GDScriptCompiler::get_error() const {
return error;
}
int GDScriptCompiler::get_error_line() const {
return err_line;
}
int GDScriptCompiler::get_error_column() const {
return err_column;
}
GDScriptCompiler::GDScriptCompiler() {
}
| 37.036779 | 256 | 0.700511 | [
"object",
"vector"
] |
67ad9d60687210f45725a3c76f2490cc5830c823 | 220,250 | cpp | C++ | IL2CPP/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_20Table.cpp | dngoins/AutographTheWorld-MR | 24e567c8030b73a6942e25b36b7370667c649b90 | [
"MIT"
] | null | null | null | IL2CPP/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_20Table.cpp | dngoins/AutographTheWorld-MR | 24e567c8030b73a6942e25b36b7370667c649b90 | [
"MIT"
] | null | null | null | IL2CPP/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_20Table.cpp | dngoins/AutographTheWorld-MR | 24e567c8030b73a6942e25b36b7370667c649b90 | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// System.ComponentModel.TypeDescriptionProvider/EmptyCustomTypeDescriptor
struct EmptyCustomTypeDescriptor_t4007109994;
// System.Reflection.MemberInfo
struct MemberInfo_t;
// System.Collections.ICollection
struct ICollection_t3904884886;
// System.Collections.IDictionary
struct IDictionary_t1363984059;
// System.ComponentModel.PropertyDescriptor[]
struct PropertyDescriptorU5BU5D_t2649761905;
// System.String[]
struct StringU5BU5D_t1281789340;
// System.Collections.IComparer
struct IComparer_t1540313114;
// System.Security.Cryptography.OidCollection
struct OidCollection_t4234766844;
// System.String
struct String_t;
// System.ComponentModel.AttributeCollection
struct AttributeCollection_t4221220734;
// System.Attribute[]
struct AttributeU5BU5D_t1575011174;
// System.Collections.ArrayList
struct ArrayList_t2718874744;
// System.ComponentModel.Design.ITypeDescriptorFilterService
struct ITypeDescriptorFilterService_t2751835844;
// System.ComponentModel.WeakHashtable
struct WeakHashtable_t3533205710;
// System.Collections.Hashtable
struct Hashtable_t1853889766;
// System.Diagnostics.BooleanSwitch
struct BooleanSwitch_t440064918;
// System.Guid[]
struct GuidU5BU5D_t545550574;
// System.ComponentModel.RefreshEventHandler
struct RefreshEventHandler_t3637242902;
// System.Type
struct Type_t;
// System.ComponentModel.EventDescriptorCollection
struct EventDescriptorCollection_t2278158832;
// System.ComponentModel.PropertyDescriptorCollection
struct PropertyDescriptorCollection_t4164928659;
// System.ComponentModel.TypeConverter
struct TypeConverter_t2249118273;
// System.Object[]
struct ObjectU5BU5D_t2843939325;
// System.Type[]
struct TypeU5BU5D_t3940880105;
// System.ComponentModel.ReferenceConverter
struct ReferenceConverter_t1811933861;
// System.ComponentModel.ICustomTypeDescriptor
struct ICustomTypeDescriptor_t1654759486;
// System.ComponentModel.EventDescriptor[]
struct EventDescriptorU5BU5D_t1482016031;
// System.Runtime.Serialization.SafeSerializationManager
struct SafeSerializationManager_t2481557153;
// System.Diagnostics.StackTrace[]
struct StackTraceU5BU5D_t1169129676;
// System.IntPtr[]
struct IntPtrU5BU5D_t4013366056;
// System.ComponentModel.EventHandlerList/ListEntry
struct ListEntry_t2424989506;
// System.ComponentModel.Component
struct Component_t3620823400;
// System.Security.Cryptography.Oid
struct Oid_t3552120260;
// System.Byte[]
struct ByteU5BU5D_t4116647657;
// System.Delegate
struct Delegate_t1188392813;
// System.ComponentModel.TypeDescriptionProvider
struct TypeDescriptionProvider_t3232077895;
// System.Void
struct Void_t1185182177;
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode
struct TypeDescriptionNode_t3022060204;
// System.Security.Cryptography.RandomNumberGenerator
struct RandomNumberGenerator_t386037858;
// System.Char[]
struct CharU5BU5D_t3528271667;
// System.ComponentModel.PropertyDescriptor
struct PropertyDescriptor_t3244362832;
// System.ComponentModel.IExtenderProvider
struct IExtenderProvider_t3668760454;
// System.Collections.Hashtable/bucket[]
struct bucketU5BU5D_t876121385;
// System.Collections.IEqualityComparer
struct IEqualityComparer_t1493878338;
// System.Reflection.MethodInfo
struct MethodInfo_t;
// System.DelegateData
struct DelegateData_t1677132599;
// System.ComponentModel.TypeConverter/StandardValuesCollection
struct StandardValuesCollection_t2184948248;
// System.Delegate[]
struct DelegateU5BU5D_t1703627840;
// System.ComponentModel.PropertyChangedEventArgs
struct PropertyChangedEventArgs_t3313059048;
// System.IAsyncResult
struct IAsyncResult_t767004451;
// System.AsyncCallback
struct AsyncCallback_t3962456242;
// System.ComponentModel.RefreshEventArgs
struct RefreshEventArgs_t9288056;
struct Exception_t_marshaled_pinvoke;
struct Exception_t_marshaled_com;
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
#ifndef TYPEDESCRIPTIONPROVIDER_T3232077895_H
#define TYPEDESCRIPTIONPROVIDER_T3232077895_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptionProvider
struct TypeDescriptionProvider_t3232077895 : public RuntimeObject
{
public:
// System.ComponentModel.TypeDescriptionProvider System.ComponentModel.TypeDescriptionProvider::_parent
TypeDescriptionProvider_t3232077895 * ____parent_0;
// System.ComponentModel.TypeDescriptionProvider/EmptyCustomTypeDescriptor System.ComponentModel.TypeDescriptionProvider::_emptyDescriptor
EmptyCustomTypeDescriptor_t4007109994 * ____emptyDescriptor_1;
public:
inline static int32_t get_offset_of__parent_0() { return static_cast<int32_t>(offsetof(TypeDescriptionProvider_t3232077895, ____parent_0)); }
inline TypeDescriptionProvider_t3232077895 * get__parent_0() const { return ____parent_0; }
inline TypeDescriptionProvider_t3232077895 ** get_address_of__parent_0() { return &____parent_0; }
inline void set__parent_0(TypeDescriptionProvider_t3232077895 * value)
{
____parent_0 = value;
Il2CppCodeGenWriteBarrier((&____parent_0), value);
}
inline static int32_t get_offset_of__emptyDescriptor_1() { return static_cast<int32_t>(offsetof(TypeDescriptionProvider_t3232077895, ____emptyDescriptor_1)); }
inline EmptyCustomTypeDescriptor_t4007109994 * get__emptyDescriptor_1() const { return ____emptyDescriptor_1; }
inline EmptyCustomTypeDescriptor_t4007109994 ** get_address_of__emptyDescriptor_1() { return &____emptyDescriptor_1; }
inline void set__emptyDescriptor_1(EmptyCustomTypeDescriptor_t4007109994 * value)
{
____emptyDescriptor_1 = value;
Il2CppCodeGenWriteBarrier((&____emptyDescriptor_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPEDESCRIPTIONPROVIDER_T3232077895_H
#ifndef INSTANCEDESCRIPTOR_T657473484_H
#define INSTANCEDESCRIPTOR_T657473484_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Design.Serialization.InstanceDescriptor
struct InstanceDescriptor_t657473484 : public RuntimeObject
{
public:
// System.Reflection.MemberInfo System.ComponentModel.Design.Serialization.InstanceDescriptor::member
MemberInfo_t * ___member_0;
// System.Collections.ICollection System.ComponentModel.Design.Serialization.InstanceDescriptor::arguments
RuntimeObject* ___arguments_1;
// System.Boolean System.ComponentModel.Design.Serialization.InstanceDescriptor::isComplete
bool ___isComplete_2;
public:
inline static int32_t get_offset_of_member_0() { return static_cast<int32_t>(offsetof(InstanceDescriptor_t657473484, ___member_0)); }
inline MemberInfo_t * get_member_0() const { return ___member_0; }
inline MemberInfo_t ** get_address_of_member_0() { return &___member_0; }
inline void set_member_0(MemberInfo_t * value)
{
___member_0 = value;
Il2CppCodeGenWriteBarrier((&___member_0), value);
}
inline static int32_t get_offset_of_arguments_1() { return static_cast<int32_t>(offsetof(InstanceDescriptor_t657473484, ___arguments_1)); }
inline RuntimeObject* get_arguments_1() const { return ___arguments_1; }
inline RuntimeObject** get_address_of_arguments_1() { return &___arguments_1; }
inline void set_arguments_1(RuntimeObject* value)
{
___arguments_1 = value;
Il2CppCodeGenWriteBarrier((&___arguments_1), value);
}
inline static int32_t get_offset_of_isComplete_2() { return static_cast<int32_t>(offsetof(InstanceDescriptor_t657473484, ___isComplete_2)); }
inline bool get_isComplete_2() const { return ___isComplete_2; }
inline bool* get_address_of_isComplete_2() { return &___isComplete_2; }
inline void set_isComplete_2(bool value)
{
___isComplete_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INSTANCEDESCRIPTOR_T657473484_H
#ifndef PROPERTYDESCRIPTORCOLLECTION_T4164928659_H
#define PROPERTYDESCRIPTORCOLLECTION_T4164928659_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyDescriptorCollection
struct PropertyDescriptorCollection_t4164928659 : public RuntimeObject
{
public:
// System.Collections.IDictionary System.ComponentModel.PropertyDescriptorCollection::cachedFoundProperties
RuntimeObject* ___cachedFoundProperties_1;
// System.Boolean System.ComponentModel.PropertyDescriptorCollection::cachedIgnoreCase
bool ___cachedIgnoreCase_2;
// System.ComponentModel.PropertyDescriptor[] System.ComponentModel.PropertyDescriptorCollection::properties
PropertyDescriptorU5BU5D_t2649761905* ___properties_3;
// System.Int32 System.ComponentModel.PropertyDescriptorCollection::propCount
int32_t ___propCount_4;
// System.String[] System.ComponentModel.PropertyDescriptorCollection::namedSort
StringU5BU5D_t1281789340* ___namedSort_5;
// System.Collections.IComparer System.ComponentModel.PropertyDescriptorCollection::comparer
RuntimeObject* ___comparer_6;
// System.Boolean System.ComponentModel.PropertyDescriptorCollection::propsOwned
bool ___propsOwned_7;
// System.Boolean System.ComponentModel.PropertyDescriptorCollection::needSort
bool ___needSort_8;
// System.Boolean System.ComponentModel.PropertyDescriptorCollection::readOnly
bool ___readOnly_9;
public:
inline static int32_t get_offset_of_cachedFoundProperties_1() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___cachedFoundProperties_1)); }
inline RuntimeObject* get_cachedFoundProperties_1() const { return ___cachedFoundProperties_1; }
inline RuntimeObject** get_address_of_cachedFoundProperties_1() { return &___cachedFoundProperties_1; }
inline void set_cachedFoundProperties_1(RuntimeObject* value)
{
___cachedFoundProperties_1 = value;
Il2CppCodeGenWriteBarrier((&___cachedFoundProperties_1), value);
}
inline static int32_t get_offset_of_cachedIgnoreCase_2() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___cachedIgnoreCase_2)); }
inline bool get_cachedIgnoreCase_2() const { return ___cachedIgnoreCase_2; }
inline bool* get_address_of_cachedIgnoreCase_2() { return &___cachedIgnoreCase_2; }
inline void set_cachedIgnoreCase_2(bool value)
{
___cachedIgnoreCase_2 = value;
}
inline static int32_t get_offset_of_properties_3() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___properties_3)); }
inline PropertyDescriptorU5BU5D_t2649761905* get_properties_3() const { return ___properties_3; }
inline PropertyDescriptorU5BU5D_t2649761905** get_address_of_properties_3() { return &___properties_3; }
inline void set_properties_3(PropertyDescriptorU5BU5D_t2649761905* value)
{
___properties_3 = value;
Il2CppCodeGenWriteBarrier((&___properties_3), value);
}
inline static int32_t get_offset_of_propCount_4() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___propCount_4)); }
inline int32_t get_propCount_4() const { return ___propCount_4; }
inline int32_t* get_address_of_propCount_4() { return &___propCount_4; }
inline void set_propCount_4(int32_t value)
{
___propCount_4 = value;
}
inline static int32_t get_offset_of_namedSort_5() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___namedSort_5)); }
inline StringU5BU5D_t1281789340* get_namedSort_5() const { return ___namedSort_5; }
inline StringU5BU5D_t1281789340** get_address_of_namedSort_5() { return &___namedSort_5; }
inline void set_namedSort_5(StringU5BU5D_t1281789340* value)
{
___namedSort_5 = value;
Il2CppCodeGenWriteBarrier((&___namedSort_5), value);
}
inline static int32_t get_offset_of_comparer_6() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___comparer_6)); }
inline RuntimeObject* get_comparer_6() const { return ___comparer_6; }
inline RuntimeObject** get_address_of_comparer_6() { return &___comparer_6; }
inline void set_comparer_6(RuntimeObject* value)
{
___comparer_6 = value;
Il2CppCodeGenWriteBarrier((&___comparer_6), value);
}
inline static int32_t get_offset_of_propsOwned_7() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___propsOwned_7)); }
inline bool get_propsOwned_7() const { return ___propsOwned_7; }
inline bool* get_address_of_propsOwned_7() { return &___propsOwned_7; }
inline void set_propsOwned_7(bool value)
{
___propsOwned_7 = value;
}
inline static int32_t get_offset_of_needSort_8() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___needSort_8)); }
inline bool get_needSort_8() const { return ___needSort_8; }
inline bool* get_address_of_needSort_8() { return &___needSort_8; }
inline void set_needSort_8(bool value)
{
___needSort_8 = value;
}
inline static int32_t get_offset_of_readOnly_9() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659, ___readOnly_9)); }
inline bool get_readOnly_9() const { return ___readOnly_9; }
inline bool* get_address_of_readOnly_9() { return &___readOnly_9; }
inline void set_readOnly_9(bool value)
{
___readOnly_9 = value;
}
};
struct PropertyDescriptorCollection_t4164928659_StaticFields
{
public:
// System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.PropertyDescriptorCollection::Empty
PropertyDescriptorCollection_t4164928659 * ___Empty_0;
public:
inline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(PropertyDescriptorCollection_t4164928659_StaticFields, ___Empty_0)); }
inline PropertyDescriptorCollection_t4164928659 * get_Empty_0() const { return ___Empty_0; }
inline PropertyDescriptorCollection_t4164928659 ** get_address_of_Empty_0() { return &___Empty_0; }
inline void set_Empty_0(PropertyDescriptorCollection_t4164928659 * value)
{
___Empty_0 = value;
Il2CppCodeGenWriteBarrier((&___Empty_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYDESCRIPTORCOLLECTION_T4164928659_H
#ifndef WEAKKEYCOMPARER_T448163292_H
#define WEAKKEYCOMPARER_T448163292_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.WeakHashtable/WeakKeyComparer
struct WeakKeyComparer_t448163292 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WEAKKEYCOMPARER_T448163292_H
#ifndef OIDENUMERATOR_T899373898_H
#define OIDENUMERATOR_T899373898_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.OidEnumerator
struct OidEnumerator_t899373898 : public RuntimeObject
{
public:
// System.Security.Cryptography.OidCollection System.Security.Cryptography.OidEnumerator::m_oids
OidCollection_t4234766844 * ___m_oids_0;
// System.Int32 System.Security.Cryptography.OidEnumerator::m_current
int32_t ___m_current_1;
public:
inline static int32_t get_offset_of_m_oids_0() { return static_cast<int32_t>(offsetof(OidEnumerator_t899373898, ___m_oids_0)); }
inline OidCollection_t4234766844 * get_m_oids_0() const { return ___m_oids_0; }
inline OidCollection_t4234766844 ** get_address_of_m_oids_0() { return &___m_oids_0; }
inline void set_m_oids_0(OidCollection_t4234766844 * value)
{
___m_oids_0 = value;
Il2CppCodeGenWriteBarrier((&___m_oids_0), value);
}
inline static int32_t get_offset_of_m_current_1() { return static_cast<int32_t>(offsetof(OidEnumerator_t899373898, ___m_current_1)); }
inline int32_t get_m_current_1() const { return ___m_current_1; }
inline int32_t* get_address_of_m_current_1() { return &___m_current_1; }
inline void set_m_current_1(int32_t value)
{
___m_current_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OIDENUMERATOR_T899373898_H
#ifndef CAPI_T4202866366_H
#define CAPI_T4202866366_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.CAPI
struct CAPI_t4202866366 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CAPI_T4202866366_H
#ifndef MEMBERDESCRIPTOR_T3815403747_H
#define MEMBERDESCRIPTOR_T3815403747_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.MemberDescriptor
struct MemberDescriptor_t3815403747 : public RuntimeObject
{
public:
// System.String System.ComponentModel.MemberDescriptor::name
String_t* ___name_0;
// System.Int32 System.ComponentModel.MemberDescriptor::nameHash
int32_t ___nameHash_1;
// System.ComponentModel.AttributeCollection System.ComponentModel.MemberDescriptor::attributeCollection
AttributeCollection_t4221220734 * ___attributeCollection_2;
// System.Attribute[] System.ComponentModel.MemberDescriptor::attributes
AttributeU5BU5D_t1575011174* ___attributes_3;
// System.Attribute[] System.ComponentModel.MemberDescriptor::originalAttributes
AttributeU5BU5D_t1575011174* ___originalAttributes_4;
// System.Boolean System.ComponentModel.MemberDescriptor::attributesFiltered
bool ___attributesFiltered_5;
// System.Boolean System.ComponentModel.MemberDescriptor::attributesFilled
bool ___attributesFilled_6;
// System.Int32 System.ComponentModel.MemberDescriptor::metadataVersion
int32_t ___metadataVersion_7;
// System.String System.ComponentModel.MemberDescriptor::category
String_t* ___category_8;
// System.String System.ComponentModel.MemberDescriptor::description
String_t* ___description_9;
// System.Object System.ComponentModel.MemberDescriptor::lockCookie
RuntimeObject * ___lockCookie_10;
public:
inline static int32_t get_offset_of_name_0() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___name_0)); }
inline String_t* get_name_0() const { return ___name_0; }
inline String_t** get_address_of_name_0() { return &___name_0; }
inline void set_name_0(String_t* value)
{
___name_0 = value;
Il2CppCodeGenWriteBarrier((&___name_0), value);
}
inline static int32_t get_offset_of_nameHash_1() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___nameHash_1)); }
inline int32_t get_nameHash_1() const { return ___nameHash_1; }
inline int32_t* get_address_of_nameHash_1() { return &___nameHash_1; }
inline void set_nameHash_1(int32_t value)
{
___nameHash_1 = value;
}
inline static int32_t get_offset_of_attributeCollection_2() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___attributeCollection_2)); }
inline AttributeCollection_t4221220734 * get_attributeCollection_2() const { return ___attributeCollection_2; }
inline AttributeCollection_t4221220734 ** get_address_of_attributeCollection_2() { return &___attributeCollection_2; }
inline void set_attributeCollection_2(AttributeCollection_t4221220734 * value)
{
___attributeCollection_2 = value;
Il2CppCodeGenWriteBarrier((&___attributeCollection_2), value);
}
inline static int32_t get_offset_of_attributes_3() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___attributes_3)); }
inline AttributeU5BU5D_t1575011174* get_attributes_3() const { return ___attributes_3; }
inline AttributeU5BU5D_t1575011174** get_address_of_attributes_3() { return &___attributes_3; }
inline void set_attributes_3(AttributeU5BU5D_t1575011174* value)
{
___attributes_3 = value;
Il2CppCodeGenWriteBarrier((&___attributes_3), value);
}
inline static int32_t get_offset_of_originalAttributes_4() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___originalAttributes_4)); }
inline AttributeU5BU5D_t1575011174* get_originalAttributes_4() const { return ___originalAttributes_4; }
inline AttributeU5BU5D_t1575011174** get_address_of_originalAttributes_4() { return &___originalAttributes_4; }
inline void set_originalAttributes_4(AttributeU5BU5D_t1575011174* value)
{
___originalAttributes_4 = value;
Il2CppCodeGenWriteBarrier((&___originalAttributes_4), value);
}
inline static int32_t get_offset_of_attributesFiltered_5() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___attributesFiltered_5)); }
inline bool get_attributesFiltered_5() const { return ___attributesFiltered_5; }
inline bool* get_address_of_attributesFiltered_5() { return &___attributesFiltered_5; }
inline void set_attributesFiltered_5(bool value)
{
___attributesFiltered_5 = value;
}
inline static int32_t get_offset_of_attributesFilled_6() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___attributesFilled_6)); }
inline bool get_attributesFilled_6() const { return ___attributesFilled_6; }
inline bool* get_address_of_attributesFilled_6() { return &___attributesFilled_6; }
inline void set_attributesFilled_6(bool value)
{
___attributesFilled_6 = value;
}
inline static int32_t get_offset_of_metadataVersion_7() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___metadataVersion_7)); }
inline int32_t get_metadataVersion_7() const { return ___metadataVersion_7; }
inline int32_t* get_address_of_metadataVersion_7() { return &___metadataVersion_7; }
inline void set_metadataVersion_7(int32_t value)
{
___metadataVersion_7 = value;
}
inline static int32_t get_offset_of_category_8() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___category_8)); }
inline String_t* get_category_8() const { return ___category_8; }
inline String_t** get_address_of_category_8() { return &___category_8; }
inline void set_category_8(String_t* value)
{
___category_8 = value;
Il2CppCodeGenWriteBarrier((&___category_8), value);
}
inline static int32_t get_offset_of_description_9() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___description_9)); }
inline String_t* get_description_9() const { return ___description_9; }
inline String_t** get_address_of_description_9() { return &___description_9; }
inline void set_description_9(String_t* value)
{
___description_9 = value;
Il2CppCodeGenWriteBarrier((&___description_9), value);
}
inline static int32_t get_offset_of_lockCookie_10() { return static_cast<int32_t>(offsetof(MemberDescriptor_t3815403747, ___lockCookie_10)); }
inline RuntimeObject * get_lockCookie_10() const { return ___lockCookie_10; }
inline RuntimeObject ** get_address_of_lockCookie_10() { return &___lockCookie_10; }
inline void set_lockCookie_10(RuntimeObject * value)
{
___lockCookie_10 = value;
Il2CppCodeGenWriteBarrier((&___lockCookie_10), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MEMBERDESCRIPTOR_T3815403747_H
#ifndef OIDCOLLECTION_T4234766844_H
#define OIDCOLLECTION_T4234766844_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.OidCollection
struct OidCollection_t4234766844 : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Security.Cryptography.OidCollection::m_list
ArrayList_t2718874744 * ___m_list_0;
public:
inline static int32_t get_offset_of_m_list_0() { return static_cast<int32_t>(offsetof(OidCollection_t4234766844, ___m_list_0)); }
inline ArrayList_t2718874744 * get_m_list_0() const { return ___m_list_0; }
inline ArrayList_t2718874744 ** get_address_of_m_list_0() { return &___m_list_0; }
inline void set_m_list_0(ArrayList_t2718874744 * value)
{
___m_list_0 = value;
Il2CppCodeGenWriteBarrier((&___m_list_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OIDCOLLECTION_T4234766844_H
#ifndef FILTERCACHEITEM_T1189670310_H
#define FILTERCACHEITEM_T1189670310_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/FilterCacheItem
struct FilterCacheItem_t1189670310 : public RuntimeObject
{
public:
// System.ComponentModel.Design.ITypeDescriptorFilterService System.ComponentModel.TypeDescriptor/FilterCacheItem::_filterService
RuntimeObject* ____filterService_0;
// System.Collections.ICollection System.ComponentModel.TypeDescriptor/FilterCacheItem::FilteredMembers
RuntimeObject* ___FilteredMembers_1;
public:
inline static int32_t get_offset_of__filterService_0() { return static_cast<int32_t>(offsetof(FilterCacheItem_t1189670310, ____filterService_0)); }
inline RuntimeObject* get__filterService_0() const { return ____filterService_0; }
inline RuntimeObject** get_address_of__filterService_0() { return &____filterService_0; }
inline void set__filterService_0(RuntimeObject* value)
{
____filterService_0 = value;
Il2CppCodeGenWriteBarrier((&____filterService_0), value);
}
inline static int32_t get_offset_of_FilteredMembers_1() { return static_cast<int32_t>(offsetof(FilterCacheItem_t1189670310, ___FilteredMembers_1)); }
inline RuntimeObject* get_FilteredMembers_1() const { return ___FilteredMembers_1; }
inline RuntimeObject** get_address_of_FilteredMembers_1() { return &___FilteredMembers_1; }
inline void set_FilteredMembers_1(RuntimeObject* value)
{
___FilteredMembers_1 = value;
Il2CppCodeGenWriteBarrier((&___FilteredMembers_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // FILTERCACHEITEM_T1189670310_H
#ifndef MEMBERDESCRIPTORCOMPARER_T457940793_H
#define MEMBERDESCRIPTORCOMPARER_T457940793_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/MemberDescriptorComparer
struct MemberDescriptorComparer_t457940793 : public RuntimeObject
{
public:
public:
};
struct MemberDescriptorComparer_t457940793_StaticFields
{
public:
// System.ComponentModel.TypeDescriptor/MemberDescriptorComparer System.ComponentModel.TypeDescriptor/MemberDescriptorComparer::Instance
MemberDescriptorComparer_t457940793 * ___Instance_0;
public:
inline static int32_t get_offset_of_Instance_0() { return static_cast<int32_t>(offsetof(MemberDescriptorComparer_t457940793_StaticFields, ___Instance_0)); }
inline MemberDescriptorComparer_t457940793 * get_Instance_0() const { return ___Instance_0; }
inline MemberDescriptorComparer_t457940793 ** get_address_of_Instance_0() { return &___Instance_0; }
inline void set_Instance_0(MemberDescriptorComparer_t457940793 * value)
{
___Instance_0 = value;
Il2CppCodeGenWriteBarrier((&___Instance_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MEMBERDESCRIPTORCOMPARER_T457940793_H
#ifndef STANDARDVALUESCOLLECTION_T2184948248_H
#define STANDARDVALUESCOLLECTION_T2184948248_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverter/StandardValuesCollection
struct StandardValuesCollection_t2184948248 : public RuntimeObject
{
public:
// System.Collections.ICollection System.ComponentModel.TypeConverter/StandardValuesCollection::values
RuntimeObject* ___values_0;
// System.Array System.ComponentModel.TypeConverter/StandardValuesCollection::valueArray
RuntimeArray * ___valueArray_1;
public:
inline static int32_t get_offset_of_values_0() { return static_cast<int32_t>(offsetof(StandardValuesCollection_t2184948248, ___values_0)); }
inline RuntimeObject* get_values_0() const { return ___values_0; }
inline RuntimeObject** get_address_of_values_0() { return &___values_0; }
inline void set_values_0(RuntimeObject* value)
{
___values_0 = value;
Il2CppCodeGenWriteBarrier((&___values_0), value);
}
inline static int32_t get_offset_of_valueArray_1() { return static_cast<int32_t>(offsetof(StandardValuesCollection_t2184948248, ___valueArray_1)); }
inline RuntimeArray * get_valueArray_1() const { return ___valueArray_1; }
inline RuntimeArray ** get_address_of_valueArray_1() { return &___valueArray_1; }
inline void set_valueArray_1(RuntimeArray * value)
{
___valueArray_1 = value;
Il2CppCodeGenWriteBarrier((&___valueArray_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STANDARDVALUESCOLLECTION_T2184948248_H
#ifndef TYPEDESCRIPTOR_T3066613587_H
#define TYPEDESCRIPTOR_T3066613587_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor
struct TypeDescriptor_t3066613587 : public RuntimeObject
{
public:
public:
};
struct TypeDescriptor_t3066613587_StaticFields
{
public:
// System.ComponentModel.WeakHashtable System.ComponentModel.TypeDescriptor::_providerTable
WeakHashtable_t3533205710 * ____providerTable_0;
// System.Collections.Hashtable System.ComponentModel.TypeDescriptor::_providerTypeTable
Hashtable_t1853889766 * ____providerTypeTable_1;
// System.Collections.Hashtable modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.TypeDescriptor::_defaultProviders
Hashtable_t1853889766 * ____defaultProviders_2;
// System.Int32 System.ComponentModel.TypeDescriptor::_metadataVersion
int32_t ____metadataVersion_3;
// System.Int32 System.ComponentModel.TypeDescriptor::_collisionIndex
int32_t ____collisionIndex_4;
// System.Diagnostics.BooleanSwitch System.ComponentModel.TypeDescriptor::TraceDescriptor
BooleanSwitch_t440064918 * ___TraceDescriptor_5;
// System.Guid[] System.ComponentModel.TypeDescriptor::_pipelineInitializeKeys
GuidU5BU5D_t545550574* ____pipelineInitializeKeys_6;
// System.Guid[] System.ComponentModel.TypeDescriptor::_pipelineMergeKeys
GuidU5BU5D_t545550574* ____pipelineMergeKeys_7;
// System.Guid[] System.ComponentModel.TypeDescriptor::_pipelineFilterKeys
GuidU5BU5D_t545550574* ____pipelineFilterKeys_8;
// System.Guid[] System.ComponentModel.TypeDescriptor::_pipelineAttributeFilterKeys
GuidU5BU5D_t545550574* ____pipelineAttributeFilterKeys_9;
// System.Object System.ComponentModel.TypeDescriptor::_internalSyncObject
RuntimeObject * ____internalSyncObject_10;
// System.ComponentModel.RefreshEventHandler System.ComponentModel.TypeDescriptor::Refreshed
RefreshEventHandler_t3637242902 * ___Refreshed_11;
public:
inline static int32_t get_offset_of__providerTable_0() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____providerTable_0)); }
inline WeakHashtable_t3533205710 * get__providerTable_0() const { return ____providerTable_0; }
inline WeakHashtable_t3533205710 ** get_address_of__providerTable_0() { return &____providerTable_0; }
inline void set__providerTable_0(WeakHashtable_t3533205710 * value)
{
____providerTable_0 = value;
Il2CppCodeGenWriteBarrier((&____providerTable_0), value);
}
inline static int32_t get_offset_of__providerTypeTable_1() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____providerTypeTable_1)); }
inline Hashtable_t1853889766 * get__providerTypeTable_1() const { return ____providerTypeTable_1; }
inline Hashtable_t1853889766 ** get_address_of__providerTypeTable_1() { return &____providerTypeTable_1; }
inline void set__providerTypeTable_1(Hashtable_t1853889766 * value)
{
____providerTypeTable_1 = value;
Il2CppCodeGenWriteBarrier((&____providerTypeTable_1), value);
}
inline static int32_t get_offset_of__defaultProviders_2() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____defaultProviders_2)); }
inline Hashtable_t1853889766 * get__defaultProviders_2() const { return ____defaultProviders_2; }
inline Hashtable_t1853889766 ** get_address_of__defaultProviders_2() { return &____defaultProviders_2; }
inline void set__defaultProviders_2(Hashtable_t1853889766 * value)
{
____defaultProviders_2 = value;
Il2CppCodeGenWriteBarrier((&____defaultProviders_2), value);
}
inline static int32_t get_offset_of__metadataVersion_3() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____metadataVersion_3)); }
inline int32_t get__metadataVersion_3() const { return ____metadataVersion_3; }
inline int32_t* get_address_of__metadataVersion_3() { return &____metadataVersion_3; }
inline void set__metadataVersion_3(int32_t value)
{
____metadataVersion_3 = value;
}
inline static int32_t get_offset_of__collisionIndex_4() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____collisionIndex_4)); }
inline int32_t get__collisionIndex_4() const { return ____collisionIndex_4; }
inline int32_t* get_address_of__collisionIndex_4() { return &____collisionIndex_4; }
inline void set__collisionIndex_4(int32_t value)
{
____collisionIndex_4 = value;
}
inline static int32_t get_offset_of_TraceDescriptor_5() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ___TraceDescriptor_5)); }
inline BooleanSwitch_t440064918 * get_TraceDescriptor_5() const { return ___TraceDescriptor_5; }
inline BooleanSwitch_t440064918 ** get_address_of_TraceDescriptor_5() { return &___TraceDescriptor_5; }
inline void set_TraceDescriptor_5(BooleanSwitch_t440064918 * value)
{
___TraceDescriptor_5 = value;
Il2CppCodeGenWriteBarrier((&___TraceDescriptor_5), value);
}
inline static int32_t get_offset_of__pipelineInitializeKeys_6() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____pipelineInitializeKeys_6)); }
inline GuidU5BU5D_t545550574* get__pipelineInitializeKeys_6() const { return ____pipelineInitializeKeys_6; }
inline GuidU5BU5D_t545550574** get_address_of__pipelineInitializeKeys_6() { return &____pipelineInitializeKeys_6; }
inline void set__pipelineInitializeKeys_6(GuidU5BU5D_t545550574* value)
{
____pipelineInitializeKeys_6 = value;
Il2CppCodeGenWriteBarrier((&____pipelineInitializeKeys_6), value);
}
inline static int32_t get_offset_of__pipelineMergeKeys_7() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____pipelineMergeKeys_7)); }
inline GuidU5BU5D_t545550574* get__pipelineMergeKeys_7() const { return ____pipelineMergeKeys_7; }
inline GuidU5BU5D_t545550574** get_address_of__pipelineMergeKeys_7() { return &____pipelineMergeKeys_7; }
inline void set__pipelineMergeKeys_7(GuidU5BU5D_t545550574* value)
{
____pipelineMergeKeys_7 = value;
Il2CppCodeGenWriteBarrier((&____pipelineMergeKeys_7), value);
}
inline static int32_t get_offset_of__pipelineFilterKeys_8() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____pipelineFilterKeys_8)); }
inline GuidU5BU5D_t545550574* get__pipelineFilterKeys_8() const { return ____pipelineFilterKeys_8; }
inline GuidU5BU5D_t545550574** get_address_of__pipelineFilterKeys_8() { return &____pipelineFilterKeys_8; }
inline void set__pipelineFilterKeys_8(GuidU5BU5D_t545550574* value)
{
____pipelineFilterKeys_8 = value;
Il2CppCodeGenWriteBarrier((&____pipelineFilterKeys_8), value);
}
inline static int32_t get_offset_of__pipelineAttributeFilterKeys_9() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____pipelineAttributeFilterKeys_9)); }
inline GuidU5BU5D_t545550574* get__pipelineAttributeFilterKeys_9() const { return ____pipelineAttributeFilterKeys_9; }
inline GuidU5BU5D_t545550574** get_address_of__pipelineAttributeFilterKeys_9() { return &____pipelineAttributeFilterKeys_9; }
inline void set__pipelineAttributeFilterKeys_9(GuidU5BU5D_t545550574* value)
{
____pipelineAttributeFilterKeys_9 = value;
Il2CppCodeGenWriteBarrier((&____pipelineAttributeFilterKeys_9), value);
}
inline static int32_t get_offset_of__internalSyncObject_10() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ____internalSyncObject_10)); }
inline RuntimeObject * get__internalSyncObject_10() const { return ____internalSyncObject_10; }
inline RuntimeObject ** get_address_of__internalSyncObject_10() { return &____internalSyncObject_10; }
inline void set__internalSyncObject_10(RuntimeObject * value)
{
____internalSyncObject_10 = value;
Il2CppCodeGenWriteBarrier((&____internalSyncObject_10), value);
}
inline static int32_t get_offset_of_Refreshed_11() { return static_cast<int32_t>(offsetof(TypeDescriptor_t3066613587_StaticFields, ___Refreshed_11)); }
inline RefreshEventHandler_t3637242902 * get_Refreshed_11() const { return ___Refreshed_11; }
inline RefreshEventHandler_t3637242902 ** get_address_of_Refreshed_11() { return &___Refreshed_11; }
inline void set_Refreshed_11(RefreshEventHandler_t3637242902 * value)
{
___Refreshed_11 = value;
Il2CppCodeGenWriteBarrier((&___Refreshed_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPEDESCRIPTOR_T3066613587_H
#ifndef REFLECTEDTYPEDATA_T1775264331_H
#define REFLECTEDTYPEDATA_T1775264331_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData
struct ReflectedTypeData_t1775264331 : public RuntimeObject
{
public:
// System.Type System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_type
Type_t * ____type_0;
// System.ComponentModel.AttributeCollection System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_attributes
AttributeCollection_t4221220734 * ____attributes_1;
// System.ComponentModel.EventDescriptorCollection System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_events
EventDescriptorCollection_t2278158832 * ____events_2;
// System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_properties
PropertyDescriptorCollection_t4164928659 * ____properties_3;
// System.ComponentModel.TypeConverter System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_converter
TypeConverter_t2249118273 * ____converter_4;
// System.Object[] System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_editors
ObjectU5BU5D_t2843939325* ____editors_5;
// System.Type[] System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_editorTypes
TypeU5BU5D_t3940880105* ____editorTypes_6;
// System.Int32 System.ComponentModel.ReflectTypeDescriptionProvider/ReflectedTypeData::_editorCount
int32_t ____editorCount_7;
public:
inline static int32_t get_offset_of__type_0() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____type_0)); }
inline Type_t * get__type_0() const { return ____type_0; }
inline Type_t ** get_address_of__type_0() { return &____type_0; }
inline void set__type_0(Type_t * value)
{
____type_0 = value;
Il2CppCodeGenWriteBarrier((&____type_0), value);
}
inline static int32_t get_offset_of__attributes_1() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____attributes_1)); }
inline AttributeCollection_t4221220734 * get__attributes_1() const { return ____attributes_1; }
inline AttributeCollection_t4221220734 ** get_address_of__attributes_1() { return &____attributes_1; }
inline void set__attributes_1(AttributeCollection_t4221220734 * value)
{
____attributes_1 = value;
Il2CppCodeGenWriteBarrier((&____attributes_1), value);
}
inline static int32_t get_offset_of__events_2() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____events_2)); }
inline EventDescriptorCollection_t2278158832 * get__events_2() const { return ____events_2; }
inline EventDescriptorCollection_t2278158832 ** get_address_of__events_2() { return &____events_2; }
inline void set__events_2(EventDescriptorCollection_t2278158832 * value)
{
____events_2 = value;
Il2CppCodeGenWriteBarrier((&____events_2), value);
}
inline static int32_t get_offset_of__properties_3() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____properties_3)); }
inline PropertyDescriptorCollection_t4164928659 * get__properties_3() const { return ____properties_3; }
inline PropertyDescriptorCollection_t4164928659 ** get_address_of__properties_3() { return &____properties_3; }
inline void set__properties_3(PropertyDescriptorCollection_t4164928659 * value)
{
____properties_3 = value;
Il2CppCodeGenWriteBarrier((&____properties_3), value);
}
inline static int32_t get_offset_of__converter_4() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____converter_4)); }
inline TypeConverter_t2249118273 * get__converter_4() const { return ____converter_4; }
inline TypeConverter_t2249118273 ** get_address_of__converter_4() { return &____converter_4; }
inline void set__converter_4(TypeConverter_t2249118273 * value)
{
____converter_4 = value;
Il2CppCodeGenWriteBarrier((&____converter_4), value);
}
inline static int32_t get_offset_of__editors_5() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____editors_5)); }
inline ObjectU5BU5D_t2843939325* get__editors_5() const { return ____editors_5; }
inline ObjectU5BU5D_t2843939325** get_address_of__editors_5() { return &____editors_5; }
inline void set__editors_5(ObjectU5BU5D_t2843939325* value)
{
____editors_5 = value;
Il2CppCodeGenWriteBarrier((&____editors_5), value);
}
inline static int32_t get_offset_of__editorTypes_6() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____editorTypes_6)); }
inline TypeU5BU5D_t3940880105* get__editorTypes_6() const { return ____editorTypes_6; }
inline TypeU5BU5D_t3940880105** get_address_of__editorTypes_6() { return &____editorTypes_6; }
inline void set__editorTypes_6(TypeU5BU5D_t3940880105* value)
{
____editorTypes_6 = value;
Il2CppCodeGenWriteBarrier((&____editorTypes_6), value);
}
inline static int32_t get_offset_of__editorCount_7() { return static_cast<int32_t>(offsetof(ReflectedTypeData_t1775264331, ____editorCount_7)); }
inline int32_t get__editorCount_7() const { return ____editorCount_7; }
inline int32_t* get_address_of__editorCount_7() { return &____editorCount_7; }
inline void set__editorCount_7(int32_t value)
{
____editorCount_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFLECTEDTYPEDATA_T1775264331_H
#ifndef TYPEDESCRIPTORINTERFACE_T3054885090_H
#define TYPEDESCRIPTORINTERFACE_T3054885090_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/TypeDescriptorInterface
struct TypeDescriptorInterface_t3054885090 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPEDESCRIPTORINTERFACE_T3054885090_H
#ifndef PROPERTYDESCRIPTORENUMERATOR_T2627442857_H
#define PROPERTYDESCRIPTORENUMERATOR_T2627442857_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyDescriptorCollection/PropertyDescriptorEnumerator
struct PropertyDescriptorEnumerator_t2627442857 : public RuntimeObject
{
public:
// System.ComponentModel.PropertyDescriptorCollection System.ComponentModel.PropertyDescriptorCollection/PropertyDescriptorEnumerator::owner
PropertyDescriptorCollection_t4164928659 * ___owner_0;
// System.Int32 System.ComponentModel.PropertyDescriptorCollection/PropertyDescriptorEnumerator::index
int32_t ___index_1;
public:
inline static int32_t get_offset_of_owner_0() { return static_cast<int32_t>(offsetof(PropertyDescriptorEnumerator_t2627442857, ___owner_0)); }
inline PropertyDescriptorCollection_t4164928659 * get_owner_0() const { return ___owner_0; }
inline PropertyDescriptorCollection_t4164928659 ** get_address_of_owner_0() { return &___owner_0; }
inline void set_owner_0(PropertyDescriptorCollection_t4164928659 * value)
{
___owner_0 = value;
Il2CppCodeGenWriteBarrier((&___owner_0), value);
}
inline static int32_t get_offset_of_index_1() { return static_cast<int32_t>(offsetof(PropertyDescriptorEnumerator_t2627442857, ___index_1)); }
inline int32_t get_index_1() const { return ___index_1; }
inline int32_t* get_address_of_index_1() { return &___index_1; }
inline void set_index_1(int32_t value)
{
___index_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYDESCRIPTORENUMERATOR_T2627442857_H
#ifndef TYPEDESCRIPTORCOMOBJECT_T50518439_H
#define TYPEDESCRIPTORCOMOBJECT_T50518439_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/TypeDescriptorComObject
struct TypeDescriptorComObject_t50518439 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPEDESCRIPTORCOMOBJECT_T50518439_H
#ifndef REFERENCECOMPARER_T1826665674_H
#define REFERENCECOMPARER_T1826665674_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ReferenceConverter/ReferenceComparer
struct ReferenceComparer_t1826665674 : public RuntimeObject
{
public:
// System.ComponentModel.ReferenceConverter System.ComponentModel.ReferenceConverter/ReferenceComparer::converter
ReferenceConverter_t1811933861 * ___converter_0;
public:
inline static int32_t get_offset_of_converter_0() { return static_cast<int32_t>(offsetof(ReferenceComparer_t1826665674, ___converter_0)); }
inline ReferenceConverter_t1811933861 * get_converter_0() const { return ___converter_0; }
inline ReferenceConverter_t1811933861 ** get_address_of_converter_0() { return &___converter_0; }
inline void set_converter_0(ReferenceConverter_t1811933861 * value)
{
___converter_0 = value;
Il2CppCodeGenWriteBarrier((&___converter_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFERENCECOMPARER_T1826665674_H
#ifndef CUSTOMTYPEDESCRIPTOR_T3093649079_H
#define CUSTOMTYPEDESCRIPTOR_T3093649079_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.CustomTypeDescriptor
struct CustomTypeDescriptor_t3093649079 : public RuntimeObject
{
public:
// System.ComponentModel.ICustomTypeDescriptor System.ComponentModel.CustomTypeDescriptor::_parent
RuntimeObject* ____parent_0;
public:
inline static int32_t get_offset_of__parent_0() { return static_cast<int32_t>(offsetof(CustomTypeDescriptor_t3093649079, ____parent_0)); }
inline RuntimeObject* get__parent_0() const { return ____parent_0; }
inline RuntimeObject** get_address_of__parent_0() { return &____parent_0; }
inline void set__parent_0(RuntimeObject* value)
{
____parent_0 = value;
Il2CppCodeGenWriteBarrier((&____parent_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CUSTOMTYPEDESCRIPTOR_T3093649079_H
#ifndef EVENTDESCRIPTORCOLLECTION_T2278158832_H
#define EVENTDESCRIPTORCOLLECTION_T2278158832_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EventDescriptorCollection
struct EventDescriptorCollection_t2278158832 : public RuntimeObject
{
public:
// System.ComponentModel.EventDescriptor[] System.ComponentModel.EventDescriptorCollection::events
EventDescriptorU5BU5D_t1482016031* ___events_0;
// System.String[] System.ComponentModel.EventDescriptorCollection::namedSort
StringU5BU5D_t1281789340* ___namedSort_1;
// System.Collections.IComparer System.ComponentModel.EventDescriptorCollection::comparer
RuntimeObject* ___comparer_2;
// System.Boolean System.ComponentModel.EventDescriptorCollection::eventsOwned
bool ___eventsOwned_3;
// System.Boolean System.ComponentModel.EventDescriptorCollection::needSort
bool ___needSort_4;
// System.Int32 System.ComponentModel.EventDescriptorCollection::eventCount
int32_t ___eventCount_5;
// System.Boolean System.ComponentModel.EventDescriptorCollection::readOnly
bool ___readOnly_6;
public:
inline static int32_t get_offset_of_events_0() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___events_0)); }
inline EventDescriptorU5BU5D_t1482016031* get_events_0() const { return ___events_0; }
inline EventDescriptorU5BU5D_t1482016031** get_address_of_events_0() { return &___events_0; }
inline void set_events_0(EventDescriptorU5BU5D_t1482016031* value)
{
___events_0 = value;
Il2CppCodeGenWriteBarrier((&___events_0), value);
}
inline static int32_t get_offset_of_namedSort_1() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___namedSort_1)); }
inline StringU5BU5D_t1281789340* get_namedSort_1() const { return ___namedSort_1; }
inline StringU5BU5D_t1281789340** get_address_of_namedSort_1() { return &___namedSort_1; }
inline void set_namedSort_1(StringU5BU5D_t1281789340* value)
{
___namedSort_1 = value;
Il2CppCodeGenWriteBarrier((&___namedSort_1), value);
}
inline static int32_t get_offset_of_comparer_2() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___comparer_2)); }
inline RuntimeObject* get_comparer_2() const { return ___comparer_2; }
inline RuntimeObject** get_address_of_comparer_2() { return &___comparer_2; }
inline void set_comparer_2(RuntimeObject* value)
{
___comparer_2 = value;
Il2CppCodeGenWriteBarrier((&___comparer_2), value);
}
inline static int32_t get_offset_of_eventsOwned_3() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___eventsOwned_3)); }
inline bool get_eventsOwned_3() const { return ___eventsOwned_3; }
inline bool* get_address_of_eventsOwned_3() { return &___eventsOwned_3; }
inline void set_eventsOwned_3(bool value)
{
___eventsOwned_3 = value;
}
inline static int32_t get_offset_of_needSort_4() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___needSort_4)); }
inline bool get_needSort_4() const { return ___needSort_4; }
inline bool* get_address_of_needSort_4() { return &___needSort_4; }
inline void set_needSort_4(bool value)
{
___needSort_4 = value;
}
inline static int32_t get_offset_of_eventCount_5() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___eventCount_5)); }
inline int32_t get_eventCount_5() const { return ___eventCount_5; }
inline int32_t* get_address_of_eventCount_5() { return &___eventCount_5; }
inline void set_eventCount_5(int32_t value)
{
___eventCount_5 = value;
}
inline static int32_t get_offset_of_readOnly_6() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832, ___readOnly_6)); }
inline bool get_readOnly_6() const { return ___readOnly_6; }
inline bool* get_address_of_readOnly_6() { return &___readOnly_6; }
inline void set_readOnly_6(bool value)
{
___readOnly_6 = value;
}
};
struct EventDescriptorCollection_t2278158832_StaticFields
{
public:
// System.ComponentModel.EventDescriptorCollection System.ComponentModel.EventDescriptorCollection::Empty
EventDescriptorCollection_t2278158832 * ___Empty_7;
public:
inline static int32_t get_offset_of_Empty_7() { return static_cast<int32_t>(offsetof(EventDescriptorCollection_t2278158832_StaticFields, ___Empty_7)); }
inline EventDescriptorCollection_t2278158832 * get_Empty_7() const { return ___Empty_7; }
inline EventDescriptorCollection_t2278158832 ** get_address_of_Empty_7() { return &___Empty_7; }
inline void set_Empty_7(EventDescriptorCollection_t2278158832 * value)
{
___Empty_7 = value;
Il2CppCodeGenWriteBarrier((&___Empty_7), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EVENTDESCRIPTORCOLLECTION_T2278158832_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef MERGEDTYPEDESCRIPTOR_T3526482283_H
#define MERGEDTYPEDESCRIPTOR_T3526482283_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/MergedTypeDescriptor
struct MergedTypeDescriptor_t3526482283 : public RuntimeObject
{
public:
// System.ComponentModel.ICustomTypeDescriptor System.ComponentModel.TypeDescriptor/MergedTypeDescriptor::_primary
RuntimeObject* ____primary_0;
// System.ComponentModel.ICustomTypeDescriptor System.ComponentModel.TypeDescriptor/MergedTypeDescriptor::_secondary
RuntimeObject* ____secondary_1;
public:
inline static int32_t get_offset_of__primary_0() { return static_cast<int32_t>(offsetof(MergedTypeDescriptor_t3526482283, ____primary_0)); }
inline RuntimeObject* get__primary_0() const { return ____primary_0; }
inline RuntimeObject** get_address_of__primary_0() { return &____primary_0; }
inline void set__primary_0(RuntimeObject* value)
{
____primary_0 = value;
Il2CppCodeGenWriteBarrier((&____primary_0), value);
}
inline static int32_t get_offset_of__secondary_1() { return static_cast<int32_t>(offsetof(MergedTypeDescriptor_t3526482283, ____secondary_1)); }
inline RuntimeObject* get__secondary_1() const { return ____secondary_1; }
inline RuntimeObject** get_address_of__secondary_1() { return &____secondary_1; }
inline void set__secondary_1(RuntimeObject* value)
{
____secondary_1 = value;
Il2CppCodeGenWriteBarrier((&____secondary_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MERGEDTYPEDESCRIPTOR_T3526482283_H
#ifndef EXCEPTION_T_H
#define EXCEPTION_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Exception
struct Exception_t : public RuntimeObject
{
public:
// System.String System.Exception::_className
String_t* ____className_1;
// System.String System.Exception::_message
String_t* ____message_2;
// System.Collections.IDictionary System.Exception::_data
RuntimeObject* ____data_3;
// System.Exception System.Exception::_innerException
Exception_t * ____innerException_4;
// System.String System.Exception::_helpURL
String_t* ____helpURL_5;
// System.Object System.Exception::_stackTrace
RuntimeObject * ____stackTrace_6;
// System.String System.Exception::_stackTraceString
String_t* ____stackTraceString_7;
// System.String System.Exception::_remoteStackTraceString
String_t* ____remoteStackTraceString_8;
// System.Int32 System.Exception::_remoteStackIndex
int32_t ____remoteStackIndex_9;
// System.Object System.Exception::_dynamicMethods
RuntimeObject * ____dynamicMethods_10;
// System.Int32 System.Exception::_HResult
int32_t ____HResult_11;
// System.String System.Exception::_source
String_t* ____source_12;
// System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager
SafeSerializationManager_t2481557153 * ____safeSerializationManager_13;
// System.Diagnostics.StackTrace[] System.Exception::captured_traces
StackTraceU5BU5D_t1169129676* ___captured_traces_14;
// System.IntPtr[] System.Exception::native_trace_ips
IntPtrU5BU5D_t4013366056* ___native_trace_ips_15;
public:
inline static int32_t get_offset_of__className_1() { return static_cast<int32_t>(offsetof(Exception_t, ____className_1)); }
inline String_t* get__className_1() const { return ____className_1; }
inline String_t** get_address_of__className_1() { return &____className_1; }
inline void set__className_1(String_t* value)
{
____className_1 = value;
Il2CppCodeGenWriteBarrier((&____className_1), value);
}
inline static int32_t get_offset_of__message_2() { return static_cast<int32_t>(offsetof(Exception_t, ____message_2)); }
inline String_t* get__message_2() const { return ____message_2; }
inline String_t** get_address_of__message_2() { return &____message_2; }
inline void set__message_2(String_t* value)
{
____message_2 = value;
Il2CppCodeGenWriteBarrier((&____message_2), value);
}
inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(Exception_t, ____data_3)); }
inline RuntimeObject* get__data_3() const { return ____data_3; }
inline RuntimeObject** get_address_of__data_3() { return &____data_3; }
inline void set__data_3(RuntimeObject* value)
{
____data_3 = value;
Il2CppCodeGenWriteBarrier((&____data_3), value);
}
inline static int32_t get_offset_of__innerException_4() { return static_cast<int32_t>(offsetof(Exception_t, ____innerException_4)); }
inline Exception_t * get__innerException_4() const { return ____innerException_4; }
inline Exception_t ** get_address_of__innerException_4() { return &____innerException_4; }
inline void set__innerException_4(Exception_t * value)
{
____innerException_4 = value;
Il2CppCodeGenWriteBarrier((&____innerException_4), value);
}
inline static int32_t get_offset_of__helpURL_5() { return static_cast<int32_t>(offsetof(Exception_t, ____helpURL_5)); }
inline String_t* get__helpURL_5() const { return ____helpURL_5; }
inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; }
inline void set__helpURL_5(String_t* value)
{
____helpURL_5 = value;
Il2CppCodeGenWriteBarrier((&____helpURL_5), value);
}
inline static int32_t get_offset_of__stackTrace_6() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTrace_6)); }
inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; }
inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; }
inline void set__stackTrace_6(RuntimeObject * value)
{
____stackTrace_6 = value;
Il2CppCodeGenWriteBarrier((&____stackTrace_6), value);
}
inline static int32_t get_offset_of__stackTraceString_7() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTraceString_7)); }
inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; }
inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; }
inline void set__stackTraceString_7(String_t* value)
{
____stackTraceString_7 = value;
Il2CppCodeGenWriteBarrier((&____stackTraceString_7), value);
}
inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_8)); }
inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; }
inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; }
inline void set__remoteStackTraceString_8(String_t* value)
{
____remoteStackTraceString_8 = value;
Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_8), value);
}
inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackIndex_9)); }
inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; }
inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; }
inline void set__remoteStackIndex_9(int32_t value)
{
____remoteStackIndex_9 = value;
}
inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast<int32_t>(offsetof(Exception_t, ____dynamicMethods_10)); }
inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; }
inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; }
inline void set__dynamicMethods_10(RuntimeObject * value)
{
____dynamicMethods_10 = value;
Il2CppCodeGenWriteBarrier((&____dynamicMethods_10), value);
}
inline static int32_t get_offset_of__HResult_11() { return static_cast<int32_t>(offsetof(Exception_t, ____HResult_11)); }
inline int32_t get__HResult_11() const { return ____HResult_11; }
inline int32_t* get_address_of__HResult_11() { return &____HResult_11; }
inline void set__HResult_11(int32_t value)
{
____HResult_11 = value;
}
inline static int32_t get_offset_of__source_12() { return static_cast<int32_t>(offsetof(Exception_t, ____source_12)); }
inline String_t* get__source_12() const { return ____source_12; }
inline String_t** get_address_of__source_12() { return &____source_12; }
inline void set__source_12(String_t* value)
{
____source_12 = value;
Il2CppCodeGenWriteBarrier((&____source_12), value);
}
inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast<int32_t>(offsetof(Exception_t, ____safeSerializationManager_13)); }
inline SafeSerializationManager_t2481557153 * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; }
inline SafeSerializationManager_t2481557153 ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; }
inline void set__safeSerializationManager_13(SafeSerializationManager_t2481557153 * value)
{
____safeSerializationManager_13 = value;
Il2CppCodeGenWriteBarrier((&____safeSerializationManager_13), value);
}
inline static int32_t get_offset_of_captured_traces_14() { return static_cast<int32_t>(offsetof(Exception_t, ___captured_traces_14)); }
inline StackTraceU5BU5D_t1169129676* get_captured_traces_14() const { return ___captured_traces_14; }
inline StackTraceU5BU5D_t1169129676** get_address_of_captured_traces_14() { return &___captured_traces_14; }
inline void set_captured_traces_14(StackTraceU5BU5D_t1169129676* value)
{
___captured_traces_14 = value;
Il2CppCodeGenWriteBarrier((&___captured_traces_14), value);
}
inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast<int32_t>(offsetof(Exception_t, ___native_trace_ips_15)); }
inline IntPtrU5BU5D_t4013366056* get_native_trace_ips_15() const { return ___native_trace_ips_15; }
inline IntPtrU5BU5D_t4013366056** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; }
inline void set_native_trace_ips_15(IntPtrU5BU5D_t4013366056* value)
{
___native_trace_ips_15 = value;
Il2CppCodeGenWriteBarrier((&___native_trace_ips_15), value);
}
};
struct Exception_t_StaticFields
{
public:
// System.Object System.Exception::s_EDILock
RuntimeObject * ___s_EDILock_0;
public:
inline static int32_t get_offset_of_s_EDILock_0() { return static_cast<int32_t>(offsetof(Exception_t_StaticFields, ___s_EDILock_0)); }
inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; }
inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; }
inline void set_s_EDILock_0(RuntimeObject * value)
{
___s_EDILock_0 = value;
Il2CppCodeGenWriteBarrier((&___s_EDILock_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Exception
struct Exception_t_marshaled_pinvoke
{
char* ____className_1;
char* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_pinvoke* ____innerException_4;
char* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
char* ____stackTraceString_7;
char* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
char* ____source_12;
SafeSerializationManager_t2481557153 * ____safeSerializationManager_13;
StackTraceU5BU5D_t1169129676* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
// Native definition for COM marshalling of System.Exception
struct Exception_t_marshaled_com
{
Il2CppChar* ____className_1;
Il2CppChar* ____message_2;
RuntimeObject* ____data_3;
Exception_t_marshaled_com* ____innerException_4;
Il2CppChar* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
Il2CppChar* ____stackTraceString_7;
Il2CppChar* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
Il2CppChar* ____source_12;
SafeSerializationManager_t2481557153 * ____safeSerializationManager_13;
StackTraceU5BU5D_t1169129676* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
#endif // EXCEPTION_T_H
#ifndef EVENTHANDLERLIST_T1108123056_H
#define EVENTHANDLERLIST_T1108123056_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EventHandlerList
struct EventHandlerList_t1108123056 : public RuntimeObject
{
public:
// System.ComponentModel.EventHandlerList/ListEntry System.ComponentModel.EventHandlerList::head
ListEntry_t2424989506 * ___head_0;
// System.ComponentModel.Component System.ComponentModel.EventHandlerList::parent
Component_t3620823400 * ___parent_1;
public:
inline static int32_t get_offset_of_head_0() { return static_cast<int32_t>(offsetof(EventHandlerList_t1108123056, ___head_0)); }
inline ListEntry_t2424989506 * get_head_0() const { return ___head_0; }
inline ListEntry_t2424989506 ** get_address_of_head_0() { return &___head_0; }
inline void set_head_0(ListEntry_t2424989506 * value)
{
___head_0 = value;
Il2CppCodeGenWriteBarrier((&___head_0), value);
}
inline static int32_t get_offset_of_parent_1() { return static_cast<int32_t>(offsetof(EventHandlerList_t1108123056, ___parent_1)); }
inline Component_t3620823400 * get_parent_1() const { return ___parent_1; }
inline Component_t3620823400 ** get_address_of_parent_1() { return &___parent_1; }
inline void set_parent_1(Component_t3620823400 * value)
{
___parent_1 = value;
Il2CppCodeGenWriteBarrier((&___parent_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EVENTHANDLERLIST_T1108123056_H
#ifndef ATTRIBUTE_T861562559_H
#define ATTRIBUTE_T861562559_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Attribute
struct Attribute_t861562559 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ATTRIBUTE_T861562559_H
#ifndef EVENTARGS_T3591816995_H
#define EVENTARGS_T3591816995_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.EventArgs
struct EventArgs_t3591816995 : public RuntimeObject
{
public:
public:
};
struct EventArgs_t3591816995_StaticFields
{
public:
// System.EventArgs System.EventArgs::Empty
EventArgs_t3591816995 * ___Empty_0;
public:
inline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(EventArgs_t3591816995_StaticFields, ___Empty_0)); }
inline EventArgs_t3591816995 * get_Empty_0() const { return ___Empty_0; }
inline EventArgs_t3591816995 ** get_address_of_Empty_0() { return &___Empty_0; }
inline void set_Empty_0(EventArgs_t3591816995 * value)
{
___Empty_0 = value;
Il2CppCodeGenWriteBarrier((&___Empty_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EVENTARGS_T3591816995_H
#ifndef ASNENCODEDDATA_T382354011_H
#define ASNENCODEDDATA_T382354011_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AsnEncodedData
struct AsnEncodedData_t382354011 : public RuntimeObject
{
public:
// System.Security.Cryptography.Oid System.Security.Cryptography.AsnEncodedData::_oid
Oid_t3552120260 * ____oid_0;
// System.Byte[] System.Security.Cryptography.AsnEncodedData::_raw
ByteU5BU5D_t4116647657* ____raw_1;
public:
inline static int32_t get_offset_of__oid_0() { return static_cast<int32_t>(offsetof(AsnEncodedData_t382354011, ____oid_0)); }
inline Oid_t3552120260 * get__oid_0() const { return ____oid_0; }
inline Oid_t3552120260 ** get_address_of__oid_0() { return &____oid_0; }
inline void set__oid_0(Oid_t3552120260 * value)
{
____oid_0 = value;
Il2CppCodeGenWriteBarrier((&____oid_0), value);
}
inline static int32_t get_offset_of__raw_1() { return static_cast<int32_t>(offsetof(AsnEncodedData_t382354011, ____raw_1)); }
inline ByteU5BU5D_t4116647657* get__raw_1() const { return ____raw_1; }
inline ByteU5BU5D_t4116647657** get_address_of__raw_1() { return &____raw_1; }
inline void set__raw_1(ByteU5BU5D_t4116647657* value)
{
____raw_1 = value;
Il2CppCodeGenWriteBarrier((&____raw_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ASNENCODEDDATA_T382354011_H
#ifndef LISTENTRY_T2424989506_H
#define LISTENTRY_T2424989506_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EventHandlerList/ListEntry
struct ListEntry_t2424989506 : public RuntimeObject
{
public:
// System.ComponentModel.EventHandlerList/ListEntry System.ComponentModel.EventHandlerList/ListEntry::next
ListEntry_t2424989506 * ___next_0;
// System.Object System.ComponentModel.EventHandlerList/ListEntry::key
RuntimeObject * ___key_1;
// System.Delegate System.ComponentModel.EventHandlerList/ListEntry::handler
Delegate_t1188392813 * ___handler_2;
public:
inline static int32_t get_offset_of_next_0() { return static_cast<int32_t>(offsetof(ListEntry_t2424989506, ___next_0)); }
inline ListEntry_t2424989506 * get_next_0() const { return ___next_0; }
inline ListEntry_t2424989506 ** get_address_of_next_0() { return &___next_0; }
inline void set_next_0(ListEntry_t2424989506 * value)
{
___next_0 = value;
Il2CppCodeGenWriteBarrier((&___next_0), value);
}
inline static int32_t get_offset_of_key_1() { return static_cast<int32_t>(offsetof(ListEntry_t2424989506, ___key_1)); }
inline RuntimeObject * get_key_1() const { return ___key_1; }
inline RuntimeObject ** get_address_of_key_1() { return &___key_1; }
inline void set_key_1(RuntimeObject * value)
{
___key_1 = value;
Il2CppCodeGenWriteBarrier((&___key_1), value);
}
inline static int32_t get_offset_of_handler_2() { return static_cast<int32_t>(offsetof(ListEntry_t2424989506, ___handler_2)); }
inline Delegate_t1188392813 * get_handler_2() const { return ___handler_2; }
inline Delegate_t1188392813 ** get_address_of_handler_2() { return &___handler_2; }
inline void set_handler_2(Delegate_t1188392813 * value)
{
___handler_2 = value;
Il2CppCodeGenWriteBarrier((&___handler_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LISTENTRY_T2424989506_H
#ifndef TYPEDESCRIPTIONNODE_T3022060204_H
#define TYPEDESCRIPTIONNODE_T3022060204_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode
struct TypeDescriptionNode_t3022060204 : public TypeDescriptionProvider_t3232077895
{
public:
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode System.ComponentModel.TypeDescriptor/TypeDescriptionNode::Next
TypeDescriptionNode_t3022060204 * ___Next_2;
// System.ComponentModel.TypeDescriptionProvider System.ComponentModel.TypeDescriptor/TypeDescriptionNode::Provider
TypeDescriptionProvider_t3232077895 * ___Provider_3;
public:
inline static int32_t get_offset_of_Next_2() { return static_cast<int32_t>(offsetof(TypeDescriptionNode_t3022060204, ___Next_2)); }
inline TypeDescriptionNode_t3022060204 * get_Next_2() const { return ___Next_2; }
inline TypeDescriptionNode_t3022060204 ** get_address_of_Next_2() { return &___Next_2; }
inline void set_Next_2(TypeDescriptionNode_t3022060204 * value)
{
___Next_2 = value;
Il2CppCodeGenWriteBarrier((&___Next_2), value);
}
inline static int32_t get_offset_of_Provider_3() { return static_cast<int32_t>(offsetof(TypeDescriptionNode_t3022060204, ___Provider_3)); }
inline TypeDescriptionProvider_t3232077895 * get_Provider_3() const { return ___Provider_3; }
inline TypeDescriptionProvider_t3232077895 ** get_address_of_Provider_3() { return &___Provider_3; }
inline void set_Provider_3(TypeDescriptionProvider_t3232077895 * value)
{
___Provider_3 = value;
Il2CppCodeGenWriteBarrier((&___Provider_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPEDESCRIPTIONNODE_T3022060204_H
#ifndef DESIGNERATTRIBUTE_T2079716647_H
#define DESIGNERATTRIBUTE_T2079716647_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerAttribute
struct DesignerAttribute_t2079716647 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.DesignerAttribute::designerTypeName
String_t* ___designerTypeName_0;
// System.String System.ComponentModel.DesignerAttribute::designerBaseTypeName
String_t* ___designerBaseTypeName_1;
// System.String System.ComponentModel.DesignerAttribute::typeId
String_t* ___typeId_2;
public:
inline static int32_t get_offset_of_designerTypeName_0() { return static_cast<int32_t>(offsetof(DesignerAttribute_t2079716647, ___designerTypeName_0)); }
inline String_t* get_designerTypeName_0() const { return ___designerTypeName_0; }
inline String_t** get_address_of_designerTypeName_0() { return &___designerTypeName_0; }
inline void set_designerTypeName_0(String_t* value)
{
___designerTypeName_0 = value;
Il2CppCodeGenWriteBarrier((&___designerTypeName_0), value);
}
inline static int32_t get_offset_of_designerBaseTypeName_1() { return static_cast<int32_t>(offsetof(DesignerAttribute_t2079716647, ___designerBaseTypeName_1)); }
inline String_t* get_designerBaseTypeName_1() const { return ___designerBaseTypeName_1; }
inline String_t** get_address_of_designerBaseTypeName_1() { return &___designerBaseTypeName_1; }
inline void set_designerBaseTypeName_1(String_t* value)
{
___designerBaseTypeName_1 = value;
Il2CppCodeGenWriteBarrier((&___designerBaseTypeName_1), value);
}
inline static int32_t get_offset_of_typeId_2() { return static_cast<int32_t>(offsetof(DesignerAttribute_t2079716647, ___typeId_2)); }
inline String_t* get_typeId_2() const { return ___typeId_2; }
inline String_t** get_address_of_typeId_2() { return &___typeId_2; }
inline void set_typeId_2(String_t* value)
{
___typeId_2 = value;
Il2CppCodeGenWriteBarrier((&___typeId_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERATTRIBUTE_T2079716647_H
#ifndef INT32_T2950945753_H
#define INT32_T2950945753_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t2950945753
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_0)); }
inline int32_t get_m_value_0() const { return ___m_value_0; }
inline int32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int32_t value)
{
___m_value_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T2950945753_H
#ifndef EMPTYCUSTOMTYPEDESCRIPTOR_T4007109994_H
#define EMPTYCUSTOMTYPEDESCRIPTOR_T4007109994_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptionProvider/EmptyCustomTypeDescriptor
struct EmptyCustomTypeDescriptor_t4007109994 : public CustomTypeDescriptor_t3093649079
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EMPTYCUSTOMTYPEDESCRIPTOR_T4007109994_H
#ifndef ROOTDESIGNERSERIALIZERATTRIBUTE_T3074689342_H
#define ROOTDESIGNERSERIALIZERATTRIBUTE_T3074689342_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute
struct RootDesignerSerializerAttribute_t3074689342 : public Attribute_t861562559
{
public:
// System.Boolean System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::reloadable
bool ___reloadable_0;
// System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::serializerTypeName
String_t* ___serializerTypeName_1;
// System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::serializerBaseTypeName
String_t* ___serializerBaseTypeName_2;
// System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::typeId
String_t* ___typeId_3;
public:
inline static int32_t get_offset_of_reloadable_0() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___reloadable_0)); }
inline bool get_reloadable_0() const { return ___reloadable_0; }
inline bool* get_address_of_reloadable_0() { return &___reloadable_0; }
inline void set_reloadable_0(bool value)
{
___reloadable_0 = value;
}
inline static int32_t get_offset_of_serializerTypeName_1() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___serializerTypeName_1)); }
inline String_t* get_serializerTypeName_1() const { return ___serializerTypeName_1; }
inline String_t** get_address_of_serializerTypeName_1() { return &___serializerTypeName_1; }
inline void set_serializerTypeName_1(String_t* value)
{
___serializerTypeName_1 = value;
Il2CppCodeGenWriteBarrier((&___serializerTypeName_1), value);
}
inline static int32_t get_offset_of_serializerBaseTypeName_2() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___serializerBaseTypeName_2)); }
inline String_t* get_serializerBaseTypeName_2() const { return ___serializerBaseTypeName_2; }
inline String_t** get_address_of_serializerBaseTypeName_2() { return &___serializerBaseTypeName_2; }
inline void set_serializerBaseTypeName_2(String_t* value)
{
___serializerBaseTypeName_2 = value;
Il2CppCodeGenWriteBarrier((&___serializerBaseTypeName_2), value);
}
inline static int32_t get_offset_of_typeId_3() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___typeId_3)); }
inline String_t* get_typeId_3() const { return ___typeId_3; }
inline String_t** get_address_of_typeId_3() { return &___typeId_3; }
inline void set_typeId_3(String_t* value)
{
___typeId_3 = value;
Il2CppCodeGenWriteBarrier((&___typeId_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ROOTDESIGNERSERIALIZERATTRIBUTE_T3074689342_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef TYPEDESCRIPTIONPROVIDERATTRIBUTE_T2619663527_H
#define TYPEDESCRIPTIONPROVIDERATTRIBUTE_T2619663527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptionProviderAttribute
struct TypeDescriptionProviderAttribute_t2619663527 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.TypeDescriptionProviderAttribute::_typeName
String_t* ____typeName_0;
public:
inline static int32_t get_offset_of__typeName_0() { return static_cast<int32_t>(offsetof(TypeDescriptionProviderAttribute_t2619663527, ____typeName_0)); }
inline String_t* get__typeName_0() const { return ____typeName_0; }
inline String_t** get_address_of__typeName_0() { return &____typeName_0; }
inline void set__typeName_0(String_t* value)
{
____typeName_0 = value;
Il2CppCodeGenWriteBarrier((&____typeName_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPEDESCRIPTIONPROVIDERATTRIBUTE_T2619663527_H
#ifndef DEFAULTEXTENDEDTYPEDESCRIPTOR_T1757997412_H
#define DEFAULTEXTENDEDTYPEDESCRIPTOR_T1757997412_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultExtendedTypeDescriptor
struct DefaultExtendedTypeDescriptor_t1757997412
{
public:
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultExtendedTypeDescriptor::_node
TypeDescriptionNode_t3022060204 * ____node_0;
// System.Object System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultExtendedTypeDescriptor::_instance
RuntimeObject * ____instance_1;
public:
inline static int32_t get_offset_of__node_0() { return static_cast<int32_t>(offsetof(DefaultExtendedTypeDescriptor_t1757997412, ____node_0)); }
inline TypeDescriptionNode_t3022060204 * get__node_0() const { return ____node_0; }
inline TypeDescriptionNode_t3022060204 ** get_address_of__node_0() { return &____node_0; }
inline void set__node_0(TypeDescriptionNode_t3022060204 * value)
{
____node_0 = value;
Il2CppCodeGenWriteBarrier((&____node_0), value);
}
inline static int32_t get_offset_of__instance_1() { return static_cast<int32_t>(offsetof(DefaultExtendedTypeDescriptor_t1757997412, ____instance_1)); }
inline RuntimeObject * get__instance_1() const { return ____instance_1; }
inline RuntimeObject ** get_address_of__instance_1() { return &____instance_1; }
inline void set__instance_1(RuntimeObject * value)
{
____instance_1 = value;
Il2CppCodeGenWriteBarrier((&____instance_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultExtendedTypeDescriptor
struct DefaultExtendedTypeDescriptor_t1757997412_marshaled_pinvoke
{
TypeDescriptionNode_t3022060204 * ____node_0;
Il2CppIUnknown* ____instance_1;
};
// Native definition for COM marshalling of System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultExtendedTypeDescriptor
struct DefaultExtendedTypeDescriptor_t1757997412_marshaled_com
{
TypeDescriptionNode_t3022060204 * ____node_0;
Il2CppIUnknown* ____instance_1;
};
#endif // DEFAULTEXTENDEDTYPEDESCRIPTOR_T1757997412_H
#ifndef GUID_T_H
#define GUID_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Guid
struct Guid_t
{
public:
// System.Int32 System.Guid::_a
int32_t ____a_1;
// System.Int16 System.Guid::_b
int16_t ____b_2;
// System.Int16 System.Guid::_c
int16_t ____c_3;
// System.Byte System.Guid::_d
uint8_t ____d_4;
// System.Byte System.Guid::_e
uint8_t ____e_5;
// System.Byte System.Guid::_f
uint8_t ____f_6;
// System.Byte System.Guid::_g
uint8_t ____g_7;
// System.Byte System.Guid::_h
uint8_t ____h_8;
// System.Byte System.Guid::_i
uint8_t ____i_9;
// System.Byte System.Guid::_j
uint8_t ____j_10;
// System.Byte System.Guid::_k
uint8_t ____k_11;
public:
inline static int32_t get_offset_of__a_1() { return static_cast<int32_t>(offsetof(Guid_t, ____a_1)); }
inline int32_t get__a_1() const { return ____a_1; }
inline int32_t* get_address_of__a_1() { return &____a_1; }
inline void set__a_1(int32_t value)
{
____a_1 = value;
}
inline static int32_t get_offset_of__b_2() { return static_cast<int32_t>(offsetof(Guid_t, ____b_2)); }
inline int16_t get__b_2() const { return ____b_2; }
inline int16_t* get_address_of__b_2() { return &____b_2; }
inline void set__b_2(int16_t value)
{
____b_2 = value;
}
inline static int32_t get_offset_of__c_3() { return static_cast<int32_t>(offsetof(Guid_t, ____c_3)); }
inline int16_t get__c_3() const { return ____c_3; }
inline int16_t* get_address_of__c_3() { return &____c_3; }
inline void set__c_3(int16_t value)
{
____c_3 = value;
}
inline static int32_t get_offset_of__d_4() { return static_cast<int32_t>(offsetof(Guid_t, ____d_4)); }
inline uint8_t get__d_4() const { return ____d_4; }
inline uint8_t* get_address_of__d_4() { return &____d_4; }
inline void set__d_4(uint8_t value)
{
____d_4 = value;
}
inline static int32_t get_offset_of__e_5() { return static_cast<int32_t>(offsetof(Guid_t, ____e_5)); }
inline uint8_t get__e_5() const { return ____e_5; }
inline uint8_t* get_address_of__e_5() { return &____e_5; }
inline void set__e_5(uint8_t value)
{
____e_5 = value;
}
inline static int32_t get_offset_of__f_6() { return static_cast<int32_t>(offsetof(Guid_t, ____f_6)); }
inline uint8_t get__f_6() const { return ____f_6; }
inline uint8_t* get_address_of__f_6() { return &____f_6; }
inline void set__f_6(uint8_t value)
{
____f_6 = value;
}
inline static int32_t get_offset_of__g_7() { return static_cast<int32_t>(offsetof(Guid_t, ____g_7)); }
inline uint8_t get__g_7() const { return ____g_7; }
inline uint8_t* get_address_of__g_7() { return &____g_7; }
inline void set__g_7(uint8_t value)
{
____g_7 = value;
}
inline static int32_t get_offset_of__h_8() { return static_cast<int32_t>(offsetof(Guid_t, ____h_8)); }
inline uint8_t get__h_8() const { return ____h_8; }
inline uint8_t* get_address_of__h_8() { return &____h_8; }
inline void set__h_8(uint8_t value)
{
____h_8 = value;
}
inline static int32_t get_offset_of__i_9() { return static_cast<int32_t>(offsetof(Guid_t, ____i_9)); }
inline uint8_t get__i_9() const { return ____i_9; }
inline uint8_t* get_address_of__i_9() { return &____i_9; }
inline void set__i_9(uint8_t value)
{
____i_9 = value;
}
inline static int32_t get_offset_of__j_10() { return static_cast<int32_t>(offsetof(Guid_t, ____j_10)); }
inline uint8_t get__j_10() const { return ____j_10; }
inline uint8_t* get_address_of__j_10() { return &____j_10; }
inline void set__j_10(uint8_t value)
{
____j_10 = value;
}
inline static int32_t get_offset_of__k_11() { return static_cast<int32_t>(offsetof(Guid_t, ____k_11)); }
inline uint8_t get__k_11() const { return ____k_11; }
inline uint8_t* get_address_of__k_11() { return &____k_11; }
inline void set__k_11(uint8_t value)
{
____k_11 = value;
}
};
struct Guid_t_StaticFields
{
public:
// System.Guid System.Guid::Empty
Guid_t ___Empty_0;
// System.Object System.Guid::_rngAccess
RuntimeObject * ____rngAccess_12;
// System.Security.Cryptography.RandomNumberGenerator System.Guid::_rng
RandomNumberGenerator_t386037858 * ____rng_13;
// System.Security.Cryptography.RandomNumberGenerator System.Guid::_fastRng
RandomNumberGenerator_t386037858 * ____fastRng_14;
public:
inline static int32_t get_offset_of_Empty_0() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ___Empty_0)); }
inline Guid_t get_Empty_0() const { return ___Empty_0; }
inline Guid_t * get_address_of_Empty_0() { return &___Empty_0; }
inline void set_Empty_0(Guid_t value)
{
___Empty_0 = value;
}
inline static int32_t get_offset_of__rngAccess_12() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____rngAccess_12)); }
inline RuntimeObject * get__rngAccess_12() const { return ____rngAccess_12; }
inline RuntimeObject ** get_address_of__rngAccess_12() { return &____rngAccess_12; }
inline void set__rngAccess_12(RuntimeObject * value)
{
____rngAccess_12 = value;
Il2CppCodeGenWriteBarrier((&____rngAccess_12), value);
}
inline static int32_t get_offset_of__rng_13() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____rng_13)); }
inline RandomNumberGenerator_t386037858 * get__rng_13() const { return ____rng_13; }
inline RandomNumberGenerator_t386037858 ** get_address_of__rng_13() { return &____rng_13; }
inline void set__rng_13(RandomNumberGenerator_t386037858 * value)
{
____rng_13 = value;
Il2CppCodeGenWriteBarrier((&____rng_13), value);
}
inline static int32_t get_offset_of__fastRng_14() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____fastRng_14)); }
inline RandomNumberGenerator_t386037858 * get__fastRng_14() const { return ____fastRng_14; }
inline RandomNumberGenerator_t386037858 ** get_address_of__fastRng_14() { return &____fastRng_14; }
inline void set__fastRng_14(RandomNumberGenerator_t386037858 * value)
{
____fastRng_14 = value;
Il2CppCodeGenWriteBarrier((&____fastRng_14), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GUID_T_H
#ifndef TOOLBOXITEMATTRIBUTE_T243705872_H
#define TOOLBOXITEMATTRIBUTE_T243705872_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ToolboxItemAttribute
struct ToolboxItemAttribute_t243705872 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.ToolboxItemAttribute::toolboxItemTypeName
String_t* ___toolboxItemTypeName_0;
public:
inline static int32_t get_offset_of_toolboxItemTypeName_0() { return static_cast<int32_t>(offsetof(ToolboxItemAttribute_t243705872, ___toolboxItemTypeName_0)); }
inline String_t* get_toolboxItemTypeName_0() const { return ___toolboxItemTypeName_0; }
inline String_t** get_address_of_toolboxItemTypeName_0() { return &___toolboxItemTypeName_0; }
inline void set_toolboxItemTypeName_0(String_t* value)
{
___toolboxItemTypeName_0 = value;
Il2CppCodeGenWriteBarrier((&___toolboxItemTypeName_0), value);
}
};
struct ToolboxItemAttribute_t243705872_StaticFields
{
public:
// System.ComponentModel.ToolboxItemAttribute System.ComponentModel.ToolboxItemAttribute::Default
ToolboxItemAttribute_t243705872 * ___Default_1;
// System.ComponentModel.ToolboxItemAttribute System.ComponentModel.ToolboxItemAttribute::None
ToolboxItemAttribute_t243705872 * ___None_2;
public:
inline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(ToolboxItemAttribute_t243705872_StaticFields, ___Default_1)); }
inline ToolboxItemAttribute_t243705872 * get_Default_1() const { return ___Default_1; }
inline ToolboxItemAttribute_t243705872 ** get_address_of_Default_1() { return &___Default_1; }
inline void set_Default_1(ToolboxItemAttribute_t243705872 * value)
{
___Default_1 = value;
Il2CppCodeGenWriteBarrier((&___Default_1), value);
}
inline static int32_t get_offset_of_None_2() { return static_cast<int32_t>(offsetof(ToolboxItemAttribute_t243705872_StaticFields, ___None_2)); }
inline ToolboxItemAttribute_t243705872 * get_None_2() const { return ___None_2; }
inline ToolboxItemAttribute_t243705872 ** get_address_of_None_2() { return &___None_2; }
inline void set_None_2(ToolboxItemAttribute_t243705872 * value)
{
___None_2 = value;
Il2CppCodeGenWriteBarrier((&___None_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TOOLBOXITEMATTRIBUTE_T243705872_H
#ifndef DESIGNERSERIALIZERATTRIBUTE_T1570548024_H
#define DESIGNERSERIALIZERATTRIBUTE_T1570548024_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Design.Serialization.DesignerSerializerAttribute
struct DesignerSerializerAttribute_t1570548024 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.Design.Serialization.DesignerSerializerAttribute::serializerTypeName
String_t* ___serializerTypeName_0;
// System.String System.ComponentModel.Design.Serialization.DesignerSerializerAttribute::serializerBaseTypeName
String_t* ___serializerBaseTypeName_1;
// System.String System.ComponentModel.Design.Serialization.DesignerSerializerAttribute::typeId
String_t* ___typeId_2;
public:
inline static int32_t get_offset_of_serializerTypeName_0() { return static_cast<int32_t>(offsetof(DesignerSerializerAttribute_t1570548024, ___serializerTypeName_0)); }
inline String_t* get_serializerTypeName_0() const { return ___serializerTypeName_0; }
inline String_t** get_address_of_serializerTypeName_0() { return &___serializerTypeName_0; }
inline void set_serializerTypeName_0(String_t* value)
{
___serializerTypeName_0 = value;
Il2CppCodeGenWriteBarrier((&___serializerTypeName_0), value);
}
inline static int32_t get_offset_of_serializerBaseTypeName_1() { return static_cast<int32_t>(offsetof(DesignerSerializerAttribute_t1570548024, ___serializerBaseTypeName_1)); }
inline String_t* get_serializerBaseTypeName_1() const { return ___serializerBaseTypeName_1; }
inline String_t** get_address_of_serializerBaseTypeName_1() { return &___serializerBaseTypeName_1; }
inline void set_serializerBaseTypeName_1(String_t* value)
{
___serializerBaseTypeName_1 = value;
Il2CppCodeGenWriteBarrier((&___serializerBaseTypeName_1), value);
}
inline static int32_t get_offset_of_typeId_2() { return static_cast<int32_t>(offsetof(DesignerSerializerAttribute_t1570548024, ___typeId_2)); }
inline String_t* get_typeId_2() const { return ___typeId_2; }
inline String_t** get_address_of_typeId_2() { return &___typeId_2; }
inline void set_typeId_2(String_t* value)
{
___typeId_2 = value;
Il2CppCodeGenWriteBarrier((&___typeId_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERSERIALIZERATTRIBUTE_T1570548024_H
#ifndef VOID_T1185182177_H
#define VOID_T1185182177_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1185182177
{
public:
union
{
struct
{
};
uint8_t Void_t1185182177__padding[1];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1185182177_H
#ifndef NOTIFYPARENTPROPERTYATTRIBUTE_T1405421815_H
#define NOTIFYPARENTPROPERTYATTRIBUTE_T1405421815_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.NotifyParentPropertyAttribute
struct NotifyParentPropertyAttribute_t1405421815 : public Attribute_t861562559
{
public:
// System.Boolean System.ComponentModel.NotifyParentPropertyAttribute::notifyParent
bool ___notifyParent_3;
public:
inline static int32_t get_offset_of_notifyParent_3() { return static_cast<int32_t>(offsetof(NotifyParentPropertyAttribute_t1405421815, ___notifyParent_3)); }
inline bool get_notifyParent_3() const { return ___notifyParent_3; }
inline bool* get_address_of_notifyParent_3() { return &___notifyParent_3; }
inline void set_notifyParent_3(bool value)
{
___notifyParent_3 = value;
}
};
struct NotifyParentPropertyAttribute_t1405421815_StaticFields
{
public:
// System.ComponentModel.NotifyParentPropertyAttribute System.ComponentModel.NotifyParentPropertyAttribute::Yes
NotifyParentPropertyAttribute_t1405421815 * ___Yes_0;
// System.ComponentModel.NotifyParentPropertyAttribute System.ComponentModel.NotifyParentPropertyAttribute::No
NotifyParentPropertyAttribute_t1405421815 * ___No_1;
// System.ComponentModel.NotifyParentPropertyAttribute System.ComponentModel.NotifyParentPropertyAttribute::Default
NotifyParentPropertyAttribute_t1405421815 * ___Default_2;
public:
inline static int32_t get_offset_of_Yes_0() { return static_cast<int32_t>(offsetof(NotifyParentPropertyAttribute_t1405421815_StaticFields, ___Yes_0)); }
inline NotifyParentPropertyAttribute_t1405421815 * get_Yes_0() const { return ___Yes_0; }
inline NotifyParentPropertyAttribute_t1405421815 ** get_address_of_Yes_0() { return &___Yes_0; }
inline void set_Yes_0(NotifyParentPropertyAttribute_t1405421815 * value)
{
___Yes_0 = value;
Il2CppCodeGenWriteBarrier((&___Yes_0), value);
}
inline static int32_t get_offset_of_No_1() { return static_cast<int32_t>(offsetof(NotifyParentPropertyAttribute_t1405421815_StaticFields, ___No_1)); }
inline NotifyParentPropertyAttribute_t1405421815 * get_No_1() const { return ___No_1; }
inline NotifyParentPropertyAttribute_t1405421815 ** get_address_of_No_1() { return &___No_1; }
inline void set_No_1(NotifyParentPropertyAttribute_t1405421815 * value)
{
___No_1 = value;
Il2CppCodeGenWriteBarrier((&___No_1), value);
}
inline static int32_t get_offset_of_Default_2() { return static_cast<int32_t>(offsetof(NotifyParentPropertyAttribute_t1405421815_StaticFields, ___Default_2)); }
inline NotifyParentPropertyAttribute_t1405421815 * get_Default_2() const { return ___Default_2; }
inline NotifyParentPropertyAttribute_t1405421815 ** get_address_of_Default_2() { return &___Default_2; }
inline void set_Default_2(NotifyParentPropertyAttribute_t1405421815 * value)
{
___Default_2 = value;
Il2CppCodeGenWriteBarrier((&___Default_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // NOTIFYPARENTPROPERTYATTRIBUTE_T1405421815_H
#ifndef SYSTEMEXCEPTION_T176217640_H
#define SYSTEMEXCEPTION_T176217640_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.SystemException
struct SystemException_t176217640 : public Exception_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYSTEMEXCEPTION_T176217640_H
#ifndef DEFAULTTYPEDESCRIPTOR_T4148937846_H
#define DEFAULTTYPEDESCRIPTOR_T4148937846_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultTypeDescriptor
struct DefaultTypeDescriptor_t4148937846
{
public:
// System.ComponentModel.TypeDescriptor/TypeDescriptionNode System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultTypeDescriptor::_node
TypeDescriptionNode_t3022060204 * ____node_0;
// System.Type System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultTypeDescriptor::_objectType
Type_t * ____objectType_1;
// System.Object System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultTypeDescriptor::_instance
RuntimeObject * ____instance_2;
public:
inline static int32_t get_offset_of__node_0() { return static_cast<int32_t>(offsetof(DefaultTypeDescriptor_t4148937846, ____node_0)); }
inline TypeDescriptionNode_t3022060204 * get__node_0() const { return ____node_0; }
inline TypeDescriptionNode_t3022060204 ** get_address_of__node_0() { return &____node_0; }
inline void set__node_0(TypeDescriptionNode_t3022060204 * value)
{
____node_0 = value;
Il2CppCodeGenWriteBarrier((&____node_0), value);
}
inline static int32_t get_offset_of__objectType_1() { return static_cast<int32_t>(offsetof(DefaultTypeDescriptor_t4148937846, ____objectType_1)); }
inline Type_t * get__objectType_1() const { return ____objectType_1; }
inline Type_t ** get_address_of__objectType_1() { return &____objectType_1; }
inline void set__objectType_1(Type_t * value)
{
____objectType_1 = value;
Il2CppCodeGenWriteBarrier((&____objectType_1), value);
}
inline static int32_t get_offset_of__instance_2() { return static_cast<int32_t>(offsetof(DefaultTypeDescriptor_t4148937846, ____instance_2)); }
inline RuntimeObject * get__instance_2() const { return ____instance_2; }
inline RuntimeObject ** get_address_of__instance_2() { return &____instance_2; }
inline void set__instance_2(RuntimeObject * value)
{
____instance_2 = value;
Il2CppCodeGenWriteBarrier((&____instance_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultTypeDescriptor
struct DefaultTypeDescriptor_t4148937846_marshaled_pinvoke
{
TypeDescriptionNode_t3022060204 * ____node_0;
Type_t * ____objectType_1;
Il2CppIUnknown* ____instance_2;
};
// Native definition for COM marshalling of System.ComponentModel.TypeDescriptor/TypeDescriptionNode/DefaultTypeDescriptor
struct DefaultTypeDescriptor_t4148937846_marshaled_com
{
TypeDescriptionNode_t3022060204 * ____node_0;
Type_t * ____objectType_1;
Il2CppIUnknown* ____instance_2;
};
#endif // DEFAULTTYPEDESCRIPTOR_T4148937846_H
#ifndef BOOLEAN_T97287965_H
#define BOOLEAN_T97287965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t97287965
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_t97287965_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_5), value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_6), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T97287965_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t3528271667* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t3528271667* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t3528271667** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t3528271667* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef PROPERTYDESCRIPTOR_T3244362832_H
#define PROPERTYDESCRIPTOR_T3244362832_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyDescriptor
struct PropertyDescriptor_t3244362832 : public MemberDescriptor_t3815403747
{
public:
// System.ComponentModel.TypeConverter System.ComponentModel.PropertyDescriptor::converter
TypeConverter_t2249118273 * ___converter_11;
// System.Object[] System.ComponentModel.PropertyDescriptor::editors
ObjectU5BU5D_t2843939325* ___editors_12;
// System.Type[] System.ComponentModel.PropertyDescriptor::editorTypes
TypeU5BU5D_t3940880105* ___editorTypes_13;
// System.Int32 System.ComponentModel.PropertyDescriptor::editorCount
int32_t ___editorCount_14;
public:
inline static int32_t get_offset_of_converter_11() { return static_cast<int32_t>(offsetof(PropertyDescriptor_t3244362832, ___converter_11)); }
inline TypeConverter_t2249118273 * get_converter_11() const { return ___converter_11; }
inline TypeConverter_t2249118273 ** get_address_of_converter_11() { return &___converter_11; }
inline void set_converter_11(TypeConverter_t2249118273 * value)
{
___converter_11 = value;
Il2CppCodeGenWriteBarrier((&___converter_11), value);
}
inline static int32_t get_offset_of_editors_12() { return static_cast<int32_t>(offsetof(PropertyDescriptor_t3244362832, ___editors_12)); }
inline ObjectU5BU5D_t2843939325* get_editors_12() const { return ___editors_12; }
inline ObjectU5BU5D_t2843939325** get_address_of_editors_12() { return &___editors_12; }
inline void set_editors_12(ObjectU5BU5D_t2843939325* value)
{
___editors_12 = value;
Il2CppCodeGenWriteBarrier((&___editors_12), value);
}
inline static int32_t get_offset_of_editorTypes_13() { return static_cast<int32_t>(offsetof(PropertyDescriptor_t3244362832, ___editorTypes_13)); }
inline TypeU5BU5D_t3940880105* get_editorTypes_13() const { return ___editorTypes_13; }
inline TypeU5BU5D_t3940880105** get_address_of_editorTypes_13() { return &___editorTypes_13; }
inline void set_editorTypes_13(TypeU5BU5D_t3940880105* value)
{
___editorTypes_13 = value;
Il2CppCodeGenWriteBarrier((&___editorTypes_13), value);
}
inline static int32_t get_offset_of_editorCount_14() { return static_cast<int32_t>(offsetof(PropertyDescriptor_t3244362832, ___editorCount_14)); }
inline int32_t get_editorCount_14() const { return ___editorCount_14; }
inline int32_t* get_address_of_editorCount_14() { return &___editorCount_14; }
inline void set_editorCount_14(int32_t value)
{
___editorCount_14 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYDESCRIPTOR_T3244362832_H
#ifndef PROPERTYCHANGEDEVENTARGS_T3313059048_H
#define PROPERTYCHANGEDEVENTARGS_T3313059048_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyChangedEventArgs
struct PropertyChangedEventArgs_t3313059048 : public EventArgs_t3591816995
{
public:
// System.String System.ComponentModel.PropertyChangedEventArgs::propertyName
String_t* ___propertyName_1;
public:
inline static int32_t get_offset_of_propertyName_1() { return static_cast<int32_t>(offsetof(PropertyChangedEventArgs_t3313059048, ___propertyName_1)); }
inline String_t* get_propertyName_1() const { return ___propertyName_1; }
inline String_t** get_address_of_propertyName_1() { return &___propertyName_1; }
inline void set_propertyName_1(String_t* value)
{
___propertyName_1 = value;
Il2CppCodeGenWriteBarrier((&___propertyName_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYCHANGEDEVENTARGS_T3313059048_H
#ifndef RECOMMENDEDASCONFIGURABLEATTRIBUTE_T279829077_H
#define RECOMMENDEDASCONFIGURABLEATTRIBUTE_T279829077_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.RecommendedAsConfigurableAttribute
struct RecommendedAsConfigurableAttribute_t279829077 : public Attribute_t861562559
{
public:
// System.Boolean System.ComponentModel.RecommendedAsConfigurableAttribute::recommendedAsConfigurable
bool ___recommendedAsConfigurable_0;
public:
inline static int32_t get_offset_of_recommendedAsConfigurable_0() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077, ___recommendedAsConfigurable_0)); }
inline bool get_recommendedAsConfigurable_0() const { return ___recommendedAsConfigurable_0; }
inline bool* get_address_of_recommendedAsConfigurable_0() { return &___recommendedAsConfigurable_0; }
inline void set_recommendedAsConfigurable_0(bool value)
{
___recommendedAsConfigurable_0 = value;
}
};
struct RecommendedAsConfigurableAttribute_t279829077_StaticFields
{
public:
// System.ComponentModel.RecommendedAsConfigurableAttribute System.ComponentModel.RecommendedAsConfigurableAttribute::No
RecommendedAsConfigurableAttribute_t279829077 * ___No_1;
// System.ComponentModel.RecommendedAsConfigurableAttribute System.ComponentModel.RecommendedAsConfigurableAttribute::Yes
RecommendedAsConfigurableAttribute_t279829077 * ___Yes_2;
// System.ComponentModel.RecommendedAsConfigurableAttribute System.ComponentModel.RecommendedAsConfigurableAttribute::Default
RecommendedAsConfigurableAttribute_t279829077 * ___Default_3;
public:
inline static int32_t get_offset_of_No_1() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077_StaticFields, ___No_1)); }
inline RecommendedAsConfigurableAttribute_t279829077 * get_No_1() const { return ___No_1; }
inline RecommendedAsConfigurableAttribute_t279829077 ** get_address_of_No_1() { return &___No_1; }
inline void set_No_1(RecommendedAsConfigurableAttribute_t279829077 * value)
{
___No_1 = value;
Il2CppCodeGenWriteBarrier((&___No_1), value);
}
inline static int32_t get_offset_of_Yes_2() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077_StaticFields, ___Yes_2)); }
inline RecommendedAsConfigurableAttribute_t279829077 * get_Yes_2() const { return ___Yes_2; }
inline RecommendedAsConfigurableAttribute_t279829077 ** get_address_of_Yes_2() { return &___Yes_2; }
inline void set_Yes_2(RecommendedAsConfigurableAttribute_t279829077 * value)
{
___Yes_2 = value;
Il2CppCodeGenWriteBarrier((&___Yes_2), value);
}
inline static int32_t get_offset_of_Default_3() { return static_cast<int32_t>(offsetof(RecommendedAsConfigurableAttribute_t279829077_StaticFields, ___Default_3)); }
inline RecommendedAsConfigurableAttribute_t279829077 * get_Default_3() const { return ___Default_3; }
inline RecommendedAsConfigurableAttribute_t279829077 ** get_address_of_Default_3() { return &___Default_3; }
inline void set_Default_3(RecommendedAsConfigurableAttribute_t279829077 * value)
{
___Default_3 = value;
Il2CppCodeGenWriteBarrier((&___Default_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RECOMMENDEDASCONFIGURABLEATTRIBUTE_T279829077_H
#ifndef READONLYATTRIBUTE_T1907441566_H
#define READONLYATTRIBUTE_T1907441566_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ReadOnlyAttribute
struct ReadOnlyAttribute_t1907441566 : public Attribute_t861562559
{
public:
// System.Boolean System.ComponentModel.ReadOnlyAttribute::isReadOnly
bool ___isReadOnly_0;
public:
inline static int32_t get_offset_of_isReadOnly_0() { return static_cast<int32_t>(offsetof(ReadOnlyAttribute_t1907441566, ___isReadOnly_0)); }
inline bool get_isReadOnly_0() const { return ___isReadOnly_0; }
inline bool* get_address_of_isReadOnly_0() { return &___isReadOnly_0; }
inline void set_isReadOnly_0(bool value)
{
___isReadOnly_0 = value;
}
};
struct ReadOnlyAttribute_t1907441566_StaticFields
{
public:
// System.ComponentModel.ReadOnlyAttribute System.ComponentModel.ReadOnlyAttribute::Yes
ReadOnlyAttribute_t1907441566 * ___Yes_1;
// System.ComponentModel.ReadOnlyAttribute System.ComponentModel.ReadOnlyAttribute::No
ReadOnlyAttribute_t1907441566 * ___No_2;
// System.ComponentModel.ReadOnlyAttribute System.ComponentModel.ReadOnlyAttribute::Default
ReadOnlyAttribute_t1907441566 * ___Default_3;
public:
inline static int32_t get_offset_of_Yes_1() { return static_cast<int32_t>(offsetof(ReadOnlyAttribute_t1907441566_StaticFields, ___Yes_1)); }
inline ReadOnlyAttribute_t1907441566 * get_Yes_1() const { return ___Yes_1; }
inline ReadOnlyAttribute_t1907441566 ** get_address_of_Yes_1() { return &___Yes_1; }
inline void set_Yes_1(ReadOnlyAttribute_t1907441566 * value)
{
___Yes_1 = value;
Il2CppCodeGenWriteBarrier((&___Yes_1), value);
}
inline static int32_t get_offset_of_No_2() { return static_cast<int32_t>(offsetof(ReadOnlyAttribute_t1907441566_StaticFields, ___No_2)); }
inline ReadOnlyAttribute_t1907441566 * get_No_2() const { return ___No_2; }
inline ReadOnlyAttribute_t1907441566 ** get_address_of_No_2() { return &___No_2; }
inline void set_No_2(ReadOnlyAttribute_t1907441566 * value)
{
___No_2 = value;
Il2CppCodeGenWriteBarrier((&___No_2), value);
}
inline static int32_t get_offset_of_Default_3() { return static_cast<int32_t>(offsetof(ReadOnlyAttribute_t1907441566_StaticFields, ___Default_3)); }
inline ReadOnlyAttribute_t1907441566 * get_Default_3() const { return ___Default_3; }
inline ReadOnlyAttribute_t1907441566 ** get_address_of_Default_3() { return &___Default_3; }
inline void set_Default_3(ReadOnlyAttribute_t1907441566 * value)
{
___Default_3 = value;
Il2CppCodeGenWriteBarrier((&___Default_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // READONLYATTRIBUTE_T1907441566_H
#ifndef DESIGNERCATEGORYATTRIBUTE_T2912925731_H
#define DESIGNERCATEGORYATTRIBUTE_T2912925731_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerCategoryAttribute
struct DesignerCategoryAttribute_t2912925731 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.DesignerCategoryAttribute::category
String_t* ___category_0;
// System.String System.ComponentModel.DesignerCategoryAttribute::typeId
String_t* ___typeId_1;
public:
inline static int32_t get_offset_of_category_0() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731, ___category_0)); }
inline String_t* get_category_0() const { return ___category_0; }
inline String_t** get_address_of_category_0() { return &___category_0; }
inline void set_category_0(String_t* value)
{
___category_0 = value;
Il2CppCodeGenWriteBarrier((&___category_0), value);
}
inline static int32_t get_offset_of_typeId_1() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731, ___typeId_1)); }
inline String_t* get_typeId_1() const { return ___typeId_1; }
inline String_t** get_address_of_typeId_1() { return &___typeId_1; }
inline void set_typeId_1(String_t* value)
{
___typeId_1 = value;
Il2CppCodeGenWriteBarrier((&___typeId_1), value);
}
};
struct DesignerCategoryAttribute_t2912925731_StaticFields
{
public:
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Component
DesignerCategoryAttribute_t2912925731 * ___Component_2;
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Default
DesignerCategoryAttribute_t2912925731 * ___Default_3;
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Form
DesignerCategoryAttribute_t2912925731 * ___Form_4;
// System.ComponentModel.DesignerCategoryAttribute System.ComponentModel.DesignerCategoryAttribute::Generic
DesignerCategoryAttribute_t2912925731 * ___Generic_5;
public:
inline static int32_t get_offset_of_Component_2() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Component_2)); }
inline DesignerCategoryAttribute_t2912925731 * get_Component_2() const { return ___Component_2; }
inline DesignerCategoryAttribute_t2912925731 ** get_address_of_Component_2() { return &___Component_2; }
inline void set_Component_2(DesignerCategoryAttribute_t2912925731 * value)
{
___Component_2 = value;
Il2CppCodeGenWriteBarrier((&___Component_2), value);
}
inline static int32_t get_offset_of_Default_3() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Default_3)); }
inline DesignerCategoryAttribute_t2912925731 * get_Default_3() const { return ___Default_3; }
inline DesignerCategoryAttribute_t2912925731 ** get_address_of_Default_3() { return &___Default_3; }
inline void set_Default_3(DesignerCategoryAttribute_t2912925731 * value)
{
___Default_3 = value;
Il2CppCodeGenWriteBarrier((&___Default_3), value);
}
inline static int32_t get_offset_of_Form_4() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Form_4)); }
inline DesignerCategoryAttribute_t2912925731 * get_Form_4() const { return ___Form_4; }
inline DesignerCategoryAttribute_t2912925731 ** get_address_of_Form_4() { return &___Form_4; }
inline void set_Form_4(DesignerCategoryAttribute_t2912925731 * value)
{
___Form_4 = value;
Il2CppCodeGenWriteBarrier((&___Form_4), value);
}
inline static int32_t get_offset_of_Generic_5() { return static_cast<int32_t>(offsetof(DesignerCategoryAttribute_t2912925731_StaticFields, ___Generic_5)); }
inline DesignerCategoryAttribute_t2912925731 * get_Generic_5() const { return ___Generic_5; }
inline DesignerCategoryAttribute_t2912925731 ** get_address_of_Generic_5() { return &___Generic_5; }
inline void set_Generic_5(DesignerCategoryAttribute_t2912925731 * value)
{
___Generic_5 = value;
Il2CppCodeGenWriteBarrier((&___Generic_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERCATEGORYATTRIBUTE_T2912925731_H
#ifndef EVENTDESCRIPTOR_T88602298_H
#define EVENTDESCRIPTOR_T88602298_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EventDescriptor
struct EventDescriptor_t88602298 : public MemberDescriptor_t3815403747
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EVENTDESCRIPTOR_T88602298_H
#ifndef EDITORATTRIBUTE_T1332199665_H
#define EDITORATTRIBUTE_T1332199665_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EditorAttribute
struct EditorAttribute_t1332199665 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.EditorAttribute::baseTypeName
String_t* ___baseTypeName_0;
// System.String System.ComponentModel.EditorAttribute::typeName
String_t* ___typeName_1;
// System.String System.ComponentModel.EditorAttribute::typeId
String_t* ___typeId_2;
public:
inline static int32_t get_offset_of_baseTypeName_0() { return static_cast<int32_t>(offsetof(EditorAttribute_t1332199665, ___baseTypeName_0)); }
inline String_t* get_baseTypeName_0() const { return ___baseTypeName_0; }
inline String_t** get_address_of_baseTypeName_0() { return &___baseTypeName_0; }
inline void set_baseTypeName_0(String_t* value)
{
___baseTypeName_0 = value;
Il2CppCodeGenWriteBarrier((&___baseTypeName_0), value);
}
inline static int32_t get_offset_of_typeName_1() { return static_cast<int32_t>(offsetof(EditorAttribute_t1332199665, ___typeName_1)); }
inline String_t* get_typeName_1() const { return ___typeName_1; }
inline String_t** get_address_of_typeName_1() { return &___typeName_1; }
inline void set_typeName_1(String_t* value)
{
___typeName_1 = value;
Il2CppCodeGenWriteBarrier((&___typeName_1), value);
}
inline static int32_t get_offset_of_typeId_2() { return static_cast<int32_t>(offsetof(EditorAttribute_t1332199665, ___typeId_2)); }
inline String_t* get_typeId_2() const { return ___typeId_2; }
inline String_t** get_address_of_typeId_2() { return &___typeId_2; }
inline void set_typeId_2(String_t* value)
{
___typeId_2 = value;
Il2CppCodeGenWriteBarrier((&___typeId_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EDITORATTRIBUTE_T1332199665_H
#ifndef INSTALLERTYPEATTRIBUTE_T3233088727_H
#define INSTALLERTYPEATTRIBUTE_T3233088727_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.InstallerTypeAttribute
struct InstallerTypeAttribute_t3233088727 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.InstallerTypeAttribute::_typeName
String_t* ____typeName_0;
public:
inline static int32_t get_offset_of__typeName_0() { return static_cast<int32_t>(offsetof(InstallerTypeAttribute_t3233088727, ____typeName_0)); }
inline String_t* get__typeName_0() const { return ____typeName_0; }
inline String_t** get_address_of__typeName_0() { return &____typeName_0; }
inline void set__typeName_0(String_t* value)
{
____typeName_0 = value;
Il2CppCodeGenWriteBarrier((&____typeName_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INSTALLERTYPEATTRIBUTE_T3233088727_H
#ifndef EXTENDERPROVIDEDPROPERTYATTRIBUTE_T3771163592_H
#define EXTENDERPROVIDEDPROPERTYATTRIBUTE_T3771163592_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ExtenderProvidedPropertyAttribute
struct ExtenderProvidedPropertyAttribute_t3771163592 : public Attribute_t861562559
{
public:
// System.ComponentModel.PropertyDescriptor System.ComponentModel.ExtenderProvidedPropertyAttribute::extenderProperty
PropertyDescriptor_t3244362832 * ___extenderProperty_0;
// System.ComponentModel.IExtenderProvider System.ComponentModel.ExtenderProvidedPropertyAttribute::provider
RuntimeObject* ___provider_1;
// System.Type System.ComponentModel.ExtenderProvidedPropertyAttribute::receiverType
Type_t * ___receiverType_2;
public:
inline static int32_t get_offset_of_extenderProperty_0() { return static_cast<int32_t>(offsetof(ExtenderProvidedPropertyAttribute_t3771163592, ___extenderProperty_0)); }
inline PropertyDescriptor_t3244362832 * get_extenderProperty_0() const { return ___extenderProperty_0; }
inline PropertyDescriptor_t3244362832 ** get_address_of_extenderProperty_0() { return &___extenderProperty_0; }
inline void set_extenderProperty_0(PropertyDescriptor_t3244362832 * value)
{
___extenderProperty_0 = value;
Il2CppCodeGenWriteBarrier((&___extenderProperty_0), value);
}
inline static int32_t get_offset_of_provider_1() { return static_cast<int32_t>(offsetof(ExtenderProvidedPropertyAttribute_t3771163592, ___provider_1)); }
inline RuntimeObject* get_provider_1() const { return ___provider_1; }
inline RuntimeObject** get_address_of_provider_1() { return &___provider_1; }
inline void set_provider_1(RuntimeObject* value)
{
___provider_1 = value;
Il2CppCodeGenWriteBarrier((&___provider_1), value);
}
inline static int32_t get_offset_of_receiverType_2() { return static_cast<int32_t>(offsetof(ExtenderProvidedPropertyAttribute_t3771163592, ___receiverType_2)); }
inline Type_t * get_receiverType_2() const { return ___receiverType_2; }
inline Type_t ** get_address_of_receiverType_2() { return &___receiverType_2; }
inline void set_receiverType_2(Type_t * value)
{
___receiverType_2 = value;
Il2CppCodeGenWriteBarrier((&___receiverType_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXTENDERPROVIDEDPROPERTYATTRIBUTE_T3771163592_H
#ifndef REFRESHEVENTARGS_T9288056_H
#define REFRESHEVENTARGS_T9288056_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.RefreshEventArgs
struct RefreshEventArgs_t9288056 : public EventArgs_t3591816995
{
public:
// System.Type System.ComponentModel.RefreshEventArgs::typeChanged
Type_t * ___typeChanged_1;
public:
inline static int32_t get_offset_of_typeChanged_1() { return static_cast<int32_t>(offsetof(RefreshEventArgs_t9288056, ___typeChanged_1)); }
inline Type_t * get_typeChanged_1() const { return ___typeChanged_1; }
inline Type_t ** get_address_of_typeChanged_1() { return &___typeChanged_1; }
inline void set_typeChanged_1(Type_t * value)
{
___typeChanged_1 = value;
Il2CppCodeGenWriteBarrier((&___typeChanged_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFRESHEVENTARGS_T9288056_H
#ifndef SETTINGSBINDABLEATTRIBUTE_T3884869596_H
#define SETTINGSBINDABLEATTRIBUTE_T3884869596_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.SettingsBindableAttribute
struct SettingsBindableAttribute_t3884869596 : public Attribute_t861562559
{
public:
// System.Boolean System.ComponentModel.SettingsBindableAttribute::_bindable
bool ____bindable_2;
public:
inline static int32_t get_offset_of__bindable_2() { return static_cast<int32_t>(offsetof(SettingsBindableAttribute_t3884869596, ____bindable_2)); }
inline bool get__bindable_2() const { return ____bindable_2; }
inline bool* get_address_of__bindable_2() { return &____bindable_2; }
inline void set__bindable_2(bool value)
{
____bindable_2 = value;
}
};
struct SettingsBindableAttribute_t3884869596_StaticFields
{
public:
// System.ComponentModel.SettingsBindableAttribute System.ComponentModel.SettingsBindableAttribute::Yes
SettingsBindableAttribute_t3884869596 * ___Yes_0;
// System.ComponentModel.SettingsBindableAttribute System.ComponentModel.SettingsBindableAttribute::No
SettingsBindableAttribute_t3884869596 * ___No_1;
public:
inline static int32_t get_offset_of_Yes_0() { return static_cast<int32_t>(offsetof(SettingsBindableAttribute_t3884869596_StaticFields, ___Yes_0)); }
inline SettingsBindableAttribute_t3884869596 * get_Yes_0() const { return ___Yes_0; }
inline SettingsBindableAttribute_t3884869596 ** get_address_of_Yes_0() { return &___Yes_0; }
inline void set_Yes_0(SettingsBindableAttribute_t3884869596 * value)
{
___Yes_0 = value;
Il2CppCodeGenWriteBarrier((&___Yes_0), value);
}
inline static int32_t get_offset_of_No_1() { return static_cast<int32_t>(offsetof(SettingsBindableAttribute_t3884869596_StaticFields, ___No_1)); }
inline SettingsBindableAttribute_t3884869596 * get_No_1() const { return ___No_1; }
inline SettingsBindableAttribute_t3884869596 ** get_address_of_No_1() { return &___No_1; }
inline void set_No_1(SettingsBindableAttribute_t3884869596 * value)
{
___No_1 = value;
Il2CppCodeGenWriteBarrier((&___No_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SETTINGSBINDABLEATTRIBUTE_T3884869596_H
#ifndef TYPECONVERTERATTRIBUTE_T3271584429_H
#define TYPECONVERTERATTRIBUTE_T3271584429_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverterAttribute
struct TypeConverterAttribute_t3271584429 : public Attribute_t861562559
{
public:
// System.String System.ComponentModel.TypeConverterAttribute::typeName
String_t* ___typeName_0;
public:
inline static int32_t get_offset_of_typeName_0() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_t3271584429, ___typeName_0)); }
inline String_t* get_typeName_0() const { return ___typeName_0; }
inline String_t** get_address_of_typeName_0() { return &___typeName_0; }
inline void set_typeName_0(String_t* value)
{
___typeName_0 = value;
Il2CppCodeGenWriteBarrier((&___typeName_0), value);
}
};
struct TypeConverterAttribute_t3271584429_StaticFields
{
public:
// System.ComponentModel.TypeConverterAttribute System.ComponentModel.TypeConverterAttribute::Default
TypeConverterAttribute_t3271584429 * ___Default_1;
public:
inline static int32_t get_offset_of_Default_1() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_t3271584429_StaticFields, ___Default_1)); }
inline TypeConverterAttribute_t3271584429 * get_Default_1() const { return ___Default_1; }
inline TypeConverterAttribute_t3271584429 ** get_address_of_Default_1() { return &___Default_1; }
inline void set_Default_1(TypeConverterAttribute_t3271584429 * value)
{
___Default_1 = value;
Il2CppCodeGenWriteBarrier((&___Default_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPECONVERTERATTRIBUTE_T3271584429_H
#ifndef X509CHAINSTATUSFLAGS_T1026973125_H
#define X509CHAINSTATUSFLAGS_T1026973125_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509ChainStatusFlags
struct X509ChainStatusFlags_t1026973125
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509ChainStatusFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509ChainStatusFlags_t1026973125, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509CHAINSTATUSFLAGS_T1026973125_H
#ifndef X500DISTINGUISHEDNAMEFLAGS_T254051580_H
#define X500DISTINGUISHEDNAMEFLAGS_T254051580_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags
struct X500DistinguishedNameFlags_t254051580
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X500DistinguishedNameFlags_t254051580, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X500DISTINGUISHEDNAMEFLAGS_T254051580_H
#ifndef STORELOCATION_T2864310644_H
#define STORELOCATION_T2864310644_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.StoreLocation
struct StoreLocation_t2864310644
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.StoreLocation::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(StoreLocation_t2864310644, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STORELOCATION_T2864310644_H
#ifndef OPENFLAGS_T968238685_H
#define OPENFLAGS_T968238685_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.OpenFlags
struct OpenFlags_t968238685
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.OpenFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(OpenFlags_t968238685, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OPENFLAGS_T968238685_H
#ifndef ASNDECODESTATUS_T788588755_H
#define ASNDECODESTATUS_T788588755_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AsnDecodeStatus
struct AsnDecodeStatus_t788588755
{
public:
// System.Int32 System.Security.Cryptography.AsnDecodeStatus::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AsnDecodeStatus_t788588755, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ASNDECODESTATUS_T788588755_H
#ifndef STORENAME_T1492274484_H
#define STORENAME_T1492274484_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.StoreName
struct StoreName_t1492274484
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.StoreName::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(StoreName_t1492274484, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STORENAME_T1492274484_H
#ifndef X509FINDTYPE_T3058503971_H
#define X509FINDTYPE_T3058503971_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.X509Certificates.X509FindType
struct X509FindType_t3058503971
{
public:
// System.Int32 System.Security.Cryptography.X509Certificates.X509FindType::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(X509FindType_t3058503971, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // X509FINDTYPE_T3058503971_H
#ifndef HASHTABLE_T1853889766_H
#define HASHTABLE_T1853889766_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Hashtable
struct Hashtable_t1853889766 : public RuntimeObject
{
public:
// System.Collections.Hashtable/bucket[] System.Collections.Hashtable::buckets
bucketU5BU5D_t876121385* ___buckets_10;
// System.Int32 System.Collections.Hashtable::count
int32_t ___count_11;
// System.Int32 System.Collections.Hashtable::occupancy
int32_t ___occupancy_12;
// System.Int32 System.Collections.Hashtable::loadsize
int32_t ___loadsize_13;
// System.Single System.Collections.Hashtable::loadFactor
float ___loadFactor_14;
// System.Int32 modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Hashtable::version
int32_t ___version_15;
// System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Hashtable::isWriterInProgress
bool ___isWriterInProgress_16;
// System.Collections.ICollection System.Collections.Hashtable::keys
RuntimeObject* ___keys_17;
// System.Collections.ICollection System.Collections.Hashtable::values
RuntimeObject* ___values_18;
// System.Collections.IEqualityComparer System.Collections.Hashtable::_keycomparer
RuntimeObject* ____keycomparer_19;
// System.Object System.Collections.Hashtable::_syncRoot
RuntimeObject * ____syncRoot_20;
public:
inline static int32_t get_offset_of_buckets_10() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___buckets_10)); }
inline bucketU5BU5D_t876121385* get_buckets_10() const { return ___buckets_10; }
inline bucketU5BU5D_t876121385** get_address_of_buckets_10() { return &___buckets_10; }
inline void set_buckets_10(bucketU5BU5D_t876121385* value)
{
___buckets_10 = value;
Il2CppCodeGenWriteBarrier((&___buckets_10), value);
}
inline static int32_t get_offset_of_count_11() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___count_11)); }
inline int32_t get_count_11() const { return ___count_11; }
inline int32_t* get_address_of_count_11() { return &___count_11; }
inline void set_count_11(int32_t value)
{
___count_11 = value;
}
inline static int32_t get_offset_of_occupancy_12() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___occupancy_12)); }
inline int32_t get_occupancy_12() const { return ___occupancy_12; }
inline int32_t* get_address_of_occupancy_12() { return &___occupancy_12; }
inline void set_occupancy_12(int32_t value)
{
___occupancy_12 = value;
}
inline static int32_t get_offset_of_loadsize_13() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___loadsize_13)); }
inline int32_t get_loadsize_13() const { return ___loadsize_13; }
inline int32_t* get_address_of_loadsize_13() { return &___loadsize_13; }
inline void set_loadsize_13(int32_t value)
{
___loadsize_13 = value;
}
inline static int32_t get_offset_of_loadFactor_14() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___loadFactor_14)); }
inline float get_loadFactor_14() const { return ___loadFactor_14; }
inline float* get_address_of_loadFactor_14() { return &___loadFactor_14; }
inline void set_loadFactor_14(float value)
{
___loadFactor_14 = value;
}
inline static int32_t get_offset_of_version_15() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___version_15)); }
inline int32_t get_version_15() const { return ___version_15; }
inline int32_t* get_address_of_version_15() { return &___version_15; }
inline void set_version_15(int32_t value)
{
___version_15 = value;
}
inline static int32_t get_offset_of_isWriterInProgress_16() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___isWriterInProgress_16)); }
inline bool get_isWriterInProgress_16() const { return ___isWriterInProgress_16; }
inline bool* get_address_of_isWriterInProgress_16() { return &___isWriterInProgress_16; }
inline void set_isWriterInProgress_16(bool value)
{
___isWriterInProgress_16 = value;
}
inline static int32_t get_offset_of_keys_17() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___keys_17)); }
inline RuntimeObject* get_keys_17() const { return ___keys_17; }
inline RuntimeObject** get_address_of_keys_17() { return &___keys_17; }
inline void set_keys_17(RuntimeObject* value)
{
___keys_17 = value;
Il2CppCodeGenWriteBarrier((&___keys_17), value);
}
inline static int32_t get_offset_of_values_18() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ___values_18)); }
inline RuntimeObject* get_values_18() const { return ___values_18; }
inline RuntimeObject** get_address_of_values_18() { return &___values_18; }
inline void set_values_18(RuntimeObject* value)
{
___values_18 = value;
Il2CppCodeGenWriteBarrier((&___values_18), value);
}
inline static int32_t get_offset_of__keycomparer_19() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ____keycomparer_19)); }
inline RuntimeObject* get__keycomparer_19() const { return ____keycomparer_19; }
inline RuntimeObject** get_address_of__keycomparer_19() { return &____keycomparer_19; }
inline void set__keycomparer_19(RuntimeObject* value)
{
____keycomparer_19 = value;
Il2CppCodeGenWriteBarrier((&____keycomparer_19), value);
}
inline static int32_t get_offset_of__syncRoot_20() { return static_cast<int32_t>(offsetof(Hashtable_t1853889766, ____syncRoot_20)); }
inline RuntimeObject * get__syncRoot_20() const { return ____syncRoot_20; }
inline RuntimeObject ** get_address_of__syncRoot_20() { return &____syncRoot_20; }
inline void set__syncRoot_20(RuntimeObject * value)
{
____syncRoot_20 = value;
Il2CppCodeGenWriteBarrier((&____syncRoot_20), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // HASHTABLE_T1853889766_H
#ifndef DELEGATE_T1188392813_H
#define DELEGATE_T1188392813_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Delegate
struct Delegate_t1188392813 : public RuntimeObject
{
public:
// System.IntPtr System.Delegate::method_ptr
Il2CppMethodPointer ___method_ptr_0;
// System.IntPtr System.Delegate::invoke_impl
intptr_t ___invoke_impl_1;
// System.Object System.Delegate::m_target
RuntimeObject * ___m_target_2;
// System.IntPtr System.Delegate::method
intptr_t ___method_3;
// System.IntPtr System.Delegate::delegate_trampoline
intptr_t ___delegate_trampoline_4;
// System.IntPtr System.Delegate::extra_arg
intptr_t ___extra_arg_5;
// System.IntPtr System.Delegate::method_code
intptr_t ___method_code_6;
// System.Reflection.MethodInfo System.Delegate::method_info
MethodInfo_t * ___method_info_7;
// System.Reflection.MethodInfo System.Delegate::original_method_info
MethodInfo_t * ___original_method_info_8;
// System.DelegateData System.Delegate::data
DelegateData_t1677132599 * ___data_9;
// System.Boolean System.Delegate::method_is_virtual
bool ___method_is_virtual_10;
public:
inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); }
inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }
inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }
inline void set_method_ptr_0(Il2CppMethodPointer value)
{
___method_ptr_0 = value;
}
inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); }
inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }
inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }
inline void set_invoke_impl_1(intptr_t value)
{
___invoke_impl_1 = value;
}
inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); }
inline RuntimeObject * get_m_target_2() const { return ___m_target_2; }
inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }
inline void set_m_target_2(RuntimeObject * value)
{
___m_target_2 = value;
Il2CppCodeGenWriteBarrier((&___m_target_2), value);
}
inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); }
inline intptr_t get_method_3() const { return ___method_3; }
inline intptr_t* get_address_of_method_3() { return &___method_3; }
inline void set_method_3(intptr_t value)
{
___method_3 = value;
}
inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); }
inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }
inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }
inline void set_delegate_trampoline_4(intptr_t value)
{
___delegate_trampoline_4 = value;
}
inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___extra_arg_5)); }
inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; }
inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; }
inline void set_extra_arg_5(intptr_t value)
{
___extra_arg_5 = value;
}
inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_6)); }
inline intptr_t get_method_code_6() const { return ___method_code_6; }
inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; }
inline void set_method_code_6(intptr_t value)
{
___method_code_6 = value;
}
inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_7)); }
inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; }
inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; }
inline void set_method_info_7(MethodInfo_t * value)
{
___method_info_7 = value;
Il2CppCodeGenWriteBarrier((&___method_info_7), value);
}
inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_8)); }
inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; }
inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; }
inline void set_original_method_info_8(MethodInfo_t * value)
{
___original_method_info_8 = value;
Il2CppCodeGenWriteBarrier((&___original_method_info_8), value);
}
inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_9)); }
inline DelegateData_t1677132599 * get_data_9() const { return ___data_9; }
inline DelegateData_t1677132599 ** get_address_of_data_9() { return &___data_9; }
inline void set_data_9(DelegateData_t1677132599 * value)
{
___data_9 = value;
Il2CppCodeGenWriteBarrier((&___data_9), value);
}
inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_is_virtual_10)); }
inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; }
inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; }
inline void set_method_is_virtual_10(bool value)
{
___method_is_virtual_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Delegate
struct Delegate_t1188392813_marshaled_pinvoke
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
MethodInfo_t * ___method_info_7;
MethodInfo_t * ___original_method_info_8;
DelegateData_t1677132599 * ___data_9;
int32_t ___method_is_virtual_10;
};
// Native definition for COM marshalling of System.Delegate
struct Delegate_t1188392813_marshaled_com
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
MethodInfo_t * ___method_info_7;
MethodInfo_t * ___original_method_info_8;
DelegateData_t1677132599 * ___data_9;
int32_t ___method_is_virtual_10;
};
#endif // DELEGATE_T1188392813_H
#ifndef DESIGNERSERIALIZATIONVISIBILITY_T3481291396_H
#define DESIGNERSERIALIZATIONVISIBILITY_T3481291396_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerSerializationVisibility
struct DesignerSerializationVisibility_t3481291396
{
public:
// System.Int32 System.ComponentModel.DesignerSerializationVisibility::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibility_t3481291396, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERSERIALIZATIONVISIBILITY_T3481291396_H
#ifndef EXTERNALEXCEPTION_T3544951457_H
#define EXTERNALEXCEPTION_T3544951457_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.InteropServices.ExternalException
struct ExternalException_t3544951457 : public SystemException_t176217640
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXTERNALEXCEPTION_T3544951457_H
#ifndef ARGUMENTEXCEPTION_T132251570_H
#define ARGUMENTEXCEPTION_T132251570_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ArgumentException
struct ArgumentException_t132251570 : public SystemException_t176217640
{
public:
// System.String System.ArgumentException::m_paramName
String_t* ___m_paramName_17;
public:
inline static int32_t get_offset_of_m_paramName_17() { return static_cast<int32_t>(offsetof(ArgumentException_t132251570, ___m_paramName_17)); }
inline String_t* get_m_paramName_17() const { return ___m_paramName_17; }
inline String_t** get_address_of_m_paramName_17() { return &___m_paramName_17; }
inline void set_m_paramName_17(String_t* value)
{
___m_paramName_17 = value;
Il2CppCodeGenWriteBarrier((&___m_paramName_17), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ARGUMENTEXCEPTION_T132251570_H
#ifndef TYPECONVERTER_T2249118273_H
#define TYPECONVERTER_T2249118273_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TypeConverter
struct TypeConverter_t2249118273 : public RuntimeObject
{
public:
public:
};
struct TypeConverter_t2249118273_StaticFields
{
public:
// System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.TypeConverter::useCompatibleTypeConversion
bool ___useCompatibleTypeConversion_1;
public:
inline static int32_t get_offset_of_useCompatibleTypeConversion_1() { return static_cast<int32_t>(offsetof(TypeConverter_t2249118273_StaticFields, ___useCompatibleTypeConversion_1)); }
inline bool get_useCompatibleTypeConversion_1() const { return ___useCompatibleTypeConversion_1; }
inline bool* get_address_of_useCompatibleTypeConversion_1() { return &___useCompatibleTypeConversion_1; }
inline void set_useCompatibleTypeConversion_1(bool value)
{
___useCompatibleTypeConversion_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TYPECONVERTER_T2249118273_H
#ifndef EDITORBROWSABLESTATE_T2839071299_H
#define EDITORBROWSABLESTATE_T2839071299_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EditorBrowsableState
struct EditorBrowsableState_t2839071299
{
public:
// System.Int32 System.ComponentModel.EditorBrowsableState::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(EditorBrowsableState_t2839071299, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EDITORBROWSABLESTATE_T2839071299_H
#ifndef OIDGROUP_T395834848_H
#define OIDGROUP_T395834848_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.OidGroup
struct OidGroup_t395834848
{
public:
// System.Int32 System.Security.Cryptography.OidGroup::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(OidGroup_t395834848, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OIDGROUP_T395834848_H
#ifndef AUTHENTICATIONEXCEPTION_T1221369422_H
#define AUTHENTICATIONEXCEPTION_T1221369422_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Authentication.AuthenticationException
struct AuthenticationException_t1221369422 : public SystemException_t176217640
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AUTHENTICATIONEXCEPTION_T1221369422_H
#ifndef REFLECTTYPEDESCRIPTIONPROVIDER_T2247041319_H
#define REFLECTTYPEDESCRIPTIONPROVIDER_T2247041319_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ReflectTypeDescriptionProvider
struct ReflectTypeDescriptionProvider_t2247041319 : public TypeDescriptionProvider_t3232077895
{
public:
// System.Collections.Hashtable System.ComponentModel.ReflectTypeDescriptionProvider::_typeData
Hashtable_t1853889766 * ____typeData_2;
public:
inline static int32_t get_offset_of__typeData_2() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319, ____typeData_2)); }
inline Hashtable_t1853889766 * get__typeData_2() const { return ____typeData_2; }
inline Hashtable_t1853889766 ** get_address_of__typeData_2() { return &____typeData_2; }
inline void set__typeData_2(Hashtable_t1853889766 * value)
{
____typeData_2 = value;
Il2CppCodeGenWriteBarrier((&____typeData_2), value);
}
};
struct ReflectTypeDescriptionProvider_t2247041319_StaticFields
{
public:
// System.Type[] System.ComponentModel.ReflectTypeDescriptionProvider::_typeConstructor
TypeU5BU5D_t3940880105* ____typeConstructor_3;
// System.Collections.Hashtable modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.ReflectTypeDescriptionProvider::_intrinsicTypeConverters
Hashtable_t1853889766 * ____intrinsicTypeConverters_4;
// System.Object System.ComponentModel.ReflectTypeDescriptionProvider::_intrinsicReferenceKey
RuntimeObject * ____intrinsicReferenceKey_5;
// System.Object System.ComponentModel.ReflectTypeDescriptionProvider::_intrinsicNullableKey
RuntimeObject * ____intrinsicNullableKey_6;
// System.Object System.ComponentModel.ReflectTypeDescriptionProvider::_dictionaryKey
RuntimeObject * ____dictionaryKey_7;
// System.Collections.Hashtable modreq(System.Runtime.CompilerServices.IsVolatile) System.ComponentModel.ReflectTypeDescriptionProvider::_attributeCache
Hashtable_t1853889766 * ____attributeCache_8;
// System.Guid System.ComponentModel.ReflectTypeDescriptionProvider::_extenderProviderKey
Guid_t ____extenderProviderKey_9;
// System.Guid System.ComponentModel.ReflectTypeDescriptionProvider::_extenderPropertiesKey
Guid_t ____extenderPropertiesKey_10;
// System.Guid System.ComponentModel.ReflectTypeDescriptionProvider::_extenderProviderPropertiesKey
Guid_t ____extenderProviderPropertiesKey_11;
// System.Type[] System.ComponentModel.ReflectTypeDescriptionProvider::_skipInterfaceAttributeList
TypeU5BU5D_t3940880105* ____skipInterfaceAttributeList_12;
// System.Object System.ComponentModel.ReflectTypeDescriptionProvider::_internalSyncObject
RuntimeObject * ____internalSyncObject_13;
public:
inline static int32_t get_offset_of__typeConstructor_3() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____typeConstructor_3)); }
inline TypeU5BU5D_t3940880105* get__typeConstructor_3() const { return ____typeConstructor_3; }
inline TypeU5BU5D_t3940880105** get_address_of__typeConstructor_3() { return &____typeConstructor_3; }
inline void set__typeConstructor_3(TypeU5BU5D_t3940880105* value)
{
____typeConstructor_3 = value;
Il2CppCodeGenWriteBarrier((&____typeConstructor_3), value);
}
inline static int32_t get_offset_of__intrinsicTypeConverters_4() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____intrinsicTypeConverters_4)); }
inline Hashtable_t1853889766 * get__intrinsicTypeConverters_4() const { return ____intrinsicTypeConverters_4; }
inline Hashtable_t1853889766 ** get_address_of__intrinsicTypeConverters_4() { return &____intrinsicTypeConverters_4; }
inline void set__intrinsicTypeConverters_4(Hashtable_t1853889766 * value)
{
____intrinsicTypeConverters_4 = value;
Il2CppCodeGenWriteBarrier((&____intrinsicTypeConverters_4), value);
}
inline static int32_t get_offset_of__intrinsicReferenceKey_5() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____intrinsicReferenceKey_5)); }
inline RuntimeObject * get__intrinsicReferenceKey_5() const { return ____intrinsicReferenceKey_5; }
inline RuntimeObject ** get_address_of__intrinsicReferenceKey_5() { return &____intrinsicReferenceKey_5; }
inline void set__intrinsicReferenceKey_5(RuntimeObject * value)
{
____intrinsicReferenceKey_5 = value;
Il2CppCodeGenWriteBarrier((&____intrinsicReferenceKey_5), value);
}
inline static int32_t get_offset_of__intrinsicNullableKey_6() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____intrinsicNullableKey_6)); }
inline RuntimeObject * get__intrinsicNullableKey_6() const { return ____intrinsicNullableKey_6; }
inline RuntimeObject ** get_address_of__intrinsicNullableKey_6() { return &____intrinsicNullableKey_6; }
inline void set__intrinsicNullableKey_6(RuntimeObject * value)
{
____intrinsicNullableKey_6 = value;
Il2CppCodeGenWriteBarrier((&____intrinsicNullableKey_6), value);
}
inline static int32_t get_offset_of__dictionaryKey_7() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____dictionaryKey_7)); }
inline RuntimeObject * get__dictionaryKey_7() const { return ____dictionaryKey_7; }
inline RuntimeObject ** get_address_of__dictionaryKey_7() { return &____dictionaryKey_7; }
inline void set__dictionaryKey_7(RuntimeObject * value)
{
____dictionaryKey_7 = value;
Il2CppCodeGenWriteBarrier((&____dictionaryKey_7), value);
}
inline static int32_t get_offset_of__attributeCache_8() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____attributeCache_8)); }
inline Hashtable_t1853889766 * get__attributeCache_8() const { return ____attributeCache_8; }
inline Hashtable_t1853889766 ** get_address_of__attributeCache_8() { return &____attributeCache_8; }
inline void set__attributeCache_8(Hashtable_t1853889766 * value)
{
____attributeCache_8 = value;
Il2CppCodeGenWriteBarrier((&____attributeCache_8), value);
}
inline static int32_t get_offset_of__extenderProviderKey_9() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____extenderProviderKey_9)); }
inline Guid_t get__extenderProviderKey_9() const { return ____extenderProviderKey_9; }
inline Guid_t * get_address_of__extenderProviderKey_9() { return &____extenderProviderKey_9; }
inline void set__extenderProviderKey_9(Guid_t value)
{
____extenderProviderKey_9 = value;
}
inline static int32_t get_offset_of__extenderPropertiesKey_10() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____extenderPropertiesKey_10)); }
inline Guid_t get__extenderPropertiesKey_10() const { return ____extenderPropertiesKey_10; }
inline Guid_t * get_address_of__extenderPropertiesKey_10() { return &____extenderPropertiesKey_10; }
inline void set__extenderPropertiesKey_10(Guid_t value)
{
____extenderPropertiesKey_10 = value;
}
inline static int32_t get_offset_of__extenderProviderPropertiesKey_11() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____extenderProviderPropertiesKey_11)); }
inline Guid_t get__extenderProviderPropertiesKey_11() const { return ____extenderProviderPropertiesKey_11; }
inline Guid_t * get_address_of__extenderProviderPropertiesKey_11() { return &____extenderProviderPropertiesKey_11; }
inline void set__extenderProviderPropertiesKey_11(Guid_t value)
{
____extenderProviderPropertiesKey_11 = value;
}
inline static int32_t get_offset_of__skipInterfaceAttributeList_12() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____skipInterfaceAttributeList_12)); }
inline TypeU5BU5D_t3940880105* get__skipInterfaceAttributeList_12() const { return ____skipInterfaceAttributeList_12; }
inline TypeU5BU5D_t3940880105** get_address_of__skipInterfaceAttributeList_12() { return &____skipInterfaceAttributeList_12; }
inline void set__skipInterfaceAttributeList_12(TypeU5BU5D_t3940880105* value)
{
____skipInterfaceAttributeList_12 = value;
Il2CppCodeGenWriteBarrier((&____skipInterfaceAttributeList_12), value);
}
inline static int32_t get_offset_of__internalSyncObject_13() { return static_cast<int32_t>(offsetof(ReflectTypeDescriptionProvider_t2247041319_StaticFields, ____internalSyncObject_13)); }
inline RuntimeObject * get__internalSyncObject_13() const { return ____internalSyncObject_13; }
inline RuntimeObject ** get_address_of__internalSyncObject_13() { return &____internalSyncObject_13; }
inline void set__internalSyncObject_13(RuntimeObject * value)
{
____internalSyncObject_13 = value;
Il2CppCodeGenWriteBarrier((&____internalSyncObject_13), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFLECTTYPEDESCRIPTIONPROVIDER_T2247041319_H
#ifndef SSLPROTOCOLS_T928472600_H
#define SSLPROTOCOLS_T928472600_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Authentication.SslProtocols
struct SslProtocols_t928472600
{
public:
// System.Int32 System.Security.Authentication.SslProtocols::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SslProtocols_t928472600, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SSLPROTOCOLS_T928472600_H
#ifndef BASENUMBERCONVERTER_T312147029_H
#define BASENUMBERCONVERTER_T312147029_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.BaseNumberConverter
struct BaseNumberConverter_t312147029 : public TypeConverter_t2249118273
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BASENUMBERCONVERTER_T312147029_H
#ifndef ENUMCONVERTER_T1688858217_H
#define ENUMCONVERTER_T1688858217_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EnumConverter
struct EnumConverter_t1688858217 : public TypeConverter_t2249118273
{
public:
// System.ComponentModel.TypeConverter/StandardValuesCollection System.ComponentModel.EnumConverter::values
StandardValuesCollection_t2184948248 * ___values_2;
// System.Type System.ComponentModel.EnumConverter::type
Type_t * ___type_3;
public:
inline static int32_t get_offset_of_values_2() { return static_cast<int32_t>(offsetof(EnumConverter_t1688858217, ___values_2)); }
inline StandardValuesCollection_t2184948248 * get_values_2() const { return ___values_2; }
inline StandardValuesCollection_t2184948248 ** get_address_of_values_2() { return &___values_2; }
inline void set_values_2(StandardValuesCollection_t2184948248 * value)
{
___values_2 = value;
Il2CppCodeGenWriteBarrier((&___values_2), value);
}
inline static int32_t get_offset_of_type_3() { return static_cast<int32_t>(offsetof(EnumConverter_t1688858217, ___type_3)); }
inline Type_t * get_type_3() const { return ___type_3; }
inline Type_t ** get_address_of_type_3() { return &___type_3; }
inline void set_type_3(Type_t * value)
{
___type_3 = value;
Il2CppCodeGenWriteBarrier((&___type_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ENUMCONVERTER_T1688858217_H
#ifndef TIMESPANCONVERTER_T3504031848_H
#define TIMESPANCONVERTER_T3504031848_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.TimeSpanConverter
struct TimeSpanConverter_t3504031848 : public TypeConverter_t2249118273
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TIMESPANCONVERTER_T3504031848_H
#ifndef EXPANDABLEOBJECTCONVERTER_T420832579_H
#define EXPANDABLEOBJECTCONVERTER_T420832579_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ExpandableObjectConverter
struct ExpandableObjectConverter_t420832579 : public TypeConverter_t2249118273
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXPANDABLEOBJECTCONVERTER_T420832579_H
#ifndef MULTICASTDELEGATE_T_H
#define MULTICASTDELEGATE_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.MulticastDelegate
struct MulticastDelegate_t : public Delegate_t1188392813
{
public:
// System.Delegate[] System.MulticastDelegate::delegates
DelegateU5BU5D_t1703627840* ___delegates_11;
public:
inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); }
inline DelegateU5BU5D_t1703627840* get_delegates_11() const { return ___delegates_11; }
inline DelegateU5BU5D_t1703627840** get_address_of_delegates_11() { return &___delegates_11; }
inline void set_delegates_11(DelegateU5BU5D_t1703627840* value)
{
___delegates_11 = value;
Il2CppCodeGenWriteBarrier((&___delegates_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.MulticastDelegate
struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t1188392813_marshaled_pinvoke
{
DelegateU5BU5D_t1703627840* ___delegates_11;
};
// Native definition for COM marshalling of System.MulticastDelegate
struct MulticastDelegate_t_marshaled_com : public Delegate_t1188392813_marshaled_com
{
DelegateU5BU5D_t1703627840* ___delegates_11;
};
#endif // MULTICASTDELEGATE_T_H
#ifndef REFERENCECONVERTER_T1811933861_H
#define REFERENCECONVERTER_T1811933861_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.ReferenceConverter
struct ReferenceConverter_t1811933861 : public TypeConverter_t2249118273
{
public:
// System.Type System.ComponentModel.ReferenceConverter::type
Type_t * ___type_3;
public:
inline static int32_t get_offset_of_type_3() { return static_cast<int32_t>(offsetof(ReferenceConverter_t1811933861, ___type_3)); }
inline Type_t * get_type_3() const { return ___type_3; }
inline Type_t ** get_address_of_type_3() { return &___type_3; }
inline void set_type_3(Type_t * value)
{
___type_3 = value;
Il2CppCodeGenWriteBarrier((&___type_3), value);
}
};
struct ReferenceConverter_t1811933861_StaticFields
{
public:
// System.String System.ComponentModel.ReferenceConverter::none
String_t* ___none_2;
public:
inline static int32_t get_offset_of_none_2() { return static_cast<int32_t>(offsetof(ReferenceConverter_t1811933861_StaticFields, ___none_2)); }
inline String_t* get_none_2() const { return ___none_2; }
inline String_t** get_address_of_none_2() { return &___none_2; }
inline void set_none_2(String_t* value)
{
___none_2 = value;
Il2CppCodeGenWriteBarrier((&___none_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFERENCECONVERTER_T1811933861_H
#ifndef DESIGNERSERIALIZATIONVISIBILITYATTRIBUTE_T4084246596_H
#define DESIGNERSERIALIZATIONVISIBILITYATTRIBUTE_T4084246596_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DesignerSerializationVisibilityAttribute
struct DesignerSerializationVisibilityAttribute_t4084246596 : public Attribute_t861562559
{
public:
// System.ComponentModel.DesignerSerializationVisibility System.ComponentModel.DesignerSerializationVisibilityAttribute::visibility
int32_t ___visibility_4;
public:
inline static int32_t get_offset_of_visibility_4() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_t4084246596, ___visibility_4)); }
inline int32_t get_visibility_4() const { return ___visibility_4; }
inline int32_t* get_address_of_visibility_4() { return &___visibility_4; }
inline void set_visibility_4(int32_t value)
{
___visibility_4 = value;
}
};
struct DesignerSerializationVisibilityAttribute_t4084246596_StaticFields
{
public:
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Content
DesignerSerializationVisibilityAttribute_t4084246596 * ___Content_0;
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Hidden
DesignerSerializationVisibilityAttribute_t4084246596 * ___Hidden_1;
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Visible
DesignerSerializationVisibilityAttribute_t4084246596 * ___Visible_2;
// System.ComponentModel.DesignerSerializationVisibilityAttribute System.ComponentModel.DesignerSerializationVisibilityAttribute::Default
DesignerSerializationVisibilityAttribute_t4084246596 * ___Default_3;
public:
inline static int32_t get_offset_of_Content_0() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_t4084246596_StaticFields, ___Content_0)); }
inline DesignerSerializationVisibilityAttribute_t4084246596 * get_Content_0() const { return ___Content_0; }
inline DesignerSerializationVisibilityAttribute_t4084246596 ** get_address_of_Content_0() { return &___Content_0; }
inline void set_Content_0(DesignerSerializationVisibilityAttribute_t4084246596 * value)
{
___Content_0 = value;
Il2CppCodeGenWriteBarrier((&___Content_0), value);
}
inline static int32_t get_offset_of_Hidden_1() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_t4084246596_StaticFields, ___Hidden_1)); }
inline DesignerSerializationVisibilityAttribute_t4084246596 * get_Hidden_1() const { return ___Hidden_1; }
inline DesignerSerializationVisibilityAttribute_t4084246596 ** get_address_of_Hidden_1() { return &___Hidden_1; }
inline void set_Hidden_1(DesignerSerializationVisibilityAttribute_t4084246596 * value)
{
___Hidden_1 = value;
Il2CppCodeGenWriteBarrier((&___Hidden_1), value);
}
inline static int32_t get_offset_of_Visible_2() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_t4084246596_StaticFields, ___Visible_2)); }
inline DesignerSerializationVisibilityAttribute_t4084246596 * get_Visible_2() const { return ___Visible_2; }
inline DesignerSerializationVisibilityAttribute_t4084246596 ** get_address_of_Visible_2() { return &___Visible_2; }
inline void set_Visible_2(DesignerSerializationVisibilityAttribute_t4084246596 * value)
{
___Visible_2 = value;
Il2CppCodeGenWriteBarrier((&___Visible_2), value);
}
inline static int32_t get_offset_of_Default_3() { return static_cast<int32_t>(offsetof(DesignerSerializationVisibilityAttribute_t4084246596_StaticFields, ___Default_3)); }
inline DesignerSerializationVisibilityAttribute_t4084246596 * get_Default_3() const { return ___Default_3; }
inline DesignerSerializationVisibilityAttribute_t4084246596 ** get_address_of_Default_3() { return &___Default_3; }
inline void set_Default_3(DesignerSerializationVisibilityAttribute_t4084246596 * value)
{
___Default_3 = value;
Il2CppCodeGenWriteBarrier((&___Default_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DESIGNERSERIALIZATIONVISIBILITYATTRIBUTE_T4084246596_H
#ifndef EDITORBROWSABLEATTRIBUTE_T1475454531_H
#define EDITORBROWSABLEATTRIBUTE_T1475454531_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.EditorBrowsableAttribute
struct EditorBrowsableAttribute_t1475454531 : public Attribute_t861562559
{
public:
// System.ComponentModel.EditorBrowsableState System.ComponentModel.EditorBrowsableAttribute::browsableState
int32_t ___browsableState_0;
public:
inline static int32_t get_offset_of_browsableState_0() { return static_cast<int32_t>(offsetof(EditorBrowsableAttribute_t1475454531, ___browsableState_0)); }
inline int32_t get_browsableState_0() const { return ___browsableState_0; }
inline int32_t* get_address_of_browsableState_0() { return &___browsableState_0; }
inline void set_browsableState_0(int32_t value)
{
___browsableState_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EDITORBROWSABLEATTRIBUTE_T1475454531_H
#ifndef WIN32EXCEPTION_T3234146298_H
#define WIN32EXCEPTION_T3234146298_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Win32Exception
struct Win32Exception_t3234146298 : public ExternalException_t3544951457
{
public:
// System.Int32 System.ComponentModel.Win32Exception::nativeErrorCode
int32_t ___nativeErrorCode_17;
public:
inline static int32_t get_offset_of_nativeErrorCode_17() { return static_cast<int32_t>(offsetof(Win32Exception_t3234146298, ___nativeErrorCode_17)); }
inline int32_t get_nativeErrorCode_17() const { return ___nativeErrorCode_17; }
inline int32_t* get_address_of_nativeErrorCode_17() { return &___nativeErrorCode_17; }
inline void set_nativeErrorCode_17(int32_t value)
{
___nativeErrorCode_17 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WIN32EXCEPTION_T3234146298_H
#ifndef INVALIDENUMARGUMENTEXCEPTION_T2634129013_H
#define INVALIDENUMARGUMENTEXCEPTION_T2634129013_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.InvalidEnumArgumentException
struct InvalidEnumArgumentException_t2634129013 : public ArgumentException_t132251570
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INVALIDENUMARGUMENTEXCEPTION_T2634129013_H
#ifndef WEAKHASHTABLE_T3533205710_H
#define WEAKHASHTABLE_T3533205710_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.WeakHashtable
struct WeakHashtable_t3533205710 : public Hashtable_t1853889766
{
public:
public:
};
struct WeakHashtable_t3533205710_StaticFields
{
public:
// System.Collections.IEqualityComparer System.ComponentModel.WeakHashtable::_comparer
RuntimeObject* ____comparer_21;
public:
inline static int32_t get_offset_of__comparer_21() { return static_cast<int32_t>(offsetof(WeakHashtable_t3533205710_StaticFields, ____comparer_21)); }
inline RuntimeObject* get__comparer_21() const { return ____comparer_21; }
inline RuntimeObject** get_address_of__comparer_21() { return &____comparer_21; }
inline void set__comparer_21(RuntimeObject* value)
{
____comparer_21 = value;
Il2CppCodeGenWriteBarrier((&____comparer_21), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WEAKHASHTABLE_T3533205710_H
#ifndef NULLABLECONVERTER_T1985728604_H
#define NULLABLECONVERTER_T1985728604_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.NullableConverter
struct NullableConverter_t1985728604 : public TypeConverter_t2249118273
{
public:
// System.Type System.ComponentModel.NullableConverter::nullableType
Type_t * ___nullableType_2;
// System.Type System.ComponentModel.NullableConverter::simpleType
Type_t * ___simpleType_3;
// System.ComponentModel.TypeConverter System.ComponentModel.NullableConverter::simpleTypeConverter
TypeConverter_t2249118273 * ___simpleTypeConverter_4;
public:
inline static int32_t get_offset_of_nullableType_2() { return static_cast<int32_t>(offsetof(NullableConverter_t1985728604, ___nullableType_2)); }
inline Type_t * get_nullableType_2() const { return ___nullableType_2; }
inline Type_t ** get_address_of_nullableType_2() { return &___nullableType_2; }
inline void set_nullableType_2(Type_t * value)
{
___nullableType_2 = value;
Il2CppCodeGenWriteBarrier((&___nullableType_2), value);
}
inline static int32_t get_offset_of_simpleType_3() { return static_cast<int32_t>(offsetof(NullableConverter_t1985728604, ___simpleType_3)); }
inline Type_t * get_simpleType_3() const { return ___simpleType_3; }
inline Type_t ** get_address_of_simpleType_3() { return &___simpleType_3; }
inline void set_simpleType_3(Type_t * value)
{
___simpleType_3 = value;
Il2CppCodeGenWriteBarrier((&___simpleType_3), value);
}
inline static int32_t get_offset_of_simpleTypeConverter_4() { return static_cast<int32_t>(offsetof(NullableConverter_t1985728604, ___simpleTypeConverter_4)); }
inline TypeConverter_t2249118273 * get_simpleTypeConverter_4() const { return ___simpleTypeConverter_4; }
inline TypeConverter_t2249118273 ** get_address_of_simpleTypeConverter_4() { return &___simpleTypeConverter_4; }
inline void set_simpleTypeConverter_4(TypeConverter_t2249118273 * value)
{
___simpleTypeConverter_4 = value;
Il2CppCodeGenWriteBarrier((&___simpleTypeConverter_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // NULLABLECONVERTER_T1985728604_H
#ifndef OID_T3552120260_H
#define OID_T3552120260_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.Oid
struct Oid_t3552120260 : public RuntimeObject
{
public:
// System.String System.Security.Cryptography.Oid::m_value
String_t* ___m_value_0;
// System.String System.Security.Cryptography.Oid::m_friendlyName
String_t* ___m_friendlyName_1;
// System.Security.Cryptography.OidGroup System.Security.Cryptography.Oid::m_group
int32_t ___m_group_2;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Oid_t3552120260, ___m_value_0)); }
inline String_t* get_m_value_0() const { return ___m_value_0; }
inline String_t** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(String_t* value)
{
___m_value_0 = value;
Il2CppCodeGenWriteBarrier((&___m_value_0), value);
}
inline static int32_t get_offset_of_m_friendlyName_1() { return static_cast<int32_t>(offsetof(Oid_t3552120260, ___m_friendlyName_1)); }
inline String_t* get_m_friendlyName_1() const { return ___m_friendlyName_1; }
inline String_t** get_address_of_m_friendlyName_1() { return &___m_friendlyName_1; }
inline void set_m_friendlyName_1(String_t* value)
{
___m_friendlyName_1 = value;
Il2CppCodeGenWriteBarrier((&___m_friendlyName_1), value);
}
inline static int32_t get_offset_of_m_group_2() { return static_cast<int32_t>(offsetof(Oid_t3552120260, ___m_group_2)); }
inline int32_t get_m_group_2() const { return ___m_group_2; }
inline int32_t* get_address_of_m_group_2() { return &___m_group_2; }
inline void set_m_group_2(int32_t value)
{
___m_group_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // OID_T3552120260_H
#ifndef GUIDCONVERTER_T3396672461_H
#define GUIDCONVERTER_T3396672461_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.GuidConverter
struct GuidConverter_t3396672461 : public TypeConverter_t2249118273
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GUIDCONVERTER_T3396672461_H
#ifndef STRINGCONVERTER_T3216726494_H
#define STRINGCONVERTER_T3216726494_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.StringConverter
struct StringConverter_t3216726494 : public TypeConverter_t2249118273
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRINGCONVERTER_T3216726494_H
#ifndef DOUBLECONVERTER_T805142290_H
#define DOUBLECONVERTER_T805142290_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.DoubleConverter
struct DoubleConverter_t805142290 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DOUBLECONVERTER_T805142290_H
#ifndef INT32CONVERTER_T677227065_H
#define INT32CONVERTER_T677227065_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Int32Converter
struct Int32Converter_t677227065 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32CONVERTER_T677227065_H
#ifndef INT16CONVERTER_T1119562914_H
#define INT16CONVERTER_T1119562914_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Int16Converter
struct Int16Converter_t1119562914 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT16CONVERTER_T1119562914_H
#ifndef SINGLECONVERTER_T902207630_H
#define SINGLECONVERTER_T902207630_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.SingleConverter
struct SingleConverter_t902207630 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SINGLECONVERTER_T902207630_H
#ifndef INT64CONVERTER_T1092099567_H
#define INT64CONVERTER_T1092099567_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.Int64Converter
struct Int64Converter_t1092099567 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT64CONVERTER_T1092099567_H
#ifndef UINT16CONVERTER_T819459975_H
#define UINT16CONVERTER_T819459975_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.UInt16Converter
struct UInt16Converter_t819459975 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UINT16CONVERTER_T819459975_H
#ifndef PROPERTYCHANGEDEVENTHANDLER_T3836340606_H
#define PROPERTYCHANGEDEVENTHANDLER_T3836340606_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.PropertyChangedEventHandler
struct PropertyChangedEventHandler_t3836340606 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// COM Callable Wrapper interface definition for System.ComponentModel.PropertyChangedEventHandler
struct IPropertyChangedEventHandler_t3836340606_ComCallableWrapper : Il2CppIUnknown
{
static const Il2CppGuid IID;
virtual il2cpp_hresult_t STDCALL Invoke(Il2CppIInspectable* ___sender0, PropertyChangedEventArgs_t3313059048 * ___e1) = 0;
};
#endif // PROPERTYCHANGEDEVENTHANDLER_T3836340606_H
#ifndef SBYTECONVERTER_T2970182448_H
#define SBYTECONVERTER_T2970182448_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.SByteConverter
struct SByteConverter_t2970182448 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SBYTECONVERTER_T2970182448_H
#ifndef REFRESHEVENTHANDLER_T3637242902_H
#define REFRESHEVENTHANDLER_T3637242902_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.RefreshEventHandler
struct RefreshEventHandler_t3637242902 : public MulticastDelegate_t
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // REFRESHEVENTHANDLER_T3637242902_H
#ifndef UINT32CONVERTER_T3472493373_H
#define UINT32CONVERTER_T3472493373_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.UInt32Converter
struct UInt32Converter_t3472493373 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UINT32CONVERTER_T3472493373_H
#ifndef UINT64CONVERTER_T4189949036_H
#define UINT64CONVERTER_T4189949036_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ComponentModel.UInt64Converter
struct UInt64Converter_t4189949036 : public BaseNumberConverter_t312147029
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UINT64CONVERTER_T4189949036_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2000 = { sizeof (DesignerAttribute_t2079716647), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2000[3] =
{
DesignerAttribute_t2079716647::get_offset_of_designerTypeName_0(),
DesignerAttribute_t2079716647::get_offset_of_designerBaseTypeName_1(),
DesignerAttribute_t2079716647::get_offset_of_typeId_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2001 = { sizeof (DesignerCategoryAttribute_t2912925731), -1, sizeof(DesignerCategoryAttribute_t2912925731_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2001[6] =
{
DesignerCategoryAttribute_t2912925731::get_offset_of_category_0(),
DesignerCategoryAttribute_t2912925731::get_offset_of_typeId_1(),
DesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Component_2(),
DesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Default_3(),
DesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Form_4(),
DesignerCategoryAttribute_t2912925731_StaticFields::get_offset_of_Generic_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2002 = { sizeof (DesignerSerializationVisibility_t3481291396)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2002[4] =
{
DesignerSerializationVisibility_t3481291396::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2003 = { sizeof (DesignerSerializationVisibilityAttribute_t4084246596), -1, sizeof(DesignerSerializationVisibilityAttribute_t4084246596_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2003[5] =
{
DesignerSerializationVisibilityAttribute_t4084246596_StaticFields::get_offset_of_Content_0(),
DesignerSerializationVisibilityAttribute_t4084246596_StaticFields::get_offset_of_Hidden_1(),
DesignerSerializationVisibilityAttribute_t4084246596_StaticFields::get_offset_of_Visible_2(),
DesignerSerializationVisibilityAttribute_t4084246596_StaticFields::get_offset_of_Default_3(),
DesignerSerializationVisibilityAttribute_t4084246596::get_offset_of_visibility_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2004 = { sizeof (DoubleConverter_t805142290), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2005 = { sizeof (EditorAttribute_t1332199665), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2005[3] =
{
EditorAttribute_t1332199665::get_offset_of_baseTypeName_0(),
EditorAttribute_t1332199665::get_offset_of_typeName_1(),
EditorAttribute_t1332199665::get_offset_of_typeId_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2006 = { sizeof (EditorBrowsableAttribute_t1475454531), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2006[1] =
{
EditorBrowsableAttribute_t1475454531::get_offset_of_browsableState_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2007 = { sizeof (EditorBrowsableState_t2839071299)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2007[4] =
{
EditorBrowsableState_t2839071299::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2008 = { sizeof (EnumConverter_t1688858217), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2008[2] =
{
EnumConverter_t1688858217::get_offset_of_values_2(),
EnumConverter_t1688858217::get_offset_of_type_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2009 = { sizeof (EventDescriptor_t88602298), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2010 = { sizeof (EventDescriptorCollection_t2278158832), -1, sizeof(EventDescriptorCollection_t2278158832_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2010[8] =
{
EventDescriptorCollection_t2278158832::get_offset_of_events_0(),
EventDescriptorCollection_t2278158832::get_offset_of_namedSort_1(),
EventDescriptorCollection_t2278158832::get_offset_of_comparer_2(),
EventDescriptorCollection_t2278158832::get_offset_of_eventsOwned_3(),
EventDescriptorCollection_t2278158832::get_offset_of_needSort_4(),
EventDescriptorCollection_t2278158832::get_offset_of_eventCount_5(),
EventDescriptorCollection_t2278158832::get_offset_of_readOnly_6(),
EventDescriptorCollection_t2278158832_StaticFields::get_offset_of_Empty_7(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2011 = { sizeof (EventHandlerList_t1108123056), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2011[2] =
{
EventHandlerList_t1108123056::get_offset_of_head_0(),
EventHandlerList_t1108123056::get_offset_of_parent_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2012 = { sizeof (ListEntry_t2424989506), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2012[3] =
{
ListEntry_t2424989506::get_offset_of_next_0(),
ListEntry_t2424989506::get_offset_of_key_1(),
ListEntry_t2424989506::get_offset_of_handler_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2013 = { sizeof (ExpandableObjectConverter_t420832579), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2014 = { sizeof (ExtenderProvidedPropertyAttribute_t3771163592), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2014[3] =
{
ExtenderProvidedPropertyAttribute_t3771163592::get_offset_of_extenderProperty_0(),
ExtenderProvidedPropertyAttribute_t3771163592::get_offset_of_provider_1(),
ExtenderProvidedPropertyAttribute_t3771163592::get_offset_of_receiverType_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2015 = { sizeof (GuidConverter_t3396672461), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2016 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2017 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2018 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2019 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2020 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2021 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2022 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2023 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2024 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2025 = { sizeof (InstallerTypeAttribute_t3233088727), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2025[1] =
{
InstallerTypeAttribute_t3233088727::get_offset_of__typeName_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2026 = { sizeof (Int16Converter_t1119562914), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2027 = { sizeof (Int32Converter_t677227065), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2028 = { sizeof (Int64Converter_t1092099567), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2029 = { sizeof (InvalidEnumArgumentException_t2634129013), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2030 = { sizeof (MemberDescriptor_t3815403747), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2030[11] =
{
MemberDescriptor_t3815403747::get_offset_of_name_0(),
MemberDescriptor_t3815403747::get_offset_of_nameHash_1(),
MemberDescriptor_t3815403747::get_offset_of_attributeCollection_2(),
MemberDescriptor_t3815403747::get_offset_of_attributes_3(),
MemberDescriptor_t3815403747::get_offset_of_originalAttributes_4(),
MemberDescriptor_t3815403747::get_offset_of_attributesFiltered_5(),
MemberDescriptor_t3815403747::get_offset_of_attributesFilled_6(),
MemberDescriptor_t3815403747::get_offset_of_metadataVersion_7(),
MemberDescriptor_t3815403747::get_offset_of_category_8(),
MemberDescriptor_t3815403747::get_offset_of_description_9(),
MemberDescriptor_t3815403747::get_offset_of_lockCookie_10(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2031 = { sizeof (NullableConverter_t1985728604), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2031[3] =
{
NullableConverter_t1985728604::get_offset_of_nullableType_2(),
NullableConverter_t1985728604::get_offset_of_simpleType_3(),
NullableConverter_t1985728604::get_offset_of_simpleTypeConverter_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2032 = { sizeof (PropertyChangedEventArgs_t3313059048), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2032[1] =
{
PropertyChangedEventArgs_t3313059048::get_offset_of_propertyName_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2033 = { sizeof (PropertyChangedEventHandler_t3836340606), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2034 = { sizeof (PropertyDescriptor_t3244362832), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2034[4] =
{
PropertyDescriptor_t3244362832::get_offset_of_converter_11(),
PropertyDescriptor_t3244362832::get_offset_of_editors_12(),
PropertyDescriptor_t3244362832::get_offset_of_editorTypes_13(),
PropertyDescriptor_t3244362832::get_offset_of_editorCount_14(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2035 = { sizeof (PropertyDescriptorCollection_t4164928659), -1, sizeof(PropertyDescriptorCollection_t4164928659_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2035[10] =
{
PropertyDescriptorCollection_t4164928659_StaticFields::get_offset_of_Empty_0(),
PropertyDescriptorCollection_t4164928659::get_offset_of_cachedFoundProperties_1(),
PropertyDescriptorCollection_t4164928659::get_offset_of_cachedIgnoreCase_2(),
PropertyDescriptorCollection_t4164928659::get_offset_of_properties_3(),
PropertyDescriptorCollection_t4164928659::get_offset_of_propCount_4(),
PropertyDescriptorCollection_t4164928659::get_offset_of_namedSort_5(),
PropertyDescriptorCollection_t4164928659::get_offset_of_comparer_6(),
PropertyDescriptorCollection_t4164928659::get_offset_of_propsOwned_7(),
PropertyDescriptorCollection_t4164928659::get_offset_of_needSort_8(),
PropertyDescriptorCollection_t4164928659::get_offset_of_readOnly_9(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2036 = { sizeof (PropertyDescriptorEnumerator_t2627442857), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2036[2] =
{
PropertyDescriptorEnumerator_t2627442857::get_offset_of_owner_0(),
PropertyDescriptorEnumerator_t2627442857::get_offset_of_index_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2037 = { sizeof (ReadOnlyAttribute_t1907441566), -1, sizeof(ReadOnlyAttribute_t1907441566_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2037[4] =
{
ReadOnlyAttribute_t1907441566::get_offset_of_isReadOnly_0(),
ReadOnlyAttribute_t1907441566_StaticFields::get_offset_of_Yes_1(),
ReadOnlyAttribute_t1907441566_StaticFields::get_offset_of_No_2(),
ReadOnlyAttribute_t1907441566_StaticFields::get_offset_of_Default_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2038 = { sizeof (RecommendedAsConfigurableAttribute_t279829077), -1, sizeof(RecommendedAsConfigurableAttribute_t279829077_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2038[4] =
{
RecommendedAsConfigurableAttribute_t279829077::get_offset_of_recommendedAsConfigurable_0(),
RecommendedAsConfigurableAttribute_t279829077_StaticFields::get_offset_of_No_1(),
RecommendedAsConfigurableAttribute_t279829077_StaticFields::get_offset_of_Yes_2(),
RecommendedAsConfigurableAttribute_t279829077_StaticFields::get_offset_of_Default_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2039 = { sizeof (ReferenceConverter_t1811933861), -1, sizeof(ReferenceConverter_t1811933861_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2039[2] =
{
ReferenceConverter_t1811933861_StaticFields::get_offset_of_none_2(),
ReferenceConverter_t1811933861::get_offset_of_type_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2040 = { sizeof (ReferenceComparer_t1826665674), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2040[1] =
{
ReferenceComparer_t1826665674::get_offset_of_converter_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2041 = { sizeof (ReflectTypeDescriptionProvider_t2247041319), -1, sizeof(ReflectTypeDescriptionProvider_t2247041319_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2041[12] =
{
ReflectTypeDescriptionProvider_t2247041319::get_offset_of__typeData_2(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__typeConstructor_3(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__intrinsicTypeConverters_4(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__intrinsicReferenceKey_5(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__intrinsicNullableKey_6(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__dictionaryKey_7(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__attributeCache_8(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__extenderProviderKey_9(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__extenderPropertiesKey_10(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__extenderProviderPropertiesKey_11(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__skipInterfaceAttributeList_12(),
ReflectTypeDescriptionProvider_t2247041319_StaticFields::get_offset_of__internalSyncObject_13(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2042 = { sizeof (ReflectedTypeData_t1775264331), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2042[8] =
{
ReflectedTypeData_t1775264331::get_offset_of__type_0(),
ReflectedTypeData_t1775264331::get_offset_of__attributes_1(),
ReflectedTypeData_t1775264331::get_offset_of__events_2(),
ReflectedTypeData_t1775264331::get_offset_of__properties_3(),
ReflectedTypeData_t1775264331::get_offset_of__converter_4(),
ReflectedTypeData_t1775264331::get_offset_of__editors_5(),
ReflectedTypeData_t1775264331::get_offset_of__editorTypes_6(),
ReflectedTypeData_t1775264331::get_offset_of__editorCount_7(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2043 = { sizeof (RefreshEventArgs_t9288056), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2043[1] =
{
RefreshEventArgs_t9288056::get_offset_of_typeChanged_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2044 = { sizeof (RefreshEventHandler_t3637242902), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2045 = { sizeof (SByteConverter_t2970182448), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2046 = { sizeof (SettingsBindableAttribute_t3884869596), -1, sizeof(SettingsBindableAttribute_t3884869596_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2046[3] =
{
SettingsBindableAttribute_t3884869596_StaticFields::get_offset_of_Yes_0(),
SettingsBindableAttribute_t3884869596_StaticFields::get_offset_of_No_1(),
SettingsBindableAttribute_t3884869596::get_offset_of__bindable_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2047 = { sizeof (SingleConverter_t902207630), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2048 = { sizeof (StringConverter_t3216726494), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2049 = { sizeof (TimeSpanConverter_t3504031848), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2050 = { sizeof (TypeConverter_t2249118273), -1, sizeof(TypeConverter_t2249118273_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2050[2] =
{
0,
TypeConverter_t2249118273_StaticFields::get_offset_of_useCompatibleTypeConversion_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2051 = { sizeof (StandardValuesCollection_t2184948248), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2051[2] =
{
StandardValuesCollection_t2184948248::get_offset_of_values_0(),
StandardValuesCollection_t2184948248::get_offset_of_valueArray_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2052 = { sizeof (TypeConverterAttribute_t3271584429), -1, sizeof(TypeConverterAttribute_t3271584429_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2052[2] =
{
TypeConverterAttribute_t3271584429::get_offset_of_typeName_0(),
TypeConverterAttribute_t3271584429_StaticFields::get_offset_of_Default_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2053 = { sizeof (TypeDescriptionProvider_t3232077895), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2053[2] =
{
TypeDescriptionProvider_t3232077895::get_offset_of__parent_0(),
TypeDescriptionProvider_t3232077895::get_offset_of__emptyDescriptor_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2054 = { sizeof (EmptyCustomTypeDescriptor_t4007109994), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2055 = { sizeof (TypeDescriptionProviderAttribute_t2619663527), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2055[1] =
{
TypeDescriptionProviderAttribute_t2619663527::get_offset_of__typeName_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2056 = { sizeof (TypeDescriptor_t3066613587), -1, sizeof(TypeDescriptor_t3066613587_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2056[12] =
{
TypeDescriptor_t3066613587_StaticFields::get_offset_of__providerTable_0(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__providerTypeTable_1(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__defaultProviders_2(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__metadataVersion_3(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__collisionIndex_4(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of_TraceDescriptor_5(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__pipelineInitializeKeys_6(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__pipelineMergeKeys_7(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__pipelineFilterKeys_8(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__pipelineAttributeFilterKeys_9(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of__internalSyncObject_10(),
TypeDescriptor_t3066613587_StaticFields::get_offset_of_Refreshed_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2057 = { sizeof (FilterCacheItem_t1189670310), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2057[2] =
{
FilterCacheItem_t1189670310::get_offset_of__filterService_0(),
FilterCacheItem_t1189670310::get_offset_of_FilteredMembers_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2058 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2059 = { sizeof (MemberDescriptorComparer_t457940793), -1, sizeof(MemberDescriptorComparer_t457940793_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2059[1] =
{
MemberDescriptorComparer_t457940793_StaticFields::get_offset_of_Instance_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2060 = { sizeof (MergedTypeDescriptor_t3526482283), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2060[2] =
{
MergedTypeDescriptor_t3526482283::get_offset_of__primary_0(),
MergedTypeDescriptor_t3526482283::get_offset_of__secondary_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2061 = { sizeof (TypeDescriptionNode_t3022060204), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2061[2] =
{
TypeDescriptionNode_t3022060204::get_offset_of_Next_2(),
TypeDescriptionNode_t3022060204::get_offset_of_Provider_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2062 = { sizeof (DefaultExtendedTypeDescriptor_t1757997412)+ sizeof (RuntimeObject), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2062[2] =
{
DefaultExtendedTypeDescriptor_t1757997412::get_offset_of__node_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
DefaultExtendedTypeDescriptor_t1757997412::get_offset_of__instance_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2063 = { sizeof (DefaultTypeDescriptor_t4148937846)+ sizeof (RuntimeObject), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2063[3] =
{
DefaultTypeDescriptor_t4148937846::get_offset_of__node_0() + static_cast<int32_t>(sizeof(RuntimeObject)),
DefaultTypeDescriptor_t4148937846::get_offset_of__objectType_1() + static_cast<int32_t>(sizeof(RuntimeObject)),
DefaultTypeDescriptor_t4148937846::get_offset_of__instance_2() + static_cast<int32_t>(sizeof(RuntimeObject)),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2064 = { sizeof (TypeDescriptorComObject_t50518439), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2065 = { sizeof (TypeDescriptorInterface_t3054885090), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2066 = { sizeof (UInt16Converter_t819459975), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2067 = { sizeof (UInt32Converter_t3472493373), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2068 = { sizeof (UInt64Converter_t4189949036), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2069 = { sizeof (Win32Exception_t3234146298), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2069[1] =
{
Win32Exception_t3234146298::get_offset_of_nativeErrorCode_17(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2070 = { sizeof (BaseNumberConverter_t312147029), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2071 = { sizeof (NotifyParentPropertyAttribute_t1405421815), -1, sizeof(NotifyParentPropertyAttribute_t1405421815_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2071[4] =
{
NotifyParentPropertyAttribute_t1405421815_StaticFields::get_offset_of_Yes_0(),
NotifyParentPropertyAttribute_t1405421815_StaticFields::get_offset_of_No_1(),
NotifyParentPropertyAttribute_t1405421815_StaticFields::get_offset_of_Default_2(),
NotifyParentPropertyAttribute_t1405421815::get_offset_of_notifyParent_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2072 = { sizeof (ToolboxItemAttribute_t243705872), -1, sizeof(ToolboxItemAttribute_t243705872_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2072[3] =
{
ToolboxItemAttribute_t243705872::get_offset_of_toolboxItemTypeName_0(),
ToolboxItemAttribute_t243705872_StaticFields::get_offset_of_Default_1(),
ToolboxItemAttribute_t243705872_StaticFields::get_offset_of_None_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2073 = { sizeof (WeakHashtable_t3533205710), -1, sizeof(WeakHashtable_t3533205710_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2073[1] =
{
WeakHashtable_t3533205710_StaticFields::get_offset_of__comparer_21(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2074 = { sizeof (WeakKeyComparer_t448163292), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2075 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2076 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2077 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2078 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2079 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2080 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2081 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2082 = { sizeof (DesignerSerializerAttribute_t1570548024), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2082[3] =
{
DesignerSerializerAttribute_t1570548024::get_offset_of_serializerTypeName_0(),
DesignerSerializerAttribute_t1570548024::get_offset_of_serializerBaseTypeName_1(),
DesignerSerializerAttribute_t1570548024::get_offset_of_typeId_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2083 = { sizeof (InstanceDescriptor_t657473484), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2083[3] =
{
InstanceDescriptor_t657473484::get_offset_of_member_0(),
InstanceDescriptor_t657473484::get_offset_of_arguments_1(),
InstanceDescriptor_t657473484::get_offset_of_isComplete_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2084 = { sizeof (RootDesignerSerializerAttribute_t3074689342), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2084[4] =
{
RootDesignerSerializerAttribute_t3074689342::get_offset_of_reloadable_0(),
RootDesignerSerializerAttribute_t3074689342::get_offset_of_serializerTypeName_1(),
RootDesignerSerializerAttribute_t3074689342::get_offset_of_serializerBaseTypeName_2(),
RootDesignerSerializerAttribute_t3074689342::get_offset_of_typeId_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2085 = { sizeof (AuthenticationException_t1221369422), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2086 = { sizeof (SslProtocols_t928472600)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2086[8] =
{
SslProtocols_t928472600::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2087 = { sizeof (OidGroup_t395834848)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2087[12] =
{
OidGroup_t395834848::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2088 = { sizeof (Oid_t3552120260), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2088[3] =
{
Oid_t3552120260::get_offset_of_m_value_0(),
Oid_t3552120260::get_offset_of_m_friendlyName_1(),
Oid_t3552120260::get_offset_of_m_group_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2089 = { sizeof (OidCollection_t4234766844), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2089[1] =
{
OidCollection_t4234766844::get_offset_of_m_list_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2090 = { sizeof (OidEnumerator_t899373898), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2090[2] =
{
OidEnumerator_t899373898::get_offset_of_m_oids_0(),
OidEnumerator_t899373898::get_offset_of_m_current_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2091 = { sizeof (CAPI_t4202866366), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2092 = { sizeof (AsnDecodeStatus_t788588755)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2092[7] =
{
AsnDecodeStatus_t788588755::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2093 = { sizeof (AsnEncodedData_t382354011), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2093[2] =
{
AsnEncodedData_t382354011::get_offset_of__oid_0(),
AsnEncodedData_t382354011::get_offset_of__raw_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2094 = { sizeof (OpenFlags_t968238685)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2094[6] =
{
OpenFlags_t968238685::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2095 = { sizeof (StoreLocation_t2864310644)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2095[3] =
{
StoreLocation_t2864310644::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2096 = { sizeof (StoreName_t1492274484)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2096[9] =
{
StoreName_t1492274484::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2097 = { sizeof (X500DistinguishedNameFlags_t254051580)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2097[11] =
{
X500DistinguishedNameFlags_t254051580::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2098 = { sizeof (X509ChainStatusFlags_t1026973125)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2098[27] =
{
X509ChainStatusFlags_t1026973125::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2099 = { sizeof (X509FindType_t3058503971)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2099[16] =
{
X509FindType_t3058503971::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 40.494576 | 214 | 0.828863 | [
"object"
] |
67b303e7dbd5ffc6399bd5da0fad6c2861f7d227 | 1,924 | cpp | C++ | trees_and_graphs/tests.cpp | agurusa/interview_prep | b777e0803ee8d3316c0f3fb60efd8463d1437424 | [
"MIT"
] | null | null | null | trees_and_graphs/tests.cpp | agurusa/interview_prep | b777e0803ee8d3316c0f3fb60efd8463d1437424 | [
"MIT"
] | null | null | null | trees_and_graphs/tests.cpp | agurusa/interview_prep | b777e0803ee8d3316c0f3fb60efd8463d1437424 | [
"MIT"
] | null | null | null | #include "../catch.hpp"
#include "route_between_nodes.cpp"
#include "minimal_tree.cpp"
SCENARIO("Given a directed graph with two or more nodes, given two nodes"){
// Graph test_graph();
Graph *test_graph = new Graph();
Node *node_0 = new Node(0);
Node *node_1 = new Node(1);
Node *node_2 = new Node(2);
Node *node_3 = new Node(3);
node_0->children.push_back(node_1);
node_0->children.push_back(node_2);
node_2->children.push_back(node_3);
node_3->children.push_back(node_1);
test_graph->nodes.push_back(node_0);
test_graph->nodes.push_back(node_1);
test_graph->nodes.push_back(node_2);
test_graph->nodes.push_back(node_3);
WHEN("There is no route between them"){
THEN("Return false"){
REQUIRE(route_between_nodes(test_graph, node_1, node_2) == false);
REQUIRE(route_between_nodes(test_graph, node_1, node_0) == false);
REQUIRE(route_between_nodes(test_graph, node_3, node_0) == false);
}
}
WHEN("There is a route between them"){
THEN("Return true"){
REQUIRE(route_between_nodes(test_graph, node_0, node_1) == true);
REQUIRE(route_between_nodes(test_graph, node_0, node_2) == true);
REQUIRE(route_between_nodes(test_graph, node_2, node_1) == true);
REQUIRE(route_between_nodes(test_graph, node_0, node_3) == true);
}
}
}
SCENARIO("Given a sorted (increasing order) array with unique integer elements"){
WHEN("Each item is added into a tree"){
THEN("The items are added to a binary search tree with minimal height"){
std::vector<int> test_vector = {1, 2, 3, 4, 5, 6 , 7};
Tree *test_tree = new Tree();
for(int i = 0; i < test_vector.size(); i++){
TreeNode *tn = new TreeNode(test_vector[i]);
test_tree->Insert(tn);
}
TreeNode *t = new TreeNode(1);
REQUIRE(*minimal_tree(test_vector, 0, test_vector.size() - 1, new Tree()) == *test_tree);
// REQUIRE(*minimal_binary_search_tree(test_vector, 0, test_vector.size() - 1, test_tree) == *t);
}
}
} | 37 | 100 | 0.702703 | [
"vector"
] |
67bf073943ed35a0501dfb5ab9cfa319e63cac26 | 1,739 | cpp | C++ | hash_table.cpp | nowhh01/dataStructures-algorithms | ea4a8187a97672e8452e44d3acad7434f2fef070 | [
"MIT"
] | null | null | null | hash_table.cpp | nowhh01/dataStructures-algorithms | ea4a8187a97672e8452e44d3acad7434f2fef070 | [
"MIT"
] | null | null | null | hash_table.cpp | nowhh01/dataStructures-algorithms | ea4a8187a97672e8452e44d3acad7434f2fef070 | [
"MIT"
] | null | null | null | #include <vector>
#include <list>
#include <algorithm>
#include <string>
template<typename HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101):mSize{size}{}
constexpr bool Contains(const HashedObj& x) const;
void Clear();
bool Insert(const HashedObj& x);
bool Insert(HashedObj&& x);
bool Remove(const HashedObj& x);
private:
std::vector<std::list<HashedObj>> mLists; // The array of Lists
int mSize;
void rehash();
size_t hash(const HashedObj& x) const;
};
template<typename Key>
class Hash
{
public:
size_t operator() (const Key& k) const;
};
template<typename HashedObj>
size_t HashTable<HashedObj>::hash(const HashedObj& x) const
{
static Hash<HashedObj> hf;
return hf(x) % mLists.size();
}
template<typename HashedObj>
void HashTable<HashedObj>::Clear()
{
for(auto& list : mLists)
{
list.clear();
}
}
template<typename HashedObj>
constexpr bool HashTable<HashedObj>::Contains(const HashedObj& x) const
{
auto& list = mLists[hash(x)];
return std::find(begin(list), end(list), x) != end(list);
}
template<typename HashedObj>
bool HashTable<HashedObj>::Remove(const HashedObj& x)
{
auto& list = mLists[hash(x)];
auto itr = std::find(begin(list), end(list), x);
if(itr == end(list))
{
return false;
}
list.erase(itr);
--mSize;
return true;
}
template<typename HashedObj>
bool HashTable<HashedObj>::Insert(const HashedObj& x)
{
auto& list = mLists[hash(x)];
if(std::find(begin(list), end(list), x) != end(list))
{
return false;
}
list.push_back(x);
// rehash;
if(++mSize > mLists.size())
{
rehash();
}
return true;
}
int main()
{
HashTable<std::string> h{};
//h.Insert("aa");
//h.Insert("bb");
//h.Insert("cc");
//h.Insert("dd");
//h.Insert("ee");
}
| 17.04902 | 71 | 0.673376 | [
"vector"
] |
67c27c99f471201b447229e817b86722550ef0b2 | 2,801 | hpp | C++ | include/nanorange/detail/concepts/object.hpp | paulbendixen/NanoRange | 993dc03ebb2d3de5395648f3c0d112d230127c65 | [
"BSL-1.0"
] | null | null | null | include/nanorange/detail/concepts/object.hpp | paulbendixen/NanoRange | 993dc03ebb2d3de5395648f3c0d112d230127c65 | [
"BSL-1.0"
] | null | null | null | include/nanorange/detail/concepts/object.hpp | paulbendixen/NanoRange | 993dc03ebb2d3de5395648f3c0d112d230127c65 | [
"BSL-1.0"
] | null | null | null | // nanorange/detail/concepts/object.hpp
//
// Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail dot com)
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef NANORANGE_DETAIL_CONCEPTS_OBJECT_HPP_INCLUDED
#define NANORANGE_DETAIL_CONCEPTS_OBJECT_HPP_INCLUDED
#include <nanorange/detail/concepts/comparison.hpp>
#include <nanorange/detail/concepts/core.hpp>
#include <nanorange/detail/concepts/movable.hpp>
#include <nanorange/detail/functional/invoke.hpp>
NANO_BEGIN_NAMESPACE
// [concept.copyable]
namespace detail {
struct copyable_concept {
template <typename>
static auto test(long) -> std::false_type;
template <typename T>
static auto test(int) -> std::enable_if_t<
copy_constructible<T> && movable<T> &&
assignable_from<T&, const T&>,
std::true_type>;
};
}
template <typename T>
NANO_CONCEPT copyable = decltype(detail::copyable_concept::test<T>(0))::value;
// [concept.semiregular]
template <typename T>
NANO_CONCEPT semiregular = copyable<T> && default_constructible<T>;
// [concept.regular]
template <typename T>
NANO_CONCEPT regular = semiregular<T> && equality_comparable<T>;
// [concept.invocable]
namespace detail {
struct invocable_concept {
/*template <typename F, typename... Args>
auto requires_(F&& f, Args&&... args) -> decltype(
nano::invoke(std::forward<F>(f), std::forward<Args>(args)...)
);*/
// FIXME: Clang really doesn't like the above, work out why
template <typename F, typename... Args>
auto requires_(F&& f, Args&&... args) -> invoke_result_t<F, Args...>;
};
} // namespace detail
template <typename F, typename... Args>
NANO_CONCEPT invocable = detail::requires_<detail::invocable_concept, F, Args...>;
// [concept.regularinvocable]
template <typename F, typename... Args>
NANO_CONCEPT regular_invocable = invocable<F, Args...>;
// [concept.predicate]
namespace detail {
struct predicate_concept {
template <typename, typename...>
static auto test(long) -> std::false_type;
template <typename F, typename... Args>
static auto test(int) -> std::enable_if_t<
regular_invocable<F, Args...> &&
boolean<invoke_result_t<F, Args...>>,
std::true_type>;
};
}
template <typename F, typename... Args>
NANO_CONCEPT predicate = decltype(detail::predicate_concept::test<F, Args...>(0))::value;
// [concept.relation]
template <typename R, typename T, typename U>
NANO_CONCEPT relation =
predicate<R, T, T> && predicate<R, U, U> &&
predicate<R, T, U> && predicate<R, U, T>;
// [concept.strictweakorder]
template <typename R, typename T, typename U>
NANO_CONCEPT strict_weak_order = relation<R, T, U>;
NANO_END_NAMESPACE
#endif
| 28.01 | 89 | 0.705819 | [
"object"
] |
67c4de6f77371ff78fa56bb17046f2973c17a246 | 1,450 | cpp | C++ | Source/Services/Privacy/permission_check_result.cpp | claytonv/xbox-live-api | d8db86cf930085c7547ae95999c9b301506de343 | [
"MIT"
] | 3 | 2020-07-15T17:50:24.000Z | 2021-11-17T11:15:11.000Z | Source/Services/Privacy/permission_check_result.cpp | CameronGoodwin/xbox-live-api | ee0c3ee2413f2fed6a373df4b26035792e922fe2 | [
"MIT"
] | null | null | null | Source/Services/Privacy/permission_check_result.cpp | CameronGoodwin/xbox-live-api | ee0c3ee2413f2fed6a373df4b26035792e922fe2 | [
"MIT"
] | 1 | 2021-02-01T01:56:08.000Z | 2021-02-01T01:56:08.000Z | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "xsapi/privacy.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_PRIVACY_CPP_BEGIN
permission_check_result::permission_check_result() :
m_isAllowed(false)
{
}
void permission_check_result::initialize(
_In_ const string_t& permissionIdRequested
)
{
m_permissionRequested = permissionIdRequested;
}
bool
permission_check_result::is_allowed() const
{
return m_isAllowed;
}
const string_t&
permission_check_result::permission_requested() const
{
return m_permissionRequested;
}
const std::vector<permission_deny_reason>&
permission_check_result::deny_reasons() const
{
return m_denyReasons;
}
xbox_live_result<permission_check_result>
permission_check_result::_Deserializer(
_In_ const web::json::value& json
)
{
if (json.is_null()) return xbox_live_result<permission_check_result>();
permission_check_result result;
std::error_code errc = xbox_live_error_code::no_error;
result.m_isAllowed = utils::extract_json_bool(json, _T("isAllowed"), errc, true);
result.m_denyReasons = utils::extract_json_vector<permission_deny_reason>(permission_deny_reason::_Deserializer, std::move(json), _T("reasons"), errc, false);
return xbox_live_result<permission_check_result>(result, errc);
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_PRIVACY_CPP_END | 26.363636 | 162 | 0.786897 | [
"vector"
] |
67c7d0f4305385144c3d8a50425fb9c40dd58269 | 4,028 | hpp | C++ | src/openms/thirdparty/evergreen/src/Tensor/TensorLike.hpp | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 348 | 2015-01-17T16:50:12.000Z | 2022-03-30T22:55:39.000Z | src/openms/thirdparty/evergreen/src/Tensor/TensorLike.hpp | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 4,259 | 2015-01-01T14:07:54.000Z | 2022-03-31T16:49:14.000Z | src/openms/thirdparty/evergreen/src/Tensor/TensorLike.hpp | Amit0617/OpenMS | 70ef98e32b02721f45fe72bd4de4b4833755a66f | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 266 | 2015-01-24T14:56:14.000Z | 2022-03-30T12:32:35.000Z | #ifndef _TENSORLIKE_HPP
#define _TENSORLIKE_HPP
template <typename T>
class TensorView;
template <typename T>
class WritableTensorView;
// Never instantiate these; always pass by reference & or &&:
template <typename T, template <typename> class TENSOR >
class TensorLike {
public:
unsigned char dimension() const {
return static_cast<const TENSOR<T> &>(*this).dimension();
}
unsigned long flat_size() const {
return static_cast<const TENSOR<T> &>(*this).flat_size();
}
const T & operator[](unsigned long i) const {
return static_cast<const TENSOR<T> &>(*this)[i];
}
const T & operator[](const_tup_t tuple) const {
#ifdef BOUNDS_CHECK
for (unsigned char k=0; k<dimension(); ++k)
assert( tuple[k] < view_shape()[k] );
#endif
return (*this)[ tuple_to_index(tuple, this->data_shape(), this->dimension()) ];
}
template <template <typename> class VECTOR>
const T & operator[](const VectorLike<unsigned long, VECTOR> & tuple) const {
return (*this)[ static_cast<const_tup_t>(tuple) ];
}
const Vector<unsigned long> & data_shape() const {
return static_cast<const TENSOR<T> &>(*this).data_shape();
}
const Vector<unsigned long> & view_shape() const {
return static_cast<const TENSOR<T> &>(*this).view_shape();
}
template <template <typename> class VECTOR>
TensorView<T> start_at_const(const VectorLike<unsigned long, VECTOR> & start) const {
return static_cast<const TENSOR<T> &>(*this).start_at_const(start);
}
template <template <typename> class VECTOR>
TensorView<T> start_at_const(const VectorLike<unsigned long, VECTOR> & start, const VectorLike<unsigned long, VECTOR> & new_view_shape) const {
return static_cast<const TENSOR<T> &>(*this).start_at_const(start, new_view_shape);
}
static void print_helper(std::ostream & os, const T*const rhs, const_tup_t data_shape, const_tup_t view_shape, unsigned char dimension) {
os << "[";
if (dimension > 1) {
unsigned long flat_size_without_first = flat_length(data_shape+1, dimension-1);
for (unsigned long i=0; i<view_shape[0]; ++i) {
print_helper(os, rhs + i*flat_size_without_first, data_shape+1, view_shape+1, dimension-1);
if (i != (view_shape[0]-1))
os << ", ";
}
}
else {
for (unsigned long i=0; i<view_shape[0]; ++i) {
os << rhs[i];
if (i != (view_shape[0]-1))
os << ", ";
}
}
os << "]";
}
};
template <typename T, template <typename> class TENSOR >
class WritableTensorLike : public TensorLike<T, TENSOR> {
public:
T & operator[](unsigned long i) {
return static_cast<TENSOR<T> &>(*this)[i];
}
T & operator[](const_tup_t tuple) {
#ifdef BOUNDS_CHECK
for (unsigned char k=0; k<this->dimension(); ++k)
assert( tuple[k] < this->view_shape()[k] );
#endif
return (*this)[ tuple_to_index(tuple, this->data_shape(), this->dimension()) ];
}
template <template <typename> class VECTOR>
T & operator[](const VectorLike<unsigned long, VECTOR> & tuple) {
return (*this)[ static_cast<const_tup_t>(tuple) ];
}
template <template <typename> class VECTOR>
WritableTensorView<T> start_at(const VectorLike<unsigned long, VECTOR> & start) {
return static_cast<const TENSOR<T> &>(*this).start_at(start);
}
template <template <typename> class VECTOR>
WritableTensorView<T> start_at(const VectorLike<unsigned long, VECTOR> & start, const VectorLike<unsigned long, VECTOR> & new_view_shape) {
return static_cast<const TENSOR<T> &>(*this).start_at(start, new_view_shape);
}
};
template <typename T, template <typename> class TENSOR>
std::ostream & operator<<(std::ostream & os, const TensorLike<T, TENSOR> & rhs) {
// To distinguish 1D Tensor from Vector:
os << "t:";
if ( rhs.flat_size() == 0 ) {
for (unsigned char k=0; k<rhs.dimension(); ++k)
os << "[";
for (unsigned char k=0; k<rhs.dimension(); ++k)
os << "]";
}
else
rhs.print_helper(os, &rhs[0ul], rhs.data_shape(), rhs.view_shape(), rhs.dimension());
return os;
}
#endif
| 35.026087 | 145 | 0.669067 | [
"vector"
] |
67c9e3a857807e9cebf6a0698ead5107b0d6d278 | 1,872 | cxx | C++ | src/Cxx/ImplicitFunctions/ImplicitSphere.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 81 | 2020-08-10T01:44:30.000Z | 2022-03-23T06:46:36.000Z | src/Cxx/ImplicitFunctions/ImplicitSphere.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 2 | 2020-09-12T17:33:52.000Z | 2021-04-15T17:33:09.000Z | src/Cxx/ImplicitFunctions/ImplicitSphere.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 27 | 2020-08-17T07:09:30.000Z | 2022-02-15T03:44:58.000Z | #include <vtkActor.h>
#include <vtkContourFilter.h>
#include <vtkImageData.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkOutlineFilter.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSampleFunction.h>
#include <vtkSphere.h>
#include <algorithm>
#include <array>
int main(int, char*[])
{
vtkNew<vtkNamedColors> colors;
// Set the background color.
std::array<unsigned char, 4> bkg{{51, 77, 102, 255}};
colors->SetColor("BkgColor", bkg.data());
vtkNew<vtkSphere> sphere;
// Sample the function
vtkNew<vtkSampleFunction> sample;
sample->SetSampleDimensions(50, 50, 50);
sample->SetImplicitFunction(sphere);
double value = 2.0;
double xmin = -value, xmax = value, ymin = -value, ymax = value,
zmin = -value, zmax = value;
sample->SetModelBounds(xmin, xmax, ymin, ymax, zmin, zmax);
// Create the 0 isosurface
vtkNew<vtkContourFilter> contours;
contours->SetInputConnection(sample->GetOutputPort());
contours->GenerateValues(1, 1, 1);
// Map the contours to graphical primitives
vtkNew<vtkPolyDataMapper> contourMapper;
contourMapper->SetInputConnection(contours->GetOutputPort());
contourMapper->ScalarVisibilityOff();
// Create an actor for the contours
vtkNew<vtkActor> contourActor;
contourActor->SetMapper(contourMapper);
// Visualize
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer);
renderWindow->SetWindowName("ImplicitSphere");
vtkNew<vtkRenderWindowInteractor> interactor;
interactor->SetRenderWindow(renderWindow);
renderer->AddActor(contourActor);
renderer->SetBackground(colors->GetColor3d("BkgColor").GetData());
renderWindow->Render();
interactor->Start();
return EXIT_SUCCESS;
}
| 27.529412 | 68 | 0.740919 | [
"render"
] |
67caba39d7731d21181e4298f06a0f4f452528a1 | 48,697 | cpp | C++ | gen/blink/bindings/core/v8/V8HTMLFrameSetElement.cpp | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | gen/blink/bindings/core/v8/V8HTMLFrameSetElement.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | gen/blink/bindings/core/v8/V8HTMLFrameSetElement.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8HTMLFrameSetElement.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8AbstractEventListener.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8Window.h"
#include "core/HTMLNames.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/custom/CustomElementProcessingStack.h"
#include "core/frame/DOMWindowEventHandlers.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8HTMLFrameSetElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8HTMLFrameSetElement::domTemplate, V8HTMLFrameSetElement::refObject, V8HTMLFrameSetElement::derefObject, V8HTMLFrameSetElement::trace, 0, 0, V8HTMLFrameSetElement::preparePrototypeObject, V8HTMLFrameSetElement::installConditionallyEnabledProperties, "HTMLFrameSetElement", &V8HTMLElement::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::NodeClassId, WrapperTypeInfo::InheritFromEventTarget, WrapperTypeInfo::Dependent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in HTMLFrameSetElement.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& HTMLFrameSetElement::s_wrapperTypeInfo = V8HTMLFrameSetElement::wrapperTypeInfo;
namespace HTMLFrameSetElementV8Internal {
static void colsAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::colsAttr), info.GetIsolate());
}
static void colsAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::colsAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void colsAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setAttribute(HTMLNames::colsAttr, cppValue);
}
static void colsAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
HTMLFrameSetElementV8Internal::colsAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void rowsAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::rowsAttr), info.GetIsolate());
}
static void rowsAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::rowsAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void rowsAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setAttribute(HTMLNames::rowsAttr, cppValue);
}
static void rowsAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
HTMLFrameSetElementV8Internal::rowsAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onblurAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onblur());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onblurAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onblurAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onblurAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnblur(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onblurAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onblurAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onerrorAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onerror());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onerrorAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onerrorAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onerrorAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnerror(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onerrorAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onerrorAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onfocusAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onfocus());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onfocusAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onfocusAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onfocusAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnfocus(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onfocusAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onfocusAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onloadAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onload());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onloadAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onloadAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onloadAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnload(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onloadAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onloadAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onresizeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onresize());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onresizeAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onresizeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onresizeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnresize(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onresizeAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onresizeAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onscrollAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onscroll());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onscrollAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onscrollAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onscrollAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnscroll(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onscrollAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onscrollAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onorientationchangeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(impl->onorientationchange());
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onorientationchangeAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onorientationchangeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onorientationchangeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
impl->setOnorientationchange(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onorientationchangeAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onorientationchangeAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onbeforeunloadAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onbeforeunload(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onbeforeunloadAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onbeforeunloadAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onbeforeunloadAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnbeforeunload(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onbeforeunloadAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onbeforeunloadAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onhashchangeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onhashchange(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onhashchangeAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onhashchangeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onhashchangeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnhashchange(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onhashchangeAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onhashchangeAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onlanguagechangeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onlanguagechange(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onlanguagechangeAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onlanguagechangeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onlanguagechangeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnlanguagechange(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onlanguagechangeAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onlanguagechangeAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onmessageAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onmessage(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onmessageAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onmessageAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onmessageAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnmessage(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onmessageAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onmessageAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onofflineAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onoffline(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onofflineAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onofflineAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onofflineAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnoffline(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onofflineAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onofflineAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void ononlineAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::ononline(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void ononlineAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::ononlineAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void ononlineAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnonline(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void ononlineAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::ononlineAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onpagehideAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onpagehide(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onpagehideAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onpagehideAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onpagehideAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnpagehide(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onpagehideAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onpagehideAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onpageshowAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onpageshow(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onpageshowAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onpageshowAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onpageshowAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnpageshow(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onpageshowAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onpageshowAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onpopstateAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onpopstate(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onpopstateAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onpopstateAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onpopstateAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnpopstate(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onpopstateAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onpopstateAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onstorageAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onstorage(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onstorageAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onstorageAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onstorageAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnstorage(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onstorageAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onstorageAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onunloadAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onunload(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onunloadAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onunloadAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onunloadAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnunload(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onunloadAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onunloadAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onrejectionhandledAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onrejectionhandled(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onrejectionhandledAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onrejectionhandledAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onrejectionhandledAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnrejectionhandled(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onrejectionhandledAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onrejectionhandledAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onunhandledrejectionAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
EventListener* cppValue(DOMWindowEventHandlers::onunhandledrejection(*impl));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->executionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void onunhandledrejectionAttributeGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
HTMLFrameSetElementV8Internal::onunhandledrejectionAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void onunhandledrejectionAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Local<v8::Object> holder = info.Holder();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(holder);
DOMWindowEventHandlers::setOnunhandledrejection(*impl, V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void onunhandledrejectionAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
HTMLFrameSetElementV8Internal::onunhandledrejectionAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void namedPropertyGetter(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
auto nameString = name.As<v8::String>();
HTMLFrameSetElement* impl = V8HTMLFrameSetElement::toImpl(info.Holder());
AtomicString propertyName = toCoreAtomicString(nameString);
RefPtrWillBeRawPtr<DOMWindow> result = impl->anonymousNamedGetter(propertyName);
if (!result)
return;
v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl);
}
static void namedPropertyGetterCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMNamedProperty");
HTMLFrameSetElementV8Internal::namedPropertyGetter(name, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace HTMLFrameSetElementV8Internal
// Suppress warning: global constructors, because AttributeConfiguration is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
static const V8DOMConfiguration::AttributeConfiguration V8HTMLFrameSetElementAttributes[] = {
{"cols", HTMLFrameSetElementV8Internal::colsAttributeGetterCallback, HTMLFrameSetElementV8Internal::colsAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"rows", HTMLFrameSetElementV8Internal::rowsAttributeGetterCallback, HTMLFrameSetElementV8Internal::rowsAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onblur", HTMLFrameSetElementV8Internal::onblurAttributeGetterCallback, HTMLFrameSetElementV8Internal::onblurAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onerror", HTMLFrameSetElementV8Internal::onerrorAttributeGetterCallback, HTMLFrameSetElementV8Internal::onerrorAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onfocus", HTMLFrameSetElementV8Internal::onfocusAttributeGetterCallback, HTMLFrameSetElementV8Internal::onfocusAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onload", HTMLFrameSetElementV8Internal::onloadAttributeGetterCallback, HTMLFrameSetElementV8Internal::onloadAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onresize", HTMLFrameSetElementV8Internal::onresizeAttributeGetterCallback, HTMLFrameSetElementV8Internal::onresizeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onscroll", HTMLFrameSetElementV8Internal::onscrollAttributeGetterCallback, HTMLFrameSetElementV8Internal::onscrollAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onbeforeunload", HTMLFrameSetElementV8Internal::onbeforeunloadAttributeGetterCallback, HTMLFrameSetElementV8Internal::onbeforeunloadAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onhashchange", HTMLFrameSetElementV8Internal::onhashchangeAttributeGetterCallback, HTMLFrameSetElementV8Internal::onhashchangeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onlanguagechange", HTMLFrameSetElementV8Internal::onlanguagechangeAttributeGetterCallback, HTMLFrameSetElementV8Internal::onlanguagechangeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onmessage", HTMLFrameSetElementV8Internal::onmessageAttributeGetterCallback, HTMLFrameSetElementV8Internal::onmessageAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onoffline", HTMLFrameSetElementV8Internal::onofflineAttributeGetterCallback, HTMLFrameSetElementV8Internal::onofflineAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"ononline", HTMLFrameSetElementV8Internal::ononlineAttributeGetterCallback, HTMLFrameSetElementV8Internal::ononlineAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onpagehide", HTMLFrameSetElementV8Internal::onpagehideAttributeGetterCallback, HTMLFrameSetElementV8Internal::onpagehideAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onpageshow", HTMLFrameSetElementV8Internal::onpageshowAttributeGetterCallback, HTMLFrameSetElementV8Internal::onpageshowAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onpopstate", HTMLFrameSetElementV8Internal::onpopstateAttributeGetterCallback, HTMLFrameSetElementV8Internal::onpopstateAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onstorage", HTMLFrameSetElementV8Internal::onstorageAttributeGetterCallback, HTMLFrameSetElementV8Internal::onstorageAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"onunload", HTMLFrameSetElementV8Internal::onunloadAttributeGetterCallback, HTMLFrameSetElementV8Internal::onunloadAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
static void installV8HTMLFrameSetElementTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "HTMLFrameSetElement", V8HTMLElement::domTemplate(isolate), V8HTMLFrameSetElement::internalFieldCount,
V8HTMLFrameSetElementAttributes, WTF_ARRAY_LENGTH(V8HTMLFrameSetElementAttributes),
0, 0,
0, 0);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
if (RuntimeEnabledFeatures::orientationEventEnabled()) {
static const V8DOMConfiguration::AttributeConfiguration attributeConfiguration =\
{"onorientationchange", HTMLFrameSetElementV8Internal::onorientationchangeAttributeGetterCallback, HTMLFrameSetElementV8Internal::onorientationchangeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAttribute(isolate, instanceTemplate, prototypeTemplate, attributeConfiguration);
}
if (RuntimeEnabledFeatures::promiseRejectionEventEnabled()) {
static const V8DOMConfiguration::AttributeConfiguration attributeConfiguration =\
{"onrejectionhandled", HTMLFrameSetElementV8Internal::onrejectionhandledAttributeGetterCallback, HTMLFrameSetElementV8Internal::onrejectionhandledAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAttribute(isolate, instanceTemplate, prototypeTemplate, attributeConfiguration);
}
if (RuntimeEnabledFeatures::promiseRejectionEventEnabled()) {
static const V8DOMConfiguration::AttributeConfiguration attributeConfiguration =\
{"onunhandledrejection", HTMLFrameSetElementV8Internal::onunhandledrejectionAttributeGetterCallback, HTMLFrameSetElementV8Internal::onunhandledrejectionAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAttribute(isolate, instanceTemplate, prototypeTemplate, attributeConfiguration);
}
{
v8::NamedPropertyHandlerConfiguration config(HTMLFrameSetElementV8Internal::namedPropertyGetterCallback, 0, 0, 0, 0);
config.flags = static_cast<v8::PropertyHandlerFlags>(static_cast<int>(config.flags) | static_cast<int>(v8::PropertyHandlerFlags::kOnlyInterceptStrings));
functionTemplate->InstanceTemplate()->SetHandler(config);
}
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8HTMLFrameSetElement::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8HTMLFrameSetElementTemplate);
}
bool V8HTMLFrameSetElement::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8HTMLFrameSetElement::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
HTMLFrameSetElement* V8HTMLFrameSetElement::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8HTMLFrameSetElement::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<HTMLFrameSetElement>()->ref();
#endif
}
void V8HTMLFrameSetElement::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<HTMLFrameSetElement>()->deref();
#endif
}
} // namespace blink
| 59.824324 | 586 | 0.77206 | [
"object"
] |
67cdbddd5caa5985fc9bbd5d2d06e77f53b33e1f | 6,565 | cpp | C++ | series0_solution/2d-poissonlFEM/unittest/TestStiffnessMatrix.cpp | BeatHubmann/19H-AdvNCSE | 3979f768da933de82bd6ab29bbf31ea9fc31e501 | [
"MIT"
] | 1 | 2020-01-05T22:38:47.000Z | 2020-01-05T22:38:47.000Z | series0_solution/2d-poissonlFEM/unittest/TestStiffnessMatrix.cpp | BeatHubmann/19H-AdvNCSE | 3979f768da933de82bd6ab29bbf31ea9fc31e501 | [
"MIT"
] | null | null | null | series0_solution/2d-poissonlFEM/unittest/TestStiffnessMatrix.cpp | BeatHubmann/19H-AdvNCSE | 3979f768da933de82bd6ab29bbf31ea9fc31e501 | [
"MIT"
] | 1 | 2019-12-08T20:43:27.000Z | 2019-12-08T20:43:27.000Z | #include <gtest/gtest.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#include "stiffness_matrix.hpp"
TEST(TestStiffnessMatrix, TestReferenceElement) {
Eigen::MatrixXd vertices(3, 3);
vertices << 0, 0, 0,
1, 0, 0,
0, 1, 0;
Eigen::Matrix3d stiffnessMatrix;
computeStiffnessMatrix(stiffnessMatrix, vertices.row(0), vertices.row(1), vertices.row(2));
// This should be equal to
//
// int_K grad lambda(0, x) * grad lambda(0, x) dx = 1
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected00 = 1;
ASSERT_NEAR(expected00, stiffnessMatrix(0, 0), 1e-8) << "stiffness matrix vector not correct at (0,0)";
// This should be equal to
//
// int_K grad lambda(0, x) * grad lambda(1, x) dx = -0.5
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected01 = -0.5;
ASSERT_NEAR(expected01, stiffnessMatrix(0, 1), 1e-8) << "stiffness matrix vector not correct at (0,1)";
// This should be equal to
//
// int_K grad lambda(0, x) * grad lambda(2, x) dx = -0.5
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected02 = -0.5;
ASSERT_NEAR(expected02, stiffnessMatrix(0, 2), 1e-8) << "stiffness matrix vector not correct at (0,2)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(0, x) dx = -0.5
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected10 = -0.5;
ASSERT_NEAR(expected10, stiffnessMatrix(1, 0), 1e-8) << "stiffness matrix vector not correct at (1,0)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(1, x) dx = 0.5
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected11 = 0.5;
ASSERT_NEAR(expected11, stiffnessMatrix(1, 1), 1e-8) << "stiffness matrix vector not correct at (1,1)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(2, x) dx = 0
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected12 = 0;
ASSERT_NEAR(expected12, stiffnessMatrix(1, 2), 1e-8) << "stiffness matrix vector not correct at (1,2)";
// This should be equal to
//
// int_K grad lambda(2, x) * grad lambda(0, x) dx = -0.5
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected20 = -0.5;
ASSERT_NEAR(expected20, stiffnessMatrix(2, 0), 1e-8) << "stiffness matrix vector not correct at (2, 0)";
// This should be equal to
//
// int_K grad lambda(2, x) * grad lambda(1, x) dx = 0
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected21 = 0;
ASSERT_NEAR(expected21, stiffnessMatrix(2, 1), 1e-8) << "stiffness matrix vector not correct at (2,1)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(2, x) dx = 0.5
//
// where K is the triangle spanned by (0,0), (1,0), (1,0)
const double expected22 = 0.5;
ASSERT_NEAR(expected22, stiffnessMatrix(2, 2), 1e-8) << "stiffness matrix vector not correct at (2,2)";
}
TEST(TestStiffnessMatrix, TestSkewTriagnle) {
Eigen::MatrixXd vertices(3, 3);
vertices << 0, 0, 0,
1, 0.4, 0,
0, 1, 0;
Eigen::Matrix3d stiffnessMatrix;
computeStiffnessMatrix(stiffnessMatrix, vertices.row(0), vertices.row(1), vertices.row(2));
// This should be equal to
//
// int_K grad lambda(0, x) * grad lambda(0, x) dx = 0.68
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected00 = 0.68;
ASSERT_NEAR(expected00, stiffnessMatrix(0, 0), 1e-8) << "stiffness matrix vector not correct at (0,0)";
// This should be equal to
//
// int_K grad lambda(0, x) * grad lambda(1, x) dx = -0.3
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected01 = -0.3;
ASSERT_NEAR(expected01, stiffnessMatrix(0, 1), 1e-8) << "stiffness matrix vector not correct at (0,1)";
// This should be equal to
//
// int_K grad lambda(0, x) * grad lambda(2, x) dx = -0.38
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected02 = -0.38;
ASSERT_NEAR(expected02, stiffnessMatrix(0, 2), 1e-8) << "stiffness matrix vector not correct at (0,2)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(0, x) dx = -0.3
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected10 = -0.3;
ASSERT_NEAR(expected10, stiffnessMatrix(1, 0), 1e-8) << "stiffness matrix vector not correct at (1,0)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(1, x) dx = 0.5
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected11 = 0.5;
ASSERT_NEAR(expected11, stiffnessMatrix(1, 1), 1e-8) << "stiffness matrix vector not correct at (1,1)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(2, x) dx = 0.2
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected12 = -0.2;
ASSERT_NEAR(expected12, stiffnessMatrix(1, 2), 1e-8) << "stiffness matrix vector not correct at (1,2)";
// This should be equal to
//
// int_K grad lambda(2, x) * grad lambda(0, x) dx = -0.38
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected20 = -0.38;
ASSERT_NEAR(expected20, stiffnessMatrix(2, 0), 1e-8) << "stiffness matrix vector not correct at (2, 0)";
// This should be equal to
//
// int_K grad lambda(2, x) * grad lambda(1, x) dx = -0.2
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected21 = -0.2;
ASSERT_NEAR(expected21, stiffnessMatrix(2, 1), 1e-8) << "stiffness matrix vector not correct at (2,1)";
// This should be equal to
//
// int_K grad lambda(1, x) * grad lambda(2, x) dx = 0.58
//
// where K is the triangle spanned by (0,0), (1,0.4), (1,0)
const double expected22 = 0.58;
ASSERT_NEAR(expected22, stiffnessMatrix(2, 2), 1e-8) << "stiffness matrix vector not correct at (2,2)";
}
| 36.270718 | 109 | 0.576238 | [
"vector"
] |
67cec16fbb71d58f1f9f1f66df45c99932c505f8 | 7,925 | cpp | C++ | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8WebGLDrawBuffers.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8WebGLDrawBuffers.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8WebGLDrawBuffers.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8WebGLDrawBuffers.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(WebGLDrawBuffers* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8WebGLDrawBuffers::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::WebGLDrawBuffers* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8WebGLDrawBuffers::wrapperTypeInfo = { gin::kEmbedderBlink, V8WebGLDrawBuffers::domTemplate, V8WebGLDrawBuffers::derefObject, 0, 0, 0, V8WebGLDrawBuffers::installPerContextEnabledMethods, 0, WrapperTypeObjectPrototype, RefCountedObject };
namespace WebGLDrawBuffersV8Internal {
template <typename T> void V8_USE(T) { }
static void drawBuffersWEBGLMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeErrorForMethod("drawBuffersWEBGL", "WebGLDrawBuffers", 1, info.Length(), info.GetIsolate());
return;
}
WebGLDrawBuffers* impl = V8WebGLDrawBuffers::toNative(info.Holder());
Vector<unsigned> buffers;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_INTERNAL(buffers, toNativeArray<unsigned>(info[0], 1, info.GetIsolate()));
}
impl->drawBuffersWEBGL(buffers);
}
static void drawBuffersWEBGLMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
WebGLDrawBuffersV8Internal::drawBuffersWEBGLMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
} // namespace WebGLDrawBuffersV8Internal
static const V8DOMConfiguration::MethodConfiguration V8WebGLDrawBuffersMethods[] = {
{"drawBuffersWEBGL", WebGLDrawBuffersV8Internal::drawBuffersWEBGLMethodCallback, 0, 1},
};
static void configureV8WebGLDrawBuffersTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "WebGLDrawBuffers", v8::Local<v8::FunctionTemplate>(), V8WebGLDrawBuffers::internalFieldCount,
0, 0,
0, 0,
V8WebGLDrawBuffersMethods, WTF_ARRAY_LENGTH(V8WebGLDrawBuffersMethods),
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
static const V8DOMConfiguration::ConstantConfiguration V8WebGLDrawBuffersConstants[] = {
{"COLOR_ATTACHMENT0_WEBGL", 0x8CE0},
{"COLOR_ATTACHMENT1_WEBGL", 0x8CE1},
{"COLOR_ATTACHMENT2_WEBGL", 0x8CE2},
{"COLOR_ATTACHMENT3_WEBGL", 0x8CE3},
{"COLOR_ATTACHMENT4_WEBGL", 0x8CE4},
{"COLOR_ATTACHMENT5_WEBGL", 0x8CE5},
{"COLOR_ATTACHMENT6_WEBGL", 0x8CE6},
{"COLOR_ATTACHMENT7_WEBGL", 0x8CE7},
{"COLOR_ATTACHMENT8_WEBGL", 0x8CE8},
{"COLOR_ATTACHMENT9_WEBGL", 0x8CE9},
{"COLOR_ATTACHMENT10_WEBGL", 0x8CEA},
{"COLOR_ATTACHMENT11_WEBGL", 0x8CEB},
{"COLOR_ATTACHMENT12_WEBGL", 0x8CEC},
{"COLOR_ATTACHMENT13_WEBGL", 0x8CED},
{"COLOR_ATTACHMENT14_WEBGL", 0x8CEE},
{"COLOR_ATTACHMENT15_WEBGL", 0x8CEF},
{"DRAW_BUFFER0_WEBGL", 0x8825},
{"DRAW_BUFFER1_WEBGL", 0x8826},
{"DRAW_BUFFER2_WEBGL", 0x8827},
{"DRAW_BUFFER3_WEBGL", 0x8828},
{"DRAW_BUFFER4_WEBGL", 0x8829},
{"DRAW_BUFFER5_WEBGL", 0x882A},
{"DRAW_BUFFER6_WEBGL", 0x882B},
{"DRAW_BUFFER7_WEBGL", 0x882C},
{"DRAW_BUFFER8_WEBGL", 0x882D},
{"DRAW_BUFFER9_WEBGL", 0x882E},
{"DRAW_BUFFER10_WEBGL", 0x882F},
{"DRAW_BUFFER11_WEBGL", 0x8830},
{"DRAW_BUFFER12_WEBGL", 0x8831},
{"DRAW_BUFFER13_WEBGL", 0x8832},
{"DRAW_BUFFER14_WEBGL", 0x8833},
{"DRAW_BUFFER15_WEBGL", 0x8834},
{"MAX_COLOR_ATTACHMENTS_WEBGL", 0x8CDF},
{"MAX_DRAW_BUFFERS_WEBGL", 0x8824},
};
V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8WebGLDrawBuffersConstants, WTF_ARRAY_LENGTH(V8WebGLDrawBuffersConstants), isolate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8WebGLDrawBuffers::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8WebGLDrawBuffersTemplate);
}
bool V8WebGLDrawBuffers::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8WebGLDrawBuffers::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
WebGLDrawBuffers* V8WebGLDrawBuffers::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
v8::Handle<v8::Object> wrap(WebGLDrawBuffers* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8WebGLDrawBuffers>(impl, isolate));
return V8WebGLDrawBuffers::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8WebGLDrawBuffers::createWrapper(PassRefPtr<WebGLDrawBuffers> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8WebGLDrawBuffers>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8WebGLDrawBuffers>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
return wrapper;
}
void V8WebGLDrawBuffers::derefObject(void* object)
{
fromInternalPointer(object)->deref();
}
template<>
v8::Handle<v8::Value> toV8NoInline(WebGLDrawBuffers* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 42.379679 | 261 | 0.744984 | [
"object",
"vector"
] |
67cee0d5dde859a5b00144a737d895cc1b6b2c18 | 23,919 | cpp | C++ | libraries/model/src/ModelTransformer.cpp | harshmittal2210/ELL | 83ee904a638badb922febd8b9d6f3a1155679181 | [
"MIT"
] | null | null | null | libraries/model/src/ModelTransformer.cpp | harshmittal2210/ELL | 83ee904a638badb922febd8b9d6f3a1155679181 | [
"MIT"
] | null | null | null | libraries/model/src/ModelTransformer.cpp | harshmittal2210/ELL | 83ee904a638badb922febd8b9d6f3a1155679181 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: ModelTransformer.cpp (model)
// Authors: Chuck Jacobs
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "ModelTransformer.h"
#include "InputNode.h"
#include "Node.h"
#include "OutputNode.h"
#include <utilities/include/Exception.h>
#include <utilities/include/StringUtil.h>
#include <algorithm>
namespace ell
{
namespace model
{
// Represents a correspondence between two ports, as when a port is transformed or copied into another model
struct PortCorrespondence
{
const InputPortBase* source;
const OutputPortBase* destination;
};
// Represents a set of correspondences between ports, for use when making copies of submodels onto a new location
class PortCorrespondences
{
public:
PortCorrespondences() = default;
PortCorrespondences(const std::vector<const InputPortBase*>& sources, const std::vector<const OutputPortBase*>& destinations);
void Add(const PortCorrespondence& correspondence);
PortCorrespondence operator[](int index) const;
using iterator = std::vector<PortCorrespondence>::iterator;
using const_iterator = std::vector<PortCorrespondence>::const_iterator;
private:
friend PortCorrespondences::iterator begin(PortCorrespondences& correspondences);
friend PortCorrespondences::iterator end(PortCorrespondences& correspondences);
friend PortCorrespondences::const_iterator begin(const PortCorrespondences& correspondences);
friend PortCorrespondences::const_iterator end(const PortCorrespondences& correspondences);
std::vector<PortCorrespondence> _correspondences;
};
//
// NullNode -- used for deleting nodes
//
template <typename ValueType>
class NullNode : public model::Node
{
public:
const model::OutputPort<ValueType>& output = _output;
NullNode(size_t size) :
Node({}, { &_output }),
_output(this, defaultOutputPortName, size){};
static std::string GetTypeName() { return utilities::GetCompositeTypeName<ValueType>("NullNode"); }
std::string GetRuntimeTypeName() const override { return GetTypeName(); }
protected:
void Compute() const override{};
void WriteToArchive(utilities::Archiver& archiver) const override{};
void ReadFromArchive(utilities::Unarchiver& archiver) override{};
private:
void Copy(model::ModelTransformer& transformer) const override
{
auto newNode = transformer.AddNode<NullNode<ValueType>>(_output.Size());
transformer.MapNodeOutput(output, newNode->output);
}
model::OutputPort<ValueType> _output;
};
//
// TransformContext implementation
//
TransformContext::TransformContext() :
_compiler(nullptr)
{
}
TransformContext::TransformContext(const NodeActionFunction& nodeActionFunction) :
_compiler(nullptr)
{
_nodeActionFunctions.emplace_back(nodeActionFunction);
}
TransformContext::TransformContext(const MapCompiler* compiler, const NodeActionFunction& nodeActionFunction) :
_compiler(compiler)
{
_nodeActionFunctions.emplace_back(nodeActionFunction);
}
bool TransformContext::IsNodeCompilable(const Node& node) const
{
return node.IsCompilable(_compiler);
}
void TransformContext::AddNodeActionFunction(const NodeActionFunction& nodeActionFunction)
{
_nodeActionFunctions.emplace_back(nodeActionFunction);
}
NodeAction TransformContext::GetNodeAction(const Node& node) const
{
for (auto iter = _nodeActionFunctions.rbegin(); iter != _nodeActionFunctions.rend(); ++iter)
{
auto& actionFunction = *iter;
auto action = actionFunction(node);
if (action != NodeAction::abstain)
{
return action;
}
}
return node.IsCompilable(_compiler) ? NodeAction::compile : NodeAction::refine;
}
//
// PortCorrespondences
//
void VerifyOntoCorrespondences(const std::vector<const InputPortBase*>& srcInputs, const std::vector<const OutputPortBase*>& onto);
PortCorrespondences::PortCorrespondences(const std::vector<const InputPortBase*>& sources, const std::vector<const OutputPortBase*>& destinations)
{
VerifyOntoCorrespondences(sources, destinations);
for (size_t i = 0, end = sources.size(); i < end; ++i)
{
_correspondences.push_back({ sources[i], destinations[i] });
}
}
void PortCorrespondences::Add(const PortCorrespondence& correspondence)
{
_correspondences.push_back(correspondence);
}
PortCorrespondence PortCorrespondences::operator[](int index) const
{
return _correspondences[index];
}
PortCorrespondences::iterator begin(PortCorrespondences& correspondences)
{
return begin(correspondences._correspondences);
}
PortCorrespondences::iterator end(PortCorrespondences& correspondences)
{
return end(correspondences._correspondences);
}
PortCorrespondences::const_iterator begin(const PortCorrespondences& correspondences)
{
return begin(correspondences._correspondences);
}
PortCorrespondences::const_iterator end(const PortCorrespondences& correspondences)
{
return end(correspondences._correspondences);
}
//
// PortOutputsMap
//
void ModelTransformer::PortOutputsMap::Clear()
{
_outputPortMap.clear();
}
bool ModelTransformer::PortOutputsMap::IsEmpty() const
{
return _outputPortMap.empty();
}
bool ModelTransformer::PortOutputsMap::IsOutputMapped(const OutputPortBase& queryPort) const
{
auto queryPortPtr = &queryPort;
return (_outputPortMap.find(queryPortPtr) != _outputPortMap.end());
}
const OutputPortBase& ModelTransformer::PortOutputsMap::GetCorrespondingPort(const OutputPortBase& queryPort) const
{
using namespace std::string_literals;
auto queryPortPtr = &queryPort;
if (_outputPortMap.find(queryPortPtr) == _outputPortMap.end())
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Could not find element "s + to_string(queryPort.GetNode()->GetId()) + "." + queryPort.GetName() + " in new model.");
}
auto targetPort = _outputPortMap.at(queryPortPtr);
if (targetPort->Size() != queryPort.Size())
{
throw utilities::InputException(utilities::InputExceptionErrors::sizeMismatch,
utilities::FormatString("Model transformation resulted in a mismatching port size, expecting %lld, but found %lld", queryPort.Size(), targetPort->Size()));
}
return *targetPort;
}
void ModelTransformer::PortOutputsMap::MapNodeOutput(const OutputPortBase* oldPort, const OutputPortBase* newPort)
{
if (oldPort->Size() != newPort->Size())
{
throw utilities::InputException(utilities::InputExceptionErrors::sizeMismatch,
utilities::FormatString("Trying to map port %s to output of different size, expecting %lld, but found %lld", oldPort->GetName().c_str(), oldPort->Size(), newPort->Size()));
}
_outputPortMap[oldPort] = newPort;
}
ModelTransformer::PortOutputsMap ModelTransformer::PortOutputsMap::ConcatenateMaps(const PortOutputsMap& prevMap, const PortOutputsMap& newMap)
{
PortOutputsMap result;
for (const auto& entry : prevMap._outputPortMap)
{
const auto& newMappedValue = newMap.GetCorrespondingPort(*entry.second);
result.MapNodeOutput(entry.first, &newMappedValue);
}
return result;
}
//
// ModelTransformer implementation
//
const OutputPortBase& ModelTransformer::SimplifyOutputs(const PortElementsBase& elements)
{
return _model.SimplifyOutputs(elements);
}
Model ModelTransformer::CopyModel(const Model& oldModel)
{
TransformContext context;
Submodel m(oldModel, {}, {});
auto result = CopySubmodel(m, context);
return std::move(result.GetModel());
}
Model ModelTransformer::CopyModel(const Model& oldModel, const TransformContext& context)
{
Submodel m(oldModel, {}, {});
auto result = CopySubmodel(m, context);
return std::move(result.GetModel());
}
Submodel ModelTransformer::CopySubmodel(const Submodel& submodel, const TransformContext& context)
{
Model destModel;
_elementsMap.Clear();
auto result = TransformSubmodelOnto(submodel, destModel, {}, context, [](const Node& node, ModelTransformer& transformer) {
transformer.CopyNode(node);
});
ResetContext();
return result;
}
Submodel ModelTransformer::CopySubmodelOnto(const Submodel& submodel, Model& destModel, const std::vector<const OutputPortBase*>& onto, const TransformContext& context)
{
_elementsMap.Clear();
auto result = TransformSubmodelOnto(submodel, destModel, {}, context, [](const Node& node, ModelTransformer& transformer) {
transformer.CopyNode(node);
});
ResetContext();
return result;
}
bool ModelTransformer::IsInPlace() const
{
return _isInPlace;
}
bool ModelTransformer::ShouldCopyNode(const Node& node) const
{
if (!IsInPlace())
return true;
if (IsInputNode(node))
{
return false;
}
const auto& inputs = node.GetInputPorts();
for (auto in : inputs)
{
if (IsInputMapped(*in))
{
return true;
}
}
return !IsInPlace(); // no inputs, but not an InputNode --- copy if we're in out-of-place mode
}
void ModelTransformer::MapNodeOutput(const OutputPortBase& oldPort, const OutputPortBase& newPort)
{
_elementsMap.MapNodeOutput(&oldPort, &newPort);
}
bool ModelTransformer::IsInputMapped(const InputPortBase& input) const
{
return _elementsMap.IsOutputMapped(input.GetReferencedPort());
}
bool ModelTransformer::IsOutputMapped(const OutputPortBase& output) const
{
return _elementsMap.IsOutputMapped(output);
}
bool ModelTransformer::IsInputNode(const Node& node) const
{
return dynamic_cast<const InputNodeBase*>(&node) != nullptr;
}
Model ModelTransformer::RefineModel(const Model& oldModel, const TransformContext& context, int maxIterations)
{
if (maxIterations <= 0)
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "maxIterations must be positive");
}
_elementsMap.Clear();
_model = CopyModel(oldModel, context);
_context = context;
// Refine until all nodes are compilable according to context.IsNodeCompilable(), until
// the model is fully refined, or until the maximum number of iterations is reached.
for (int i = 0; i < maxIterations; ++i)
{
Model currentModel = std::move(_model);
_model = Model();
auto previousElementMap = std::move(_elementsMap);
_elementsMap.Clear();
_isModelCompilable = true;
// Do one refinement pass
// Note: as a side-effect, _elementsMap may be modified
bool didRefineAny = false;
currentModel.Visit([this, &didRefineAny](const Node& node) {
bool didRefineNode = RefineNode(node);
didRefineAny |= didRefineNode;
});
if (!previousElementMap.IsEmpty())
{
// Now we have 2 maps, the previous one mapping A->B, and a new one mapping B->C (in _elementsMap).
// Concatenate them to get a map A->C, and keep it.
auto newElementsMap = PortOutputsMap::ConcatenateMaps(previousElementMap, _elementsMap);
_elementsMap = newElementsMap;
}
// check for early end condition
if (!didRefineAny || _isModelCompilable)
{
break;
}
}
ResetContext();
return std::move(_model);
}
bool ModelTransformer::Compatible(const InputPortBase* source, const OutputPortBase* dest)
{
return (source->Size() == dest->Size()) && (source->GetType() == dest->GetType());
}
void ModelTransformer::MapCorrespondingInputs(const std::vector<const InputPortBase*>& sources, const std::vector<const OutputPortBase*>& destinations)
{
// Set up port mapping between the given source inputs and their corresponding destination inputs
// throw an exception if the inputs are ill-formed
PortCorrespondences correspondences(sources, destinations);
for (auto correspondence : correspondences)
{
auto source = correspondence.source;
auto dest = correspondence.destination;
if (!Compatible(source, dest))
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Incompatible source and destination inputs");
}
MapNodeOutput(source->GetReferencedPort(), *dest);
}
}
Model ModelTransformer::TransformModel(const Model& model, const TransformContext& context, const NodeTransformFunction& transformFunction)
{
Model newModel;
Submodel submodel(model, {}, {});
auto result = TransformSubmodelOnto(submodel, newModel, {}, context, transformFunction);
return result.GetModel().ShallowCopy();
}
Submodel ModelTransformer::TransformSubmodelOnto(const Submodel& submodel, Model& destModel, const std::vector<const OutputPortBase*>& onto, const TransformContext& context, const NodeTransformFunction& transformFunction)
{
_context = context;
_model = destModel.ShallowCopy();
_isInPlace = (submodel.GetModel() == destModel);
auto previousElementMap = std::move(_elementsMap);
_elementsMap.Clear();
VerifyOntoCorrespondences(submodel.GetInputPorts(), onto);
std::vector<const InputPortBase*> sourceInputs = submodel.GetInputPorts();
MapCorrespondingInputs(sourceInputs, onto);
submodel.GetModel().VisitSubmodel(sourceInputs, submodel.GetOutputPorts(), [this, transformFunction](const Node& node) {
transformFunction(node, *this);
AssignNodeAncestor(node);
});
if (!previousElementMap.IsEmpty())
{
// Now we have 2 maps, the previous one mapping A->B, and a new one mapping B->C (in _elementsMap).
// Concatenate them to get a map A->C, and keep it.
auto newElementsMap = PortOutputsMap::ConcatenateMaps(previousElementMap, _elementsMap);
_elementsMap = newElementsMap;
}
ResetContext();
_model = Model();
auto newOutputs = GetCorrespondingOutputs(submodel.GetOutputPorts());
// Now visit the new outputs until we encounter an input port referencing a port from the "onto" list. That will be one of the new inputs. We should encounter one for each of the "onto" items.
std::vector<const InputPortBase*> newInputs(submodel.GetInputPorts().size(), nullptr);
std::unordered_map<const OutputPortBase*, int> ontoPortToIndexMap;
for (int i = 0, size = (int)onto.size(); i < size; ++i)
{
ontoPortToIndexMap[onto[i]] = i;
}
destModel.VisitSubmodel(newOutputs, [&ontoPortToIndexMap, &newInputs](const Node& node) {
// check node's input ports -- if one of them references one of the onto ports, set it in the newInputs vector at the corresponding location
for (auto input : node.GetInputPorts())
{
auto referencedPort = &input->GetReferencedPort();
if (ontoPortToIndexMap.find(referencedPort) != ontoPortToIndexMap.end())
{
auto index = ontoPortToIndexMap[referencedPort];
newInputs[index] = input;
ontoPortToIndexMap.erase(referencedPort);
}
}
});
return { destModel.ShallowCopy(), newInputs, newOutputs };
}
void VerifyOntoCorrespondences(const std::vector<const InputPortBase*>& sources, const std::vector<const OutputPortBase*>& destinations)
{
if (sources.size() != destinations.size())
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Trying to graft a submodel onto a destination with a different number of outputs");
}
bool ok = std::equal(sources.begin(), sources.end(), destinations.begin(), [](const InputPortBase* s, const OutputPortBase* d) {
return s->GetType() == d->GetType();
});
if (!ok)
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Trying to graft a submodel onto a destination with an incompatible port type");
}
}
Submodel ModelTransformer::TransformSubmodelOnto(const Submodel& submodel, const std::vector<const OutputPortBase*>& onto, const TransformContext& context, const NodeTransformFunction& transformFunction)
{
auto destModel = submodel.GetModel().ShallowCopy();
return TransformSubmodelOnto(submodel, destModel, onto, context, transformFunction);
}
void ModelTransformer::Reset()
{
ResetContext();
_model = Model();
_elementsMap.Clear();
_isModelCompilable = false;
}
void ModelTransformer::ResetContext()
{
_context = TransformContext();
}
const OutputPortBase& ModelTransformer::GetCorrespondingInputs(const InputPortBase& port) const
{
return GetCorrespondingOutputs(port);
}
const OutputPortBase& ModelTransformer::GetCorrespondingOutputs(const InputPortBase& port) const
{
return GetCorrespondingOutputs(port.GetReferencedPort());
}
const OutputPortBase& ModelTransformer::GetCorrespondingOutputs(const OutputPortBase& port) const
{
if (IsInPlace() && !IsOutputMapped(port))
{
return port;
}
return _elementsMap.GetCorrespondingPort(port);
}
std::vector<const OutputPortBase*> ModelTransformer::GetCorrespondingOutputs(const std::vector<const OutputPortBase*>& ports) const
{
std::vector<const OutputPortBase*> result;
for (auto output : ports)
{
result.push_back(&GetCorrespondingOutputs(*output));
}
return result;
}
const OutputPortBase& ModelTransformer::GetCorrespondingOutputs(const PortElementsBase& elements) const
{
return GetCorrespondingOutputs(*elements.GetRanges()[0].ReferencedPort());
}
InputNodeBase* ModelTransformer::GetCorrespondingInputNode(const InputNodeBase* inputNode) const
{
return GetCorrespondingInputNodeAs(inputNode);
}
void ModelTransformer::DeleteNode(const Node& node)
{
using PortType = Port::PortType;
const auto& outputPorts = node.GetOutputPorts();
for (auto outputPort : outputPorts)
{
auto layout = outputPort->GetMemoryLayout().GetExtent();
switch (outputPort->GetType())
{
case PortType::boolean:
{
auto outputNode = AddNode<NullNode<bool>>(outputPort->Size());
MapNodeOutput(*static_cast<const OutputPort<bool>*>(outputPort), outputNode->output);
break;
}
case PortType::integer:
{
auto outputNode = AddNode<NullNode<int>>(outputPort->Size());
MapNodeOutput(*static_cast<const OutputPort<int>*>(outputPort), outputNode->output);
break;
}
case PortType::bigInt:
{
auto outputNode = AddNode<NullNode<std::int64_t>>(outputPort->Size());
MapNodeOutput(*static_cast<const OutputPort<std::int64_t>*>(outputPort), outputNode->output);
break;
}
case PortType::smallReal:
{
auto outputNode = AddNode<NullNode<float>>(outputPort->Size());
MapNodeOutput(*static_cast<const OutputPort<float>*>(outputPort), outputNode->output);
break;
}
case PortType::real:
{
auto outputNode = AddNode<NullNode<double>>(outputPort->Size());
MapNodeOutput(*static_cast<const OutputPort<double>*>(outputPort), outputNode->output);
break;
}
default:
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Unknown port type");
}
}
}
void ModelTransformer::CopyNode(const Node& node)
{
if (ShouldCopyNode(node))
{
node.Copy(*this);
if (IsOutputMapped(*node.GetOutputPort(0)))
{
const auto& port = GetCorrespondingOutputs(*node.GetOutputPort(0));
auto newNode = const_cast<Node*>(port.GetNode());
if (newNode && newNode != (&node))
{
// copy metadata
newNode->GetMetadata() = node.GetMetadata();
}
}
}
}
bool ModelTransformer::RefineNode(const Node& node)
{
// If the node action is "refine" or the default, try to refine the node, otherwise leave it alone
auto action = GetContext().GetNodeAction(node);
if (action == NodeAction::refine || action == NodeAction::abstain)
{
auto didRefineNode = node.InvokeRefine(*this);
AssignNodeAncestor(node);
return didRefineNode;
}
else
{
CopyNode(node);
}
return false;
}
std::vector<const Node*> ModelTransformer::FindUncompilableNodes(const Model& model, const TransformContext& context) const
{
std::vector<const Node*> uncompilableNodes;
auto iter = model.GetNodeIterator();
while (iter.IsValid())
{
auto node = iter.Get();
if (!context.IsNodeCompilable(*node))
{
uncompilableNodes.push_back(node);
}
iter.Next();
}
return uncompilableNodes;
}
void ModelTransformer::AssignNodeAncestor(const Node& ancestorNode)
{
auto iter = _model.GetReverseNodeIterator();
while (iter.IsValid())
{
auto node = const_cast<Node*>(iter.Get());
if (node->GetMetadata().HasEntry("ancestor"))
{
break;
}
else
{
if (ancestorNode.GetMetadata().HasEntry("ancestor"))
{
node->GetMetadata().SetEntry("ancestor", ancestorNode.GetMetadata().GetEntry<std::string>("ancestor"));
}
else
{
node->GetMetadata().SetEntry("ancestor", ancestorNode.GetId().ToString());
}
}
iter.Next();
}
}
} // namespace model
} // namespace ell
| 36.240909 | 225 | 0.624106 | [
"vector",
"model"
] |
67d35721051e5a4327a0156d19da954ec8b83342 | 3,903 | cpp | C++ | src/utils/correction_inf_msg.cpp | mfkiwl/FLVIS | 7472fef6fbc6cfc1e2c0de5dd1d0a7ae5462f689 | [
"BSD-2-Clause"
] | 113 | 2020-10-18T12:35:16.000Z | 2022-03-29T06:08:49.000Z | src/utils/correction_inf_msg.cpp | JazzyFeng/FLVIS-gpu | 74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b | [
"BSD-2-Clause"
] | 9 | 2020-07-04T07:54:57.000Z | 2022-02-17T06:37:33.000Z | src/utils/correction_inf_msg.cpp | JazzyFeng/FLVIS-gpu | 74dd8a136d1923592d2ca74d2408cc2c3bbb8c7b | [
"BSD-2-Clause"
] | 29 | 2021-01-11T13:04:53.000Z | 2022-03-29T06:08:50.000Z | #include "include/correction_inf_msg.h"
CorrectionInfMsg::CorrectionInfMsg()
{
}
CorrectionInfMsg::CorrectionInfMsg(ros::NodeHandle& nh, string topic_name, int buffersize)
{
correction_inf_pub = nh.advertise<flvis::CorrectionInf>(topic_name,1);
}
void CorrectionInfMsg::pub(const int64_t &frame_id_in,
const SE3 &T_c_w_in,
const int &lm_count_in,
const vector<int64_t> &lm_id_in,
const vector<Vec3> &lm_3d_in,
const int &lm_outlier_count_in,
const vector<int64_t> &lm_outlier_id_in,
ros::Time stamp)
{
flvis::CorrectionInf c_inf;
c_inf.frame_id = frame_id_in;
Vec3 t=T_c_w_in.translation();
Quaterniond uq= T_c_w_in.unit_quaternion();
c_inf.T_c_w.translation.x=t[0];
c_inf.T_c_w.translation.y=t[1];
c_inf.T_c_w.translation.z=t[2];
c_inf.T_c_w.rotation.w=uq.w();
c_inf.T_c_w.rotation.x=uq.x();
c_inf.T_c_w.rotation.y=uq.y();
c_inf.T_c_w.rotation.z=uq.z();
c_inf.lm_count = lm_count_in;
c_inf.lm_id_data.layout.dim.push_back(std_msgs::MultiArrayDimension());
c_inf.lm_id_data.layout.dim[0].label = "lm_id";
c_inf.lm_id_data.layout.dim[0].size = static_cast<uint32_t>(lm_id_in.size());
c_inf.lm_id_data.layout.dim[0].stride = static_cast<uint32_t>(lm_id_in.size());
c_inf.lm_id_data.data.clear();
c_inf.lm_id_data.data.insert(c_inf.lm_id_data.data.end(),lm_id_in.begin(),lm_id_in.end());
for(size_t i=0; i<lm_id_in.size(); i++)
{
Vec3 p3d=lm_3d_in.at(i);
geometry_msgs::Vector3 vp3d;
vp3d.x = p3d[0];
vp3d.y = p3d[1];
vp3d.z = p3d[2];
c_inf.lm_3d_data.push_back(vp3d);
}
c_inf.lm_outlier_count = lm_outlier_count_in;
c_inf.lm_outlier_id_data.layout.dim.push_back(std_msgs::MultiArrayDimension());
c_inf.lm_outlier_id_data.layout.dim[0].label = "lm_outlier_id";
c_inf.lm_outlier_id_data.layout.dim[0].size = static_cast<uint32_t>(lm_outlier_id_in.size());
c_inf.lm_outlier_id_data.layout.dim[0].stride = static_cast<uint32_t>(lm_outlier_id_in.size());
c_inf.lm_outlier_id_data.data.clear();
c_inf.lm_outlier_id_data.data.insert(c_inf.lm_outlier_id_data.data.end(),lm_outlier_id_in.begin(),lm_outlier_id_in.end());
this->correction_inf_pub.publish(c_inf);
}
void CorrectionInfMsg::unpack(flvis::CorrectionInfConstPtr c_inf_ptr,
int64_t &frame_id_out,
SE3 &T_c_w_out,
int &lm_count_out,
vector<int64_t> &lm_id_out,
vector<Vec3> &lm_3d_out,
int &lm_outlier_count_out,
vector<int64_t> &lm_outlier_id_out)
{
lm_id_out.clear();
lm_3d_out.clear();
lm_outlier_id_out.clear();
frame_id_out = c_inf_ptr->frame_id;
Vec3 t;
Quaterniond uq;
t[0] = c_inf_ptr->T_c_w.translation.x;
t[1] = c_inf_ptr->T_c_w.translation.y;
t[2] = c_inf_ptr->T_c_w.translation.z;
uq.w() = c_inf_ptr->T_c_w.rotation.w;
uq.x() = c_inf_ptr->T_c_w.rotation.x;
uq.y() = c_inf_ptr->T_c_w.rotation.y;
uq.z() = c_inf_ptr->T_c_w.rotation.z;
T_c_w_out = SE3(uq,t);
lm_count_out = c_inf_ptr->lm_count;
for(auto i=0; i<lm_count_out; i++)
{
lm_id_out.push_back(c_inf_ptr->lm_id_data.data[i]);
Vec3 p3d(c_inf_ptr->lm_3d_data.at(i).x,c_inf_ptr->lm_3d_data.at(i).y,c_inf_ptr->lm_3d_data.at(i).z);
lm_3d_out.push_back(p3d);
}
lm_outlier_count_out = c_inf_ptr->lm_outlier_count;
for(auto i=0; i<lm_outlier_count_out; i++)
{
lm_outlier_id_out.push_back(c_inf_ptr->lm_outlier_id_data.data[i]);
}
}
| 36.138889 | 126 | 0.623879 | [
"vector"
] |
67d99ad375d27d9e81b6494a8ebc8781ffe4dec3 | 3,161 | cpp | C++ | src/main.cpp | oussamaabdulhay/positioning_system | b9c3b0c4616160aade2565d78238ae74d1b62274 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | oussamaabdulhay/positioning_system | b9c3b0c4616160aade2565d78238ae74d1b62274 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | oussamaabdulhay/positioning_system | b9c3b0c4616160aade2565d78238ae74d1b62274 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <vector>
#include "../include/ROSUnit_RTK1.hpp"
#include "../include/ROSUnit_RTK2.hpp"
#include "../include/EmlidRTK.hpp"
#include "../include/ROSUnit_Xsens.hpp"
#include <fstream>
int main(int argc, char** argv) {
ros::init(argc, argv, "testing_node");
std::ofstream write_data("/home/osama/test//heading.csv");
std::ofstream write_data2("/home/osama/test//originalposition.csv");
std::ofstream write_data3("/home/osama/test//transformed.csv");
ros::NodeHandle nh;
ros::Rate rate(10);
ROSUnit* myROSRTK1 = new ROSUnit_RTK1(nh);
ROSUnit* myXsens = new ROSUnit_Xsens(nh);
ROSUnit* myROSRTK2 = new ROSUnit_RTK2(nh);
EmlidRTK* test = new EmlidRTK;
myROSRTK1->add_callback_msg_receiver((msg_receiver*) test);
myROSRTK2->add_callback_msg_receiver((msg_receiver*) test);
myXsens->add_callback_msg_receiver((msg_receiver*) test); // PositionMsg RTK1;
// PositionMsg RTK2;
// Vector3D <double> heading;st);
PositionMsg pos;
PositionMsg final_pos;
Vector3D <double> heading;
PositionMsg RTK1;
PositionMsg RTK2;
// Vector3D <double> heading;
while(ros::ok()){
ros::spinOnce();
RTK1=test->getRTK1();
RTK2=test->getRTK2();
// write_data2 <<setprecision(12)<< pos.x << ", ";
// write_data2 <<setprecision(12)<< pos.y << ", ";
// write_data2 <<setprecision(12)<< pos.z << "\n ";
// write_data3 <<setprecision(12)<< final_pos.x << ", ";
// write_data3 <<setprecision(12)<< final_pos.y << ", ";
// write_data3 <<setprecision(12)<< final_pos.z << "\n ";
//write_data <<setprecision(12) <<heading.z << " \n ";
//write_data2 <<setprecision(12)<< RTK1.x << ", ";
//write_data2 <<setprecision(12)<< RTK1.y << " ,";
// write_data2 <<setprecision(12)<< RTK1.z << "\n ";
// write_data3 <<setprecision(12)<< RTK2.x << " ,";
// write_data3 <<setprecision(12)<< RTK2.y << " ,";
// write_data3 <<setprecision(12)<< RTK2.z << "\n ";
pos = test->getPosition();
//heading = test->getHeading();
final_pos=test->Transformed();
// cout<<setprecision(12)<<"Original_pos.x ="<<pos.x<< "\n";
// cout<<setprecision(12)<<"Original_pos.y ="<<pos.y<< "\n";
// cout<<setprecision(12)<<"Original_pos.z ="<<pos.z << "\n";
// cout<<setprecision(12)<<"transformed_pos.x ="<< final_pos.x << "\n";
// cout<<setprecision(12)<<"transformed_pos.y ="<< final_pos.y << "\n";
// cout<<setprecision(12)<<"transformed_pos.z ="<< final_pos.x << "\n" ;
//cout << " Heading=" <<heading.yaw << "\n";
//write_data <<heading.yaw << "\n ";
write_data2 <<setprecision(12)<< pos.x << ", ";
write_data2 <<setprecision(12)<< pos.y << ", ";
write_data2 <<setprecision(12)<< pos.z << "\n ";
write_data3 <<setprecision(12)<< final_pos.x << ", ";
write_data3 <<setprecision(12)<< final_pos.y << ", ";
write_data3 <<setprecision(12)<< final_pos.z << "\n ";
rate.sleep();
}
}
| 37.630952 | 83 | 0.575451 | [
"vector"
] |
67e1027af02023a8a93cd5e63c4a358cbd9b373f | 1,337 | cpp | C++ | contests/atcoder/abc170/abc170_c/main.cpp | conao3/coder | 2cdb610fec013da88a3470d460108e8a9b462445 | [
"CC0-1.0"
] | null | null | null | contests/atcoder/abc170/abc170_c/main.cpp | conao3/coder | 2cdb610fec013da88a3470d460108e8a9b462445 | [
"CC0-1.0"
] | null | null | null | contests/atcoder/abc170/abc170_c/main.cpp | conao3/coder | 2cdb610fec013da88a3470d460108e8a9b462445 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cctype>
using namespace std;
#define ll long long
#define ld long double
#define v vector
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rep3(i, m, n) for (int i = (m); i < (int)(n); ++i)
#define rrep(i, n) for (int i = (int)(n)-1; i >= 0; --i)
#define rrep3(i, m, n) for (int i = (int)(n)-1; i >= (m); --i)
#define all(x) begin(x), end(x)
#define rall(x) end(x), begin(x)
#define endl '\n'
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll solve(ll X, ll N, const vector<ll> & p) {
vector<bool> db(110, 0);
ll res;
rep(i, N)
db[p[i]] = true;
ll i = X;
while (db[i] == true && i < 110) ++i;
res = i;
i = X;
while (db[i] == true && 0 <= i) --i;
if (X-i <= res-X) return i;
else return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll X, N;
cin >> X >> N;
if (N == 0) {
cout << X << endl;
return 0;
}
vector<ll> p(N);
rep (i, N) {
cin >> p[i];
}
auto ans = solve(X, N, p);
cout << ans << endl;
return 0;
}
| 18.315068 | 62 | 0.551234 | [
"vector"
] |
67e468c2c1ed20982f81962a59c922efec990746 | 4,384 | cc | C++ | shell/platform/linux/fl_method_call.cc | masterashu/engine | 243bb59c7179a7e701ce478080d6ce990710ae73 | [
"BSD-3-Clause"
] | null | null | null | shell/platform/linux/fl_method_call.cc | masterashu/engine | 243bb59c7179a7e701ce478080d6ce990710ae73 | [
"BSD-3-Clause"
] | null | null | null | shell/platform/linux/fl_method_call.cc | masterashu/engine | 243bb59c7179a7e701ce478080d6ce990710ae73 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_call.h"
#include "flutter/shell/platform/linux/fl_method_call_private.h"
#include "flutter/shell/platform/linux/fl_method_channel_private.h"
#include <gmodule.h>
struct _FlMethodCall {
GObject parent_instance;
// Name of method being called.
gchar* name;
// Arguments provided to method call.
FlValue* args;
// Channel to respond on.
FlMethodChannel* channel;
FlBinaryMessengerResponseHandle* response_handle;
};
G_DEFINE_TYPE(FlMethodCall, fl_method_call, G_TYPE_OBJECT)
static void fl_method_call_dispose(GObject* object) {
FlMethodCall* self = FL_METHOD_CALL(object);
g_clear_pointer(&self->name, g_free);
g_clear_pointer(&self->args, fl_value_unref);
g_clear_object(&self->channel);
g_clear_object(&self->response_handle);
G_OBJECT_CLASS(fl_method_call_parent_class)->dispose(object);
}
static void fl_method_call_class_init(FlMethodCallClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_method_call_dispose;
}
static void fl_method_call_init(FlMethodCall* self) {}
FlMethodCall* fl_method_call_new(
const gchar* name,
FlValue* args,
FlMethodChannel* channel,
FlBinaryMessengerResponseHandle* response_handle) {
g_return_val_if_fail(name != nullptr, nullptr);
g_return_val_if_fail(args != nullptr, nullptr);
g_return_val_if_fail(FL_IS_METHOD_CHANNEL(channel), nullptr);
g_return_val_if_fail(FL_IS_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle),
nullptr);
FlMethodCall* self =
FL_METHOD_CALL(g_object_new(fl_method_call_get_type(), nullptr));
self->name = g_strdup(name);
self->args = fl_value_ref(args);
self->channel = FL_METHOD_CHANNEL(g_object_ref(channel));
self->response_handle =
FL_BINARY_MESSENGER_RESPONSE_HANDLE(g_object_ref(response_handle));
return self;
}
G_MODULE_EXPORT const gchar* fl_method_call_get_name(FlMethodCall* self) {
g_return_val_if_fail(FL_IS_METHOD_CALL(self), nullptr);
return self->name;
}
G_MODULE_EXPORT FlValue* fl_method_call_get_args(FlMethodCall* self) {
g_return_val_if_fail(FL_IS_METHOD_CALL(self), nullptr);
return self->args;
}
gboolean fl_method_call_respond(FlMethodCall* self,
FlMethodResponse* response,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE);
g_return_val_if_fail(FL_IS_METHOD_RESPONSE(response), FALSE);
return fl_method_channel_respond(self->channel, self->response_handle,
response, error);
}
G_MODULE_EXPORT gboolean fl_method_call_respond_success(FlMethodCall* self,
FlValue* result,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE);
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_success_response_new(result));
return fl_method_channel_respond(self->channel, self->response_handle,
response, error);
}
G_MODULE_EXPORT gboolean fl_method_call_respond_error(FlMethodCall* self,
const gchar* code,
const gchar* message,
FlValue* details,
GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE);
g_return_val_if_fail(code != nullptr, FALSE);
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_error_response_new(code, message, details));
return fl_method_channel_respond(self->channel, self->response_handle,
response, error);
}
G_MODULE_EXPORT gboolean
fl_method_call_respond_not_implemented(FlMethodCall* self, GError** error) {
g_return_val_if_fail(FL_IS_METHOD_CALL(self), FALSE);
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
return fl_method_channel_respond(self->channel, self->response_handle,
response, error);
}
| 36.533333 | 79 | 0.693887 | [
"object"
] |
67ec1aca04935e18611f2d58196a2279549bcb33 | 344 | cpp | C++ | Questions Level-Wise/Easy/maximum-product-of-three-numbers.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | 2 | 2021-03-05T22:32:23.000Z | 2021-03-05T22:32:29.000Z | Questions Level-Wise/Easy/maximum-product-of-three-numbers.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | Questions Level-Wise/Easy/maximum-product-of-three-numbers.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | class Solution {
public:
int maximumProduct(vector<int>& nums)
{
int Size=nums.size();
std::sort(nums.begin(),nums.end());
if(nums[0]<0&&nums[1]<0&&(nums[0]*nums[1]>=nums[Size-2]*nums[Size-3]))
return nums[Size-1]*nums[0]*nums[1];
return nums[Size-1]*nums[Size-2]*nums[Size-3];
}
};
| 28.666667 | 78 | 0.543605 | [
"vector"
] |
67f483b629a0478e85cbe9aeadd6cb6397e48e64 | 10,027 | cpp | C++ | Box2d/Source/Dynamics/b2Body.cpp | sroske/launch-it | cba4f99f8d5ef6465b7b4b87b05936b26b13766a | [
"MIT"
] | 1 | 2016-02-01T22:26:49.000Z | 2016-02-01T22:26:49.000Z | Box2d/Source/Dynamics/b2Body.cpp | sroske/launch-it | cba4f99f8d5ef6465b7b4b87b05936b26b13766a | [
"MIT"
] | null | null | null | Box2d/Source/Dynamics/b2Body.cpp | sroske/launch-it | cba4f99f8d5ef6465b7b4b87b05936b26b13766a | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2006-2007 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 "b2Body.h"
#include "b2World.h"
#include "Joints/b2Joint.h"
#include "../Collision/Shapes/b2Shape.h"
#include "../Collision/Shapes/b2EdgeShape.h"
b2Body::b2Body(const b2BodyDef* bd, b2World* world)
{
b2Assert(world->m_lock == false);
m_flags = 0;
if (bd->isBullet)
{
m_flags |= e_bulletFlag;
}
if (bd->fixedRotation)
{
m_flags |= e_fixedRotationFlag;
}
if (bd->allowSleep)
{
m_flags |= e_allowSleepFlag;
}
if (bd->isSleeping)
{
m_flags |= e_sleepFlag;
}
m_world = world;
m_xf.position = bd->position;
m_xf.R.Set(bd->angle);
m_sweep.localCenter = bd->massData.center;
m_sweep.t0 = 1.0f;
m_sweep.a0 = m_sweep.a = bd->angle;
m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
m_jointList = NULL;
m_contactList = NULL;
m_controllerList = NULL;
m_prev = NULL;
m_next = NULL;
m_linearDamping = bd->linearDamping;
m_angularDamping = bd->angularDamping;
m_force.Set(0.0f, 0.0f);
m_torque = 0.0f;
m_linearVelocity.SetZero();
m_angularVelocity = 0.0f;
m_sleepTime = 0.0f;
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
m_mass = bd->massData.mass;
if (m_mass > 0.0f)
{
m_invMass = 1.0f / m_mass;
}
if ((m_flags & b2Body::e_fixedRotationFlag) == 0)
{
m_I = bd->massData.I;
}
if (m_I > 0.0f)
{
m_invI = 1.0f / m_I;
}
if (m_invMass == 0.0f && m_invI == 0.0f)
{
m_type = e_staticType;
}
else
{
m_type = e_dynamicType;
}
m_userData = bd->userData;
m_shapeList = NULL;
m_shapeCount = 0;
}
b2Body::~b2Body()
{
b2Assert(m_world->m_lock == false);
// shapes and joints are destroyed in b2World::Destroy
}
float32 connectEdges(b2EdgeShape * const & s1, b2EdgeShape * const & s2, float32 angle1)
{
float32 angle2 = b2Atan2(s2->GetDirectionVector().y, s2->GetDirectionVector().x);
b2Vec2 core = tanf((angle2 - angle1) * 0.5f) * s2->GetDirectionVector();
core = b2_toiSlop * (core - s2->GetNormalVector()) + s2->GetVertex1();
b2Vec2 cornerDir = s1->GetDirectionVector() + s2->GetDirectionVector();
cornerDir.Normalize();
bool convex = b2Dot(s1->GetDirectionVector(), s2->GetNormalVector()) > 0.0f;
s1->SetNextEdge(s2, core, cornerDir, convex);
s2->SetPrevEdge(s1, core, cornerDir, convex);
return angle2;
}
b2Shape* b2Body::CreateShape(b2ShapeDef* def)
{
b2Assert(m_world->m_lock == false);
if (m_world->m_lock == true)
{
return NULL;
}
// TODO: Decide on a better place to initialize edgeShapes. (b2Shape::Create() can't
// return more than one shape to add to parent body... maybe it should add
// shapes directly to the body instead of returning them?)
if (def->type == e_edgeShape) {
b2EdgeChainDef* edgeDef = (b2EdgeChainDef*)def;
b2Vec2 v1;
b2Vec2 v2;
int i;
if (edgeDef->isALoop) {
v1 = edgeDef->vertices[edgeDef->vertexCount-1];
i = 0;
} else {
v1 = edgeDef->vertices[0];
i = 1;
}
b2EdgeShape* s0 = NULL;
b2EdgeShape* s1 = NULL;
b2EdgeShape* s2 = NULL;
float32 angle = 0.0f;
for (; i < edgeDef->vertexCount; i++) {
v2 = edgeDef->vertices[i];
void* mem = m_world->m_blockAllocator.Allocate(sizeof(b2EdgeShape));
s2 = new (mem) b2EdgeShape(v1, v2, def);
s2->m_next = m_shapeList;
m_shapeList = s2;
++m_shapeCount;
s2->m_body = this;
s2->CreateProxy(m_world->m_broadPhase, m_xf);
s2->UpdateSweepRadius(m_sweep.localCenter);
if (s1 == NULL) {
s0 = s2;
angle = b2Atan2(s2->GetDirectionVector().y, s2->GetDirectionVector().x);
} else {
angle = connectEdges(s1, s2, angle);
}
s1 = s2;
v1 = v2;
}
if (edgeDef->isALoop) connectEdges(s1, s0, angle);
return s0;
}
b2Shape* s = b2Shape::Create(def, &m_world->m_blockAllocator);
s->m_next = m_shapeList;
m_shapeList = s;
++m_shapeCount;
s->m_body = this;
// Add the shape to the world's broad-phase.
s->CreateProxy(m_world->m_broadPhase, m_xf);
// Compute the sweep radius for CCD.
s->UpdateSweepRadius(m_sweep.localCenter);
return s;
}
void b2Body::DestroyShape(b2Shape* s)
{
b2Assert(m_world->m_lock == false);
if (m_world->m_lock == true)
{
return;
}
b2Assert(s->GetBody() == this);
s->DestroyProxy(m_world->m_broadPhase);
b2Assert(m_shapeCount > 0);
b2Shape** node = &m_shapeList;
bool found = false;
while (*node != NULL)
{
if (*node == s)
{
*node = s->m_next;
found = true;
break;
}
node = &(*node)->m_next;
}
// You tried to remove a shape that is not attached to this body.
b2Assert(found);
s->m_body = NULL;
s->m_next = NULL;
--m_shapeCount;
b2Shape::Destroy(s, &m_world->m_blockAllocator);
}
// TODO_ERIN adjust linear velocity and torque to account for movement of center.
void b2Body::SetMass(const b2MassData* massData)
{
b2Assert(m_world->m_lock == false);
if (m_world->m_lock == true)
{
return;
}
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
m_mass = massData->mass;
if (m_mass > 0.0f)
{
m_invMass = 1.0f / m_mass;
}
if ((m_flags & b2Body::e_fixedRotationFlag) == 0)
{
m_I = massData->I;
}
if (m_I > 0.0f)
{
m_invI = 1.0f / m_I;
}
// Move center of mass.
m_sweep.localCenter = massData->center;
m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
// Update the sweep radii of all child shapes.
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
s->UpdateSweepRadius(m_sweep.localCenter);
}
int16 oldType = m_type;
if (m_invMass == 0.0f && m_invI == 0.0f)
{
m_type = e_staticType;
}
else
{
m_type = e_dynamicType;
}
// If the body type changed, we need to refilter the broad-phase proxies.
if (oldType != m_type)
{
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
s->RefilterProxy(m_world->m_broadPhase, m_xf);
}
}
}
// TODO_ERIN adjust linear velocity and torque to account for movement of center.
void b2Body::SetMassFromShapes()
{
b2Assert(m_world->m_lock == false);
if (m_world->m_lock == true)
{
return;
}
// Compute mass data from shapes. Each shape has its own density.
m_mass = 0.0f;
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
b2Vec2 center = b2Vec2_zero;
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
b2MassData massData;
s->ComputeMass(&massData);
m_mass += massData.mass;
center += massData.mass * massData.center;
m_I += massData.I;
}
// Compute center of mass, and shift the origin to the COM.
if (m_mass > 0.0f)
{
m_invMass = 1.0f / m_mass;
center *= m_invMass;
}
if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0)
{
// Center the inertia about the center of mass.
m_I -= m_mass * b2Dot(center, center);
b2Assert(m_I > 0.0f);
m_invI = 1.0f / m_I;
}
else
{
m_I = 0.0f;
m_invI = 0.0f;
}
// Move center of mass.
m_sweep.localCenter = center;
m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
// Update the sweep radii of all child shapes.
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
s->UpdateSweepRadius(m_sweep.localCenter);
}
int16 oldType = m_type;
if (m_invMass == 0.0f && m_invI == 0.0f)
{
m_type = e_staticType;
}
else
{
m_type = e_dynamicType;
}
// If the body type changed, we need to refilter the broad-phase proxies.
if (oldType != m_type)
{
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
s->RefilterProxy(m_world->m_broadPhase, m_xf);
}
}
}
bool b2Body::SetXForm(const b2Vec2& position, float32 angle)
{
b2Assert(m_world->m_lock == false);
if (m_world->m_lock == true)
{
return true;
}
if (IsFrozen())
{
return false;
}
m_xf.R.Set(angle);
m_xf.position = position;
m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
m_sweep.a0 = m_sweep.a = angle;
bool freeze = false;
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
bool inRange = s->Synchronize(m_world->m_broadPhase, m_xf, m_xf);
if (inRange == false)
{
freeze = true;
break;
}
}
if (freeze == true)
{
m_flags |= e_frozenFlag;
m_linearVelocity.SetZero();
m_angularVelocity = 0.0f;
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
s->DestroyProxy(m_world->m_broadPhase);
}
// Failure
return false;
}
// Success
m_world->m_broadPhase->Commit();
return true;
}
bool b2Body::SynchronizeShapes()
{
b2XForm xf1;
xf1.R.Set(m_sweep.a0);
xf1.position = m_sweep.c0 - b2Mul(xf1.R, m_sweep.localCenter);
bool inRange = true;
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
inRange = s->Synchronize(m_world->m_broadPhase, xf1, m_xf);
if (inRange == false)
{
break;
}
}
if (inRange == false)
{
m_flags |= e_frozenFlag;
m_linearVelocity.SetZero();
m_angularVelocity = 0.0f;
for (b2Shape* s = m_shapeList; s; s = s->m_next)
{
s->DestroyProxy(m_world->m_broadPhase);
}
// Failure
return false;
}
// Success
return true;
}
| 21.893013 | 89 | 0.632293 | [
"shape"
] |
67f5850a7c713040eab3529780457e80503c6e50 | 5,429 | cpp | C++ | src/main/algorithms/cpp/array/create_maximum_number_321/solution.cpp | algorithmlover2016/leet_code | 2eecc7971194c8a755e67719d8f66c636694e7e9 | [
"Apache-2.0"
] | null | null | null | src/main/algorithms/cpp/array/create_maximum_number_321/solution.cpp | algorithmlover2016/leet_code | 2eecc7971194c8a755e67719d8f66c636694e7e9 | [
"Apache-2.0"
] | null | null | null | src/main/algorithms/cpp/array/create_maximum_number_321/solution.cpp | algorithmlover2016/leet_code | 2eecc7971194c8a755e67719d8f66c636694e7e9 | [
"Apache-2.0"
] | null | null | null | #include "../../head.h"
// #define DEBUG
class Solution {
public:
std::vector<int> maxNumber(std::vector<int> const & nums1, std::vector<int> const & nums2, int k) {
// plagiarizing from https://leetcode.com/problems/create-maximum-number/discuss/77287/C%2B%2B-16ms-FASTEST-beats-97.
int const nums1Size = nums1.size();
int const nums2Size = nums2.size();
#ifdef DEBUG
std::cout << "1, 2Size: " << nums1Size << ",\t" << nums2Size << "\n";
#endif
int needNums1Min = std::max(0, k - nums2Size);
int needNums1Max = std::min(k, nums1Size);
int needNums2Min = k - needNums1Max;
int needNums2Max = k - needNums1Min;
std::unordered_map<int, std::vector<int>> nums1DpMemo;
std::unordered_map<int, std::vector<int>> nums2DpMemo;
nums1DpMemo[needNums1Max] = getMaxVec(nums1, needNums1Max);
nums2DpMemo[needNums2Max] = getMaxVec(nums2, needNums2Max);
getRangeMax(nums1DpMemo, needNums1Max, needNums1Min);
getRangeMax(nums2DpMemo, needNums2Max, needNums2Min);
std::vector<int> ans(k, INT_MIN);
for (int needNums1Len = needNums1Min; needNums1Len <= needNums1Max; needNums1Len++) {
int needNums2Len = k - needNums1Len;
#ifdef DEBUG
std::cout << "nums1Len, nums2Len: " << needNums1Len << ",\t" << needNums2Len << "\t";
std::cout << "1Len, 2Len: " << nums1DpMemo[needNums1Len].size() << ",\t"
<< nums2DpMemo[needNums2Len].size() << "\n";
#endif
std::vector<int> curAns;
merge(nums1DpMemo[needNums1Len], nums2DpMemo[needNums2Len], curAns);
if (curAns > ans) {
ans = curAns;
}
}
return ans;
}
void merge(std::vector<int> const & nums1,
std::vector<int> const & nums2,
std::vector<int> & ans) {
int idx1 = 0, idx2 = 0;
while (idx1 < nums1.size() && idx2 < nums2.size()) {
if (nums1[idx1] > nums2[idx2]) {
ans.emplace_back(nums1[idx1++]);
} else if (nums1[idx1] < nums2[idx2]) {
ans.emplace_back(nums2[idx2++]);
} else {
bool large = !std::lexicographical_compare(nums1.begin() + idx1, nums1.end(),
nums2.begin() + idx2, nums2.end());
if (large) {
getEqualEle(nums1, idx1, nums1[idx1], ans);
} else {
getEqualEle(nums2, idx2, nums2[idx2], ans);
}
}
}
if (idx1 < nums1.size()) {
getLeftEle(nums1, idx1, ans);
} else if (idx2 < nums2.size()) {
getLeftEle(nums2, idx2, ans);
}
}
void getLeftEle(std::vector<int> const & nums, int idx, std::vector<int> & ans) {
for (; idx < nums.size(); idx++) {
ans.emplace_back(nums[idx]);
}
}
void getEqualEle(std::vector<int> const & nums, int & idx, int const target, std::vector<int> & ans) {
for (; idx < nums.size() && target == nums[idx]; idx++) {
ans.emplace_back(nums[idx]);
}
}
void getRangeMax(std::unordered_map<int, std::vector<int>> & numsDpMemo,
int needNumsMax, int needNumsMin) {
if (numsDpMemo.find(needNumsMax) == numsDpMemo.end()) {
return;
}
for (int start = needNumsMax; start > needNumsMin; start--) {
std::list<int> ans(numsDpMemo[start].begin(), numsDpMemo[start].end());
int pre = INT_MAX;
std::list<int>::iterator it = ans.begin();
for (; it != ans.end(); it++) {
if (pre < *it) {
break;
}
pre = *it;
}
ans.erase(std::prev(it));
numsDpMemo[start - 1] = std::vector<int>(ans.begin(), ans.end());
}
}
std::vector<int> getMaxVec(std::vector<int> const & nums, int target) {
if (nums.empty() || 0 == target) {
return {};
}
int const numsSize = nums.size();
if (target >= numsSize) {
return nums;
}
int const needDelNum = numsSize - target;
#ifdef DEBUG
std::cout << "size, target, del: " << numsSize << ",\t" << target << ",\t" << needDelNum << "\n";
#endif
std::vector<int> ans; //using as stack
for (int idx = 0; idx < numsSize; idx++) {
// idx - ans.size() means util idx(exclude) the number that we have delete
// if we can do a delete operation, which means ans.pop(),
// we must let idx - ans.size() < needDelNum
// ans.size() means the num that we will take
while (!ans.empty() && ans.back() < nums[idx] && (idx - ans.size() < needDelNum)) {
ans.pop_back();
}
if (idx - ans.size() == needDelNum) {
getLeftEle(nums, idx, ans);
return ans;
}
ans.emplace_back(nums[idx]);
}
// if all the elements in nums are all the same, according to my code,
// ans will be nums. then we just need cut the last needDelNum elements with resize
if (target != ans.size()) {
ans.resize(target);
}
return ans;
}
};
| 38.232394 | 125 | 0.511881 | [
"vector"
] |
67fa77f46b8f180f6ddeef3c6ccd9c1af067c8cf | 1,367 | cpp | C++ | C++/ambiguous-coordinates.cpp | black-shadows/LeetCode-Solutions | b1692583f7b710943ffb19b392b8bf64845b5d7a | [
"Fair",
"Unlicense"
] | 1 | 2020-04-16T08:38:14.000Z | 2020-04-16T08:38:14.000Z | ambiguous-coordinates.cpp | Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise | f1111b4edd401a3fc47111993bd7250cf4dc76da | [
"MIT"
] | null | null | null | ambiguous-coordinates.cpp | Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise | f1111b4edd401a3fc47111993bd7250cf4dc76da | [
"MIT"
] | 1 | 2021-12-25T14:48:56.000Z | 2021-12-25T14:48:56.000Z | // Time: O(n^4)
// Space: O(n^2)
class Solution {
public:
vector<string> ambiguousCoordinates(string S) {
vector<string> result;
for (int i = 1; i < S.length() - 2; ++i) {
const auto& lefts = make(S, 1, i);
const auto& rights = make(S, i + 1, S.length() - 2 - i);
for (const auto& left : lefts) {
for (const auto& right : rights) {
string s;
s += "(";
s += left;
s += ", ";
s += right;
s += ")";
result.emplace_back(move(s));
}
}
}
return result;
}
private:
// Time: O(n^2)
// Space: O(n^2)
vector<string> make(const string& S, int i, int n) {
vector<string> result;
for (int d = 1; d <= n; ++d) {
const auto& left = S.substr(i, d);
const auto& right = S.substr(i + d, n - d);
if ((left.front() != '0' || left == "0") &&
right.back() != '0') {
string s;
s += left;
s += (!right.empty() ? "." : "");
s += right;
result.emplace_back(move(s));
}
}
return result;
}
};
| 29.717391 | 69 | 0.355523 | [
"vector"
] |
db014ba0241321f4be6a291d661563cebee38a37 | 8,091 | cpp | C++ | src/wmecore/Scene2DBase.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/Scene2DBase.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/Scene2DBase.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | // This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "Wme.h"
#include "Scene2DBase.h"
#include "SceneNode2D.h"
#include "Viewport.h"
#include "ViewportLayout.h"
#include "Canvas2D.h"
#include "ActiveSpot.h"
// temp
#include "SpriteEntity.h"
#include "Sprite.h"
#include "SpriteFrame.h"
#include "SpriteSubFrame.h"
#include "TextureElement2D.h"
#include "UiButtonOld.h"
#include "TextElement2D.h"
#include "FontManager.h"
#include "RectElement2D.h"
#include "SpriteTexture.h"
#include "ResizableElement2D.h"
#include "UiWindow.h"
#include "UiBorder.h"
#include "UiInteractiveArea.h"
#include "UiButton.h"
namespace Wme
{
//////////////////////////////////////////////////////////////////////////
Scene2DBase::Scene2DBase()
{
m_Viewport = NULL;
m_Canvas = NULL;
// temp
m_TestSprite = NULL;
m_TestEntity = NULL;
m_Tex = NULL;
m_Font = NULL;
m_Text = NULL;
m_TestNode = NULL;
m_Rect = NULL;
m_RectNode = NULL;
m_Resizable = NULL;
m_ResizableImage = NULL;
m_ResizableNode = NULL;
m_Window1 = m_Window2 = NULL;
m_Border = NULL;
}
//////////////////////////////////////////////////////////////////////////
Scene2DBase::~Scene2DBase()
{
SAFE_DELETE(m_Tex);
SAFE_DELETE(m_TestEntity);
SAFE_DELETE(m_TestSprite);
SAFE_DELETE(m_Text);
SAFE_DELETE(m_TestNode);
SAFE_DELETE(m_Rect);
SAFE_DELETE(m_RectNode);
SAFE_DELETE(m_Resizable);
SAFE_DELETE(m_ResizableImage);
SAFE_DELETE(m_ResizableNode);
SAFE_DELETE(m_Window1);
Game::GetInstance()->GetFontMgr()->ReleaseFont(m_Font);
SAFE_DELETE(m_Canvas);
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::Create()
{
Scene::Create();
m_Canvas = new Canvas2D(GetUniqueMovableName("Canvas2D", L"Canvas2D"), m_Viewport);
this->GetRootNode()->attachObject(m_Canvas);
// test data
/*
static UiButton dummy(NULL);
dummy.SetName(L"molly");
m_Tex = new TextureElement2D();
m_Tex->SetSubFrame(m_TestSprite->GetFrames().at(0)->GetSubFrames().at(0));
m_Tex->SetColor(Ogre::ColourValue(1.0f, 1.0f, 1.0f, 1.0f));
m_Tex->SetOwner(&dummy);
m_Canvas->GetRootNode()->AttachElement(m_Tex);
*/
//m_Canvas->GetRootNode()->SetClippingRect(Rect(-25, -50, 25, 50));
m_TestEntity = new SpriteEntity();
m_TestEntity->SetName(L"molly entity");
m_TestEntity->PutToStage(this);
m_TestSprite = new Sprite(m_TestEntity);
m_TestSprite->LoadFromFile(L"actors/molly/walk/walk.sprite");
m_TestEntity->SetCurrentSprite(m_TestSprite);
m_TestEntity->SetPosition(400, 400);
m_TestEntity->GetSceneNode()->SetClippingRect(Rect(0, -222, 50, 30));
//m_TestEntity->SetRotation(270.0f);
m_Font = Game::GetInstance()->GetFontMgr()->GetFont(L"arial.font", false);
m_Text = new TextElement2D();
m_Text->SetFont(m_Font);
m_Text->SetText(L"CCCC\nTest test test.\nSecond line.");
m_Text->SetWidth(500);
m_Text->SetHeight(500);
m_Text->SetLeadingSpace(20);
m_Text->SetUnderline(true);
m_Text->SetDecorationType(TextElement2D::DECORATION_OUTLINE);
m_Text->SetDecorationColor(Ogre::ColourValue::Red);
m_TestNode = m_Canvas->GetRootNode()->CreateChildNode();
m_TestNode->AttachElement(m_Text);
m_TestNode->SetPosition(400, 500);
//m_TestNode->SetRotation(10);
//m_TestNode->SetScale(2, 2);
m_Rect = new RectElement2D();
m_Rect->SetWidth(100);
m_Rect->SetHeight(80);
m_Rect->SetStrokeThickness(10);
m_Rect->SetFillColor(Ogre::ColourValue(0, 1, 0, 0.5f));
m_Rect->SetStrokeColor(Ogre::ColourValue::Red);
m_RectNode = m_Canvas->GetRootNode()->CreateChildNode();
m_RectNode->AttachElement(m_Rect);
m_RectNode->SetPosition(300, 300);
m_RectNode->SetRotation(45);
//m_RectNode->SetScale(10, 10);
m_ResizableImage = new ResizableImage();
m_ResizableImage->SetTexture(L"win_grid.bmp");
m_ResizableImage->SetFrameLeftWidth(30);
m_ResizableImage->SetFrameRightWidth(30);
m_ResizableImage->SetFrameTopHeight(30);
m_ResizableImage->SetFrameBottomHeight(30);
m_ResizableImage->SetPaintMiddlePart(true);
m_ResizableImage->SetStretchHorizontal(true);
m_ResizableImage->SetStretchVertical(true);
m_Resizable = new ResizableElement2D();
m_Resizable->SetWidth(200);
m_Resizable->SetHeight(150);
m_Resizable->SetImage(m_ResizableImage);
m_ResizableNode = m_Canvas->GetRootNode()->CreateChildNode();
m_ResizableNode->AttachElement(m_Resizable);
m_ResizableNode->SetPosition(400, 30);
m_Window1 = new UiWindow(m_Canvas);
m_Window1->SetName(L"Window1");
m_Window1->SetClipChildren(true);
m_Window1->SetPosX(60);
m_Window1->SetPosY(440);
m_Window1->SetWidth(200);
m_Window1->SetHeight(200);
m_Window2 = new UiWindow(m_Canvas);
m_Window2->SetPosX(150);
m_Window2->SetPosY(150);
m_Window2->SetWidth(100);
m_Window2->SetHeight(100);
m_Window1->AddChild(m_Window2);
m_Window1->SetWidth(300);
m_Window1->SetHeight(200);
m_Border = new UiBorder(m_Canvas);
m_Border->SetImage(L"win_grid.image");
m_Window1->AddChild(m_Border);
m_Border->FillParent(5,5,5,5);
UiInteractiveArea* area = new UiInteractiveArea(m_Canvas);
m_Window1->AddChild(area);
area->FillParent();
/*
m_Window1->GetSceneNode()->SetRotation(15);
m_Window1->GetSceneNode()->SetScale(2, 1);
*/
/*
m_Window2->SetAnchor(UiObjectBase::ANCHOR_LEFT, m_Window1, 10);
m_Window2->SetAnchor(UiObjectBase::ANCHOR_RIGHT, m_Window1, 10);
m_Window2->SetAnchor(UiObjectBase::ANCHOR_TOP, m_Window1, 10);
m_Window2->SetAnchor(UiObjectBase::ANCHOR_BOTTOM, m_Window1, 10);
*/
m_Window2->SetAnchor(UiObjectBase::ANCHOR_VERTICAL_CENTER, m_Window1);
m_Window2->SetAnchor(UiObjectBase::ANCHOR_HORIZONTAL_CENTER, m_Window1);
UiButton* button = new UiButton(m_Canvas);
button->SetSize(150, 50);
button->SetPosX(20);
button->SetPosY(20);
m_Window1->AddChild(button);
//m_Canvas->GetRootNode()->SetRotation(45);
//m_Canvas->GetRootNode()->SetPosition(400, 400);
//m_Canvas->GetRootNode()->SetScale(1.5f, 1.5f);
//m_ElementCol->getParentSceneNode()->attachObject(m_Canvas);
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::Update()
{
Scene::Update();
if (m_TestEntity) m_TestEntity->Update();
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::Shutdown()
{
Scene::Shutdown();
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::RegisterActiveSpots(Viewport* viewport, Camera* camera, Ogre::uint8 renderQueueId)
{
if (m_Canvas && viewport == m_Viewport && renderQueueId == m_Canvas->getRenderQueueGroup())
{
ActiveSpotCanvas* spot = new ActiveSpotCanvas(viewport, m_Canvas);
viewport->AddActiveSpot(spot);
}
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::SetViewport(Viewport* viewport)
{
m_Viewport = viewport;
if (m_Canvas) m_Canvas->SetViewport(viewport);
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::OnSceneNodeCreated(SceneNode2D* node)
{
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::OnSceneNodeDestroyed(SceneNode2D* node)
{
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::OnSceneNodeChanged(SceneNode2D* node)
{
}
//////////////////////////////////////////////////////////////////////////
void Scene2DBase::OnSceneGraphDirty()
{
}
//////////////////////////////////////////////////////////////////////////
bool Scene2DBase::HandleMouseEvent(Viewport* viewport, MouseEvent& event)
{
bool res = Stage::HandleMouseEvent(viewport, event);
MousePickResult result;
if (viewport->GetParentLayout()->GetObjectAt(event.GetPosX(), event.GetPosY(), result))
{
if (result.Object->HandleMouseEvent(viewport, event)) res = true;
}
return res;
}
} // namespace Wme
| 27.9 | 101 | 0.638487 | [
"object"
] |
db0c2d53f46ce528259323356569797e95a33198 | 6,082 | cpp | C++ | Apps/MultiTrackerViewer/MeshIO.cpp | xchern/MultiTracker | 06cdad3e1b2e24f1a87de07f64b9aab2807b129e | [
"BSD-2-Clause"
] | 3 | 2017-10-31T20:51:12.000Z | 2020-12-18T15:56:40.000Z | Apps/MultiTrackerViewer/MeshIO.cpp | xchern/MultiTracker | 06cdad3e1b2e24f1a87de07f64b9aab2807b129e | [
"BSD-2-Clause"
] | null | null | null | Apps/MultiTrackerViewer/MeshIO.cpp | xchern/MultiTracker | 06cdad3e1b2e24f1a87de07f64b9aab2807b129e | [
"BSD-2-Clause"
] | 3 | 2018-03-19T12:29:31.000Z | 2020-12-22T12:04:46.000Z | //
// MeshIO.cpp
//
// Christopher Batty, Fang Da 2014
//
//
#include <fstream>
#include "MeshIO.h"
bool MeshIO::save(LosTopos::SurfTrack & st, const std::string & filename, bool binary)
{
if (binary)
{
std::ofstream os(filename.c_str(), std::ios::binary);
size_t n;
n = st.m_mesh.nv();
os.write((char *)&n, sizeof (size_t));
for (size_t i = 0; i < n; i++)
{
LosTopos::Vec3d x = st.get_position(i);
os.write((char *)&(x[0]), sizeof (x[0]));
os.write((char *)&(x[1]), sizeof (x[1]));
os.write((char *)&(x[2]), sizeof (x[2]));
}
n = st.m_mesh.nt();
os.write((char *)&n, sizeof (size_t));
for (size_t i = 0; i < n; i++)
{
LosTopos::Vec3st t = st.m_mesh.get_triangle(i);
if (t[0] == t[1])
continue;
LosTopos::Vec2i l = st.m_mesh.get_triangle_label(i);
os.write((char *)&(t[0]), sizeof (t[0]));
os.write((char *)&(t[1]), sizeof (t[1]));
os.write((char *)&(t[2]), sizeof (t[2]));
os.write((char *)&(l[0]), sizeof (l[0]));
os.write((char *)&(l[1]), sizeof (l[1]));
}
return os.good();
} else
{
std::ofstream os(filename.c_str());
os << st.m_mesh.nv() << std::endl;
for (size_t i = 0; i < st.m_mesh.nv(); i++)
{
os << st.get_position(i) << std::endl;
}
os << st.m_mesh.nt() << std::endl;
for (size_t i = 0; i < st.m_mesh.nt(); i++)
{
LosTopos::Vec3st t = st.m_mesh.get_triangle(i);
if (t[0] == t[1])
continue;
LosTopos::Vec2i l = st.m_mesh.get_triangle_label(i);
os << t << " " << l << std::endl;
}
os.close();
return os.good();
}
}
bool MeshIO::load(LosTopos::SurfTrack & st, const std::string & filename, bool binary)
{
std::ifstream test(filename.c_str());
if (!test.is_open())
{
std::cout << "[MeshIO::load] Error: file " << filename.c_str() << " not found." << std::endl;
return false;
}
for (size_t i = 0; i < st.m_mesh.nt(); i++)
{
if (st.m_mesh.get_triangle(i)[0] == st.m_mesh.get_triangle(i)[1])
continue;
st.remove_triangle(i);
}
for (size_t i = 0; i < st.m_mesh.nv(); i++)
st.remove_vertex(i);
if (binary)
{
std::ifstream is(filename.c_str(), std::ios::binary);
size_t n;
//n = st.m_mesh.nv();
is.read((char *)&n, sizeof (size_t));
st.m_mesh.set_num_vertices(n);
std::vector<LosTopos::Vec3d> pos(n);
for (size_t i = 0; i < n; i++)
{
LosTopos::Vec3d x;
is.read((char *)&(x[0]), sizeof (x[0]));
is.read((char *)&(x[1]), sizeof (x[1]));
is.read((char *)&(x[2]), sizeof (x[2]));
pos[i] = x;
}
st.m_masses.resize(n);
for (size_t i = 0; i < n; i++)
st.m_masses[i] = LosTopos::Vec3d(1, 1, 1);
//n = st.m_mesh.nt();
is.read((char *)&n, sizeof (size_t));
std::vector<LosTopos::Vec3st> tris(n);
std::vector<LosTopos::Vec2i> labels(n);
for (size_t i = 0; i < n; i++)
{
LosTopos::Vec3st t;
is.read((char *)&(t[0]), sizeof (t[0]));
is.read((char *)&(t[1]), sizeof (t[1]));
is.read((char *)&(t[2]), sizeof (t[2]));
tris[i] = t;
LosTopos::Vec2i l;
is.read((char *)&(l[0]), sizeof (l[0]));
is.read((char *)&(l[1]), sizeof (l[1]));
labels[i] = l;
}
//(We load the triangles first so that when we compute the edge lengths
//to determine the length scale for the acceleration grid, it's not a div by zero.
//I realize this is non-obvious and non-ideal; I apologize!)
st.m_mesh.replace_all_triangles(tris, labels);
st.set_all_positions(pos);
st.set_all_newpositions(pos);
st.set_all_remesh_velocities(std::vector<LosTopos::Vec3d>(n, LosTopos::Vec3d(0)));
//why do these need resizing at all?
size_t nv = st.m_mesh.m_vertex_to_triangle_map.size();
st.pm_positions.resize(nv);
st.pm_newpositions.resize(nv);
st.pm_velocities.resize(nv);
st.m_velocities.resize(nv);
is.close();
return is.good();
} else
{
std::ifstream is(filename.c_str());
size_t n;
is >> n;
st.m_mesh.set_num_vertices(n);
std::vector<LosTopos::Vec3d> pos(n);
for (size_t i = 0; i < n; i++)
{
LosTopos::Vec3d x;
is >> x[0] >> x[1] >> x[2];
pos[i] = x;
}
st.m_masses.resize(n);
for (size_t i = 0; i < n; i++)
st.m_masses[i] = LosTopos::Vec3d(1, 1, 1);
st.set_all_positions(pos);
st.set_all_newpositions(pos);
st.set_all_remesh_velocities(std::vector<LosTopos::Vec3d>(n, LosTopos::Vec3d(0)));
n = st.m_mesh.nt();
is >> n;
std::vector<LosTopos::Vec3st> tris;
std::vector<LosTopos::Vec2i> labels;
for (size_t i = 0; i < n; i++)
{
LosTopos::Vec3st t;
is >> t[0] >> t[1] >> t[2];
tris.push_back(t);
LosTopos::Vec2i l;
is >> l[0] >> l[1];
labels.push_back(l);
}
st.m_mesh.replace_all_triangles(tris, labels);
size_t nv = st.m_mesh.m_vertex_to_triangle_map.size();
st.pm_positions.resize(nv);
st.pm_newpositions.resize(nv);
st.pm_velocities.resize(nv);
st.m_velocities.resize(nv);
is.close();
return is.good();
}
}
| 29.381643 | 101 | 0.464814 | [
"vector"
] |
db0e6f6a9071ed03da7bb502765b23bc1e594495 | 5,929 | cpp | C++ | LinaResource/src/Core/ResourceManager.cpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 10 | 2018-09-30T22:29:27.000Z | 2018-10-08T14:04:42.000Z | LinaResource/src/Core/ResourceManager.cpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 15 | 2018-10-02T22:14:17.000Z | 2018-10-12T08:01:36.000Z | LinaResource/src/Core/ResourceManager.cpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 1 | 2018-09-30T16:37:10.000Z | 2018-09-30T16:37:10.000Z | /*
This file is a part of: Lina Engine
https://github.com/inanevin/Lina
Author: Inan Evin
http://www.inanevin.com
Copyright (c) [2018-2020] [Inan Evin]
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 "Core/ResourceManager.hpp"
#include "Resources/ResourceStorage.hpp"
#include "EventSystem/EventSystem.hpp"
#include "EventSystem/ResourceEvents.hpp"
#include "Log/Log.hpp"
#include "Utility/UtilityFunctions.hpp"
namespace Lina::Resources
{
#define RESOURCEPACKAGE_EXTENSION ".linabundle"
ResourceManager* ResourceManager::s_resourceManager = nullptr;
ResourceProgressData ResourceManager::s_currentProgressData;
void ResourceManager::LoadEditorResources()
{
LINA_WARN("[Resource Manager] -> Loading Editor Resources");
// Find resources.
m_rootFolder = new Utility::Folder();
m_rootFolder->m_fullPath = "Resources/";
m_rootFolder->m_name = "Resources";
Utility::ScanFolder(m_rootFolder, true, &s_currentProgressData.m_currentTotalFiles);
// Set progress & fill.
s_currentProgressData.m_state = ResourceProgressState::Pending;
s_currentProgressData.m_progressTitle = "Loading resources...";
s_currentProgressData.m_state = ResourceProgressState::InProgress;
s_currentProgressData.m_currentProcessedFiles = 0;
m_bundle.ScanFileResources(m_rootFolder);
m_bundle.LoadAllFileResources();
Event::EventSystem::Get()->Trigger<Event::EAllResourcesLoaded>(Event::EAllResourcesLoaded {});
ResourceManager::ResetProgress();
}
void ResourceManager::OnRequestResourceReload(const Event::ERequestResourceReload& ev)
{
m_bundle.LoadSingleFile(ev.m_tid, ev.m_fullPath);
m_eventSys->Trigger<Event::EResourceReloaded>(Event::EResourceReloaded{ev.m_tid, ev.m_sid});
}
void ResourceManager::Shutdown()
{
// Make sure we don't have any packing/unpacking going on.
if (m_future.valid())
{
m_future.cancel();
m_future.get();
}
delete m_rootFolder;
LINA_TRACE("[Shutdown] -> Resource Manager {0}", typeid(*this).name());
}
void ResourceManager::ResetProgress()
{
s_currentProgressData.m_currentProcessedFiles = s_currentProgressData.m_currentTotalFiles = 0;
s_currentProgressData.m_currentResourceName = s_currentProgressData.m_progressTitle = "";
s_currentProgressData.m_state = ResourceProgressState::None;
s_currentProgressData.m_currentProgress = 0.0f;
}
void ResourceManager::TriggerResourceUpdatedEvent()
{
Event::EventSystem::Get()->Trigger<Event::EResourceLoadUpdated>(Event::EResourceLoadUpdated{ResourceManager::s_currentProgressData.m_currentResourceName, ResourceManager::s_currentProgressData.m_currentProgress});
}
void ResourceManager::PackageProject(const std::string& path, const std::string& name)
{
// Find out which resources to export.
std::vector<std::string> filesToPack;
AddAllResourcesToPack(filesToPack, m_rootFolder);
// Export resources.
m_packager.PackageFileset(filesToPack, path + "/" + name + RESOURCEPACKAGE_EXTENSION, m_appInfo.m_packagePass);
}
void ResourceManager::Initialize(ApplicationInfo& appInfo)
{
m_appInfo = appInfo;
m_eventSys = Event::EventSystem::Get();
m_eventSys->Connect<Event::ERequestResourceReload, &ResourceManager::OnRequestResourceReload>(this);
}
void ResourceManager::AddAllResourcesToPack(std::vector<std::string>& resources, Utility::Folder* folder)
{
for (auto& childFolder : folder->m_folders)
AddAllResourcesToPack(resources, childFolder);
for (auto& file : folder->m_files)
resources.push_back(file->m_fullPath);
}
void ResourceManager::ImportResourceBundle(const std::string& path, const std::string& name)
{
const std::string fullPath = path + name + RESOURCEPACKAGE_EXTENSION;
if (!Utility::FileExists(fullPath))
{
LINA_ERR("Package does not exist, aborting import. {0}", fullPath);
return;
}
std::string fullBundlePath = fullPath;
s_currentProgressData.m_progressTitle = "Unpacking level resources...";
s_currentProgressData.m_currentResourceName = fullBundlePath;
// Start unpacking process, preceeded & followed by an event dispatch.
// m_eventSys->Trigger<Event::EResourceProgressStarted>();
// Start unpacking.
m_packager.Unpack(fullBundlePath, m_appInfo.m_packagePass, &m_bundle);
m_bundle.LoadAllMemoryResources();
// Set progress end.
ResetProgress();
}
} // namespace Lina::Resources
| 39.264901 | 221 | 0.694215 | [
"vector"
] |
db10e09e47041434c6a1535b2faac57946c3e9d8 | 52,042 | cpp | C++ | oneflow/core/framework/op_interpreter/lazy_op_interpreter.cpp | felixhao28/oneflow | e558af6ef6c4ed90e4abc7bc1ba895f55795626d | [
"Apache-2.0"
] | null | null | null | oneflow/core/framework/op_interpreter/lazy_op_interpreter.cpp | felixhao28/oneflow | e558af6ef6c4ed90e4abc7bc1ba895f55795626d | [
"Apache-2.0"
] | null | null | null | oneflow/core/framework/op_interpreter/lazy_op_interpreter.cpp | felixhao28/oneflow | e558af6ef6c4ed90e4abc7bc1ba895f55795626d | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <memory>
#include "oneflow/core/common/cpp_attribute.h"
#include "oneflow/core/common/maybe.h"
#include "oneflow/core/common/cpp_attribute.h"
#include "oneflow/core/framework/consistency_check.h"
#include "oneflow/core/framework/user_op_conf.h"
#include "oneflow/core/framework/op_expr.h"
#include "oneflow/core/framework/op_builder.h"
#include "oneflow/core/framework/multi_client_session_context.h"
#include "oneflow/core/framework/op_interpreter.h"
#include "oneflow/core/framework/op_interpreter/op_interpreter_util.h"
#include "oneflow/core/framework/instructions_builder.h"
#include "oneflow/core/framework/op_arg_util.h"
#include "oneflow/core/framework/scope_util.h"
#include "oneflow/core/framework/session_util.h"
#include "oneflow/core/framework/symbol_storage_util.h"
#include "oneflow/core/framework/tensor.h"
#include "oneflow/core/framework/tensor_name_scope.h"
#include "oneflow/core/framework/tensor_tuple.h"
#include "oneflow/core/framework/user_op_registry.h"
#include "oneflow/core/framework/nd_sbp.h"
#include "oneflow/core/eager/foreign_boxing_util.h"
#include "oneflow/core/operator/operator.h"
#include "oneflow/core/job/sbp_parallel.h"
#include "oneflow/core/job/job_build_and_infer_ctx_mgr.h"
#include "oneflow/core/vm/vm_util.h"
namespace oneflow {
namespace one {
namespace {
Maybe<Tensor> BuildTensor(const OpAttribute& op_attribute, const std::string& bn_in_op,
const std::shared_ptr<ParallelDesc>& parallel_desc, const bool is_lazy,
const bool is_local) {
CHECK_OR_RETURN(op_attribute.has_logical_blob_desc_signature());
const auto& blob_desc_sign_map = op_attribute.logical_blob_desc_signature().bn_in_op2blob_desc();
auto blob_desc_it = blob_desc_sign_map.find(bn_in_op);
CHECK_OR_RETURN(blob_desc_it != blob_desc_sign_map.end())
<< "blob_desc of " << bn_in_op << " not found in op " << op_attribute.op_conf().name();
auto shape = std::make_shared<Shape>(blob_desc_it->second.shape());
auto dtype = blob_desc_it->second.data_type();
if (is_local) {
const auto& device = JUST(Device::MakeDeviceByParallelDesc(*parallel_desc));
const auto& tensor =
JUST(MirroredTensor::MakeTensor(shape, dtype, device, is_lazy,
/* requires_grad= */ false, /* is_leaf= */ true));
return static_cast<std::shared_ptr<Tensor>>(tensor);
} else {
const auto& nd_sbp_sign_map = op_attribute.nd_sbp_signature().bn_in_op2nd_sbp();
auto nd_sbp_it = nd_sbp_sign_map.find(bn_in_op);
CHECK_OR_RETURN(nd_sbp_it != nd_sbp_sign_map.end())
<< "nd_sbp of " << bn_in_op << " not found in op " << op_attribute.op_conf().name();
NdSbp nd_sbp(nd_sbp_it->second);
const auto& tensor = JUST(ConsistentTensor::MakeTensor(
shape, dtype, SymbolOf(nd_sbp), SymbolOf(*parallel_desc), is_lazy,
/*requires_grad=*/false, /*is_leaf=*/true));
return static_cast<std::shared_ptr<Tensor>>(tensor);
}
}
Maybe<void> CheckTensorMatchAttr(const std::shared_ptr<Tensor>& tensor,
const OpAttribute& op_attribute, const std::string& bn_in_op,
const std::shared_ptr<ParallelDesc>& parallel_desc,
const bool is_local) {
CHECK_EQ_OR_RETURN(tensor->is_local(), is_local);
CHECK_OR_RETURN(op_attribute.has_logical_blob_desc_signature());
const auto& blob_desc_sign_map = op_attribute.logical_blob_desc_signature().bn_in_op2blob_desc();
auto blob_desc_it = blob_desc_sign_map.find(bn_in_op);
CHECK_OR_RETURN(blob_desc_it != blob_desc_sign_map.end())
<< "blob_desc of " << bn_in_op << " not found in op " << op_attribute.op_conf().name();
auto shape = std::make_shared<Shape>(blob_desc_it->second.shape());
auto dtype = blob_desc_it->second.data_type();
CHECK_EQ_OR_RETURN(*tensor->shape(), *shape);
CHECK_EQ_OR_RETURN(tensor->dtype()->data_type(), dtype);
if (is_local) {
const auto& device = JUST(Device::MakeDeviceByParallelDesc(*parallel_desc));
CHECK_OR_RETURN(JUST(tensor->device()) == device);
} else {
const auto& nd_sbp_sign_map = op_attribute.nd_sbp_signature().bn_in_op2nd_sbp();
auto nd_sbp_it = nd_sbp_sign_map.find(bn_in_op);
CHECK_OR_RETURN(nd_sbp_it != nd_sbp_sign_map.end())
<< "nd_sbp of " << bn_in_op << " not found in op " << op_attribute.op_conf().name();
NdSbp nd_sbp(nd_sbp_it->second);
CHECK_OR_RETURN(JUST(tensor->nd_sbp()) == SymbolOf(nd_sbp))
<< "The input sbp is not valid for an inplace operation, please try to use non-inplace.";
CHECK_OR_RETURN(JUST(tensor->parallel_desc()) == SymbolOf(*parallel_desc));
}
return Maybe<void>::Ok();
}
std::string GetDeviceTagOfTensor(const std::shared_ptr<Tensor>& tensor) {
if (tensor->is_cuda()) {
return "gpu";
} else {
return "cpu";
}
}
std::string GetDeviceTagByDeviceTypeStr(const std::string& device_type) {
if (device_type == "cuda") {
return "gpu";
} else {
return "cpu";
}
}
bool GetIsDynamicOfTensor(const std::shared_ptr<Tensor>& tensor) {
if (tensor->is_consistent()) {
return false;
} else {
return true;
}
}
Maybe<void> GenNdSbpByTensor(NdSbp* nd_sbp, const std::shared_ptr<Tensor>& tensor) {
nd_sbp->clear_sbp_parallel();
if (tensor->is_local()) {
// NOTE(chengcheng):
// OneFlow Lazy is always consistent. LocalTensor is a special case of ConsistentTensor which
// placement is only this rank, and SbpParallel is Broadcast.
nd_sbp->add_sbp_parallel()->mutable_broadcast_parallel();
} else {
*nd_sbp = *JUST(tensor->nd_sbp());
}
return Maybe<void>::Ok();
}
Maybe<void> GenVariableOpConfNdSbpStringByTensor(VariableOpConf* var_conf,
const std::shared_ptr<Tensor>& tensor) {
var_conf->clear_nd_sbp();
if (tensor->is_local()) {
SbpParallel broadcast;
broadcast.mutable_broadcast_parallel();
var_conf->add_nd_sbp(SbpParallelToString(broadcast));
} else {
const NdSbp& nd_sbp = *JUST(tensor->nd_sbp());
for (const auto& sbp_parallel : nd_sbp.sbp_parallel()) {
var_conf->add_nd_sbp(SbpParallelToString(sbp_parallel));
}
}
return Maybe<void>::Ok();
}
Maybe<const ParallelDesc> GetParallelDescOfTensor(const std::shared_ptr<Tensor>& tensor) {
if (tensor->is_local()) {
const auto& device = JUST(tensor->device());
const auto& placement = JUST(Placement4Device(device));
return placement.shared_from_symbol();
} else {
return JUST(tensor->parallel_desc()).shared_from_symbol();
}
}
Maybe<Scope> NewScopeWithParallelConfAndCurScope(
const std::shared_ptr<cfg::ParallelConf>& parallel_conf) {
std::shared_ptr<Scope> new_scope;
const auto& old_scope = JUST(GetCurrentScope());
JUST(PhysicalRun([&](InstructionsBuilder* builder) -> Maybe<void> {
new_scope = JUST(builder->BuildScopeWithNewParallelConf(old_scope, parallel_conf));
return Maybe<void>::Ok();
}));
// NOTE(chengcheng): need sync vm for get scope right now
JUST(vm::CurrentRankSync());
CHECK_OR_RETURN(new_scope);
return new_scope;
}
Maybe<Scope> NewScopeWithParallelDescByTensor(const std::shared_ptr<Tensor>& tensor) {
std::shared_ptr<cfg::ParallelConf> parallel_conf = std::make_shared<cfg::ParallelConf>();
parallel_conf->InitFromProto(JUST(GetParallelDescOfTensor(tensor))->parallel_conf());
return NewScopeWithParallelConfAndCurScope(parallel_conf);
}
int32_t GetGradAccStep(const JobConfigProto& job_conf) {
if (job_conf.has_train_conf() && job_conf.has_num_gradient_accumulation_steps()
&& job_conf.num_gradient_accumulation_steps() > 1) {
return job_conf.num_gradient_accumulation_steps();
} else {
return 1;
}
}
Maybe<Tensor> GradAccTryInsertUnpackAfterInput(
const OperatorConf& input_conf, const std::shared_ptr<ParallelDesc>& blob_parallel_desc,
const std::shared_ptr<Tensor>& input_tensor) {
auto infer_ctx = JUST(GetCurInferCtx());
int64_t grad_acc_step = GetGradAccStep(infer_ctx->job().job_conf());
if (grad_acc_step > 1) {
// NOTE(chengcheng):
// We assume that the input data is one mini-batch which containing multi micro-batches.
// So we need unpack input data for each micro-batch.
VLOG(2)
<< " Current OneFlow nn.Graph grad acc semantics is different from Torch. \n"
<< " Once call nn.Graph in OneFlow, it indicates a mini-batch. When grad acc steps > 1, \n"
<< " the input tensor of nn.Graph will be unpacked by 0th dim into multiple micro-batches "
<< " and exec them in order.\n";
user_op::UserOpConfWrapperBuilder unpack_builder("System-GradientAccumulation-InputUnpack-"
+ input_conf.name() + "-" + NewUniqueId());
const std::string input_tensor_lbn = GenLogicalBlobName(input_conf.name(), "out");
const auto unpack_op = unpack_builder.OpTypeName("unpack")
.Input("in", input_tensor_lbn)
.Output("out")
.Attr<int32_t>("unpack_num", grad_acc_step)
.ScopeSymbolId(input_conf.scope_symbol_id())
.DeviceTag(input_conf.device_tag())
.Build();
OpAttribute unpack_op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(unpack_op.op_conf()));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op: \n"
<< unpack_op.op_conf().DebugString() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< unpack_op_attr.DebugString() << std::endl;
const std::string unpack_lbn = unpack_op.output("out", 0);
auto unpack_input =
JUST(BuildTensor(unpack_op_attr, "out_0", blob_parallel_desc, /* is_lazy= */ true,
/* is_local= */ input_tensor->is_local()));
TensorNameScope::Global()->Record(unpack_input, unpack_lbn);
return unpack_input;
} else {
return input_tensor;
}
}
Maybe<Tensor> GradAccTryInsertRepeatAfterVar(
const OperatorConf& var_conf, const std::shared_ptr<ParallelDesc>& blob_parallel_desc,
const std::shared_ptr<Tensor>& var_tensor) {
auto infer_ctx = JUST(GetCurInferCtx());
int64_t grad_acc_step = GetGradAccStep(infer_ctx->job().job_conf());
if (grad_acc_step > 1) {
// NOTE(chengcheng):
// We assume that the nn.Graph once call is one mini-batch which containing multi
// micro-batches. So we just repeat variable tensor for each micro-batch.
VLOG(2)
<< " Current OneFlow nn.Graph grad acc semantics is different from Torch. \n"
<< " Once call nn.Graph in OneFlow, it indicates a mini-batch. When grad acc steps > 1, \n"
<< " the var tensor of nn.Graph will be repeated exec for multiple micro-batches. \n";
const std::string var_tensor_lbn = GenLogicalBlobName(var_conf.name(), "out");
user_op::UserOpConfWrapperBuilder repeat_builder("System-GradientAccumulation-VariableRepeat-"
+ var_conf.name() + "-" + NewUniqueId());
const auto repeat_op = repeat_builder.OpTypeName("repeat")
.Input("in", var_tensor_lbn)
.Output("out")
.Attr<int32_t>("repeat_num", grad_acc_step)
.ScopeSymbolId(var_conf.scope_symbol_id())
.DeviceTag(var_conf.device_tag())
.Build();
OpAttribute repeat_op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(repeat_op.op_conf()));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op: \n"
<< repeat_op.op_conf().DebugString() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< repeat_op_attr.DebugString() << std::endl;
const std::string repeat_lbn = repeat_op.output("out", 0);
auto repeat_var =
JUST(BuildTensor(repeat_op_attr, "out_0", blob_parallel_desc, /* is_lazy= */ true,
/* is_local= */ var_tensor->is_local()));
TensorNameScope::Global()->Record(repeat_var, repeat_lbn);
return repeat_var;
} else {
return var_tensor;
}
}
Maybe<Tensor> GradAccTryInsertPackBeforeOutput(const std::shared_ptr<Scope>& scope,
const std::string& output_in_lbn,
const std::string& output_op_name,
const std::shared_ptr<Tensor>& output_tensor) {
auto infer_ctx = JUST(GetCurInferCtx());
int64_t grad_acc_step = GetGradAccStep(infer_ctx->job().job_conf());
if (grad_acc_step > 1) {
// NOTE(chengcheng):
// We assume that the nn.Graph once call is one mini-batch which containing multi
// micro-batches. So we need pack output tensor for each micro-batch to one micro-batch.
VLOG(2)
<< " Current OneFlow nn.Graph grad acc semantics is different from Torch. \n"
<< " Once call nn.Graph in OneFlow, it indicates a mini-batch. When grad acc steps > 1, \n"
<< " the output tensor of nn.Graph will be packed to a big tensor by 0th dim, after exec \n"
<< " for multiple micro-batches. \n";
user_op::UserOpConfWrapperBuilder pack_builder("System-GradientAccumulation-OutputPack-"
+ output_op_name);
const auto output_pack_op = pack_builder.OpTypeName("pack")
.Input("in", output_in_lbn)
.Output("out")
.Attr<int32_t>("pack_num", grad_acc_step)
.ScopeSymbolId(JUST(scope->symbol_id()))
.DeviceTag(GetDeviceTagOfTensor(output_tensor))
.Build();
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(output_pack_op.op_conf()));
auto blob_parallel_desc =
JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
OpAttribute pack_op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(output_pack_op.op_conf()));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op: \n"
<< output_pack_op.op_conf().DebugString() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< pack_op_attr.DebugString() << std::endl;
const std::string pack_lbn = output_pack_op.output("out", 0);
auto packed_output =
JUST(BuildTensor(pack_op_attr, "out_0", blob_parallel_desc, /* is_lazy= */ true,
/* is_local= */ output_tensor->is_local()));
TensorNameScope::Global()->Record(packed_output, pack_lbn);
return packed_output;
} else {
return output_tensor;
}
}
Maybe<void> GradAccTryInsertRepeatTickBeforeSource(
const std::shared_ptr<OperatorConf>& source_op_conf) {
auto infer_ctx = JUST(GetCurInferCtx());
int64_t grad_acc_step = GetGradAccStep(infer_ctx->job().job_conf());
if (grad_acc_step > 1) {
// NOTE(chengcheng):
// We assume that the nn.Graph once call is one mini-batch which containing multi
// micro-batches. So we need repeat source op for each micro-batch in one micro-batch.
VLOG(2)
<< " Current OneFlow nn.Graph grad acc semantics is different from Torch. \n"
<< " Once call nn.Graph in OneFlow, it indicates a mini-batch. When grad acc steps > 1, \n"
<< " the source op of nn.Graph will be repeated exec n-times for multiple micro-batches.\n";
// Insert Tick
OperatorConf tick_conf{};
tick_conf.set_name("System-GradientAccumulation-RepeatTick-DeviceTick-"
+ source_op_conf->name());
tick_conf.set_device_tag(source_op_conf->device_tag());
tick_conf.mutable_device_tick_conf()->set_out("out");
tick_conf.set_scope_symbol_id(source_op_conf->scope_symbol_id());
auto tick_lbn = GenLogicalBlobName(tick_conf.name(), tick_conf.device_tick_conf().out());
OpAttribute tick_op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(tick_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op: \n"
<< tick_conf.DebugString() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< tick_op_attr.DebugString() << std::endl;
user_op::UserOpConfWrapperBuilder repeat_builder(
"System-GradientAccumulation-RepeatTick-Repeat-" + source_op_conf->name());
const auto repeat_op = repeat_builder.OpTypeName("repeat")
.Input("in", tick_lbn)
.Output("out")
.Attr<int32_t>("repeat_num", grad_acc_step)
.ScopeSymbolId(source_op_conf->scope_symbol_id())
.DeviceTag(source_op_conf->device_tag())
.Build();
OpAttribute repeat_op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(repeat_op.op_conf()));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op: \n"
<< repeat_op.op_conf().DebugString() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< repeat_op_attr.DebugString() << std::endl;
const std::string repeat_tick_lbn = repeat_op.output("out", 0);
(*source_op_conf->mutable_user_conf()->mutable_input())[user_op::kUserSourceOpTickInputArgName]
.add_s(repeat_op.output("out", 0));
}
return Maybe<void>::Ok();
}
Maybe<std::string> GradAccTryInsertRepeatAfterFreeVar(const OperatorConf& var_conf) {
const std::string var_tensor_lbn = GenLogicalBlobName(var_conf.name(), "out");
auto infer_ctx = JUST(GetCurInferCtx());
int64_t grad_acc_step = GetGradAccStep(infer_ctx->job().job_conf());
if (grad_acc_step > 1) {
// NOTE(chengcheng):
// We assume that the nn.Graph once call is one mini-batch which containing multi
// micro-batches. So we just repeat variable tensor for each micro-batch.
VLOG(2)
<< " Current OneFlow nn.Graph grad acc semantics is different from Torch. \n"
<< " Once call nn.Graph in OneFlow, it indicates a mini-batch. When grad acc steps > 1, \n"
<< " the free var tensor of nn.Graph will be repeated exec for multiple micro-batches. \n";
user_op::UserOpConfWrapperBuilder repeat_builder("System-GradientAccumulation-VariableRepeat-"
+ var_conf.name() + "-" + NewUniqueId());
const auto repeat_op = repeat_builder.OpTypeName("repeat")
.Input("in", var_tensor_lbn)
.Output("out")
.Attr<int32_t>("repeat_num", grad_acc_step)
.ScopeSymbolId(var_conf.scope_symbol_id())
.DeviceTag(var_conf.device_tag())
.Build();
OpAttribute repeat_op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(repeat_op.op_conf()));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op: \n"
<< repeat_op.op_conf().DebugString() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< repeat_op_attr.DebugString() << std::endl;
const std::string repeat_lbn = repeat_op.output("out", 0);
return repeat_lbn;
} else {
return var_tensor_lbn;
}
}
Maybe<void> AddFreeEagerTensorToVariableOp(const std::shared_ptr<Tensor>& input_tensor) {
CHECK_OR_RETURN(input_tensor->is_eager());
const std::string& empty_lbn = TensorNameScope::Global()->Lookup(input_tensor);
CHECK_OR_RETURN(empty_lbn.empty());
std::shared_ptr<Scope> scope = JUST(NewScopeWithParallelDescByTensor(input_tensor));
OperatorConf op_conf;
op_conf.set_scope_symbol_id(JUST(scope->symbol_id()));
op_conf.set_device_tag(GetDeviceTagOfTensor(input_tensor));
VariableOpConf* var_conf = op_conf.mutable_variable_conf();
var_conf->set_out("out");
input_tensor->shape()->ToProto(var_conf->mutable_shape());
var_conf->set_data_type(input_tensor->dtype()->data_type());
// NOTE(chengcheng): VariableOpConf initializer_conf is useless because variable is inited
// by EagerTensor.
var_conf->mutable_initializer()->mutable_empty_conf();
JUST(GenVariableOpConfNdSbpStringByTensor(var_conf, input_tensor));
// NOTE(chengcheng): Free EagerTensor not trainable
var_conf->set_trainable(false);
auto infer_ctx = JUST(GetCurInferCtx());
// NOTE(chengcheng): MUST reset unique op name before InferCtx::AddOp, FreeEagerTensor has no
// name so just new a unique name for it.
const std::string new_op_name = *JUST(infer_ctx->NewUniqueOpNameByFunctionalOpConf(op_conf));
op_conf.set_name(new_op_name);
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " try to add op: \n"
<< op_conf.DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op : \n"
<< op_conf.name() << " for FreeEagerTensor.\n";
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< op_attr.DebugString() << " for FreeEagerTensor.\n";
// NOTE(chengcheng): MUST store this tensor to MultiClientSessionContext for graph runtime bind.
const std::string graph_name = *JUST(JUST(GlobalJobBuildAndInferCtxMgr())->GetCurrentJobName());
const std::string lbn = GenLogicalBlobName(new_op_name, "out");
Global<MultiClientSessionContext>::Get()->StoreFreeEagerTensorWithNameByGraphName(
graph_name, input_tensor, new_op_name);
// NOTE(chengcheng): MUST record this eager_tensor name as new variable output lbn.
// NOTE(chengcheng): in GradAcc FreeEagerTensor need insert repeat op, but there is no need to
// create a new tensor for repeat op out. We just set repeat lbn as this free eager tensor's lbn.
TensorNameScope::Global()->Record(input_tensor,
*JUST(GradAccTryInsertRepeatAfterFreeVar(op_conf)));
return Maybe<void>::Ok();
}
} // namespace
Maybe<void> LazyInterpreter::ApplyImpl(const FeedInputOpExpr& op_expr, const TensorTuple& inputs,
TensorTuple* outputs, const OpExprInterpContext& ctx) const {
// NOTE(chengcheng): inputs[0] is the EagerTensor
CHECK_EQ_OR_RETURN(inputs.size(), 1);
CHECK_EQ_OR_RETURN(op_expr.input_size(), 1);
const std::shared_ptr<Tensor>& input_tensor = inputs.at(0);
CHECK_OR_RETURN(input_tensor->is_eager());
std::shared_ptr<Scope> scope = JUST(NewScopeWithParallelDescByTensor(input_tensor));
OperatorConf op_conf;
op_conf.set_name(op_expr.op_name()); // construct by python nn.Graph
op_conf.set_scope_symbol_id(JUST(scope->symbol_id()));
op_conf.set_device_tag(GetDeviceTagOfTensor(input_tensor));
// NOTE(chengcheng):
// We contruct InputOpConf instead of FeedInputOpConf because FeedInputOpExpr JUST for getting
// input EagerTensor.
InputOpConf* input_conf = op_conf.mutable_input_conf();
input_conf->set_out("out");
InterfaceBlobConf* blob_conf = input_conf->mutable_blob_conf();
input_tensor->shape()->ToProto(blob_conf->mutable_shape());
blob_conf->set_data_type(input_tensor->dtype()->data_type());
// NOTE(chengcheng): is_dynamic true has conflict in consistent lazy job even if world size 1.
// this flag will be removed in the future.
// blob_conf->set_is_dynamic(GetIsDynamicOfTensor(input_tensor));
blob_conf->set_is_dynamic(false);
JUST(GenNdSbpByTensor(blob_conf->mutable_nd_sbp(), input_tensor));
auto infer_ctx = JUST(GetCurInferCtx());
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " try to add op: \n: " << op_conf.DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op : \n"
<< op_conf.name() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< op_attr.DebugString() << std::endl;
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(op_conf));
auto blob_parallel_desc = JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
// Check outputs num and setup output tensor properties.
CHECK_EQ_OR_RETURN(outputs->size(), 1);
CHECK_EQ_OR_RETURN(op_expr.output_size(), 1);
CHECK_OR_RETURN(!(*outputs)[0]);
const std::string obn = "out"; // NOTE(chengcheng): obn is NOT op_expr.indexed_obns
auto origin_input = JUST(BuildTensor(op_attr, obn, blob_parallel_desc, /* is_lazy= */ true,
/* is_local= */ input_tensor->is_local()));
TensorNameScope::Global()->Record(origin_input, GenLogicalBlobName(op_conf.name(), obn));
// NOTE(chengcheng): Do GradAcc pass when add input op.
(*outputs)[0] = JUST(GradAccTryInsertUnpackAfterInput(op_conf, blob_parallel_desc, origin_input));
return Maybe<void>::Ok();
}
Maybe<void> LazyInterpreter::ApplyImpl(const FeedVariableOpExpr& op_expr, const TensorTuple& inputs,
TensorTuple* outputs, const OpExprInterpContext& ctx) const {
// NOTE(chengcheng): inputs[0] is the EagerTensor
CHECK_EQ_OR_RETURN(inputs.size(), 1);
CHECK_EQ_OR_RETURN(op_expr.input_size(), 1);
const std::shared_ptr<Tensor>& input_tensor = inputs.at(0);
CHECK_OR_RETURN(input_tensor->is_eager());
std::shared_ptr<Scope> scope = JUST(NewScopeWithParallelDescByTensor(input_tensor));
OperatorConf op_conf;
op_conf.set_name(op_expr.op_name()); // construct by python nn.Graph
op_conf.set_scope_symbol_id(JUST(scope->symbol_id()));
op_conf.set_device_tag(GetDeviceTagOfTensor(input_tensor));
// NOTE(chengcheng):
// We contruct VariableOpConf instead of FeedVariableOpConf because FeedVariableOpExpr JUST
// for getting input EagerTensor.
VariableOpConf* var_conf = op_conf.mutable_variable_conf();
var_conf->set_out("out");
input_tensor->shape()->ToProto(var_conf->mutable_shape());
var_conf->set_data_type(input_tensor->dtype()->data_type());
// NOTE(chengcheng): VariableOpConf initializer_conf is useless because variable is inited
// by EagerTensor.
var_conf->mutable_initializer()->mutable_empty_conf();
JUST(GenVariableOpConfNdSbpStringByTensor(var_conf, input_tensor));
if (!input_tensor->requires_grad()) { var_conf->set_trainable(false); }
if (input_tensor->requires_grad()) {
double l2 = JUST(ctx.attrs.GetAttr<double>("l2"));
if (unlikely(l2 != 0.0)) { var_conf->mutable_regularizer()->mutable_l1_l2_conf()->set_l2(l2); }
}
auto infer_ctx = JUST(GetCurInferCtx());
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " try to add op: \n: " << op_conf.DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op : \n"
<< op_conf.name() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< op_attr.DebugString() << std::endl;
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(op_conf));
auto blob_parallel_desc = JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
// Check outputs num and setup output tensor properties.
CHECK_EQ_OR_RETURN(outputs->size(), 1);
CHECK_EQ_OR_RETURN(op_expr.output_size(), 1);
CHECK_OR_RETURN(!(*outputs)[0]);
const std::string obn = "out"; // NOTE(chengcheng): obn is NOT op_expr.indexed_obns
auto origin_var = JUST(BuildTensor(op_attr, obn, blob_parallel_desc, /* is_lazy= */ true,
/* is_local */ input_tensor->is_local()));
// NOTE(chengcheng): Record variable op output LazyTenosr
TensorNameScope::Global()->Record(origin_var, GenLogicalBlobName(op_conf.name(), obn));
// NOTE(chengcheng): Record EagerTensor as variable tensor name
TensorNameScope::Global()->Record(input_tensor, GenLogicalBlobName(op_conf.name(), obn));
(*outputs)[0] = JUST(GradAccTryInsertRepeatAfterVar(op_conf, blob_parallel_desc, origin_var));
return Maybe<void>::Ok();
}
Maybe<void> LazyInterpreter::ApplyImpl(const FetchOutputOpExpr& op_expr, const TensorTuple& inputs,
TensorTuple* outputs, const OpExprInterpContext& ctx) const {
// NOTE(chengcheng): inputs[0] is the LazyTensor
CHECK_EQ_OR_RETURN(inputs.size(), 1);
CHECK_EQ_OR_RETURN(op_expr.input_size(), 1);
const std::shared_ptr<Tensor>& input_tensor = inputs.at(0);
std::string input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
// Lazy tensor must has lbn.
// Eager tensor may has lbn if it has already been treated as an output of a variable op
// or an output of an inplace op.
if (input_lbn.empty()) {
CHECK_OR_RETURN(input_tensor->is_eager());
// This output tensor is a new free eager tensor, so treat it as a new variable op output.
JUST(AddFreeEagerTensorToVariableOp(input_tensor));
input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
}
CHECK_OR_RETURN(!input_lbn.empty()); // lbn must exist.
std::shared_ptr<Scope> scope = JUST(NewScopeWithParallelDescByTensor(input_tensor));
std::shared_ptr<Tensor> output_tensor =
JUST(GradAccTryInsertPackBeforeOutput(scope, input_lbn, op_expr.op_name(), input_tensor));
const std::string output_lbn = TensorNameScope::Global()->Lookup(output_tensor);
OperatorConf op_conf;
op_conf.set_name(op_expr.op_name()); // construct by python nn.Graph
op_conf.set_scope_symbol_id(JUST(scope->symbol_id()));
op_conf.set_device_tag(GetDeviceTagOfTensor(output_tensor));
// NOTE(chengcheng):
// We contruct OutputOpConf instead of FetchOutputOpConf because FetchOutputOpExpr JUST
// for get nn.Graph output LazyTensor.
OutputOpConf* output_conf = op_conf.mutable_output_conf();
output_conf->set_in(output_lbn);
output_conf->set_out("out");
InterfaceBlobConf* blob_conf = output_conf->mutable_blob_conf();
output_tensor->shape()->ToProto(blob_conf->mutable_shape());
blob_conf->set_data_type(output_tensor->dtype()->data_type());
// NOTE(chengcheng): is_dynamic true has conflict in consistent lazy job even if world size 1.
// this flag will be removed in the future.
// blob_conf->set_is_dynamic(GetIsDynamicOfTensor(output_tensor));
blob_conf->set_is_dynamic(false);
JUST(GenNdSbpByTensor(blob_conf->mutable_nd_sbp(), output_tensor));
auto infer_ctx = JUST(GetCurInferCtx());
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " try to add op: \n"
<< op_conf.DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op : \n"
<< op_conf.name() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< op_attr.DebugString() << std::endl;
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(op_conf));
auto blob_parallel_desc = JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
// Check outputs num and setup output tensor properties.
CHECK_EQ_OR_RETURN(outputs->size(), 1);
CHECK_EQ_OR_RETURN(op_expr.output_size(), 1);
CHECK_OR_RETURN(!(*outputs)[0]);
const std::string obn = "out"; // NOTE(chengcheng): obn is NOT op_expr.indexed_obns
(*outputs)[0] = JUST(BuildTensor(op_attr, obn, blob_parallel_desc, /* is_lazy= */ false,
/* is_local= */ output_tensor->is_local()));
return Maybe<void>::Ok();
}
Maybe<void> LazyInterpreter::ApplyImpl(const ImageDecoderRandomCropResizeOpExpr& op_expr,
const TensorTuple& inputs, TensorTuple* outputs,
const OpExprInterpContext& ctx) const {
CHECK_EQ_OR_RETURN(inputs.size(), 1);
CHECK_EQ_OR_RETURN(op_expr.input_size(), 1);
const std::shared_ptr<Tensor>& input_tensor = inputs.at(0);
const std::string& input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
CHECK_OR_RETURN(!input_lbn.empty()); // lbn must exist.
auto op_conf = JUST(OpInterpUtil::GenBuiltinOpConf(op_expr, ctx.attrs));
std::string device_tag;
if (IsCpuOnly(*op_conf)) {
device_tag = "cpu";
} else {
device_tag = "gpu";
}
std::shared_ptr<cfg::ParallelConf> parallel_conf = std::make_shared<cfg::ParallelConf>();
parallel_conf->InitFromProto(JUST(GetParallelDescOfTensor(input_tensor))->parallel_conf());
parallel_conf->set_device_tag(device_tag); // NOTE(chengcheng): only support gpu decode.
const auto& scope = JUST(NewScopeWithParallelConfAndCurScope(parallel_conf));
op_conf->set_scope_symbol_id(JUST(scope->symbol_id()));
op_conf->set_device_tag(device_tag);
// NOTE(chengcheng): replace right input_lbn and obn
ReplaceInputLbnInOpCustomizedConf(op_conf.get(), /* ibn */ "in", input_lbn);
op_conf->mutable_image_decoder_random_crop_resize_conf()->set_out("out");
auto infer_ctx = JUST(GetCurInferCtx());
// NOTE(chengcheng): MUST reset unique op name before InferCtx::AddOp
const std::string new_op_name = *JUST(infer_ctx->NewUniqueOpNameByFunctionalOpConf(*op_conf));
op_conf->set_name(new_op_name);
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " try to add op: \n"
<< op_conf->DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(*op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op : \n"
<< op_conf->name() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< op_attr.DebugString() << std::endl;
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(*op_conf));
auto blob_parallel_desc = JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
// Check outputs num and setup output tensor properties.
CHECK_EQ_OR_RETURN(outputs->size(), 1);
CHECK_EQ_OR_RETURN(op_expr.output_size(), 1);
CHECK_OR_RETURN(!(*outputs)[0]);
const std::string obn = "out"; // NOTE(chengcheng): obn is NOT op_expr.indexed_obns
(*outputs)[0] = JUST(BuildTensor(op_attr, obn, blob_parallel_desc, /* is_lazy= */ true,
/* is_local= */ input_tensor->is_local()));
TensorNameScope::Global()->Record((*outputs)[0], GenLogicalBlobName(new_op_name, obn));
return Maybe<void>::Ok();
}
namespace {
Maybe<void> LazyInterpreterApplyImplForSourceUserOpExpr(const UserOpExpr& op_expr,
TensorTuple* outputs,
const OpExprInterpContext& ctx) {
NonRecursiveMetaInfoConsistencyCheckScope non_scope;
bool is_local;
std::shared_ptr<const ParallelDesc> parallel_desc;
if (ctx.parallel_desc.has_value()) {
// NOTE(chengcheng): consistent
CHECK_OR_RETURN(!ctx.device.has_value());
const auto& parallel_desc_sym = JUST(ctx.parallel_desc);
parallel_desc = parallel_desc_sym.shared_from_symbol();
JUST(MetaInfoConsistencyCheck(parallel_desc_sym, ctx.nd_sbp, 1));
is_local = false;
} else {
// NOTE(chengcheng): local
CHECK_OR_RETURN(!ctx.nd_sbp.has_value());
if (ctx.device.has_value()) {
const auto& device = JUST(ctx.device);
const auto& placement = JUST(Placement4Device(device));
parallel_desc = placement.shared_from_symbol();
} else {
// NOTE(chengcheng): if functor NOT set device, using cpu device default.
const auto& device = JUST(Device::New("cpu"));
const auto& placement = JUST(Placement4Device(device));
parallel_desc = placement.shared_from_symbol();
}
is_local = true;
}
std::shared_ptr<cfg::ParallelConf> parallel_conf = std::make_shared<cfg::ParallelConf>();
parallel_conf->InitFromProto(parallel_desc->parallel_conf());
const auto& scope = JUST(NewScopeWithParallelConfAndCurScope(parallel_conf));
auto op_conf = JUST(OpInterpUtil::GenBuiltinOpConf(op_expr, ctx.attrs));
op_conf->set_scope_symbol_id(JUST(scope->symbol_id()));
op_conf->set_device_tag(parallel_conf->device_tag());
auto infer_ctx = JUST(GetCurInferCtx());
// NOTE(chengcheng): MUST reset unique op name before InferCtx::AddOp
const std::string new_op_name = *JUST(infer_ctx->NewUniqueOpNameByFunctionalOpConf(*op_conf));
// NOTE(chengcheng): for UserOp, NOT only reset op_name, but also the output values.
op_conf->set_name(new_op_name);
for (auto& pair : *(op_conf->mutable_user_conf()->mutable_output())) {
auto& list_s = pair.second;
for (int i = 0; i < list_s.s_size(); ++i) {
std::string old_lbn = list_s.s(i);
LogicalBlobId old_lbi = GenLogicalBlobId(old_lbn);
// NOTE(chengcheng): MUST change the old_lbn to new op name.
std::string new_lbn = GenLogicalBlobName(new_op_name, old_lbi.blob_name());
list_s.set_s(i, new_lbn);
}
}
JUST(GradAccTryInsertRepeatTickBeforeSource(op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " try to add op: \n"
<< op_conf->DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(*op_conf));
VLOG(2) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name() << " add op : \n"
<< op_conf->name() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << infer_ctx->job().job_conf().job_name()
<< " infer and and op attr : \n"
<< op_attr.DebugString() << std::endl;
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(*op_conf));
auto blob_parallel_desc = JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
// Check outputs num and setup output tensor properties.
CHECK_EQ_OR_RETURN(outputs->size(), op_expr.output_size());
for (int i = 0; i < op_expr.output_size(); ++i) {
CHECK_OR_RETURN(!(*outputs)[i]);
const std::string& obn = op_expr.indexed_obns().at(i);
(*outputs)[i] =
JUST(BuildTensor(op_attr, obn, blob_parallel_desc, /* is_lazy= */ true, is_local));
TensorNameScope::Global()->Record((*outputs)[i], GenLogicalBlobName(new_op_name, obn));
}
return Maybe<void>::Ok();
}
Maybe<void> LazyInterpreterApplyImplForCopyUserOpExpr(const UserOpExpr& op_expr,
const TensorTuple& inputs,
TensorTuple* outputs,
const OpExprInterpContext& ctx) {
CHECK_OR_RETURN(op_expr.op_type_name() == "copy");
CHECK_EQ_OR_RETURN(inputs.size(), 1);
CHECK_EQ_OR_RETURN(op_expr.input_size(), 1);
const std::shared_ptr<Tensor>& input_tensor = inputs.at(0);
std::string input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
if (input_lbn.empty()) {
JUST(AddFreeEagerTensorToVariableOp(input_tensor));
input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
}
CHECK_OR_RETURN(!input_lbn.empty()); // lbn must exist.
std::string device_type = JUST(ctx.attrs.GetAttr<std::string>("device_type"));
int64_t device_id = JUST(ctx.attrs.GetAttr<int64_t>("device_id"));
CHECK_EQ_OR_RETURN(outputs->size(), 1);
CHECK_EQ_OR_RETURN(op_expr.output_size(), 1);
if (input_tensor->is_local()) {
(*outputs)[0] =
JUST(MirroredTensor::MakeTensor(input_tensor->shape(), input_tensor->dtype()->data_type(),
JUST(Device::New(device_type, device_id)),
/* is_lazy= */ true,
/*requires_grad=*/false, /*is_leaf=*/true));
} else {
ParallelConf parallel_conf = JUST(input_tensor->parallel_desc())->parallel_conf();
parallel_conf.set_device_tag(GetDeviceTagByDeviceTypeStr(device_type));
ParallelDesc parallel_desc(parallel_conf);
(*outputs)[0] =
JUST(ConsistentTensor::MakeTensor(input_tensor->shape(), input_tensor->dtype()->data_type(),
JUST(input_tensor->nd_sbp()), SymbolOf(parallel_desc),
/* is_lazy= */ true,
/*requires_grad=*/false, /*is_leaf=*/true));
}
// NOTE(chengcheng): output tensor lbn is SAME with input tensor.
TensorNameScope::Global()->Record(outputs->at(0), input_lbn);
return Maybe<void>::Ok();
}
} // namespace
Maybe<void> LazyInterpreter::ApplyImpl(const UserOpExpr& op_expr, const TensorTuple& inputs,
TensorTuple* outputs, const OpExprInterpContext& ctx) const {
CHECK_EQ_OR_RETURN(inputs.size(), op_expr.input_size());
// NOTE(chengcheng): Handle special UserOp such as:
// 1. [Source UserOp] : OFRecordReader, CoinFlip
// 2. [Change Placement/ParallelDesc UserOp] : to(copy)/to_global/parallel_cast
// 3. [Multi-Inputs & Different ParallelDesc for each input UserOp] : like there are 2 inputs,
// one from CPU and the other from GPU.
// ..., etc.
//
// Need add if for each special UserOp for infer:
// 1. op_conf: device_tag,
// 2. output tensor: is_local,
// 3. op_parallel_conf for build new scope with parallel_desc
// 4. output blob (different with tensor) -> parallel_conf
// 5. need add to JobBuildAndInferCtx (like copy will NOT need)
if (inputs.size() == 0) {
// NOTE(chengcheng): handle for source UserOp like OFRecordReader, CoinFlip
return LazyInterpreterApplyImplForSourceUserOpExpr(op_expr, outputs, ctx);
}
if (op_expr.op_type_name() == "copy") {
// NOTE(chengcheng): handle for copy UserOp which will NOT add op to job.
return LazyInterpreterApplyImplForCopyUserOpExpr(op_expr, inputs, outputs, ctx);
}
// NOTE(chengcheng):
// Normal UserOp inputs size >= 1 for infer parallel_desc.
CHECK_GE_OR_RETURN(inputs.size(), 1);
auto op_conf = JUST(OpInterpUtil::GenBuiltinOpConf(op_expr, ctx.attrs));
std::shared_ptr<Scope> scope = JUST(NewScopeWithParallelDescByTensor(inputs.at(0)));
op_conf->set_scope_symbol_id(JUST(scope->symbol_id()));
const std::string device_tag = GetDeviceTagOfTensor(inputs.at(0));
const bool is_local = inputs.at(0)->is_local();
const std::shared_ptr<const ParallelDesc> parallel_desc =
JUST(GetParallelDescOfTensor(inputs.at(0)));
op_conf->set_device_tag(device_tag);
auto infer_ctx = JUST(GetCurInferCtx());
// NOTE(chengcheng): MUST reset unique op name before InferCtx::AddOp
const std::string new_op_name = *JUST(infer_ctx->NewUniqueOpNameByFunctionalOpConf(*op_conf));
const std::string graph_name = infer_ctx->job().job_conf().job_name();
for (int i = 0; i < inputs.size(); ++i) {
const auto& input_tensor = inputs.at(i);
CHECK_OR_RETURN(device_tag == GetDeviceTagOfTensor(input_tensor))
<< " Lazy nn.Graph name : " << graph_name << " encountered ERROR where multi-input tensor"
<< " has different device types in module/op_name: " << new_op_name
<< ". Please use tensor.to() or tensor.to_global() to synchronize all the input with the "
"same device.";
// TODO: Print out all the placement
CHECK_OR_RETURN(parallel_desc->Equals(*JUST(GetParallelDescOfTensor(input_tensor))))
<< " Lazy nn.Graph name : " << graph_name << " encountered ERROR where multi-input tensor"
<< " has different placements in module/op_name: " << new_op_name
<< ". Please use tensor.to() or tensor.to_global() to synchronize all the input with the "
"same placement.";
CHECK_EQ_OR_RETURN(is_local, input_tensor->is_local());
const std::string& ibn = op_expr.indexed_ibns().at(i);
std::string lbn = TensorNameScope::Global()->Lookup(input_tensor);
if (lbn.empty()) {
JUST(AddFreeEagerTensorToVariableOp(input_tensor));
lbn = TensorNameScope::Global()->Lookup(input_tensor);
}
CHECK_OR_RETURN(!lbn.empty()); // NOTE(chengcheng): lbn must not empty now.
ReplaceInputLbnInOpCustomizedConf(op_conf.get(), ibn, lbn);
}
// NOTE(chengcheng): for UserOp, NOT only reset op_name, but also the output values.
op_conf->set_name(new_op_name);
for (auto& pair : *(op_conf->mutable_user_conf()->mutable_output())) {
auto& list_s = pair.second;
for (int i = 0; i < list_s.s_size(); ++i) {
std::string old_lbn = list_s.s(i);
LogicalBlobId old_lbi = GenLogicalBlobId(old_lbn);
// NOTE(chengcheng): MUST change the old_lbn to new op name.
std::string new_lbn = GenLogicalBlobName(new_op_name, old_lbi.blob_name());
list_s.set_s(i, new_lbn);
}
}
// Check outputs num and setup output tensor properties.
CHECK_EQ_OR_RETURN(outputs->size(), op_expr.output_size());
// Disable boxing if the computation is inplace.
for (int i = 0; i < op_expr.output_size(); ++i) {
const auto& output = outputs->at(i);
if (output) {
const std::string& lbn = TensorNameScope::Global()->Lookup(output);
CHECK_OR_RETURN(!lbn.empty()) << "The output which index is " << i
<< " has no tensor name, please check whether the inplaced "
"output is also an input of the operation "
<< new_op_name;
JUST(infer_ctx->DisableBoxing(lbn));
}
}
VLOG(2) << "Lazy nn.Graph name " << graph_name << " try to add op: \n"
<< op_conf->DebugString() << std::endl;
OpAttribute op_attr = *JUST(infer_ctx->AddAndInferConsistentOp(*op_conf));
VLOG(2) << "Lazy nn.Graph name " << graph_name << " add op : \n" << op_conf->name() << std::endl;
VLOG(3) << "Lazy nn.Graph name " << graph_name << " infer and and op attr : \n"
<< op_attr.DebugString() << std::endl;
int64_t parallel_desc_sym_id = JUST(scope->GetParallelDescSymbolId(*op_conf));
auto blob_parallel_desc = JUST(GetSymbol<cfg::ParallelConf, ParallelDesc>(parallel_desc_sym_id));
for (int i = 0; i < op_expr.output_size(); ++i) {
const std::string& obn = op_expr.indexed_obns().at(i);
if (!(*outputs)[i]) {
(*outputs)[i] =
JUST(BuildTensor(op_attr, obn, blob_parallel_desc, /* is_lazy= */ true, is_local));
} else {
VLOG(2) << "Lazy nn.Graph name " << graph_name << " op name " << new_op_name
<< " run with inplace.";
const std::shared_ptr<Tensor>& inplace_out = (*outputs)[i];
JUST(CheckTensorMatchAttr(inplace_out, op_attr, obn, blob_parallel_desc, is_local));
}
TensorNameScope::Global()->Record((*outputs)[i], GenLogicalBlobName(new_op_name, obn));
}
return Maybe<void>::Ok();
}
Maybe<void> LazyInterpreter::ApplyImpl(const FunctionOpExpr& op_expr, const TensorTuple& inputs,
TensorTuple* outputs, const OpExprInterpContext& ctx) const {
// TODO(hjchen2)
OF_UNIMPLEMENTED() << "The type " << op_expr.op_type_name()
<< " has not been supported in LazyInterpreter::Apply.";
return Maybe<void>::Ok();
}
Maybe<void> LazyInterpreter::ApplyImpl(const ConsistentToConsistentOpExpr& op_expr,
const TensorTuple& inputs, TensorTuple* outputs,
const OpExprInterpContext& ctx) const {
CHECK_EQ_OR_RETURN(op_expr.input_size(), 1);
CHECK_EQ_OR_RETURN(inputs.size(), 1);
const auto& input_tensor = inputs[0];
CHECK_OR_RETURN(input_tensor->is_consistent());
CHECK_OR_RETURN(ctx.parallel_desc.has_value());
const auto& parallel_desc_sym = JUST(ctx.parallel_desc);
CHECK_OR_RETURN(ctx.nd_sbp.has_value());
const auto& sbp_sym = JUST(ctx.nd_sbp);
std::string input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
if (input_lbn.empty()) {
JUST(AddFreeEagerTensorToVariableOp(input_tensor));
input_lbn = TensorNameScope::Global()->Lookup(input_tensor);
CHECK_OR_RETURN(!input_lbn.empty());
}
std::shared_ptr<Tensor> input_proxy;
if (!JUST(GetParallelDescOfTensor(input_tensor))
->Equals(*parallel_desc_sym.shared_from_symbol())) {
// NOTE(zwx): The input tensor's parallel_desc is not equal to that of op's,
// create a proxy input with the parallel_desc that is the same as op's
input_proxy =
JUST(ConsistentTensor::MakeTensor(input_tensor->shape(), input_tensor->dtype()->data_type(),
JUST(input_tensor->nd_sbp()), parallel_desc_sym,
/* is_lazy= */ true,
/*requires_grad=*/false, /*is_leaf=*/true));
TensorNameScope::Global()->Record(input_proxy, input_lbn);
}
CHECK_EQ_OR_RETURN(op_expr.output_size(), 1);
CHECK_EQ_OR_RETURN(outputs->size(), 1);
CHECK_OR_RETURN(!(*outputs)[0]);
if (!op_expr.grad_nd_sbp().has_value() && sbp_sym == JUST(input_tensor->nd_sbp())) {
// NOTE(chengcheng): if to_global ONLY change placement (nd_sbp and grad_nd_sbp is same),
// there is no need to build hierarchical_parallel_cast op.
if (input_proxy) {
(*outputs)[0] = input_proxy;
} else {
(*outputs)[0] = input_tensor;
}
return Maybe<void>::Ok();
}
// build parallel cast op expr
std::shared_ptr<std::vector<std::string>> sbp_list_ptr = JUST(GetNdSbpStrList(sbp_sym));
std::string grad_mode;
std::vector<std::string> grad_sbp_str_list;
if (op_expr.grad_nd_sbp().has_value()) {
grad_mode = "manual";
grad_sbp_str_list = *JUST(GetNdSbpStrList(JUST(op_expr.grad_nd_sbp())));
} else {
grad_mode = "identity";
}
std::shared_ptr<UserOpExpr> parallel_cast_op_expr =
JUST(OpBuilder("hierarchical_parallel_cast", "trivial_op_name")
.Input("in")
.Output("out")
.Attr<std::vector<std::string>>("nd_sbp", *sbp_list_ptr)
.Attr<std::string>("grad_mode", grad_mode)
.Attr<std::vector<std::string>>("grad_nd_sbp", grad_sbp_str_list)
.Build());
if (input_proxy) {
(*outputs)[0] =
JUST(OpInterpUtil::Dispatch<one::Tensor>(*parallel_cast_op_expr, {input_proxy}));
} else {
(*outputs)[0] =
JUST(OpInterpUtil::Dispatch<one::Tensor>(*parallel_cast_op_expr, {input_tensor}));
}
return Maybe<void>::Ok();
}
} // namespace one
} // namespace oneflow
| 49.611058 | 100 | 0.66823 | [
"shape",
"vector"
] |
db184f5a1b4e45a0f668c32556da9fe4494b69ec | 21,698 | cc | C++ | chrome/browser/webauthn/authenticator_request_dialog_model.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/webauthn/authenticator_request_dialog_model.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/webauthn/authenticator_request_dialog_model.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/webauthn/authenticator_request_dialog_model.h"
#include <iterator>
#include <utility>
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "build/build_config.h"
#include "device/fido/features.h"
#include "device/fido/fido_authenticator.h"
#include "device/fido/pin.h"
namespace {
// Attempts to auto-select the most likely transport that will be used to
// service this request, or returns base::nullopt if unsure.
base::Optional<device::FidoTransportProtocol> SelectMostLikelyTransport(
const device::FidoRequestHandlerBase::TransportAvailabilityInfo&
transport_availability,
base::Optional<device::FidoTransportProtocol> last_used_transport,
bool cable_extension_provided,
bool have_paired_phones) {
const base::flat_set<AuthenticatorTransport>& candidate_transports(
transport_availability.available_transports);
// If there is only one transport available, select that instead of showing a
// transport selection screen with only a single item.
if (candidate_transports.size() == 1) {
return *candidate_transports.begin();
}
// The remaining decisions apply to GetAssertion requests only. For
// MakeCredential, the user needs to choose from transport selection.
if (transport_availability.request_type !=
device::FidoRequestHandlerBase::RequestType::kGetAssertion) {
return base::nullopt;
}
// Auto advance to the platform authenticator if it has a matching credential
// for the (possibly empty) allow list.
if (base::Contains(candidate_transports,
device::FidoTransportProtocol::kInternal) &&
*transport_availability
.has_recognized_platform_authenticator_credential) {
return device::FidoTransportProtocol::kInternal;
}
// If the RP supplied the caBLE extension then respect that and always select
// caBLE for GetAssertion operations.
if (cable_extension_provided &&
base::Contains(
candidate_transports,
AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy)) {
return AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy;
}
// The remaining decisions are based on the most recently used successful
// transport.
if (!last_used_transport ||
!base::Contains(candidate_transports, *last_used_transport)) {
return base::nullopt;
}
// Auto-advancing to platform authenticator based on credential availability
// has been handled above. Hence, at this point it does not have a matching
// credential and should not be advanced to, because it would fail
// immediately.
if (*last_used_transport == device::FidoTransportProtocol::kInternal) {
return base::nullopt;
}
// Auto-advancing to caBLE based on a caBLEv1 request extension has been
// handled above. For caBLEv2, only auto-advance if the user has previously
// paired a caBLEv2 authenticator.
if (*last_used_transport ==
device::FidoTransportProtocol::kCloudAssistedBluetoothLowEnergy &&
!have_paired_phones) {
return base::nullopt;
}
return *last_used_transport;
}
} // namespace
AuthenticatorRequestDialogModel::EphemeralState::EphemeralState() = default;
AuthenticatorRequestDialogModel::EphemeralState::~EphemeralState() = default;
void AuthenticatorRequestDialogModel::EphemeralState::Reset() {
selected_authenticator_id_ = base::nullopt;
saved_authenticators_.RemoveAllAuthenticators();
responses_.clear();
}
AuthenticatorRequestDialogModel::AuthenticatorRequestDialogModel(
const std::string& relying_party_id)
: relying_party_id_(relying_party_id) {}
AuthenticatorRequestDialogModel::~AuthenticatorRequestDialogModel() {
for (auto& observer : observers_)
observer.OnModelDestroyed(this);
}
void AuthenticatorRequestDialogModel::SetCurrentStep(Step step) {
current_step_ = step;
for (auto& observer : observers_)
observer.OnStepTransition();
}
void AuthenticatorRequestDialogModel::HideDialog() {
SetCurrentStep(Step::kNotStarted);
}
void AuthenticatorRequestDialogModel::StartFlow(
TransportAvailabilityInfo transport_availability,
base::Optional<device::FidoTransportProtocol> last_used_transport,
bool is_conditional) {
DCHECK_EQ(current_step(), Step::kNotStarted);
transport_availability_ = std::move(transport_availability);
last_used_transport_ = last_used_transport;
if (is_conditional) {
// If this is a conditional request, keep the UI hidden while dispatching
// requests.
SetCurrentStep(Step::kSubtleUI);
} else {
StartGuidedFlowForMostLikelyTransportOrShowTransportSelection();
}
}
void AuthenticatorRequestDialogModel::StartOver() {
ephemeral_state_.Reset();
for (auto& observer : observers_)
observer.OnStartOver();
SetCurrentStep(Step::kTransportSelection);
}
void AuthenticatorRequestDialogModel::
StartGuidedFlowForMostLikelyTransportOrShowTransportSelection() {
DCHECK(current_step() == Step::kNotStarted);
// If no authenticator other than the one for the native Windows API is
// available, or if the sole authenticator is caBLE, but there's no caBLE
// extension nor paired phone, then don't show Chrome UI but proceed straight
// to the native Windows UI.
if (transport_availability_.has_win_native_api_authenticator &&
!win_native_api_already_tried_) {
const auto& transports = transport_availability_.available_transports;
if (transports.empty() ||
(transports.size() == 1 &&
base::Contains(
transports,
AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy) &&
!cable_extension_provided_ && !have_paired_phones_)) {
StartWinNativeApi();
return;
}
}
auto most_likely_transport =
SelectMostLikelyTransport(transport_availability_, last_used_transport_,
cable_extension_provided_, have_paired_phones_);
if (most_likely_transport) {
StartGuidedFlowForTransport(*most_likely_transport);
} else if (!transport_availability_.available_transports.empty()) {
SetCurrentStep(Step::kTransportSelection);
} else {
SetCurrentStep(Step::kErrorNoAvailableTransports);
}
}
void AuthenticatorRequestDialogModel::StartGuidedFlowForTransport(
AuthenticatorTransport transport) {
DCHECK(current_step() == Step::kTransportSelection ||
current_step() == Step::kUsbInsertAndActivate ||
current_step() == Step::kCableActivate ||
current_step() == Step::kNotStarted);
switch (transport) {
case AuthenticatorTransport::kUsbHumanInterfaceDevice:
SetCurrentStep(Step::kUsbInsertAndActivate);
break;
case AuthenticatorTransport::kNearFieldCommunication:
SetCurrentStep(Step::kTransportSelection);
break;
case AuthenticatorTransport::kInternal:
StartPlatformAuthenticatorFlow();
break;
case AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy:
EnsureBleAdapterIsPoweredAndContinueWithCable();
break;
default:
break;
}
}
void AuthenticatorRequestDialogModel::
HideDialogAndDispatchToNativeWindowsApi() {
if (!transport_availability()->has_win_native_api_authenticator ||
transport_availability()->win_native_api_authenticator_id.empty()) {
NOTREACHED();
SetCurrentStep(Step::kClosed);
return;
}
// The Windows-native UI already handles retrying so we do not offer a second
// level of retry in that case.
offer_try_again_in_ui_ = false;
// There is no AuthenticatorReference for the Windows authenticator, hence
// directly call DispatchRequestAsyncInternal here.
DispatchRequestAsyncInternal(
transport_availability()->win_native_api_authenticator_id);
HideDialog();
}
void AuthenticatorRequestDialogModel::StartWinNativeApi() {
DCHECK(transport_availability_.has_win_native_api_authenticator);
if (resident_key_requirement() !=
device::ResidentKeyRequirement::kDiscouraged &&
!transport_availability_.win_native_ui_shows_resident_credential_notice) {
SetCurrentStep(Step::kResidentCredentialConfirmation);
} else {
HideDialogAndDispatchToNativeWindowsApi();
}
}
void AuthenticatorRequestDialogModel::StartPhonePairing() {
DCHECK(cable_qr_string_);
SetCurrentStep(Step::kCableV2QRCode);
}
void AuthenticatorRequestDialogModel::
EnsureBleAdapterIsPoweredAndContinueWithCable() {
DCHECK(current_step() == Step::kTransportSelection ||
current_step() == Step::kUsbInsertAndActivate ||
current_step() == Step::kCableActivate ||
current_step() == Step::kNotStarted);
Step cable_step;
if (cable_extension_provided_) {
// caBLEv1.
cable_step = Step::kCableActivate;
} else {
// caBLEv2. Display QR code if the user never paired a phone before, or
// show instructions how to use the previously paired phone otherwise. The
// user can still decide to pair a new phone on that screen.
cable_step =
have_paired_phones_ ? Step::kCableV2Activate : Step::kCableV2QRCode;
}
if (ble_adapter_is_powered()) {
SetCurrentStep(cable_step);
return;
}
next_step_once_ble_powered_ = cable_step;
SetCurrentStep(transport_availability()->can_power_on_ble_adapter
? Step::kBlePowerOnAutomatic
: Step::kBlePowerOnManual);
}
void AuthenticatorRequestDialogModel::ContinueWithFlowAfterBleAdapterPowered() {
DCHECK(current_step() == Step::kBlePowerOnManual ||
current_step() == Step::kBlePowerOnAutomatic);
DCHECK(ble_adapter_is_powered());
DCHECK(next_step_once_ble_powered_.has_value());
SetCurrentStep(*next_step_once_ble_powered_);
}
void AuthenticatorRequestDialogModel::PowerOnBleAdapter() {
DCHECK_EQ(current_step(), Step::kBlePowerOnAutomatic);
if (!bluetooth_adapter_power_on_callback_)
return;
bluetooth_adapter_power_on_callback_.Run();
}
void AuthenticatorRequestDialogModel::TryUsbDevice() {
DCHECK_EQ(current_step(), Step::kUsbInsertAndActivate);
}
void AuthenticatorRequestDialogModel::StartPlatformAuthenticatorFlow() {
// Never try the platform authenticator if the request is known in advance to
// fail. Proceed to a special error screen instead.
if (transport_availability_.request_type ==
device::FidoRequestHandlerBase::RequestType::kGetAssertion) {
DCHECK(transport_availability_
.has_recognized_platform_authenticator_credential);
if (!*transport_availability_
.has_recognized_platform_authenticator_credential) {
SetCurrentStep(Step::kErrorInternalUnrecognized);
return;
}
}
if (transport_availability_.request_type ==
device::FidoRequestHandlerBase::RequestType::kMakeCredential &&
transport_availability_.is_off_the_record_context) {
SetCurrentStep(Step::kPlatformAuthenticatorOffTheRecordInterstitial);
return;
}
HideDialogAndDispatchToPlatformAuthenticator();
}
void AuthenticatorRequestDialogModel::
HideDialogAndDispatchToPlatformAuthenticator() {
HideDialog();
auto& authenticators =
ephemeral_state_.saved_authenticators_.authenticator_list();
auto platform_authenticator_it =
std::find_if(authenticators.begin(), authenticators.end(),
[](const auto& authenticator) {
return authenticator.transport ==
device::FidoTransportProtocol::kInternal;
});
if (platform_authenticator_it == authenticators.end()) {
return;
}
DispatchRequestAsync(&*platform_authenticator_it);
}
void AuthenticatorRequestDialogModel::ShowCableUsbFallback() {
DCHECK_EQ(current_step(), Step::kCableActivate);
SetCurrentStep(Step::kAndroidAccessory);
}
void AuthenticatorRequestDialogModel::ShowCable() {
DCHECK_EQ(current_step(), Step::kAndroidAccessory);
SetCurrentStep(Step::kCableActivate);
}
void AuthenticatorRequestDialogModel::Cancel() {
if (is_request_complete()) {
SetCurrentStep(Step::kClosed);
}
for (auto& observer : observers_)
observer.OnCancelRequest();
}
void AuthenticatorRequestDialogModel::OnSheetModelDidChange() {
for (auto& observer : observers_)
observer.OnSheetModelChanged();
}
void AuthenticatorRequestDialogModel::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void AuthenticatorRequestDialogModel::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void AuthenticatorRequestDialogModel::OnRequestComplete() {
SetCurrentStep(Step::kClosed);
}
void AuthenticatorRequestDialogModel::OnRequestTimeout() {
if (current_step_ == Step::kSubtleUI) {
Cancel();
return;
}
// The request may time out while the UI shows a different error.
if (!is_request_complete()) {
SetCurrentStep(Step::kTimedOut);
}
}
void AuthenticatorRequestDialogModel::OnActivatedKeyNotRegistered() {
DCHECK(!is_request_complete());
SetCurrentStep(Step::kKeyNotRegistered);
}
void AuthenticatorRequestDialogModel::OnActivatedKeyAlreadyRegistered() {
DCHECK(!is_request_complete());
SetCurrentStep(Step::kKeyAlreadyRegistered);
}
void AuthenticatorRequestDialogModel::OnSoftPINBlock() {
SetCurrentStep(Step::kClientPinErrorSoftBlock);
}
void AuthenticatorRequestDialogModel::OnHardPINBlock() {
SetCurrentStep(Step::kClientPinErrorHardBlock);
}
void AuthenticatorRequestDialogModel::OnAuthenticatorRemovedDuringPINEntry() {
SetCurrentStep(Step::kClientPinErrorAuthenticatorRemoved);
}
void AuthenticatorRequestDialogModel::OnAuthenticatorMissingResidentKeys() {
SetCurrentStep(Step::kMissingCapability);
}
void AuthenticatorRequestDialogModel::OnAuthenticatorMissingUserVerification() {
SetCurrentStep(Step::kMissingCapability);
}
void AuthenticatorRequestDialogModel::OnAuthenticatorMissingLargeBlob() {
SetCurrentStep(Step::kMissingCapability);
}
void AuthenticatorRequestDialogModel::OnNoCommonAlgorithms() {
SetCurrentStep(Step::kMissingCapability);
}
void AuthenticatorRequestDialogModel::OnAuthenticatorStorageFull() {
SetCurrentStep(Step::kStorageFull);
}
void AuthenticatorRequestDialogModel::OnUserConsentDenied() {
SetCurrentStep(Step::kErrorInternalUnrecognized);
}
bool AuthenticatorRequestDialogModel::OnWinUserCancelled() {
// If caBLE v2 isn't enabled then this event isn't handled and will cause the
// request to fail with a NotAllowedError.
if (!base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport)) {
return false;
}
// Otherwise, if the user cancels out of the Windows-native UI, we show the
// transport selection dialog which allows them to pair a phone.
win_native_api_already_tried_ = true;
StartOver();
return true;
}
void AuthenticatorRequestDialogModel::OnBluetoothPoweredStateChanged(
bool powered) {
transport_availability_.is_ble_powered = powered;
for (auto& observer : observers_)
observer.OnBluetoothPoweredStateChanged();
// For the manual flow, the user has to click the "next" button explicitly.
if (current_step() == Step::kBlePowerOnAutomatic)
ContinueWithFlowAfterBleAdapterPowered();
}
void AuthenticatorRequestDialogModel::SetRequestCallback(
RequestCallback request_callback) {
request_callback_ = request_callback;
}
void AuthenticatorRequestDialogModel::SetBluetoothAdapterPowerOnCallback(
base::RepeatingClosure bluetooth_adapter_power_on_callback) {
bluetooth_adapter_power_on_callback_ = bluetooth_adapter_power_on_callback;
}
void AuthenticatorRequestDialogModel::OnHavePIN(base::string16 pin) {
if (!pin_callback_) {
// Protect against the view submitting a PIN more than once without
// receiving a matching response first. |CollectPIN| is called again if
// the user needs to be prompted for a retry.
return;
}
std::move(pin_callback_).Run(pin);
}
void AuthenticatorRequestDialogModel::OnRetryUserVerification(int attempts) {
uv_attempts_ = attempts;
SetCurrentStep(Step::kRetryInternalUserVerification);
}
void AuthenticatorRequestDialogModel::OnResidentCredentialConfirmed() {
DCHECK_EQ(current_step(), Step::kResidentCredentialConfirmation);
HideDialogAndDispatchToNativeWindowsApi();
}
void AuthenticatorRequestDialogModel::OnAttestationPermissionResponse(
bool attestation_permission_granted) {
if (!attestation_callback_) {
return;
}
std::move(attestation_callback_).Run(attestation_permission_granted);
}
void AuthenticatorRequestDialogModel::AddAuthenticator(
const device::FidoAuthenticator& authenticator) {
if (!authenticator.AuthenticatorTransport()) {
#if defined(OS_WIN)
DCHECK(authenticator.IsWinNativeApiAuthenticator());
#endif // defined(OS_WIN)
return;
}
AuthenticatorReference authenticator_reference(
authenticator.GetId(), *authenticator.AuthenticatorTransport());
ephemeral_state_.saved_authenticators_.AddAuthenticator(
std::move(authenticator_reference));
}
void AuthenticatorRequestDialogModel::RemoveAuthenticator(
base::StringPiece authenticator_id) {
ephemeral_state_.saved_authenticators_.RemoveAuthenticator(authenticator_id);
}
void AuthenticatorRequestDialogModel::DispatchRequestAsync(
AuthenticatorReference* authenticator) {
// Dispatching to the same authenticator twice may result in unexpected
// behavior.
if (authenticator->dispatched) {
return;
}
DispatchRequestAsyncInternal(authenticator->authenticator_id);
authenticator->dispatched = true;
}
void AuthenticatorRequestDialogModel::DispatchRequestAsyncInternal(
const std::string& authenticator_id) {
if (!request_callback_)
return;
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(request_callback_, authenticator_id));
}
// SelectAccount is called to trigger an account selection dialog.
void AuthenticatorRequestDialogModel::SelectAccount(
std::vector<device::AuthenticatorGetAssertionResponse> responses,
base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)>
callback) {
ephemeral_state_.responses_ = std::move(responses);
selection_callback_ = std::move(callback);
SetCurrentStep(Step::kSelectAccount);
}
void AuthenticatorRequestDialogModel::OnAccountSelected(size_t index) {
if (!selection_callback_) {
// It's possible that the user could activate the dialog more than once
// before the Webauthn request is completed and its torn down.
return;
}
auto selected = std::move(ephemeral_state_.responses_[index]);
ephemeral_state_.responses_.clear();
std::move(selection_callback_).Run(std::move(selected));
}
void AuthenticatorRequestDialogModel::SetSelectedAuthenticatorForTesting(
AuthenticatorReference test_authenticator) {
ephemeral_state_.selected_authenticator_id_ =
test_authenticator.authenticator_id;
ephemeral_state_.saved_authenticators_.AddAuthenticator(
std::move(test_authenticator));
}
bool AuthenticatorRequestDialogModel::cable_should_suggest_usb() const {
return base::Contains(transport_availability_.available_transports,
AuthenticatorTransport::kAndroidAccessory);
}
void AuthenticatorRequestDialogModel::CollectPIN(
device::pin::PINEntryReason reason,
device::pin::PINEntryError error,
uint32_t min_pin_length,
int attempts,
base::OnceCallback<void(base::string16)> provide_pin_cb) {
pin_callback_ = std::move(provide_pin_cb);
min_pin_length_ = min_pin_length;
pin_error_ = error;
switch (reason) {
case device::pin::PINEntryReason::kChallenge:
pin_attempts_ = attempts;
SetCurrentStep(Step::kClientPinEntry);
return;
case device::pin::PINEntryReason::kChange:
SetCurrentStep(Step::kClientPinChange);
return;
case device::pin::PINEntryReason::kSet:
SetCurrentStep(Step::kClientPinSetup);
return;
}
}
void AuthenticatorRequestDialogModel::StartInlineBioEnrollment(
base::OnceClosure next_callback) {
max_bio_samples_ = base::nullopt;
bio_samples_remaining_ = base::nullopt;
bio_enrollment_callback_ = std::move(next_callback);
SetCurrentStep(Step::kInlineBioEnrollment);
}
void AuthenticatorRequestDialogModel::OnSampleCollected(
int bio_samples_remaining) {
DCHECK(current_step_ == Step::kInlineBioEnrollment);
bio_samples_remaining_ = bio_samples_remaining;
if (!max_bio_samples_) {
max_bio_samples_ = bio_samples_remaining + 1;
}
OnSheetModelDidChange();
}
void AuthenticatorRequestDialogModel::OnBioEnrollmentDone() {
std::move(bio_enrollment_callback_).Run();
}
void AuthenticatorRequestDialogModel::RequestAttestationPermission(
bool is_enterprise_attestation,
base::OnceCallback<void(bool)> callback) {
DCHECK(current_step_ != Step::kClosed);
attestation_callback_ = std::move(callback);
SetCurrentStep(is_enterprise_attestation
? Step::kEnterpriseAttestationPermissionRequest
: Step::kAttestationPermissionRequest);
}
void AuthenticatorRequestDialogModel::set_cable_transport_info(
bool cable_extension_provided,
bool have_paired_phones,
const base::Optional<std::string>& cable_qr_string) {
cable_extension_provided_ = cable_extension_provided;
have_paired_phones_ = have_paired_phones;
cable_qr_string_ = cable_qr_string;
}
base::WeakPtr<AuthenticatorRequestDialogModel>
AuthenticatorRequestDialogModel::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
| 33.903125 | 80 | 0.76431 | [
"vector"
] |
db186503b5174111415af979f02bc1ae9e3606a5 | 1,232 | cpp | C++ | Codeforces/1207B/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Codeforces/1207B/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Codeforces/1207B/implementation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define SIZE 51
bool arr[SIZE][SIZE], vis[SIZE][SIZE];
int row, col;
vector<pair<int, int> > vec;
bool check() {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (arr[i][j] && !vis[i][j])
return false;
return true;
}
void mark(int x, int y) {
if (x + 1 < row && y + 1 < col && arr[x][y] && arr[x + 1][y] && arr[x][y + 1] && arr[x + 1][y + 1]) {
vis[x][y] = true, vis[x + 1][y] = true, vis[x][y + 1] = true, vis[x + 1][y + 1] = true;
vec.push_back(make_pair(x, y));
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> row >> col;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cin >> arr[i][j];
memset(vis, false, sizeof(vis));
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (arr[i][j])
mark(i, j);
if (!check()) {
cout << -1 << '\n';
} else {
cout << vec.size() << '\n';
for (auto & p : vec)
cout << p.first + 1 << ' ' << p.second + 1 << '\n';
}
return 0;
} | 25.142857 | 106 | 0.405032 | [
"vector"
] |
db18ff1ddc36668ddf9445f8d97521e7cf3f535b | 11,657 | hpp | C++ | SRC/Maps/DataTileProvider.hpp | poli0048/Recon | d3836b3ea569f389c238469b17390ed6e9c34b65 | [
"BSD-3-Clause"
] | 1 | 2021-12-26T12:53:35.000Z | 2021-12-26T12:53:35.000Z | SRC/Maps/DataTileProvider.hpp | poli0048/Recon | d3836b3ea569f389c238469b17390ed6e9c34b65 | [
"BSD-3-Clause"
] | null | null | null | SRC/Maps/DataTileProvider.hpp | poli0048/Recon | d3836b3ea569f389c238469b17390ed6e9c34b65 | [
"BSD-3-Clause"
] | 2 | 2021-06-12T18:34:18.000Z | 2021-12-26T12:53:44.000Z | //This module provides an interface for accessing GIS data stored in an FRF KV store. It can provide vis tiles of GIS
//data for display with ImGui and it has utilities to retrieve and edit raw data at any point on Earth. Essentially,
//the DataTileProvider allows other modules to pretend that we have a raster canvas covering the entire planet in a
//Normalized Mercator (NM) projection at a certain resolution level. We can sample and edit this canvas by providing the
//NM coordinates of the point we want. Internally, it manages a global pyramid of FRF tiles. Edits occur at a fixed resolution
//level and lower-resolution tiles are updated based on the contents of the edit level. Tiles are only created when touched
//by an edit, and they are destroyed automatically when they reach a state equivalent to a default empty tile. Tiles are only
//held in memory when they are in use (or have been used within a certain number of seconds). When a tile is not held in memory
//it is saved back to an on-disk KV store.
//Author: Bryan Poling
//Copyright (c) 2020 Sentek Systems, LLC. All rights reserved.
#pragma once
//System Includes
#include <unordered_map>
#include <mutex>
#include <chrono>
#include <tuple>
#include <ratio>
#include <deque>
//External Includes
#include "../HandyImGuiInclude.hpp"
//Project Includes
#include "../EigenAliases.h"
#include "Tile.hpp"
#include "SatelliteSources.hpp"
#include "Interfaces.hpp"
#include "DataTileTypes.hpp"
#include "FRFTileStore.hpp"
#include "../Journal.h"
namespace Maps {
//m_FRFTile should be valid once an object is in the cache and the FRF tile should remain valid until destruction
struct DataTileCacheItem {
using TimePoint = std::chrono::time_point<std::chrono::steady_clock>;
public:
Tile m_tileKey;
TimePoint m_lastTouch; //Last time this item was accessed in any way
std::unique_ptr<FRFImage> m_FRFTile;
bool m_FRFEdited = false;
TimePoint m_LastEditTime;
//Vis tiles are not explicitly double-buffered. Instead, to prevent screen blanking, we use delayed texture deletion
bool m_vizValid = false;
VizualizationTileKey m_VizKey;
ImTextureID m_TextureID;
TimePoint m_VizEvalTime;
DataTileCacheItem() = delete;
DataTileCacheItem(FRFTileStore * AssociatedFileStore) : m_FRFFileStore(AssociatedFileStore) { }
~DataTileCacheItem();
static void InitializeFRFTileContents(FRFImage * FRFTile);
static void UpdateFRFTileTimeTag(FRFImage * FRFTile);
private:
FRFTileStore * m_FRFFileStore; //Pointer to the file store associated with the cache - used for write-back in destructor
bool FRFImageIsTrivial(void); //Returns true if FRF tile has the same contents as a freshly-initialized tile
};
struct PaintActionItem {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
int m_shape; //0=Circle, 1=Rectangle
Eigen::Vector2d m_Center_NM;
DataLayer m_layer;
double m_Value; //NaN for erase action
//Circle Properties
double m_Radius_meters;
//Rectangle Properties
double m_LengthX; //Meters
double m_LengthY; //Meters
double m_Theta; //Radians
PaintActionItem() = default;
~PaintActionItem() = default;
//Returns true if the given item is essentially the same as this item (i.e. close enough that if we can skip one of them)
bool IsEssentiallyIdentical(PaintActionItem const & OtherItem);
Eigen::Vector4d GetNM_AABB(void);
void GetCorners(Eigen::Vector2d & P1_NM, Eigen::Vector2d & P2_NM, Eigen::Vector2d & P3_NM, Eigen::Vector2d & P4_NM); //Only for rectangle actions
};
//DataTileProvider is a singleton class. It is thread-safe so many different modules can share it on or off main-thread.
struct DataTileProvider : IFRFFileReceiver {
using TimePoint = std::chrono::time_point<std::chrono::steady_clock>;
static constexpr std::chrono::seconds ExpirationTimeSeconds = std::chrono::seconds(20);
static constexpr std::chrono::seconds LowResUpdatePeriodSeconds = std::chrono::seconds(3);
static constexpr int32_t NumberOfVizEvaluationThreads = 4;
static constexpr size_t MaxNumberOfJobsInThreadPool = 8; //New jobs will only be added to the queue if there is room
static constexpr int32_t TileEditZoomLevel = 20; //The pyramid level on which edits are done (lower-res tiles are derived from these)
static constexpr int32_t DataTileMinZoomLevel = 15; //The lowest pyramid level for which viz tiles are maintained and returned (empty below this)
private:
static DataTileProvider * s_instance;
Journal & Log;
FRFTileStore * m_FRFFileStore;
std::atomic_bool m_abort; //Set to True to signal to secondary threads that it's time to wrap things up.
std::mutex m_cache_mtx;
std::unordered_map<Tile, DataTileCacheItem> m_cache;
std::mutex m_editStream_mtx;
std::Edeque<PaintActionItem> m_actionQueue; //Push to back and pop from front
Handy::ThreadPool m_threads_VisEval; //Thread pool for evaluating visualizations from FRF tiles and loading them into GPU memory
std::mutex m_mtx_TilesWithcurrentVizEvalJobs;
std::unordered_set<Tile> m_TilesWithcurrentVizEvalJobs; //Just a set of Tile keys - we only allow one job per tile in queue at once
//The DataTileProvider runs a simple garbage collector in a separate thread to periodically purge unused tiles from the memory cache
void GarbageCollectionThreadMain(void);
std::thread m_garbageCollectionThread;
//The DataTileProvider processed edit actions in a separate thread
void DataEditThreadMain(void);
std::thread m_DataEditThread;
void TouchLoadFRFTile(Tile Key);
//FRF Edit Support Functions
bool AllTilesPresent(std::vector<Tile> const & Tiles);
void TouchLoadFRFTilesAndWait(std::vector<Tile> const & Tiles);
void UpdateLowerResTiles(std::unordered_set<Tile> const & EditedTiles);
bool ExecuteEditActionOnTile_Circle(PaintActionItem const & Action, Tile tile, Eigen::Vector4d const & AABB_NM);
bool ExecuteEditActionOnTile_Rectangle(PaintActionItem const & Action, Tile tile, Eigen::Vector4d const & AABB_NM);
public:
static void Init(Journal & LogRef) { s_instance = new DataTileProvider(LogRef); }
static void Destroy(void) { delete s_instance; s_instance = nullptr; }
static DataTileProvider * Instance(void) { return s_instance; }
DataTileProvider(Journal & LogRef);
~DataTileProvider();
//Retrieve the given visualization tile. If not cached a request will be issued to start generating it (loading the FRF resource if needed).
//If another viz tile is already present for the same tile it will be returned if the one requested needs to be generated and isn't ready yet.
//This is inteanded to prevent screen blanking while chanhing visualization parameters.
ImTextureID TryGetLoadUpdate_VizTile(VizualizationTileKey Key);
//Data access - get a value from a single layer at a single location. The retrieved data is passed back through reference argument "Value".
//Important note: This function follows the immediate-mode paradigm used in many other parts of this program, which may seem unexpected. This
//means that if the requested value isn't immediately available this function will fail and return false. However, it will queue up the needed
//resources for loading so later calls accessing the same location will eventually succeed (and return True).
bool TryGetData(Eigen::Vector2d const & Position_NM, DataLayer layer, double & Value);
//Same as TryGetData, but will block until the requested data is available (up to a given number of seconds, after which it will return NaN)
double GetData(Eigen::Vector2d const & Position_NM, DataLayer layer, double Timeout);
//Get the min and max (non-NaN) values of a given data layer along a line from point A to point B, sampled every "sampleDist" meters.
//Aborts if the values can't be resolved within "Timeout" seconds. Returns true on success and false on timeout.
//On success, NaNsDetected will also be populated... true if any NaNs detected on line and false otherwise.
bool GetDataExtremesOnLine(Eigen::Vector2d const & PointA_NM, Eigen::Vector2d const & PointB_NM, double SampleDist, DataLayer layer,
double Timeout, double & Data_Min, double & Data_Max, bool & NaNsDetected);
//FRF Edit Tools - when painting, tiles will be created as needed. Painting is done at a fixed pyramid level (set in a constexpr above)
//and lower-res levels are derived from this level and updated as needed. We make a special exception and take the rectangle angle in
//degrees so it can be exposed in degrees by ImGui without conversion. Painting is done asynchronously.
inline void Paint_Circle(Eigen::Vector2d const & Center_NM, double Radius_meters, DataLayer layer, double Value);
inline void Erase_Circle(Eigen::Vector2d const & Center_NM, double Radius_meters, DataLayer layer);
inline void Paint_Rect(Eigen::Vector2d const & Center_NM, double LengthX, double LengthY, double AngleDeg, DataLayer layer, double Value);
inline void Erase_Rect(Eigen::Vector2d const & Center_NM, double LengthX, double LengthY, double AngleDeg, DataLayer layer);
//Force-purge tiles from cache. Note that the cache will self-garbage-collect so this is only needed if you are changing things on disk
//or want to force a flush of cached data back to disk (like on exit)
void PurgeAllTiles();
//Called after an asynchronous FRFImage retrieval - We are responsible for deletion of Data.
void OnReceivedFRFTile(Tile TileKey, FRFImage * Data) override;
};
inline void DataTileProvider::Paint_Circle(Eigen::Vector2d const & Center_NM, double Radius_meters, DataLayer layer, double Value) {
std::scoped_lock lock(m_editStream_mtx);
m_actionQueue.emplace_back();
m_actionQueue.back().m_shape = 0;
m_actionQueue.back().m_Center_NM = Center_NM;
m_actionQueue.back().m_layer = layer;
m_actionQueue.back().m_Value = Value;
m_actionQueue.back().m_Radius_meters = Radius_meters;
}
inline void DataTileProvider::Erase_Circle(Eigen::Vector2d const & Center_NM, double Radius_meters, DataLayer layer) {
std::scoped_lock lock(m_editStream_mtx);
m_actionQueue.emplace_back();
m_actionQueue.back().m_shape = 0;
m_actionQueue.back().m_Center_NM = Center_NM;
m_actionQueue.back().m_layer = layer;
m_actionQueue.back().m_Value = std::nan("");
m_actionQueue.back().m_Radius_meters = Radius_meters;
}
inline void DataTileProvider::Paint_Rect(Eigen::Vector2d const & Center_NM, double LengthX, double LengthY, double AngleDeg, DataLayer layer, double Value) {
double const PI = 3.14159265358979;
std::scoped_lock lock(m_editStream_mtx);
m_actionQueue.emplace_back();
m_actionQueue.back().m_shape = 1;
m_actionQueue.back().m_Center_NM = Center_NM;
m_actionQueue.back().m_layer = layer;
m_actionQueue.back().m_Value = Value;
m_actionQueue.back().m_LengthX = LengthX;
m_actionQueue.back().m_LengthY = LengthY;
m_actionQueue.back().m_Theta = AngleDeg*PI/180.0;
}
inline void DataTileProvider::Erase_Rect(Eigen::Vector2d const & Center_NM, double LengthX, double LengthY, double AngleDeg, DataLayer layer) {
double const PI = 3.14159265358979;
std::scoped_lock lock(m_editStream_mtx);
m_actionQueue.emplace_back();
m_actionQueue.back().m_shape = 1;
m_actionQueue.back().m_Center_NM = Center_NM;
m_actionQueue.back().m_layer = layer;
m_actionQueue.back().m_Value = std::nan("");
m_actionQueue.back().m_LengthX = LengthX;
m_actionQueue.back().m_LengthY = LengthY;
m_actionQueue.back().m_Theta = AngleDeg*PI/180.0;
}
}
| 51.127193 | 158 | 0.756798 | [
"object",
"vector"
] |
db1b60a3169b12ae07ff20600d62a0d8465531f7 | 9,343 | cc | C++ | onnxruntime/test/providers/cpu/controlflow/if_test.cc | twosense/onnxruntime | 77b981824aed851442a3bed33525d27adb525111 | [
"MIT"
] | 2 | 2019-07-30T10:37:33.000Z | 2021-01-05T21:12:29.000Z | onnxruntime/test/providers/cpu/controlflow/if_test.cc | twosense/onnxruntime | 77b981824aed851442a3bed33525d27adb525111 | [
"MIT"
] | null | null | null | onnxruntime/test/providers/cpu/controlflow/if_test.cc | twosense/onnxruntime | 77b981824aed851442a3bed33525d27adb525111 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "gmock/gmock.h"
// #include "core/framework/customregistry.h"
#include "core/framework/session_state.h"
#include "core/providers/cpu/controlflow/if.h"
#include "test/providers/provider_test_utils.h"
#include "core/session/inference_session.h"
#include "test/util/include/default_providers.h"
using namespace ONNX_NAMESPACE;
namespace onnxruntime {
namespace test {
namespace {
struct RunOptions {
bool include_dim_values_in_main_graph = false;
int symbolic_dim_value_in_main_graph = -1;
bool include_dim_values_in_subgraph = true;
bool mixed_execution_providers = false;
};
}
static const ONNX_NAMESPACE::GraphProto CreateSubgraph(bool then_branch, const RunOptions& options);
/*
Main graph
split_input if_cond if_graph_input_0,
| | |
[Split] | [Identity]
| | |
| | if_input_0
| split_out_0 | |
------------------[If]-------------- (see below for then/else subgraphs in If node)
split_out_1 |
|
if_out_0
*/
class IfOpTester : public OpTester {
public:
IfOpTester(const RunOptions& options) : OpTester("If"), options_{options} {
}
protected:
void AddNodes(onnxruntime::Graph& graph,
std::vector<onnxruntime::NodeArg*>& graph_input_defs,
std::vector<onnxruntime::NodeArg*>& graph_output_defs,
std::vector<std::function<void(onnxruntime::Node& node)>>& /*add_attribute_funcs*/) override {
// Graph inputs are 0:Split input, 1:Cond for If, 2:if input
ASSERT_EQ(graph_input_defs.size(), 3);
ASSERT_EQ(graph_output_defs.size(), 1);
NodeArg* split_input = graph_input_defs[0];
NodeArg* if_cond_input = graph_input_defs[1];
NodeArg* if_input = graph_input_defs[2];
std::vector<NodeArg*> inputs;
std::vector<NodeArg*> outputs;
// add Split node
{
TypeProto split_out_type;
split_out_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_FLOAT);
auto& split_out_0 = graph.GetOrCreateNodeArg("split_out_0", &split_out_type);
auto& split_out_1 = graph.GetOrCreateNodeArg("split_out_1", &split_out_type);
inputs = {split_input};
outputs = {&split_out_0, &split_out_1};
graph.AddNode("split", "Split", "Split into 2", inputs, outputs);
}
// add If node
{
inputs = {if_cond_input};
outputs = {graph_output_defs[0]};
auto& if_node = graph.AddNode("if", "If", "If node", inputs, outputs);
auto then_proto = CreateSubgraph(true, options_);
auto else_proto = CreateSubgraph(false, options_);
if_node.AddAttribute("then_branch", {then_proto});
if_node.AddAttribute("else_branch", {else_proto});
}
// add Identity node so if_graph_input_0 comes from graph inputs
{
inputs = {if_input};
outputs = {&graph.GetOrCreateNodeArg("if_input_0", if_input->TypeAsProto())};
graph.AddNode("identity", "Identity", "Pass if input through from graph inputs.", inputs, outputs);
}
}
private:
RunOptions options_;
};
/* Subgraphs looks like this. All inputs come from outer scope so we just
create a NodeArg with the input name. The numbers in [] are the values the tests are expected to produce
as output from each node.
THEN branch
split_out_0 if_input_0 [1]
\ |
[1] \ |
\------[Add]
|
add_out_0 [2]
ELSE branch
split_out_1 if_input_0 [1]
\ |
[10] \ |
\------[Add]
|
add_out_1 [11]
*/
static const ONNX_NAMESPACE::GraphProto CreateSubgraph(bool then_branch, const RunOptions& options) {
bool include_dim_values = options.include_dim_values_in_subgraph;
bool sym_dim_zero = options.symbolic_dim_value_in_main_graph == 0;
Model model(then_branch ? "If_then" : "If_else");
auto& graph = model.MainGraph();
std::vector<NodeArg*> inputs;
std::vector<NodeArg*> outputs;
const std::string suffix = then_branch ? "0" : "1";
// graph input has to have type and rank even though it's an outer scope value.
TypeProto input_tensor_type;
input_tensor_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_FLOAT);
auto* mutable_dim = input_tensor_type.mutable_tensor_type()->mutable_shape()->add_dim();
if (include_dim_values) {
mutable_dim->set_dim_value(1);
} else if (sym_dim_zero) {
mutable_dim->set_dim_param("symbolic");
}
// outer scope values
auto& split_output = graph.GetOrCreateNodeArg("split_out_" + suffix, &input_tensor_type);
auto& if_input = graph.GetOrCreateNodeArg("if_input_0", &input_tensor_type);
// add so that we don't end up with it being considered a graph input
graph.AddOuterScopeNodeArg("split_out_" + suffix);
graph.AddOuterScopeNodeArg("if_input_0");
{
// Add
// graph output has to have type and shape
TypeProto add_output_tensor;
add_output_tensor.mutable_tensor_type()->set_elem_type(TensorProto_DataType_FLOAT);
mutable_dim = add_output_tensor.mutable_tensor_type()->mutable_shape()->add_dim();
if (include_dim_values) {
mutable_dim->set_dim_value(1);
} else if (sym_dim_zero) {
mutable_dim->set_dim_param("symbolic");
}
auto& add_out = graph.GetOrCreateNodeArg("add_out_" + suffix, &add_output_tensor);
inputs = {&split_output, &if_input};
outputs = {&add_out};
graph.AddNode("add", "Add", "Add two inputs.", inputs, outputs);
}
auto status = graph.Resolve();
EXPECT_EQ(status, Status::OK());
auto& proto = graph.ToGraphProto();
return proto;
}
void RunTest(bool condition_value,
RunOptions options,
OpTester::ExpectResult expect_result = OpTester::ExpectResult::kExpectSuccess,
const std::string& failure_message = "") {
IfOpTester test{options};
test.AddShapeToTensorData(options.include_dim_values_in_main_graph,
options.symbolic_dim_value_in_main_graph);
// add the main graph inputs and outputs.
// we will handle the 'If' inputs in the AddNodes override, and as 'If' is the last node
// it's outputs are 1:1 with the graph outputs.
// simple tensor that we split into 2, and use one output for the 'then' and one for the 'else' branch in the If
test.AddInput<float>("split_input", {2}, {1.f, 10.f});
// graph input to specify which branch to take
test.AddInput<bool>("if_cond", {1}, {condition_value});
test.AddInput<float>("if_graph_input_0", {1}, {1.f});
std::vector<int64_t> output_shape{1};
if (condition_value) {
test.AddOutput<float>("if_out_0", output_shape, {2.f});
} else {
test.AddOutput<float>("if_out_0", output_shape, {11.f});
}
if (options.mixed_execution_providers) {
// we want the CUDA provider to be first, and the CPU provider second. all except the Scannode should run on
// CUDA given that, which creates the scenario where we need to copy to/from CPU to execute the Scan node correctly.
std::vector<std::unique_ptr<IExecutionProvider>> execution_providers;
execution_providers.push_back(DefaultCudaExecutionProvider());
execution_providers.push_back(DefaultCpuExecutionProvider());
test.Run(expect_result, failure_message, {}, nullptr, &execution_providers);
} else {
test.Run(expect_result, failure_message);
}
}
TEST(If, ShapeInMainGraph_NoShapeInSubgraph_True) {
RunOptions options{};
options.include_dim_values_in_main_graph = true;
options.include_dim_values_in_subgraph = false;
RunTest(true, options);
}
TEST(If, ShapeInMainGraph_NoShapeInSubgraph_False) {
RunOptions options{};
options.include_dim_values_in_main_graph = true;
options.include_dim_values_in_subgraph = false;
RunTest(false, options);
}
TEST(If, NoShapeInMainGraph_ShapeInSubgraph_True) {
RunOptions options{};
options.include_dim_values_in_main_graph = false;
options.include_dim_values_in_subgraph = true;
RunTest(true, options);
}
TEST(If, NoShapeInMainGraph_ShapeInSubgraph_False) {
RunOptions options{};
options.include_dim_values_in_main_graph = false;
options.include_dim_values_in_subgraph = true;
RunTest(false, options);
}
#ifdef USE_CUDA
TEST(If, MixedExecutionProviders) {
RunOptions options{};
options.mixed_execution_providers = true;
RunTest(true, options);
}
#endif // USE_CUDA
TEST(If, SymbolicShapeInMainGraph_NoShapeInSubgraph_True) {
RunOptions options;
options.include_dim_values_in_main_graph = true;
options.symbolic_dim_value_in_main_graph = 0;
options.include_dim_values_in_subgraph = false;
RunTest(true, options);
}
TEST(If, SymbolicShapeInMainGraph_NoShapeInSubgraph_False) {
RunOptions options;
options.include_dim_values_in_main_graph = true;
options.symbolic_dim_value_in_main_graph = 0;
options.include_dim_values_in_subgraph = false;
RunTest(false, options);
}
} // namespace test
} // namespace onnxruntime
| 32.782456 | 120 | 0.679118 | [
"shape",
"vector",
"model"
] |
db1bbd260dd30535733939269593a1ac8a23b9b7 | 18,262 | cpp | C++ | dev/Gems/EMotionFX/Code/MysticQt/Source/ButtonGroup.cpp | BadDevCode/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | 2 | 2020-06-27T12:13:44.000Z | 2020-06-27T12:13:46.000Z | dev/Gems/EMotionFX/Code/MysticQt/Source/ButtonGroup.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | dev/Gems/EMotionFX/Code/MysticQt/Source/ButtonGroup.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// include the required headers
#include "ButtonGroup.h"
#include <QtWidgets/QPushButton>
#include <MCore/Source/LogManager.h>
#include <AzCore/Casting/numeric_cast.h>
namespace MysticQt
{
// calculate the interpolated gradient colors based on the global start and end color for the button group
void ButtonGroup::GetButtonGradientColors(uint32 rowIndex, uint32 numRows, QColor startColor, QColor endColor, QColor* outStartColor, QColor* outEndColor)
{
if (numRows == 0)
{
return;
}
const float startR = aznumeric_cast<float>(startColor.redF());
const float startG = aznumeric_cast<float>(startColor.greenF());
const float startB = aznumeric_cast<float>(startColor.blueF());
const float endR = aznumeric_cast<float>(endColor.redF());
const float endG = aznumeric_cast<float>(endColor.greenF());
const float endB = aznumeric_cast<float>(endColor.blueF());
const float weightStart = rowIndex / (float)numRows;
const float weightEnd = (rowIndex + 1) / (float)numRows;
const float interpolatedStartR = MCore::LinearInterpolate<float>(startR, endR, weightStart);
const float interpolatedStartG = MCore::LinearInterpolate<float>(startG, endG, weightStart);
const float interpolatedStartB = MCore::LinearInterpolate<float>(startB, endB, weightStart);
const float interpolatedEndR = MCore::LinearInterpolate<float>(startR, endR, weightEnd);
const float interpolatedEndG = MCore::LinearInterpolate<float>(startG, endG, weightEnd);
const float interpolatedEndB = MCore::LinearInterpolate<float>(startB, endB, weightEnd);
outStartColor->setRgbF(interpolatedStartR, interpolatedStartG, interpolatedStartB);
outEndColor->setRgbF(interpolatedEndR, interpolatedEndG, interpolatedEndB);
}
// prepare the different border styles depending on where the cell is located
void ButtonGroup::GetBorderStyleSheet(AZStd::string* outStyleSheet, uint32 numRows, uint32 numColumns, uint32 i, uint32 j)
{
if (numRows == 1 && numColumns == 1)
{
}
// we are dealing with a horizontal button group
else if (numRows == 1)
{
// left
if (i == 0)
{
*outStyleSheet = AZStd::string::format("border-bottom: 1px solid rgb(90,90,90); border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-right: none; border-left-width: 1px; border-top-width: 1px;");
}
// right
else if (i == numColumns - 1)
{
*outStyleSheet = AZStd::string::format("border-bottom: 1px solid rgb(90,90,90); border-right: 1px solid rgb(90,90,90); border-top-left-radius: 0px; border-bottom-left-radius: 0px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-top-width: 1px;");
}
// all middle buttons in the horizontal button group
else
{
*outStyleSheet = AZStd::string::format("border-bottom: 1px solid rgb(90,90,90); border-radius: 0px; border-right: none; border-left-width: 1px; border-top-width: 1px;");
}
}
// if we are dealing with a vertical button group
else if (numColumns == 1)
{
// top
if (j == 0)
{
*outStyleSheet = AZStd::string::format("border-right: 1px solid rgb(90,90,90); border-radius: 0px; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom: none; border-left-width: 1px; border-top-width: 1px;");
}
// bottom
else if (j == numRows - 1)
{
*outStyleSheet = AZStd::string::format("border-bottom: 1px solid rgb(90,90,90); border-radius: 0px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; border-top: none; border-left-width: 1px; border-right-width: 1px;");
}
// all middle buttons in the horizontal button group
else
{
*outStyleSheet = AZStd::string::format("border-right: 1px solid rgb(90,90,90); border-radius: 0px; border-top: none; border-left-width: 1px; border-bottom-width: 1px;");
}
}
// most left column
else if (i == 0)
{
// left top
if (j == 0)
{
*outStyleSheet = AZStd::string::format("border-radius: 0px; border-right: none; border-top-left-radius: 5px; border-bottom: none; border-right: none; border-top-width: 1px; border-left-width: 1px;");
}
// left bottom
else if (j == numRows - 1)
{
*outStyleSheet = AZStd::string::format("border-bottom : 1px solid rgb(90,90,90); border-radius: 0px; border-bottom-left-radius: 5px; border-right: none; border-left-width: 1px;");
}
// all middle buttons in the most left column
else
{
*outStyleSheet = AZStd::string::format("border-radius: 0px; border-bottom: none; border-right: none; border-left-width: 1px;");
}
}
// most right column
else if (i == numColumns - 1)
{
// right top
if (j == 0)
{
*outStyleSheet = AZStd::string::format("border-right: 1px solid rgb(90,90,90); border-radius: 0px; border-top-right-radius: 5px; border-bottom: none;");
}
// right bottom
else if (j == numRows - 1)
{
*outStyleSheet = AZStd::string::format("border-right: 1px solid rgb(90,90,90); border-bottom: 1px solid rgb(90,90,90); border-radius: 0px; border-bottom-right-radius: 5px;");
}
// all middle buttons in the most right columns
else
{
*outStyleSheet = AZStd::string::format("border-right: 1px solid rgb(90,90,90); border-radius: 0px; border-bottom: none;");
}
}
// all middle columns
else
{
// top
if (j == 0)
{
*outStyleSheet = AZStd::string::format("border-right: none; border-radius: 0px; border-bottom: none;");
}
// bottom
else if (j == numRows - 1)
{
*outStyleSheet = AZStd::string::format("border-right: none; border-bottom: 1px solid rgb(90,90,90); border-radius: 0px;");
}
// all middle buttons
else
{
*outStyleSheet = AZStd::string::format("border-right: none; border-radius: 0px; border-bottom: none;");
}
}
}
// prepare a whole style sheet for a given button
void ButtonGroup::PrepareStyleSheet(AZStd::string* outStyleSheet, uint32 numRows, uint32 numColumns, uint32 i, uint32 j)
{
AZStd::string helperStyleString;
//////////////////////////////////////////////////////////////////////////////////////////////
// normal state
//////////////////////////////////////////////////////////////////////////////////////////////
*outStyleSheet += AZStd::string::format("QPushButton#ButtonGroup \n");
*outStyleSheet += AZStd::string::format("{ \n");
*outStyleSheet += AZStd::string::format(" background-color: rgb(45, 45, 45); \n");
*outStyleSheet += AZStd::string::format(" color: rgb(170, 170, 170); \n");
GetBorderStyleSheet(&helperStyleString, numRows, numColumns, i, j);
*outStyleSheet += AZStd::string::format(" %s \n", helperStyleString.c_str());
*outStyleSheet += AZStd::string::format(" padding: 3px; \n");
*outStyleSheet += AZStd::string::format("} \n\n");
//////////////////////////////////////////////////////////////////////////////////////////////
// checked state
//////////////////////////////////////////////////////////////////////////////////////////////
*outStyleSheet += AZStd::string::format("QPushButton#ButtonGroup:checked \n");
*outStyleSheet += AZStd::string::format("{ \n");
// these are the global start and end colors for the button group (gradient goes vertically like in the tab headers)
QColor startColor(244, 156, 28);
QColor endColor(200, 110, 0);
QColor localStartColor, localEndColor;
GetButtonGradientColors(j, numRows, startColor, endColor, &localStartColor, &localEndColor);
*outStyleSheet += AZStd::string::format("background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgb(%i, %i, %i), stop:1 rgb(%i, %i, %i));\n", localStartColor.red(), localStartColor.green(), localStartColor.blue(), localEndColor.red(), localEndColor.green(), localEndColor.blue());
*outStyleSheet += AZStd::string::format(" color: black; \n");
GetBorderStyleSheet(&helperStyleString, numRows, numColumns, i, j);
*outStyleSheet += AZStd::string::format(" %s \n", helperStyleString.c_str());
*outStyleSheet += AZStd::string::format("} \n\n");
//////////////////////////////////////////////////////////////////////////////////////////////
// hover state
//////////////////////////////////////////////////////////////////////////////////////////////
*outStyleSheet += AZStd::string::format("QPushButton#ButtonGroup:hover \n");
*outStyleSheet += AZStd::string::format("{ \n");
*outStyleSheet += AZStd::string::format(" background-color: rgb(144, 152, 160); \n");
*outStyleSheet += AZStd::string::format(" color: black; \n");
GetBorderStyleSheet(&helperStyleString, numRows, numColumns, i, j);
*outStyleSheet += AZStd::string::format(" %s \n", helperStyleString.c_str());
*outStyleSheet += AZStd::string::format("} \n\n");
//////////////////////////////////////////////////////////////////////////////////////////////
// pressed state
//////////////////////////////////////////////////////////////////////////////////////////////
*outStyleSheet += AZStd::string::format("QPushButton#ButtonGroup:pressed \n");
*outStyleSheet += AZStd::string::format("{ \n");
*outStyleSheet += AZStd::string::format(" background-color: black; \n");
*outStyleSheet += AZStd::string::format(" color: rgb(244, 156, 28); \n");
GetBorderStyleSheet(&helperStyleString, numRows, numColumns, i, j);
*outStyleSheet += AZStd::string::format(" %s \n", helperStyleString.c_str());
*outStyleSheet += AZStd::string::format("} \n\n");
//////////////////////////////////////////////////////////////////////////////////////////////
// disabled state
//////////////////////////////////////////////////////////////////////////////////////////////
*outStyleSheet += AZStd::string::format("QPushButton#ButtonGroup:disabled \n");
*outStyleSheet += AZStd::string::format("{ \n");
*outStyleSheet += AZStd::string::format(" background-color: rgb(55, 55, 55); \n");
*outStyleSheet += AZStd::string::format(" color: rgb(105, 105, 105); \n");
GetBorderStyleSheet(&helperStyleString, numRows, numColumns, i, j);
*outStyleSheet += AZStd::string::format(" %s \n", helperStyleString.c_str());
*outStyleSheet += AZStd::string::format("} \n\n");
}
// the constructor
ButtonGroup::ButtonGroup(QWidget* parent, uint32 numRows, uint32 numColumns, EMode mode)
: QWidget(parent)
{
uint32 i;
mMode = mode;
// create the grid layout
mGridLayout = new QGridLayout(this);
mGridLayout->setMargin(0);
// set the vertical and the horizontal spacing
mGridLayout->setSpacing(0);
// reserve memory upfront to prevent allocs
AZStd::string styleModString;
styleModString.reserve(16192);
// iterate over the columns
QString temp;
for (i = 0; i < numColumns; ++i)
{
// iterate over the rows
for (uint32 j = 0; j < numRows; ++j)
{
// create a button
temp.sprintf("%d%d", i, j);
QPushButton* button = new QPushButton(temp, this);
button->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
button->setCheckable(true);
button->setMinimumHeight(22);
button->setMaximumHeight(22);
connect(button, &QPushButton::clicked, this, &MysticQt::ButtonGroup::OnButtonPressed);
// prepare and set the style sheet
PrepareStyleSheet(&styleModString, numRows, numColumns, i, j);
button->setStyleSheet(styleModString.c_str());
// add our button to the layout
mGridLayout->addWidget(button, j, i);
}
}
}
// destructor
ButtonGroup::~ButtonGroup()
{
delete mGridLayout;
}
QPushButton* ButtonGroup::GetButton(uint32 rowNr, uint32 columnNr)
{
QLayoutItem* layoutItem = mGridLayout->itemAtPosition(rowNr, columnNr);
assert(layoutItem);
QWidget* widget = layoutItem->widget();
return (QPushButton*)widget;
}
// find the column and row indices for the given button widget
void ButtonGroup::FindButtonIndices(QWidget* buttonToFind, uint32* outRowNr, uint32* outColumnNr)
{
// reset the output indices
*outColumnNr = MCORE_INVALIDINDEX32;
*outRowNr = MCORE_INVALIDINDEX32;
// get the number of columns and iterate through them
const uint32 numColumns = GetNumColumns();
for (uint32 i = 0; i < numColumns; ++i)
{
// get the number of rows and iterate through them
const uint32 numRows = GetNumRows();
for (uint32 j = 0; j < numRows; ++j)
{
// check the current widget against the one we are trying to find
QLayoutItem* layoutItem = mGridLayout->itemAtPosition(j, i);
if (layoutItem->widget() == buttonToFind)
{
*outColumnNr = i;
*outRowNr = j;
return;
}
}
}
}
// enable or disable all buttons in the button group
void ButtonGroup::SetEnabled(bool isEnabled)
{
// get the number of columns and iterate through them
const uint32 numColumns = GetNumColumns();
for (uint32 columnNr = 0; columnNr < numColumns; ++columnNr)
{
// get the number of rows and iterate through them
const uint32 numRows = GetNumRows();
for (uint32 rowNr = 0; rowNr < numRows; ++rowNr)
{
QPushButton* button = GetButton(rowNr, columnNr);
if (button)
{
button->setEnabled(isEnabled);
}
}
}
}
bool ButtonGroup::GetIsButtonChecked(uint32 rowNr, uint32 columnNr)
{
QPushButton* button = GetButton(rowNr, columnNr);
assert(button);
return button->isChecked();
}
void ButtonGroup::OnButtonPressed()
{
if (mMode == MODE_RADIOBUTTONS)
{
QPushButton* button = qobject_cast<QPushButton*>(sender());
// get the number of columns and iterate through them
const uint32 numColumns = GetNumColumns();
for (uint32 i = 0; i < numColumns; ++i)
{
// get the number of rows and iterate through them
const uint32 numRows = GetNumRows();
for (uint32 j = 0; j < numRows; ++j)
{
// check the current widget against the one we are trying to find
QLayoutItem* layoutItem = mGridLayout->itemAtPosition(j, i);
QPushButton* currentButton = (QPushButton*)layoutItem->widget();
if (currentButton == button)
{
currentButton->setChecked(true);
}
else
{
currentButton->setChecked(false);
}
}
}
}
emit ButtonPressed();
}
} // namespace MysticQt
#include <MysticQt/Source/ButtonGroup.moc>
| 46.232911 | 298 | 0.513471 | [
"solid"
] |
db1cc18f8bdbb70b42b0e9f1b7c71a68ebe6415e | 1,476 | cpp | C++ | Question_21_30/answers_cpp/answer_22.cpp | nuck555/ImageProcessing100Wen | 9e0d361f6eb61c9f23ac3e14e36a384b994c5511 | [
"MIT"
] | 3,482 | 2019-03-26T15:00:42.000Z | 2022-03-31T14:44:36.000Z | Question_21_30/answers_cpp/answer_22.cpp | nuck555/ImageProcessing100Wen | 9e0d361f6eb61c9f23ac3e14e36a384b994c5511 | [
"MIT"
] | 33 | 2019-11-26T09:21:50.000Z | 2021-09-17T08:35:23.000Z | Question_21_30/answers_cpp/answer_22.cpp | nuck555/ImageProcessing100Wen | 9e0d361f6eb61c9f23ac3e14e36a384b994c5511 | [
"MIT"
] | 1,129 | 2019-04-11T02:00:34.000Z | 2022-03-31T08:08:01.000Z | #include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <math.h>
// histogram transform
cv::Mat histogram_transform(cv::Mat img, int m0, int s0){
// get height and width
int width = img.cols;
int height = img.rows;
int channel = img.channels();
// histogram transformation hyper-parameters
double m, s;
double sum = 0., squared_sum = 0.;
double val;
// output image
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3);
// get sum
for (int y = 0; y < height; y++){
for (int x = 0; x < width; x++){
for (int c = 0; c < 3; c++){
val = (float)img.at<cv::Vec3b>(y, x)[c];
sum += val;
squared_sum += (val * val);
}
}
}
// get standard deviation
m = sum / (height * width * channel);
s = sqrt(squared_sum / (height * width * channel) - m * m);
// histogram transformation
for (int y = 0; y < height; y++){
for ( int x = 0; x < width; x++){
for ( int c = 0; c < 3; c++){
val = img.at<cv::Vec3b>(y, x)[c];
out.at<cv::Vec3b>(y, x)[c] = (uchar)(s0 / s * (val - m) + m0);
}
}
}
return out;
}
int main(int argc, const char* argv[]){
// read image
cv::Mat img = cv::imread("imori_dark.jpg", cv::IMREAD_COLOR);
// histogram transform
cv::Mat out = histogram_transform(img, 128, 52);
//cv::imwrite("out.jpg", out);
cv::imshow("answer", out);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}
| 22.029851 | 70 | 0.556233 | [
"transform"
] |
db1ceee04311c14ce492f8682361c4be5e17167f | 846 | cpp | C++ | 75a.cpp | Vinzz34/important | 5950931d95fa4c705e4bbcbcdb5af37aa1731fcf | [
"MIT"
] | null | null | null | 75a.cpp | Vinzz34/important | 5950931d95fa4c705e4bbcbcdb5af37aa1731fcf | [
"MIT"
] | null | null | null | 75a.cpp | Vinzz34/important | 5950931d95fa4c705e4bbcbcdb5af37aa1731fcf | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
#define ld long double
#define vi vector<int>
#define vpii vector<pair<int,int>>
#define PB push_back
#define MP make_pair
#define fi first
#define se second
#define sz(a) int((a).size())
#define FOR(a,b,c) for(int a=b;a<(int)(c);a++)
#define MOD 1000000007
#define EACH(v) for(auto x : v)
#define VINZZ
int rmzeros(int num){
int dig=0,x=0,ans=0;
while(num>0){
dig=num%10;
if(dig!=0){
ans+=dig*(pow(10,x));
x++;
}
num=num/10;
}
return ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int a,b;
cin>>a>>b;
int c=0;
c=a+b;
a=rmzeros(a);
b=rmzeros(b);
c=rmzeros(c);
if(c==a+b){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
#ifdef VINZZ
cerr<<"Time: "<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
#endif
return 0;
}
| 15.666667 | 56 | 0.619385 | [
"vector"
] |
db1e35454c6dd0745bce7818863bb05527239339 | 6,107 | cpp | C++ | tags/ewsupdateitemstagsjob.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 122 | 2016-03-01T12:53:43.000Z | 2021-11-06T21:14:21.000Z | tags/ewsupdateitemstagsjob.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 54 | 2016-05-02T10:05:47.000Z | 2022-02-01T18:10:38.000Z | tags/ewsupdateitemstagsjob.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 17 | 2016-05-18T21:02:08.000Z | 2022-01-27T20:33:26.000Z | /* This file is part of Akonadi EWS Resource
Copyright (C) 2015-2016 Krzysztof Nowicki <krissn@op.pl>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "ewsupdateitemstagsjob.h"
#include <AkonadiCore/Tag>
#include <AkonadiCore/TagFetchJob>
#include <AkonadiCore/TagAttribute>
#include <AkonadiCore/AttributeFactory>
#include "ewsid.h"
#include "ewsupdateitemrequest.h"
#include "ewsitemhandler.h"
#include "ewsclient.h"
#include "ewstagstore.h"
#include "ewsresource.h"
#include "ewsglobaltagswritejob.h"
using namespace Akonadi;
EwsUpdateItemsTagsJob::EwsUpdateItemsTagsJob(const Akonadi::Item::List &items, EwsTagStore *tagStore,
EwsClient &client, EwsResource *parent)
: EwsJob(parent), mItems(items), mTagStore(tagStore), mClient(client)
{
}
EwsUpdateItemsTagsJob::~EwsUpdateItemsTagsJob()
{
}
void EwsUpdateItemsTagsJob::start()
{
Tag::List unknownTags;
/* In the Exchange world it is not possible to add or remove individual tags from an item
* - it is necessary to write the full list of tags at once. Unfortunately the tags objects
* attached to an item only contain the id. They're missing any persistent identification such
* as the uid. If the EWS resource hasn't seen these tags yet it is necessary to fetch them
* first before any further processing.
*/
Q_FOREACH(const Item &item, mItems) {
qDebug() << item.tags().size();
Q_FOREACH(const Tag &tag, item.tags()) {
qDebug() << tag.name() << tag.url() << tag.gid() << tag.id();
if (!mTagStore->containsId(tag.id())) {
unknownTags.append(tag);
}
}
}
if (!unknownTags.empty()) {
TagFetchJob *job = new TagFetchJob(unknownTags, this);
connect(job, &TagFetchJob::result, this, &EwsUpdateItemsTagsJob::itemsTagsChangedTagsFetched);
} else {
doUpdateItemsTags();
}
}
void EwsUpdateItemsTagsJob::itemsTagsChangedTagsFetched(KJob *job)
{
Item::List items = job->property("items").value<Item::List>();
if (job->error()) {
setErrorMsg(job->errorString());
emitResult();
return;
}
TagFetchJob *tagJob = qobject_cast<TagFetchJob*>(job);
if (!tagJob) {
setErrorMsg(QStringLiteral("Invalid TagFetchJob job object"));
emitResult();
return;
}
/* All unknown tags have been fetched and can be written to Exchange. */
mTagStore->addTags(tagJob->tags());
EwsResource *res = qobject_cast<EwsResource*>(parent());
Q_ASSERT(res);
EwsGlobalTagsWriteJob *writeJob = new EwsGlobalTagsWriteJob(mTagStore, mClient,
res->rootCollection(), this);
connect(writeJob, &EwsGlobalTagsWriteJob::result, this,
&EwsUpdateItemsTagsJob::globalTagsWriteFinished);
writeJob->start();
}
void EwsUpdateItemsTagsJob::globalTagsWriteFinished(KJob *job)
{
if (job->error()) {
setErrorMsg(job->errorString());
emitResult();
return;
}
doUpdateItemsTags();
}
void EwsUpdateItemsTagsJob::doUpdateItemsTags()
{
EwsUpdateItemRequest *req = new EwsUpdateItemRequest(mClient, this);
Q_FOREACH(const Item &item, mItems) {
EwsUpdateItemRequest::ItemChange ic(EwsId(item.remoteId(), item.remoteRevision()),
EwsItemHandler::mimeToItemType(item.mimeType()));
if (!item.tags().isEmpty()) {
QStringList tagList;
QStringList categoryList;
Q_FOREACH(const Tag &tag, item.tags()) {
Q_ASSERT(mTagStore->containsId(tag.id()));
tagList.append(mTagStore->tagRemoteId(tag.id()));
QString name = mTagStore->tagName(tag.id());
if (!name.isEmpty()) {
categoryList.append(name);
}
}
EwsUpdateItemRequest::Update *upd
= new EwsUpdateItemRequest::SetUpdate(EwsResource::tagsProperty, tagList);
ic.addUpdate(upd);
upd = new EwsUpdateItemRequest::SetUpdate(EwsPropertyField("item:Categories"), categoryList);
ic.addUpdate(upd);
} else {
EwsUpdateItemRequest::Update *upd
= new EwsUpdateItemRequest::DeleteUpdate(EwsResource::tagsProperty);
ic.addUpdate(upd);
upd = new EwsUpdateItemRequest::DeleteUpdate(EwsPropertyField("item:Categories"));
ic.addUpdate(upd);
}
req->addItemChange(ic);
}
connect(req, &EwsUpdateItemRequest::result, this,
&EwsUpdateItemsTagsJob::updateItemsTagsRequestFinished);
req->start();
}
void EwsUpdateItemsTagsJob::updateItemsTagsRequestFinished(KJob *job)
{
if (job->error()) {
setErrorMsg(job->errorString());
emitResult();
return;
}
EwsUpdateItemRequest *req = qobject_cast<EwsUpdateItemRequest*>(job);
if (!req) {
setErrorMsg(QStringLiteral("Invalid EwsUpdateItemRequest job object"));
return;
}
Q_ASSERT(mItems.count() == req->responses().count());
auto itemIt = mItems.begin();
Q_FOREACH(const EwsUpdateItemRequest::Response &resp, req->responses()) {
if (resp.isSuccess()) {
itemIt->setRemoteRevision(resp.itemId().changeKey());
}
}
emitResult();
}
| 34.502825 | 105 | 0.649091 | [
"object"
] |
db1fce247fdd2078e150df325493577fda05c1be | 831 | cpp | C++ | Backtracking/Permutations.cpp | ShauryaAiri/InterviewBit-Solutions | 89de715220be1e8a40f844a00c35120a13e10836 | [
"MIT"
] | 1 | 2019-03-11T12:37:20.000Z | 2019-03-11T12:37:20.000Z | Backtracking/Permutations.cpp | ashaywalke/InterviewBit-Solutions | 6757929e1fd3e65780cc4243266c1d477a2d225b | [
"MIT"
] | null | null | null | Backtracking/Permutations.cpp | ashaywalke/InterviewBit-Solutions | 6757929e1fd3e65780cc4243266c1d477a2d225b | [
"MIT"
] | 1 | 2018-10-04T11:03:49.000Z | 2018-10-04T11:03:49.000Z | //https://www.interviewbit.com/problems/permutations/
void permutation(vector<int> A, int N, vector<vector<int>> &perms, vector<int>perm, vector<int> chosen )
{
if(perm.size()==N)
{
// sort(perm.begin(), perm.end());
// cout<<"pushing = "<<left<<endl;
perms.push_back(perm);
return;
}
else
{
for(int i=0; i< N; i++){
if(chosen[i]) continue;
perm.push_back(A[i]);
chosen[i] = 1;
permutation(A, N, perms, perm, chosen);
chosen[i] = 0;
perm.pop_back();
}
}
}
vector<vector<int> > Solution::permute(vector<int> &A)
{
int N =A.size();
vector<int> chosen(N, 0);
vector<int> perm;
vector<vector<int>> perms;
permutation(A, N, perms, perm, chosen);
return perms;
}
| 25.181818 | 104 | 0.523466 | [
"vector"
] |
db20eff18d1803e4ccb10244971d25d3f12132b3 | 5,782 | cc | C++ | src/graphics/intersect.cc | asmuth-archive/travistest | b69b0981952bb8274031792a887169a2cca12d95 | [
"Apache-2.0"
] | 721 | 2015-01-01T15:14:48.000Z | 2017-04-28T20:27:56.000Z | src/graphics/intersect.cc | asmuth-archive/travistest | b69b0981952bb8274031792a887169a2cca12d95 | [
"Apache-2.0"
] | 98 | 2019-08-02T01:01:59.000Z | 2019-08-02T11:54:38.000Z | src/graphics/intersect.cc | asmuth-archive/travistest | b69b0981952bb8274031792a887169a2cca12d95 | [
"Apache-2.0"
] | 93 | 2015-01-02T11:21:33.000Z | 2017-04-26T08:18:33.000Z | /**
* This file is part of the "clip" project
* Copyright (c) 2018 Paul Asmuth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "intersect.h"
namespace clip {
bool intersect_line_line(
vec2 p0,
vec2 v0,
vec2 p1,
vec2 v1,
vec2* p /* = nullptr */) {
// ensure the direction vectors are normalized
v0 = normalize(v0);
v1 = normalize(v1);
// consider lines as parallel if the angle between them is smaller than some
// threshold
const double a_epsilon = 0.001;
double a = acos(dot(v0, v1));
double a_norm = fmod(M_PI - a, M_PI);
if (a_norm < a_epsilon) {
return false;
}
// if the lines are not parallel, but the user is not interested in the
// intersection point, return
if (!p) {
return true;
}
// the next step is to compute the point of intersection. we start with the
// implicit expressions that define the global y coordinates of all points on
// the input lines in terms of the global x coordinate written in the standard
// form:
//
// aN * x + bN * y = cN
//
// we already have the direction vector (a and b) as an input argument, so
// we can find a valid c that satisfies the equation simply by evaluating the
// left part of the equation with the known point on the line that we also
// have.
auto a0 = -v0.y;
auto a1 = -v1.y;
auto b0 = v0.x;
auto b1 = v1.x;
auto c0 = a0 * p0.x + b0 * p0.y;
auto c1 = a1 * p1.x + b1 * p1.y;
// the x coordinate of the point of intersection can now be determined
// by solving the following system of linear equations. the two equations are
// the standard-form line equations derived above.
//
// a0 * x + b0 * y = c0
// a1 * x + b1 * y = c1
//
// or written in matrix coefficient form:
//
// | a0 b0 | | x | | c0 |
// | | + | | = | |
// | a1 b1 | | y | | c1 |
//
// this system can be solved using cramer's rule (there must be a solution
// since the lines are already determined not to be parallel). to do so, we
// first calculate the three "denominator", "x numerator" and "y numerator"
// determinants of the (substituted) coefficient matrix and then compute the
// result by dividing the determinants as defined by cramer's rule:
auto dd = (a0 * b1 - b0 * a1); // standard determinant
auto dx = (b1 * c0 - b0 * c1); // replace x coefficients (a0/a1) with solution
auto dy = (a0 * c1 - a1 * c0); // replace y coefficients (b0/b1) with solution
p->x = dx / dd;
p->y = dy / dd;
return true;
}
bool intersect_line_lineseg(
vec2 p0,
vec2 v0,
vec2 s1,
vec2 e1,
vec2* p /* = nullptr */) {
// find the intersection between the infinite lines given by {p0, v1} and the
// infinite line that passes through {s0, e0}
vec2 pt;
auto pt_exists = intersect_line_line(
p0,
v0,
s1,
normalize(sub(e1, s1)),
&pt);
if (!pt_exists) {
return false;
}
// check if the intersection point is outside of the line segment
const double epsilon = 0.001;
if (pt.x + epsilon < std::min(s1.x, e1.x) ||
pt.x - epsilon > std::max(s1.x, e1.x) ||
pt.y + epsilon < std::min(s1.y, e1.y) ||
pt.y - epsilon > std::max(s1.y, e1.y)) {
return false;
}
// we found a point of intersection that is located on the line segment,
// return it
if (p) {
*p = pt;
}
return true;
}
bool intersect_lineseg_lineseg(
vec2 s0,
vec2 e0,
vec2 s1,
vec2 e1,
vec2* p /* = nullptr */) {
// find the intersection between the infinite lines that pass through {s0, e0}
// and {s1, e1} respectively
vec2 pt;
auto pt_exists = intersect_line_line(
s0,
sub(e0, s0),
s1,
normalize(sub(e1, s1)),
&pt);
if (!pt_exists) {
return false;
}
// check if the intersection point is outside of one of the lines segments
const double epsilon = 0.001;
if (pt.x + epsilon < std::min(s0.x, e0.x) ||
pt.x - epsilon > std::max(s0.x, e0.x) ||
pt.y + epsilon < std::min(s0.y, e0.y) ||
pt.y - epsilon > std::max(s0.y, e0.y) ||
pt.x + epsilon < std::min(s1.x, e1.x) ||
pt.x - epsilon > std::max(s1.x, e1.x) ||
pt.y + epsilon < std::min(s1.y, e1.y) ||
pt.y - epsilon > std::max(s1.y, e1.y)) {
return false;
}
// we found a point of intersection that is located on both line segments,
// return it
if (p) {
*p = pt;
}
return true;
}
void intersect_poly_line(
const Polygon2& p0,
const vec2& p1,
const vec2& v1,
std::vector<vec2>* x) {
// intersect with each edge of the polygon
for (size_t i = 0; i < p0.vertices.size(); ++i) {
Point p;
auto p_found = intersect_line_lineseg(
p1,
v1,
p0.vertices[i],
p0.vertices[(i + 1) % p0.vertices.size()],
&p);
if (p_found) {
x->push_back(p);
}
}
}
void intersect_poly_lineseg(
const Polygon2& p0,
const vec2& s1,
const vec2& e1,
std::vector<vec2>* x) {
// intersect with each edge of the polygon
for (size_t i = 0; i < p0.vertices.size(); ++i) {
Point p;
auto p_found = intersect_lineseg_lineseg(
p0.vertices[i],
p0.vertices[(i + 1) % p0.vertices.size()],
s1,
e1,
&p);
if (p_found) {
x->push_back(p);
}
}
}
} // namespace clip
| 26.893023 | 80 | 0.602041 | [
"vector"
] |
db234c586425b53ae2b7355192a4c6e2b718e439 | 962 | cpp | C++ | src/test/testlib/testbench_shells.cpp | catenocrypt/peerboot-cpp | 2520cd6cf391d5554c0d072fc5d31414e161836a | [
"MIT"
] | 7 | 2019-11-06T09:01:08.000Z | 2022-01-24T00:08:18.000Z | src/test/testlib/testbench_shells.cpp | catenocrypt/peerboot-cpp | 2520cd6cf391d5554c0d072fc5d31414e161836a | [
"MIT"
] | null | null | null | src/test/testlib/testbench_shells.cpp | catenocrypt/peerboot-cpp | 2520cd6cf391d5554c0d072fc5d31414e161836a | [
"MIT"
] | 1 | 2021-01-16T17:52:24.000Z | 2021-01-16T17:52:24.000Z | #include "testbench_shells.hpp"
#include "connector_peer.hpp"
#include <memory>
#include <vector>
using namespace pebo;
using namespace std;
long TestBenchShells::myCounter = 0;
void TestBenchShells::addShell(shared_ptr<Shell> shell_in)
{
string id = "testnode" + to_string(++myCounter);
myShells[id] = shell_in;
}
void TestBenchShells::connect()
{
// connect pair-wise
for(auto s1 = myShells.begin(); s1 != myShells.end(); ++s1)
{
for(auto s2 = myShells.begin(); s2 != myShells.end(); ++s2)
{
if (s1 != s2)
{
// connect s1 with s2, using a ConnectedClient
ConnectorPeer::connect2Nets(s1->second->getPeboNet().get(), s2->second->getPeboNet().get(), s1->first, s2->first);
}
}
}
}
void TestBenchShells::deinit()
{
// connect pair-wise
for(auto s = myShells.begin(); s != myShells.end(); ++s)
{
s->second->deinit();
}
}
| 22.904762 | 129 | 0.589397 | [
"vector"
] |
db260af005af8266fe65078ed0a38b00177130ec | 8,912 | cc | C++ | src/tools/persistent_intersection_homology.cc | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 56 | 2019-04-24T22:11:15.000Z | 2022-03-22T11:37:47.000Z | src/tools/persistent_intersection_homology.cc | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 48 | 2016-11-30T09:37:13.000Z | 2019-01-30T21:43:39.000Z | src/tools/persistent_intersection_homology.cc | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 11 | 2019-05-02T11:54:31.000Z | 2020-12-10T14:05:40.000Z | #include <aleph/containers/DataDescriptors.hh>
#include <aleph/containers/DimensionalityEstimators.hh>
#include <aleph/containers/PointCloud.hh>
#include <aleph/config/FLANN.hh>
#ifdef ALEPH_WITH_FLANN
#include <aleph/geometry/FLANN.hh>
#else
#include <aleph/geometry/BruteForce.hh>
#endif
#include <aleph/geometry/SphereSampling.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>
#include <aleph/geometry/distances/Euclidean.hh>
#include <aleph/math/Statistics.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistenceDiagrams/distances/Bottleneck.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/PhiPersistence.hh>
#include <aleph/topology/BarycentricSubdivision.hh>
#include <aleph/topology/Filter.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/Skeleton.hh>
#include <aleph/topology/filtrations/Data.hh>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>
#include <getopt.h>
using DataType = double;
using VertexType = unsigned;
using Distance = aleph::geometry::distances::Euclidean<DataType>;
using PointCloud = aleph::containers::PointCloud<DataType>;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using Filtration = aleph::topology::filtrations::Data<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
#ifdef ALEPH_WITH_FLANN
using NearestNeighbours = aleph::geometry::FLANN<PointCloud, Distance>;
#else
using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;
#endif
template <class Functor> std::vector<DataType> extract( const PointCloud& pointCloud, Functor f )
{
std::vector<DataType> values;
values.reserve( pointCloud.size() );
for( std::size_t i = 0; i < pointCloud.size(); i++ )
{
auto p = pointCloud[i];
auto x = f( p.begin(), p.end() );
values.push_back(x);
}
return values;
}
std::vector<DataType> standardizeValues( const std::vector<DataType>& data )
{
auto mean = aleph::math::sampleMean( data.begin(), data.end() );
auto sdev = aleph::math::sampleStandardDeviation( data.begin(), data.end() );
auto result = data;
std::transform( data.begin(), data.end(), result.begin(),
[&mean, &sdev] ( DataType x )
{
return ( x - mean ) / sdev;
}
);
return result;
}
int main( int argc, char** argv )
{
DataType filterThreshold = DataType();
bool invert = false;
bool standardize = false;
{
static option commandLineOptions[] =
{
{ "filter" , required_argument, nullptr, 'f' },
{ "invert" , no_argument , nullptr, 'i' },
{ "standardize", no_argument , nullptr, 's' },
{ nullptr , 0 , nullptr, 0 }
};
int option = 0;
while( ( option = getopt_long( argc, argv, "f:is", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'f':
filterThreshold = static_cast<DataType>( std::stod(optarg) );
break;
case 'i':
invert = true;
break;
case 's':
standardize = true;
break;
}
}
}
if( ( argc - optind ) < 2 )
return -1;
std::string inputPointCloud = argv[optind++];
std::string inputCurvatures = "";
DataType epsilon = static_cast<DataType>( std::stod( argv[optind++] ) );
if( ( argc - optind ) >= 1 )
inputCurvatures = argv[optind++];
auto pointCloud = aleph::containers::load<DataType>( inputPointCloud );
std::vector<DataType> singularityValues;
singularityValues.reserve( pointCloud.size() );
if( inputCurvatures.empty() == false )
{
std::cerr << "* Loading singularity values...";
auto curvatures = aleph::containers::load<DataType>( inputCurvatures );
singularityValues = extract( curvatures,
[] ( auto begin, auto end )
{
return std::accumulate( begin, end, DataType() );
} );
std::cerr << "finished\n";
if( standardize )
{
std::cerr << "* Standardizing singularity values...";
singularityValues = standardizeValues( singularityValues );
std::cerr << "finished\n";
}
}
unsigned dimension = 2;
if( ( argc - optind ) >= 1 )
dimension = static_cast<unsigned>( std::stoul( argv[optind++] ) );
auto K
= aleph::geometry::buildVietorisRipsComplex(
NearestNeighbours( pointCloud ),
epsilon,
dimension
);
std::cerr << "* Obtained Vietoris--Rips complex with " << K.size() << " simplices\n";
decltype(K) K0, K1, K2, K3, L;
// Determine stratification ------------------------------------------
//
// There are two modes of operation here. First, if no singularity
// values have been specified by the user, we employ the canonical
// stratification based on skeletons.
if( singularityValues.empty() )
{
std::cerr << "* Calculating skeletons...";
K0 = aleph::topology::Skeleton()( 0, K );
K1 = K0;
K2 = K;
std::cerr << "finished\n";
std::cerr << "* Performing barycentric subdivision...";
// Barycentric subdivision to ensure that the resulting complex is
// flaglike in the sense of MacPherson et al.
L = aleph::topology::BarycentricSubdivision()( K, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
{
bool useMaximum = true;
bool skipOneDimensionalSimplices = true;
L.recalculateWeights( useMaximum, skipOneDimensionalSimplices );
L.sort( aleph::topology::filtrations::Data<typename decltype(L)::ValueType>() ); // FIXME
}
std::cerr << "finished\n"
<< "* Subdivided simplicial complex has " << L.size() << " simplices\n";
}
// Else, we use the supplied singularity values to forbid parts of the
// original data sets because they are too close to a singularity.
else
{
std::cerr << "* Using singularity values to filter complex...";
aleph::topology::Filter filter;
K0 = filter( K,
[&filterThreshold,&invert,&singularityValues] ( auto s )
{
if( s.dimension() == 0 )
{
auto v = s[0];
auto x = singularityValues.at(v);
if( invert )
return x > filterThreshold;
else
return x < filterThreshold;
}
return false;
}
);
std::cerr << "finished\n"
<< "* Filtered 0-dimensional complex has " << K0.size() << " simplices\n";
K1 = filter( K,
[&filterThreshold,&invert,&singularityValues] ( auto s )
{
if( s.dimension() == 0 )
{
auto v = s[0];
auto x = singularityValues.at(v);
if( invert )
return x > filterThreshold;
else
return x < filterThreshold;
}
else if( s.dimension() == 1 )
{
auto u = s[0];
auto v = s[1];
auto x = singularityValues.at(u);
auto y = singularityValues.at(v);
if( invert )
return std::max(x,y) > filterThreshold;
else
return std::max(x,y) < filterThreshold;
}
return false;
}
);
if( K.dimension() == 2 )
{
K1 = K0;
K2 = K;
}
else
{
K2 = K1;
K3 = K;
}
L = K;
}
std::cerr << "* Calculating persistent homology...";
auto D1 = aleph::calculatePersistenceDiagrams( K );
std::cerr << "finished\n";
std::cerr << "* Calculating intersection homology...";
auto D2 = D1;
if( K.dimension() == 2 )
D2 = aleph::calculateIntersectionHomology( L, {K0,K1,K2}, aleph::PerversityGM( {0} ) );
else
D2 = aleph::calculateIntersectionHomology( L, {K0,K1,K2,K3}, aleph::PerversityGM( {0,1} ) );
std::cerr << "finished\n";
{
std::ofstream out0( "/tmp/D_0_PH.txt" );
std::ofstream out1( "/tmp/D_0_IH.txt" );
D1.front().removeDiagonal();
D2.front().removeDiagonal();
out0 << D1.front() << "\n";
out1 << D2.front() << "\n";
}
if( D1.size() >= 2 && D2.size() >= 2 )
{
std::ofstream out0( "/tmp/D_1_PH.txt" );
std::ofstream out1( "/tmp/D_1_IH.txt" );
D1[1].removeDiagonal();
D2[1].removeDiagonal();
out0 << D1[1] << "\n";
out1 << D2[1] << "\n";
}
std::cerr << D1.size() << "," << D2.size() << "\n";
if( D1.size() >= 3 && D2.size() >= 3 )
{
std::ofstream out0( "/tmp/D_2_PH.txt" );
std::ofstream out1( "/tmp/D_2_IH.txt" );
D1[2].removeDiagonal();
D2[2].removeDiagonal();
out0 << D1[2] << "\n";
out1 << D2[2] << "\n";
}
}
| 26.602985 | 122 | 0.587747 | [
"geometry",
"vector",
"transform"
] |
db2619220707ff4b8fcce1ad5336685e82dd8077 | 2,670 | cpp | C++ | Applications/NavierStokes/OAT15A/sources/exasim4.0/kernel/application/fluxDriver.cpp | rloekvh/Exasim | c794431e8b1eff902c2ffad8182d1a9b53339c0d | [
"MIT"
] | 37 | 2020-12-09T20:24:36.000Z | 2022-02-18T17:19:23.000Z | Applications/NavierStokes/OAT15A/sources/exasim4.0/kernel/application/fluxDriver.cpp | rloekvh/Exasim | c794431e8b1eff902c2ffad8182d1a9b53339c0d | [
"MIT"
] | 25 | 2020-11-25T20:37:33.000Z | 2022-02-25T15:53:11.000Z | Applications/NavierStokes/OAT15A/sources/exasim4.0/kernel/application/fluxDriver.cpp | rloekvh/Exasim | c794431e8b1eff902c2ffad8182d1a9b53339c0d | [
"MIT"
] | 8 | 2020-11-30T15:34:06.000Z | 2022-01-09T21:06:00.000Z | #ifndef __FLUXDRIVER
#define __FLUXDRIVER
void FluxDriver(dstype *f, dstype *xg, dstype *udg, dstype *odg, meshstruct &mesh,
masterstruct &master, appstruct &app, solstruct &sol, tempstruct &temp,
commonstruct &common, Int nge, Int e1, Int e2, Int backend)
{
Int nc = common.nc; // number of compoments of (u, q, p)
Int ncu = common.ncu;// number of compoments of (u)
Int ncq = common.ncq;// number of compoments of (q)
Int ncp = common.ncp;// number of compoments of (p)
Int nco = common.nco;// number of compoments of (o)
Int ncx = common.ncx;// number of compoments of (xdg)
Int nd = common.nd; // spatial dimension
Int numPoints = nge*(e2-e1);
dstype time = common.time;
/* 2. Compute physical source */
#ifdef HAVE_ONETHREAD
if (backend==0) {
// if (common.appname == 1)
// opuFluxNS(f, xg, udg, odg, &app.physicsparam[0], time,
// numPoints, nc, ncu, nd, ncx, nco);
// else if (common.appname == 2)
// opuFluxPoisson(f, xg, udg, odg, &app.physicsparam[0], time,
// numPoints, nc, ncu, nd, ncx, nco);
// else
opuFlux(f, xg, udg, odg, &app.physicsparam[0], time,
numPoints, nc, ncu, nd, ncx, nco, common.appname);
}
#endif
#ifdef HAVE_OPENMP
if (backend==1) {
// if (common.appname == 1)
// cpuFluxNS(f, xg, udg, odg, &app.physicsparam[0], time,
// numPoints, nc, ncu, nd, ncx, nco);
// else if (common.appname == 2)
// cpuFluxPoisson(f, xg, udg, odg, &app.physicsparam[0], time,
// numPoints, nc, ncu, nd, ncx, nco);
// else
cpuFlux(f, xg, udg, odg, &app.physicsparam[0], time,
numPoints, nc, ncu, nd, ncx, nco, common.appname);
}
#endif
#ifdef HAVE_CUDA
if (backend==2) {
// if (common.appname == 1)
// gpuFluxNS(f, xg, udg, odg, &app.physicsparam[0], time,
// numPoints, nc, ncu, nd, ncx, nco);
// else if (common.appname == 2)
// gpuFluxPoisson(f, xg, udg, odg, &app.physicsparam[0], time,
// numPoints, nc, ncu, nd, ncx, nco);
// else
gpuFlux(f, xg, udg, odg, &app.physicsparam[0], time,
numPoints, nc, ncu, nd, ncx, nco, common.appname);
}
#endif
}
#endif
| 43.770492 | 98 | 0.491386 | [
"mesh"
] |
db330fdecd1bb77466597a92002f9731c92905a2 | 6,215 | cpp | C++ | Implementation/Core/amc_systemstate.cpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | 15 | 2020-11-10T17:22:39.000Z | 2021-12-16T14:45:11.000Z | Implementation/Core/amc_systemstate.cpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | 5 | 2021-08-30T06:58:52.000Z | 2022-03-09T15:25:49.000Z | Implementation/Core/amc_systemstate.cpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | 20 | 2020-08-06T15:53:34.000Z | 2022-02-09T13:49:59.000Z | /*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "amc_systemstate.hpp"
#include "libmc_exceptiontypes.hpp"
#include "amc_logger.hpp"
#include "amc_parameterhandler.hpp"
#include "amc_statesignalhandler.hpp"
#include "amc_driverhandler.hpp"
#include "amc_toolpathhandler.hpp"
#include "amc_servicehandler.hpp"
#include "amc_ui_handler.hpp"
#include "amc_statemachinedata.hpp"
#include "libmcdata_dynamic.hpp"
#include "common_chrono.hpp"
#define __STRINGIZE(x) #x
#define __STRINGIZE_VALUE_OF(x) __STRINGIZE(x)
namespace AMC {
CSystemState::CSystemState(AMC::PLogger pLogger, LibMCData::PDataModel pDataModel, LibMCEnv::PWrapper pEnvWrapper)
{
LibMCAssertNotNull(pLogger.get());
LibMCAssertNotNull(pDataModel.get());
LibMCAssertNotNull(pEnvWrapper.get());
m_pGlobalChrono = std::make_shared<AMCCommon::CChrono>();
m_pLogger = pLogger;
m_pDataModel = pDataModel;
// Retrieve Installation UUID and Secret
m_pDataModel->GetInstallationInformation(m_sInstallationUUID, m_sInstallationSecret);
// Create Data Model Instances
m_pStorage = m_pDataModel->CreateStorage();
m_pBuildJobHandler = m_pDataModel->CreateBuildJobHandler();
m_pLoginHandler = m_pDataModel->CreateLoginHandler();
m_pToolpathHandler = std::make_shared<CToolpathHandler>(m_pStorage, m_pBuildJobHandler);
m_pDriverHandler = std::make_shared<CDriverHandler>(pEnvWrapper, m_pToolpathHandler);
m_pSignalHandler = std::make_shared<CStateSignalHandler>();
m_pServiceHandler = std::make_shared<CServiceHandler>(m_pLogger);
m_pStateMachineData = std::make_shared<CStateMachineData>();
m_pUIHandler = std::make_shared<CUIHandler>(m_pStateMachineData, m_pSignalHandler, pEnvWrapper, m_pLogger);
}
CSystemState::~CSystemState()
{
}
CLogger* CSystemState::logger()
{
return m_pLogger.get();
}
CStateSignalHandler* CSystemState::stateSignalHandler()
{
return m_pSignalHandler.get();
}
CDriverHandler* CSystemState::driverHandler()
{
return m_pDriverHandler.get();
}
CToolpathHandler* CSystemState::toolpathHandler()
{
return m_pToolpathHandler.get();
}
CServiceHandler* CSystemState::serviceHandler()
{
return m_pServiceHandler.get();
}
CUIHandler* CSystemState::uiHandler()
{
return m_pUIHandler.get();
}
CStateMachineData* CSystemState::stateMachineData()
{
return m_pStateMachineData.get();
}
PLogger CSystemState::getLoggerInstance()
{
return m_pLogger;
}
PStateSignalHandler CSystemState::getStateSignalHandlerInstance()
{
return m_pSignalHandler;
}
PDriverHandler CSystemState::getDriverHandlerInstance()
{
return m_pDriverHandler;
}
PToolpathHandler CSystemState::getToolpathHandlerInstance()
{
return m_pToolpathHandler;
}
PStateMachineData CSystemState::getStateMachineData()
{
return m_pStateMachineData;
}
LibMCData::PLoginHandler CSystemState::getLoginHandlerInstance()
{
return m_pLoginHandler;
}
LibMCData::PBuildJobHandler CSystemState::getBuildJobHandlerInstance()
{
return m_pBuildJobHandler;
}
AMCCommon::PChrono CSystemState::getGlobalChronoInstance()
{
return m_pGlobalChrono;
}
LibMCData::CStorage * CSystemState::storage()
{
return m_pStorage.get();
}
LibMCData::CBuildJobHandler* CSystemState::buildJobHandler()
{
return m_pBuildJobHandler.get();
}
LibMCData::CLoginHandler* CSystemState::loginHandler()
{
return m_pLoginHandler.get();
}
AMCCommon::CChrono* CSystemState::globalChrono()
{
return m_pGlobalChrono.get();
}
void CSystemState::addLibraryPath(const std::string& sLibraryName, const std::string& sLibraryPath, const std::string& sLibraryResourcePath)
{
m_LibraryPathes.insert(std::make_pair(sLibraryName, std::make_pair (sLibraryPath, sLibraryResourcePath)));
m_pToolpathHandler->setLibraryPath(sLibraryName, sLibraryPath);
}
std::string CSystemState::getLibraryPath(const std::string& sLibraryName)
{
auto iIter = m_LibraryPathes.find(sLibraryName);
if (iIter == m_LibraryPathes.end())
throw ELibMCCustomException(LIBMC_ERROR_LIBRARYPATHNOTFOUND, sLibraryName);
return iIter->second.first;
}
std::string CSystemState::getLibraryResourcePath(const std::string& sLibraryName)
{
auto iIter = m_LibraryPathes.find(sLibraryName);
if (iIter == m_LibraryPathes.end())
throw ELibMCCustomException(LIBMC_ERROR_LIBRARYPATHNOTFOUND, sLibraryName);
return iIter->second.second;
}
std::string CSystemState::getSystemUserID()
{
// TODO: Retrieve a unique User ID for the current running session
return "amc";
}
std::string CSystemState::getInstallationUUID()
{
return m_sInstallationUUID;
}
std::string CSystemState::getInstallationSecret()
{
return m_sInstallationSecret;
}
std::string CSystemState::getGitHash()
{
return __STRINGIZE_VALUE_OF(__GITHASH);
}
}
| 26.334746 | 141 | 0.7786 | [
"model"
] |
db338e6ef10078f2d3cb89fb7e236674e39b8db1 | 1,142 | cpp | C++ | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/menu_screen/MenuPresenter.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/menu_screen/MenuPresenter.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/menu_screen/MenuPresenter.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <gui/menu_screen/MenuPresenter.hpp>
#include <gui/menu_screen/MenuView.hpp>
MenuPresenter::MenuPresenter(MenuView& v)
: view(v)
{
}
MenuPresenter::~MenuPresenter()
{
}
void MenuPresenter::activate()
{
for (int i = 0; i < model->getNumberOfRooms(); i++)
{
// Avoid "Master Bedroom" - name too long :)
if (i != 1)
{
view.addRoomToHomeAutomationTile(model->getRoomTemperatureInfo(i));
}
}
view.initializeTiles();
}
void MenuPresenter::deactivate()
{
}
| 23.791667 | 80 | 0.541156 | [
"model"
] |
b9cdda16d4dfed86fdb6b486e053c7cafe4353f8 | 3,741 | hpp | C++ | far/hilight.hpp | lidacity/FarManager | 4ff6edbd53b6652d3ab1d9ae86f66873be850209 | [
"BSD-3-Clause"
] | null | null | null | far/hilight.hpp | lidacity/FarManager | 4ff6edbd53b6652d3ab1d9ae86f66873be850209 | [
"BSD-3-Clause"
] | null | null | null | far/hilight.hpp | lidacity/FarManager | 4ff6edbd53b6652d3ab1d9ae86f66873be850209 | [
"BSD-3-Clause"
] | null | null | null | #ifndef HILIGHT_HPP_DE941BF9_997F_45B6_A454_3F455C156548
#define HILIGHT_HPP_DE941BF9_997F_45B6_A454_3F455C156548
#pragma once
/*
hilight.hpp
Files highlighting
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Internal:
#include "plugin.hpp"
// Platform:
#include "platform.chrono.hpp"
// Common:
#include "common/noncopyable.hpp"
// External:
//----------------------------------------------------------------------------
class FileFilterParams;
class FileList;
class FileListItem;
class HierarchicalConfig;
class VMenu2;
namespace highlight
{
struct color
{
enum
{
normal,
selected,
normal_current,
selected_current,
count
};
};
class element
{
private:
struct colors
{
FarColor FileColor{};
FarColor MarkColor{};
bool operator ==(const colors& rhs) const
{
return FileColor == rhs.FileColor && MarkColor == rhs.MarkColor;
}
};
struct mark
{
wchar_t Char{};
bool Transparent{};
bool operator ==(const mark& rhs) const
{
return Char == rhs.Char && Transparent == rhs.Transparent;
}
};
public:
using colors_array = std::array<colors, color::count>;
colors_array Color;
mark Mark;
bool operator==(const element& rhs) const
{
return Color == rhs.Color && Mark == rhs.Mark;
}
};
class configuration: noncopyable
{
public:
configuration();
void UpdateCurrentTime();
const element* GetHiColor(const FileListItem& Item, const FileList* Owner, bool UseAttrHighlighting = false);
int GetGroup(const FileListItem& Object, const FileList* Owner);
void HiEdit(int MenuPos);
void UpdateHighlighting(bool RefreshMasks = false);
void Save(bool always);
static void ApplyFinalColor(element::colors_array::value_type& Colors, size_t PaletteIndex);
private:
void InitHighlightFiles(/*const*/ HierarchicalConfig& cfg);
void ClearData();
int MenuPosToRealPos(int MenuPos, int*& Count, bool Insert = false);
void FillMenu(VMenu2 *HiMenu, int MenuPos);
void ProcessGroups();
struct element_hash
{
size_t operator()(const element& item) const;
};
std::unordered_set<element, element_hash> Colors;
std::vector<FileFilterParams> HiData;
int FirstCount{}, UpperCount{}, LowerCount{}, LastCount{};
os::chrono::time_point CurrentTime;
bool m_Changed{};
};
}
#endif // HILIGHT_HPP_DE941BF9_997F_45B6_A454_3F455C156548
| 25.979167 | 111 | 0.732692 | [
"object",
"vector"
] |
b9d0f5fb47f345363784b04ae9386f21f1d11371 | 463 | cpp | C++ | CodeForces/Complete/1200-1299/1243A-MaximumSquare.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/1200-1299/1243A-MaximumSquare.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/1200-1299/1243A-MaximumSquare.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <vector>
#include <algorithm>
int main(){
long q; scanf("%ld", &q);
while(q--){
long n; scanf("%ld", &n);
std::vector<long> a(n); for(long p = 0; p < n; p++){scanf("%ld", &a[p]);}
sort(a.rbegin(), a.rend());
long side(0);
for(long p = 0; p < n; p++){
if(a[p] >= p + 1){side = p + 1;}
else{break;}
}
printf("%ld\n", side);
}
return 0;
}
| 20.130435 | 81 | 0.421166 | [
"vector"
] |
b9d6990c499ad7088d71f26b6bac9893dde8cb79 | 4,547 | cpp | C++ | fuzzer.cpp | zhaoxiaoyunok/python-library-fuzzers | 83db496f75280795415821097802a96fbf72f50f | [
"MIT"
] | 4 | 2019-07-03T06:01:08.000Z | 2019-07-29T08:07:54.000Z | fuzzer.cpp | zhaoxiaoyunok/python-library-fuzzers | 83db496f75280795415821097802a96fbf72f50f | [
"MIT"
] | null | null | null | fuzzer.cpp | zhaoxiaoyunok/python-library-fuzzers | 83db496f75280795415821097802a96fbf72f50f | [
"MIT"
] | 4 | 2019-07-03T03:24:56.000Z | 2021-12-11T12:30:31.000Z | #include <climits>
#include <cstdlib>
#include <iomanip>
#include <libgen.h>
#include <sstream>
#include <vector>
#include <string>
#include <optional>
#include <Python.h>
#ifndef PYTHON_HARNESS_PATH
#error "Define PYTHON_HARNESS_PATH"
#endif
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static std::string ToAbsolutePath(const std::string argv0, const std::string relativePath) {
char absoluteRootPath[PATH_MAX+1];
char argv0Copy[argv0.size()+1];
memcpy(argv0Copy, argv0.c_str(), argv0.size()+1);
if ( realpath(dirname(argv0Copy), absoluteRootPath) == nullptr ) {
printf("Fatal error: Cannot resolve absolute root path\n");
abort();
}
return std::string(std::string(absoluteRootPath) + "/" + relativePath);
}
void* pFunc = nullptr;
extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
const std::string argv0 = (*argv)[0];
const std::string absoluteCPythonInstallPath = ToAbsolutePath(argv0, "cpython-install");
const std::string absoluteScriptPath = ToAbsolutePath(argv0, PYTHON_HARNESS_PATH);
std::vector<uint8_t> program;
{
if ( setenv("PYTHONHOME", absoluteCPythonInstallPath.c_str(), 1) != 0 ) {
printf("Fatal error: Cannot set PYTHONHOME\n");
abort();
}
}
FILE* fp = fopen(absoluteScriptPath.c_str(), "rb");
if ( fp == nullptr ) {
printf("Fatal error: Cannot open script: %s\n", absoluteScriptPath.c_str());
abort();
}
fseek (fp, 0, SEEK_END);
long length = ftell(fp);
if ( length < 1 ) {
printf("Fatal error: Cannot retrieve script file size\n");
abort();
}
fseek (fp, 0, SEEK_SET);
program.resize(length);
if ( fread(program.data(), 1, length, fp) != static_cast<size_t>(length) ) {
printf("Fatal error: Cannot read script\n");
abort();
}
fclose(fp);
std::string code = std::string(program.data(), program.data() + program.size());
{
wchar_t *program = Py_DecodeLocale(argv0.c_str(), nullptr);
Py_SetProgramName(program);
PyMem_RawFree(program);
}
Py_Initialize();
{
std::string setArgv0;
setArgv0 += "import sys";
setArgv0 += "\n";
setArgv0 += "sys.argv[0] = '" + absoluteScriptPath + "'\n";
if ( PyRun_SimpleString(setArgv0.c_str()) != 0 ) {
printf("Fatal: Cannot set argv[0]\n");
PyErr_PrintEx(1);
abort();
}
}
{
std::string setPYTHONPATH;
setPYTHONPATH += "import sys";
setPYTHONPATH += "\n";
setPYTHONPATH += "sys.path.append('" + absoluteScriptPath + "')\n";
setPYTHONPATH += "\n";
if ( PyRun_SimpleString(setPYTHONPATH.c_str()) != 0 ) {
printf("Fatal: Cannot set PYTHONPATH\n");
PyErr_PrintEx(1);
abort();
}
}
PyObject *pValue, *pModule, *pLocal;
pModule = PyModule_New("fuzzermod");
PyModule_AddStringConstant(pModule, "__file__", "");
pLocal = PyModule_GetDict(pModule);
pValue = PyRun_String(code.c_str(), Py_file_input, pLocal, pLocal);
if ( pValue == nullptr ) {
printf("Fatal: Cannot create Python function from string\n");
PyErr_PrintEx(1);
abort();
}
Py_DECREF(pValue);
pFunc = PyObject_GetAttrString(pModule, "FuzzerRunOne");
if (pFunc == nullptr || !PyCallable_Check(static_cast<PyObject*>(pFunc))) {
printf("Fatal: FuzzerRunOne not defined or not callable\n");
abort();
}
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
std::optional<std::vector<uint8_t>> ret = std::nullopt;
PyObject *pArgs, *pValue;
pArgs = PyTuple_New(1);
pValue = PyBytes_FromStringAndSize((const char*)data, size);
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(static_cast<PyObject*>(pFunc), pArgs);
if ( pValue == nullptr ) {
/* Abort on unhandled exception */
PyErr_PrintEx(1);
abort();
}
if ( PyBytes_Check(pValue) ) {
/* Retrieve output */
uint8_t* output;
Py_ssize_t outputSize;
if ( PyBytes_AsStringAndSize(pValue, (char**)&output, &outputSize) != -1) {
/* Return output */
ret = std::vector<uint8_t>(output, output + outputSize);
goto end;
} else {
/* TODO this should not happen */
}
}
end:
Py_DECREF(pValue);
Py_DECREF(pArgs);
//return ret;
return 0;
}
| 27.895706 | 92 | 0.601495 | [
"vector"
] |
b9d75d853cca50f6979abab77ae3e1aae8b1f16a | 1,764 | cpp | C++ | src/parser.cpp | baines/lang | afec2d61cda4569c5593ef491f5b2af69580728b | [
"MIT"
] | null | null | null | src/parser.cpp | baines/lang | afec2d61cda4569c5593ef491f5b2af69580728b | [
"MIT"
] | null | null | null | src/parser.cpp | baines/lang | afec2d61cda4569c5593ef491f5b2af69580728b | [
"MIT"
] | null | null | null | #include "el3.h"
using namespace el3;
static TokenType matching_bracket(TokenType t){
switch(t){
case TKN_FUNC_START: return TKN_FUNC_END;
case TKN_BLOCK_START: return TKN_BLOCK_END;
case TKN_LIST_START: return TKN_LIST_END;
case TKN_FUNC_END: return TKN_FUNC_START;
case TKN_BLOCK_END: return TKN_BLOCK_START;
case TKN_LIST_END: return TKN_LIST_START;
default: return TKN_INVALID;
}
}
static ErrorCode validate_args_marker(const std::vector<Token>& tokens, size_t& index){
for(ssize_t i = index - 1; i >= 0; --i){
Token t = tokens[i];
//NOTE: It is permissible for a block with no args to have an arg marker.
if(t.type == TKN_BLOCK_START){
return EL3_ERR_NONE;
}
if(t.type == TKN_ARGS_MARKER){
return EL3_ERR_MULTIPLE_ARG_DECL;
}
if(t.type != TKN_SYMBOL){
index = i;
return EL3_ERR_NON_SYMBOL_ARG;
}
}
return EL3_ERR_ARG_MARKER_OUTSIDE_BLOCK;
}
bool Context::parse(const std::vector<Token>& tokens){
Stack brackets(tokens.size());
for(size_t i = 0, j = tokens.size(); i < j; ++i){
Token t = tokens[i];
switch(t.type){
case TKN_FUNC_START:
case TKN_BLOCK_START:
case TKN_LIST_START:
brackets.push(t);
break;
case TKN_FUNC_END:
case TKN_BLOCK_END:
case TKN_LIST_END: {
Token match = brackets.pop();
if(match.type != matching_bracket(t.type)){
error_print(EL3_ERR_BRACKET_MISMATCH, t);
return false;
}
break;
}
case TKN_ARGS_MARKER: {
ErrorCode e;
if((e = validate_args_marker(tokens, i))){
error_print(e, tokens[i]);
return false;
}
break;
}
}
}
if(!brackets.frame_empty()){
error_print(EL3_ERR_BRACKET_MISMATCH, brackets.pop());
return false;
} else {
return true;
}
}
| 22.05 | 87 | 0.672902 | [
"vector"
] |
b9d8780a82a94371d78059f5d6b56b1f0095a648 | 10,702 | cpp | C++ | android-30/android/media/AudioFormat.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-30/android/media/AudioFormat.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/media/AudioFormat.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../os/Parcel.hpp"
#include "../../JObject.hpp"
#include "../../JString.hpp"
#include "./AudioFormat.hpp"
namespace android::media
{
// Fields
jint AudioFormat::CHANNEL_CONFIGURATION_DEFAULT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_CONFIGURATION_DEFAULT"
);
}
jint AudioFormat::CHANNEL_CONFIGURATION_INVALID()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_CONFIGURATION_INVALID"
);
}
jint AudioFormat::CHANNEL_CONFIGURATION_MONO()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_CONFIGURATION_MONO"
);
}
jint AudioFormat::CHANNEL_CONFIGURATION_STEREO()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_CONFIGURATION_STEREO"
);
}
jint AudioFormat::CHANNEL_INVALID()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_INVALID"
);
}
jint AudioFormat::CHANNEL_IN_BACK()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_BACK"
);
}
jint AudioFormat::CHANNEL_IN_BACK_PROCESSED()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_BACK_PROCESSED"
);
}
jint AudioFormat::CHANNEL_IN_DEFAULT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_DEFAULT"
);
}
jint AudioFormat::CHANNEL_IN_FRONT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_FRONT"
);
}
jint AudioFormat::CHANNEL_IN_FRONT_PROCESSED()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_FRONT_PROCESSED"
);
}
jint AudioFormat::CHANNEL_IN_LEFT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_LEFT"
);
}
jint AudioFormat::CHANNEL_IN_LEFT_PROCESSED()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_LEFT_PROCESSED"
);
}
jint AudioFormat::CHANNEL_IN_MONO()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_MONO"
);
}
jint AudioFormat::CHANNEL_IN_PRESSURE()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_PRESSURE"
);
}
jint AudioFormat::CHANNEL_IN_RIGHT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_RIGHT"
);
}
jint AudioFormat::CHANNEL_IN_RIGHT_PROCESSED()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_RIGHT_PROCESSED"
);
}
jint AudioFormat::CHANNEL_IN_STEREO()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_STEREO"
);
}
jint AudioFormat::CHANNEL_IN_VOICE_DNLINK()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_VOICE_DNLINK"
);
}
jint AudioFormat::CHANNEL_IN_VOICE_UPLINK()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_VOICE_UPLINK"
);
}
jint AudioFormat::CHANNEL_IN_X_AXIS()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_X_AXIS"
);
}
jint AudioFormat::CHANNEL_IN_Y_AXIS()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_Y_AXIS"
);
}
jint AudioFormat::CHANNEL_IN_Z_AXIS()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_IN_Z_AXIS"
);
}
jint AudioFormat::CHANNEL_OUT_5POINT1()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_5POINT1"
);
}
jint AudioFormat::CHANNEL_OUT_7POINT1()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_7POINT1"
);
}
jint AudioFormat::CHANNEL_OUT_7POINT1_SURROUND()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_7POINT1_SURROUND"
);
}
jint AudioFormat::CHANNEL_OUT_BACK_CENTER()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_BACK_CENTER"
);
}
jint AudioFormat::CHANNEL_OUT_BACK_LEFT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_BACK_LEFT"
);
}
jint AudioFormat::CHANNEL_OUT_BACK_RIGHT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_BACK_RIGHT"
);
}
jint AudioFormat::CHANNEL_OUT_DEFAULT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_DEFAULT"
);
}
jint AudioFormat::CHANNEL_OUT_FRONT_CENTER()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_FRONT_CENTER"
);
}
jint AudioFormat::CHANNEL_OUT_FRONT_LEFT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_FRONT_LEFT"
);
}
jint AudioFormat::CHANNEL_OUT_FRONT_LEFT_OF_CENTER()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_FRONT_LEFT_OF_CENTER"
);
}
jint AudioFormat::CHANNEL_OUT_FRONT_RIGHT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_FRONT_RIGHT"
);
}
jint AudioFormat::CHANNEL_OUT_FRONT_RIGHT_OF_CENTER()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_FRONT_RIGHT_OF_CENTER"
);
}
jint AudioFormat::CHANNEL_OUT_LOW_FREQUENCY()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_LOW_FREQUENCY"
);
}
jint AudioFormat::CHANNEL_OUT_MONO()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_MONO"
);
}
jint AudioFormat::CHANNEL_OUT_QUAD()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_QUAD"
);
}
jint AudioFormat::CHANNEL_OUT_SIDE_LEFT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_SIDE_LEFT"
);
}
jint AudioFormat::CHANNEL_OUT_SIDE_RIGHT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_SIDE_RIGHT"
);
}
jint AudioFormat::CHANNEL_OUT_STEREO()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_STEREO"
);
}
jint AudioFormat::CHANNEL_OUT_SURROUND()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"CHANNEL_OUT_SURROUND"
);
}
JObject AudioFormat::CREATOR()
{
return getStaticObjectField(
"android.media.AudioFormat",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
jint AudioFormat::ENCODING_AAC_ELD()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AAC_ELD"
);
}
jint AudioFormat::ENCODING_AAC_HE_V1()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AAC_HE_V1"
);
}
jint AudioFormat::ENCODING_AAC_HE_V2()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AAC_HE_V2"
);
}
jint AudioFormat::ENCODING_AAC_LC()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AAC_LC"
);
}
jint AudioFormat::ENCODING_AAC_XHE()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AAC_XHE"
);
}
jint AudioFormat::ENCODING_AC3()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AC3"
);
}
jint AudioFormat::ENCODING_AC4()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_AC4"
);
}
jint AudioFormat::ENCODING_DEFAULT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_DEFAULT"
);
}
jint AudioFormat::ENCODING_DOLBY_MAT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_DOLBY_MAT"
);
}
jint AudioFormat::ENCODING_DOLBY_TRUEHD()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_DOLBY_TRUEHD"
);
}
jint AudioFormat::ENCODING_DTS()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_DTS"
);
}
jint AudioFormat::ENCODING_DTS_HD()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_DTS_HD"
);
}
jint AudioFormat::ENCODING_E_AC3()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_E_AC3"
);
}
jint AudioFormat::ENCODING_E_AC3_JOC()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_E_AC3_JOC"
);
}
jint AudioFormat::ENCODING_IEC61937()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_IEC61937"
);
}
jint AudioFormat::ENCODING_INVALID()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_INVALID"
);
}
jint AudioFormat::ENCODING_MP3()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_MP3"
);
}
jint AudioFormat::ENCODING_OPUS()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_OPUS"
);
}
jint AudioFormat::ENCODING_PCM_16BIT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_PCM_16BIT"
);
}
jint AudioFormat::ENCODING_PCM_8BIT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_PCM_8BIT"
);
}
jint AudioFormat::ENCODING_PCM_FLOAT()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"ENCODING_PCM_FLOAT"
);
}
jint AudioFormat::SAMPLE_RATE_UNSPECIFIED()
{
return getStaticField<jint>(
"android.media.AudioFormat",
"SAMPLE_RATE_UNSPECIFIED"
);
}
// QJniObject forward
AudioFormat::AudioFormat(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
jint AudioFormat::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
jboolean AudioFormat::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint AudioFormat::getChannelCount() const
{
return callMethod<jint>(
"getChannelCount",
"()I"
);
}
jint AudioFormat::getChannelIndexMask() const
{
return callMethod<jint>(
"getChannelIndexMask",
"()I"
);
}
jint AudioFormat::getChannelMask() const
{
return callMethod<jint>(
"getChannelMask",
"()I"
);
}
jint AudioFormat::getEncoding() const
{
return callMethod<jint>(
"getEncoding",
"()I"
);
}
jint AudioFormat::getFrameSizeInBytes() const
{
return callMethod<jint>(
"getFrameSizeInBytes",
"()I"
);
}
jint AudioFormat::getSampleRate() const
{
return callMethod<jint>(
"getSampleRate",
"()I"
);
}
jint AudioFormat::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
JString AudioFormat::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
void AudioFormat::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::media
| 19.564899 | 75 | 0.704822 | [
"object"
] |
b9e08ae5fb4eb9ebfcbff6991df6a19ac8fc9718 | 4,073 | hpp | C++ | core/src/Rendering/RenderQueue.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 36 | 2015-03-12T10:42:36.000Z | 2022-01-12T04:20:40.000Z | core/src/Rendering/RenderQueue.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 1 | 2015-12-17T00:25:43.000Z | 2016-02-20T12:00:57.000Z | core/src/Rendering/RenderQueue.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 6 | 2017-06-17T07:57:53.000Z | 2019-04-09T21:11:24.000Z | /*
* Copyright (c) 2013, Hernan Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CRIMILD_CORE_RENDERING_RENDER_QUEUE_
#define CRIMILD_CORE_RENDERING_RENDER_QUEUE_
#include "Foundation/SharedObject.hpp"
#include "Foundation/Containers/Array.hpp"
#include "SceneGraph/Geometry.hpp"
#include "SceneGraph/Camera.hpp"
#include "SceneGraph/Light.hpp"
#include "Material.hpp"
#include <functional>
#include <vector>
#include <chrono>
namespace crimild {
class RenderQueue;
using RenderQueuePtr = SharedPointer< RenderQueue >;
class RenderQueue : public SharedObject {
public:
struct Renderable {
SharedPointer< Geometry > geometry;
SharedPointer< Material > material;
Matrix4f modelTransform;
double distanceFromCamera;
};
enum class RenderableType {
BACKGROUND,
OCCLUDER,
SHADOW_CASTER,
OPAQUE,
OPAQUE_CUSTOM,
TRANSLUCENT,
TRANSLUCENT_CUSTOM,
SCREEN,
DEBUG,
};
using Renderables = std::list< Renderable >;
public:
explicit RenderQueue( void );
virtual ~RenderQueue( void );
public:
void reset( void );
void setCamera( Camera *camera );
Camera *getCamera( void ) { return crimild::get_ptr( _camera ); }
const Matrix4f &getViewMatrix( void ) const { return _viewMatrix; }
const Matrix4f &getProjectionMatrix( void ) const { return _projectionMatrix; }
void push( Geometry *geometry );
void push( Light *light );
Renderables *getRenderables( RenderableType type ) { return &_renderables[ type ]; }
void each( Renderables *renderables, std::function< void( Renderable * ) > callback );
void each( std::function< void( Light *, int ) > callback );
private:
SharedPointer< Camera > _camera;
Matrix4f _viewMatrix;
Matrix4f _projectionMatrix;
std::vector< SharedPointer< Light >> _lights;
std::map< RenderableType, Renderables > _renderables;
public:
unsigned long getTimestamp( void ) const { return _timestamp; }
void setTimestamp( unsigned long value ) { _timestamp = value; }
private:
std::chrono::microseconds::rep _timestamp;
};
namespace messaging {
struct RenderQueueAvailable {
containers::Array< SharedPointer< RenderQueue >> renderQueues;
};
}
}
#endif
| 32.846774 | 94 | 0.668795 | [
"geometry",
"vector"
] |
b9e2c93dc23d8417c19a5ba7f4be91bfafe2c62d | 3,210 | cpp | C++ | src/webcam_capture.cpp | danielvicedo/webcam_capture | 6e8101528392ca925be42e68fd212f431d318edc | [
"BSD-3-Clause"
] | null | null | null | src/webcam_capture.cpp | danielvicedo/webcam_capture | 6e8101528392ca925be42e68fd212f431d318edc | [
"BSD-3-Clause"
] | null | null | null | src/webcam_capture.cpp | danielvicedo/webcam_capture | 6e8101528392ca925be42e68fd212f431d318edc | [
"BSD-3-Clause"
] | null | null | null |
//opencv
#include "opencv2/opencv.hpp"
#include <opencv2/core/mat.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//std
#include <iostream>
#include <cstdlib>
//main
int main(int argc, char *argv[])
{
cv::VideoCapture camera; //OpenCV video capture object
cv::Mat image; //OpenCV image object
cv::Mat temporary; //OpenCV temporary image for color modification
int cam_id; //camera id . Associated to device number in /dev/videoX
int user_key; //user pressed key to quit
cv::Vec3b pixel_intensity; //pixel RGB intensity
cv::Vec4b Rect; //pixel RGB intensity
//check user args
switch(argc)
{
case 1: //no argument provided, so try /dev/video0
cam_id = 0;
break;
case 2: //an argument is provided. Get it and set cam_id
cam_id = atoi(argv[1]);
break;
default:
std::cout << "Invalid number of arguments. Call program as: webcam_capture [video_device_id]. " << std::endl;
std::cout << "EXIT program." << std::endl;
break;
}
//advertising to the user
std::cout << "Opening video device " << cam_id << std::endl;
//open the video stream and make sure it's opened
if( !camera.open(cam_id) )
{
std::cout << "Error opening the camera. May be invalid device id. EXIT program." << std::endl;
return -1;
}
//capture loop. Out of user press a key
while(1)
{
//Read image and check it. Blocking call up to a new image arrives from camera.
if(!camera.read(image))
{
std::cout << "No frame" << std::endl;
cv::waitKey();
}
// get intensity of the central pixel. Ordered as BGR. Rows = 480, Cols = 640
pixel_intensity = image.at<cv::Vec3b>(image.rows/2, image.cols/2);
std::cout << "RGB: " << (unsigned int)pixel_intensity[2] << ","
<< (unsigned int)pixel_intensity[1] << ","
<< (unsigned int)pixel_intensity[0] << std::endl;
// manipulate the central pixel value. Set it as blue
pixel_intensity[0] = 255;
pixel_intensity[1] = 0;
pixel_intensity[2] = 0;
image.at<cv::Vec3b>(image.rows/2, image.cols/2) = pixel_intensity;
// Create a rectangle
// declare variables
int x = image.cols/2-100;
int y = image.rows/2-100;
int width = 200;
int height = 200;
cv::Rect rect(x, y, width, height);
// Point 1 is the upper left corner of the rectangle
cv::Point pt1(x, y);
// Point 2 is the bottom right corner of the rectangle
cv::Point pt2(x + width, y + height);
// Calls the image, both points and the color of the rectangle
cv::rectangle(image, pt1, pt2, cv::Scalar(0, 255, 0));
// Greyscale the inside of the rectangle
// use a temporary image to convert to Greyscale
cvtColor(image, temporary, CV_BGR2GRAY);
cvtColor(temporary, temporary, CV_GRAY2BGR);
//put mask temporary(rect) in front of image to see both at the same time
temporary(rect).copyTo(image(rect));
temporary = image;
//show image in a window
cv::imshow("Output Window", image);
//Waits 30 millisecond to check if 'q' key has been pressed. If so, breaks the loop. Otherwise continues.
if( (unsigned char)(cv::waitKey(30) & 0xff) == 'q' ) break;
}
}
| 31.782178 | 112 | 0.638941 | [
"object"
] |
b9e7c0c3ca0541f49fb24ad111c156ee0650a10a | 1,500 | cpp | C++ | src/game/server/tf/bot/map_entities/tf_bot_hint_entity.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/server/tf/bot/map_entities/tf_bot_hint_entity.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/server/tf/bot/map_entities/tf_bot_hint_entity.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
//
//
//=============================================================================
#include "cbase.h"
#include "tf_bot_hint_entity.h"
#include "tf_obj.h"
#include "tf_player.h"
BEGIN_DATADESC( CBaseTFBotHintEntity )
DEFINE_KEYFIELD( m_isDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
END_DATADESC()
IMPLEMENT_AUTO_LIST( ITFBotHintEntityAutoList );
//------------------------------------------------------------------------------
CBaseTFBotHintEntity::CBaseTFBotHintEntity( void )
: m_isDisabled( false ),
m_hintType( HINT_INVALID )
{
}
bool CBaseTFBotHintEntity::OwnerObjectHasNoOwner() const
{
CBaseEntity* pOwner = GetOwnerEntity();
if ( pOwner && pOwner->IsBaseObject() )
{
CBaseObject *pObj = static_cast< CBaseObject* >( pOwner );
if ( pObj->GetBuilder() == NULL )
{
return true;
}
else
{
if ( !pObj->GetBuilder()->IsPlayerClass( TF_CLASS_ENGINEER ) )
{
AssertMsg( 0, "Object has an owner that's not engineer." );
Warning( "Object has an owner that's not engineer." );
}
}
}
return false;
}
bool CBaseTFBotHintEntity::OwnerObjectFinishBuilding() const
{
CBaseEntity* pOwner = GetOwnerEntity();
if ( pOwner && pOwner->IsBaseObject() )
{
CBaseObject *pObj = static_cast< CBaseObject* >( pOwner );
return !pObj->IsBuilding();
}
return false;
}
| 24.590164 | 80 | 0.621333 | [
"object"
] |
b9eb6e3f88385cd4671c10a129eecdb371e95058 | 1,507 | hpp | C++ | include/nbla/computation_graph/computation_graph.hpp | PAC-P2P/nnabla | bb7e7d52555a5bc145ec3c9a2e152fa5b11574de | [
"Apache-2.0"
] | 1 | 2021-04-08T00:33:23.000Z | 2021-04-08T00:33:23.000Z | include/nbla/computation_graph/computation_graph.hpp | enomotom/nnabla | 1947fe16a0a41d19d76cd916f151aa1991ea1b44 | [
"Apache-2.0"
] | null | null | null | include/nbla/computation_graph/computation_graph.hpp | enomotom/nnabla | 1947fe16a0a41d19d76cd916f151aa1991ea1b44 | [
"Apache-2.0"
] | 1 | 2020-08-19T08:32:51.000Z | 2020-08-19T08:32:51.000Z | // Copyright (c) 2017 Sony Corporation. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __NBLA_COMPUTATION_GRAPH_HPP__
#define __NBLA_COMPUTATION_GRAPH_HPP__
#include <nbla/computation_graph/function.hpp>
#include <nbla/computation_graph/variable.hpp>
#include <nbla/nd_array.hpp>
namespace nbla {
/** Create CgVariable outputs.
Created CGVariables are held as weak_ptr by cg_f. The `need_grad`
flags are automatically applied to created outputs.
*/
NBLA_API vector<CgVariablePtr> create_function_outputs(CgFunctionPtr cg_f,
int n_outputs = -1);
/**
*/
NBLA_API vector<CgVariablePtr> connect(CgFunctionPtr cg_f,
const vector<CgVariablePtr> &inputs,
int n_outputs = 1,
vector<NdArrayPtr> inplace_outputs = {},
bool execute = false);
}
#endif
| 35.880952 | 79 | 0.658925 | [
"vector"
] |
b9f01d6886b19dfde42dc7e46c172740cc10fc1f | 6,653 | cc | C++ | src/cache_refresh/cache_refresh.cc | zmarano/guest-oslogin | 45dbaa6b9beee283d09a9b9ab4caf8c724fd458c | [
"Apache-2.0"
] | 1 | 2022-01-25T15:47:40.000Z | 2022-01-25T15:47:40.000Z | src/cache_refresh/cache_refresh.cc | JazzEd-EdTech/guest-oslogin | b7ada1adc2e7649bd7cb16070ce1d0c1d9df5906 | [
"Apache-2.0"
] | null | null | null | src/cache_refresh/cache_refresh.cc | JazzEd-EdTech/guest-oslogin | b7ada1adc2e7649bd7cb16070ce1d0c1d9df5906 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <errno.h>
#include <nss.h>
#include <pthread.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <string.h>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <compat.h>
#include <oslogin_utils.h>
using oslogin_utils::BufferManager;
using oslogin_utils::MutexLock;
using oslogin_utils::NssCache;
using oslogin_utils::GetUsersForGroup;
// File paths for the nss cache file.
static const char kDefaultFilePath[] = K_DEFAULT_PFILE_PATH;
static const char kDefaultBackupFilePath[] = K_DEFAULT_BACKUP_PFILE_PATH;
static const char kDefaultGroupPath[] = K_DEFAULT_GFILE_PATH;
static const char kDefaultBackupGroupPath[] = K_DEFAULT_BACKUP_GFILE_PATH;
// Local NSS Cache size. This affects the maximum number of passwd or group
// entries per http request.
static const uint64_t kNssGroupCacheSize = 499;
static const uint64_t kNssPasswdCacheSize = 2048;
// Passwd buffer size. We are guaranteed that a single OS Login user will not
// exceed 32k.
static const uint64_t kPasswdBufferSize = 32768;
int refreshpasswdcache() {
syslog(LOG_INFO, "Refreshing passwd entry cache");
int error_code = 0;
// Temporary buffer to hold passwd entries before writing.
char buffer[kPasswdBufferSize];
struct passwd pwd;
NssCache nss_cache(kNssPasswdCacheSize);
std::ofstream cache_file(kDefaultBackupFilePath);
if (cache_file.fail()) {
syslog(LOG_ERR, "Failed to open file %s.", kDefaultBackupFilePath);
return -1;
}
chown(kDefaultBackupFilePath, 0, 0);
chmod(kDefaultBackupFilePath, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
nss_cache.Reset();
while (!nss_cache.OnLastPage() || nss_cache.HasNextEntry()) {
BufferManager buffer_manager(buffer, kPasswdBufferSize);
if (!nss_cache.NssGetpwentHelper(&buffer_manager, &pwd, &error_code)) {
if (error_code == ERANGE) {
syslog(LOG_ERR, "passwd entry size out of range, skipping");
} else if (error_code == EINVAL) {
syslog(LOG_ERR, "Malformed passwd entry, skipping");
} else if (error_code == ENOENT) {
syslog(LOG_ERR, "Failure getting users, quitting");
break;
} else if (error_code == ENOMSG) {
// ENOMSG means OS Login is not enabled.
break;
}
continue;
}
if (strlen(pwd.pw_passwd) == 0) {
pwd.pw_passwd = (char *)"*";
}
cache_file << pwd.pw_name << ":" << pwd.pw_passwd << ":" << pwd.pw_uid
<< ":" << pwd.pw_gid << ":" << pwd.pw_gecos << ":" << pwd.pw_dir
<< ":" << pwd.pw_shell << "\n";
}
cache_file.close();
if (error_code == ENOMSG) {
remove(kDefaultBackupFilePath);
return 0;
} else if (error_code == ENOENT) {
syslog(LOG_ERR, "Failed to get users, not updating passwd cache file, removing %s.", kDefaultBackupFilePath);
// If the cache file already exists, we don't want to overwrite it on a
// server error. So remove the backup file and return here.
struct stat buffer;
if (stat(kDefaultFilePath, &buffer) == 0) {
remove(kDefaultBackupFilePath);
return 0;
}
}
if (rename(kDefaultBackupFilePath, kDefaultFilePath) != 0) {
syslog(LOG_ERR, "Error moving %s to %s.", kDefaultBackupFilePath, kDefaultFilePath);
remove(kDefaultBackupFilePath);
}
return 0;
}
int refreshgroupcache() {
syslog(LOG_INFO, "Refreshing group entry cache");
int error_code = 0;
// Temporary buffer to hold passwd entries before writing.
char buffer[kPasswdBufferSize];
NssCache nss_cache(kNssGroupCacheSize);
std::ofstream cache_file(kDefaultBackupGroupPath);
if (cache_file.fail()) {
syslog(LOG_ERR, "Failed to open file %s.", kDefaultBackupGroupPath);
return -1;
}
chown(kDefaultBackupGroupPath, 0, 0);
chmod(kDefaultBackupGroupPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
struct group grp;
nss_cache.Reset();
std::vector<string> users;
while (!nss_cache.OnLastPage() || nss_cache.HasNextEntry()) {
BufferManager buffer_manager(buffer, kPasswdBufferSize);
if (!nss_cache.NssGetgrentHelper(&buffer_manager, &grp, &error_code)) {
if (error_code == ERANGE) {
syslog(LOG_ERR, "Group entry size out of range, skipping");
} else if (error_code == EINVAL) {
syslog(LOG_ERR, "Malformed group entry, skipping");
} else if (error_code == ENOENT) {
syslog(LOG_ERR, "Failure getting groups, quitting");
break;
} else if (error_code == ENOMSG) {
// ENOMSG means OS Login is not enabled.
break;
}
continue;
}
std::string name(grp.gr_name);
if (!GetUsersForGroup(name, &users, &error_code)) {
syslog(LOG_ERR,
"Error getting users for group %s (error_code %d), skipping.",
grp.gr_name, error_code);
continue;
}
cache_file << grp.gr_name << ":" << grp.gr_passwd << ":" << grp.gr_gid << ":" << users.front();
users.erase(users.begin());
for (int i = 0; i < (int)users.size(); i++) {
cache_file << "," << users[i];
}
cache_file << "\n";
}
cache_file.close();
if (error_code == ENOMSG) {
remove(kDefaultBackupGroupPath);
return 0;
} else if (error_code == ENOENT) {
syslog(LOG_ERR, "Failed to get groups, not updating passwd cache file, removing %s.", kDefaultBackupGroupPath);
// If the cache file already exists, we don't want to overwrite it on a
// server error. So remove the backup file and return here.
struct stat buffer;
if (stat(kDefaultGroupPath, &buffer) == 0) {
remove(kDefaultBackupGroupPath);
return 0;
}
}
if (rename(kDefaultBackupGroupPath, kDefaultGroupPath) != 0) {
syslog(LOG_ERR, "Error moving %s to %s.", kDefaultBackupGroupPath, kDefaultGroupPath);
remove(kDefaultBackupGroupPath);
}
return 0;
}
int main() {
openlog("oslogin_cache_refresh", LOG_PID|LOG_PERROR, LOG_USER);
int u_res, g_res;
u_res = refreshpasswdcache();
g_res = refreshgroupcache();
closelog();
if (u_res != 0)
return u_res;
return g_res;
}
| 33.60101 | 115 | 0.678491 | [
"vector"
] |
b9f0c6a4cfe9e6763a1cdfd3350f654b9d40f873 | 6,743 | cpp | C++ | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/AFMSPOSet.cpp | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/AFMSPOSet.cpp | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/AFMSPOSet.cpp | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | //////////////////////////////////////////////////////////////////
// (c) Copyright 2010- by Ken Esler and Jeongnim Kim
//////////////////////////////////////////////////////////////////
// National Center for Supercomputing Applications &
// Materials Computation Center
// University of Illinois, Urbana-Champaign
// Urbana, IL 61801
// e-mail: esler@uiuc.edu
//
// Supported by
// National Center for Supercomputing Applications, UIUC
// Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
#include "QMCWaveFunctions/AFMSPOSet.h"
#include "Numerics/OhmmsBlas.h"
#include "OhmmsData/AttributeSet.h"
namespace qmcplusplus
{
// void
// AFMSPOSet::addParameter (string id, int iorb, int basis)
// {
//
// }
bool
AFMSPOSet::put (xmlNodePtr node, SPOPool_t &spo_pool)
{
string gsName, basisName, opt("true"), varname("theta");
OhmmsAttributeSet attrib;
attrib.add (gsName, "gs_sposet");
attrib.add (basisName, "basis_sposet");
// attrib.add (pm, "sign");
attrib.add (theta, "theta");
attrib.add (varname, "prefix");
attrib.add (opt, "optimize");
attrib.put (node);
Optimizable = ((opt=="yes")||(opt=="true"));
// if (N == 0) {
// app_error() << "You must specify \"size\" attribute for linearopt sposet.\n";
// abort();
// }
/////////////////////////////////////
// First, find ground-state SPOSet //
/////////////////////////////////////
if (gsName == "")
{
app_error() << "You must supply \"gs_sposet\". Aborting.\n";
abort();
}
SPOPool_t::iterator iter = spo_pool.find(gsName);
if (iter == spo_pool.end())
{
app_error() << "No sposet named \"" << gsName << "\" found. Abort.\n";
abort();
}
else
{
app_log() << " Found ground-state SPOSet \"" << gsName << "\".\n";
GSOrbitals = iter->second;
}
//////////////////////////////////////
// Now, find basis SPOSet from pool //
//////////////////////////////////////
iter = spo_pool.find(basisName);
if (iter == spo_pool.end())
{
app_error() << "No sposet named \"" << basisName << "\" found. Abort.\n";
abort();
}
else
{
BasisOrbitals = iter->second;
app_log() << " Found basis SPOSet \"" << basisName << "\".\n";
}
N = BasisOrbitals->getOrbitalSetSize();
OrbitalSetSize = N;
int M = GSOrbitals->getOrbitalSetSize();
if (N!=M)
{
app_error() << "sposet sizes do not match \"" << N << ", "<<M<<". ABORT."<<endl;
abort();
}
resize(N);
if(Optimizable)
myVars.insert(varname,theta,true,optimize::SPO_P);
resetTheta(theta);
return SPOSetBase::put(node);
}
void
AFMSPOSet::resetTargetParticleSet(ParticleSet& P)
{
GSOrbitals->resetTargetParticleSet(P);
BasisOrbitals->resetTargetParticleSet(P);
}
void
AFMSPOSet::setOrbitalSetSize(int norbs)
{
OrbitalSetSize = norbs;
}
void
AFMSPOSet::checkInVariables(opt_variables_type& active)
{
active.insertFrom(myVars);
}
void
AFMSPOSet::checkOutVariables(const opt_variables_type& active)
{
myVars.getIndex(active);
}
void
AFMSPOSet::resetParameters(const opt_variables_type& active)
{
if(Optimizable)
{
int loc=myVars.where(0);
if (loc>=0)
myVars[0]=active[loc];
theta=active[loc];
}
resetTheta(theta);
}
// Obsolete
void
AFMSPOSet::evaluateDerivatives
(ParticleSet& P, int iat, const opt_variables_type& active,
ValueMatrix_t& d_phi, ValueMatrix_t& d_lapl_phi)
{
app_error() << "AFMSPOSet::evaluateDerivatives" <<endl;
abort();
}
void
AFMSPOSet::evaluate(const ParticleSet& P, int iat, ValueVector_t& psi)
{
GSOrbitals->evaluate(P,iat,GSVal);
BasisOrbitals->evaluate(P,iat,BasisVal);
for (int i=0; i<N; i++)
psi[i] = costheta*GSVal[i] + pm*sintheta*BasisVal[i];
}
void
AFMSPOSet::evaluate(const ParticleSet& P, const PosType& r,
vector<RealType> &psi)
{
app_error() << "AFMSPOSet::evaluate(const ParticleSet& P, const PosType& r, vector<RealType> &psi)\n should not be called. Abort.\n";
abort();
}
void
AFMSPOSet::evaluate(const ParticleSet& P, int iat,
ValueVector_t& psi, GradVector_t& dpsi,
ValueVector_t& d2psi)
{
GSOrbitals->evaluate(P,iat,GSVal,GSGrad,GSLapl);
BasisOrbitals->evaluate(P,iat,BasisVal,BasisGrad,BasisLapl);
for (int iorb=0; iorb<N; iorb++)
{
psi [iorb] = costheta*GSVal[iorb] + pm*sintheta*BasisVal[iorb];
d2psi[iorb] = costheta*GSLapl[iorb]+ pm*sintheta*BasisLapl[iorb];
for(int x(0); x<OHMMS_DIM; x++)
dpsi [iorb][x] = costheta*GSGrad[iorb][x] + pm*sintheta*BasisGrad[iorb][x];
}
}
void
AFMSPOSet::evaluate(const ParticleSet& P, int iat,
ValueVector_t& psi, GradVector_t& dpsi,
HessVector_t& gg_psi)
{
app_error() << "Need specialization for AFMSPOSet::evaluate(HessVector_t) Abort.\n";
abort();
}
void AFMSPOSet::evaluateForDeriv (const ParticleSet& P, int first, int last,
ValueMatrix_t& logdet, GradMatrix_t& dlogdet, ValueMatrix_t& d2logdet)
{
GSOrbitals->evaluate_notranspose(P, first, last, GSValMatrix, GSGradMatrix, GSLaplMatrix);
BasisOrbitals->evaluate_notranspose(P, first, last, BasisValMatrix, BasisGradMatrix, BasisLaplMatrix);
logdet = dsintheta*BasisValMatrix + dcostheta*GSValMatrix;
d2logdet = dsintheta*BasisLaplMatrix + dcostheta*GSLaplMatrix;
// Gradient part.
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
for (int dim=0; dim<OHMMS_DIM; dim++)
dlogdet(i,j)[dim] = dsintheta*BasisGradMatrix(i,j)[dim] + dcostheta*GSGradMatrix(i,j)[dim];
// for (int i=0; i<N; i++) for (int j=0; j<N; j++) d2logdet(i,j) -= 2.0*dot(dlogdet(i,j),dlogdet(i,j));
}
void
AFMSPOSet::evaluate_notranspose
(const ParticleSet& P, int first, int last,
ValueMatrix_t& logdet, GradMatrix_t& dlogdet, ValueMatrix_t& d2logdet)
{
GSOrbitals->evaluate_notranspose(P, first, last, GSValMatrix, GSGradMatrix, GSLaplMatrix);
BasisOrbitals->evaluate_notranspose(P, first, last, BasisValMatrix, BasisGradMatrix, BasisLaplMatrix);
logdet = costheta*GSValMatrix +pm*sintheta*BasisValMatrix;
d2logdet = costheta*GSLaplMatrix +pm*sintheta*BasisLaplMatrix;
// Gradient part.
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
for (int dim=0; dim<OHMMS_DIM; dim++)
dlogdet(i,j)[dim] = costheta*GSGradMatrix(i,j)[dim] + pm*sintheta*BasisGradMatrix(i,j)[dim];
}
SPOSetBase*
AFMSPOSet::makeClone() const
{
SPOSetBase *gs, *basis;
AFMSPOSet *clone;
gs = GSOrbitals->makeClone();
basis = BasisOrbitals->makeClone();
clone = new AFMSPOSet(N,gs,basis);
clone->setOrbitalSetSize(N);
clone->Optimizable=Optimizable;
clone->myVars=myVars;
clone->resetTheta(theta);
clone->pm=pm;
return clone;
}
}
| 28.572034 | 137 | 0.627614 | [
"vector"
] |
b9f1afac4230f156f5c00d78df32b2fca619fd79 | 3,618 | cpp | C++ | Altera/MemTest.cpp | vinayby/BlueLink | 69944e51df8358877b9a86d3749f220fa459c0da | [
"Apache-2.0"
] | 12 | 2015-09-29T10:16:36.000Z | 2021-09-04T22:04:50.000Z | Altera/MemTest.cpp | vinayby/BlueLink | 69944e51df8358877b9a86d3749f220fa459c0da | [
"Apache-2.0"
] | 1 | 2015-09-14T22:35:10.000Z | 2015-09-14T22:35:10.000Z | Altera/MemTest.cpp | vinayby/BlueLink | 69944e51df8358877b9a86d3749f220fa459c0da | [
"Apache-2.0"
] | 6 | 2015-08-25T18:09:17.000Z | 2020-07-01T14:36:05.000Z | /*
* MemTest.cpp
*
* Created on: Nov 26, 2015
* Author: jcassidy
*/
#include <cinttypes>
struct Command
{
uint64_t time;
uint64_t addr;
uint64_t data;
bool write;
};
struct Response
{
uint64_t time;
uint64_t data;
};
class MultiPortMemory
{
public:
/// Manage time (must be monotonically increasing)
void time(uint64_t t);
uint64_t time() const;
};
class MemoryPort
{
public:
};
#include <vector>
#include <fstream>
#include <array>
#include <iostream>
#include <iomanip>
#include <boost/range/adaptor/indexed.hpp>
using namespace std;
int main(int argc,char **argv)
{
array<vector<Response>::const_iterator,NPorts> portRespIt;
// set up each port's response iterator to point at the first response for that port
for(unsigned i=0;i<NPorts;++i)
for(portRespIt[i] = resps.begin(); portRespIt[i] != resps.end() && portRespIt[i]->port != i; ++portRespIt[i]){}
vector<uint64_t> v(N,0); // memory contents
size_t Nread=0, Nwrite=0;
for(vector<Command>::const_iterator cmdIt = cmds.begin(); cmdIt != cmds.end(); ++cmdIt)
{
assert (cmdIt->addr < N); // check address & port number within valid range
assert (cmdIt->port < NPorts);
if (cmdIt->write)
{
v[cmdIt->addr] = cmdIt->data;
++Nwrite;
}
else
{
++Nread;
if (portRespIt[cmdIt->port] == resps.end())
cout << "ERROR: Missing expected response for command " << dec << (cmdIt-cmds.begin()) <<
" (read issued at time " << dec << cmdIt->t << " for address " << hex << cmdIt->addr << ")" << endl;
else
{
if (portRespIt[cmdIt->port]->data != v[cmdIt->addr])
{
// make sure the iterator for this port's responses is pointing the right place
assert(portRespIt[cmdIt->port]->port == cmdIt->port);
cout << "ERROR: Incorrect response for port " << dec << cmdIt->port << " at time " << portRespIt[cmdIt->port]->t << " expecting " << hex << v[cmdIt->addr] << " but got " << portRespIt[cmdIt->port]->data << endl;
unsigned N=0;
cout << " Previous commands for address: " << endl;
for(vector<Command>::const_iterator it=cmdIt; N < 6 && it != cmds.begin(); --it)
{
if (it->addr == cmdIt->addr)
{
++N;
cout << " time " << dec << setw(6) << it->t << " port " << it->port << " " << hex << setw(6) << it->addr << ' ';
if (it->write)
cout << " write " << it->data;
else
cout << " read";
cout << endl;
}
}
cout << endl << endl;
cout << " Previous commands:" << endl;
for(vector<Command>::const_iterator it=cmdIt; N < 8 && (it--) != cmds.begin();)
{
++N;
cout << " time " << dec << setw(6) << it->t << ' ' << hex << setw(6) << it->addr << ' ';
if (it->write)
cout << " write " << it->data;
else
cout << " read";
cout << endl;
}
cout << endl << endl;
}
// advance to the next response on this port
portRespIt[cmdIt->port]++;
while(portRespIt[cmdIt->port] != resps.end() && portRespIt[cmdIt->port]->port != cmdIt->port)
++portRespIt[cmdIt->port];
}
}
}
assert(Nread+Nwrite==cmds.size());
cout << "Processed " << dec << cmds.size() << " commands (" << Nread << " reads/" << Nwrite << " writes)" << endl;
}
vector<Command> loadCommands(const string fn)
{
vector<Command> cmd;
uint64_t t,addr,data;
char op,p;
unsigned port;
ifstream is(fn.c_str());
while (!is.eof())
{
is >> dec >> t >> hex >> p >> port >> op >> addr;
assert(p=='P');
if (op == 'W')
is >> data;
else
data=0;
cmd.push_back(Command { t, addr, data, port, op=='W' });
}
return cmd;
}
| 23.802632 | 216 | 0.570205 | [
"vector"
] |
b9f46e623404b6bac42768081eb2ccc0368bb188 | 13,596 | cc | C++ | src/sim/proxy_ptr.test.cc | He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- | 9d36aaacbc7eea357608524113bec97bae2ea229 | [
"BSD-3-Clause"
] | 4 | 2020-12-25T03:12:00.000Z | 2022-01-07T03:35:35.000Z | src/sim/proxy_ptr.test.cc | He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- | 9d36aaacbc7eea357608524113bec97bae2ea229 | [
"BSD-3-Clause"
] | 3 | 2021-03-26T20:33:59.000Z | 2022-01-24T22:54:03.000Z | src/sim/proxy_ptr.test.cc | He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- | 9d36aaacbc7eea357608524113bec97bae2ea229 | [
"BSD-3-Clause"
] | 3 | 2020-04-27T06:22:06.000Z | 2021-04-15T10:12:33.000Z | /*
* Copyright 2020 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include <vector>
#include "sim/proxy_ptr.hh"
struct Access
{
bool read;
Addr addr;
Addr size;
Access(bool _read, Addr _addr, Addr _size) :
read(_read), addr(_addr), size(_size)
{}
bool
operator == (const Access &other) const
{
return read == other.read &&
addr == other.addr &&
size == other.size;
}
bool
operator != (const Access &other) const
{
return !(*this == other);
}
};
using Accesses = std::vector<Access>;
class BackingStore
{
public:
std::vector<uint8_t> store;
Addr base;
BackingStore(Addr _base, size_t _size) : store(_size, 0), base(_base) {}
void
rangeCheck(Addr addr, Addr size)
{
panic_if(addr < base || addr + size > base + store.size(),
"Range [%#x,%#x) outside of [%#x,%#x).",
addr, addr + size, base, base + store.size());
}
mutable Accesses accesses;
::testing::AssertionResult
expect_access(size_t idx, const Access &other) const
{
if (idx >= accesses.size()) {
return ::testing::AssertionFailure() << "index " << idx <<
" out of bounds";
}
if (accesses[idx] != other) {
return ::testing::AssertionFailure() << "access[" << idx <<
"] was " << accesses[idx] << ", expected " << other;
}
return ::testing::AssertionSuccess();
}
::testing::AssertionResult
expect_accesses(Accesses expected) const
{
if (accesses.size() != expected.size()) {
return ::testing::AssertionFailure() <<
"Wrong number of accesses, was " << accesses.size() <<
" expected " << expected.size();
}
auto failure = ::testing::AssertionFailure();
bool success = true;
if (accesses.size() == expected.size()) {
for (size_t idx = 0; idx < expected.size(); idx++) {
auto result = expect_access(idx, expected[idx]);
if (!result) {
failure << result.message();
success = false;
}
}
}
if (!success)
return failure;
else
return ::testing::AssertionSuccess();
}
void
writeBlob(Addr ptr, const void *data, int size)
{
rangeCheck(ptr, size);
accesses.emplace_back(false, ptr, size);
memcpy(store.data() + (ptr - base), data, size);
}
void
readBlob(Addr ptr, void *data, int size)
{
rangeCheck(ptr, size);
accesses.emplace_back(true, ptr, size);
memcpy(data, store.data() + (ptr - base), size);
}
};
::testing::AssertionResult
accessed(const char *expr1, const char *expr2,
const BackingStore &store, const Accesses &expected)
{
return store.expect_accesses(expected);
}
#define EXPECT_ACCESSES(store, ...) \
do { \
Accesses expected({__VA_ARGS__}); \
EXPECT_PRED_FORMAT2(accessed, store, expected); \
store.accesses.clear(); \
} while (false)
std::ostream &
operator << (std::ostream &os, const Access &access)
{
ccprintf(os, "%s(%#x, %d)", access.read ? "read" : "write",
access.addr, access.size);
return os;
}
class TestProxy
{
public:
BackingStore &store;
TestProxy(BackingStore &_store) : store(_store) {}
// Sneaky constructor for testing GuestABI integration.
TestProxy(ThreadContext *tc) : store(*(BackingStore *)tc) {}
void
writeBlob(Addr ptr, const void *data, int size)
{
store.writeBlob(ptr, data, size);
}
void
readBlob(Addr ptr, void *data, int size)
{
store.readBlob(ptr, data, size);
}
};
template <typename T>
using TestPtr = ProxyPtr<T, TestProxy>;
template <typename T>
using ConstTestPtr = ConstProxyPtr<T, TestProxy>;
TEST(ProxyPtr, Clean)
{
BackingStore store(0x1000, 0x1000);
EXPECT_ACCESSES(store);
{
ConstTestPtr<uint32_t> test_ptr(0x1100, store);
EXPECT_ACCESSES(store, { true, test_ptr.addr(), sizeof(uint32_t) });
}
EXPECT_ACCESSES(store);
{
TestPtr<uint32_t> test_ptr(0x1100, store);
EXPECT_ACCESSES(store, { true, test_ptr.addr(), sizeof(uint32_t) });
}
EXPECT_ACCESSES(store);
}
TEST(ProxyPtr, Dirty)
{
BackingStore store(0x1000, 0x1100);
EXPECT_ACCESSES(store);
{
TestPtr<uint32_t> test_ptr(0x1100, store);
*test_ptr = 0xa5a5a5a5;
EXPECT_ACCESSES(store, { true, test_ptr.addr(), sizeof(uint32_t) });
}
EXPECT_ACCESSES(store, { false, 0x1100, sizeof(uint32_t) });
EXPECT_EQ(store.store[0x100], 0xa5);
EXPECT_EQ(store.store[0x101], 0xa5);
EXPECT_EQ(store.store[0x102], 0xa5);
EXPECT_EQ(store.store[0x103], 0xa5);
}
TEST(ProxyPtr, LoadAndFlush)
{
BackingStore store(0x1000, 0x1100);
store.store[0x100] = 0xa5;
store.store[0x101] = 0xa5;
store.store[0x102] = 0xa5;
store.store[0x103] = 0xa5;
TestPtr<uint32_t> test_ptr(0x1100, store);
// Check that the backing store is unmodified.
EXPECT_EQ(store.store[0x100], 0xa5);
EXPECT_EQ(store.store[0x101], 0xa5);
EXPECT_EQ(store.store[0x102], 0xa5);
EXPECT_EQ(store.store[0x103], 0xa5);
// Change the value in our local buffered copy.
*test_ptr = 0x5a5a5a5a;
// Verify that the backing store hasn't been changed.
EXPECT_EQ(store.store[0x100], 0xa5);
EXPECT_EQ(store.store[0x101], 0xa5);
EXPECT_EQ(store.store[0x102], 0xa5);
EXPECT_EQ(store.store[0x103], 0xa5);
// Flush out our modifications.
test_ptr.flush();
// Verify that they've been written back to the store.
EXPECT_EQ(store.store[0x100], 0x5a);
EXPECT_EQ(store.store[0x101], 0x5a);
EXPECT_EQ(store.store[0x102], 0x5a);
EXPECT_EQ(store.store[0x103], 0x5a);
// Update the store and try to flush again.
store.store[0x100] = 0xaa;
test_ptr.flush();
// Verify that no flush happened, since our ptr was "clean".
EXPECT_EQ(store.store[0x100], 0xaa);
// Force a flush.
test_ptr.flush(true);
// Verify that the flush happened even though the ptr was "clean".
EXPECT_EQ(store.store[0x100], 0x5a);
// Update the store.
store.store[0x100] = 0xa5;
store.store[0x101] = 0xa5;
store.store[0x102] = 0xa5;
store.store[0x103] = 0xa5;
// Verify that our local copy hasn't changed.
EXPECT_EQ(*(const uint32_t *)test_ptr, 0x5a5a5a5a);
// Reload the pointer from the store.
test_ptr.load();
EXPECT_EQ(*(const uint32_t *)test_ptr, 0xa5a5a5a5);
}
TEST(ProxyPtr, ConstOperators)
{
bool is_same;
BackingStore store(0x1000, 0x1000);
const Addr addr1 = 0x1100;
const Addr addr2 = 0x1200;
using PtrType = uint32_t;
ConstTestPtr<PtrType> test_ptr1(addr1, store);
EXPECT_EQ(test_ptr1.addr(), addr1);
ConstTestPtr<PtrType> test_ptr2(addr2, store);
EXPECT_EQ(test_ptr2.addr(), addr2);
// Pointer +/- integer.
auto next_ptr = test_ptr1 + 2;
EXPECT_EQ(next_ptr.addr(), addr1 + 2 * sizeof(PtrType));
auto reverse_next_ptr = 2 + test_ptr1;
EXPECT_EQ(reverse_next_ptr.addr(), addr1 + 2 * sizeof(PtrType));
auto prev_ptr = test_ptr1 - 2;
EXPECT_EQ(prev_ptr.addr(), addr1 - 2 * sizeof(PtrType));
// Pointer-pointer subtraction.
auto diff = test_ptr2 - test_ptr1;
EXPECT_EQ(diff, (addr2 - addr1) / sizeof(PtrType));
// Assignment.
ConstTestPtr<PtrType> target(addr2, store);
EXPECT_EQ(target.addr(), addr2);
target = test_ptr1;
EXPECT_EQ(target.addr(), addr1);
// Conversions.
EXPECT_TRUE(test_ptr1);
ConstTestPtr<PtrType> null(0, store);
EXPECT_FALSE(null);
EXPECT_NE((const PtrType *)test_ptr1, nullptr);
EXPECT_EQ((const PtrType *)null, nullptr);
// Dereferences.
is_same = std::is_same<decltype(*test_ptr1), const PtrType &>::value;
EXPECT_TRUE(is_same);
store.store[0x100] = 0x55;
store.store[0x101] = 0x55;
store.store[0x102] = 0x55;
store.store[0x103] = 0x55;
// Force an update since we changed the backing store behind our ptrs back.
test_ptr1.load();
EXPECT_EQ(*test_ptr1, 0x55555555);
store.store[0x100] = 0x11;
store.store[0x101] = 0x22;
store.store[0x102] = 0x33;
store.store[0x103] = 0x44;
struct TestStruct
{
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
};
ConstTestPtr<TestStruct> struct_ptr(addr1, store);
EXPECT_EQ(struct_ptr->a, 0x11);
EXPECT_EQ(struct_ptr->b, 0x22);
EXPECT_EQ(struct_ptr->c, 0x33);
EXPECT_EQ(struct_ptr->d, 0x44);
is_same = std::is_same<decltype((struct_ptr->a)), const uint8_t &>::value;
EXPECT_TRUE(is_same);
}
TEST(ProxyPtr, NonConstOperators)
{
bool is_same;
BackingStore store(0x1000, 0x1000);
const Addr addr1 = 0x1100;
const Addr addr2 = 0x1200;
using PtrType = uint32_t;
TestPtr<PtrType> test_ptr1(addr1, store);
EXPECT_EQ(test_ptr1.addr(), addr1);
TestPtr<PtrType> test_ptr2(addr2, store);
EXPECT_EQ(test_ptr2.addr(), addr2);
// Pointer +/- integer.
auto next_ptr = test_ptr1 + 2;
EXPECT_EQ(next_ptr.addr(), addr1 + 2 * sizeof(PtrType));
auto reverse_next_ptr = 2 + test_ptr1;
EXPECT_EQ(reverse_next_ptr.addr(), addr1 + 2 * sizeof(PtrType));
auto prev_ptr = test_ptr1 - 2;
EXPECT_EQ(prev_ptr.addr(), addr1 - 2 * sizeof(PtrType));
// Pointer-pointer subtraction.
auto diff = test_ptr2 - test_ptr1;
EXPECT_EQ(diff, (addr2 - addr1) / sizeof(PtrType));
// Assignment.
TestPtr<PtrType> target(addr2, store);
EXPECT_EQ(target.addr(), addr2);
target = test_ptr1;
EXPECT_EQ(target.addr(), addr1);
// Conversions.
EXPECT_TRUE(test_ptr1);
TestPtr<PtrType> null(0, store);
EXPECT_FALSE(null);
EXPECT_NE((PtrType *)test_ptr1, nullptr);
EXPECT_EQ((PtrType *)null, nullptr);
EXPECT_NE((const PtrType *)test_ptr1, nullptr);
EXPECT_EQ((const PtrType *)null, nullptr);
// Dereferences.
is_same = std::is_same<decltype(*test_ptr1), PtrType &>::value;
EXPECT_TRUE(is_same);
// Flush test_ptr1, which has been conservatively marked as dirty.
test_ptr1.flush();
store.store[0x100] = 0x55;
store.store[0x101] = 0x55;
store.store[0x102] = 0x55;
store.store[0x103] = 0x55;
// Force an update since we changed the backing store behind our ptrs back.
test_ptr1.load();
EXPECT_EQ(*test_ptr1, 0x55555555);
store.store[0x100] = 0x11;
store.store[0x101] = 0x22;
store.store[0x102] = 0x33;
store.store[0x103] = 0x44;
struct TestStruct
{
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
};
TestPtr<TestStruct> struct_ptr(addr1, store);
EXPECT_EQ(struct_ptr->a, 0x11);
EXPECT_EQ(struct_ptr->b, 0x22);
EXPECT_EQ(struct_ptr->c, 0x33);
EXPECT_EQ(struct_ptr->d, 0x44);
is_same = std::is_same<decltype((struct_ptr->a)), uint8_t &>::value;
EXPECT_TRUE(is_same);
}
struct TestABI
{
using State = int;
};
namespace GuestABI
{
template <>
struct Argument<TestABI, Addr>
{
static Addr
get(ThreadContext *tc, typename TestABI::State &state)
{
return 0x1000;
}
};
}
bool abiCalled = false;
bool abiCalledConst = false;
void
abiTestFunc(ThreadContext *tc, TestPtr<uint8_t> ptr)
{
abiCalled = true;
EXPECT_EQ(ptr.addr(), 0x1000);
}
void
abiTestFuncConst(ThreadContext *tc, ConstTestPtr<uint8_t> ptr)
{
abiCalledConst = true;
EXPECT_EQ(ptr.addr(), 0x1000);
}
TEST(ProxyPtr, GuestABI)
{
BackingStore store(0x1000, 0x1000);
EXPECT_FALSE(abiCalled);
EXPECT_FALSE(abiCalledConst);
invokeSimcall<TestABI>((ThreadContext *)&store, abiTestFunc);
EXPECT_TRUE(abiCalled);
EXPECT_FALSE(abiCalledConst);
invokeSimcall<TestABI>((ThreadContext *)&store, abiTestFuncConst);
EXPECT_TRUE(abiCalled);
EXPECT_TRUE(abiCalledConst);
}
| 26.146154 | 79 | 0.640997 | [
"vector"
] |
b9f5e68e23adc5de4da1e202514d533c831b2623 | 9,839 | cpp | C++ | geos-3.7.0beta1/src/index/strtree/STRtree.cpp | litbangbungamayang/SIMTR | 23435e829f6c766ec8483c88005daac654de4057 | [
"MIT"
] | null | null | null | geos-3.7.0beta1/src/index/strtree/STRtree.cpp | litbangbungamayang/SIMTR | 23435e829f6c766ec8483c88005daac654de4057 | [
"MIT"
] | null | null | null | geos-3.7.0beta1/src/index/strtree/STRtree.cpp | litbangbungamayang/SIMTR | 23435e829f6c766ec8483c88005daac654de4057 | [
"MIT"
] | null | null | null | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: index/strtree/STRtree.java rev. 1.11
*
**********************************************************************/
#include <geos/index/strtree/STRtree.h>
#include <geos/index/strtree/BoundablePair.h>
#include <geos/geom/Envelope.h>
#include <vector>
#include <cassert>
#include <cmath>
#include <algorithm> // std::sort
#include <iostream> // for debugging
#include <limits>
#include <geos/util/GEOSException.h>
using namespace std;
using namespace geos::geom;
namespace geos {
namespace index { // geos.index
namespace strtree { // geos.index.strtree
static bool yComparator(Boundable *a, Boundable *b)
{
assert(a);
assert(b);
const void* aBounds = a->getBounds();
const void* bBounds = b->getBounds();
assert(aBounds);
assert(bBounds);
const Envelope* aEnv = static_cast<const Envelope*>(aBounds);
const Envelope* bEnv = static_cast<const Envelope*>(bBounds);
// NOTE - mloskot:
// The problem of instability is directly related to mathematical definition of
// "strict weak ordering" as a fundamental requirement for binary predicate:
//
// if a is less than b then b is not less than a,
// if a is less than b and b is less than c
// then a is less than c,
// and so on.
//
// For some very low values, this predicate does not fulfill this requiremnet,
// NOTE - strk:
// It seems that the '<' comparison here gives unstable results.
// In particular, when inlines are on (for Envelope::getMinY and getMaxY)
// things are fine, but when they are off we can even get a memory corruption !!
//return STRtree::centreY(aEnv) < STRtree::centreY(bEnv);
// NOTE - mloskot:
// This comparison does not answer if a is "lower" than b
// what is required for sorting. This comparison only answeres
// if a and b are "almost the same" or different
/*NOTE - cfis
In debug mode VC++ checks the predicate in both directions.
If !_Pred(_Left, _Right)
Then an exception is thrown if _Pred(_Right, _Left).
See xutility around line 320:
bool __CLRCALL_OR_CDECL _Debug_lt_pred(_Pr _Pred, _Ty1& _Left, _Ty2& _Right,
const wchar_t *_Where, unsigned int _Line)*/
//return std::fabs( STRtree::centreY(aEnv) - STRtree::centreY(bEnv) ) < 1e-30
// NOTE - strk:
// See http://trac.osgeo.org/geos/ticket/293
// as for why simple comparison (<) isn't used here
return AbstractSTRtree::compareDoubles(STRtree::centreY(aEnv),
STRtree::centreY(bEnv));
}
/*public*/
STRtree::STRtree(size_t nodeCapacity): AbstractSTRtree(nodeCapacity)
{
}
/*public*/
STRtree::~STRtree()
{
}
bool
STRtree::STRIntersectsOp::intersects(const void* aBounds, const void* bBounds)
{
return ((Envelope*)aBounds)->intersects((Envelope*)bBounds);
}
/*private*/
std::unique_ptr<BoundableList>
STRtree::createParentBoundables(BoundableList* childBoundables, int newLevel)
{
assert(!childBoundables->empty());
int minLeafCount=(int) ceil((double)childBoundables->size()/(double)getNodeCapacity());
std::unique_ptr<BoundableList> sortedChildBoundables ( sortBoundables(childBoundables) );
std::unique_ptr< vector<BoundableList*> > verticalSlicesV (
verticalSlices(sortedChildBoundables.get(), (int)ceil(sqrt((double)minLeafCount)))
);
std::unique_ptr<BoundableList> ret (
createParentBoundablesFromVerticalSlices(verticalSlicesV.get(), newLevel)
);
for (size_t i=0, vssize=verticalSlicesV->size(); i<vssize; ++i)
{
BoundableList* inner = (*verticalSlicesV)[i];
delete inner;
}
return ret;
}
/*private*/
std::unique_ptr<BoundableList>
STRtree::createParentBoundablesFromVerticalSlices(std::vector<BoundableList*>* verticalSlices, int newLevel)
{
assert(!verticalSlices->empty());
std::unique_ptr<BoundableList> parentBoundables( new BoundableList() );
for (size_t i=0, vssize=verticalSlices->size(); i<vssize; ++i)
{
std::unique_ptr<BoundableList> toAdd (
createParentBoundablesFromVerticalSlice(
(*verticalSlices)[i], newLevel)
);
assert(!toAdd->empty());
parentBoundables->insert(
parentBoundables->end(),
toAdd->begin(),
toAdd->end());
}
return parentBoundables;
}
/*protected*/
std::unique_ptr<BoundableList>
STRtree::createParentBoundablesFromVerticalSlice(BoundableList* childBoundables, int newLevel)
{
return AbstractSTRtree::createParentBoundables(childBoundables, newLevel);
}
/*private*/
std::vector<BoundableList*>*
STRtree::verticalSlices(BoundableList* childBoundables, size_t sliceCount)
{
size_t sliceCapacity = (size_t) ceil((double)childBoundables->size() / (double) sliceCount);
vector<BoundableList*>* slices = new vector<BoundableList*>(sliceCount);
size_t i=0, nchilds=childBoundables->size();
for (size_t j=0; j<sliceCount; j++)
{
(*slices)[j]=new BoundableList();
(*slices)[j]->reserve(sliceCapacity);
size_t boundablesAddedToSlice = 0;
while (i<nchilds && boundablesAddedToSlice<sliceCapacity)
{
Boundable *childBoundable=(*childBoundables)[i];
++i;
(*slices)[j]->push_back(childBoundable);
++boundablesAddedToSlice;
}
}
return slices;
}
/*public*/
const void* STRtree::nearestNeighbour(const Envelope* env, const void* item, ItemDistance* itemDist) {
build();
ItemBoundable bnd = ItemBoundable(env, (void*) item);
BoundablePair bp(getRoot(), &bnd, itemDist);
return nearestNeighbour(&bp).first;
}
std::pair<const void*, const void*> STRtree::nearestNeighbour(BoundablePair* initBndPair) {
return nearestNeighbour(initBndPair, std::numeric_limits<double>::infinity());
}
std::pair<const void*, const void*> STRtree::nearestNeighbour(ItemDistance * itemDist) {
BoundablePair bp(this->getRoot(), this->getRoot(), itemDist);
return nearestNeighbour(&bp);
}
std::pair<const void*, const void*> STRtree::nearestNeighbour(STRtree* tree, ItemDistance* itemDist) {
BoundablePair bp(getRoot(), tree->getRoot(), itemDist);
return nearestNeighbour(&bp);
}
std::pair<const void*, const void*> STRtree::nearestNeighbour(BoundablePair* initBndPair, double maxDistance) {
double distanceLowerBound = maxDistance;
BoundablePair* minPair = nullptr;
BoundablePair::BoundablePairQueue priQ;
priQ.push(initBndPair);
while(!priQ.empty() && distanceLowerBound > 0.0) {
BoundablePair* bndPair = priQ.top();
double currentDistance = bndPair->getDistance();
/**
* If the distance for the first node in the queue
* is >= the current minimum distance, all other nodes
* in the queue must also have a greater distance.
* So the current minDistance must be the true minimum,
* and we are done.
*/
if (minPair && currentDistance >= distanceLowerBound)
break;
priQ.pop();
/**
* If the pair members are leaves
* then their distance is the exact lower bound.
* Update the distanceLowerBound to reflect this
* (which must be smaller, due to the test
* immediately prior to this).
*/
if (bndPair->isLeaves()) {
distanceLowerBound = currentDistance;
minPair = bndPair;
} else {
/**
* Otherwise, expand one side of the pair,
* (the choice of which side to expand is heuristically determined)
* and insert the new expanded pairs into the queue
*/
bndPair->expandToQueue(priQ, distanceLowerBound);
}
if (bndPair != initBndPair && bndPair != minPair)
delete bndPair;
}
/* Free any remaining BoundablePairs in the queue */
while(!priQ.empty()) {
BoundablePair* bndPair = priQ.top();
priQ.pop();
if (bndPair != initBndPair)
delete bndPair;
}
if (!minPair)
throw util::GEOSException("Error computing nearest neighbor");
const void* item0 = dynamic_cast<const ItemBoundable*>(minPair->getBoundable(0))->getItem();
const void* item1 = dynamic_cast<const ItemBoundable*>(minPair->getBoundable(1))->getItem();
if (minPair != initBndPair)
delete minPair;
return std::pair<const void*, const void*>(item0, item1);
}
class STRAbstractNode: public AbstractNode{
public:
STRAbstractNode(int level, int capacity)
:
AbstractNode(level, capacity)
{}
~STRAbstractNode() override
{
delete (Envelope *)bounds;
}
protected:
void* computeBounds() const override
{
Envelope* bounds=nullptr;
const BoundableList& b = *getChildBoundables();
if ( b.empty() ) return nullptr;
BoundableList::const_iterator i=b.begin();
BoundableList::const_iterator e=b.end();
bounds=new Envelope(* static_cast<const Envelope*>((*i)->getBounds()) );
for(; i!=e; ++i)
{
const Boundable* childBoundable=*i;
bounds->expandToInclude((Envelope*)childBoundable->getBounds());
}
return bounds;
}
};
/*protected*/
AbstractNode*
STRtree::createNode(int level)
{
AbstractNode *an = new STRAbstractNode(level, static_cast<int>(nodeCapacity));
nodes->push_back(an);
return an;
}
/*public*/
void
STRtree::insert(const Envelope *itemEnv, void* item)
{
if (itemEnv->isNull()) { return; }
AbstractSTRtree::insert(itemEnv, item);
}
/*private*/
std::unique_ptr<BoundableList>
STRtree::sortBoundables(const BoundableList* input)
{
assert(input);
std::unique_ptr<BoundableList> output ( new BoundableList(*input) );
assert(output->size() == input->size());
sort(output->begin(), output->end(), yComparator);
return output;
}
} // namespace geos.index.strtree
} // namespace geos.index
} // namespace geos
| 28.436416 | 111 | 0.693566 | [
"geometry",
"vector"
] |
b9f9279d3b4092de5b8f901cff43e5e841fd2035 | 3,154 | cpp | C++ | src/standalone-renderer/main.cpp | shiinamiyuki/MiyukiRenderer | 81f45a86509b0c003ea7fa8c092c5b96b557d6c3 | [
"MIT"
] | 53 | 2019-06-13T12:34:46.000Z | 2019-09-26T02:20:01.000Z | src/standalone-renderer/main.cpp | shiinamiyuki/miyuki-renderer | 81f45a86509b0c003ea7fa8c092c5b96b557d6c3 | [
"MIT"
] | null | null | null | src/standalone-renderer/main.cpp | shiinamiyuki/miyuki-renderer | 81f45a86509b0c003ea7fa8c092c5b96b557d6c3 | [
"MIT"
] | 5 | 2020-01-01T03:05:39.000Z | 2022-01-22T14:38:19.000Z | // MIT License
//
// Copyright (c) 2019 椎名深雪
//
// 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 "../core/export.h"
#include <stdexcept>
#include <iostream>
#include <cxxopts.hpp>
#include <miyuki.foundation/defs.h>
#include <fstream>
#include <miyuki.renderer/graph.h>
#include <miyuki.foundation/log.hpp>
int main(int argc, char **argv) {
using namespace miyuki;
try {
cxxopts::Options options("myk-cli", "miyuki-renderer :: Standalone");
options.add_options()
("f,file", "Scene file name", cxxopts::value<std::string>())
("o,out", "Output image file name", cxxopts::value<std::string>())
("h,help", "Print help and exit.");
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help({""}) << std::endl;
return 0;
}
std::string sceneFile = result["file"].as<std::string>(), outFile = "out.png";
if (result.count("out") != 0) {
outFile = result["out"].as<std::string>();
}
{
CurrentPathGuard _guard;
fs::path scenePath = fs::absolute(fs::path(sceneFile));
if (!fs::exists(scenePath)) {
MIYUKI_THROW(std::runtime_error, "file doesn't exist");
}
fs::path sceneDir = scenePath.parent_path();
fs::current_path(sceneDir);
sceneFile = fs::path(sceneFile).filename().string();
auto ctx = core::Initialize();
std::ifstream in(sceneFile);
std::string str((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
json data = json::parse(str);
auto graph = serialize::fromJson<core::SceneGraph>(*ctx,data);
graph.render(ctx, outFile);
}
return 0;
} catch (std::exception &e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
std::cerr << "Exited." << std::endl;
return -1;
}
} | 40.435897 | 87 | 0.604629 | [
"render"
] |
b9ff17e874b78dad277fc039fbc84cba75dda3f9 | 4,826 | cc | C++ | programl/graph/format/node_link_graph.cc | xshaun/compiler-programl | f90bcd84700d0f245c80440a3d5fd29370d2f973 | [
"Apache-2.0"
] | 1 | 2020-07-14T12:17:45.000Z | 2020-07-14T12:17:45.000Z | programl/graph/format/node_link_graph.cc | island255/ProGraML | 6c4ea50639773009e7c287feb62c6994fa4f3445 | [
"Apache-2.0"
] | null | null | null | programl/graph/format/node_link_graph.cc | island255/ProGraML | 6c4ea50639773009e7c287feb62c6994fa4f3445 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019-2020 the ProGraML authors.
//
// Contact Chris Cummins <chrisc.101@gmail.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "programl/graph/format/node_link_graph.h"
#include "labm8/cpp/logging.h"
#include "labm8/cpp/status.h"
#include "labm8/cpp/status_macros.h"
#include "nlohmann/json.hpp"
#include "programl/proto/program_graph.pb.h"
using json = nlohmann::json;
using labm8::Status;
namespace programl {
namespace graph {
namespace format {
namespace detail {
template <typename T>
[[nodiscard]] Status MaybeAddFeatures(const T& message, json* dict) {
if (message.has_features()) {
auto features = json::object({});
RETURN_IF_ERROR(CreateFeaturesDict(message.features(), &features));
(*dict)["features"] = features;
}
return Status::OK;
}
Status CreateGraphDict(const ProgramGraph& graph, json* graphDict) {
auto functions = json::array({});
for (int i = 0; i < graph.function_size(); ++i) {
const Function& function = graph.function(i);
auto functionDict = json::object({
{"name", function.name()},
{"module", function.module()},
});
RETURN_IF_ERROR(MaybeAddFeatures(function, &functionDict));
functions.push_back(functionDict);
}
(*graphDict)["function"] = functions;
auto modules = json::array({});
for (int i = 0; i < graph.module_size(); ++i) {
const Module& module = graph.module(i);
auto moduleDict = json::object({
{"name", module.name()},
});
RETURN_IF_ERROR(MaybeAddFeatures(module, &moduleDict));
modules.push_back(moduleDict);
}
(*graphDict)["module"] = modules;
RETURN_IF_ERROR(MaybeAddFeatures(graph, graphDict));
return Status::OK;
}
Status CreateNodesList(const ProgramGraph& graph, json* nodes) {
for (int i = 0; i < graph.node_size(); ++i) {
const Node& node = graph.node(i);
// Construct the node dictionary.
auto nodeDict = json::object({
{"id", i},
{"type", node.type()},
{"text", node.text()},
{"function", node.function()},
{"block", node.block()},
});
RETURN_IF_ERROR(MaybeAddFeatures(node, &nodeDict));
nodes->push_back(nodeDict);
}
return Status::OK;
}
Status CreateLinksList(const ProgramGraph& graph, json* edges) {
for (int i = 0; i < graph.edge_size(); ++i) {
const Edge& edge = graph.edge(i);
auto edgeDict = json::object({
{"flow", edge.flow()},
{"position", edge.position()},
{"source", edge.source()},
{"target", edge.target()},
{"key", 0},
});
RETURN_IF_ERROR(MaybeAddFeatures(edge, &edgeDict));
edges->push_back(edgeDict);
}
return Status::OK;
}
Status CreateFeatureArray(const Feature& feature, json* featureArray) {
if (feature.has_bytes_list()) {
for (int i = 0; i < feature.bytes_list().value_size(); ++i) {
featureArray->push_back(feature.bytes_list().value(i));
}
} else if (feature.has_float_list()) {
for (int i = 0; i < feature.float_list().value_size(); ++i) {
featureArray->push_back(feature.float_list().value(i));
}
} else if (feature.has_int64_list()) {
for (int i = 0; i < feature.int64_list().value_size(); ++i) {
featureArray->push_back(feature.int64_list().value(i));
}
} else {
return Status(labm8::error::Code::INTERNAL, "Empty feature");
}
return Status::OK;
}
Status CreateFeaturesDict(const Features& features, json* featuresDict) {
for (const auto& feature : features.feature()) {
auto featureArray = json::array({});
RETURN_IF_ERROR(CreateFeatureArray(feature.second, &featureArray));
featuresDict->push_back({feature.first, featureArray});
}
return Status::OK;
}
} // namespace detail
Status ProgramGraphToNodeLinkGraph(const ProgramGraph& graph, json* dict) {
CHECK(dict) << "nullptr for output argument";
(*dict)["directed"] = true;
(*dict)["multigraph"] = true;
(*dict)["graph"] = json::object();
(*dict)["nodes"] = json::array();
(*dict)["links"] = json::array();
RETURN_IF_ERROR(detail::CreateGraphDict(graph, &(*dict)["graph"]));
RETURN_IF_ERROR(detail::CreateNodesList(graph, &(*dict)["nodes"]));
RETURN_IF_ERROR(detail::CreateLinksList(graph, &(*dict)["links"]));
return Status::OK;
}
} // namespace format
} // namespace graph
} // namespace programl
| 30.738854 | 75 | 0.659552 | [
"object"
] |
6a03c5eab4d89b8e6d77ce4f25c61e85a05619a7 | 10,118 | cpp | C++ | src/add-ons/kernel/drivers/network/usb_asix/Driver.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/add-ons/kernel/drivers/network/usb_asix/Driver.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/add-ons/kernel/drivers/network/usb_asix/Driver.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* ASIX AX88172/AX88772/AX88178 USB 2.0 Ethernet Driver.
* Copyright (c) 2008, 2011 S.Zharski <imker@gmx.li>
* Distributed under the terms of the MIT license.
*
* Heavily based on code of the
* Driver for USB Ethernet Control Model devices
* Copyright (C) 2008 Michael Lotz <mmlr@mlotz.ch>
* Distributed under the terms of the MIT license.
*
*/
#include "Driver.h"
#include <stdio.h>
#include <lock.h> // for mutex
#include <util/AutoLock.h>
#include "AX88172Device.h"
#include "AX88178Device.h"
#include "AX88772Device.h"
#include "Settings.h"
int32 api_version = B_CUR_DRIVER_API_VERSION;
static const char *sDeviceBaseName = "net/usb_asix/";
ASIXDevice *gASIXDevices[MAX_DEVICES];
char *gDeviceNames[MAX_DEVICES + 1];
usb_module_info *gUSBModule = NULL;
mutex gDriverLock;
// IMPORTANT: keep entries sorted by ids to let the
// binary search lookup procedure work correctly !!!
DeviceInfo gSupportedDevices[] = {
{ { 0x0411, 0x003d }, DeviceInfo::AX88172, "Melco LUA-U2-KTX" },
{ { 0x0411, 0x006e }, DeviceInfo::AX88178, "Melco LUA3-U2-AGT" },
{ { 0x04bb, 0x0930 }, DeviceInfo::AX88178, "I/O Data ETG-US2" },
{ { 0x04f1, 0x3008 }, DeviceInfo::AX88172, "JVC MP-PRX1" },
{ { 0x050d, 0x5055 }, DeviceInfo::AX88178, "Belkin F5D5055" },
{ { 0x0557, 0x2009 }, DeviceInfo::AX88172, "ATEN UC-210T" },
{ { 0x05ac, 0x1402 }, DeviceInfo::AX88772, "Apple A1277" },
{ { 0x077b, 0x2226 }, DeviceInfo::AX88172, "LinkSys USB 2.0" },
{ { 0x0789, 0x0160 }, DeviceInfo::AX88178, "Logitec LAN-GTJ/U2A" },
{ { 0x07aa, 0x0017 }, DeviceInfo::AX88172, "Corega USB2TX" },
{ { 0x07b8, 0x420a }, DeviceInfo::AX88172, "ABOCOM UF200" },
{ { 0x07d1, 0x3c05 }, DeviceInfo::AX88772, "D-Link DUB-E100 rev.B1" },
{ { 0x0846, 0x1040 }, DeviceInfo::AX88172, "NetGear USB 2.0 Ethernet" },
{ { 0x086e, 0x1920 }, DeviceInfo::AX88172, "System TALKS SGC-X2UL" },
{ { 0x08dd, 0x90ff }, DeviceInfo::AX88172, "Billionton USB2AR" },
{ { 0x0b95, 0x1720 }, DeviceInfo::AX88172, "ASIX 88172 10/100" },
{ { 0x0b95, 0x1780 }, DeviceInfo::AX88178, "ASIX 88178 10/100/1000" },
{ { 0x0b95, 0x7720 }, DeviceInfo::AX88772, "ASIX 88772 10/100" },
{ { 0x0b95, 0x772a }, DeviceInfo::AX88772A, "AX88772A 10/100" },
{ { 0x0b95, 0x772b }, DeviceInfo::AX88772B, "AX88772B 10/100" },
{ { 0x0b95, 0x7e2b }, DeviceInfo::AX88772B, "AX88772B 10/100" },
{ { 0x0df6, 0x0056 }, DeviceInfo::AX88178, "Sitecom LN-031" },
{ { 0x0df6, 0x061c }, DeviceInfo::AX88178, "Sitecom LN-028" },
{ { 0x1189, 0x0893 }, DeviceInfo::AX88172, "Acer C&M EP-1427X-2" },
{ { 0x13b1, 0x0018 }, DeviceInfo::AX88772A, "Linksys USB200M rev.2" },
{ { 0x14ea, 0xab11 }, DeviceInfo::AX88178, "Planex GU-1000T" },
{ { 0x1557, 0x7720 }, DeviceInfo::AX88772, "OQO 01+ Ethernet" },
{ { 0x1631, 0x6200 }, DeviceInfo::AX88172, "GoodWay USB2Ethernet" },
{ { 0x1737, 0x0039 }, DeviceInfo::AX88178, "LinkSys 1000" },
{ { 0x17ef, 0x7203 }, DeviceInfo::AX88772, "Lenovo U2L100P 10/100" },
{ { 0x2001, 0x1a00 }, DeviceInfo::AX88172, "D-Link DUB-E100" },
{ { 0x2001, 0x1a02 }, DeviceInfo::AX88772B, "D-Link DUB-E100 rev.C1" },
{ { 0x2001, 0x3c05 }, DeviceInfo::AX88772, "D-Link DUB-E100 rev.B1" },
{ { 0x6189, 0x182d }, DeviceInfo::AX88172, "Sitecom LN-029" },
};
ASIXDevice *
lookup_and_create_device(usb_device device)
{
const usb_device_descriptor *deviceDescriptor
= gUSBModule->get_device_descriptor(device);
if (deviceDescriptor == NULL) {
TRACE_ALWAYS("Error of getting USB device descriptor.\n");
return NULL;
}
TRACE("trying %#06x:%#06x.\n",
deviceDescriptor->vendor_id, deviceDescriptor->product_id);
// use binary search to lookup device in table
uint32 id = deviceDescriptor->vendor_id << 16
| deviceDescriptor->product_id;
int left = -1;
int right = B_COUNT_OF(gSupportedDevices);
while ((right - left) > 1) {
int i = (left + right) / 2;
((gSupportedDevices[i].Key() < id) ? left : right) = i;
}
if (gSupportedDevices[right].Key() == id) {
switch (gSupportedDevices[right].fType) {
case DeviceInfo::AX88172:
return new AX88172Device(device, gSupportedDevices[right]);
case DeviceInfo::AX88772:
case DeviceInfo::AX88772A:
case DeviceInfo::AX88772B:
return new AX88772Device(device, gSupportedDevices[right]);
case DeviceInfo::AX88178:
return new AX88178Device(device, gSupportedDevices[right]);
default:
TRACE_ALWAYS("Unknown device type:%#x ignored.\n",
static_cast<int>(gSupportedDevices[right].fType));
break;
}
} else {
TRACE_ALWAYS("Search for %#x failed %d-%d.\n", id, left, right);
}
return NULL;
}
status_t
usb_asix_device_added(usb_device device, void **cookie)
{
*cookie = NULL;
MutexLocker lock(gDriverLock); // released on exit
// check if this is a replug of an existing device first
for (int32 i = 0; i < MAX_DEVICES; i++) {
if (gASIXDevices[i] == NULL)
continue;
if (gASIXDevices[i]->CompareAndReattach(device) != B_OK)
continue;
TRACE("The device is plugged back. Use entry at %ld.\n", i);
*cookie = gASIXDevices[i];
return B_OK;
}
// no such device yet, create a new one
ASIXDevice *asixDevice = lookup_and_create_device(device);
if (asixDevice == 0) {
return ENODEV;
}
status_t status = asixDevice->InitCheck();
if (status < B_OK) {
delete asixDevice;
return status;
}
status = asixDevice->SetupDevice(false);
if (status < B_OK) {
delete asixDevice;
return status;
}
for (int32 i = 0; i < MAX_DEVICES; i++) {
if (gASIXDevices[i] != NULL)
continue;
gASIXDevices[i] = asixDevice;
*cookie = asixDevice;
TRACE("New device is added at %ld.\n", i);
return B_OK;
}
// no space for the device
TRACE_ALWAYS("Error: no more device entries availble.\n");
delete asixDevice;
return B_ERROR;
}
status_t
usb_asix_device_removed(void *cookie)
{
MutexLocker lock(gDriverLock); // released on exit
ASIXDevice *device = (ASIXDevice *)cookie;
for (int32 i = 0; i < MAX_DEVICES; i++) {
if (gASIXDevices[i] == device) {
if (device->IsOpen()) {
// the device will be deleted upon being freed
device->Removed();
} else {
gASIXDevices[i] = NULL;
delete device;
TRACE("Device at %ld deleted.\n", i);
}
break;
}
}
return B_OK;
}
// #pragma mark -
status_t
init_hardware()
{
return B_OK;
}
status_t
init_driver()
{
status_t status = get_module(B_USB_MODULE_NAME,
(module_info **)&gUSBModule);
if (status < B_OK)
return status;
load_settings();
TRACE_ALWAYS("%s\n", kVersion);
for (int32 i = 0; i < MAX_DEVICES; i++)
gASIXDevices[i] = NULL;
gDeviceNames[0] = NULL;
mutex_init(&gDriverLock, DRIVER_NAME"_devices");
static usb_notify_hooks notifyHooks = {
&usb_asix_device_added,
&usb_asix_device_removed
};
const size_t count = B_COUNT_OF(gSupportedDevices);
static usb_support_descriptor sDescriptors[count] = {{ 0 }};
for (size_t i = 0; i < count; i++) {
sDescriptors[i].vendor = gSupportedDevices[i].VendorId();
sDescriptors[i].product = gSupportedDevices[i].ProductId();
}
gUSBModule->register_driver(DRIVER_NAME, sDescriptors, count, NULL);
gUSBModule->install_notify(DRIVER_NAME, ¬ifyHooks);
return B_OK;
}
void
uninit_driver()
{
gUSBModule->uninstall_notify(DRIVER_NAME);
mutex_lock(&gDriverLock);
for (int32 i = 0; i < MAX_DEVICES; i++) {
if (gASIXDevices[i]) {
delete gASIXDevices[i];
gASIXDevices[i] = NULL;
}
}
for (int32 i = 0; gDeviceNames[i]; i++) {
free(gDeviceNames[i]);
gDeviceNames[i] = NULL;
}
mutex_destroy(&gDriverLock);
put_module(B_USB_MODULE_NAME);
release_settings();
}
static status_t
usb_asix_open(const char *name, uint32 flags, void **cookie)
{
MutexLocker lock(gDriverLock); // released on exit
*cookie = NULL;
status_t status = ENODEV;
int32 index = strtol(name + strlen(sDeviceBaseName), NULL, 10);
if (index >= 0 && index < MAX_DEVICES && gASIXDevices[index]) {
status = gASIXDevices[index]->Open(flags);
*cookie = gASIXDevices[index];
}
return status;
}
static status_t
usb_asix_read(void *cookie, off_t position, void *buffer, size_t *numBytes)
{
ASIXDevice *device = (ASIXDevice *)cookie;
return device->Read((uint8 *)buffer, numBytes);
}
static status_t
usb_asix_write(void *cookie, off_t position, const void *buffer,
size_t *numBytes)
{
ASIXDevice *device = (ASIXDevice *)cookie;
return device->Write((const uint8 *)buffer, numBytes);
}
static status_t
usb_asix_control(void *cookie, uint32 op, void *buffer, size_t length)
{
ASIXDevice *device = (ASIXDevice *)cookie;
return device->Control(op, buffer, length);
}
static status_t
usb_asix_close(void *cookie)
{
ASIXDevice *device = (ASIXDevice *)cookie;
return device->Close();
}
static status_t
usb_asix_free(void *cookie)
{
ASIXDevice *device = (ASIXDevice *)cookie;
MutexLocker lock(gDriverLock); // released on exit
status_t status = device->Free();
for (int32 i = 0; i < MAX_DEVICES; i++) {
if (gASIXDevices[i] == device) {
// the device is removed already but as it was open the
// removed hook has not deleted the object
gASIXDevices[i] = NULL;
delete device;
TRACE("Device at %ld deleted.\n", i);
break;
}
}
return status;
}
const char **
publish_devices()
{
for (int32 i = 0; gDeviceNames[i]; i++) {
free(gDeviceNames[i]);
gDeviceNames[i] = NULL;
}
MutexLocker lock(gDriverLock); // released on exit
int32 deviceCount = 0;
for (int32 i = 0; i < MAX_DEVICES; i++) {
if (gASIXDevices[i] == NULL)
continue;
gDeviceNames[deviceCount] = (char *)malloc(strlen(sDeviceBaseName) + 4);
if (gDeviceNames[deviceCount]) {
sprintf(gDeviceNames[deviceCount], "%s%" B_PRId32, sDeviceBaseName,
i);
TRACE("publishing %s\n", gDeviceNames[deviceCount]);
deviceCount++;
} else
TRACE_ALWAYS("Error: out of memory during allocating dev.name.\n");
}
gDeviceNames[deviceCount] = NULL;
return (const char **)&gDeviceNames[0];
}
device_hooks *
find_device(const char *name)
{
static device_hooks deviceHooks = {
usb_asix_open,
usb_asix_close,
usb_asix_free,
usb_asix_control,
usb_asix_read,
usb_asix_write,
NULL, /* select */
NULL /* deselect */
};
return &deviceHooks;
}
| 25.61519 | 75 | 0.684127 | [
"object",
"model"
] |
6a040ce6d387446c2b892d6927810f3e1813d7ca | 5,122 | cpp | C++ | Terminal/Terminal.Draw.cpp | PierceLBrooks/Terminal | d29bcd031417b5b1dcb9893ead84e15dad7dfd08 | [
"MIT"
] | 2 | 2021-11-07T04:14:08.000Z | 2022-03-08T02:44:37.000Z | Terminal/Terminal.Draw.cpp | PierceLBrooks/Terminal | d29bcd031417b5b1dcb9893ead84e15dad7dfd08 | [
"MIT"
] | null | null | null | Terminal/Terminal.Draw.cpp | PierceLBrooks/Terminal | d29bcd031417b5b1dcb9893ead84e15dad7dfd08 | [
"MIT"
] | 1 | 2022-03-08T16:56:25.000Z | 2022-03-08T16:56:25.000Z |
#include "Terminal.hpp"
#include "vterm/vterm.h"
#include <cmath>
using namespace std;
using namespace sf;
namespace {
Color reverseOf(Color col) {
return Color(255 - col.r, 255 - col.g, 255 - col.b, col.a);
}
void reverse(Color& col) {
col.r = 255 - col.r;
col.g = 255 - col.g;
col.b = 255 - col.b;
}
inline void pushQuadVertex(vector<Vertex>& arr, const Vertex& a, const Vertex& b, const Vertex& c, const Vertex& d) {
arr.push_back(a);
arr.push_back(b);
arr.push_back(c);
arr.push_back(b);
arr.push_back(c);
arr.push_back(d);
}
inline void pushVertexColor(vector<Vertex>& arr, FloatRect rect, Color color) {
pushQuadVertex(arr,
Vertex(Vector2f(rect.left, rect.top), color, Vector2f(1, 1)),
Vertex(Vector2f(rect.left + rect.width, rect.top), color, Vector2f(1, 1)),
Vertex(Vector2f(rect.left, rect.top + rect.height), color, Vector2f(1, 1)),
Vertex(Vector2f(rect.left + rect.width, rect.top + rect.height), color, Vector2f(1, 1)));
}
inline void pushVertexTextureColor(vector<Vertex>& arr, FloatRect rect, IntRect texRect, Color color) {
pushQuadVertex(arr,
Vertex(Vector2f(rect.left, rect.top), color, Vector2f(texRect.left, texRect.top)),
Vertex(Vector2f(rect.left + rect.width, rect.top), color, Vector2f(texRect.left + texRect.width, texRect.top)),
Vertex(Vector2f(rect.left, rect.top + rect.height), color, Vector2f(texRect.left, texRect.top + texRect.height)),
Vertex(Vector2f(rect.left + rect.width, rect.top + rect.height), color, Vector2f(texRect.left + texRect.width, texRect.top + texRect.height)));
}
}
bool Terminal::redrawIfRequired(Font& font, vector<Vertex>& target, Color bgColor) {
if (needRedraw) {
needRedraw = false;
forceRedraw(font, target, bgColor);
return true;
} else
return false;
}
void Terminal::forceRedraw(Font& font, vector<Vertex>& target, Color bgColor) {
if (charTopOffset == -4096) {
// Guess the character centering offset
// Let's use the pipe character '|' as a reference
Glyph g = font.getGlyph('|', charSize, false, 0);
charTopOffset = (cellSize.y - g.bounds.height) / 2.0f + (g.bounds.height + g.bounds.top);
}
target.clear();
if (bgColor != Color::Black)
pushVertexColor(target, FloatRect(0, 0, (cols + 1) * cellSize.x, (rows + 1) * cellSize.y), bgColor);
VTermPos curpos;
VTermScreen* scr = vterm_obtain_screen(term);
vterm_state_get_cursorpos(vterm_obtain_state(term), &curpos);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
VTermScreenCell cell;
if (altScreen) {
if (!vterm_screen_get_cell(scr, VTermPos{ i, j }, &cell))
continue;
} else {
if (i < scrollbackOffset) {
auto& line = scrollback[scrollback.size() - scrollbackOffset + i];
if (j < line.size())
cell = line[j];
else
continue;
} else if (!vterm_screen_get_cell(scr, VTermPos{ i - scrollbackOffset, j }, &cell))
continue;
}
vterm_state_convert_color_to_rgb(vterm_obtain_state(term), &cell.fg);
vterm_state_convert_color_to_rgb(vterm_obtain_state(term), &cell.bg);
FloatRect cellRect(j * cellSize.x, i * cellSize.y, cellSize.x * cell.width, cellSize.y);
Color bg(cell.bg.rgb.red, cell.bg.rgb.green, cell.bg.rgb.blue);
Color fg(cell.fg.rgb.red, cell.fg.rgb.green, cell.fg.rgb.blue);
if (cell.attrs.reverse)
swap(bg, fg);
// Draw the cursor
if (cursorVisible && curpos.row == i - scrollbackOffset && curpos.col == j) {
float thick = font.getUnderlineThickness(charSize);
switch (cursorShape) {
case VTERM_PROP_CURSORSHAPE_BLOCK:
reverse(bg);
reverse(fg);
break;
case VTERM_PROP_CURSORSHAPE_BAR_LEFT:
pushVertexColor(target, FloatRect(cellRect.left, cellRect.top, thick, cellRect.height), reverseOf(bg));
break;
case VTERM_PROP_CURSORSHAPE_UNDERLINE:
pushVertexColor(target, FloatRect(cellRect.left, cellRect.top + cellRect.height - 1 - thick, cellRect.width, thick), reverseOf(bg));
break;
}
}
if (bg != Color::Black)
pushVertexColor(target, cellRect, bg);
if (cell.attrs.underline) {
float thick = font.getUnderlineThickness(charSize);
pushVertexColor(target, FloatRect(cellRect.left, cellRect.top + cellRect.height - 1 - thick, cellRect.width, thick), fg);
}
if (cell.attrs.strike) { // I'm too lazy to somehow get the strikeline position
float thick = font.getUnderlineThickness(charSize);
pushVertexColor(target, FloatRect(cellRect.left, roundf(cellRect.top + cellRect.height * 0.6f - thick / 2.0f), cellRect.width, thick), fg);
}
if (cell.chars[0] && cell.chars[0] != ' ') {
Glyph glyph = font.getGlyph(cell.chars[0], charSize, hasBold && cell.attrs.bold, 0.0F);
FloatRect renderRect;
renderRect.left = roundf(j * cellSize.x + (cellSize.x * cell.width - glyph.advance) / 2.0f + glyph.bounds.left);
renderRect.width = glyph.bounds.width;
renderRect.top = roundf((i + 1) * cellSize.y + glyph.bounds.top - charTopOffset);
renderRect.height = glyph.bounds.height;
pushVertexTextureColor(target, renderRect, glyph.textureRect, fg);
}
j += cell.width - 1;
}
}
| 34.375839 | 146 | 0.681179 | [
"vector"
] |
6a0bd79bd94332c8f5a236476be588c8abf0e7f2 | 3,067 | cpp | C++ | private/shell/browseui/mbdrop.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/browseui/mbdrop.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/browseui/mbdrop.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | //
// Routines for implementing drop target capability to menubands.
//
#include "priv.h"
#include "mbdrop.h"
#include "iface.h" // for MBIF_
#define SUPERCLASS
//=================================================================
// Implementation of CMenuBandDropTarget
//=================================================================
// Constructor
CMenuBandDropTarget::CMenuBandDropTarget(HWND hwnd, int idTarget, DWORD dwFlags) :
_cRef(1), _hwndParent(hwnd), _idTarget(idTarget), _dwFlagsMBIF(dwFlags)
{
}
STDMETHODIMP_(ULONG) CMenuBandDropTarget::AddRef()
{
_cRef++;
return _cRef;
}
STDMETHODIMP_(ULONG) CMenuBandDropTarget::Release()
{
ASSERT(_cRef > 0);
_cRef--;
if (_cRef > 0)
return _cRef;
delete this;
return 0;
}
STDMETHODIMP CMenuBandDropTarget::QueryInterface(REFIID riid, void **ppvObj)
{
HRESULT hres;
static const QITAB qit[] = {
QITABENT(CMenuBandDropTarget, IDropTarget),
{ 0 },
};
hres = QISearch(this, (LPCQITAB)qit, riid, ppvObj);
return hres;
}
/*----------------------------------------------------------
Purpose: IDropTarget::DragEnter method
*/
STDMETHODIMP CMenuBandDropTarget::DragEnter(IDataObject * pdtobj, DWORD grfKeyState,
POINTL pt, DWORD * pdwEffect)
{
// If this item cascades out, then we want to pop the submenu open
// after a timer. We don't allow a drop on the cascadable item
// itself. (We could, but then we'd have to default to a location
// inside the submenu, and I'm lazy right now.)
if (*pdwEffect & (DROPEFFECT_MOVE | DROPEFFECT_COPY))
{
if (_dwFlagsMBIF & SMIF_SUBMENU)
{
// _idTimer = SetTimer(NULL, 0, 2000,
}
*pdwEffect &= (DROPEFFECT_MOVE | DROPEFFECT_COPY);
}
else
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
/*----------------------------------------------------------
Purpose: IDropTarget::DragOver method
*/
STDMETHODIMP CMenuBandDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD * pdwEffect)
{
*pdwEffect &= (DROPEFFECT_MOVE | DROPEFFECT_COPY);
return S_OK;
}
/*----------------------------------------------------------
Purpose: IDropTarget::DragLeave method
*/
STDMETHODIMP CMenuBandDropTarget::DragLeave(void)
{
// Kill timer, release object
return S_OK;
}
/*----------------------------------------------------------
Purpose: IDropTarget::Drop method
*/
STDMETHODIMP CMenuBandDropTarget::Drop(IDataObject * pdtobj, DWORD grfKeyState, POINTL pt,
DWORD * pdwEffect)
{
if (*pdwEffect & (DROPEFFECT_MOVE | DROPEFFECT_COPY))
{
if (_dwFlagsMBIF & SMIF_SUBMENU)
{
// We don't allow drops on submenu items. Must go into
// cascaded menu.
*pdwEffect = DROPEFFECT_NONE;
}
}
return S_OK;
}
| 24.34127 | 92 | 0.533746 | [
"object"
] |
6a1382604c020c9d6896c6b3ab840554feefa1be | 2,443 | cc | C++ | leetcode/src/text_justification.cc | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 5 | 2016-04-29T07:14:23.000Z | 2020-01-07T04:56:11.000Z | leetcode/src/text_justification.cc | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | null | null | null | leetcode/src/text_justification.cc | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 1 | 2016-04-29T07:14:32.000Z | 2016-04-29T07:14:32.000Z | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> lv;
lv.clear();
vector<string> ans;
ans.clear();
int l_cnt = 0;
for (int i=0; i<words.size(); ) {
if (l_cnt+words[i].length()+(l_cnt!=0) > L) {
string tar = "";
if (l_cnt == L) {
for (auto str : lv) {
if (tar != "")
tar = tar+" ";
tar = tar+str;
}
} else {
if (lv.size() == 1) {
tar = lv[0];
for (int j=tar.length(); j<L; j++)
tar = tar+" ";
} else {
int tmp = (L-l_cnt)/(lv.size()-1);
int tmp_r = (L-l_cnt)%(lv.size()-1);
for (auto str : lv) {
if (tar != "") {
tar = tar+" ";
for (int j=0; j<tmp; j++)
tar = tar+" ";
if (tmp_r)
tar = tar+" ", tmp_r--;
}
tar = tar+str;
}
}
}
l_cnt = 0;
ans.push_back(tar);
lv.clear();
} else {
if (l_cnt)
l_cnt++;
l_cnt = l_cnt+words[i].length();
lv.push_back(words[i]);
i++;
}
}
if (!lv.empty()) {
string tar = "";
for (auto str : lv) {
if (tar != "")
tar = tar+" ";
tar = tar+str;
}
for (int i=tar.length(); i<L; i++)
tar = tar+" ";
ans.push_back(tar);
}
return ans;
}
};
int main() {
string strs[7] = {
//"This", "is", "an", "example", "of", "text", "justification."
"Listen","to","many,","speak","to","a","few."
};
vector<string> tv(strs, strs+7);
tv = Solution().fullJustify(tv, 6);
for (auto i : tv) {
cout<<"\""<<i<<"\""<<endl;
}
}
| 29.083333 | 67 | 0.306181 | [
"vector"
] |
6a1a61f7e3124dd98f728cd34528112a84061a36 | 1,834 | cpp | C++ | source/TestHarness/TestProfileLibrary.cpp | easmith14/cse687-group1 | 48de6502c0bcc76f5269fdab8b8d1f2378f75a1e | [
"MIT"
] | 2 | 2021-04-15T22:57:53.000Z | 2021-04-27T02:13:55.000Z | source/TestHarness/TestProfileLibrary.cpp | easmith14/cse687-group1 | 48de6502c0bcc76f5269fdab8b8d1f2378f75a1e | [
"MIT"
] | null | null | null | source/TestHarness/TestProfileLibrary.cpp | easmith14/cse687-group1 | 48de6502c0bcc76f5269fdab8b8d1f2378f75a1e | [
"MIT"
] | 1 | 2021-04-15T22:58:35.000Z | 2021-04-15T22:58:35.000Z | /*
CSE687 - Object Oriented Design
Syracuse University
///////////////////////////////////////////////////////////
// Final Project by Aaron Mendelsohn, Evan Smith, Stephen Woodward, Mike Rice
///////////////////////////////////////////////////////////
5/13/2021
*/
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include "TestProfileLibrary.h"
#include "UserPrompter.h"
#include "CelestialBody.h"
#include "Spacecraft.h"
#include "GaseousCloud.h"
#include <Windows.h>
#include <tchar.h>
#include <experimental/filesystem>
namespace ns = std::experimental::filesystem;
using std::cout;
using std::cin;
//constructor
TestProfileLibrary::TestProfileLibrary()
{
//cout << "TestProfileLibrary created\n";
}
//destructor
TestProfileLibrary::~TestProfileLibrary()
{
}
//TODO: change this to grab the names of the available dlls and return a vector<string>
vector<string> get_filenames(std::experimental::filesystem::path path)
{
namespace stdfs = std::experimental::filesystem;
std::vector<std::string> filenames;
// http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator
const stdfs::directory_iterator end{};
for (stdfs::directory_iterator iter{ path }; iter != end; ++iter)
{
// http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file
if (stdfs::is_regular_file(*iter))
{
if (iter->path().extension().string() == ".dll")
{
filenames.push_back(iter->path().filename().string());
}
}
}
return filenames;
}
//instantiates objects and returns vector of created objects
vector<string> TestProfileLibrary::GetTestList()
{
const char* relPath = "..\\DLLs";
char buf[200];
string path = _fullpath(buf, relPath, 200);
return get_filenames(path);
}
| 24.453333 | 87 | 0.642857 | [
"object",
"vector"
] |
6a1c0111b3575b546d1d4f6dd2d7741809171bab | 2,332 | hpp | C++ | agency/execution/execution_agent/detail/basic_execution_agent.hpp | ccecka/agency | 729f5346e842c9cef3ad6f34d18d17a96a001a75 | [
"BSD-3-Clause"
] | null | null | null | agency/execution/execution_agent/detail/basic_execution_agent.hpp | ccecka/agency | 729f5346e842c9cef3ad6f34d18d17a96a001a75 | [
"BSD-3-Clause"
] | null | null | null | agency/execution/execution_agent/detail/basic_execution_agent.hpp | ccecka/agency | 729f5346e842c9cef3ad6f34d18d17a96a001a75 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <agency/detail/config.hpp>
#include <agency/coordinate/lattice.hpp>
#include <agency/detail/index_lexicographical_rank.hpp>
#include <agency/execution/execution_agent/execution_agent_traits.hpp>
#include <agency/execution/executor/properties/bulk_guarantee.hpp>
#include <utility>
namespace agency
{
namespace detail
{
template<class ExecutionRequirement, class Index = size_t>
class basic_execution_agent
{
public:
using execution_requirement = ExecutionRequirement;
using index_type = Index;
__AGENCY_ANNOTATION
index_type index() const
{
return index_;
}
using domain_type = lattice<index_type>;
__AGENCY_ANNOTATION
const domain_type& domain() const
{
return domain_;
}
using size_type = decltype(std::declval<domain_type>().size());
__AGENCY_ANNOTATION
size_type group_size() const
{
return domain().size();
}
__AGENCY_ANNOTATION
auto group_shape() const
-> decltype(this->domain().shape())
{
return domain().shape();
}
__AGENCY_ANNOTATION
size_type rank() const
{
return agency::detail::index_lexicographical_rank(index(), group_shape());
}
__AGENCY_ANNOTATION
bool elect() const
{
return rank() == 0;
}
class param_type
{
public:
param_type() = default;
param_type(const param_type& other) = default;
__AGENCY_ANNOTATION
param_type(const domain_type& d)
: domain_(d)
{}
__AGENCY_ANNOTATION
param_type(const index_type& min, const index_type& max)
: param_type(domain_type(min,max))
{}
__AGENCY_ANNOTATION
const domain_type& domain() const
{
return domain_;
}
private:
domain_type domain_;
};
__AGENCY_ANNOTATION
static domain_type domain(const param_type& p)
{
return p.domain();
}
protected:
__agency_exec_check_disable__
__AGENCY_ANNOTATION
basic_execution_agent(const index_type& index, const param_type& param) : index_(index), domain_(param.domain()) {}
friend struct agency::execution_agent_traits<basic_execution_agent>;
private:
index_type index_;
domain_type domain_;
};
} // end detail
} // end agency
| 20.103448 | 119 | 0.660806 | [
"shape"
] |
6a1e51104f937fb7b2f50c2232b26793aef138b0 | 3,344 | cpp | C++ | SpaceShooter/src/Game/UI/Widget.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/UI/Widget.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/UI/Widget.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | #include "../../Engine/Audio/Audiosource.h"
#include "../Components/CAnimation.h"
#include "../../Engine/Renderer.h"
#include "../../Engine/Image.h"
#include "../../Engine/Math.h"
#include "Widget.h"
Ptr<Widget> Widget::Create()
{
Ptr<Widget> p = new Widget();
p->mThis = p;
return p;
}
Ptr<Widget> Widget::Create(const int ID, const Transform2D& Tranform2D)
{
Ptr<Widget> p = new Widget(ID, Tranform2D);
p->mThis = p;
return p;
}
Widget::Widget()
{
mID = -1;
mParentWidget = nullptr;
mThis = nullptr;
mTransform = Transform2D();
mAnimationComp = nullptr;
}
Widget::Widget(const int ID, const Transform2D& Tranform2D)
{
mID = ID;
mParentWidget = nullptr;
mThis = nullptr;
mTransform = Tranform2D;
mAnimationComp = nullptr;
}
Widget::~Widget()
{
DeleteAllChildrenWidgets();
mThis = nullptr;
mParentWidget = nullptr;
mAnimationComp = nullptr;
}
void Widget::Init()
{
// Adjust transform relative to parent Widget
if (mParentWidget != nullptr)
{
// Position
mTransform.Position.x += mParentWidget->GetPosition().x;
mTransform.Position.y += mParentWidget->GetPosition().y;
// Rotation
mTransform.Rotation = WrapValue(mTransform.Rotation + mParentWidget->GetRotation(), 360);
// Scale
mTransform.Scale.x *= mParentWidget->GetScale().x;
mTransform.Scale.y *= mParentWidget->GetScale().y;
}
size_t Size = mChildrenWidgets.size();
for (uint32 i = 0; i < Size; ++i)
{
if (mChildrenWidgets[i] != nullptr)
mChildrenWidgets[i]->Init();
}
if (mAnimationComp != nullptr)
mAnimationComp->Init();
}
void Widget::Update(float Elapsed)
{
size_t Size = mChildrenWidgets.size();
for (uint32 i = 0; i < Size; ++i)
{
if (mChildrenWidgets[i] != nullptr)
mChildrenWidgets[i]->Update(Elapsed);
}
if (mAnimationComp != nullptr)
{
mAnimationComp->Update(Elapsed);
}
}
void Widget::Render()
{
if (mAnimationComp != nullptr && mAnimationComp->GetCurrentImage() != nullptr)
{
Renderer::Instance()->SetColor(255, 255, 255, 255);
Renderer::Instance()->SetBlendMode(Renderer::ALPHA);
Renderer::Instance()->DrawImage(mAnimationComp->GetCurrentImage(), GetPosition().x, GetPosition().y, 0, mAnimationComp->GetCurrentImage()->GetWidth()*GetScale().x, mAnimationComp->GetCurrentImage()->GetHeight()*GetScale().y, GetRotation() + mAnimationComp->GetCurrentImage()->GetFixImageRotation());
}
size_t Size = mChildrenWidgets.size();
for (uint32 i = 0; i < Size; ++i)
{
if (mChildrenWidgets[i] != nullptr)
mChildrenWidgets[i]->Render();
}
}
void Widget::AddAnimationComponent(Ptr<CAnimation> _Component)
{
if (_Component != nullptr)
mAnimationComp = _Component;
}
void Widget::AddChildWidget(Ptr<Widget> ChildWidget)
{
if (ChildWidget != nullptr)
{
mChildrenWidgets.push_back(ChildWidget);
ChildWidget->SetParentWidget(mThis);
}
}
void Widget::DeleteAllChildrenWidgets()
{
size_t Size = mChildrenWidgets.size();
for (uint32 i = 0; i < Size; ++i)
{
mChildrenWidgets[i] = nullptr;
}
mChildrenWidgets.clear();
} | 26.125 | 307 | 0.619318 | [
"render",
"transform"
] |
6a2421c352255ed61229a477ef3ca72bfb20c5e2 | 213 | hpp | C++ | include/PascalTriangle.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | include/PascalTriangle.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | include/PascalTriangle.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #ifndef PASCAL_TRIANGLE_HPP_
#define PASCAL_TRIANGLE_HPP_
#include <vector>
using namespace std;
class PascalTriangle {
public:
vector<vector<int>> generate(int numRows);
};
#endif // PASCAL_TRIANGLE_HPP_
| 15.214286 | 46 | 0.774648 | [
"vector"
] |
6a285419f73b87f2be7d2c1c5fd55a54453ab8b5 | 1,050 | cpp | C++ | solutions/merge_intervals.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/merge_intervals.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/merge_intervals.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | // Given a collection of intervals, merge all overlapping intervals.
// Example 1:
// Input: [[1,3],[2,6],[8,10],[15,18]]
// Output: [[1,6],[8,10],[15,18]]
// Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
// Example 2:
// Input: [[1,4],[4,5]]
// Output: [[1,5]]
// Explanation: Intervals [1,4] and [4,5] are considered overlapping.
// NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
// solution: sorting or hashmap
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& itv) {
vector<vector<int>> res;
if (itv.size() == 0) return res;
sort(itv.begin(), itv.end(), [](vector<int>& a, vector<int>& b) {return a[0] < b[0];});
res.push_back(itv[0]);
for (auto e : itv) {
if (e[0] > res.back()[1]) {
res.push_back(e);
} else {
res.back()[1] = max(e[1], res.back()[1]);
}
}
return res;
}
}; | 28.378378 | 126 | 0.548571 | [
"vector"
] |
6a295865f52c11789ed963501b86f380783f088d | 4,265 | cpp | C++ | routing/leaps_graph.cpp | vicpopov/omim | 664b458998fb0f2405f68ae830c2798e027b2dcc | [
"Apache-2.0"
] | null | null | null | routing/leaps_graph.cpp | vicpopov/omim | 664b458998fb0f2405f68ae830c2798e027b2dcc | [
"Apache-2.0"
] | null | null | null | routing/leaps_graph.cpp | vicpopov/omim | 664b458998fb0f2405f68ae830c2798e027b2dcc | [
"Apache-2.0"
] | null | null | null | #include "routing/leaps_graph.hpp"
#include "base/assert.hpp"
#include <set>
#include <utility>
namespace routing
{
LeapsGraph::LeapsGraph(IndexGraphStarter & starter, MwmHierarchyHandler && hierarchyHandler)
: m_starter(starter), m_hierarchyHandler(std::move(hierarchyHandler))
{
m_startPoint = m_starter.GetPoint(m_starter.GetStartSegment(), true /* front */);
m_finishPoint = m_starter.GetPoint(m_starter.GetFinishSegment(), true /* front */);
m_startSegment = m_starter.GetStartSegment();
m_finishSegment = m_starter.GetFinishSegment();
}
void LeapsGraph::GetOutgoingEdgesList(astar::VertexData<Vertex, Weight> const & vertexData,
std::vector<SegmentEdge> & edges)
{
GetEdgesList(vertexData.m_vertex, true /* isOutgoing */, edges);
}
void LeapsGraph::GetIngoingEdgesList(astar::VertexData<Vertex, Weight> const & vertexData,
std::vector<SegmentEdge> & edges)
{
GetEdgesList(vertexData.m_vertex, false /* isOutgoing */, edges);
}
RouteWeight LeapsGraph::HeuristicCostEstimate(Segment const & from, Segment const & to)
{
ASSERT(to == m_startSegment || to == m_finishSegment, ());
bool const toFinish = to == m_finishSegment;
auto const & toPoint = toFinish ? m_finishPoint : m_startPoint;
return m_starter.HeuristicCostEstimate(from, toPoint);
}
void LeapsGraph::GetEdgesList(Segment const & segment, bool isOutgoing,
std::vector<SegmentEdge> & edges)
{
edges.clear();
if (segment == m_startSegment)
{
CHECK(isOutgoing, ("Only forward wave of A* should get edges from start. Backward wave should "
"stop when first time visit the |m_startSegment|."));
return GetEdgesListFromStart(segment, edges);
}
if (segment == m_finishSegment)
{
CHECK(!isOutgoing, ("Only backward wave of A* should get edges to finish. Forward wave should "
"stop when first time visit the |m_finishSegment|."));
return GetEdgesListToFinish(segment, edges);
}
if (!m_starter.IsRoutingOptionsGood(segment))
return;
auto & crossMwmGraph = m_starter.GetGraph().GetCrossMwmGraph();
if (crossMwmGraph.IsTransition(segment, isOutgoing))
{
auto const segMwmId = segment.GetMwmId();
std::vector<Segment> twins;
m_starter.GetGraph().GetTwinsInner(segment, isOutgoing, twins);
for (auto const & twin : twins)
edges.emplace_back(twin, m_hierarchyHandler.GetCrossBorderPenalty(segMwmId, twin.GetMwmId()));
return;
}
if (isOutgoing)
crossMwmGraph.GetOutgoingEdgeList(segment, edges);
else
crossMwmGraph.GetIngoingEdgeList(segment, edges);
}
void LeapsGraph::GetEdgesListFromStart(Segment const & segment, std::vector<SegmentEdge> & edges)
{
for (auto const mwmId : m_starter.GetStartEnding().m_mwmIds)
{
// Connect start to all exits (|isEnter| == false).
auto const & exits = m_starter.GetGraph().GetTransitions(mwmId, false /* isEnter */);
for (auto const & exit : exits)
{
auto const & exitFrontPoint = m_starter.GetPoint(exit, true /* front */);
auto const weight = m_starter.GetGraph().CalcLeapWeight(m_startPoint, exitFrontPoint);
edges.emplace_back(exit, weight);
}
}
}
void LeapsGraph::GetEdgesListToFinish(Segment const & segment, std::vector<SegmentEdge> & edges)
{
for (auto const mwmId : m_starter.GetFinishEnding().m_mwmIds)
{
// Connect finish to all enters (|isEnter| == true).
auto const & enters = m_starter.GetGraph().GetTransitions(mwmId, true /* isEnter */);
for (auto const & enter : enters)
{
auto const & enterFrontPoint = m_starter.GetPoint(enter, true /* front */);
auto const weight = m_starter.GetGraph().CalcLeapWeight(enterFrontPoint, m_finishPoint);
edges.emplace_back(enter, weight);
}
}
}
ms::LatLon const & LeapsGraph::GetPoint(Segment const & segment, bool front) const
{
return m_starter.GetPoint(segment, front);
}
Segment const & LeapsGraph::GetStartSegment() const
{
return m_startSegment;
}
Segment const & LeapsGraph::GetFinishSegment() const
{
return m_finishSegment;
}
RouteWeight LeapsGraph::GetAStarWeightEpsilon()
{
return m_starter.GetAStarWeightEpsilon();
}
} // namespace routing
| 32.067669 | 100 | 0.699883 | [
"vector"
] |
6a2b22b793d0938fa26a86342036679fae14791b | 11,925 | hpp | C++ | Cbc/CoinUtils/src/CoinDenseVector.hpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/CoinUtils/src/CoinDenseVector.hpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/CoinUtils/src/CoinDenseVector.hpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | /* $Id: CoinDenseVector.hpp 2083 2019-01-06 19:38:09Z unxusr $ */
// Copyright (C) 2003, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef CoinDenseVector_H
#define CoinDenseVector_H
#if defined(_MSC_VER)
// Turn off compiler warning about long names
#pragma warning(disable : 4786)
#endif
#include <cassert>
#include <cstdlib>
#include <cmath>
#include "CoinHelperFunctions.hpp"
//#############################################################################
/** A function that tests the methods in the CoinDenseVector class. The
only reason for it not to be a member method is that this way it doesn't
have to be compiled into the library. And that's a gain, because the
library should be compiled with optimization on, but this method should be
compiled with debugging. */
template < typename T >
void CoinDenseVectorUnitTest(T dummy);
//#############################################################################
/** Dense Vector
Stores a dense (or expanded) vector of floating point values.
Type of vector elements is controlled by templating.
(Some working quantities such as accumulated sums
are explicitly declared of type double). This allows the
components of the vector integer, single or double precision.
Here is a sample usage:
@verbatim
const int ne = 4;
double el[ne] = { 10., 40., 1., 50. }
// Create vector and set its value
CoinDenseVector<double> r(ne,el);
// access each element
assert( r.getElements()[0]==10. );
assert( r.getElements()[1]==40. );
assert( r.getElements()[2]== 1. );
assert( r.getElements()[3]==50. );
// Test for equality
CoinDenseVector<double> r1;
r1=r;
// Add dense vectors.
// Similarly for subtraction, multiplication,
// and division.
CoinDenseVector<double> add = r + r1;
assert( add[0] == 10.+10. );
assert( add[1] == 40.+40. );
assert( add[2] == 1.+ 1. );
assert( add[3] == 50.+50. );
assert( r.sum() == 10.+40.+1.+50. );
@endverbatim
*/
template < typename T >
class CoinDenseVector {
private:
/**@name Private member data */
//@{
/// Size of element vector
int nElements_;
///Vector elements
T *elements_;
//@}
public:
/**@name Get methods. */
//@{
/// Get the size
inline int getNumElements() const { return nElements_; }
inline int size() const { return nElements_; }
/// Get element values
inline const T *getElements() const { return elements_; }
/// Get element values
inline T *getElements() { return elements_; }
//@}
//-------------------------------------------------------------------
// Set indices and elements
//-------------------------------------------------------------------
/**@name Set methods */
//@{
/// Reset the vector (i.e. set all elemenets to zero)
void clear();
/** Assignment operator */
CoinDenseVector &operator=(const CoinDenseVector &);
/** Member of array operator */
T &operator[](int index) const;
/** Set vector size, and elements.
Size is the length of the elements vector.
The element vector is copied into this class instance's
member data. */
void setVector(int size, const T *elems);
/** Elements set to have the same scalar value */
void setConstant(int size, T elems);
/** Set an existing element in the dense vector
The first argument is the "index" into the elements() array
*/
void setElement(int index, T element);
/** Resize the dense vector to be the first newSize elements.
If length is decreased, vector is truncated. If increased
new entries, set to new default element */
void resize(int newSize, T fill = T());
/** Append a dense vector to this dense vector */
void append(const CoinDenseVector &);
//@}
/**@name norms, sum and scale */
//@{
/// 1-norm of vector
inline T oneNorm() const
{
T norm = 0;
for (int i = 0; i < nElements_; i++)
norm += CoinAbs(elements_[i]);
return norm;
}
/// 2-norm of vector
inline double twoNorm() const
{
double norm = 0.;
for (int i = 0; i < nElements_; i++)
norm += elements_[i] * elements_[i];
// std namespace removed because it was causing a compile
// problem with Microsoft Visual C++
return /*std::*/ sqrt(norm);
}
/// infinity-norm of vector
inline T infNorm() const
{
T norm = 0;
for (int i = 0; i < nElements_; i++)
norm = CoinMax(norm, CoinAbs(elements_[i]));
return norm;
}
/// sum of vector elements
inline T sum() const
{
T sume = 0;
for (int i = 0; i < nElements_; i++)
sume += elements_[i];
return sume;
}
/// scale vector elements
inline void scale(T factor)
{
for (int i = 0; i < nElements_; i++)
elements_[i] *= factor;
return;
}
//@}
/**@name Arithmetic operators. */
//@{
/// add <code>value</code> to every entry
void operator+=(T value);
/// subtract <code>value</code> from every entry
void operator-=(T value);
/// multiply every entry by <code>value</code>
void operator*=(T value);
/// divide every entry by <code>value</code>
void operator/=(T value);
//@}
/**@name Constructors and destructors */
//@{
/** Default constructor */
CoinDenseVector();
/** Alternate Constructors - set elements to vector of Ts */
CoinDenseVector(int size, const T *elems);
/** Alternate Constructors - set elements to same scalar value */
CoinDenseVector(int size, T element = T());
/** Copy constructors */
CoinDenseVector(const CoinDenseVector &);
/** Destructor */
~CoinDenseVector();
//@}
private:
/**@name Private methods */
//@{
/// Copy internal data
void gutsOfSetVector(int size, const T *elems);
/// Set all elements to a given value
void gutsOfSetConstant(int size, T value);
//@}
};
//#############################################################################
/**@name Arithmetic operators on dense vectors.
<strong>NOTE</strong>: Because these methods return an object (they can't
return a reference, though they could return a pointer...) they are
<em>very</em> inefficient...
*/
//@{
/// Return the sum of two dense vectors
template < typename T >
inline CoinDenseVector< T > operator+(const CoinDenseVector< T > &op1,
const CoinDenseVector< T > &op2)
{
assert(op1.size() == op2.size());
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
const T *elements2 = op2.getElements();
T *elements3 = op3.getElements();
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] + elements2[i];
return op3;
}
/// Return the difference of two dense vectors
template < typename T >
inline CoinDenseVector< T > operator-(const CoinDenseVector< T > &op1,
const CoinDenseVector< T > &op2)
{
assert(op1.size() == op2.size());
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
const T *elements2 = op2.getElements();
T *elements3 = op3.getElements();
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] - elements2[i];
return op3;
}
/// Return the element-wise product of two dense vectors
template < typename T >
inline CoinDenseVector< T > operator*(const CoinDenseVector< T > &op1,
const CoinDenseVector< T > &op2)
{
assert(op1.size() == op2.size());
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
const T *elements2 = op2.getElements();
T *elements3 = op3.getElements();
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] * elements2[i];
return op3;
}
/// Return the element-wise ratio of two dense vectors
template < typename T >
inline CoinDenseVector< T > operator/(const CoinDenseVector< T > &op1,
const CoinDenseVector< T > &op2)
{
assert(op1.size() == op2.size());
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
const T *elements2 = op2.getElements();
T *elements3 = op3.getElements();
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] / elements2[i];
return op3;
}
//@}
/**@name Arithmetic operators on dense vector and a constant.
These functions create a dense vector as a result. That dense vector will
have the same indices as <code>op1</code> and the specified operation is
done entry-wise with the given value. */
//@{
/// Return the sum of a dense vector and a constant
template < typename T >
inline CoinDenseVector< T > operator+(const CoinDenseVector< T > &op1, T value)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] + dvalue;
return op3;
}
/// Return the difference of a dense vector and a constant
template < typename T >
inline CoinDenseVector< T > operator-(const CoinDenseVector< T > &op1, T value)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] - dvalue;
return op3;
}
/// Return the element-wise product of a dense vector and a constant
template < typename T >
inline CoinDenseVector< T > operator*(const CoinDenseVector< T > &op1, T value)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] * dvalue;
return op3;
}
/// Return the element-wise ratio of a dense vector and a constant
template < typename T >
inline CoinDenseVector< T > operator/(const CoinDenseVector< T > &op1, T value)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] / dvalue;
return op3;
}
/// Return the sum of a constant and a dense vector
template < typename T >
inline CoinDenseVector< T > operator+(T value, const CoinDenseVector< T > &op1)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] + dvalue;
return op3;
}
/// Return the difference of a constant and a dense vector
template < typename T >
inline CoinDenseVector< T > operator-(T value, const CoinDenseVector< T > &op1)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = dvalue - elements1[i];
return op3;
}
/// Return the element-wise product of a constant and a dense vector
template < typename T >
inline CoinDenseVector< T > operator*(T value, const CoinDenseVector< T > &op1)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = elements1[i] * dvalue;
return op3;
}
/// Return the element-wise ratio of a a constant and dense vector
template < typename T >
inline CoinDenseVector< T > operator/(T value, const CoinDenseVector< T > &op1)
{
int size = op1.size();
CoinDenseVector< T > op3(size);
const T *elements1 = op1.getElements();
T *elements3 = op3.getElements();
double dvalue = value;
for (int i = 0; i < size; i++)
elements3[i] = dvalue / elements1[i];
return op3;
}
//@}
#endif
/* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
*/
| 29.664179 | 79 | 0.634465 | [
"object",
"vector"
] |
6a31c6de2d5b919febea8c6e9b4a16ce9994a950 | 5,174 | cpp | C++ | RobotArm/src/main.cpp | CreateBaseNZ/cb_projects | 0b024cdee6bbc90395814b61cdacc415b90fb931 | [
"MIT"
] | null | null | null | RobotArm/src/main.cpp | CreateBaseNZ/cb_projects | 0b024cdee6bbc90395814b61cdacc415b90fb931 | [
"MIT"
] | null | null | null | RobotArm/src/main.cpp | CreateBaseNZ/cb_projects | 0b024cdee6bbc90395814b61cdacc415b90fb931 | [
"MIT"
] | null | null | null | #include "Arduino.h"
#include "RobotArm.h"
#include "SoftwareSerial.h"
#include "VarSpeedServo.h"
#include "Geometry.h"
#include "BasicLinearAlgebra.h"
float linkLengths[] = {0.05, 0.105, 0.105, 0.045};
RobotArm robotArm(linkLengths);
float positions[10][3];
int noOfPositions=-1;
// This function coverts a comma separated string into an array
int Parse(char input[], float output[],size_t numRead)
{
int count = 0;
char temp[10];
int tempCount = 0;
for (size_t i = 0; i < numRead; i++)
{
if (input[i] != ',')
{
temp[tempCount] = input[i];
tempCount++;
}
else
{
temp[tempCount] = '\0';
output[count] = atof((char *)temp);
temp[0] = '\0';
tempCount = 0;
count++;
}
}
temp[tempCount] = '\0';
output[count] = atof((char *)temp);
return count+1;
}
int EnterInputPos(float pos[10][3]){
bool Entering=false;
int index=0;
int totalPositions=-1;
Serial<<"How many different positions do you want?\n";
while(!Entering){
if(Serial.available()){
char bitData[100];
float data[20];
size_t numRead;
numRead = Serial.readBytesUntil('\n', bitData, sizeof(bitData) - 1);
int length=Parse(bitData,data,numRead);
if(totalPositions==-1){
if (length==1 && data[0]>0 && data[0]<=10){
totalPositions=data[0];
Serial<<"Enter Postion Number 1:\n";
}else{
Serial<<"Enter a number between 1 and 10...\n";
}
}else{
if(length==3){
if(robotArm.Move_position_cylinder_theta(data[0],data[2],data[1],0)){
for(int i=0;i<3;i++){
pos[index][i]=data[i];
}
Serial<<"Position Number "<<(index+1)<<": r= "<<data[0]<<", z= "<<data[1]<<", beta= 0, alpha= "<<data[2]<<"\n";
index++;
if(index==totalPositions){
Entering=true;
}else{
Serial<<"Enter Position Number "<<(index+1)<<":\n";
}
}else{
Serial<<"Enter an alternative position Number "<<(index+1)<<": \n";
}
}else{
Serial<<"The inputs should be in the form= r, z, alpha\n";
}
}
}
}
return totalPositions;
}
float torad(float angle){
return angle*M_PI/180;
}
float t=0,last_t;
int alpha_deg=0;
void setup()
{
int motorPins[4]={2,3,4,5};
robotArm.ConfigurePins(motorPins);
Serial.begin(9600);
int pins[3]={15,18,19},limit[3]={180,200,140};
robotArm.ConfigureBasketBall(pins,3,limit);
// int pin[3]={6,14,18};
// robotArm.ConfigureUltraSonic(pin,3);
//robotArm.Move_position_4link(0.15,0.155,0 ,0);
//delay(1000);
// noOfPositions=EnterInputPos(positions);
// Serial<<"Start Shooting!!\n";
float angles[4] = {0, M_PI_4, M_PI_4,M_PI_2};
float z = linkLengths[0] + linkLengths[1] * cos(angles[1]) + linkLengths[2] * cos(angles[1] + angles[2]) + linkLengths[3] *cos(angles[1] + angles[2] + angles[3]);
float r = linkLengths[1] * sin(angles[1]) + linkLengths[2] * sin(angles[1] + angles[2]) + linkLengths[3] *sin(angles[1] + angles[2] + angles[3]);
float x = r * cos(angles[0]);
float y = r * sin(angles[0]);
float theta = -(angles[1] + angles[2] + angles[3]-M_PI_2);
// robotArm.Move_position_xyz(x, y, z, theta * 180 / M_PI);
//Serial << o << "\n";
// float angles[4] = {M_PI_2, 0,0 ,M_PI_4 };
// Matrix<4, 4> o[noOfJoints+1];
// robotArm.ForwardKinematics(o, angles, linkLengths);
// Serial << o[0] << "\n";
// Serial << o[1] << "\n";
// Serial << o[2] << "\n";
// Serial << o[3] << "\n";
// Serial << o[4] << "\n";
Serial<< x << ", " << y << ", " << z << ", " << theta << "\n";
//robotArm.Move_position_xyz_theta(x, y, z, theta * 180 / M_PI);
Serial << x << ", " << y << ", " << z << ", " << theta << "\n";
}
void loop()
{
//This Section is for position controller testing
//Testing Inverse Kinematics
// Matrix<4, 4> o[noOfJoints+1];
// float r[4]={0,torad(0),torad(0),torad(0)};
// robotArm.ForwardKinematics(o, r, linkLengths);
// Serial<<o[4]<<"\n";
// Matrix<noOfJoints,noOfJoints> VelForwardKinematics=robotArm.CalculateJacobian(o);
// Serial<<VelForwardKinematics<<"\n";
// if(VelForwardKinematics.Det()!=0){
// Matrix<noOfJoints,noOfJoints> VelInverseKinematics=VelForwardKinematics.Inverse();
// Serial<<VelInverseKinematics<<"\n";
// Matrix<4,1> Targert={0,0,1,0};
// Serial<<(VelInverseKinematics*Targert)<<"\n";
// }else{
// Matrix<noOfJoints,1> zeroVector = {0, 0, 0, 0};
// Serial<<"too Much\n";
// }
// while(1){
// }
//Test Move command
//robotArm.Move(0.005,0,0,0,0,0);
//Hand control mode
//robotArm.HandControl();
//Skeleton for basketball
// for(int i=0;i<noOfPositions;i++){
// if(robotArm.Move_position_4link(positions[i][0],positions[i][1],0,positions[i][2])){
// delay(2000);
// while(!robotArm.DetectPassage()){
// delay(1);
// }
// }
// }
//robotArm.DetectPassage();
// float angles[4] = {0, 0, 0, 0};
// Matrix<4, 4> o[noOfJoints+1];
// robotArm.ForwardKinematics(o, angles, linkLengths);
// Serial << o[0] << "\n";
}
| 29.231638 | 164 | 0.568419 | [
"geometry"
] |
6a432e4440c401f16eaa62a0565a746756e1e252 | 27,012 | cpp | C++ | Engine/Source/Runtime/Landscape/Private/LandscapeLight.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Landscape/Private/LandscapeLight.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Landscape/Private/LandscapeLight.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
LandscapeLight.cpp: Static lighting for LandscapeComponents
=============================================================================*/
#include "Landscape.h"
#include "LandscapeLight.h"
#include "LandscapeInfo.h"
#include "LandscapeRender.h"
#include "LandscapeDataAccess.h"
#include "ComponentReregisterContext.h"
#include "UnrealEngine.h"
#if WITH_EDITOR
#define LANDSCAPE_LIGHTMAP_UV_INDEX 1
TMap<FIntPoint, FColor> FLandscapeStaticLightingMesh::LandscapeUpscaleHeightDataCache;
TMap<FIntPoint, FColor> FLandscapeStaticLightingMesh::LandscapeUpscaleXYOffsetDataCache;
/** A texture mapping for landscapes */
/** Initialization constructor. */
FLandscapeStaticLightingTextureMapping::FLandscapeStaticLightingTextureMapping(
ULandscapeComponent* InComponent,FStaticLightingMesh* InMesh,int32 InLightMapWidth,int32 InLightMapHeight,bool bPerformFullQualityRebuild) :
FStaticLightingTextureMapping(
InMesh,
InComponent,
InLightMapWidth,
InLightMapHeight,
LANDSCAPE_LIGHTMAP_UV_INDEX
),
LandscapeComponent(InComponent)
{
}
void FLandscapeStaticLightingTextureMapping::Apply(FQuantizedLightmapData* QuantizedData, const TMap<ULightComponent*,FShadowMapData2D*>& ShadowMapData)
{
//ELightMapPaddingType PaddingType = GAllowLightmapPadding ? LMPT_NormalPadding : LMPT_NoPadding;
ELightMapPaddingType PaddingType = LMPT_NoPadding;
const bool bHasNonZeroData = QuantizedData != NULL && QuantizedData->HasNonZeroData();
// We always create a light map if the surface either has any non-zero lighting data, or if the surface has a shadow map. The runtime
// shaders are always expecting a light map in the case of a shadow map, even if the lighting is entirely zero. This is simply to reduce
// the number of shader permutations to support in the very unlikely case of a unshadowed surfaces that has lighting values of zero.
const bool bNeedsLightMap = bHasNonZeroData || ShadowMapData.Num() > 0 || Mesh->RelevantLights.Num() > 0 || (QuantizedData != NULL && QuantizedData->bHasSkyShadowing);
if (bNeedsLightMap)
{
// Create a light-map for the primitive.
LandscapeComponent->LightMap = FLightMap2D::AllocateLightMap(
LandscapeComponent,
QuantizedData,
LandscapeComponent->Bounds,
PaddingType,
LMF_Streamed
);
}
else
{
LandscapeComponent->LightMap = NULL;
}
if (ShadowMapData.Num() > 0)
{
LandscapeComponent->ShadowMap = FShadowMap2D::AllocateShadowMap(
LandscapeComponent,
ShadowMapData,
LandscapeComponent->Bounds,
PaddingType,
SMF_Streamed
);
}
else
{
LandscapeComponent->ShadowMap = NULL;
}
// Build the list of statically irrelevant lights.
// TODO: This should be stored per LOD.
LandscapeComponent->IrrelevantLights.Empty();
for (int32 LightIndex = 0; LightIndex < Mesh->RelevantLights.Num(); LightIndex++)
{
const ULightComponent* Light = Mesh->RelevantLights[LightIndex];
// Check if the light is stored in the light-map.
const bool bIsInLightMap = LandscapeComponent->LightMap && LandscapeComponent->LightMap->LightGuids.Contains(Light->LightGuid);
// Add the light to the statically irrelevant light list if it is in the potentially relevant light list, but didn't contribute to the light-map.
if(!bIsInLightMap)
{
LandscapeComponent->IrrelevantLights.AddUnique(Light->LightGuid);
}
}
LandscapeComponent->bHasCachedStaticLighting = true;
// Mark the primitive's package as dirty.
LandscapeComponent->MarkPackageDirty();
}
namespace
{
// Calculate Geometric LOD for lighting
int32 GetLightingLOD(const ULandscapeComponent* InComponent)
{
if (InComponent->LightingLODBias < 0)
{
return FMath::Clamp<int32>(InComponent->ForcedLOD >= 0 ? InComponent->ForcedLOD : InComponent->LODBias, 0, FMath::CeilLogTwo(InComponent->SubsectionSizeQuads + 1) - 1);
}
else
{
return InComponent->LightingLODBias;
}
}
};
/** Initialization constructor. */
FLandscapeStaticLightingMesh::FLandscapeStaticLightingMesh(ULandscapeComponent* InComponent, const TArray<ULightComponent*>& InRelevantLights, int32 InExpandQuadsX, int32 InExpandQuadsY, float InLightMapRatio, int32 InLOD)
: FStaticLightingMesh(
FMath::Square(((InComponent->ComponentSizeQuads + 1) >> InLOD) - 1 + 2 * InExpandQuadsX) * 2,
FMath::Square(((InComponent->ComponentSizeQuads + 1) >> InLOD) - 1 + 2 * InExpandQuadsX) * 2,
FMath::Square(((InComponent->ComponentSizeQuads + 1) >> InLOD) + 2 * InExpandQuadsX),
FMath::Square(((InComponent->ComponentSizeQuads + 1) >> InLOD) + 2 * InExpandQuadsX),
0,
!!(InComponent->CastShadow | InComponent->bCastHiddenShadow),
false,
InRelevantLights,
InComponent,
InComponent->Bounds.GetBox(),
InComponent->GetLightingGuid()
)
, LandscapeComponent(InComponent)
, LightMapRatio(InLightMapRatio)
, ExpandQuadsX(InExpandQuadsX)
, ExpandQuadsY(InExpandQuadsY)
{
const float LODScale = (float)InComponent->ComponentSizeQuads / (((InComponent->ComponentSizeQuads + 1) >> InLOD) - 1);
LocalToWorld = FTransform(FQuat::Identity, FVector::ZeroVector, FVector(LODScale, LODScale, 1)) * InComponent->ComponentToWorld;
ComponentSizeQuads = ((InComponent->ComponentSizeQuads + 1) >> InLOD) - 1;
NumVertices = ComponentSizeQuads + 2*InExpandQuadsX + 1;
NumQuads = NumVertices - 1;
UVFactor = LightMapRatio / NumVertices;
bReverseWinding = (LocalToWorld.GetDeterminant() < 0.0f);
int32 GeometricLOD = ::GetLightingLOD(InComponent);
GetHeightmapData(InLOD, FMath::Max(GeometricLOD, InLOD));
}
FLandscapeStaticLightingMesh::~FLandscapeStaticLightingMesh()
{
}
namespace
{
void GetLODData(ULandscapeComponent* LandscapeComponent, int32 X, int32 Y, int32 HeightmapOffsetX, int32 HeightmapOffsetY, int32 LODValue, int32 HeightmapStride, FColor& OutHeight, FColor& OutXYOffset)
{
int32 ComponentSize = ((LandscapeComponent->SubsectionSizeQuads + 1) * LandscapeComponent->NumSubsections) >> LODValue;
int32 LODHeightmapSize = LandscapeComponent->HeightmapTexture->Source.GetSizeX() >> LODValue;
float Ratio = (float)(LODHeightmapSize) / (HeightmapStride);
int32 CurrentHeightmapOffsetX = FMath::RoundToInt((float)(LODHeightmapSize)* LandscapeComponent->HeightmapScaleBias.Z);
int32 CurrentHeightmapOffsetY = FMath::RoundToInt((float)(LODHeightmapSize)* LandscapeComponent->HeightmapScaleBias.W);
float XX = FMath::Clamp<float>((X - HeightmapOffsetX) * Ratio, 0.f, ComponentSize - 1.f) + CurrentHeightmapOffsetX;
int32 XI = (int32)XX;
float XF = XX - XI;
float YY = FMath::Clamp<float>((Y - HeightmapOffsetY) * Ratio, 0.f, ComponentSize - 1.f) + CurrentHeightmapOffsetY;
int32 YI = (int32)YY;
float YF = YY - YI;
FLandscapeComponentDataInterface DataInterface(LandscapeComponent, LODValue);
FColor* HeightMipData = DataInterface.GetRawHeightData();
FColor* XYOffsetMipData = DataInterface.GetRawXYOffsetData();
FColor H1 = HeightMipData[XI + YI * LODHeightmapSize];
FColor H2 = HeightMipData[FMath::Min(XI + 1, LODHeightmapSize - 1) + YI * LODHeightmapSize];
FColor H3 = HeightMipData[XI + FMath::Min(YI + 1, LODHeightmapSize - 1) * LODHeightmapSize];
FColor H4 = HeightMipData[FMath::Min(XI + 1, LODHeightmapSize - 1) + FMath::Min(YI + 1, LODHeightmapSize - 1) * LODHeightmapSize];
uint16 Height = FMath::RoundToInt(FMath::Lerp(FMath::Lerp<float>(((H1.R << 8) + H1.G), ((H2.R << 8) + H2.G), XF),
FMath::Lerp<float>(((H3.R << 8) + H3.G), ((H4.R << 8) + H4.G), XF), YF));
uint8 B = FMath::RoundToInt(FMath::Lerp(FMath::Lerp<float>((H1.B), (H2.B), XF),
FMath::Lerp<float>((H3.B), (H4.B), XF), YF));
uint8 A = FMath::RoundToInt(FMath::Lerp<float>(FMath::Lerp((H1.A), (H2.A), XF),
FMath::Lerp<float>((H3.A), (H4.A), XF), YF));
OutHeight = FColor((Height >> 8), Height & 255, B, A);
if (LandscapeComponent->XYOffsetmapTexture)
{
FColor X1 = XYOffsetMipData[XI + YI * LODHeightmapSize];
FColor X2 = XYOffsetMipData[FMath::Min(XI + 1, LODHeightmapSize - 1) + YI * LODHeightmapSize];
FColor X3 = XYOffsetMipData[XI + FMath::Min(YI + 1, LODHeightmapSize - 1) * LODHeightmapSize];
FColor X4 = XYOffsetMipData[FMath::Min(XI + 1, LODHeightmapSize - 1) + FMath::Min(YI + 1, LODHeightmapSize - 1) * LODHeightmapSize];
uint16 XComp = FMath::RoundToInt(FMath::Lerp(FMath::Lerp<float>(((X1.R << 8) + X1.G), ((X2.R << 8) + X2.G), XF),
FMath::Lerp<float>(((X3.R << 8) + X3.G), ((X4.R << 8) + X4.G), XF), YF));
uint16 YComp = FMath::RoundToInt(FMath::Lerp(FMath::Lerp<float>(((X1.B << 8) + X1.A), ((X2.B << 8) + X2.A), XF),
FMath::Lerp<float>(((X3.B << 8) + X3.A), ((X4.B << 8) + X4.A), XF), YF));
OutXYOffset = FColor((XComp >> 8), XComp & 255, YComp >> 8, YComp & 255);
}
}
void InternalUpscaling(FLandscapeComponentDataInterface& DataInterface, ULandscapeComponent* LandscapeComponent, int32 InLOD, int32 GeometryLOD, TArray<FColor>& CompHeightData, TArray<FColor>& CompXYOffsetData)
{
// Upscaling using Landscape LOD system
ULandscapeInfo* const Info = LandscapeComponent->GetLandscapeInfo();
check(Info);
FIntPoint ComponentBase = LandscapeComponent->GetSectionBase() / LandscapeComponent->ComponentSizeQuads;
int32 NeighborLODs[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
int32 MaxLOD = FMath::CeilLogTwo(LandscapeComponent->SubsectionSizeQuads + 1) - 1;
bool bNeedUpscaling = GeometryLOD > InLOD;
int32 NeighborIdx = 0;
for (int32 y = -1; y <= 1; y++)
{
for (int32 x = -1; x <= 1; x++)
{
if (x == 0 && y == 0)
{
continue;
}
ULandscapeComponent* Neighbor = Info->XYtoComponentMap.FindRef(ComponentBase + FIntPoint(x, y));
int32 NeighborLOD = -1;
if (Neighbor)
{
NeighborLOD = ::GetLightingLOD(Neighbor);
}
else
{
NeighborLOD = 0;
// Sample neighbor components to find maximum LOD
for (int32 yy = -1; yy <= 1; yy++)
{
for (int32 xx = -1; xx <= 1; xx++)
{
if (xx == 0 && yy == 0)
{
continue;
}
ULandscapeComponent* ComponentNeighbor = Info->XYtoComponentMap.FindRef(ComponentBase + FIntPoint(x+xx, y+yy));
if (ComponentNeighbor)
{
NeighborLOD = FMath::Max(::GetLightingLOD(ComponentNeighbor), NeighborLOD);
}
}
}
}
bNeedUpscaling |= (NeighborLOD > InLOD);
NeighborLODs[NeighborIdx++] = NeighborLOD;
}
}
if (bNeedUpscaling)
{
check(LandscapeComponent);
// Need Upscaling
int32 HeightmapStride = LandscapeComponent->HeightmapTexture->Source.GetSizeX() >> InLOD;
int32 HeightDataSize = HeightmapStride * HeightmapStride;
CompHeightData.Empty(HeightDataSize);
CompXYOffsetData.Empty(HeightDataSize);
CompHeightData.AddZeroed(HeightDataSize);
CompXYOffsetData.AddZeroed(HeightDataSize);
// Update for only component region for performance
int32 ComponentSize = ((LandscapeComponent->SubsectionSizeQuads + 1) * LandscapeComponent->NumSubsections) >> InLOD;
for (int32 Y = DataInterface.HeightmapComponentOffsetY; Y < DataInterface.HeightmapComponentOffsetY + ComponentSize; ++Y)
{
for (int32 X = DataInterface.HeightmapComponentOffsetX; X < DataInterface.HeightmapComponentOffsetX + ComponentSize; ++X)
{
FIntPoint IXY(X - DataInterface.HeightmapComponentOffsetX, Y - DataInterface.HeightmapComponentOffsetY);
IXY += ComponentBase * (ComponentSize - 1);
FColor* CachedHeight = FLandscapeStaticLightingMesh::LandscapeUpscaleHeightDataCache.Find(IXY);
FColor* CachedXYOffset = FLandscapeStaticLightingMesh::LandscapeUpscaleXYOffsetDataCache.Find(IXY);
if (CachedHeight)
{
CompHeightData[X + Y * HeightmapStride] = *CachedHeight;
if (CachedXYOffset)
{
CompXYOffsetData[X + Y * HeightmapStride] = *CachedXYOffset;
}
}
else
{
// LOD System similar to the shader
FVector2D XY(float(X - DataInterface.HeightmapComponentOffsetX) / (ComponentSize - 1), float(Y - DataInterface.HeightmapComponentOffsetY) / (ComponentSize - 1));
XY = XY - 0.5f;
float RealLOD = GeometryLOD;
if (XY.X < 0.f)
{
if (XY.Y < 0.f)
{
RealLOD = FMath::Lerp(
FMath::Lerp<float>(NeighborLODs[0], NeighborLODs[1], XY.X + 1.f),
FMath::Lerp<float>(NeighborLODs[3], GeometryLOD, XY.X + 1.f),
XY.Y + 1.f); // 0
}
else
{
RealLOD = FMath::Lerp(
FMath::Lerp<float>(NeighborLODs[3], GeometryLOD, XY.X + 1.f),
FMath::Lerp<float>(NeighborLODs[5], NeighborLODs[6], XY.X + 1.f),
XY.Y); // 2
}
}
else
{
if (XY.Y < 0.f)
{
RealLOD = FMath::Lerp(
FMath::Lerp<float>(NeighborLODs[1], NeighborLODs[2], XY.X),
FMath::Lerp<float>(GeometryLOD, NeighborLODs[4], XY.X),
XY.Y + 1.f); // 1
}
else
{
RealLOD = FMath::Lerp(
FMath::Lerp<float>(GeometryLOD, NeighborLODs[4], XY.X),
FMath::Lerp<float>(NeighborLODs[6], NeighborLODs[7], XY.X),
XY.Y); // 3
}
}
RealLOD = FMath::Min(RealLOD, (float)MaxLOD);
int32 LODValue = (int32)RealLOD;
float MorphAlpha = FMath::Fractional(RealLOD);
FColor Height[2];
FColor XYOffset[2];
::GetLODData(LandscapeComponent, X, Y, DataInterface.HeightmapComponentOffsetX, DataInterface.HeightmapComponentOffsetY,
FMath::Min(MaxLOD, LODValue), HeightmapStride, Height[0], XYOffset[0]);
// Interpolation between two LOD
if ((RealLOD > InLOD) && (LODValue + 1 <= MaxLOD) && MorphAlpha != 0.f)
{
::GetLODData(LandscapeComponent, X, Y, DataInterface.HeightmapComponentOffsetX, DataInterface.HeightmapComponentOffsetY,
FMath::Min(MaxLOD, LODValue + 1), HeightmapStride, Height[1], XYOffset[1]);
// Need interpolation
uint16 Height0 = (Height[0].R << 8) + Height[0].G;
uint16 Height1 = (Height[1].R << 8) + Height[1].G;
uint16 LerpHeight = FMath::RoundToInt(FMath::Lerp<float>(Height0, Height1, MorphAlpha));
CompHeightData[X + Y * HeightmapStride] =
FColor((LerpHeight >> 8), LerpHeight & 255,
FMath::RoundToInt(FMath::Lerp<float>(Height[0].B, Height[1].B, MorphAlpha)),
FMath::RoundToInt(FMath::Lerp<float>(Height[0].A, Height[1].A, MorphAlpha)));
if (LandscapeComponent->XYOffsetmapTexture)
{
uint16 XComp0 = (XYOffset[0].R << 8) + XYOffset[0].G;
uint16 XComp1 = (XYOffset[1].R << 8) + XYOffset[1].G;
uint16 LerpXComp = FMath::RoundToInt(FMath::Lerp<float>(XComp0, XComp1, MorphAlpha));
uint16 YComp0 = (XYOffset[0].B << 8) + XYOffset[0].A;
uint16 YComp1 = (XYOffset[1].B << 8) + XYOffset[1].A;
uint16 LerpYComp = FMath::RoundToInt(FMath::Lerp<float>(YComp0, YComp1, MorphAlpha));
CompXYOffsetData[X + Y * HeightmapStride] =
FColor(LerpXComp >> 8, LerpXComp & 255, LerpYComp >> 8, LerpYComp & 255);
}
}
else
{
CompHeightData[X + Y * HeightmapStride] = Height[0];
CompXYOffsetData[X + Y * HeightmapStride] = XYOffset[0];
}
// Caching current calculated value
FLandscapeStaticLightingMesh::LandscapeUpscaleHeightDataCache.Add(IXY, CompHeightData[X + Y * HeightmapStride]);
if (LandscapeComponent->XYOffsetmapTexture)
{
FLandscapeStaticLightingMesh::LandscapeUpscaleHeightDataCache.Add(IXY, CompXYOffsetData[X + Y * HeightmapStride]);
}
}
}
}
DataInterface.SetRawHeightData(&CompHeightData[0]);
if (LandscapeComponent->XYOffsetmapTexture)
{
DataInterface.SetRawXYOffsetData(&CompXYOffsetData[0]);
}
}
}
};
void FLandscapeStaticLightingMesh::GetHeightmapData(int32 InLOD, int32 GeometryLOD)
{
ULandscapeInfo* const Info = LandscapeComponent->GetLandscapeInfo();
check(Info);
HeightData.Empty(FMath::Square(NumVertices));
HeightData.AddUninitialized(FMath::Square(NumVertices));
const int32 NumSubsections = LandscapeComponent->NumSubsections;
const int32 SubsectionSizeVerts = (LandscapeComponent->SubsectionSizeQuads + 1) >> InLOD;
const int32 SubsectionSizeQuads = SubsectionSizeVerts - 1;
FIntPoint ComponentBase = LandscapeComponent->GetSectionBase()/LandscapeComponent->ComponentSizeQuads;
// assume that ExpandQuad size <= SubsectionSizeQuads...
check(ExpandQuadsX <= SubsectionSizeQuads);
check(ExpandQuadsY <= SubsectionSizeQuads);
int32 MaxLOD = FMath::CeilLogTwo(LandscapeComponent->SubsectionSizeQuads + 1) - 1;
// copy heightmap data for this component...
{
// Data array for upscaling case
TArray<FColor> CompHeightData;
TArray<FColor> CompXYOffsetData;
FLandscapeComponentDataInterface DataInterface(LandscapeComponent, InLOD);
::InternalUpscaling(DataInterface, LandscapeComponent, InLOD, GeometryLOD, CompHeightData, CompXYOffsetData);
for (int32 Y = 0; Y < ComponentSizeQuads + 1; Y++)
{
const FColor* const Data = DataInterface.GetHeightData(0, Y);
for (int32 SubsectionX = 0; SubsectionX < NumSubsections; SubsectionX++)
{
const int32 X = SubsectionSizeQuads * SubsectionX;
const int32 CompX = X + FMath::Min(X/SubsectionSizeQuads, NumSubsections - 1);
const FColor* const SubsectionData = &Data[CompX];
// Copy the data
FMemory::Memcpy( &HeightData[X + ExpandQuadsX + (Y + ExpandQuadsY) * NumVertices], SubsectionData, SubsectionSizeVerts * sizeof(FColor));
}
}
}
// copy surrounding heightmaps...
for (int32 ComponentY = 0; ComponentY < 3; ComponentY++)
{
for (int32 ComponentX = 0; ComponentX < 3; ComponentX++)
{
if (ComponentX == 1 && ComponentY == 1)
{
// Ourself
continue;
}
const int32 XSource = (ComponentX == 0) ? (ComponentSizeQuads - ExpandQuadsX) : ((ComponentX == 1) ? 0 : 1);
const int32 YSource = (ComponentY == 0) ? (ComponentSizeQuads - ExpandQuadsY) : ((ComponentY == 1) ? 0 : 1);
const int32 XDest = (ComponentX == 0) ? 0 : ((ComponentX == 1) ? ExpandQuadsX : (ComponentSizeQuads + ExpandQuadsX + 1));
const int32 YDest = (ComponentY == 0) ? 0 : ((ComponentY == 1) ? ExpandQuadsY : (ComponentSizeQuads + ExpandQuadsY + 1));
const int32 XNum = (ComponentX == 1) ? (ComponentSizeQuads + 1) : ExpandQuadsX;
const int32 YNum = (ComponentY == 1) ? (ComponentSizeQuads + 1) : ExpandQuadsY;
const int32 XBackup = (ComponentX == 2) ? (ComponentSizeQuads + ExpandQuadsX) : ExpandQuadsX;
const int32 YBackup = (ComponentY == 2) ? (ComponentSizeQuads + ExpandQuadsY) : ExpandQuadsY;
const int32 XBackupNum = (ComponentX == 1) ? (ComponentSizeQuads + 1) : 1;
const int32 YBackupNum = (ComponentY == 1) ? (ComponentSizeQuads + 1) : 1;
ULandscapeComponent* Neighbor = Info->XYtoComponentMap.FindRef(ComponentBase + FIntPoint((ComponentX - 1), (ComponentY - 1)));
if (Neighbor)
{
// Data array for upscaling case
TArray<FColor> CompHeightData;
TArray<FColor> CompXYOffsetData;
int32 NeighborGeometricLOD = ::GetLightingLOD(Neighbor);
FLandscapeComponentDataInterface DataInterface(Neighbor, InLOD);
::InternalUpscaling(DataInterface, Neighbor, InLOD, NeighborGeometricLOD, CompHeightData, CompXYOffsetData);
for (int32 Y = 0; Y < YNum; Y++)
{
const FColor* const Data = DataInterface.GetHeightData(0, YSource + Y);
int32 NextX;
for (int32 X = XSource; X < XSource + XNum; X = NextX)
{
NextX = (X / SubsectionSizeQuads + 1) * SubsectionSizeQuads + 1;
const int32 CompX = X + FMath::Min(X/SubsectionSizeQuads, NumSubsections - 1);
const FColor* const SubsectionData = &Data[CompX];
// Copy the data
FMemory::Memcpy( &HeightData[XDest + (X - XSource) + (YDest + Y) * NumVertices], SubsectionData, FMath::Min(NextX - X, XSource + XNum - X) * sizeof(FColor));
}
}
}
else
{
for (int32 Y = 0; Y < YNum; Y++)
{
for (int32 X = 0; X < XNum; X += XBackupNum)
{
const FColor* const BackupData = &HeightData[XBackup + (YBackup + (Y % YBackupNum)) * NumVertices];
// Copy the data
FMemory::Memcpy( &HeightData[XDest + X + (YDest + Y) * NumVertices], BackupData, XBackupNum * sizeof(FColor));
}
}
}
}
}
}
/** Fills in the static lighting vertex data for the Landscape vertex. */
void FLandscapeStaticLightingMesh::GetStaticLightingVertex(int32 VertexIndex, FStaticLightingVertex& OutVertex) const
{
const int32 X = VertexIndex % NumVertices;
const int32 Y = VertexIndex / NumVertices;
const int32 LocalX = X - ExpandQuadsX;
const int32 LocalY = Y - ExpandQuadsY;
const FColor* Data = &HeightData[X + Y * NumVertices];
OutVertex.WorldTangentZ.X = 2.0f / 255.f * (float)Data->B - 1.0f;
OutVertex.WorldTangentZ.Y = 2.0f / 255.f * (float)Data->A - 1.0f;
OutVertex.WorldTangentZ.Z = FMath::Sqrt(1.0f - (FMath::Square(OutVertex.WorldTangentZ.X) + FMath::Square(OutVertex.WorldTangentZ.Y)));
OutVertex.WorldTangentX = FVector4(OutVertex.WorldTangentZ.Z, 0.0f, -OutVertex.WorldTangentZ.X);
OutVertex.WorldTangentY = OutVertex.WorldTangentZ ^ OutVertex.WorldTangentX;
// Copied from FLandscapeComponentDataInterface::GetWorldPositionTangents to fix bad lighting when rotated
OutVertex.WorldTangentX = LocalToWorld.TransformVectorNoScale(OutVertex.WorldTangentX);
OutVertex.WorldTangentY = LocalToWorld.TransformVectorNoScale(OutVertex.WorldTangentY);
OutVertex.WorldTangentZ = LocalToWorld.TransformVectorNoScale(OutVertex.WorldTangentZ);
const uint16 Height = (Data->R << 8) + Data->G;
OutVertex.WorldPosition = LocalToWorld.TransformPosition(FVector(LocalX, LocalY, LandscapeDataAccess::GetLocalHeight(Height)));
OutVertex.TextureCoordinates[0] = FVector2D((float)X / NumVertices, (float)Y / NumVertices);
OutVertex.TextureCoordinates[LANDSCAPE_LIGHTMAP_UV_INDEX].X = X * UVFactor;
OutVertex.TextureCoordinates[LANDSCAPE_LIGHTMAP_UV_INDEX].Y = Y * UVFactor;
}
void FLandscapeStaticLightingMesh::GetTriangle(int32 TriangleIndex,FStaticLightingVertex& OutV0,FStaticLightingVertex& OutV1,FStaticLightingVertex& OutV2) const
{
int32 I0, I1, I2;
GetTriangleIndices(TriangleIndex,I0, I1, I2);
GetStaticLightingVertex(I0,OutV0);
GetStaticLightingVertex(I1,OutV1);
GetStaticLightingVertex(I2,OutV2);
}
void FLandscapeStaticLightingMesh::GetTriangleIndices(int32 TriangleIndex,int32& OutI0,int32& OutI1,int32& OutI2) const
{
int32 QuadIndex = TriangleIndex >> 1;
int32 QuadTriIndex = TriangleIndex & 1;
int32 QuadX = QuadIndex % (NumVertices - 1);
int32 QuadY = QuadIndex / (NumVertices - 1);
switch(QuadTriIndex)
{
case 0:
OutI0 = (QuadX + 0) + (QuadY + 0) * NumVertices;
OutI1 = (QuadX + 1) + (QuadY + 1) * NumVertices;
OutI2 = (QuadX + 1) + (QuadY + 0) * NumVertices;
break;
case 1:
OutI0 = (QuadX + 0) + (QuadY + 0) * NumVertices;
OutI1 = (QuadX + 0) + (QuadY + 1) * NumVertices;
OutI2 = (QuadX + 1) + (QuadY + 1) * NumVertices;
break;
}
if (bReverseWinding)
{
Swap(OutI1, OutI2);
}
}
const static FName FLandscapeStaticLightingMesh_IntersectLightRayName(TEXT("FLandscapeStaticLightingMesh_IntersectLightRay"));
FLightRayIntersection FLandscapeStaticLightingMesh::IntersectLightRay(const FVector& Start,const FVector& End,bool bFindNearestIntersection) const
{
// Intersect the light ray with the terrain component.
FHitResult Result(1.0f);
FHitResult NewHitInfo;
FCollisionQueryParams NewTraceParams( FLandscapeStaticLightingMesh_IntersectLightRayName, true );
const bool bIntersects = LandscapeComponent->LineTraceComponent( Result, Start, End, NewTraceParams );
// Setup a vertex to represent the intersection.
FStaticLightingVertex IntersectionVertex;
if(bIntersects)
{
IntersectionVertex.WorldPosition = Result.Location;
IntersectionVertex.WorldTangentZ = Result.Normal;
}
else
{
IntersectionVertex.WorldPosition.Set(0,0,0);
IntersectionVertex.WorldTangentZ.Set(0,0,1);
}
return FLightRayIntersection(bIntersects,IntersectionVertex);
}
void ULandscapeComponent::GetStaticLightingInfo(FStaticLightingPrimitiveInfo& OutPrimitiveInfo,const TArray<ULightComponent*>& InRelevantLights,const FLightingBuildOptions& Options)
{
if( HasStaticLighting() )
{
const float LightMapRes = StaticLightingResolution > 0.f ? StaticLightingResolution : GetLandscapeProxy()->StaticLightingResolution;
const int32 LightingLOD = GetLandscapeProxy()->StaticLightingLOD;
int32 PatchExpandCountX = 0;
int32 PatchExpandCountY = 0;
int32 DesiredSize = 1;
const float LightMapRatio = ::GetTerrainExpandPatchCount(LightMapRes, PatchExpandCountX, PatchExpandCountY, ComponentSizeQuads, (NumSubsections * (SubsectionSizeQuads+1)), DesiredSize, LightingLOD);
int32 SizeX = DesiredSize;
int32 SizeY = DesiredSize;
if (SizeX > 0 && SizeY > 0)
{
FLandscapeStaticLightingMesh* StaticLightingMesh = new FLandscapeStaticLightingMesh(this, InRelevantLights, PatchExpandCountX, PatchExpandCountY, LightMapRatio, LightingLOD);
OutPrimitiveInfo.Meshes.Add(StaticLightingMesh);
// Create a static lighting texture mapping
OutPrimitiveInfo.Mappings.Add(new FLandscapeStaticLightingTextureMapping(
this,StaticLightingMesh,SizeX,SizeY,true));
}
}
}
bool ULandscapeComponent::GetLightMapResolution( int32& Width, int32& Height ) const
{
// Assuming DXT_1 compression at the moment...
float LightMapRes = StaticLightingResolution > 0.f ? StaticLightingResolution : GetLandscapeProxy()->StaticLightingResolution;
int32 PatchExpandCountX = 1;
int32 PatchExpandCountY = 1;
int32 DesiredSize = 1;
uint32 LightingLOD = GetLandscapeProxy()->StaticLightingLOD;
float LightMapRatio = ::GetTerrainExpandPatchCount(LightMapRes, PatchExpandCountX, PatchExpandCountY, ComponentSizeQuads, (NumSubsections * (SubsectionSizeQuads+1)), DesiredSize, LightingLOD);
Width = DesiredSize;
Height = DesiredSize;
return false;
}
void ULandscapeComponent::GetLightAndShadowMapMemoryUsage( int32& LightMapMemoryUsage, int32& ShadowMapMemoryUsage ) const
{
int32 Width, Height;
GetLightMapResolution(Width, Height);
const auto FeatureLevel = GetWorld() ? GetWorld()->FeatureLevel : GMaxRHIFeatureLevel;
if(AllowHighQualityLightmaps(FeatureLevel))
{
LightMapMemoryUsage = NUM_HQ_LIGHTMAP_COEF * (Width * Height * 4 / 3); // assuming DXT5
}
else
{
LightMapMemoryUsage = NUM_LQ_LIGHTMAP_COEF * (Width * Height * 4 / 3) / 2; // assuming DXT1
}
ShadowMapMemoryUsage = (Width * Height * 4 / 3); // assuming G8
return;
}
#endif
void ULandscapeComponent::InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
{
if (bHasCachedStaticLighting)
{
Modify();
FComponentReregisterContext ReregisterContext(this);
// Block until the RT processes the unregister before modifying variables that it may need to access
FlushRenderingCommands();
Super::InvalidateLightingCacheDetailed(bInvalidateBuildEnqueuedLighting, bTranslationOnly);
// Discard all cached lighting.
IrrelevantLights.Empty();
LightMap = NULL;
ShadowMap = NULL;
}
}
| 39.034682 | 222 | 0.708611 | [
"mesh"
] |
6a461f38b41d18d0802b77190ca6855da87668dc | 3,742 | cpp | C++ | src/autocoder/CPPGenerator/generate_functions/generate_UserObjects.cpp | JPL-UNLV-CS-2021/qsm | e0b282040edc808bc62b6afe892c5d05adbc02d6 | [
"Apache-2.0"
] | null | null | null | src/autocoder/CPPGenerator/generate_functions/generate_UserObjects.cpp | JPL-UNLV-CS-2021/qsm | e0b282040edc808bc62b6afe892c5d05adbc02d6 | [
"Apache-2.0"
] | 2 | 2021-05-14T17:26:52.000Z | 2021-05-21T03:45:24.000Z | src/autocoder/CPPGenerator/generate_functions/generate_UserObjects.cpp | JPL-UNLV-CS-2021/qsm | e0b282040edc808bc62b6afe892c5d05adbc02d6 | [
"Apache-2.0"
] | null | null | null | #include "generate_UserObjects.h"
#include <vector>
#include <string>
using json = nlohmann::json;
using namespace std;
using std::filesystem::current_path;
string cleanBSPCPP(string s);
string cleanBSPHPP(string s);
void eraseSubStr(std::string& mainStr, const std::string& toErase);
void generate_UserObjects(json j) {
//Get files from json
vector<string> fileNames;
vector<string> fileContents;
string temp = "";
for(auto it : j.items()) {
if (it.key() == "files") {
for (auto userFile : it.value().items()) {
if (userFile.key() == "bsp.cpp") {
fileNames.push_back(userFile.key());
temp = cleanBSPCPP(userFile.value());
fileContents.push_back(temp);
}
else if (userFile.key() == "bsp.hpp"){
fileNames.push_back(userFile.key());
temp = cleanBSPHPP(userFile.value());
fileContents.push_back(temp);
}
else {
fileNames.push_back(userFile.key());
fileContents.push_back(userFile.value());
}
}
}
}
ofstream outFile;
for (int i = 0; i < fileNames.size(); i++) {
outFile.open("Output_Files/generated_code/UserObjects/" + fileNames[i]);
outFile << fileContents[i];
outFile.close();
}
}
string cleanBSPCPP(string s){
string badstring1 = "#include \"qpcpp.hpp\" // QP/C++ framework API\n";
string badstring2 = "using namespace QP;\n";
string badstring3 = " << QP_VERSION_STR\n";
string badstring4 = "// callback functions needed by the framework --------------------------------";
string badstring5 = "void QF::onStartup(void) {}";
string badstring6 = "void QP::QF::onCleanup(void) {}";
string badstring7 = "void QP::QF_onClockTick(void) {";
string badstring8 = " QF::TICK_X(0U, 0); // QF clock tick processing for rate 0\n}";
string badstring10 = "void Q_onAssert(char const * const module, int loc) {";
string badstring11 = " cerr << \"Assertion failed in \" << module << \":\" << loc << endl;";
string badstring12 = " exit(-1);\n}";
eraseSubStr(s, badstring1);
eraseSubStr(s, badstring2);
eraseSubStr(s, badstring3);
eraseSubStr(s, badstring4);
eraseSubStr(s, badstring5);
eraseSubStr(s, badstring6);
eraseSubStr(s, badstring7);
eraseSubStr(s, badstring8);
eraseSubStr(s, badstring10);
eraseSubStr(s, badstring11);
eraseSubStr(s, badstring12);
return s;
}
string cleanBSPHPP(string s) {
string badstring1 = "enum BlinkySignals {";
string badstring2 = "enum { TICKS_PER_SEC = 100 }; // numer of clock ticks in a second";
string badstring3 = "enum BlinkySignals {";
string badstring4 = " TIMEOUT_SIG = QP::Q_USER_SIG, // offset the first signal";
string badstring5 = " MAX_SIG\n};";
string badstring6 = "// active object(s) used in this application -------------------------------";
string badstring7 = "$declare${AOs::AO_Blinky}";
eraseSubStr(s, badstring1);
eraseSubStr(s, badstring2);
eraseSubStr(s, badstring3);
eraseSubStr(s, badstring4);
eraseSubStr(s, badstring5);
eraseSubStr(s, badstring6);
eraseSubStr(s, badstring7);
return s;
}
/*
* Erase First Occurrence of given substring from main string.
*/
void eraseSubStr(std::string& mainStr, const std::string& toErase)
{
// Search for the substring in string
size_t pos = mainStr.find(toErase);
if (pos != std::string::npos)
{
// If found then erase it from string
mainStr.erase(pos, toErase.length());
}
} | 34.018182 | 105 | 0.595938 | [
"object",
"vector"
] |
6a4719e5d3920168b572589a7d47de1c8b8a4f88 | 2,942 | cc | C++ | gnuradio-3.7.13.4/gr-blocks/lib/multiply_const_vff_impl.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gr-blocks/lib/multiply_const_vff_impl.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gr-blocks/lib/multiply_const_vff_impl.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | /* -*- c++ -*- */
/*
* Copyright 2014-2015 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <multiply_const_vff_impl.h>
#include <gnuradio/io_signature.h>
#include <volk/volk.h>
namespace gr {
namespace blocks {
multiply_const_vff::sptr
multiply_const_vff::make(std::vector<float> k)
{
return gnuradio::get_initial_sptr
(new multiply_const_vff_impl(k));
}
multiply_const_vff_impl::multiply_const_vff_impl(std::vector<float> k)
: sync_block("multiply_const_vff",
io_signature::make(1, 1, sizeof(float)*k.size()),
io_signature::make(1, 1, sizeof(float)*k.size())),
d_k(k)
{
const int alignment_multiple =
volk_get_alignment() / sizeof(float);
set_alignment(std::max(1,alignment_multiple));
}
int
multiply_const_vff_impl::work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
float *iptr = (float*)input_items[0];
float *optr = (float*)output_items[0];
int nitems_per_block = output_signature()->sizeof_stream_item(0)/sizeof(float);
for(int i = 0; i < noutput_items; i++) {
for(int j = 0; j < nitems_per_block; j++) {
*optr++ = *iptr++ * d_k[j];
}
}
return noutput_items;
}
void
multiply_const_vff_impl::setup_rpc()
{
#ifdef GR_CTRLPORT
add_rpc_variable(
rpcbasic_sptr(new rpcbasic_register_get<multiply_const_vff,
std::vector<float> >(
alias(), "coefficient",
&multiply_const_vff::k,
pmt::mp(-1024.0f), pmt::mp(1024.0f), pmt::mp(0.0f),
"", "Coefficient", RPC_PRIVLVL_MIN,
DISPTIME | DISPOPTSTRIP)));
add_rpc_variable(
rpcbasic_sptr(new rpcbasic_register_set<multiply_const_vff,
std::vector<float> >(
alias(), "coefficient",
&multiply_const_vff::set_k,
pmt::mp(-1024.0f), pmt::mp(1024.0f), pmt::mp(0.0f),
"", "Coefficient",
RPC_PRIVLVL_MIN, DISPNULL)));
#endif /* GR_CTRLPORT */
}
} /* namespace blocks */
} /* namespace gr */
| 30.329897 | 85 | 0.64344 | [
"vector"
] |
6a48a30e8725e0159c831bd20c7f8ebb287b75e9 | 1,988 | hpp | C++ | pose_refinement/SA-LMPE/ba/openMVG/numeric/lm.hpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | pose_refinement/SA-LMPE/ba/openMVG/numeric/lm.hpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | pose_refinement/SA-LMPE/ba/openMVG/numeric/lm.hpp | Aurelio93/satellite-pose-estimation | 46957a9bc9f204d468f8fe3150593b3db0f0726a | [
"MIT"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z | // This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_NUMERIC_LM_HPP
#define OPENMVG_NUMERIC_LM_HPP
// Levenberg Marquardt Non Linear Optimization
#include <Eigen/Core>
namespace openMVG
{
using namespace Eigen;
/**
* @brief Generic functor Levenberg-Marquardt minimization
* @tparam _Scalar Type of internal computation
* @tparam NX Number of values per sample at compile time
* @tparam NY Number of samples at compile time
*/
template<typename _Scalar, int NX = Dynamic, int NY = Dynamic>
struct Functor
{
using Scalar = _Scalar;
enum
{
InputsAtCompileTime = NX,
ValuesAtCompileTime = NY
};
using InputType = Matrix<Scalar, InputsAtCompileTime, 1>;
using ValueType = Matrix<Scalar, ValuesAtCompileTime, 1>;
using JacobianType = Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime>;
/// Number of values per sample
const int m_inputs;
// Number of sample
const int m_values;
/**
* @brief Default constructor
*/
Functor()
: m_inputs( InputsAtCompileTime ),
m_values( ValuesAtCompileTime )
{
}
/**
* @brief Constructor
* @param inputs Number of column per sample
* @param values Number of sample
*/
Functor( int inputs, int values ) : m_inputs( inputs ), m_values( values ) {}
/**
* @brief Get number of samples
* @return Number of samples
*/
int inputs() const
{
return m_inputs;
}
/**
* @brief Get number of samples
* @return Number of samples
*/
int values() const
{
return m_values;
}
// you should define that in the subclass :
// void operator() (const InputType& x, ValueType* v, JacobianType* _j=0) const;
};
}; // namespace openMVG
#endif // OPENMVG_NUMERIC_LM_HPP
| 22.850575 | 83 | 0.69668 | [
"geometry"
] |
c69a4ed4e0fcc00aa2cbbb3c2e32ac2323b5893f | 389 | hpp | C++ | gui/src/inspector/materialInspector.hpp | F4r3n/FarenMediaLibrary | 3f71054df7178ca79781b101ca2d58cd95a20a43 | [
"Apache-2.0"
] | 7 | 2016-09-09T16:43:15.000Z | 2021-06-16T22:32:33.000Z | gui/src/inspector/materialInspector.hpp | F4r3n/FarenMediaLibrary | 3f71054df7178ca79781b101ca2d58cd95a20a43 | [
"Apache-2.0"
] | null | null | null | gui/src/inspector/materialInspector.hpp | F4r3n/FarenMediaLibrary | 3f71054df7178ca79781b101ca2d58cd95a20a43 | [
"Apache-2.0"
] | 1 | 2020-01-05T19:22:32.000Z | 2020-01-05T19:22:32.000Z | #pragma once
#include "inspector.hpp"
#include "Components/CMaterial.h"
#include "macroInspectorHelper.hpp"
#include <vector>
#include "Rendering/MaterialValue.h"
namespace gui {
DECLARE_INSPECTOR_CLASS(Material, fmc::CMaterial)
private:
std::string _ValueTypeToName(fm::ValuesType inValueType);
std::vector<const char*> _valuesShader;
std::vector<const char*> _typesMaterial;
};
}
| 25.933333 | 58 | 0.77635 | [
"vector"
] |
c6a388205d51102a87acc7c9d41f2ed95dae94a1 | 1,921 | cpp | C++ | Maths/src/cCRC.cpp | ErrorFlexXx/Clipped | 68266f1e418c25a10485ca2b4696bfdaa735ca6f | [
"MIT"
] | null | null | null | Maths/src/cCRC.cpp | ErrorFlexXx/Clipped | 68266f1e418c25a10485ca2b4696bfdaa735ca6f | [
"MIT"
] | null | null | null | Maths/src/cCRC.cpp | ErrorFlexXx/Clipped | 68266f1e418c25a10485ca2b4696bfdaa735ca6f | [
"MIT"
] | null | null | null | #include "cCRC.h"
#include "cFormat.h"
#include <ClippedUtils/cLogger.h>
using namespace std;
using namespace Clipped;
template <class T>
CRC<T>::CRC(const T generator, const T init, const T finalXOR, const bool reflectInput, const bool reflectResult, const String& name)
: init(init)
, crc(init)
, reflectInput(reflectInput)
, reflectResult(reflectResult)
, finalXOR(finalXOR)
, generator(generator)
, name(name)
{
calculateTable();
}
template <class T>
void CRC<T>::begin()
{
crc = init;
}
template <class T>
void CRC<T>::update(const uint8_t* data, size_t length)
{
for(size_t i = 0; i < length; i++)
{
uint8_t dataByte = data[i];
if(reflectInput)
{
dataByte = reflect(dataByte);
}
uint8_t tmp = (crc >> ((sizeof(T) - 1) * 8)) ^ dataByte;
crc = (crc << 8) ^ lookupTable[static_cast<uint8_t>(tmp)];
}
}
template <class T>
void CRC<T>::update(const std::vector<uint8_t>& data)
{
update(reinterpret_cast<const uint8_t*>(data.data()), data.size());
}
template <class T>
T CRC<T>::finish()
{
if(reflectResult)
{
crc = reflect(crc);
}
return crc ^ finalXOR;
}
template <class T>
void CRC<T>::calculateTable()
{
for(size_t i = 0; i < 256; i++)
{
T currentByte = static_cast<T>((T)i << ((sizeof(T) - 1) * 8));
for(unsigned char bit = 0; bit < 8; bit++)
{
if((currentByte & ((T)1 << ((sizeof(T) * 8) - 1))) != 0)
{
currentByte <<= 1;
currentByte ^= generator;
}
else
{
currentByte <<= 1;
}
}
lookupTable.push_back(currentByte);
}
}
// Please compile template class for the following types:
template class CRC<uint8_t>;
template class CRC<uint16_t>;
template class CRC<uint32_t>;
template class CRC<uint64_t>;
| 22.08046 | 133 | 0.571057 | [
"vector"
] |
c6a3ef300c92baccfdf1c05342af368f2a0a09fa | 748 | cpp | C++ | 1st/find_minimu_in_rotated_sorted_array.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/find_minimu_in_rotated_sorted_array.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/find_minimu_in_rotated_sorted_array.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <vector>
using std::vector;
using std::endl;
using std::cout;
class Solution {
public:
int findMin(vector<int> &num) {
vector<int>::size_type left = 0;
vector<int>::size_type right = num.size() - 1;
vector<int>::size_type mid;
do {
if (num[left] <= num[right])
return num[left];
mid = (right - left) / 2 + left;
if (num[mid] > num.back())
left = mid + 1;
else
right = mid;
} while ( left < right);
return num[left];
}
};
int main(void)
{
vector<int> num;
num.push_back(2);
num.push_back(1);
cout << Solution().findMin(num) << endl;
return 0;
}
| 21.371429 | 54 | 0.501337 | [
"vector"
] |
c6a420d60ab855f60065b9bc53f8031bf1bfdaf1 | 7,885 | cpp | C++ | src/demos/gpu/demo_GPU_mixer.cpp | yangfengzzz/chrono | 6abb679feef0e64ae1863268052624c581f876a8 | [
"BSD-3-Clause"
] | null | null | null | src/demos/gpu/demo_GPU_mixer.cpp | yangfengzzz/chrono | 6abb679feef0e64ae1863268052624c581f876a8 | [
"BSD-3-Clause"
] | null | null | null | src/demos/gpu/demo_GPU_mixer.cpp | yangfengzzz/chrono | 6abb679feef0e64ae1863268052624c581f876a8 | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Nic Olsen
// =============================================================================
// Chrono::Gpu evaluation of several simple mixer designs. Material consisting
// of spherical particles is let to aggitate in a rotating mixer. Metrics on the
// performance of each mixer can be determined in post-processing.
// =============================================================================
#include <cmath>
#include <iostream>
#include <string>
#include "chrono/core/ChGlobal.h"
#include "chrono/utils/ChUtilsSamplers.h"
#include "chrono/assets/ChTriangleMeshShape.h"
#include "chrono_gpu/ChGpuData.h"
#include "chrono_gpu/physics/ChSystemGpu.h"
#include "chrono_gpu/utils/ChGpuJsonParser.h"
#include "chrono_gpu/utils/ChGpuVisualization.h"
#include "chrono_thirdparty/filesystem/path.h"
using namespace chrono;
using namespace chrono::gpu;
// Output frequency
float out_fps = 200;
// Enable/disable run-time visualization (if Chrono::OpenGL is available)
bool render = true;
float render_fps = 2000;
int main(int argc, char* argv[]) {
ChGpuSimulationParameters params;
if (argc != 2 || ParseJSON(gpu::GetDataFile(argv[1]), params) == false) {
std::cout << "Usage:\n./demo_GPU_mixer <json_file>" << std::endl;
return 1;
}
const float Bx = params.box_X;
const float By = Bx;
const float chamber_height = Bx / 3; // TODO
const float fill_height = chamber_height;
const float Bz = chamber_height + fill_height;
std::cout << "Box Dims: " << Bx << " " << By << " " << Bz << std::endl;
float iteration_step = params.step_size;
ChSystemGpuMesh gpu_sys(params.sphere_radius, params.sphere_density, make_float3(Bx, By, Bz));
gpu_sys.SetKn_SPH2SPH(params.normalStiffS2S);
gpu_sys.SetKn_SPH2WALL(params.normalStiffS2W);
gpu_sys.SetKn_SPH2MESH(params.normalStiffS2M);
gpu_sys.SetKt_SPH2SPH(params.tangentStiffS2S);
gpu_sys.SetKt_SPH2WALL(params.tangentStiffS2W);
gpu_sys.SetKt_SPH2MESH(params.tangentStiffS2M);
gpu_sys.SetGn_SPH2SPH(params.normalDampS2S);
gpu_sys.SetGn_SPH2WALL(params.normalDampS2W);
gpu_sys.SetGn_SPH2MESH(params.normalDampS2M);
gpu_sys.SetGt_SPH2SPH(params.tangentDampS2S);
gpu_sys.SetGt_SPH2WALL(params.tangentDampS2W);
gpu_sys.SetGt_SPH2MESH(params.tangentDampS2M);
gpu_sys.SetCohesionRatio(params.cohesion_ratio);
gpu_sys.SetAdhesionRatio_SPH2MESH(params.adhesion_ratio_s2m);
gpu_sys.SetAdhesionRatio_SPH2WALL(params.adhesion_ratio_s2w);
gpu_sys.SetFrictionMode(chrono::gpu::CHGPU_FRICTION_MODE::MULTI_STEP);
gpu_sys.SetStaticFrictionCoeff_SPH2SPH(params.static_friction_coeffS2S);
gpu_sys.SetStaticFrictionCoeff_SPH2WALL(params.static_friction_coeffS2W);
gpu_sys.SetStaticFrictionCoeff_SPH2MESH(params.static_friction_coeffS2M);
gpu_sys.SetParticleOutputMode(params.write_mode);
std::string out_dir = GetChronoOutputPath() + "GPU/";
filesystem::create_directory(filesystem::path(out_dir));
out_dir = out_dir + params.output_dir;
filesystem::create_directory(filesystem::path(out_dir));
gpu_sys.SetTimeIntegrator(CHGPU_TIME_INTEGRATOR::CENTERED_DIFFERENCE);
gpu_sys.SetFixedStepSize(params.step_size);
gpu_sys.SetBDFixed(true);
const float chamber_bottom = -Bz / 2.f;
const float fill_bottom = chamber_bottom + chamber_height;
ChVector<float> cyl_center(0, 0, 0);
const float cyl_rad = Bx / 2.f;
gpu_sys.CreateBCCylinderZ(cyl_center, cyl_rad, false, false);
utils::HCPSampler<float> sampler(2.1f * params.sphere_radius);
std::vector<ChVector<float>> body_points;
const float fill_radius = Bx / 2.f - 2.f * params.sphere_radius;
const float fill_top = fill_bottom + fill_height;
std::cout << "Fill radius " << fill_radius << std::endl;
std::cout << "Fill bottom " << fill_bottom << std::endl;
std::cout << "Fill top " << fill_top << std::endl;
ChVector<float> center(0, 0, fill_bottom);
center.z() += 2 * params.sphere_radius;
while (center.z() < fill_top - 2 * params.sphere_radius) {
auto points = sampler.SampleCylinderZ(center, fill_radius, 0);
body_points.insert(body_points.end(), points.begin(), points.end());
center.z() += 2.1f * params.sphere_radius;
}
gpu_sys.SetParticlePositions(body_points);
gpu_sys.SetGravitationalAcceleration(ChVector<float>(0, 0, -980));
// Add the mixer mesh to the GPU system
float scale_xy = Bx / 2.f;
float scale_z = chamber_height;
ChVector<> scaling(scale_xy, scale_xy, scale_z);
float mixer_mass = 10;
auto mixer_mesh = chrono_types::make_shared<geometry::ChTriangleMeshConnected>();
mixer_mesh->LoadWavefrontMesh(GetChronoDataFile("models/mixer/internal_mixer.obj"), true, false);
mixer_mesh->Transform(ChVector<>(0, 0, 0), ChMatrix33<>(scaling));
auto mixer_mesh_id = gpu_sys.AddMesh(mixer_mesh, mixer_mass);
float rev_per_sec = 1.f;
float ang_vel_Z = rev_per_sec * 2 * (float)CH_C_PI;
ChVector<> mesh_lin_vel(0);
ChVector<> mesh_ang_vel(0, 0, ang_vel_Z);
gpu_sys.EnableMeshCollision(true);
gpu_sys.Initialize();
ChGpuVisualization gpu_vis(&gpu_sys);
std::shared_ptr<ChBody> mixer;
if (render) {
// Create proxy body for mixer mesh
mixer = chrono_types::make_shared<ChBody>();
auto trimesh_shape = chrono_types::make_shared<ChTriangleMeshShape>();
trimesh_shape->SetMesh(mixer_mesh);
mixer->AddAsset(trimesh_shape);
gpu_vis.AddProxyBody(mixer);
gpu_vis.SetTitle("Chrono::Gpu mixer demo");
gpu_vis.SetCameraPosition(ChVector<>(0, -100, 75), ChVector<>(0, 0, 0));
gpu_vis.SetCameraMoveScale(1.0f);
gpu_vis.Initialize();
}
unsigned int out_steps = (unsigned int)(1 / (out_fps * iteration_step));
unsigned int render_steps = (unsigned int)(1 / (render_fps * iteration_step));
unsigned int total_frames = (unsigned int)(params.time_end * out_fps);
std::cout << "out_steps " << out_steps << std::endl;
unsigned int currframe = 0;
unsigned int step = 0;
for (float t = 0; t < params.time_end; t += iteration_step, step++) {
ChVector<> mesh_pos(0, 0, chamber_bottom + chamber_height / 2.0);
ChQuaternion<> mesh_rot = Q_from_AngZ(t * ang_vel_Z);
gpu_sys.ApplyMeshMotion(mixer_mesh_id, mesh_pos, mesh_rot, mesh_lin_vel, mesh_ang_vel);
if (step % out_steps == 0) {
std::cout << "Output frame " << (currframe + 1) << " of " << total_frames << std::endl;
char filename[100];
char mesh_filename[100];
sprintf(filename, "%s/step%06u", out_dir.c_str(), currframe);
sprintf(mesh_filename, "%s/step%06u_mesh", out_dir.c_str(), currframe++);
gpu_sys.WriteParticleFile(std::string(filename));
gpu_sys.WriteMeshes(std::string(mesh_filename));
ChVector<> force;
ChVector<> torque;
gpu_sys.CollectMeshContactForces(0, force, torque);
std::cout << "torque: " << torque.x() << ", " << torque.y() << ", " << torque.z() << std::endl;
}
if (render && step % render_steps == 0) {
mixer->SetPos(mesh_pos);
mixer->SetRot(mesh_rot);
if (gpu_vis.Render())
break;
}
gpu_sys.AdvanceSimulation(iteration_step);
}
return 0;
}
| 39.228856 | 107 | 0.661256 | [
"mesh",
"geometry",
"render",
"vector",
"transform"
] |
c6a9ede02246aab85a418bbbca52edcba78cb650 | 3,558 | cpp | C++ | Samples/XamlContextMenu/cpp/Scenario3.xaml.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,504 | 2019-05-07T06:56:42.000Z | 2022-03-31T19:37:59.000Z | Samples/XamlContextMenu/cpp/Scenario3.xaml.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 314 | 2019-05-08T16:56:30.000Z | 2022-03-21T07:13:45.000Z | Samples/XamlContextMenu/cpp/Scenario3.xaml.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,219 | 2019-05-07T00:47:26.000Z | 2022-03-30T21:12:31.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario3.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
Scenario3::Scenario3()
{
InitializeComponent();
AllItems = SampleDataModel::GetSampleData();
sharedFlyout = safe_cast<MenuFlyout^>(Resources->Lookup("SampleContextMenu"));
}
void Scenario3::ListView_ContextRequested(UIElement^ sender, ContextRequestedEventArgs^ e)
{
// Walk up the tree to find the ListViewItem.
// There may not be one if the click wasn't on an item.
auto requestedElement = safe_cast<FrameworkElement^>(e->OriginalSource);
while ((requestedElement != sender) && !dynamic_cast<ListViewItem^>(requestedElement))
{
requestedElement = safe_cast<FrameworkElement^>(VisualTreeHelper::GetParent(requestedElement));
}
if (requestedElement != sender)
{
// The context menu request was indeed for a ListViewItem.
auto model = safe_cast<SampleDataModel^>(ItemListView->ItemFromContainer(requestedElement));
Point point;
if (e->TryGetPosition(requestedElement, &point))
{
rootPage->NotifyUser("Showing flyout for " + model->Title + " at " + point.X.ToString() + "," + point.Y.ToString(), NotifyType::StatusMessage);
sharedFlyout->ShowAt(requestedElement, point);
}
else
{
// Not invoked via pointer, so let XAML choose a default location.
rootPage->NotifyUser("Showing flyout for " + model->Title + " at default location", NotifyType::StatusMessage);
sharedFlyout->ShowAt(requestedElement);
}
e->Handled = true;
}
}
void Scenario3::ListView_ContextCanceled(UIElement^ sender, RoutedEventArgs^ e)
{
sharedFlyout->Hide();
}
SampleDataModel^ Scenario3::GetDataModelForCurrentListViewFlyout()
{
// Obtain the ListViewItem for which the user requested a context menu.
auto listViewItem = sharedFlyout->Target;
// Get the data model for the ListViewItem.
return safe_cast<SampleDataModel^>(ItemListView->ItemFromContainer(listViewItem));
}
void Scenario3::OpenMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
SampleDataModel^ model = GetDataModelForCurrentListViewFlyout();
rootPage->NotifyUser("Item: " + model->Title + ", Action: Open", NotifyType::StatusMessage);
}
void Scenario3::PrintMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
SampleDataModel^ model = GetDataModelForCurrentListViewFlyout();
rootPage->NotifyUser("Item: " + model->Title + ", Action: Print", NotifyType::StatusMessage);
}
void Scenario3::DeleteMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
SampleDataModel^ model = GetDataModelForCurrentListViewFlyout();
rootPage->NotifyUser("Item: " + model->Title + ", Action: Delete", NotifyType::StatusMessage);
}
| 38.258065 | 156 | 0.672569 | [
"object",
"model"
] |
c6aa39417f0b62e54e8313df7f6ed8d2ef317914 | 3,132 | cc | C++ | art/Framework/IO/FileStatsCollector.cc | drbenmorgan/fnal-art | 31b8a5c76af364bbbfd8960bc2039b4f3cd47ae3 | [
"BSD-3-Clause"
] | null | null | null | art/Framework/IO/FileStatsCollector.cc | drbenmorgan/fnal-art | 31b8a5c76af364bbbfd8960bc2039b4f3cd47ae3 | [
"BSD-3-Clause"
] | 16 | 2021-11-05T14:29:41.000Z | 2022-03-24T15:43:39.000Z | art/Framework/IO/FileStatsCollector.cc | drbenmorgan/fnal-art | 31b8a5c76af364bbbfd8960bc2039b4f3cd47ae3 | [
"BSD-3-Clause"
] | 2 | 2020-09-26T01:37:11.000Z | 2021-05-03T13:02:24.000Z | #include "art/Framework/IO/FileStatsCollector.h"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/filesystem.hpp"
#include <string>
using boost::posix_time::ptime;
namespace {
auto now = boost::posix_time::second_clock::universal_time;
}
art::FileStatsCollector::FileStatsCollector(std::string const& moduleLabel,
std::string const& processName)
: moduleLabel_{moduleLabel}, processName_{processName}
{}
void
art::FileStatsCollector::recordFileOpen()
{
resetStatistics_();
if (!inputFilesSeen_.empty()) {
inputFilesSeen_.emplace_back(lastOpenedInputFile_);
}
fo_ = now();
fileCloseRecorded_ = false;
}
void
art::FileStatsCollector::recordInputFile(std::string const& inputFileName)
{
if (!inputFileName.empty()) {
inputFilesSeen_.emplace_back(inputFileName);
}
lastOpenedInputFile_ = inputFileName;
}
void
art::FileStatsCollector::recordEvent(EventID const& id)
{
++nEvents_;
if (!lowestEventIDSeen_.isValid()) {
lowestEventIDSeen_ = highestEventIDSeen_ = id;
} else if (id < lowestEventIDSeen_) {
lowestEventIDSeen_ = id;
} else if (id > highestEventIDSeen_) {
highestEventIDSeen_ = id;
}
}
void
art::FileStatsCollector::recordRun(RunID const& id)
{
if (!lowestRun_.isValid()) {
lowestRun_ = highestRun_ = id;
lowestRunStartTime_ = highestRunStartTime_ = now();
return;
}
if (id < lowestRun_) {
lowestRun_ = id;
lowestRunStartTime_ = now();
if (lowestSubRun_.runID() != lowestRun_) {
lowestSubRun_ = SubRunID{};
lowestSubRunStartTime_ = ptime{};
}
} else if (id > highestRun_) {
highestRun_ = id;
highestRunStartTime_ = now();
if (highestSubRun_.runID() != highestRun_) {
highestSubRun_ = SubRunID{};
highestSubRunStartTime_ = ptime{};
}
}
}
void
art::FileStatsCollector::recordSubRun(SubRunID const& id)
{
if (!lowestSubRun_.isValid()) {
lowestSubRun_ = highestSubRun_ = id;
lowestSubRunStartTime_ = highestSubRunStartTime_ = now();
} else if (id < lowestSubRun_) {
lowestSubRun_ = id;
lowestSubRunStartTime_ = now();
} else if (id > highestSubRun_) {
highestSubRun_ = id;
highestSubRunStartTime_ = now();
}
subRunsSeen_.emplace(id);
}
void
art::FileStatsCollector::recordFileClose()
{
fc_ = now();
fileCloseRecorded_ = true;
}
std::vector<std::string>
art::FileStatsCollector::parents(bool const want_basename) const
{
std::vector<std::string> result;
if (want_basename) {
result.reserve(inputFilesSeen_.size());
for (auto const& ifile : inputFilesSeen_) {
boost::filesystem::path const ifp{ifile};
result.emplace_back(ifp.filename().native());
}
} else {
result = inputFilesSeen_;
}
return result;
}
void
art::FileStatsCollector::resetStatistics_()
{
fo_ = fc_ = ptime{};
lowestRun_ = highestRun_ = RunID{};
lowestSubRun_ = highestSubRun_ = SubRunID{};
lowestRunStartTime_ = highestRunStartTime_ = ptime{};
lowestSubRunStartTime_ = highestSubRunStartTime_ = ptime{};
inputFilesSeen_.clear();
nEvents_ = 0ul;
subRunsSeen_.clear();
}
| 24.661417 | 75 | 0.692529 | [
"vector"
] |
c6aea733fe1837a3ce2b5a16691a5a118f450709 | 5,359 | cpp | C++ | src/Npfs/UnitTesting/MsgSerDes-Test.cpp | joluxer/NpfsCpp | f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f | [
"Zlib"
] | null | null | null | src/Npfs/UnitTesting/MsgSerDes-Test.cpp | joluxer/NpfsCpp | f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f | [
"Zlib"
] | null | null | null | src/Npfs/UnitTesting/MsgSerDes-Test.cpp | joluxer/NpfsCpp | f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f | [
"Zlib"
] | null | null | null | /*
* MsgSerDes-Test.cpp
*
* Created on: 19.07.2012
* Author: jlode
*/
#include "tut/tut.h"
#include "../MsgBufferSerDes.h"
#include "../NpStr.h"
#include "HeapMemory.h"
namespace tut
{
struct MsgSerDesTest: public Npfs::MsgBufferSerDes
{
static const unsigned char testPattern[8];
static const unsigned char rxTestData[256];
unsigned char rxBuffer[256], txBuffer[256];
MsgSerDesTest(): MsgBufferSerDes(rxBuffer, txBuffer, sizeof(rxBuffer))
{
memcpy(rxBuffer, rxTestData, sizeof(rxBuffer));
mm = new HeapMemory;
}
~MsgSerDesTest()
{
delete mm;
}
};
const unsigned char MsgSerDesTest::rxTestData[256] =
{
0x18, 0x11, 0x7c, 0xd1, 0x97, 0x95, 0x84, 0x5c, 0x85, 0x0a, 0x9f, 0xfd, 0x55, 0xff, 0xf5, 0x5a,
0xd8, 0xa0, 0xed, 0x76, 0xcf, 0xf2, 0x29, 0x58, 0x8f, 0xbd, 0x43, 0xab, 0x68, 0x7d, 0x53, 0x5b,
0x83, 0x64, 0xe7, 0x96, 0x77, 0xb8, 0x93, 0xda, 0x10, 0x93, 0xd8, 0xaf, 0x2a, 0x19, 0x95, 0x75,
0xe0, 0xd5, 0x35, 0x6d, 0x4d, 0xfc, 0x4d, 0x33, 0xde, 0x3b, 0xa1, 0x64, 0x5f, 0x25, 0xc7, 0x74,
0xea, 0xa0, 0x47, 0x7b, 0x02, 0x63, 0xae, 0xfb, 0xc1, 0xfb, 0x1f, 0x14, 0x74, 0xb6, 0x87, 0x04,
0x0f, 0x42, 0x72, 0x12, 0x15, 0x02, 0x9b, 0xc7, 0x2a, 0x29, 0xb7, 0xe5, 0x0e, 0x18, 0xae, 0xf6,
0x38, 0x34, 0x11, 0x56, 0x34, 0xde, 0x50, 0xc4, 0x90, 0x1a, 0x91, 0x23, 0xd0, 0x54, 0xd9, 0x69,
0x83, 0x38, 0x77, 0xda, 0x6c, 0x88, 0xfd, 0xe5, 0x62, 0x5e, 0xa7, 0x11, 0x13, 0x81, 0x99, 0xdd,
0x93, 0x70, 0x27, 0x9e, 0x55, 0xdc, 0xd0, 0xf6, 0xbd, 0x44, 0x85, 0x8f, 0x8b, 0x2f, 0x60, 0xdc,
0x3b, 0xf1, 0xcb, 0x69, 0x79, 0xd7, 0x8c, 0xf3, 0xc0, 0x31, 0xd8, 0xa7, 0x30, 0x5a, 0x5a, 0x0a,
0x57, 0xbf, 0x98, 0x15, 0x58, 0xea, 0xe2, 0x71, 0x1a, 0xb5, 0xeb, 0xd2, 0xfc, 0xf5, 0x74, 0x81,
0xd9, 0x3b, 0xa6, 0x93, 0xc2, 0x63, 0x63, 0xc6, 0x48, 0xc8, 0x78, 0x71, 0x37, 0x31, 0x06, 0x9e,
0x8c, 0x0f, 0xa2, 0xf7, 0xe5, 0xbb, 0x26, 0xbc, 0xfa, 0xff, 0x11, 0xaa, 0x92, 0x28, 0xcb, 0xb4,
0x8a, 0x99, 0x37, 0x70, 0x40, 0x19, 0x5e, 0x47, 0x81, 0x2d, 0xcf, 0xcb, 0x70, 0x9e, 0x59, 0xfe,
0x8c, 0x8b, 0xc0, 0xba, 0x55, 0xfe, 0xd5, 0x85, 0x43, 0xfb, 0xe9, 0xd0, 0xd9, 0x9b, 0x0b, 0xaf,
0x74, 0x3b, 0x65, 0x99, 0x31, 0x36, 0x01, 0xd0, 0x3b, 0x16, 0x73, 0x4d, 0x71, 0xd6, 0x2d, 0x5c,
};
const unsigned char MsgSerDesTest::testPattern[8] = { 0x26, 0x95, 0xd0, 0x05, 0xaa, 0x5b, 0xb8, 0x61 };
namespace
{
typedef test_group<MsgSerDesTest> TestGroup;
TestGroup serDesTest_group("1 MsgSerDes");
typedef TestGroup::object testobject;
}
template<> template<>
void testobject::test<1>()
{
set_test_name("construction");
ensure("rbyteCount zero check", rbyteCount == 0);
ensure("rbyteCount read check", consumedByteCount() == 0);
}
template<> template<>
void testobject::test<2>()
{
set_test_name("64 bit numbers");
putUI64(0x61b85baa05d09526ULL);
ensure("TX data check", memcmp(txBuffer, testPattern, 8) == 0);
uint64_t result = getUI64();
ensure("RX data check", 0x5c849597d17c1118ull == result);
}
template<> template<>
void testobject::test<3>()
{
set_test_name("32 bit numbers");
putUI32(0x05d09526ul);
ensure("TX data check", memcmp(txBuffer, testPattern, 4) == 0);
uint32_t result = getUI32();
ensure("RX data check", 0xd17c1118 == result);
}
template<> template<>
void testobject::test<4>()
{
set_test_name("16 bit numbers");
putUI16(0x9526);
ensure("TX data check", memcmp(txBuffer, testPattern, 2) == 0);
uint16_t result = getUI64();
ensure("RX data check", 0x1118 == result);
}
template<> template<>
void testobject::test<5>()
{
set_test_name("8 bit numbers");
putUI8(0x26);
ensure("TX data check", memcmp(txBuffer, testPattern, 1) == 0);
uint8_t result = getUI64();
ensure("RX data check", 0x18 == result);
}
template<> template<>
void testobject::test<6>()
{
set_test_name("binary buffer transfer");
unsigned char* rxTestBuffer = 0;
put(testPattern, 8);
ensure("TX data check", memcmp(txBuffer, testPattern, 1) == 0);
get(rxTestBuffer, 32);
ensure("RX data check", memcmp(rxBuffer, rxTestBuffer, 32) == 0);
release(rxTestBuffer);
}
template<> template<>
void testobject::test<7>()
{
set_test_name("String transfer");
Npfs::NpStr rxTestString;
Npfs::NpStr txTestString;
txTestString.str = "The quick brown fox jumps over the lazy dogs back 0123456789 times!";
txTestString.len = strlen(txTestString.str);
put(txTestString);
ensure("TX data check", (txBuffer[0] == (txTestString.len & 0xff)) && (txBuffer[1] == ((txTestString.len >> 8) & 0xff)) && (memcmp(txBuffer + 2, txTestString.str, txTestString.len) == 0));
memcpy(rxBuffer, txBuffer, txTestString.len + 2);
get(rxTestString);
ensure("RX data check", (rxBuffer[0] == (rxTestString.len & 0xff)) && (rxBuffer[1] == ((rxTestString.len >> 8) & 0xff)) && (memcmp(rxBuffer + 2, rxTestString.str, rxTestString.len) == 0));
ensure("consumed bytes", (consumedByteCount() - 2) == rxTestString.len);
release(rxTestString);
}
template<> template<>
void testobject::test<8>()
{
set_test_name("Qid transfer");
Npfs::NpQid qid;
get(qid);
ensure_equals("RX data check: type", qid.type, 0x18);
ensure_equals("RX data check: version", qid.version, 0x97d17c11);
ensure_equals("RX data check: path", qid.path, 0x55fd9f0a855c8495ull);
put(qid);
ensure("cross transfer data check", (memcmp(rxBuffer, txBuffer, 13) == 0));
}
}
| 30.976879 | 190 | 0.672887 | [
"object"
] |
c6af35bfafd835930dc1d1acb0f3c55cdc7db7a7 | 933 | cpp | C++ | matrix/shift2DGrid.cpp | Gooner1886/DSA-101 | 44092e10ad39bebbf7da93e897927106d5a45ae7 | [
"MIT"
] | 20 | 2022-01-04T19:36:14.000Z | 2022-03-21T15:35:09.000Z | matrix/shift2DGrid.cpp | Gooner1886/DSA-101 | 44092e10ad39bebbf7da93e897927106d5a45ae7 | [
"MIT"
] | null | null | null | matrix/shift2DGrid.cpp | Gooner1886/DSA-101 | 44092e10ad39bebbf7da93e897927106d5a45ae7 | [
"MIT"
] | null | null | null | // Leetcode - 1260 - Shift 2D Grid
void rev(vector<int> &nums, int start, int end)
{
while (start < end)
{
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
vector<vector<int>> shiftGrid(vector<vector<int>> &grid, int k)
{
vector<int> nums(grid.size() * grid[0].size());
int index = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
nums[index] = grid[i][j];
index++;
}
}
k = k % (nums.size());
rev(nums, 0, nums.size() - k - 1);
rev(nums, nums.size() - k, nums.size() - 1);
rev(nums, 0, nums.size() - 1);
index = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
grid[i][j] = nums[index];
index++;
}
}
return grid;
} | 22.214286 | 63 | 0.436227 | [
"vector"
] |
c6bb97c4b6ef9adcc305eacdde9fe076d058bcdf | 2,775 | cpp | C++ | graphics/src/models/Circle.cpp | brockyates/learning-opengl | ec229ad319b7dc32cb57f50b410d66386530b1a4 | [
"MIT"
] | null | null | null | graphics/src/models/Circle.cpp | brockyates/learning-opengl | ec229ad319b7dc32cb57f50b410d66386530b1a4 | [
"MIT"
] | null | null | null | graphics/src/models/Circle.cpp | brockyates/learning-opengl | ec229ad319b7dc32cb57f50b410d66386530b1a4 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Circle.h"
#include "helpers/GlobalMacros.h"
#include "types/Vertex1.h"
#include <glm/gtc/matrix_transform.hpp>
#include <sstream>
namespace
{
int ValidateVertexCount(const int vertexCount)
{
if(vertexCount < 4)
{
std::stringstream ss;
ss << "Attempted to generate circle model with " << vertexCount << " vertexes. Minimum number of vertexes for this model is 4.";
AppAssert(vertexCount > 3, ss.str());
}
return vertexCount;
}
}
namespace Graphics
{
Circle::Circle(const int vertexCount)
: Model(MakeVertexes(ValidateVertexCount(vertexCount)), MakeIndexesForTriangleDrawMode(vertexCount))
{}
std::vector<Vertex1> Circle::MakeVertexes(const int vertexCount) const
{
const auto defaultColor = glm::vec4{ 1.0f, 1.0f, 1.0f, 1.0f };
const auto origin = glm::vec4{ 0.0f, 0.0f, 0.0f, 1.0f };
const auto basePoint = glm::vec4{ 0.0f, 1.0f, 0.0f, 1.0f };
const auto angle = 2.0f * glm::pi<float>() / static_cast<float>(vertexCount - 1);
std::vector<Vertex1> vertexes;
vertexes.reserve(vertexCount);
vertexes.emplace_back(origin, defaultColor);
vertexes.emplace_back(basePoint, defaultColor);
const glm::vec3 rotationAxis(0.0f, 0.0f, 1.0f);
for (auto i = 1; i < vertexCount - 1; i++) //Note the loop index starts at 1.
{
const auto transform = rotate(glm::mat4(1.0f), i*angle, rotationAxis);
const auto nextPoint = transform * basePoint;
vertexes.emplace_back(nextPoint, defaultColor);
}
return vertexes;
}
std::vector<int> Circle::MakeIndexesForTriangleDrawMode(const int vertexCount)
{
std::vector<int> indexes;
indexes.reserve(3 * (vertexCount - 1));
for (auto i = 0; i < vertexCount - 2; i++)
{
indexes.emplace_back(i+2);
indexes.emplace_back(0);
indexes.emplace_back(i+1);
}
indexes.emplace_back(1);
indexes.emplace_back(0);
indexes.emplace_back(vertexCount - 1);
return indexes;
}
std::vector<int> Circle::MakeIndexesForLineDrawMode(const int vertexCount)
{
std::vector<int> indexes;
indexes.reserve((vertexCount - 1) * 4);
for (auto i = 0; i < vertexCount - 2; i++)
{
indexes.emplace_back(0);
indexes.emplace_back(i+1);
indexes.emplace_back(i+1);
indexes.emplace_back(i+2);
}
indexes.emplace_back(0);
indexes.emplace_back(vertexCount - 1);
indexes.emplace_back(vertexCount - 1);
indexes.emplace_back(1);
return indexes;
}
}
| 28.316327 | 140 | 0.598198 | [
"vector",
"model",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.