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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
902d2b157ef5cab3f6ab29bce46c2cbee9b2618b | 2,295 | hpp | C++ | src/Core/TreeStructures/BVH.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Core/TreeStructures/BVH.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null | src/Core/TreeStructures/BVH.hpp | nmellado/Radium-Engine | 6e42e4be8d14bcd496371a5f58d483f7d03f9cf4 | [
"Apache-2.0"
] | null | null | null |
#ifndef RADIUMENGINE_BVH_HPP
#define RADIUMENGINE_BVH_HPP
#include <Core/RaCore.hpp>
#include <Core/Mesh/TriangleMesh.hpp>
#include <Core/Math/Frustum.hpp>
#include <vector>
#include <memory>
namespace Ra
{
namespace Core
{
/// This class stores a 3-dimensional hierarchy of meshes of arbitrary type.
/// Built on a binary tree
template <typename T>
class BVH
{
class Node {
public:
inline Node( const std::shared_ptr<T>& t );
inline Node( const std::shared_ptr<Node>& l, const std::shared_ptr<Node>& r );
inline std::shared_ptr<Node> getLeftChild() const;
inline std::shared_ptr<Node> getRightChild() const;
inline Aabb getAabb() const
{
return m_aabb;
}
inline std::shared_ptr<T> getData()
{
return m_data;
}
inline bool isFinal() const
{
return m_children.empty();
}
protected:
Aabb m_aabb ;
std::vector<std::shared_ptr<Node>> m_children ;
std::shared_ptr<T> m_data;
};
public:
// public types and constants.
typedef std::shared_ptr<Node> NodePtr;
typedef Node * Nodep;
public:
RA_CORE_ALIGNED_NEW
inline BVH();
inline BVH( const BVH& other ) = default;
inline BVH& operator= ( const BVH& other ) = default;
inline void insertLeaf(const std::shared_ptr<T>& t);
//TODO removeLeaf()
inline void clear();
inline void update();
inline void buildBottomUpSlow();
//TODO void buildBottomUpFast();
//TODO void buildTopDown();
void getInFrustumSlow(std::vector<std::shared_ptr<T>> & objects, const Frustum & frustum) const;
protected:
std::vector<NodePtr> m_leaves;
NodePtr m_root;
Aabb m_root_aabb;
bool m_upToDate;
};
}
}
#include <Core/TreeStructures/BVH.inl>
#endif //RADIUMENGINE_BVH_HPP
| 23.418367 | 108 | 0.518954 | [
"mesh",
"vector"
] |
9031ba4541039a92f8ba353c045f0c8599ab9cf4 | 2,835 | cpp | C++ | python/src/cpc_wrapper.cpp | ghbplayer/incubator-datasketches-cpp | 2b69c07a6910e61d7e13338ca4d506c513f7896d | [
"Apache-2.0"
] | null | null | null | python/src/cpc_wrapper.cpp | ghbplayer/incubator-datasketches-cpp | 2b69c07a6910e61d7e13338ca4d506c513f7896d | [
"Apache-2.0"
] | null | null | null | python/src/cpc_wrapper.cpp | ghbplayer/incubator-datasketches-cpp | 2b69c07a6910e61d7e13338ca4d506c513f7896d | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "cpc_sketch.hpp"
#include "cpc_union.hpp"
#include "cpc_common.hpp"
#include <pybind11/pybind11.h>
#include <sstream>
namespace py = pybind11;
namespace datasketches {
namespace python {
cpc_sketch* cpc_sketch_deserialize(py::bytes skBytes) {
std::string skStr = skBytes; // implicit cast
return new cpc_sketch(cpc_sketch::deserialize(skStr.c_str(), skStr.length()));
}
py::object cpc_sketch_serialize(const cpc_sketch& sk) {
auto serResult = sk.serialize();
return py::bytes((char*)serResult.data(), serResult.size());
}
std::string cpc_sketch_to_string(const cpc_sketch& sk) {
std::ostringstream ss;
sk.to_stream(ss);
return ss.str();
}
cpc_sketch* cpc_union_get_result(const cpc_union& u) {
return new cpc_sketch(u.get_result());
}
}
}
namespace dspy = datasketches::python;
void init_cpc(py::module &m) {
using namespace datasketches;
py::class_<cpc_sketch>(m, "cpc_sketch")
.def(py::init<uint8_t, uint64_t>(), py::arg("lg_k"), py::arg("seed")=DEFAULT_SEED)
.def(py::init<const cpc_sketch&>())
.def("__str__", &dspy::cpc_sketch_to_string)
.def("serialize", &dspy::cpc_sketch_serialize)
.def_static("deserialize", &dspy::cpc_sketch_deserialize)
.def<void (cpc_sketch::*)(uint64_t)>("update", &cpc_sketch::update, py::arg("datum"))
.def<void (cpc_sketch::*)(double)>("update", &cpc_sketch::update, py::arg("datum"))
.def<void (cpc_sketch::*)(const std::string&)>("update", &cpc_sketch::update, py::arg("datum"))
.def("is_empty", &cpc_sketch::is_empty)
.def("get_estimate", &cpc_sketch::get_estimate)
.def("get_lower_bound", &cpc_sketch::get_lower_bound, py::arg("kappa"))
.def("get_upper_bound", &cpc_sketch::get_upper_bound, py::arg("kappa"))
;
py::class_<cpc_union>(m, "cpc_union")
.def(py::init<uint8_t, uint64_t>(), py::arg("lg_k"), py::arg("seed")=DEFAULT_SEED)
.def(py::init<const cpc_union&>())
.def("update", &cpc_union::update, py::arg("sketch"))
.def("get_result", &dspy::cpc_union_get_result)
;
}
| 34.156627 | 99 | 0.705115 | [
"object"
] |
9031e7125c43ee9ca835acfffcb814efa8d3212d | 4,313 | c++ | C++ | src/extern/inventor/apps/examples/Mentor/CXX/05.6.TransformOrdering.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/extern/inventor/apps/examples/Mentor/CXX/05.6.TransformOrdering.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/extern/inventor/apps/examples/Mentor/CXX/05.6.TransformOrdering.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*--------------------------------------------------------------
* This is an example from the Inventor Mentor,
* chapter 5, example 6.
*
* This example shows the effect of different order of
* operation of transforms. The left object is first
* scaled, then rotated, and finally translated to the left.
* The right object is first rotated, then scaled, and finally
* translated to the right.
*------------------------------------------------------------*/
#include <stdlib.h>
#include <Inventor/Xt/SoXt.h>
#include <Inventor/Xt/viewers/SoXtExaminerViewer.h>
#include <Inventor/SoDB.h>
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/nodes/SoRotationXYZ.h>
#include <Inventor/nodes/SoScale.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoTranslation.h>
int
main(int, char **argv)
{
// Initialize Inventor and Xt
Widget myWindow = SoXt::init(argv[0]);
if (myWindow == NULL) exit(1);
SoSeparator *root = new SoSeparator;
root->ref();
// Create two separators, for left and right objects.
SoSeparator *leftSep = new SoSeparator;
SoSeparator *rightSep = new SoSeparator;
root->addChild(leftSep);
root->addChild(rightSep);
// Create the transformation nodes
SoTranslation *leftTranslation = new SoTranslation;
SoTranslation *rightTranslation = new SoTranslation;
SoRotationXYZ *myRotation = new SoRotationXYZ;
SoScale *myScale = new SoScale;
// Fill in the values
leftTranslation->translation.setValue(-1.0, 0.0, 0.0);
rightTranslation->translation.setValue(1.0, 0.0, 0.0);
myRotation->angle = M_PI/2; // 90 degrees
myRotation->axis = SoRotationXYZ::X;
myScale->scaleFactor.setValue(2., 1., 3.);
// Add transforms to the scene.
leftSep->addChild(leftTranslation); // left graph
leftSep->addChild(myRotation); // then rotated
leftSep->addChild(myScale); // first scaled
rightSep->addChild(rightTranslation); // right graph
rightSep->addChild(myScale); // then scaled
rightSep->addChild(myRotation); // first rotated
// Read an object from file. (as in example 4.2.Lights)
SoInput myInput;
if (!myInput.openFile("/usr/share/src/Inventor/examples/data/temple.iv"))
exit (1);
SoSeparator *fileContents = SoDB::readAll(&myInput);
if (fileContents == NULL)
exit (1);
// Add an instance of the object under each separator.
leftSep->addChild(fileContents);
rightSep->addChild(fileContents);
// Construct a renderArea and display the scene.
SoXtExaminerViewer *myViewer =
new SoXtExaminerViewer(myWindow);
myViewer->setSceneGraph(root);
myViewer->setTitle("Transform Ordering");
myViewer->viewAll();
myViewer->show();
SoXt::show(myWindow);
SoXt::mainLoop();
}
| 36.243697 | 77 | 0.686297 | [
"object",
"transform"
] |
9034fe71c8317f689f4fac35d6e64bf6ad812ee9 | 1,445 | cpp | C++ | Sniper.cpp | Dolev/WarGame-master-B | 2e3f636b2530802917a96e565a3af68643275d7d | [
"MIT"
] | null | null | null | Sniper.cpp | Dolev/WarGame-master-B | 2e3f636b2530802917a96e565a3af68643275d7d | [
"MIT"
] | null | null | null | Sniper.cpp | Dolev/WarGame-master-B | 2e3f636b2530802917a96e565a3af68643275d7d | [
"MIT"
] | null | null | null | //
// Created by dolev hindy on 18/07/2020.
//
#include <iostream> // 25/5
using namespace std;
#include "Sniper.hpp"
Soldier* Sniper::copy(int player_number){
Soldier *temp=new Sniper(player_number);
temp->initial_health_points=this->initial_health_points;
temp->father=this->father;
temp->its_max_health_points=this->its_max_health_points;
return temp;
}
void Sniper::attack_or_cure(std::vector<std::vector<Soldier*>> board,std::pair<int,int> source){ //on the strongest one
int max=0;
Soldier *s;
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j]) {
int b = board[i][j]->initial_health_points;
// cout<<"b="<<b<<endl;
if (b > max && board[i][j]->player_number != this->player_number) {
max = b;
s = board[i][j];
}
}
}
}
if(this->father==0){
this->damage_per_activity=100;
}
// cout<<"attack"<<endl;
// cout<<"attack"<<endl;
if(max>0)
s->initial_health_points=s->initial_health_points-this->damage_per_activity;
// cout<<"after minos"<<endl;
// cout<<"points now="<<s->initial_health_points<<endl;
if(max>0)
if(s->initial_health_points<=0){ //25/5
// s->initial_health_points=0;
s=0;
}
} | 28.9 | 121 | 0.541176 | [
"vector"
] |
903abba1d1df025ac2bf9ecb894301218173f9bf | 2,398 | hpp | C++ | cpp/src/toppra/constraint/joint_torque/pinocchio.hpp | stevegolton/toppra | 846e2a7f5b87e0e1884b244b07d5fd661edcd9bd | [
"MIT"
] | 342 | 2017-07-26T17:37:19.000Z | 2022-03-28T19:50:27.000Z | cpp/src/toppra/constraint/joint_torque/pinocchio.hpp | stevegolton/toppra | 846e2a7f5b87e0e1884b244b07d5fd661edcd9bd | [
"MIT"
] | 151 | 2017-11-30T06:14:29.000Z | 2022-03-29T02:06:08.000Z | cpp/src/toppra/constraint/joint_torque/pinocchio.hpp | stevegolton/toppra | 846e2a7f5b87e0e1884b244b07d5fd661edcd9bd | [
"MIT"
] | 134 | 2017-08-18T21:35:39.000Z | 2022-03-25T03:43:08.000Z | #ifndef TOPPRA_CONSTRAINT_JOINT_TORQUE_PINOCCIO_HPP
#define TOPPRA_CONSTRAINT_JOINT_TORQUE_PINOCCIO_HPP
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/multibody/data.hpp>
#include <pinocchio/algorithm/rnea.hpp>
#include <pinocchio/parsers/urdf.hpp>
#include <toppra/constraint/joint_torque.hpp>
namespace toppra {
namespace constraint {
namespace jointTorque {
/** Implementation of JointTorque using pinocchio::rnea function.
* \extends JointTorque
* */
template<typename Model = pinocchio::Model>
class Pinocchio;
template<typename _Model>
class Pinocchio : public JointTorque {
public:
typedef _Model Model;
typedef typename Model::Data Data;
std::ostream& print(std::ostream& os) const
{
return JointTorque::print(os << "Pinocchio - ");
}
void computeInverseDynamics (const Vector& q, const Vector& v, const Vector& a,
Vector& tau)
{
tau = pinocchio::rnea(m_model, m_data, q, v, a);
}
Pinocchio (const Model& model, const Vector& frictionCoeffs = Vector())
: JointTorque (-model.effortLimit, model.effortLimit, frictionCoeffs)
, m_model (model)
, m_data (model)
{
}
/// Move-assignment operator
Pinocchio (Pinocchio&& other)
: JointTorque(other)
, m_storage (std::move(other.m_storage))
, m_model (other.m_model)
, m_data (std::move(other.m_data))
{}
Pinocchio (const std::string& urdfFilename, const Vector& friction = Vector())
: Pinocchio (makeModel(urdfFilename), friction) {}
const Model& model() const { return m_model; }
private:
/// Build a pinocchio::Model
/// \param urdfFilename path to a URDF file.
static Model* makeModel (const std::string& urdfFilename)
{
Model* model (new Model);
pinocchio::urdf::buildModel(urdfFilename, *model);
return model;
}
/// Constructor that takes ownership of the model
Pinocchio (Model* model, const Vector& friction)
: JointTorque (-model->effortLimit, model->effortLimit, friction)
, m_storage (model)
, m_model (*model)
, m_data (m_model)
{
}
/// Store the pinocchio::Model object, in case this object owns it.
std::unique_ptr<Model> m_storage;
const Model& m_model;
Data m_data;
}; // class Pinocchio
} // namespace jointTorque
} // namespace constraint
} // namespace toppra
#endif
| 27.25 | 83 | 0.678899 | [
"object",
"vector",
"model"
] |
903dd363cb1f637a6d8c1867c8e4880e7073f66e | 23,179 | cpp | C++ | Engine/Plugins/Media/AndroidCamera/Source/AndroidCamera/Private/AndroidJavaCameraPlayer.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Media/AndroidCamera/Source/AndroidCamera/Private/AndroidJavaCameraPlayer.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Media/AndroidCamera/Source/AndroidCamera/Private/AndroidJavaCameraPlayer.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "AndroidJavaCameraPlayer.h"
#include "AndroidApplication.h"
#if UE_BUILD_SHIPPING
// always clear any exceptions in SHipping
#define CHECK_JNI_RESULT(Id) if (Id == 0) { JEnv->ExceptionClear(); }
#else
#define CHECK_JNI_RESULT(Id) \
if (Id == 0) \
{ \
if (bIsOptional) { JEnv->ExceptionClear(); } \
else { JEnv->ExceptionDescribe(); checkf(Id != 0, TEXT("Failed to find " #Id)); } \
}
#endif
static jfieldID FindField(JNIEnv* JEnv, jclass Class, const ANSICHAR* FieldName, const ANSICHAR* FieldType, bool bIsOptional)
{
jfieldID Field = Class == NULL ? NULL : JEnv->GetFieldID(Class, FieldName, FieldType);
CHECK_JNI_RESULT(Field);
return Field;
}
FJavaAndroidCameraPlayer::FJavaAndroidCameraPlayer(bool swizzlePixels, bool vulkanRenderer)
: FJavaClassObject(GetClassName(), "(ZZ)V", swizzlePixels, vulkanRenderer)
, GetDurationMethod(GetClassMethod("getDuration", "()I"))
, ResetMethod(GetClassMethod("reset", "()V"))
, GetCurrentPositionMethod(GetClassMethod("getCurrentPosition", "()I"))
, DidCompleteMethod(GetClassMethod("didComplete", "()Z"))
, IsLoopingMethod(GetClassMethod("isLooping", "()Z"))
, IsPlayingMethod(GetClassMethod("isPlaying", "()Z"))
, IsPreparedMethod(GetClassMethod("isPrepared", "()Z"))
, SetDataSourceURLMethod(GetClassMethod("setDataSourceURL", "(Ljava/lang/String;)Z"))
, PrepareMethod(GetClassMethod("prepare", "()V"))
, PrepareAsyncMethod(GetClassMethod("prepareAsync", "()V"))
, SeekToMethod(GetClassMethod("seekTo", "(I)V"))
, SetLoopingMethod(GetClassMethod("setLooping", "(Z)V"))
, ReleaseMethod(GetClassMethod("release", "()V"))
, GetVideoHeightMethod(GetClassMethod("getVideoHeight", "()I"))
, GetVideoWidthMethod(GetClassMethod("getVideoWidth", "()I"))
, GetFrameRateMethod(GetClassMethod("getFrameRate", "()I"))
, SetVideoEnabledMethod(GetClassMethod("setVideoEnabled", "(Z)V"))
, SetAudioEnabledMethod(GetClassMethod("setAudioEnabled", "(Z)V"))
, GetVideoLastFrameDataMethod(GetClassMethod("getVideoLastFrameData", "()Lcom/epicgames/ue4/CameraPlayer14$FrameUpdateInfo;"))
, StartMethod(GetClassMethod("start", "()V"))
, PauseMethod(GetClassMethod("pause", "()V"))
, StopMethod(GetClassMethod("stop", "()V"))
, GetVideoLastFrameMethod(GetClassMethod("getVideoLastFrame", "(I)Lcom/epicgames/ue4/CameraPlayer14$FrameUpdateInfo;"))
, GetAudioTracksMethod(GetClassMethod("GetAudioTracks", "()[Lcom/epicgames/ue4/CameraPlayer14$AudioTrackInfo;"))
, GetCaptionTracksMethod(GetClassMethod("GetCaptionTracks", "()[Lcom/epicgames/ue4/CameraPlayer14$CaptionTrackInfo;"))
, GetVideoTracksMethod(GetClassMethod("GetVideoTracks", "()[Lcom/epicgames/ue4/CameraPlayer14$VideoTrackInfo;"))
, DidResolutionChangeMethod(GetClassMethod("didResolutionChange", "()Z"))
, GetExternalTextureIdMethod(GetClassMethod("getExternalTextureId", "()I"))
, UpdateVideoFrameMethod(GetClassMethod("updateVideoFrame", "(I)Lcom/epicgames/ue4/CameraPlayer14$FrameUpdateInfo;"))
, TakePictureMethod(GetClassMethod("takePicture", "(Ljava/lang/String;II)Z"))
{
VideoTexture = nullptr;
bVideoTextureValid = false;
ScaleRotation.X = 1.0f;
ScaleRotation.Y = 0.0f;
ScaleRotation.Z = 0.0f;
ScaleRotation.W = 1.0f;
Offset.X = 0.0f;
Offset.Y = 0.0f;
Offset.Z = 0.0f;
Offset.W = 0.0f;
bTrackInfoSupported = FAndroidMisc::GetAndroidBuildVersion() >= 16;
PlayerState = FPlayerState::Inactive;
if (bTrackInfoSupported)
{
SelectTrackMethod = GetClassMethod("selectTrack", "(I)V");
}
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
// get field IDs for FrameUpdateInfo class members
jclass localFrameUpdateInfoClass = FAndroidApplication::FindJavaClass("com/epicgames/ue4/CameraPlayer14$FrameUpdateInfo");
FrameUpdateInfoClass = (jclass)JEnv->NewGlobalRef(localFrameUpdateInfoClass);
JEnv->DeleteLocalRef(localFrameUpdateInfoClass);
FrameUpdateInfo_Buffer = FindField(JEnv, FrameUpdateInfoClass, "Buffer", "Ljava/nio/Buffer;", false);
FrameUpdateInfo_CurrentPosition = FindField(JEnv, FrameUpdateInfoClass, "CurrentPosition", "I", false);
FrameUpdateInfo_FrameReady = FindField(JEnv, FrameUpdateInfoClass, "FrameReady", "Z", false);
FrameUpdateInfo_RegionChanged = FindField(JEnv, FrameUpdateInfoClass, "RegionChanged", "Z", false);
FrameUpdateInfo_ScaleRotation00 = FindField(JEnv, FrameUpdateInfoClass, "ScaleRotation00", "F", false);
FrameUpdateInfo_ScaleRotation01 = FindField(JEnv, FrameUpdateInfoClass, "ScaleRotation01", "F", false);
FrameUpdateInfo_ScaleRotation10 = FindField(JEnv, FrameUpdateInfoClass, "ScaleRotation10", "F", false);
FrameUpdateInfo_ScaleRotation11 = FindField(JEnv, FrameUpdateInfoClass, "ScaleRotation11", "F", false);
FrameUpdateInfo_UOffset = FindField(JEnv, FrameUpdateInfoClass, "UOffset", "F", false);
FrameUpdateInfo_VOffset = FindField(JEnv, FrameUpdateInfoClass, "VOffset", "F", false);
// get field IDs for AudioTrackInfo class members
jclass localAudioTrackInfoClass = FAndroidApplication::FindJavaClass("com/epicgames/ue4/CameraPlayer14$AudioTrackInfo");
AudioTrackInfoClass = (jclass)JEnv->NewGlobalRef(localAudioTrackInfoClass);
JEnv->DeleteLocalRef(localAudioTrackInfoClass);
AudioTrackInfo_Index = FindField(JEnv, AudioTrackInfoClass, "Index", "I", false);
AudioTrackInfo_MimeType = FindField(JEnv, AudioTrackInfoClass, "MimeType", "Ljava/lang/String;", false);
AudioTrackInfo_DisplayName = FindField(JEnv, AudioTrackInfoClass, "DisplayName", "Ljava/lang/String;", false);
AudioTrackInfo_Language = FindField(JEnv, AudioTrackInfoClass, "Language", "Ljava/lang/String;", false);
AudioTrackInfo_Channels = FindField(JEnv, AudioTrackInfoClass, "Channels", "I", false);
AudioTrackInfo_SampleRate = FindField(JEnv, AudioTrackInfoClass, "SampleRate", "I", false);
// get field IDs for CaptionTrackInfo class members
jclass localCaptionTrackInfoClass = FAndroidApplication::FindJavaClass("com/epicgames/ue4/CameraPlayer14$CaptionTrackInfo");
CaptionTrackInfoClass = (jclass)JEnv->NewGlobalRef(localCaptionTrackInfoClass);
JEnv->DeleteLocalRef(localCaptionTrackInfoClass);
CaptionTrackInfo_Index = FindField(JEnv, CaptionTrackInfoClass, "Index", "I", false);
CaptionTrackInfo_MimeType = FindField(JEnv, CaptionTrackInfoClass, "MimeType", "Ljava/lang/String;", false);
CaptionTrackInfo_DisplayName = FindField(JEnv, CaptionTrackInfoClass, "DisplayName", "Ljava/lang/String;", false);
CaptionTrackInfo_Language = FindField(JEnv, CaptionTrackInfoClass, "Language", "Ljava/lang/String;", false);
// get field IDs for VideoTrackInfo class members
jclass localVideoTrackInfoClass = FAndroidApplication::FindJavaClass("com/epicgames/ue4/CameraPlayer14$VideoTrackInfo");
VideoTrackInfoClass = (jclass)JEnv->NewGlobalRef(localVideoTrackInfoClass);
JEnv->DeleteLocalRef(localVideoTrackInfoClass);
VideoTrackInfo_Index = FindField(JEnv, VideoTrackInfoClass, "Index", "I", false);
VideoTrackInfo_MimeType = FindField(JEnv, VideoTrackInfoClass, "MimeType", "Ljava/lang/String;", false);
VideoTrackInfo_DisplayName = FindField(JEnv, VideoTrackInfoClass, "DisplayName", "Ljava/lang/String;", false);
VideoTrackInfo_Language = FindField(JEnv, VideoTrackInfoClass, "Language", "Ljava/lang/String;", false);
VideoTrackInfo_BitRate = FindField(JEnv, VideoTrackInfoClass, "BitRate", "I", false);
VideoTrackInfo_Width = FindField(JEnv, VideoTrackInfoClass, "Width", "I", false);
VideoTrackInfo_Height = FindField(JEnv, VideoTrackInfoClass, "Height", "I", false);
VideoTrackInfo_FrameRate = FindField(JEnv, VideoTrackInfoClass, "FrameRate", "F", false);
VideoTrackInfo_FrameRateLow = FindField(JEnv, VideoTrackInfoClass, "FrameRateLow", "F", false);
VideoTrackInfo_FrameRateHigh = FindField(JEnv, VideoTrackInfoClass, "FrameRateHigh", "F", false);
}
int32 FJavaAndroidCameraPlayer::GetDuration()
{
return CallMethod<int32>(GetDurationMethod);
}
bool FJavaAndroidCameraPlayer::IsActive()
{
return PlayerState == FPlayerState::Active;
}
void FJavaAndroidCameraPlayer::Reset()
{
PlayerState = FPlayerState::Inactive;
ScaleRotation.X = 1.0f;
ScaleRotation.Y = 0.0f;
ScaleRotation.Z = 0.0f;
ScaleRotation.W = 1.0f;
Offset.X = 0.0f;
Offset.Y = 0.0f;
CallMethod<void>(ResetMethod);
}
void FJavaAndroidCameraPlayer::Stop()
{
CallMethod<void>(StopMethod);
}
int32 FJavaAndroidCameraPlayer::GetCurrentPosition()
{
int32 position = CallMethod<int32>(GetCurrentPositionMethod);
return position;
}
bool FJavaAndroidCameraPlayer::IsLooping()
{
return CallMethod<bool>(IsLoopingMethod);
}
bool FJavaAndroidCameraPlayer::IsPlaying()
{
return CallMethod<bool>(IsPlayingMethod);
}
bool FJavaAndroidCameraPlayer::IsPrepared()
{
return CallMethod<bool>(IsPreparedMethod);
}
bool FJavaAndroidCameraPlayer::DidComplete()
{
return CallMethod<bool>(DidCompleteMethod);
}
bool FJavaAndroidCameraPlayer::SetDataSource(const FString & Url)
{
ScaleRotation.X = 1.0f;
ScaleRotation.Y = 0.0f;
ScaleRotation.Z = 0.0f;
ScaleRotation.W = 1.0f;
Offset.X = 0.0f;
Offset.Y = 0.0f;
bool Result = CallMethod<bool>(SetDataSourceURLMethod, GetJString(Url));
if (Result)
{
PlayerState = FPlayerState::Active;
}
return Result;
}
bool FJavaAndroidCameraPlayer::Prepare()
{
// This can return an exception in some cases (URL without internet, for example)
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
JEnv->CallVoidMethod(Object, PrepareMethod.Method);
if (JEnv->ExceptionCheck())
{
JEnv->ExceptionDescribe();
JEnv->ExceptionClear();
return false;
}
return true;
}
bool FJavaAndroidCameraPlayer::PrepareAsync()
{
// This can return an exception in some cases (URL without internet, for example)
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
JEnv->CallVoidMethod(Object, PrepareAsyncMethod.Method);
if (JEnv->ExceptionCheck())
{
JEnv->ExceptionDescribe();
JEnv->ExceptionClear();
return false;
}
return true;
}
void FJavaAndroidCameraPlayer::SeekTo(int32 Milliseconds)
{
CallMethod<void>(SeekToMethod, Milliseconds);
}
void FJavaAndroidCameraPlayer::SetLooping(bool Looping)
{
CallMethod<void>(SetLoopingMethod, Looping);
}
void FJavaAndroidCameraPlayer::Release()
{
CallMethod<void>(ReleaseMethod);
}
int32 FJavaAndroidCameraPlayer::GetVideoHeight()
{
return CallMethod<int32>(GetVideoHeightMethod);
}
int32 FJavaAndroidCameraPlayer::GetVideoWidth()
{
return CallMethod<int32>(GetVideoWidthMethod);
}
float FJavaAndroidCameraPlayer::GetFrameRate()
{
return (float)CallMethod<int32>(GetFrameRateMethod);
}
void FJavaAndroidCameraPlayer::SetVideoEnabled(bool enabled /*= true*/)
{
CallMethod<void>(SetVideoEnabledMethod, enabled);
}
void FJavaAndroidCameraPlayer::SetAudioEnabled(bool enabled /*= true*/)
{
CallMethod<void>(SetAudioEnabledMethod, enabled);
}
bool FJavaAndroidCameraPlayer::GetVideoLastFrameData(void* & outPixels, int64 & outCount, int32 *CurrentPosition, bool *bRegionChanged)
{
// This can return an exception in some cases
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
jobject Result = JEnv->CallObjectMethod(Object, GetVideoLastFrameDataMethod.Method);
if (JEnv->ExceptionCheck())
{
JEnv->ExceptionDescribe();
JEnv->ExceptionClear();
if (nullptr != Result)
{
JEnv->DeleteLocalRef(Result);
}
*CurrentPosition = -1;
*bRegionChanged = false;
return false;
}
if (nullptr == Result)
{
return false;
}
jobject buffer = JEnv->GetObjectField(Result, FrameUpdateInfo_Buffer);
if (nullptr != buffer)
{
*CurrentPosition = (int32)JEnv->GetIntField(Result, FrameUpdateInfo_CurrentPosition);
bool bFrameReady = (bool)JEnv->GetBooleanField(Result, FrameUpdateInfo_FrameReady);
*bRegionChanged = (bool)JEnv->GetBooleanField(Result, FrameUpdateInfo_RegionChanged);
ScaleRotation.X = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation00);
ScaleRotation.Y = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation01);
ScaleRotation.Z = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation10);
ScaleRotation.W = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation11);
Offset.X = (float)JEnv->GetFloatField(Result, FrameUpdateInfo_UOffset);
Offset.Y = (float)JEnv->GetFloatField(Result, FrameUpdateInfo_VOffset);
outPixels = JEnv->GetDirectBufferAddress(buffer);
outCount = JEnv->GetDirectBufferCapacity(buffer);
// the GetObjectField returns a local ref, but Java will still own the real buffer
JEnv->DeleteLocalRef(buffer);
JEnv->DeleteLocalRef(Result);
return !(nullptr == outPixels || 0 == outCount);
}
JEnv->DeleteLocalRef(Result);
return false;
}
void FJavaAndroidCameraPlayer::Start()
{
CallMethod<void>(StartMethod);
}
void FJavaAndroidCameraPlayer::Pause()
{
CallMethod<void>(PauseMethod);
}
bool FJavaAndroidCameraPlayer::DidResolutionChange()
{
return CallMethod<bool>(DidResolutionChangeMethod);
}
int32 FJavaAndroidCameraPlayer::GetExternalTextureId()
{
return CallMethod<int32>(GetExternalTextureIdMethod);
}
bool FJavaAndroidCameraPlayer::UpdateVideoFrame(int32 ExternalTextureId, int32 *CurrentPosition, bool *bRegionChanged)
{
// This can return an exception in some cases
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
jobject Result = JEnv->CallObjectMethod(Object, UpdateVideoFrameMethod.Method, ExternalTextureId);
if (JEnv->ExceptionCheck())
{
JEnv->ExceptionDescribe();
JEnv->ExceptionClear();
if (nullptr != Result)
{
JEnv->DeleteLocalRef(Result);
}
*CurrentPosition = -1;
*bRegionChanged = false;
return false;
}
if (nullptr == Result)
{
*CurrentPosition = -1;
*bRegionChanged = false;
return false;
}
*CurrentPosition = (int32)JEnv->GetIntField(Result, FrameUpdateInfo_CurrentPosition);
bool bFrameReady = (bool)JEnv->GetBooleanField(Result, FrameUpdateInfo_FrameReady);
*bRegionChanged = (bool)JEnv->GetBooleanField(Result, FrameUpdateInfo_RegionChanged);
ScaleRotation.X = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation00);
ScaleRotation.Y = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation01);
ScaleRotation.Z = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation10);
ScaleRotation.W = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation11);
Offset.X = (float)JEnv->GetFloatField(Result, FrameUpdateInfo_UOffset);
Offset.Y = (float)JEnv->GetFloatField(Result, FrameUpdateInfo_VOffset);
JEnv->DeleteLocalRef(Result);
return bFrameReady;
}
bool FJavaAndroidCameraPlayer::GetVideoLastFrame(int32 destTexture)
{
// This can return an exception in some cases
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
jobject Result = JEnv->CallObjectMethod(Object, GetVideoLastFrameMethod.Method, destTexture);
if (JEnv->ExceptionCheck())
{
JEnv->ExceptionDescribe();
JEnv->ExceptionClear();
return false;
}
if (nullptr == Result)
{
return false;
}
bool bFrameReady = (bool)JEnv->GetBooleanField(Result, FrameUpdateInfo_FrameReady);
ScaleRotation.X = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation00);
ScaleRotation.Y = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation01);
ScaleRotation.Z = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation10);
ScaleRotation.W = (float)(float)JEnv->GetFloatField(Result, FrameUpdateInfo_ScaleRotation11);
Offset.X = (float)JEnv->GetFloatField(Result, FrameUpdateInfo_UOffset);
Offset.Y = (float)JEnv->GetFloatField(Result, FrameUpdateInfo_VOffset);
JEnv->DeleteLocalRef(Result);
return bFrameReady;
}
bool FJavaAndroidCameraPlayer::TakePicture(const FString& Filename)
{
return TakePicture(Filename, 0, 0);
}
bool FJavaAndroidCameraPlayer::TakePicture(const FString& Filename, int32 Width, int32 Height)
{
return CallMethod<bool>(TakePictureMethod, GetJString(Filename), Width, Height);
}
FName FJavaAndroidCameraPlayer::GetClassName()
{
if (FAndroidMisc::GetAndroidBuildVersion() >= 14)
{
return FName("com/epicgames/ue4/CameraPlayer14");
}
else
{
return FName("");
}
}
bool FJavaAndroidCameraPlayer::SelectTrack(int32 index)
{
if (!bTrackInfoSupported)
{
// Just assume it worked
return true;
}
// This can return an exception in some cases
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
JEnv->CallVoidMethod(Object, SelectTrackMethod.Method, index);
if (JEnv->ExceptionCheck())
{
JEnv->ExceptionDescribe();
JEnv->ExceptionClear();
return false;
}
return true;
}
bool FJavaAndroidCameraPlayer::GetAudioTracks(TArray<FAudioTrack>& AudioTracks)
{
AudioTracks.Empty();
jobjectArray TrackArray = CallMethod<jobjectArray>(GetAudioTracksMethod);
if (nullptr != TrackArray)
{
bool bIsOptional = false;
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
jsize ElementCount = JEnv->GetArrayLength(TrackArray);
for (int Index = 0; Index < ElementCount; ++Index)
{
jobject Track = JEnv->GetObjectArrayElement(TrackArray, Index);
int32 AudioTrackIndex = AudioTracks.AddDefaulted();
FAudioTrack& AudioTrack = AudioTracks[AudioTrackIndex];
AudioTrack.Index = (int32)JEnv->GetIntField(Track, AudioTrackInfo_Index);
jstring jsMimeType = (jstring)JEnv->GetObjectField(Track, AudioTrackInfo_MimeType);
CHECK_JNI_RESULT(jsMimeType);
const char * nativeMimeType = JEnv->GetStringUTFChars(jsMimeType, 0);
AudioTrack.MimeType = FString(nativeMimeType);
JEnv->ReleaseStringUTFChars(jsMimeType, nativeMimeType);
JEnv->DeleteLocalRef(jsMimeType);
jstring jsDisplayName = (jstring)JEnv->GetObjectField(Track, AudioTrackInfo_DisplayName);
CHECK_JNI_RESULT(jsDisplayName);
const char * nativeDisplayName = JEnv->GetStringUTFChars(jsDisplayName, 0);
AudioTrack.DisplayName = FString(nativeDisplayName);
JEnv->ReleaseStringUTFChars(jsDisplayName, nativeDisplayName);
JEnv->DeleteLocalRef(jsDisplayName);
jstring jsLanguage = (jstring)JEnv->GetObjectField(Track, AudioTrackInfo_Language);
CHECK_JNI_RESULT(jsLanguage);
const char * nativeLanguage = JEnv->GetStringUTFChars(jsLanguage, 0);
AudioTrack.Language = FString(nativeLanguage);
JEnv->ReleaseStringUTFChars(jsLanguage, nativeLanguage);
JEnv->DeleteLocalRef(jsLanguage);
AudioTrack.Channels = (int32)JEnv->GetIntField(Track, AudioTrackInfo_Channels);
AudioTrack.SampleRate = (int32)JEnv->GetIntField(Track, AudioTrackInfo_SampleRate);
}
JEnv->DeleteGlobalRef(TrackArray);
return true;
}
return false;
}
bool FJavaAndroidCameraPlayer::GetCaptionTracks(TArray<FCaptionTrack>& CaptionTracks)
{
CaptionTracks.Empty();
jobjectArray TrackArray = CallMethod<jobjectArray>(GetCaptionTracksMethod);
if (nullptr != TrackArray)
{
bool bIsOptional = false;
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
jsize ElementCount = JEnv->GetArrayLength(TrackArray);
for (int Index = 0; Index < ElementCount; ++Index)
{
jobject Track = JEnv->GetObjectArrayElement(TrackArray, Index);
int32 CaptionTrackIndex = CaptionTracks.AddDefaulted();
FCaptionTrack& CaptionTrack = CaptionTracks[CaptionTrackIndex];
CaptionTrack.Index = (int32)JEnv->GetIntField(Track, CaptionTrackInfo_Index);
jstring jsMimeType = (jstring)JEnv->GetObjectField(Track, CaptionTrackInfo_MimeType);
CHECK_JNI_RESULT(jsMimeType);
const char * nativeMimeType = JEnv->GetStringUTFChars(jsMimeType, 0);
CaptionTrack.MimeType = FString(nativeMimeType);
JEnv->ReleaseStringUTFChars(jsMimeType, nativeMimeType);
JEnv->DeleteLocalRef(jsMimeType);
jstring jsDisplayName = (jstring)JEnv->GetObjectField(Track, CaptionTrackInfo_DisplayName);
CHECK_JNI_RESULT(jsDisplayName);
const char * nativeDisplayName = JEnv->GetStringUTFChars(jsDisplayName, 0);
CaptionTrack.DisplayName = FString(nativeDisplayName);
JEnv->ReleaseStringUTFChars(jsDisplayName, nativeDisplayName);
JEnv->DeleteLocalRef(jsDisplayName);
jstring jsLanguage = (jstring)JEnv->GetObjectField(Track, CaptionTrackInfo_Language);
CHECK_JNI_RESULT(jsLanguage);
const char * nativeLanguage = JEnv->GetStringUTFChars(jsLanguage, 0);
CaptionTrack.Language = FString(nativeLanguage);
JEnv->ReleaseStringUTFChars(jsLanguage, nativeLanguage);
JEnv->DeleteLocalRef(jsLanguage);
}
JEnv->DeleteGlobalRef(TrackArray);
return true;
}
return false;
}
bool FJavaAndroidCameraPlayer::GetVideoTracks(TArray<FVideoTrack>& VideoTracks)
{
VideoTracks.Empty();
jobjectArray TrackArray = CallMethod<jobjectArray>(GetVideoTracksMethod);
if (nullptr != TrackArray)
{
bool bIsOptional = false;
JNIEnv* JEnv = FAndroidApplication::GetJavaEnv();
jsize ElementCount = JEnv->GetArrayLength(TrackArray);
if (ElementCount > 0)
{
jobject Track = JEnv->GetObjectArrayElement(TrackArray, 0);
int32 VideoTrackIndex = VideoTracks.AddDefaulted();
FVideoTrack& VideoTrack = VideoTracks[VideoTrackIndex];
VideoTrack.Index = (int32)JEnv->GetIntField(Track, VideoTrackInfo_Index);
jstring jsMimeType = (jstring)JEnv->GetObjectField(Track, VideoTrackInfo_MimeType);
CHECK_JNI_RESULT(jsMimeType);
const char * nativeMimeType = JEnv->GetStringUTFChars(jsMimeType, 0);
VideoTrack.MimeType = FString(nativeMimeType);
JEnv->ReleaseStringUTFChars(jsMimeType, nativeMimeType);
JEnv->DeleteLocalRef(jsMimeType);
jstring jsDisplayName = (jstring)JEnv->GetObjectField(Track, VideoTrackInfo_DisplayName);
CHECK_JNI_RESULT(jsDisplayName);
const char * nativeDisplayName = JEnv->GetStringUTFChars(jsDisplayName, 0);
VideoTrack.DisplayName = FString(nativeDisplayName);
JEnv->ReleaseStringUTFChars(jsDisplayName, nativeDisplayName);
JEnv->DeleteLocalRef(jsDisplayName);
jstring jsLanguage = (jstring)JEnv->GetObjectField(Track, VideoTrackInfo_Language);
CHECK_JNI_RESULT(jsLanguage);
const char * nativeLanguage = JEnv->GetStringUTFChars(jsLanguage, 0);
VideoTrack.Language = FString(nativeLanguage);
JEnv->ReleaseStringUTFChars(jsLanguage, nativeLanguage);
JEnv->DeleteLocalRef(jsLanguage);
VideoTrack.BitRate = (int32)JEnv->GetIntField(Track, VideoTrackInfo_BitRate);
VideoTrack.Dimensions = FIntPoint(GetVideoWidth(), GetVideoHeight());
VideoTrack.FrameRate = GetFrameRate();
VideoTrack.FrameRates = TRange<float>(JEnv->GetFloatField(Track, VideoTrackInfo_FrameRateLow), JEnv->GetFloatField(Track, VideoTrackInfo_FrameRateHigh));
VideoTrack.Format = 0;
for (int Index = 0; Index < ElementCount; ++Index)
{
jobject Format = JEnv->GetObjectArrayElement(TrackArray, Index);
int32 VideoFormatIndex = VideoTrack.Formats.AddDefaulted();
FVideoFormat& VideoFormat = VideoTrack.Formats[VideoFormatIndex];
VideoFormat.Dimensions = FIntPoint((int32)JEnv->GetIntField(Format, VideoTrackInfo_Width), (int32)JEnv->GetIntField(Format, VideoTrackInfo_Height));
VideoFormat.FrameRate = JEnv->GetFloatField(Format, VideoTrackInfo_FrameRateHigh);
VideoFormat.FrameRates = TRange<float>(JEnv->GetFloatField(Format, VideoTrackInfo_FrameRateLow), JEnv->GetFloatField(Format, VideoTrackInfo_FrameRateHigh));
if (VideoTrack.Dimensions == VideoFormat.Dimensions)
{
VideoTrack.Format = VideoFormatIndex;
VideoFormat.FrameRate = VideoTrack.FrameRate;
}
}
}
JEnv->DeleteGlobalRef(TrackArray);
return true;
}
return false;
}
| 36.968102 | 160 | 0.772596 | [
"object"
] |
903e1b420ce18f5e0675c665b8f6e492878dc1e0 | 6,008 | cpp | C++ | cheapest_insertion_perturbed.cpp | RickyDevMJ/Insertion-TSP | 03ddba54dbeea097a18d0d8de9fecc8be708ff01 | [
"MIT"
] | null | null | null | cheapest_insertion_perturbed.cpp | RickyDevMJ/Insertion-TSP | 03ddba54dbeea097a18d0d8de9fecc8be708ff01 | [
"MIT"
] | null | null | null | cheapest_insertion_perturbed.cpp | RickyDevMJ/Insertion-TSP | 03ddba54dbeea097a18d0d8de9fecc8be708ff01 | [
"MIT"
] | 1 | 2021-04-23T06:30:46.000Z | 2021-04-23T06:30:46.000Z | #include <bits/stdc++.h>
using namespace std;
u_int edge_hash(u_int i, u_int j, u_int m) {
return i * m + j;
}
double distance(double x_i, double y_i, double x_j, double y_j) {
double l1 = x_i - x_j;
double l2 = y_i - y_j;
return sqrt(l1*l1 + l2*l2);
}
#define distance(coordinates, i, j) distance(coordinates[i].first, coordinates[i].second, coordinates[j].first, coordinates[j].second)
double tour_cost(u_int n, double x[], double y[]) {
vector<pair<double, double>> coordinates;
unordered_map<u_int, priority_queue<pair<double, u_int>>> insertion_cost;
unordered_map<u_int, pair<u_int, u_int>> edge_map;
unordered_set<u_int> current_vertices, current_edges;
// Reading inputs
for (u_int i = 0; i < n; i++) {
coordinates.push_back(make_pair(x[i], y[i]));
}
// Initial vertex is vertex 0
current_vertices.insert(0);
// Choosing the second vertex
double min_distance = numeric_limits<double>::max();
u_int vertex_index = 0, edge_index;
for (u_int i = 1; i < n; i++) {
double dist = distance(coordinates, 0, i);
if (dist < min_distance) {
min_distance = dist;
vertex_index = i;
}
}
current_vertices.insert(vertex_index);
edge_index = edge_hash(0, vertex_index, n);
edge_map[edge_index] = make_pair(0, vertex_index);
current_edges.insert(edge_index);
// Choosing remaining vertices
for (u_int i = 0; i < n; i++) {
if (current_vertices.find(i) != current_vertices.end())
continue;
priority_queue<pair<double, u_int>> temp;
insertion_cost.emplace(pair<u_int, priority_queue<pair<double, u_int>>>(i, temp));
u_int v1 = edge_map[edge_index].first, v2 = edge_map[edge_index].second;
double c = distance(coordinates, v1, v2), d1 = distance(coordinates, i, v1), d2 = distance(coordinates, i, v2);
insertion_cost[i].push(make_pair(-(d1+d2-c), edge_index));
}
for (u_int num = 2; num < n; num++) {
min_distance = numeric_limits<double>::max();
vertex_index = 0;
for (u_int i = 0; i < n; i++) {
if (current_vertices.find(i) != current_vertices.end())
continue;
pair<double, u_int> top = insertion_cost[i].top();
while (current_edges.find(top.second) == current_edges.end()) {
insertion_cost[i].pop();
top = insertion_cost[i].top();
}
if (top.first < min_distance) {
min_distance = top.first;
vertex_index = i;
edge_index = top.second;
}
}
u_int v1 = edge_map[edge_index].first, v2 = edge_map[edge_index].second;
u_int edge_index_1 = edge_hash(vertex_index, v1, n), edge_index_2 = edge_hash(vertex_index, v2, n);
current_vertices.insert(vertex_index);
if(num != 2)
current_edges.erase(edge_index);
current_edges.insert(edge_index_1);
current_edges.insert(edge_index_2);
edge_map[edge_index_1] = make_pair(vertex_index, v1);
edge_map[edge_index_2] = make_pair(vertex_index, v2);
for (u_int i = 0; i < n; i++) {
if (current_vertices.find(i) != current_vertices.end())
continue;
double c1 = distance(coordinates, vertex_index, v1), c2 = distance(coordinates, vertex_index, v2);
double d = distance(coordinates, i, vertex_index);
double d1 = distance(coordinates, i, v1), d2 = distance(coordinates, i, v2);
insertion_cost[i].push(make_pair(-(d+d1-c1), edge_index_1));
insertion_cost[i].push(make_pair(-(d+d2-c2), edge_index_2));
}
}
// Output answer
double ans = 0.0;
assert(current_edges.size() == n);
unordered_set<u_int> first_occurence, second_occurence;
for (const auto& edge: current_edges) {
u_int e1 = edge_map[edge].first, e2 = edge_map[edge].second;
// Correctness check
if (first_occurence.find(e1) == first_occurence.end())
first_occurence.insert(e1);
else if (second_occurence.find(e1) == second_occurence.end())
second_occurence.insert(e1);
else {
cout << "Error in output !!" << endl;
return 1;
}
if (first_occurence.find(e2) == first_occurence.end())
first_occurence.insert(e2);
else if (second_occurence.find(e2) == second_occurence.end())
second_occurence.insert(e2);
else {
cout << "Error in output !!" << endl;
return 1;
}
ans += distance(coordinates, e1, e2);
}
// Another correctness check
for (u_int e1 : first_occurence) {
if (second_occurence.find(e1) == second_occurence.end()) {
cout << "Error in output !!" << endl;
return 1;
}
}
return ans;
}
int main(int argc, char* argv[]) {
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
u_int n;
cin >> n;
double x[n], y[n];
double MAX = -1.0;
for(u_int i = 0; i < n; i++) {
u_int id;
cin >> id >> x[i] >> y[i];
MAX = max(abs(x[i]), MAX);
MAX = max(abs(y[i]), MAX);
}
string type = "normal";
double sigma = 0.01;
u_int numOuts = 25;
if(argc > 1)
type = string(argv[1]);
if(argc > 2)
sigma = atof(argv[2]);
if(argc > 3)
numOuts = atoi(argv[3]);
double sum = 0.0;
double values[numOuts];
if(string(type) == "uniform") {
uniform_real_distribution<double> distribution(-sigma, sigma);
for(u_int j = 0; j < numOuts; j++) {
double out_x[n], out_y[n];
for(u_int i = 0; i < n; i++) {
out_x[i] = x[i] / MAX + distribution(generator);
out_y[i] = y[i] / MAX + distribution(generator);
}
double cost = tour_cost(n, out_x, out_y) * MAX;
sum += cost;
values[j] = cost;
}
}
else {
normal_distribution<double> distribution(0.0, sigma);
for(u_int j = 0; j < numOuts; j++) {
double out_x[n], out_y[n];
for(u_int i = 0; i < n; i++) {
out_x[i] = x[i] / MAX + distribution(generator);
out_y[i] = y[i] / MAX + distribution(generator);
}
double cost = tour_cost(n, out_x, out_y) * MAX;
sum += cost;
values[j] = cost;
}
}
double variance = 0.0;
double average = sum / numOuts;
for(u_int i = 0; i < numOuts; i++) {
variance += (values[i] - average) * (values[i] - average);
}
variance /= numOuts;
cout << "Scaling factor: " << MAX << endl;
cout << "Perturbed tour cost: " << average << endl;
cout << "Variance: " << variance << endl;
return 0;
}
| 27.814815 | 134 | 0.654128 | [
"vector"
] |
903ee09e818de091a7ae3cb8af3c59ed817a57d0 | 3,827 | cpp | C++ | Xface/XFace/src/XEngine/ModelFileFactory.cpp | thuhcsi/Crystal.TTVS | 9e6c86566bfacf4fc571ad7b1308bcb7382bb213 | [
"Apache-2.0"
] | 75 | 2020-08-18T03:27:13.000Z | 2022-01-05T13:17:50.000Z | Xface/XFace/src/XEngine/ModelFileFactory.cpp | thuhcsi/Crystal.TTVS | 9e6c86566bfacf4fc571ad7b1308bcb7382bb213 | [
"Apache-2.0"
] | 1 | 2020-11-11T09:31:06.000Z | 2020-11-19T14:44:41.000Z | Xface/XFace/src/XEngine/ModelFileFactory.cpp | thuhcsi/Crystal.TTVS | 9e6c86566bfacf4fc571ad7b1308bcb7382bb213 | [
"Apache-2.0"
] | 10 | 2020-08-18T04:35:29.000Z | 2021-09-09T01:41:23.000Z | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Xface Core Library; 3D Model File Loader.
*
* The Initial Developer of the Original Code is
* ITC-irst, TCC Division (http://tcc.itc.it) Trento / ITALY.
* For info, contact: xface-info@itc.it or http://xface.itc.it
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* - Koray Balci (koraybalci@yahoo.com)
* ***** END LICENSE BLOCK ***** */
#include <XEngine/ModelFileFactory.h>
#include <XEngine/ObjLoader.h>
#include <XEngine/VRML1Loader.h>
#include <XEngine/VRML97Loader.h>
#include <XEngine/MeshManager.h>
#include <fstream>
#include <iostream>
#include <algorithm>
namespace XEngine{
//! List of files in memory are stored here as a static var
std::list<MeshInfo> ModelFileFactory::s_filenames;
/*!
Load the mesh from here.
*/
std::list<Drawable*> ModelFileFactory::loadModelFile(const std::string& filename, const std::string& path)
{
std::list<Drawable*> drawables;
MeshInfo info;
IModelLoader* pLoader = 0;
std::string ext(filename.begin() + filename.find_last_of('.') + 1, filename.end());
if(ext == "obj")
{
pLoader = new OBJLoader;
}
else if( (ext == "wrl") || (ext == "WRL"))
{
std::string modelfile = path + filename;
std::ifstream fp(modelfile.c_str());
if(fp.fail())
return drawables;
std::string format, version;
fp >> format >> version;
fp.close();
if(format != "#VRML")
return drawables;
if(version == "V1.0")
pLoader = new VRML1Loader;
else
pLoader = new VRML97Loader;
}
else
return drawables;
// load the model, return value stores the drawables
drawables = pLoader->loadModel(filename, path);
delete pLoader;
// if the file is not loaded correctly, this list is empty
if(drawables.empty())
return drawables;
// save the load info
info.format = ext;
info.file = filename;
info.drawables = drawables;
s_filenames.push_back(info);
return drawables;
}
/*!
UnLoad a single mesh file from here.
*/
MeshInfo ModelFileFactory::unloadModelFile(const std::string& filename)
{
MeshInfo retVal;
FILEMESHES::iterator it = s_filenames.begin();
while (it != s_filenames.end())
{
if(it->file == filename)
{
MeshManager* pMM = MeshManager::getInstance();
std::list<Drawable*>::iterator mesh_it = it->drawables.begin();
while (mesh_it != it->drawables.end())
{
pMM->removeMesh((*mesh_it)->getMeshName());
++mesh_it;
}
retVal = *it;
s_filenames.erase(it);
return retVal;
}
++it;
}
return retVal;
}
/*!
UnLoads all the mesh files from memory.
*/
void ModelFileFactory::unloadAllFiles()
{
MeshManager* pMM = MeshManager::getInstance();
FILEMESHES::iterator it = s_filenames.begin();
while (it != s_filenames.end() && !s_filenames.empty())
{
unloadModelFile(it->file);
it = s_filenames.begin();
}
s_filenames.clear();
}
/*!
Checks is the file is already loaded or not.
\return 0 pointer if it is not loaded, pointer to MeshInfo already loaded otherwise.
*/
const MeshInfo* ModelFileFactory::isFileLoaded(const std::string& filename)
{
FILEMESHES::const_iterator it = s_filenames.begin();
while (it != s_filenames.end())
{
if(it->file == filename)
return &(*it);
++it;
}
return 0;
}
}// namespace XFace
| 24.850649 | 106 | 0.687745 | [
"mesh",
"model",
"3d"
] |
903f1de7486e19f6e4e1c103fc70aba58b58dd81 | 9,067 | cc | C++ | P2P/FiniteFieldCal.cc | hbhzwj/zetasim | 55e6bc3d0db7949abbac222dbe2502e85072c6cb | [
"BSD-4-Clause-UC"
] | 1 | 2017-11-04T22:00:48.000Z | 2017-11-04T22:00:48.000Z | P2P/FiniteFieldCal.cc | hbhzwj/zetasim | 55e6bc3d0db7949abbac222dbe2502e85072c6cb | [
"BSD-4-Clause-UC"
] | null | null | null | P2P/FiniteFieldCal.cc | hbhzwj/zetasim | 55e6bc3d0db7949abbac222dbe2502e85072c6cb | [
"BSD-4-Clause-UC"
] | null | null | null | /* FiniteFieldCal.h
* Jing Wang
* June, 2010
ZetaSim - A NS2 based Simulation suit for Zeta Protocol
Copright (C) 2010 Jing Wang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Jing Wang
Department of Electronics and Information Engineering
Huazhong University of Science and Technology
Wuhan, Hubei, 430074
hbhzwj@gmail.com
*/
#include "FiniteFieldCal.h"
//#include "wj_galois.h"
void Matrix::InsertRow ( CodeWord_t* r, int len )
{
//printf("Enter Matrix::InsertRow()\n");
if ( len != COL_SIZE ) {
std::cout << "Error " << std::cout;
exit ( 1 );
}
//printf("Access(%d, 0): ", row);
CodeWord_t& cp = Access ( row, 0 ); // Get the address of header of the next line
//PrintCodeWord(&cp, col);
memcpy ( &cp, r, len );
row++;
}
void Matrix::SwapCol ( int m, int n )
{
//printf("Enter SwapCol\n");
CodeWord_t tmp;
for ( int i = 0 ; i < row; i++ ) {
tmp = Access ( i, m );
Access ( i, m ) = Access ( i, n );
Access ( i, n ) = Access ( i, m );
}
}
void Matrix::AddRow ( int desRow, int srcRow, CodeWord_t Coef )
{
CodeWord_t* desAddr = ( CodeWord_t * ) & Access ( desRow, 0 );
CodeWord_t* srcAddr = ( CodeWord_t * ) & Access ( srcRow, 0 );
RegionMultiply ( srcAddr, ( int ) Coef, COL_SIZE, desAddr, 1, sizeof ( CodeWord_t ) );
}
bool Matrix::IsRelated()
{
//printf ( "Enter Matrix::IsRelate()\n" );
// Since in Each step, we use the precode rule. So the Coeffeicnet row, except last one
// forms a up-triangle form. We make use of this propety to accelarate the
// program
bool upTriFlag = true; // the flag to check whether the Coeffeicnet , except last row forms a up-triangle form or not
int i, j;
for ( i = 0; i < ( row-1 ); i++ ) { // don't include last row
for ( j = 0; j < ( row-1 ); j++ ) {
if ( ( i == j ) && ( Access ( i, j ) == 0 ) ) {
upTriFlag = false;
break;
}
if ( ( i > j ) && ( Access ( i, j ) !=0 ) ) {
printf("i: %d j: %d\n", i, j);
upTriFlag = false;
break;
}
}
if ( upTriFlag == false ) {
break;
}
}
if ( upTriFlag == false ) { // flag is flase means there is some problems in the last PreDecode function
std::cerr << "[ERROR] in Matrix::IsRelated()" << std::endl;
std::cerr << "i: " << i << "j: " << j << std::endl;
exit ( 1 );
}
bool relatedFlag = true;
for ( j = ( row-1 ); j < col ; j++ ) {
if ( Access ( row-1, j ) != 0 ) {
relatedFlag = false;
break;
}
}
return relatedFlag;
}
void File::PreDecode()
{
//printf ( "Enter File::PreDecode()\n" );
int row = coefMat_.row;
int col = coefMat_.col;
int i = 0, j = 0;
// transform the Matrix into a UpTriangle Form
for ( j = 0; j < ( row-1 ); j++ ) {
CodeWord_t coef = Divide ( coefMat_.Access ( row-1, j ),
coefMat_.Access ( j, j ) );
coefMat_.AddRow ( row-1, j, coef );
}
if ( coefMat_.Access ( row-1, row-1 ) == 0 ) {
// find the first nonzelo element in row and column with A(i,j)!=0
for ( j = row; j < col; j ++ ) {
if ( coefMat_.Access(row-1, j) != 0 ) {
break;
}
}
if ( j == col ) { // could not find such a column
std::cerr << "Matrix::PreDeocde(), the matrix is not full rank" << std::endl;
exit ( 1 );
} else { // swap the two columns
coefMat_.SwapCol ( row-1, j );
invMat_.SwapCol ( row-1, j );
}
}
}
CodeWord_t GenRand ( int fieldSize )
{
if ( fieldSize > sizeof ( unsigned int ) * 8 ) {
std::cerr << "fieldSize is twoo large" << std::endl;
return NULL;
}
unsigned int i = rand();
CodeWord_t randNum;
memcpy ( ( BYTE* ) &randNum, ( BYTE* ) &i, fieldSize / 8 );
return randNum;
}
void RegionMultiply ( CodeWord_t* data, CodeWord_t coef, int dataSize, CodeWord_t* res, int add, int codeWordSize )
{
switch ( codeWordSize ) {
case sizeof ( BYTE ) :
galois_w08_region_multiply ( ( char* ) data,
( int ) coef,
dataSize * codeWordSize,
( char* ) res,
add );
break;
case 2*sizeof ( BYTE ) :
galois_w16_region_multiply ( ( char* ) data,
( int ) coef,
dataSize * codeWordSize,
( char* ) res, add );
break;
case 4*sizeof ( BYTE ) :
galois_w32_region_multiply ( ( char* ) data,
( int ) coef,
dataSize * codeWordSize,
( char* ) res, add );
break;
default:
std::cout << "Don't support CodeWordSize [" << codeWordSize<< "]" << std::endl;
}
}
CodeWord_t Multiply ( CodeWord_t x, CodeWord_t y )
{
//int res = galois_logtable_multiply ( ( int ) x, ( int ) y, sizeof ( CodeWord_t ) *8 );
int res = galois_shift_multiply ( ( int ) x, ( int ) y, sizeof ( CodeWord_t ) *8 );
return ( CodeWord_t ) res;
}
CodeWord_t Divide ( CodeWord_t& x, CodeWord_t& y )
{
//printf ( "line25\n" );
//int res = galois_logtable_divide ( ( int ) x, ( int ) y, sizeof ( CodeWord_t ) *8 );
if ( (((int) x) < 0) || (((int) y) < 0) ) {
std::cerr << "ERROR in Divide()" << std::endl;
exit(1);
}
int res = galois_single_divide ( ( int ) x, ( int ) y, sizeof ( CodeWord_t ) * 8 );
return ( CodeWord_t ) res;
}
void PrintCodeWord ( CodeWord_t word )
{
int k;
for ( k = 8 * sizeof ( CodeWord_t ) -1; k >= 0 ; k-- ) {
if ( ( word & ( 1 << k ) ) == 0 ) {
std::cout << "0";
} else {
std::cout << "1";
}
}
std::cout << "\n";
}
void PrintCodeWord ( CodeWord_t word, char op) {
int k;
for ( k = 8 * sizeof ( CodeWord_t ) -1; k >= 0 ; k-- ) {
if ( ( word & ( 1 << k ) ) == 0 ) {
std::cout << "0";
} else {
std::cout << "1";
}
}
std::cout << op;
}
void PrintCodeWord ( CodeWord_t* wordP, int n )
{
int j, k;
for ( j = 0; j < n; j++ ) {
CodeWord_t word = * ( wordP + j );
for ( k = 8 * sizeof ( CodeWord_t ) -1; k >= 0 ; k-- ) {
if ( ( word & ( 1 << k ) ) == 0 ) {
std::cout << "0";
} else {
std::cout << "1";
}
}
std::cout << "\t";
}
std::cout << std::endl;
}
void PrintCoef ( Matrix mat )
{
std::cout << "*****************************" << std::endl;
std::cout << "row: " << mat.row << " col: " << mat.col << std::endl;
int i, j, k;
std::cout << "\t\t";
for ( j = 0; j < mat.col; j ++) {
std::cout << j << "\t\t";
}
std::cout << std::endl;
for ( i = 0; i < mat.row; i++ ) {
std::cout << "Row [" << i << "] ";
for ( j = 0; j < mat.col; j++ ) {
for ( k = 8 * sizeof ( CodeWord_t ) -1; k >= 0 ; k-- ) {
CodeWord_t word = mat.Access ( i,j );
if ( ( word & ( 1 << k ) ) == 0 ) {
std::cout << "0";
} else {
std::cout << "1";
}
}
std::cout << "\t";
}
std::cout << std::endl;
}
std::cout << "*****************************" << std::endl << std::endl;
}
| 32.615108 | 125 | 0.446785 | [
"transform"
] |
9041424231db027ac42cfa8de5da661edd8a1763 | 5,005 | hpp | C++ | include/calib/cameraCalibration.hpp | mtszkw/foosball | 764d559546ad3eb8fc6c2ea895d5ef4eb1b5f1a3 | [
"MIT"
] | 23 | 2018-07-06T07:37:03.000Z | 2020-05-10T05:35:09.000Z | include/calib/cameraCalibration.hpp | mtszkw/foosball | 764d559546ad3eb8fc6c2ea895d5ef4eb1b5f1a3 | [
"MIT"
] | 1 | 2018-12-13T14:07:37.000Z | 2018-12-13T16:21:01.000Z | include/calib/cameraCalibration.hpp | mtszkw/foosball | 764d559546ad3eb8fc6c2ea895d5ef4eb1b5f1a3 | [
"MIT"
] | 9 | 2018-10-02T19:19:30.000Z | 2021-01-18T15:30:28.000Z | #pragma once
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cstdio>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/highgui.hpp>
class Settings
{
public:
Settings() : goodInput(false) {}
enum Pattern { NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
enum InputType { INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST };
void write(cv::FileStorage& fs) const; //Write serialization for this class
void read(const cv::FileNode& node); // Read serialization for this class
void validate();
cv::Mat nextImage();
static bool readStringList(const std::string& filename, std::vector<std::string>& l);
static bool isListOfImages(const std::string& filename);
public:
cv::Size boardSize; // The size of the board -> Number of items by width and height
Pattern calibrationPattern; // One of the Chessboard, circles, or asymmetric circle pattern
float squareSize; // The size of a square in your defined unit (point, millimeter,etc).
int nrFrames; // The number of frames to use from the input for calibration
float aspectRatio; // The aspect ratio
int delay; // In case of a video input
int skip; // Frames to be skipped
bool writePoints; // Write detected feature points
bool writeExtrinsics; // Write extrinsic parameters
bool calibZeroTangentDist; // Assume zero tangential distortion
bool calibFixPrincipalPoint; // Fix the principal point at the center
bool flipVertical; // Flip the captured images around the horizontal axis
std::string outputFileName; // The name of the file where to write
bool showUndistorsed; // Show undistorted images after calibration
std::string input; // The input ->
bool useFisheye; // use fisheye camera model for calibration
bool fixK1; // fix K1 distortion coefficient
bool fixK2; // fix K2 distortion coefficient
bool fixK3; // fix K3 distortion coefficient
bool fixK4; // fix K4 distortion coefficient
bool fixK5; // fix K5 distortion coefficient
int cameraID;
std::vector<std::string> imageList;
size_t atImageList;
cv::VideoCapture inputCapture;
InputType inputType;
bool goodInput;
int flag;
private:
std::string patternToUse;
};
namespace calibration
{
class CameraCalibration
{
private:
cv::Mat cameraMatrix;
cv::Mat distCoeffs;
std::string inputSettingsFile = "default.xml";
std::string calibrationFileName;
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
bool runCalibrationAndSave(Settings& s, cv::Size imageSize, cv::Mat& cameraMatrix,
cv::Mat& distCoeffs, std::vector<std::vector<cv::Point2f>> imagePoints);
static double computeReprojectionErrors(const std::vector<std::vector<cv::Point3f> >& objectPoints,
const std::vector<std::vector<cv::Point2f> >& imagePoints,
const std::vector<cv::Mat>& rvecs, const std::vector<cv::Mat>& tvecs,
const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs,
std::vector<float>& perViewErrors, bool fisheye);
static void calcBoardCornerPositions(cv::Size boardSize, float squareSize,
std::vector<cv::Point3f>& corners, Settings::Pattern patternType /*= Settings::CHESSBOARD*/);
static bool runCalibration(Settings& s, cv::Size& imageSize, cv::Mat& cameraMatrix,
cv::Mat& distCoeffs, std::vector<std::vector<cv::Point2f> > imagePoints,
std::vector<cv::Mat>& rvecs, std::vector<cv::Mat>& tvecs, std::vector<float>& reprojErrs,
double& totalAvgErr);
static void saveCameraParams(Settings& s, cv::Size& imageSize, cv::Mat& cameraMatrix,
cv::Mat& distCoeffs, const std::vector<cv::Mat>& rvecs, const std::vector<cv::Mat>& tvecs,
const std::vector<float>& reprojErrs,
const std::vector<std::vector<cv::Point2f> >& imagePoints, double totalAvgErr);
void loadCalibrationFile();
public:
static void help();
cv::Mat getUndistortedImage(cv::Mat distortedImage);
CameraCalibration() {};
CameraCalibration(std::string inputSettingsFile) : inputSettingsFile(inputSettingsFile) {}
CameraCalibration(std::string inputSettingsFile,
std::string calibrationFileName) : CameraCalibration(inputSettingsFile)
{
this->calibrationFileName = calibrationFileName;
if(!calibrationFileName.empty()) {
loadCalibrationFile();
}
}
bool init();
};
}
| 40.691057 | 105 | 0.636963 | [
"vector",
"model"
] |
9044323f05bf69c83152d0af0fa5b70ff8cad381 | 805 | hpp | C++ | include/protowork.hpp | yicuiheng/protowork | 55e048f9f8c1fc6b8ecf495425424c1694e64a60 | [
"MIT"
] | null | null | null | include/protowork.hpp | yicuiheng/protowork | 55e048f9f8c1fc6b8ecf495425424c1694e64a60 | [
"MIT"
] | 1 | 2021-06-13T13:31:04.000Z | 2021-06-13T13:31:04.000Z | include/protowork.hpp | yicuiheng/protowork | 55e048f9f8c1fc6b8ecf495425424c1694e64a60 | [
"MIT"
] | null | null | null | #ifndef PROTOWORK_HPP
#define PROTOWORK_HPP
#include <memory>
#include <unordered_map>
#include <vector>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <protowork/input.hpp>
#include <protowork/world.hpp>
#include <protowork/ui.hpp>
struct GLFWwindow;
namespace protowork {
struct app_t {
struct config_t {
std::size_t width;
std::size_t height;
const char *title;
};
explicit app_t(config_t const &);
explicit app_t(std::size_t width, std::size_t height, const char *title)
: app_t{config_t{width, height, title}} {}
~app_t();
void update();
void draw() const;
bool should_close() const;
world_t world;
ui_t ui;
private:
GLFWwindow *m_window = nullptr;
input_t m_input;
};
} // namespace protowork
#endif
| 17.12766 | 76 | 0.66087 | [
"vector"
] |
90448b7f4b024c4b19284441c0085ea3f438afbc | 1,813 | cpp | C++ | SegmentationThingy/segmentation.cpp | aravindarc/tamil_hocr_training | edf7ba7ac22178d946f68d618feb4699df65b946 | [
"MIT"
] | null | null | null | SegmentationThingy/segmentation.cpp | aravindarc/tamil_hocr_training | edf7ba7ac22178d946f68d618feb4699df65b946 | [
"MIT"
] | null | null | null | SegmentationThingy/segmentation.cpp | aravindarc/tamil_hocr_training | edf7ba7ac22178d946f68d618feb4699df65b946 | [
"MIT"
] | null | null | null | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat3b img = imread("test1.jpg");
Mat1b bin;
cvtColor(img, bin, COLOR_BGR2GRAY);
bin = bin < 200;
vector<Point> pts;
findNonZero(bin, pts);
RotatedRect box = minAreaRect(pts);
cout << box.size.width << ", " << box.size.height << endl;
Point2f vertices[4];
box.points(vertices);
for(int i=0; i<4; i++)
line(img, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0));
Mat1b rotated;
Mat M = getRotationMatrix2D(box.center, box.angle, 1.0);
warpAffine(bin, rotated, M, bin.size());
Mat1f horProj;
reduce(rotated, horProj, 1, CV_REDUCE_AVG);
// Remove noise in histogram. White bins identify space lines, black bins identify text lines
float th = 0;
Mat1b hist = horProj <= th;
// Get mean coordinate of white white pixels groups
vector<int> ycoords;
int y = 0;
int count = 0;
bool isSpace = false;
for (int i = 0; i < rotated.rows; ++i)
{
if (!isSpace)
{
if (hist(i))
{
isSpace = true;
count = 1;
y = i;
}
}
else
{
if (!hist(i))
{
isSpace = false;
ycoords.push_back(y / count);
}
else
{
y += i;
count++;
}
}
}
// Draw line as final result
Mat3b result;
cvtColor(rotated, result, COLOR_GRAY2BGR);
for (int i = 0; i < ycoords.size(); ++i)
{
line(result, Point(0, ycoords[i]), Point(result.cols, ycoords[i]), Scalar(0, 255, 0));
}
imwrite("bin.jpg", result);
return 0;
} | 22.382716 | 97 | 0.506895 | [
"vector"
] |
904835967f0e1c0c5d7771bf4aea1e1fead0b75f | 2,596 | cpp | C++ | frameworks/core/components/grid_layout/grid_layout_element.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/core/components/grid_layout/grid_layout_element.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/core/components/grid_layout/grid_layout_element.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:50.000Z | 2021-09-13T11:17:50.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "core/components/grid_layout/grid_layout_element.h"
#include "base/log/log.h"
#include "base/utils/utils.h"
#include "core/components/grid_layout/grid_layout_component.h"
#include "core/components/grid_layout/render_grid_layout.h"
#include "core/components/proxy/render_item_proxy.h"
#include "core/pipeline/base/composed_element.h"
namespace OHOS::Ace {
RefPtr<RenderNode> GridLayoutElement::CreateRenderNode()
{
return ComponentGroupElement::CreateRenderNode();
}
void GridLayoutElement::Update()
{
ComponentGroupElement::Update();
}
bool GridLayoutElement::RequestNextFocus(bool vertical, bool reverse, const Rect& rect)
{
RefPtr<RenderGridLayout> grid = AceType::DynamicCast<RenderGridLayout>(renderNode_);
if (!grid) {
LOGE("Render grid is null.");
return false;
}
LOGI("RequestNextFocus vertical:%{public}d reverse:%{public}d.", vertical, reverse);
bool ret = false;
while (!ret) {
int32_t focusIndex = grid->RequestNextFocus(vertical, reverse);
int32_t size = GetChildrenList().size();
if (focusIndex < 0 || focusIndex >= size) {
return false;
}
auto iter = GetChildrenList().begin();
std::advance(iter, focusIndex);
auto focusNode = *iter;
if (!focusNode) {
LOGE("Target focus node is null.");
return false;
}
// If current Node can not obtain focus, move to next.
ret = focusNode->RequestFocusImmediately();
}
return ret;
}
void GridLayoutElement::ApplyRenderChild(const RefPtr<RenderElement>& renderChild)
{
if (!renderChild) {
LOGE("Element child is null");
return;
}
if (!renderNode_) {
LOGE("RenderElement don't have a render node");
return;
}
auto proxy = RenderItemProxy::Create();
proxy->AddChild(renderChild->GetRenderNode());
proxy->Attach(context_);
renderNode_->AddChild(proxy);
}
} // namespace OHOS::Ace | 31.277108 | 88 | 0.681433 | [
"render"
] |
904f6d636b2612a8ab8178e7b835dedb4bdfada1 | 10,956 | cpp | C++ | projects/RealTimeEngine/code/Application.cpp | Nechrito/s0009d-lab-env | 61599401536205c344654ef2a270a010df0e2254 | [
"MIT"
] | null | null | null | projects/RealTimeEngine/code/Application.cpp | Nechrito/s0009d-lab-env | 61599401536205c344654ef2a270a010df0e2254 | [
"MIT"
] | null | null | null | projects/RealTimeEngine/code/Application.cpp | Nechrito/s0009d-lab-env | 61599401536205c344654ef2a270a010df0e2254 | [
"MIT"
] | null | null | null | // Copyright © 2020 Philip Lindh
// All rights reserved
#include "config.h"
#include "Application.h"
#include "Model.h"
#include "LightNode.h"
#include "SoftwareRenderer.h"
#include "Screen.h"
#include "Camera.h"
#include <cmath>
Application::Application()
{
// window
this->window = nullptr;
this->windowTitle = this->baseTitleString = "Philip Lindh | Check The Console! | ";
// camera
Camera::Instance().SetViewport(width, height);
Camera::Instance().SetFieldOfView(65.0f, 0.1f, 10.0f);
Camera::Instance().SetPosition(Vector3(0, -4, -8));
}
bool Application::Open()
{
App::Open();
// Initialize window with a set of rules
this->window = new Display::Window;
this->window->SetSize(width, height);
this->window->SetTitle(windowTitle);
// Subscribe to callback functions
this->window->SetMouseMoveFunction([this] (const double x, const double y)
{
Camera::Instance().Rotate(width * 0.5 - x, height * 0.5 - y);
this->window->SetCursorPosition(width * 0.5, height * 0.5);
});
this->window->SetMouseScrollFunction([] (float x, const float y)
{
Camera::Instance().Zoom(y);
});
this->window->SetKeyPressFunction([this] (int32, const int32 button, const int32 action, int32)
{
const auto iterator = find(cachedKeys.begin(), cachedKeys.end(), button);
if (action == 0)
{
if (iterator != cachedKeys.end()) // clear all cached keys which have been released
cachedKeys.erase(iterator);
}
else if (iterator == cachedKeys.end()) // insert new pushed down key
cachedKeys.push_back(button);
// released shift
if (action == 0 && sprint && button == 50)
sprint = false;
// current key isn't being pressed, boring
if (action != 1)
return;
switch (button)
{
case 9: exit(0); /*this->window->Close();*/ break; // Esc
case 11: rotateModel = !rotateModel; break; // 2
case 14: cpuRender = !cpuRender; break; // 5
case 50: sprint = !sprint; break; // Shift
case 10: // 1
{
drawWireframe = !drawWireframe;
if (drawWireframe)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
break;
case 12: // 3
{
if (cpuRender)
{
std::cout << "Sorry, the light type is currently enforced for CPU-Rendering\n";
return;
}
const int next = int(activeLightType) + 1;
const int index = next >= 3 ? 0 : next;
this->activeLightType = LightType(index);
}
break;
case 13: // 4
{
for (auto& light : lightNodes)
{
if (light.GetCurrentGamma() == 1.0f)
light.SetGamma(1.6f);
else
light.SetGamma(1.0f);
}
}
break;
case 24: Camera::Instance().SetCameraMode(CameraMode::ORBIT); break; // Q
case 26: Camera::Instance().SetCameraMode(CameraMode::FREELOOK); break; // E
case 27: Camera::Instance().SetCameraMode(CameraMode::FORCED); break; // R
}
});
return this->window->Open();
}
void Application::Run()
{
// Hides unseen faces through culling, can be seen through wireframe-mode
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
// Models
Model* lightModel = new Model("models/Sun/cube.obj", "shaders/model.glsl", Vector3(0, 12, 10));
Model* landscape = new Model("models/Landscape/landscape.obj", "shaders/phong.glsl");
//Model* targetModel = new Model("models/Fox/Fox.obj", "shaders/phong.glsl", Vector3(0, 0.1, 0));
Model* targetModel = new Model("models/FoxGLTF/Fox.gltf", "shaders/phong.glsl", Vector3(0, 0.1, 0));
// Lights
this->lightNodes.emplace_back(lightModel, LightType::SPOTLIGHT);
this->lightNodes.emplace_back(lightModel, LightType::POINTLIGHT);
this->lightNodes.emplace_back(lightModel, LightType::DIRECTLIGHT);
// Shaders
const auto vertexShader = [] (Vertex& vertex, Matrix4x4& model, Matrix4x4& view, Matrix4x4& projection) -> Vertex
{
const Vector4 position = (projection * view * model).Transpose() * vertex.Position;
return { position, vertex.Normal, vertex.TextureCoordinates };
};
const auto fragmentShader = [this] (Vertex& vertex, Texture& texture, Material& material) -> Vector3
{
const Vector3 textureColor = TextureResource::GetTextureColor(texture, vertex.TextureCoordinates);
//return textureColor; // <-- Un-Comment this to discard lightning
const Vector3 vPosition = vertex.Position.To3D();
const Vector3 cPosition = Camera::Instance().GetPosition();
Vector3 result;
Vector3 lPosition;
Vector3 lightColor;
for (LightNode& light : lightNodes)
{
if (light.GetType() != this->activeLightType)
{
continue;
}
lPosition = light.GetPosition();
lightColor = light.GetColor();
}
const Vector3 lightDir = (lPosition - vPosition).Normalized();
const Vector3 normal = vertex.Normal.Normalized().To3D();
const Vector3 viewDir = (cPosition - vPosition).Normalized();
Vector3 ambient = lightColor * material.Ambient;
Vector3 diffuse = lightColor * material.Diffuse * std::max(normal.Dot(lightDir), 0.0f);
const Vector3 reflection = (lightDir * -1).Reflect(normal);
const float specularValue = CMath::Saturate(viewDir.Dot(reflection));
const float lambertian = CMath::Pow(specularValue, material.SpecularExponent);
Vector3 specular = lightColor * material.Specular * lambertian;
const float distance = lPosition.Distance(vPosition);
const float attenuation = 1.0f / (1.0f + 0.14f * distance + 0.07f * (distance * distance));
ambient *= attenuation;
diffuse *= attenuation;
specular *= attenuation;
const Vector3 combined = ambient + diffuse + specular;
result += Vector3::Saturate(combined);
return result * textureColor;
};
// Software-renderer
SoftwareRenderer renderer;
renderer.SetVertexShader(vertexShader);
renderer.SetPixelShader(fragmentShader);
// Node-container for objects we'd like to render
Screen screen(renderer);
screen.AddRenderableObject(lightModel);
screen.AddRenderableObject(targetModel);
screen.AddRenderableObject(landscape);
// Entities referenced shader
std::vector<Shader> shaders;
shaders.push_back(*targetModel->GetShader());
shaders.push_back(*landscape->GetShader());
// Force-centre the cursor when done loading
this->window->SetCursorPosition(width * 0.5, height * 0.5);
this->window->SetCursorVisibility(false);
// Prints a simple input guide to the console
std::cout << "\n-----KEYBOARD INPUT-----\n";
std::cout << "Escape: Quits the application\n";
std::cout << "1: Toggle Wireframe\n";
std::cout << "2: Toggle Model Rotation\n";
std::cout << "3: Change Active Light\n";
std::cout << "4: Toggle Gamma\n";
std::cout << "5: Toggle Render (CPU / GPU)\n";
std::cout << "\n";
std::cout << "Arrow Up: Increase Light Intensity\n";
std::cout << "Arrow Down: Decrease Light Intensity\n";
std::cout << "\n";
std::cout << "Q: Camera Orbit\n";
std::cout << "E: Camera Free-look\n";
std::cout << "R: Camera Look At Target\n";
std::cout << "---------LINUX----------\n";
// time since launch, used for computing the fps
// todo: can be changed to CMath, but gotta debug to determine which is faster
double start = glfwGetTime();
while (this->window->IsOpen())
{
// Processes callback functions such as keyboard/mouse input
this->window->Update();
// Clear screen
glClearColor(0.5f, 0.3f, 0.65f, 1);
//glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Adding one frame for each iteration
this->frameCount++;
// Keys which are currently being pressed
for (auto& key : cachedKeys)
{
switch (key)
{
case 25: Camera::Instance().Translate(CameraDirection::FORWARD, deltaTime, sprint); break; // W
case 38: Camera::Instance().Translate(CameraDirection::LEFT, deltaTime, sprint); break; // A
case 39: Camera::Instance().Translate(CameraDirection::BACKWARD, deltaTime, sprint); break; // S
case 40: Camera::Instance().Translate(CameraDirection::RIGHT, deltaTime, sprint); break; // D
case 111: for (auto& light : lightNodes) light.IncreaseIntensity(deltaTime); break; // Up
case 116: for (auto& light : lightNodes) light.DecreaseIntensity(deltaTime); break; // Down
}
}
// Rotation
if (this->rotateModel)
{
targetModel->Rotate(deltaTime * 50);
}
// Set direction towards the targeted model
Vector3 targetPosition = targetModel->GetPosition();
Camera::Instance().SetTarget(targetPosition);
// Fetch what makes up the camera-perspective by far/near - plane
Matrix4x4 view = Camera::Instance().View(currentTime);
Matrix4x4 projection = Camera::Instance().Projection();
for (auto& light : lightNodes)
{
if (light.GetType() != this->activeLightType)
{
continue;
}
if (light.GetType() == LightType::POINTLIGHT)
{
const auto orbitRadius = 10;
const auto lightSpeed = 0.65;
const auto orbitX = sin(currentTime * lightSpeed) * orbitRadius;
const auto orbitZ = cos(currentTime * lightSpeed) * orbitRadius;
light.SetPosition(Vector3(orbitX, 5, orbitZ) + targetPosition);
light.SetDirection(targetPosition);
}
light.SetCameraPosition(Camera::Instance().GetPosition());
light.Render(view, projection, shaders);
}
// Render
if (this->cpuRender)
{
screen.Draw(view, projection);
}
else
{
targetModel->Draw(view, projection);
landscape->Draw(view, projection);
}
// Swaps front & back buffers of the window
this->window->SwapBuffers();
// Time between current and previous frame, useful to limit movement as compute speed differs with unlocked frame-rate
// Can also be used for timers
this->currentTime = glfwGetTime();
this->deltaTime = currentTime - lastFrame;
this->lastFrame = currentTime;
// FPS counter
const double timeElapsed = currentTime - start;
if (timeElapsed >= 0.5)
{
this->fps = frameCount / timeElapsed;
std::string selectedLight;
switch (activeLightType)
{
case LightType::DIRECTLIGHT: selectedLight = "DirectLight"; break;
case LightType::POINTLIGHT: selectedLight = "PointLight"; break;
case LightType::SPOTLIGHT: selectedLight = "SpotLight"; break;
}
std::string fpsFormatted = fps <= 10 ? CString::FormatString("%.1f", fps) : CString::FormatString("%.0f", fps);
std::string title = windowTitle.append(selectedLight).append(" | FPS: ").append(fpsFormatted);
this->window->SetTitle(title);
this->windowTitle = this->baseTitleString;
this->frameCount = 0;
start = glfwGetTime();
}
}
delete targetModel;
delete landscape;
}
| 30.689076 | 121 | 0.658726 | [
"render",
"vector",
"model"
] |
9057688aa16dcfbc2c8e90e7cff5b6a289120b81 | 2,673 | cpp | C++ | src/libbu/semaphore_register.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 83 | 2021-03-10T05:54:52.000Z | 2022-03-31T16:33:46.000Z | src/libbu/semaphore_register.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 13 | 2021-06-24T17:07:48.000Z | 2022-03-31T15:31:33.000Z | src/libbu/semaphore_register.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 54 | 2021-03-10T07:57:06.000Z | 2022-03-28T23:20:37.000Z | /* S E M A P H O R E _ R E G I S T E R . C P P
* BRL-CAD
*
* Copyright (c) 2019-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
#include "common.h"
#include <vector>
#include "bu/str.h"
#include "bu/parallel.h"
/* #define DEBUGSEM 1 */
#ifdef DEBUGSEM
# include <iostream>
#endif
static const int SEM_LOCK = 1;
static std::vector<const char *> &
semaphore_registry(bool wipe = false)
{
/* semaphore #1 is used internally here and only here, so we start with it */
static std::vector<const char *> semaphores = {"SEM_LOCK"};
if (wipe) {
#ifdef DEBUGSEM
std::cout << "!!! clearing " << semaphores.size() << " semaphores" << std::endl;
for (size_t i = 0; i < semaphores.size(); i++) {
std::cout << "!!! found " << semaphores[i] << " = " << i+1 << std::endl;
}
#endif
bu_semaphore_acquire(SEM_LOCK);
semaphores.clear();
bu_semaphore_release(SEM_LOCK);
}
return semaphores;
}
extern "C" void
semaphore_clear(void)
{
(void)semaphore_registry(true);
}
static size_t
semaphore_registered(const char *name)
{
const std::vector<const char *> &semaphores = semaphore_registry();
for (size_t i = 0; i < semaphores.size(); ++i) {
if (BU_STR_EQUAL(semaphores[i], name)) {
#ifdef DEBUGSEM
printf("!!! found %s = %zu\n", semaphores[i], i+1);
#endif
return i+1;
}
}
return 0;
}
extern "C" int
bu_semaphore_register(const char *name)
{
std::vector<const char *> &semaphores = semaphore_registry();
#ifdef DEBUGSEM
printf("!!! registering %s (have %zu)\n", name, semaphores.size());
#endif
bu_semaphore_acquire(SEM_LOCK);
size_t idx = semaphore_registered(name);
if (!idx) {
semaphores.push_back(name);
idx = semaphores.size();
}
bu_semaphore_release(SEM_LOCK);
#ifdef DEBUGSEM
printf("!!! added %s = %zu\n", name, idx);
#endif
return idx;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 23.243478 | 81 | 0.664422 | [
"cad",
"vector"
] |
905ccf7f94c34a3bfa7370341a70fa226453a4e1 | 3,808 | hpp | C++ | Jackal/Source/RenderDevice/Public/RenderDevice/GraphicsPipelineState.hpp | CheezBoiger/Jackal | 6c87bf19f6c1cd63f53c815820b32fc71b48bf77 | [
"MIT"
] | null | null | null | Jackal/Source/RenderDevice/Public/RenderDevice/GraphicsPipelineState.hpp | CheezBoiger/Jackal | 6c87bf19f6c1cd63f53c815820b32fc71b48bf77 | [
"MIT"
] | null | null | null | Jackal/Source/RenderDevice/Public/RenderDevice/GraphicsPipelineState.hpp | CheezBoiger/Jackal | 6c87bf19f6c1cd63f53c815820b32fc71b48bf77 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 Jackal Engine, MIT License.
#pragma once
#include "Core/Platform/JTypes.hpp"
#include "Core/Platform/Api.hpp"
#include "Core/Platform/Platform.hpp"
#include "Core/Structure/JString.hpp"
#include "RenderDeviceTypes.hpp"
#include "MaterialLayout.hpp"
#include "RenderObject.hpp"
namespace jackal {
class Shader;
struct VertexAttributeT {
uint32 Binding;
uint32 Location;
FormatT Format;
uint32 Offset;
};
struct VertexBindingInfoT {
uint32 Binding;
uint32 Stride;
VertexInputRate InputRate;
uint32 VertexAttributesCount;
VertexAttributeT* VertexAttribute;
};
// Graphics Pipeline information. This information is
// sent through the graphics pipeline state object to parse
// and set values.
typedef struct {
// Add a Vertex Shader to the rendering pipeline. This is
// MANDATORY or else the pipeline state will not function,
// or even build.
Shader* VertexShader;
// Add a Hull Shader to the rendering pipeline. This is optional.
// Best to leave this null if not in use.
Shader* HullShader;
// Add a Domain Shader to the rendering pipeline. This is optional.
// Best to leave this null if not in use.
Shader* DomainShader;
// Add a Geometry Shader to the rendering pipeline. This is optional.
// Best to leave this null if not in use.
Shader* GeometryShader;
// Add a Pixel Shader to the rendering pipeline. This is optional.
// Best to leave this null if not in use.
Shader* PixelShader;
BlendT SrcBlendMode;
BlendT DstBlendMode;
BlendOperationT BlendOp;
CullModeT CullMode;
FrontFaceT FrontFace;
CompareT DepthTestCompare;
TopologyT Topology;
VertexBindingInfoT VertexBindingInfo;
// This is the layout of the Graphics Pipeline shaders, in terms of how
// samplers, uniforms, and data is laid out in shader code. Pipeline needs
// reference to the material layout that defines how data given it will be
// used.
MaterialLayout* Layout;
bool8 ZBufferEnable : 1,
StencilEnable : 1,
BlendEnable : 1,
CullFaceEnable : 1;
} GraphicsPipelineInfoT;
struct GraphicsPipelineStateInfo {
BlendT SrcBlendMode;
BlendT DstBlendMode;
BlendOperationT BlendOp;
CullModeT CullMode;
FrontFaceT FrontFace;
CompareT DepthTestCompare;
TopologyT Topology;
VertexBindingInfoT VertexBindingInfo;
// This is the layout of the Graphics Pipeline shaders, in terms of how
// samplers, uniforms, and data is laid out in shader code. Pipeline needs
// reference to the material layout that defines how data given it will be
// used.
MaterialLayout* Layout;
bool8 ZBufferEnable : 1,
StencilEnable : 1,
BlendEnable : 1,
CullFaceEnable : 1;
};
// Graphics pipeline state object. Used to set up the rendering
// pipeline of the render device.
class GraphicsPipelineState : public RenderObject {
protected:
GraphicsPipelineState() { }
public:
virtual ~GraphicsPipelineState() { }
// Set the pipeline state of this rendering pipe. This function will
// bake the info provided to this pipeline, can not reverse this once
// done!
virtual void Bake(const GraphicsPipelineInfoT &info) = 0;
virtual void CleanUp() = 0;
// Get the information of this pipeline state.
GraphicsPipelineStateInfo *GetPipelineInformation() { return &mPipelineInfo; }
RenderErrorT GetLastError() { return mLastError; }
protected:
GraphicsPipelineStateInfo mPipelineInfo;
RenderErrorT mLastError;
};
} // jackal | 30.222222 | 80 | 0.67542 | [
"geometry",
"render",
"object"
] |
9068a4072ecf5f2b982360cfe2b1f007bac0e7b2 | 11,135 | cc | C++ | content/browser/renderer_host/gpu_message_filter.cc | SlimKatLegacy/android_external_chromium_org | ee480ef5039d7c561fc66ccf52169ead186f1bea | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | content/browser/renderer_host/gpu_message_filter.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | content/browser/renderer_host/gpu_message_filter.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2015-02-09T08:49:30.000Z | 2017-08-26T02:03:34.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "content/browser/renderer_host/gpu_message_filter.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "content/browser/gpu/browser_gpu_channel_host_factory.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "content/browser/renderer_host/render_widget_helper.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/port/browser/render_widget_host_view_frame_subscriber.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/service/gpu_switches.h"
namespace content {
struct GpuMessageFilter::CreateViewCommandBufferRequest {
CreateViewCommandBufferRequest(
int32 surface_id,
const GPUCreateCommandBufferConfig& init_params,
scoped_ptr<IPC::Message> reply)
: surface_id(surface_id),
init_params(init_params),
reply(reply.Pass()) {
}
int32 surface_id;
GPUCreateCommandBufferConfig init_params;
scoped_ptr<IPC::Message> reply;
};
struct GpuMessageFilter::FrameSubscription {
FrameSubscription(
int in_route_id,
scoped_ptr<RenderWidgetHostViewFrameSubscriber> in_subscriber)
: route_id(in_route_id),
surface_id(0),
subscriber(in_subscriber.Pass()),
factory(subscriber.get()) {
}
int route_id;
int surface_id;
scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber;
base::WeakPtrFactory<RenderWidgetHostViewFrameSubscriber> factory;
};
GpuMessageFilter::GpuMessageFilter(int render_process_id,
RenderWidgetHelper* render_widget_helper)
: gpu_process_id_(0),
render_process_id_(render_process_id),
share_contexts_(false),
render_widget_helper_(render_widget_helper),
weak_ptr_factory_(this) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(USE_AURA) || defined(OS_ANDROID)
// We use the GPU process for UI on Aura, and we need to share renderer GL
// contexts with the compositor context.
share_contexts_ = true;
#else
// Share contexts when compositing webview plugin or using share groups
// for asynchronous texture uploads.
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableBrowserPluginCompositing) ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableShareGroupAsyncTextureUpload))
share_contexts_ = true;
#endif
}
GpuMessageFilter::~GpuMessageFilter() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
EndAllFrameSubscriptions();
}
bool GpuMessageFilter::OnMessageReceived(
const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(GpuMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuHostMsg_EstablishGpuChannel,
OnEstablishGpuChannel)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuHostMsg_CreateViewCommandBuffer,
OnCreateViewCommandBuffer)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
void GpuMessageFilter::SurfaceUpdated(int32 surface_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
typedef std::vector<linked_ptr<CreateViewCommandBufferRequest> > RequestList;
RequestList retry_requests;
retry_requests.swap(pending_requests_);
for (RequestList::iterator it = retry_requests.begin();
it != retry_requests.end(); ++it) {
if ((*it)->surface_id != surface_id) {
pending_requests_.push_back(*it);
} else {
linked_ptr<CreateViewCommandBufferRequest> request = *it;
OnCreateViewCommandBuffer(request->surface_id,
request->init_params,
request->reply.release());
}
}
}
void GpuMessageFilter::BeginFrameSubscription(
int route_id,
scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
linked_ptr<FrameSubscription> subscription(
new FrameSubscription(route_id, subscriber.Pass()));
BeginFrameSubscriptionInternal(subscription);
}
void GpuMessageFilter::EndFrameSubscription(int route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
FrameSubscriptionList frame_subscription_list;
frame_subscription_list.swap(frame_subscription_list_);
for (FrameSubscriptionList::iterator it = frame_subscription_list.begin();
it != frame_subscription_list.end(); ++it) {
if ((*it)->route_id != route_id)
frame_subscription_list_.push_back(*it);
else
EndFrameSubscriptionInternal(*it);
}
}
void GpuMessageFilter::OnEstablishGpuChannel(
CauseForGpuLaunch cause_for_gpu_launch,
IPC::Message* reply_ptr) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
scoped_ptr<IPC::Message> reply(reply_ptr);
// TODO(apatrick): Eventually, this will return the route ID of a
// GpuProcessStub, from which the renderer process will create a
// GpuProcessProxy. The renderer will use the proxy for all subsequent
// communication with the GPU process. This means if the GPU process
// terminates, the renderer process will not find itself unknowingly sending
// IPCs to a newly launched GPU process. Also, I will rename this function
// to something like OnCreateGpuProcess.
GpuProcessHost* host = GpuProcessHost::FromID(gpu_process_id_);
if (!host) {
host = GpuProcessHost::Get(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
cause_for_gpu_launch);
if (!host) {
reply->set_reply_error();
Send(reply.release());
return;
}
gpu_process_id_ = host->host_id();
// Apply all frame subscriptions to the new GpuProcessHost.
BeginAllFrameSubscriptions();
}
host->EstablishGpuChannel(
render_process_id_,
share_contexts_,
base::Bind(&GpuMessageFilter::EstablishChannelCallback,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(&reply)));
}
void GpuMessageFilter::OnCreateViewCommandBuffer(
int32 surface_id,
const GPUCreateCommandBufferConfig& init_params,
IPC::Message* reply_ptr) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
scoped_ptr<IPC::Message> reply(reply_ptr);
GpuSurfaceTracker* surface_tracker = GpuSurfaceTracker::Get();
gfx::GLSurfaceHandle compositing_surface;
int renderer_id = 0;
int render_widget_id = 0;
bool result = surface_tracker->GetRenderWidgetIDForSurface(
surface_id, &renderer_id, &render_widget_id);
if (result && renderer_id == render_process_id_) {
compositing_surface = surface_tracker->GetSurfaceHandle(surface_id);
} else {
DLOG(ERROR) << "Renderer " << render_process_id_
<< " tried to access a surface for renderer " << renderer_id;
}
if (compositing_surface.parent_gpu_process_id &&
compositing_surface.parent_gpu_process_id != gpu_process_id_) {
// If the current handle for the surface is using a different (older) gpu
// host, it means the GPU process died and we need to wait until the UI
// re-allocates the surface in the new process.
linked_ptr<CreateViewCommandBufferRequest> request(
new CreateViewCommandBufferRequest(
surface_id, init_params, reply.Pass()));
pending_requests_.push_back(request);
return;
}
GpuProcessHost* host = GpuProcessHost::FromID(gpu_process_id_);
if (!host || compositing_surface.is_null()) {
// TODO(apatrick): Eventually, this IPC message will be routed to a
// GpuProcessStub with a particular routing ID. The error will be set if
// the GpuProcessStub with that routing ID is not in the MessageRouter.
reply->set_reply_error();
Send(reply.release());
return;
}
host->CreateViewCommandBuffer(
compositing_surface,
surface_id,
render_process_id_,
init_params,
base::Bind(&GpuMessageFilter::CreateCommandBufferCallback,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(&reply)));
}
void GpuMessageFilter::EstablishChannelCallback(
scoped_ptr<IPC::Message> reply,
const IPC::ChannelHandle& channel,
const gpu::GPUInfo& gpu_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
GpuHostMsg_EstablishGpuChannel::WriteReplyParams(
reply.get(), render_process_id_, channel, gpu_info);
Send(reply.release());
}
void GpuMessageFilter::CreateCommandBufferCallback(
scoped_ptr<IPC::Message> reply, int32 route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
GpuHostMsg_CreateViewCommandBuffer::WriteReplyParams(reply.get(), route_id);
Send(reply.release());
}
void GpuMessageFilter::BeginAllFrameSubscriptions() {
FrameSubscriptionList frame_subscription_list;
frame_subscription_list.swap(frame_subscription_list_);
for (FrameSubscriptionList::iterator it = frame_subscription_list.begin();
it != frame_subscription_list.end(); ++it) {
BeginFrameSubscriptionInternal(*it);
}
}
void GpuMessageFilter::EndAllFrameSubscriptions() {
for (FrameSubscriptionList::iterator it = frame_subscription_list_.begin();
it != frame_subscription_list_.end(); ++it) {
EndFrameSubscriptionInternal(*it);
}
frame_subscription_list_.clear();
}
void GpuMessageFilter::BeginFrameSubscriptionInternal(
linked_ptr<FrameSubscription> subscription) {
if (!subscription->surface_id) {
GpuSurfaceTracker* surface_tracker = GpuSurfaceTracker::Get();
subscription->surface_id = surface_tracker->LookupSurfaceForRenderer(
render_process_id_, subscription->route_id);
// If the surface ID cannot be found this subscription is dropped.
if (!subscription->surface_id)
return;
}
frame_subscription_list_.push_back(subscription);
// Frame subscriber is owned by this object, but it is shared with
// GpuProcessHost. GpuProcessHost can be destroyed in the case of crashing
// and we do not get a signal. This object can also be destroyed independent
// of GpuProcessHost. To ensure that GpuProcessHost does not reference a
// deleted frame subscriber, a weak reference is shared.
GpuProcessHost* host = GpuProcessHost::FromID(gpu_process_id_);
if (!host)
return;
host->BeginFrameSubscription(subscription->surface_id,
subscription->factory.GetWeakPtr());
}
void GpuMessageFilter::EndFrameSubscriptionInternal(
linked_ptr<FrameSubscription> subscription) {
GpuProcessHost* host = GpuProcessHost::FromID(gpu_process_id_);
// An empty surface ID means subscription has never started in GpuProcessHost
// so it is not necessary to end it.
if (!host || !subscription->surface_id)
return;
// Note that GpuProcessHost here might not be the same one that frame
// subscription has applied.
host->EndFrameSubscription(subscription->surface_id);
}
} // namespace content
| 36.870861 | 79 | 0.734261 | [
"object",
"vector"
] |
906b4e781a0e64a2592998209208b5e322c9da06 | 9,264 | cc | C++ | third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h"
#include "base/optional.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/skia/include/utils/SkNullCanvas.h"
namespace blink {
namespace {
bool IsColorGray(const SkColor& color) {
return abs(static_cast<int>(SkColorGetR(color)) -
static_cast<int>(SkColorGetG(color))) +
abs(static_cast<int>(SkColorGetG(color)) -
static_cast<int>(SkColorGetB(color))) <=
8;
}
bool IsColorTransparent(const SkColor& color) {
return (SkColorGetA(color) < 128);
}
const int kPixelsToSample = 1000;
const int kBlocksCount1D = 10;
const float kMinOpaquePixelPercentageForForeground = 0.2;
} // namespace
DarkModeImageClassifier::DarkModeImageClassifier()
: pixels_to_sample_(kPixelsToSample),
blocks_count_horizontal_(kBlocksCount1D),
blocks_count_vertical_(kBlocksCount1D) {}
DarkModeClassification DarkModeImageClassifier::Classify(
Image* image,
const FloatRect& src_rect,
const FloatRect& dest_rect) {
DarkModeClassification result = image->GetDarkModeClassification(src_rect);
if (result != DarkModeClassification::kNotClassified)
return result;
result = image->CheckTypeSpecificConditionsForDarkMode(dest_rect, this);
if (result != DarkModeClassification::kNotClassified) {
image->AddDarkModeClassification(src_rect, result);
return result;
}
auto features_or_null = GetFeatures(image, src_rect);
if (!features_or_null) {
// Do not cache this classification.
return DarkModeClassification::kDoNotApplyFilter;
}
result = ClassifyWithFeatures(features_or_null.value());
image->AddDarkModeClassification(src_rect, result);
return result;
}
base::Optional<DarkModeImageClassifier::Features>
DarkModeImageClassifier::GetFeatures(Image* image, const FloatRect& src_rect) {
SkBitmap bitmap;
if (!image->GetBitmap(src_rect, &bitmap))
return base::nullopt;
if (pixels_to_sample_ > src_rect.Width() * src_rect.Height())
pixels_to_sample_ = src_rect.Width() * src_rect.Height();
if (blocks_count_horizontal_ > src_rect.Width())
blocks_count_horizontal_ = floor(src_rect.Width());
if (blocks_count_vertical_ > src_rect.Height())
blocks_count_vertical_ = floor(src_rect.Height());
float transparency_ratio;
float background_ratio;
Vector<SkColor> sampled_pixels;
GetSamples(bitmap, &sampled_pixels, &transparency_ratio, &background_ratio);
// TODO(https://crbug.com/945434): Investigate why an incorrect resource is
// loaded and how we can fetch the correct resource. This condition will
// prevent going further with the rest of the classification logic.
if (sampled_pixels.size() == 0)
return base::nullopt;
return ComputeFeatures(sampled_pixels, transparency_ratio, background_ratio);
}
// Extracts sample pixels from the image. The image is separated into uniformly
// distributed blocks through its width and height, each block is sampled, and
// checked to see if it seems to be background or foreground.
void DarkModeImageClassifier::GetSamples(const SkBitmap& bitmap,
Vector<SkColor>* sampled_pixels,
float* transparency_ratio,
float* background_ratio) {
int pixels_per_block =
pixels_to_sample_ / (blocks_count_horizontal_ * blocks_count_vertical_);
int transparent_pixels = 0;
int opaque_pixels = 0;
int blocks_count = 0;
Vector<int> horizontal_grid(blocks_count_horizontal_ + 1);
Vector<int> vertical_grid(blocks_count_vertical_ + 1);
for (int block = 0; block <= blocks_count_horizontal_; block++) {
horizontal_grid[block] = static_cast<int>(round(
block * bitmap.width() / static_cast<float>(blocks_count_horizontal_)));
}
for (int block = 0; block <= blocks_count_vertical_; block++) {
vertical_grid[block] = static_cast<int>(round(
block * bitmap.height() / static_cast<float>(blocks_count_vertical_)));
}
sampled_pixels->clear();
Vector<IntRect> foreground_blocks;
for (int y = 0; y < blocks_count_vertical_; y++) {
for (int x = 0; x < blocks_count_horizontal_; x++) {
IntRect block(horizontal_grid[x], vertical_grid[y],
horizontal_grid[x + 1] - horizontal_grid[x],
vertical_grid[y + 1] - vertical_grid[y]);
Vector<SkColor> block_samples;
int block_transparent_pixels;
GetBlockSamples(bitmap, block, pixels_per_block, &block_samples,
&block_transparent_pixels);
opaque_pixels += static_cast<int>(block_samples.size());
transparent_pixels += block_transparent_pixels;
sampled_pixels->AppendRange(block_samples.begin(), block_samples.end());
if (opaque_pixels >
kMinOpaquePixelPercentageForForeground * pixels_per_block) {
foreground_blocks.push_back(block);
}
blocks_count++;
}
}
*transparency_ratio = static_cast<float>(transparent_pixels) /
(transparent_pixels + opaque_pixels);
*background_ratio =
1.0 - static_cast<float>(foreground_blocks.size()) / blocks_count;
}
// Selects samples at regular intervals from a block of the image.
// Returns the opaque sampled pixels, and the number of transparent
// sampled pixels.
void DarkModeImageClassifier::GetBlockSamples(const SkBitmap& bitmap,
const IntRect& block,
const int required_samples_count,
Vector<SkColor>* sampled_pixels,
int* transparent_pixels_count) {
*transparent_pixels_count = 0;
int x1 = block.X();
int y1 = block.Y();
int x2 = block.MaxX();
int y2 = block.MaxY();
DCHECK(x1 < bitmap.width());
DCHECK(y1 < bitmap.height());
DCHECK(x2 <= bitmap.width());
DCHECK(y2 <= bitmap.height());
sampled_pixels->clear();
int cx = static_cast<int>(
ceil(static_cast<float>(x2 - x1) / sqrt(required_samples_count)));
int cy = static_cast<int>(
ceil(static_cast<float>(y2 - y1) / sqrt(required_samples_count)));
for (int y = y1; y < y2; y += cy) {
for (int x = x1; x < x2; x += cx) {
SkColor new_sample = bitmap.getColor(x, y);
if (IsColorTransparent(new_sample))
(*transparent_pixels_count)++;
else
sampled_pixels->push_back(new_sample);
}
}
}
DarkModeImageClassifier::Features DarkModeImageClassifier::ComputeFeatures(
const Vector<SkColor>& sampled_pixels,
const float transparency_ratio,
const float background_ratio) {
int samples_count = static_cast<int>(sampled_pixels.size());
// Is image grayscale.
int color_pixels = 0;
for (const SkColor& sample : sampled_pixels) {
if (!IsColorGray(sample))
color_pixels++;
}
ColorMode color_mode = (color_pixels > samples_count / 100)
? ColorMode::kColor
: ColorMode::kGrayscale;
DarkModeImageClassifier::Features features;
features.is_colorful = color_mode == ColorMode::kColor;
features.color_buckets_ratio =
ComputeColorBucketsRatio(sampled_pixels, color_mode);
features.transparency_ratio = transparency_ratio;
features.background_ratio = background_ratio;
features.is_svg = image_type_ == ImageType::kSvg;
return features;
}
float DarkModeImageClassifier::ComputeColorBucketsRatio(
const Vector<SkColor>& sampled_pixels,
const ColorMode color_mode) {
HashSet<unsigned, WTF::AlreadyHashed,
WTF::UnsignedWithZeroKeyHashTraits<unsigned>>
buckets;
// If image is in color, use 4 bits per color channel, otherwise 4 bits for
// illumination.
if (color_mode == ColorMode::kColor) {
for (const SkColor& sample : sampled_pixels) {
unsigned bucket = ((SkColorGetR(sample) >> 4) << 8) +
((SkColorGetG(sample) >> 4) << 4) +
((SkColorGetB(sample) >> 4));
buckets.insert(bucket);
}
} else {
for (const SkColor& sample : sampled_pixels) {
unsigned illumination =
(SkColorGetR(sample) * 5 + SkColorGetG(sample) * 3 +
SkColorGetB(sample) * 2) /
10;
buckets.insert(illumination / 16);
}
}
// Using 4 bit per channel representation of each color bucket, there would be
// 2^4 buckets for grayscale images and 2^12 for color images.
const float max_buckets[] = {16, 4096};
return static_cast<float>(buckets.size()) /
max_buckets[color_mode == ColorMode::kColor];
}
void DarkModeImageClassifier::ResetDataMembersToDefaults() {
pixels_to_sample_ = kPixelsToSample;
blocks_count_horizontal_ = kBlocksCount1D;
blocks_count_vertical_ = kBlocksCount1D;
}
} // namespace blink
| 36.616601 | 84 | 0.6875 | [
"vector"
] |
90844bbe2289ba54cbc1f5d106888e9c80f4ead0 | 18,609 | cpp | C++ | Lexer.cpp | Nalleyer/CalculatorTheHardWay | 7e72944921cc0e16b739630e8235207ccfeffe22 | [
"MIT"
] | null | null | null | Lexer.cpp | Nalleyer/CalculatorTheHardWay | 7e72944921cc0e16b739630e8235207ccfeffe22 | [
"MIT"
] | null | null | null | Lexer.cpp | Nalleyer/CalculatorTheHardWay | 7e72944921cc0e16b739630e8235207ccfeffe22 | [
"MIT"
] | null | null | null | //
// Created by Nalley on 2017/7/27.
//
#include <iostream>
#include "Lexer.h"
using std::string;
Lexer::Lexer()
: mColumn(0)
, mNumLine(0)
{
}
std::vector<Token> Lexer::getTokens()
{
return mTokens;
}
void Lexer::runLexer(const std::string &input)
{
clear();
auto nowState = State::INIT;
string nowStr = "";
auto lastLine = mNumLine;
auto lastColumn = mColumn;
for(auto i = 0; i < input.length() + 1; i++)
{
char ch = ( i== input.length() ) ? '\0' : input.at(i) ;
CharType cht;
try
{
cht = charType( ch );
}
catch ( std::invalid_argument & e)
{
error(e.what());
}
catch (...)
{
error("unkown error");
}
auto outPair = mLexerTable.at(std::make_pair(nowState, cht));
if ( outPair.second == TokenType::BAD_TOKEN )
{
error("bad token !");
}
else if ( outPair.second != TokenType::NO_TOKEN )
{
mTokens.emplace_back(Token{outPair.second, nowStr, lastLine + 1, lastColumn - nowStr.length() + 2});
nowStr = "";
}
if ( ch != ' ')
{
nowStr.push_back(ch);
}
nowState = outPair.first;
lastLine = mNumLine;
lastColumn = mColumn;
updatePosition(nowState);
}
mTokens.emplace_back(Token{TokenType::ENDL, "", 0, 0});
}
void Lexer::updatePosition(const State &nowState)
{
mColumn++;
if ( nowState == State::ENDL )
{
mNumLine++;
mColumn = 0;
}
}
/*
std::vector<string> Lexer::getTokens()
{
}
*/
void Lexer::clear()
{
mColumn = 0;
mNumLine = 0;
}
CharType Lexer::charType(char ch)
{
switch(ch)
{
case '\0' : return CharType::END;
case ' ' : return CharType::SPACE;
case '\n' : return CharType::ENDL;
case '+' : return CharType::ADD;
case '-' : return CharType::SUB;
case '*' : return CharType::MUL;
case '/' : return CharType::DIV;
case '(' : return CharType::LP;
case ')' : return CharType::RP;
case '.' : return CharType::POINT;
case '=' : return CharType::ASN;
default :
{
if ('0' <= ch and ch <= '9')
{
return CharType::NUM;
}
if ( ('a' <= ch and ch <= 'z')
or ('A' <= ch and ch <= 'Z') )
{
return CharType::WORD;
}
else
{
string info = "char ";
info += ch;
info += " is unacceptable";
throw std::invalid_argument(info);
}
}
}
}
void Lexer::error(const std::string &info)
{
std::cerr << "on line " << mNumLine + 1 << ", column " << mColumn + 1 << ":\n";
std::cerr << info << '\n';
exit(1);
}
const std::unordered_map< Lexer::MapInType, Lexer::MapOUtType, pair_hash > Lexer::mLexerTable{
/* init */
{ {State::INIT, CharType::END}, {State::OVER, TokenType::NO_TOKEN}},
{ {State::INIT, CharType::SPACE}, {State::INIT, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::ENDL}, {State::ENDL, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::ADD}, {State::ADD, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::SUB}, {State::SUB, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::MUL}, {State::MUL, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::DIV}, {State::DIV, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::LP}, {State::LP, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::RP}, {State::RP, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::NUM}, {State::NUM_INT, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::POINT}, {State::POINT_FNT, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::WORD}, {State::VAR, TokenType::NO_TOKEN} },
{ {State::INIT, CharType::ASN}, {State::ASN, TokenType::NO_TOKEN} },
/* add */
{ {State::ADD, CharType::END}, {State::OVER, TokenType::ADD} },
{ {State::ADD, CharType::SPACE}, {State::INIT, TokenType::ADD} },
{ {State::ADD, CharType::ENDL}, {State::ENDL, TokenType::ADD} },
{ {State::ADD, CharType::ADD}, {State::ADD, TokenType::ADD} },
{ {State::ADD, CharType::SUB}, {State::SUB, TokenType::ADD} },
{ {State::ADD, CharType::MUL}, {State::MUL, TokenType::ADD} },
{ {State::ADD, CharType::DIV}, {State::DIV, TokenType::ADD} },
{ {State::ADD, CharType::LP}, {State::LP, TokenType::ADD} },
{ {State::ADD, CharType::RP}, {State::RP, TokenType::ADD} },
{ {State::ADD, CharType::NUM}, {State::NUM_INT, TokenType::ADD} },
{ {State::ADD, CharType::POINT}, {State::POINT_FNT, TokenType::ADD} },
{ {State::ADD, CharType::WORD}, {State::VAR, TokenType::ADD} },
{ {State::ADD, CharType::ASN}, {State::ASN, TokenType::ADD} },
/* sub */
{ {State::SUB, CharType::END}, {State::OVER, TokenType::SUB} },
{ {State::SUB, CharType::SPACE}, {State::INIT, TokenType::SUB} },
{ {State::SUB, CharType::ENDL}, {State::ENDL, TokenType::SUB} },
{ {State::SUB, CharType::ADD}, {State::ADD, TokenType::SUB} },
{ {State::SUB, CharType::SUB}, {State::SUB, TokenType::SUB} },
{ {State::SUB, CharType::MUL}, {State::MUL, TokenType::SUB} },
{ {State::SUB, CharType::DIV}, {State::DIV, TokenType::SUB} },
{ {State::SUB, CharType::LP}, {State::LP, TokenType::SUB} },
{ {State::SUB, CharType::RP}, {State::RP, TokenType::SUB} },
{ {State::SUB, CharType::NUM}, {State::NUM_INT, TokenType::SUB} },
{ {State::SUB, CharType::POINT}, {State::POINT_FNT, TokenType::SUB} },
{ {State::SUB, CharType::WORD}, {State::VAR, TokenType::SUB} },
{ {State::SUB, CharType::ASN}, {State::ASN, TokenType::SUB} },
/* mul */
{ {State::MUL, CharType::END}, {State::OVER, TokenType::MUL} },
{ {State::MUL, CharType::SPACE}, {State::INIT, TokenType::MUL} },
{ {State::MUL, CharType::ENDL}, {State::ENDL, TokenType::MUL} },
{ {State::MUL, CharType::ADD}, {State::ADD, TokenType::MUL} },
{ {State::MUL, CharType::SUB}, {State::SUB, TokenType::MUL} },
{ {State::MUL, CharType::MUL}, {State::MUL, TokenType::MUL} },
{ {State::MUL, CharType::DIV}, {State::DIV, TokenType::MUL} },
{ {State::MUL, CharType::LP}, {State::LP, TokenType::MUL} },
{ {State::MUL, CharType::RP}, {State::RP, TokenType::MUL} },
{ {State::MUL, CharType::NUM}, {State::NUM_INT, TokenType::MUL} },
{ {State::MUL, CharType::POINT}, {State::POINT_FNT, TokenType::MUL} },
{ {State::MUL, CharType::WORD}, {State::VAR, TokenType::MUL} },
{ {State::MUL, CharType::ASN}, {State::ASN, TokenType::MUL} },
/* div */
{ {State::DIV, CharType::END}, {State::OVER, TokenType::DIV} },
{ {State::DIV, CharType::SPACE}, {State::INIT, TokenType::DIV} },
{ {State::DIV, CharType::ENDL}, {State::ENDL, TokenType::DIV} },
{ {State::DIV, CharType::ADD}, {State::ADD, TokenType::DIV} },
{ {State::DIV, CharType::SUB}, {State::SUB, TokenType::DIV} },
{ {State::DIV, CharType::MUL}, {State::MUL, TokenType::DIV} },
{ {State::DIV, CharType::DIV}, {State::DIV, TokenType::DIV} },
{ {State::DIV, CharType::LP}, {State::LP, TokenType::DIV} },
{ {State::DIV, CharType::RP}, {State::RP, TokenType::DIV} },
{ {State::DIV, CharType::NUM}, {State::NUM_INT, TokenType::DIV} },
{ {State::DIV, CharType::POINT}, {State::POINT_FNT, TokenType::DIV} },
{ {State::DIV, CharType::WORD}, {State::VAR, TokenType::DIV} },
{ {State::DIV, CharType::ASN}, {State::ASN, TokenType::DIV} },
/* left par */
{ {State::LP, CharType::END}, {State::OVER, TokenType::LEFT_PAR} },
{ {State::LP, CharType::SPACE}, {State::INIT, TokenType::LEFT_PAR} },
{ {State::LP, CharType::ENDL}, {State::ENDL, TokenType::LEFT_PAR} },
{ {State::LP, CharType::ADD}, {State::ADD, TokenType::LEFT_PAR} },
{ {State::LP, CharType::SUB}, {State::SUB, TokenType::LEFT_PAR} },
{ {State::LP, CharType::MUL}, {State::MUL, TokenType::LEFT_PAR} },
{ {State::LP, CharType::DIV}, {State::DIV, TokenType::LEFT_PAR} },
{ {State::LP, CharType::LP}, {State::LP, TokenType::LEFT_PAR} },
{ {State::LP, CharType::RP}, {State::RP, TokenType::LEFT_PAR} },
{ {State::LP, CharType::NUM}, {State::NUM_INT, TokenType::LEFT_PAR} },
{ {State::LP, CharType::POINT}, {State::POINT_FNT, TokenType::LEFT_PAR} },
{ {State::LP, CharType::WORD}, {State::VAR, TokenType::LEFT_PAR} },
{ {State::LP, CharType::ASN}, {State::ASN, TokenType::LEFT_PAR} },
/* right par */
{ {State::RP, CharType::END}, {State::OVER, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::SPACE}, {State::INIT, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::ENDL}, {State::ENDL, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::ADD}, {State::ADD, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::SUB}, {State::SUB, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::MUL}, {State::MUL, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::DIV}, {State::DIV, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::LP}, {State::LP, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::RP}, {State::RP, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::NUM}, {State::NUM_INT, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::POINT}, {State::POINT_FNT, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::WORD}, {State::VAR, TokenType::RIGHT_PAR} },
{ {State::RP, CharType::ASN}, {State::ASN, TokenType::RIGHT_PAR} },
/* num integer part */
{ {State::NUM_INT, CharType::END}, {State::OVER, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::SPACE}, {State::INIT, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::ENDL}, {State::ENDL, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::ADD}, {State::ADD, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::SUB}, {State::SUB, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::MUL}, {State::MUL, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::DIV}, {State::DIV, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::LP}, {State::LP, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::RP}, {State::RP, TokenType::NUMBER} },
{ {State::NUM_INT, CharType::NUM}, {State::NUM_INT, TokenType::NO_TOKEN} },
{ {State::NUM_INT, CharType::POINT}, {State::POINT_NML, TokenType::NO_TOKEN} },
{ {State::NUM_INT, CharType::WORD}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::NUM_INT, CharType::ASN}, {State::ASN, TokenType::NUMBER} },
/* front point */
{ {State::POINT_FNT, CharType::END}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::SPACE}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::ENDL}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::ADD}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::SUB}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::MUL}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::DIV}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::LP}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::RP}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::NUM}, {State::NUM_INT, TokenType::NO_TOKEN} },
{ {State::POINT_FNT, CharType::POINT}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::WORD}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_FNT, CharType::ASN}, {State::OVER, TokenType::BAD_TOKEN} },
/* normal point, which is after number */
{ {State::POINT_NML, CharType::END}, {State::OVER, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::SPACE}, {State::INIT, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::ENDL}, {State::ENDL, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::ADD}, {State::ADD, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::SUB}, {State::SUB, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::MUL}, {State::MUL, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::DIV}, {State::DIV, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::LP}, {State::LP, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::RP}, {State::RP, TokenType::NUMBER} },
{ {State::POINT_NML, CharType::NUM}, {State::NUM_DEC, TokenType::NO_TOKEN} },
{ {State::POINT_NML, CharType::POINT}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_NML, CharType::WORD}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::POINT_NML, CharType::ASN}, {State::ASN, TokenType::NUMBER} },
/* number, decimal part */
{ {State::NUM_DEC, CharType::END}, {State::OVER, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::SPACE}, {State::INIT, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::ENDL}, {State::ENDL, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::ADD}, {State::ADD, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::SUB}, {State::SUB, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::MUL}, {State::MUL, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::DIV}, {State::DIV, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::LP}, {State::LP, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::RP}, {State::RP, TokenType::NUMBER} },
{ {State::NUM_DEC, CharType::NUM}, {State::NUM_DEC, TokenType::NO_TOKEN} },
{ {State::NUM_DEC, CharType::POINT}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::NUM_DEC, CharType::WORD}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::NUM_DEC, CharType::ASN}, {State::ASN, TokenType::NUMBER} },
/* variable */
{ {State::VAR, CharType::END}, {State::OVER, TokenType::VAR} },
{ {State::VAR, CharType::SPACE}, {State::INIT, TokenType::VAR} },
{ {State::VAR, CharType::ENDL}, {State::ENDL, TokenType::VAR} },
{ {State::VAR, CharType::ADD}, {State::ADD, TokenType::VAR} },
{ {State::VAR, CharType::SUB}, {State::SUB, TokenType::VAR} },
{ {State::VAR, CharType::MUL}, {State::MUL, TokenType::VAR} },
{ {State::VAR, CharType::DIV}, {State::DIV, TokenType::VAR} },
{ {State::VAR, CharType::LP}, {State::LP, TokenType::VAR} },
{ {State::VAR, CharType::RP}, {State::RP, TokenType::VAR} },
{ {State::VAR, CharType::NUM}, {State::VAR, TokenType::NO_TOKEN} },
{ {State::VAR, CharType::POINT}, {State::OVER, TokenType::BAD_TOKEN} },
{ {State::VAR, CharType::WORD}, {State::VAR, TokenType::NO_TOKEN} },
{ {State::VAR, CharType::ASN}, {State::ASN, TokenType::VAR} },
/* = */
{ {State::ASN, CharType::END}, {State::OVER, TokenType::ASSIGN} },
{ {State::ASN, CharType::SPACE}, {State::INIT, TokenType::ASSIGN} },
{ {State::ASN, CharType::ENDL}, {State::ENDL, TokenType::ASSIGN} },
{ {State::ASN, CharType::ADD}, {State::ADD, TokenType::ASSIGN} },
{ {State::ASN, CharType::SUB}, {State::SUB, TokenType::ASSIGN} },
{ {State::ASN, CharType::MUL}, {State::MUL, TokenType::ASSIGN} },
{ {State::ASN, CharType::DIV}, {State::DIV, TokenType::ASSIGN} },
{ {State::ASN, CharType::LP}, {State::LP, TokenType::ASSIGN} },
{ {State::ASN, CharType::RP}, {State::RP, TokenType::ASSIGN} },
{ {State::ASN, CharType::NUM}, {State::NUM_INT, TokenType::ASSIGN} },
{ {State::ASN, CharType::POINT}, {State::POINT_FNT, TokenType::ASSIGN} },
{ {State::ASN, CharType::WORD}, {State::VAR, TokenType::ASSIGN} },
{ {State::ASN, CharType::ASN}, {State::ASN, TokenType::ASSIGN} },
/* \n */
{ {State::ENDL, CharType::END}, {State::OVER, TokenType::ENDL} },
{ {State::ENDL, CharType::SPACE}, {State::INIT, TokenType::ENDL} },
{ {State::ENDL, CharType::ENDL}, {State::ENDL, TokenType::ENDL} },
{ {State::ENDL, CharType::ADD}, {State::ADD, TokenType::ENDL} },
{ {State::ENDL, CharType::SUB}, {State::SUB, TokenType::ENDL} },
{ {State::ENDL, CharType::MUL}, {State::MUL, TokenType::ENDL} },
{ {State::ENDL, CharType::DIV}, {State::DIV, TokenType::ENDL} },
{ {State::ENDL, CharType::LP}, {State::LP, TokenType::ENDL} },
{ {State::ENDL, CharType::RP}, {State::RP, TokenType::ENDL} },
{ {State::ENDL, CharType::NUM}, {State::NUM_INT, TokenType::ENDL} },
{ {State::ENDL, CharType::POINT}, {State::POINT_FNT, TokenType::ENDL} },
{ {State::ENDL, CharType::WORD}, {State::VAR, TokenType::ENDL} },
{ {State::ENDL, CharType::ASN}, {State::ASN, TokenType::ENDL} }
};
| 55.056213 | 112 | 0.516256 | [
"vector"
] |
9084cb262b16ff62e69f6453d8f2c20364fde0bd | 2,918 | cc | C++ | src/float-counts-remove-zeros.cc | RoseSAK/pocolm | 2da2b6e5a709fb40021f7bbcdd18d84f174dfe30 | [
"Apache-2.0"
] | 88 | 2016-04-16T03:42:04.000Z | 2022-02-10T17:45:39.000Z | src/float-counts-remove-zeros.cc | RoseSAK/pocolm | 2da2b6e5a709fb40021f7bbcdd18d84f174dfe30 | [
"Apache-2.0"
] | 81 | 2016-05-09T00:07:18.000Z | 2022-02-02T05:59:04.000Z | src/float-counts-remove-zeros.cc | RoseSAK/pocolm | 2da2b6e5a709fb40021f7bbcdd18d84f174dfe30 | [
"Apache-2.0"
] | 43 | 2016-05-17T04:51:10.000Z | 2022-01-25T12:14:15.000Z | // float-counts-remove-zeros.cc
// Copyright 2016 Johns Hopkins University (Author: Daniel Povey)
// See ../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <stdlib.h>
#include "pocolm-types.h"
#include "lm-state.h"
namespace pocolm {
void RemoveZeroCounts(FloatLmState *lm_state) {
std::vector<std::pair<int32, float> >::const_iterator
in_iter = lm_state->counts.begin(),
in_end = lm_state->counts.end();
std::vector<std::pair<int32, float> >::iterator
out_iter = lm_state->counts.begin();
for (; in_iter != in_end; ++in_iter) {
if (in_iter->second != 0.0) {
*out_iter = *in_iter;
out_iter++;
}
}
size_t new_size = out_iter - lm_state->counts.begin();
lm_state->counts.resize(new_size);
}
}
/*
This program copies float-counts while removing zero-valued counts
and LM states that have no counts.
*/
int main (int argc, const char **argv) {
if (argc != 1) {
std::cerr << "Usage: float-counts-remove-zeros < <float-counts> > <float-counts>\n"
<< "This program copies float-counts while removing zero counts and\n"
<< "LM-states that have no counts.\n"
<< "See also float-counts-stats-remove-zeros\n";
exit(1);
}
int64 num_lm_states_in = 0,
num_lm_states_out = 0,
num_counts_in = 0,
num_counts_out = 0;
// we only get EOF after trying to read past the end of the file,
// so first call peek().
while (std::cin.peek(), !std::cin.eof()) {
pocolm::FloatLmState lm_state;
lm_state.Read(std::cin);
num_lm_states_in++;
num_counts_in += static_cast<int64>(lm_state.counts.size());
pocolm::RemoveZeroCounts(&lm_state);
if (!lm_state.counts.empty()) {
num_lm_states_out++;
num_counts_out += static_cast<int64>(lm_state.counts.size());
lm_state.Write(std::cout);
}
}
std::cerr << "float-counts-remove-zeros: reduced LM states from "
<< num_lm_states_in << " to " << num_lm_states_out
<< " and counts from "
<< num_counts_in << " to " << num_counts_out << ".\n";
return 0;
}
// see egs/simple/local/test_float_counts.sh for a a command line example of using this.
| 31.376344 | 88 | 0.666552 | [
"vector"
] |
9084cd6a4475ad7e1747398e6f35eafa59373d78 | 2,243 | cpp | C++ | cs10/madlibs.cpp | bmoya217/ucr | 16a1b24b40845b9b98c6e93b8e1bf24a9f090f4b | [
"Apache-2.0"
] | null | null | null | cs10/madlibs.cpp | bmoya217/ucr | 16a1b24b40845b9b98c6e93b8e1bf24a9f090f4b | [
"Apache-2.0"
] | null | null | null | cs10/madlibs.cpp | bmoya217/ucr | 16a1b24b40845b9b98c6e93b8e1bf24a9f090f4b | [
"Apache-2.0"
] | null | null | null | #include <string>
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
// defines the strings
vector<string> word (10);
// asks for users blind input of strings
cout << "Enter any type of animal: ";
cin >> word[0];
cout << "\n\nEnter another animal: ";
cin >> word[1];
cout << "\n\nEnter one more: ";
cin >> word[2];
cout << "\n\nEnter your characters name: ";
cin >> word[3];
cout << "\n\nEnter a noun bigger than the first animal: ";
cin >> word[4];
cout << "\n\nEnter an emotion: ";
cin >> word[5];
cout << "\n\nEnter a verb that ends in -ed: ";
cin >> word[6];
cout << "\n\nEnter a verb that ends in -ing: ";
cin >> word[7];
cout << "\n\nEnter a type of building material: ";
cin >> word[8];
cout << "\n\nEnter another type of building material:";
cin >> word[9];
// 80 dashes to represent the start of the story
string measuringStick(80, '-');
cout << measuringStick << endl;
// paragraph 1
cout << "\033cThere once was a " << animal1 << " who lived in a ";
cout << homeForCharacter << ". He was very " << emotion << endl;
cout << "because he";
cout << " only " << verbED << " all day long. Unfortuneately, " << name;
cout << " the " << endl;
cout << animal1 << " was very lonely.\n" << endl;
// paragraph 2
cout << "One day " << name << " decided that he wanted more friends. ";
cout << "So then he tried making" << endl;
cout << "one out of " << object1 << " and ";
cout << object2 << ". When that didn't work, " << name << " got " <<endl;
cout << "very sad.";
cout << endl << endl;
// paragraoh 3
cout << "To fill in his time " << name << " decided to take " << verbING;
cout << " classes. Months later," << endl;
cout << "his newly aquired skill was what helped ";
cout << "him win over his soon-to-be wife, the" << endl;
cout << "very bodacios " << animal2;
cout << ". However, that unkind lady cheated on him with a " << endl;
cout << animal3 << " and " << name << " died alone.\n";
// 80 dashes to represent the end of the story
cout << measuringStick;
return 0;
} | 33.477612 | 77 | 0.551048 | [
"vector"
] |
9085412a8df783b340351f0b3b4ea8ec1b2ecd58 | 2,523 | cpp | C++ | src/topics/inferencer.cpp | Bungarch/meta | c0c4fc7fe78e8e910cecd31bf85f7f9da829cce5 | [
"MIT"
] | null | null | null | src/topics/inferencer.cpp | Bungarch/meta | c0c4fc7fe78e8e910cecd31bf85f7f9da829cce5 | [
"MIT"
] | null | null | null | src/topics/inferencer.cpp | Bungarch/meta | c0c4fc7fe78e8e910cecd31bf85f7f9da829cce5 | [
"MIT"
] | null | null | null | /**
* @file topics/inferencer.cpp
* @author Chase Geigle
*
* All files in META are dual-licensed under the MIT and NCSA licenses. For more
* details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the
* project.
*/
#include "meta/topics/inferencer.h"
namespace meta
{
namespace topics
{
inferencer::inferencer(const cpptoml::table& config)
{
auto topics_cfg = config.get_table("lda");
if (!topics_cfg)
{
throw inferencer_exception{
"Missing [lda] configuration in configuration file"};
}
auto prefix = topics_cfg->get_as<std::string>("model-prefix");
if (!prefix)
{
throw inferencer_exception{"Missing prefix key in configuration file"};
}
std::ifstream phi{*prefix + ".phi.bin", std::ios::binary};
if (!phi)
{
throw inferencer_exception{
"missing topic term probabilities file:" + *prefix + ".phi.bin"};
}
auto alpha = topics_cfg->get_as<double>("alpha");
if (!alpha)
{
throw inferencer_exception{
"missing alpha parameter in configuration file"};
}
auto num_topics = topics_cfg->get_as<uint64_t>("topics");
if (!num_topics)
{
throw inferencer_exception{"missing topics key in [lda] table"};
}
prior_ = stats::dirichlet<topic_id>(*alpha, *num_topics);
load_from_stream(phi);
}
inferencer::inferencer(std::istream& topic_stream, double alpha)
{
load_from_stream(topic_stream);
prior_ = stats::dirichlet<topic_id>(alpha, topics_.size());
}
void inferencer::load_from_stream(std::istream& topic_stream)
{
auto check = [&]() {
if (!topic_stream)
throw inferencer_exception{"topic term stream ended unexpectedly"};
};
auto num_topics = io::packed::read<std::size_t>(topic_stream);
check();
topics_.resize(num_topics);
io::packed::read<std::size_t>(topic_stream); // discard vocab size
check();
printing::progress term_progress{" > Loading topic term probabilities: ",
num_topics};
for (topic_id tid{0}; tid < num_topics; ++tid)
{
check();
term_progress(tid);
io::packed::read(topic_stream, topics_[tid]);
}
}
const stats::multinomial<term_id>&
inferencer::term_distribution(topic_id k) const
{
return topics_[k];
}
std::size_t inferencer::num_topics() const
{
return topics_.size();
}
const stats::dirichlet<topic_id>& inferencer::proportions_prior() const
{
return prior_;
}
}
}
| 24.259615 | 80 | 0.644867 | [
"model"
] |
908bd8c2997898997524c52360c913dd090c2c85 | 7,859 | cpp | C++ | edge_swap.cpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | edge_swap.cpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | edge_swap.cpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | #include "edge_swap.hpp"
#include <cassert>
#include "algebra.hpp"
#include "quality.hpp"
#include "tables.hpp"
namespace omega_h {
/* tables hardcoding all possible 2D meshes (triangulations) of
an N-sided polygon, where N ranges from 3 to 7.
for a given polygon, many possible triangulations may share
the same triangle, so the list of unique triangles is stored
separately.
this is useful because it allows caching of quality metrics
computed based on the unique triangle which can then be
reused when evaluating the quality of triangulations. */
LOOP_CONST unsigned const swap_mesh_sizes[MAX_EDGE_SWAP+1] =
{0 //0
,0 //1
,0 //2
,1 //3
,2 //4
,3 //5
,4 //6
,5 //7
};
LOOP_CONST unsigned const swap_mesh_counts[MAX_EDGE_SWAP+1] =
{0 //0
,0 //1
,0 //2
,1 //3
,2 //4
,5 //5
,14 //6
,42 //7
};
#define MAX_UNIQUE_TRIS 35
LOOP_CONST static unsigned const triangles_3[1][3] = {{0,1,2}};
LOOP_CONST static unsigned const meshes_3[1] =
{0
};
LOOP_CONST static unsigned const triangles_4[4][3] =
{{0,1,2}
,{0,2,3}
,{0,1,3}
,{1,2,3}
};
LOOP_CONST static unsigned const meshes_4[2 * 2] =
{0,1
,2,3
};
LOOP_CONST static unsigned const triangles_5[10][3] =
{{0,1,2}
,{0,2,3}
,{0,3,4}
,{0,1,4}
,{1,3,4}
,{1,2,3}
,{2,3,4}
,{0,2,4}
,{0,1,3}
,{1,2,4}
};
LOOP_CONST static unsigned const meshes_5[5 * 3] =
{0,1,2
,3,4,5
,0,6,7
,2,5,8
,3,6,9
};
LOOP_CONST static unsigned const triangles_6[20][3] =
{{0,1,2}
,{0,2,3}
,{0,3,4}
,{0,4,5}
,{0,2,5}
,{2,4,5}
,{2,3,4}
,{0,3,5}
,{3,4,5}
,{0,2,4}
,{2,3,5}
,{1,2,3}
,{0,1,3}
,{0,1,5}
,{1,4,5}
,{1,3,4}
,{0,1,4}
,{1,3,5}
,{1,2,4}
,{1,2,5}
};
LOOP_CONST static unsigned const meshes_6[14 * 4] =
{0, 1 ,2 ,3
,0, 4 ,5 ,6
,0, 1 ,7 ,8
,0, 3 ,6 ,9
,0, 4 ,8 ,10
,2, 3 ,11,12
,11,13,14,15
,7 ,8 ,11,12
,3 ,11,15,16
,8 ,11,13,17
,6 ,13,14,18
,3 ,6 ,16,18
,5 ,6 ,13,19
,8 ,10,13,19
};
LOOP_CONST static unsigned const triangles_7[35][3] =
{{0,1,2}
,{0,2,3}
,{0,3,4}
,{0,4,5}
,{0,5,6}
,{0,3,6}
,{3,5,6}
,{3,4,5}
,{0,4,6}
,{4,5,6}
,{0,3,5}
,{3,4,6}
,{0,2,4}
,{2,3,4}
,{0,2,6}
,{2,5,6}
,{2,4,5}
,{0,2,5}
,{2,4,6}
,{2,3,5}
,{2,3,6}
,{0,1,3}
,{1,2,3}
,{0,1,4}
,{1,3,4}
,{0,1,6}
,{1,5,6}
,{1,4,5}
,{0,1,5}
,{1,4,6}
,{1,3,5}
,{1,3,6}
,{1,2,4}
,{1,2,5}
,{1,2,6}
};
LOOP_CONST static unsigned const meshes_7[42 * 5] =
{0 ,1 ,2 ,3 ,4
,0 ,1 ,5 ,6 ,7
,0 ,1 ,2 ,8 ,9
,0 ,1 ,4 ,7 ,10
,0 ,1 ,5 ,9 ,11
,0 ,3 ,4 ,12,13
,0 ,13,14,15,16
,0 ,8 ,9 ,12,13
,0 ,4 ,13,16,17
,0 ,9 ,13,14,18
,0 ,7 ,14,15,19
,0 ,4 ,7 ,17,19
,0 ,6 ,7 ,14,20
,0 ,9 ,11,14,20
,2 ,3 ,4 ,21,22
,5 ,6 ,7 ,21,22
,2 ,8 ,9 ,21,22
,4 ,7 ,10,21,22
,5 ,9 ,11,21,22
,3 ,4 ,22,23,24
,22,24,25,26,27
,8 ,9 ,22,23,24
,4 ,22,24,27,28
,9 ,22,24,25,29
,7 ,22,25,26,30
,4 ,7 ,22,28,30
,6 ,7 ,22,25,31
,9 ,11,22,25,31
,3 ,4 ,13,23,32
,13,25,26,27,32
,8 ,9 ,13,23,32
,4 ,13,27,28,32
,9 ,13,25,29,32
,13,16,25,26,33
,4 ,13,16,28,33
,13,15,16,25,34
,9 ,13,18,25,34
,7 ,19,25,26,33
,4 ,7 ,19,28,33
,7 ,15,19,25,34
,6 ,7 ,20,25,34
,9 ,11,20,25,34
};
/* array [8] of pointer to array [3] of unsigned const */
LOOP_CONST swap_tri_t const* const swap_triangles[MAX_EDGE_SWAP+1] =
{0
,0
,0
,triangles_3
,triangles_4
,triangles_5
,triangles_6
,triangles_7
};
LOOP_CONST unsigned const* const swap_meshes[MAX_EDGE_SWAP+1] =
{0
,0
,0
,meshes_3
,meshes_4
,meshes_5
,meshes_6
,meshes_7
};
LOOP_IN struct swap_choice choose_edge_swap(
unsigned ring_size,
double (*edge_x)[3],
double (*ring_x)[3])
{
unsigned tris_per_mesh = swap_mesh_sizes[ring_size];
unsigned nmeshes = swap_mesh_counts[ring_size];
unsigned const* mesh = swap_meshes[ring_size];
swap_tri_t const* tris = swap_triangles[ring_size];
unsigned char cached[MAX_UNIQUE_TRIS] = {0};
double cache[MAX_UNIQUE_TRIS] = {0};
struct swap_choice out;
out.code = INVALID;
out.quality = -1;
for (unsigned i = 0; i < nmeshes; ++i) {
double mesh_minq = 1;
for (unsigned j = 0; j < tris_per_mesh; ++j) {
unsigned tri = mesh[j];
double tri_minq;
if (!cached[tri]) {
unsigned const* tri_verts = tris[tri];
double tet_x[4][3];
for (unsigned k = 0; k < 3; ++k) {
unsigned vert = tri_verts[k];
copy_vector(ring_x[vert], tet_x[k], 3);
}
tri_minq = 1;
for (unsigned k = 0; k < 2; ++k) {
copy_vector(edge_x[1 - k], tet_x[3], 3);
double tet_q = tet_quality(tet_x);
if (tet_q < tri_minq)
tri_minq = tet_q;
swap_vectors(tet_x[0], tet_x[1], 3);
}
cached[tri] = 1;
cache[tri] = tri_minq;
}
tri_minq = cache[tri];
if (tri_minq < mesh_minq)
mesh_minq = tri_minq;
if (mesh_minq < 0)
break;
}
if (mesh_minq > out.quality) {
out.code = i;
out.quality = mesh_minq;
}
mesh += tris_per_mesh;
}
return out;
}
LOOP_IN static void get_swap_tets(
unsigned ring_size,
unsigned code,
unsigned const edge_v[2],
unsigned const* ring_v,
unsigned* out)
{
unsigned* p = out;
unsigned tris_per_mesh = swap_mesh_sizes[ring_size];
unsigned const* mesh = swap_meshes[ring_size] + code * tris_per_mesh;
swap_tri_t const* tris = swap_triangles[ring_size];
for (unsigned i = 0; i < tris_per_mesh; ++i) {
unsigned tet_verts[4];
unsigned tri = mesh[i];
unsigned const* tri_verts = tris[tri];
for (unsigned j = 0; j < 3; ++j)
tet_verts[j] = ring_v[tri_verts[j]];
for (unsigned j = 0; j < 2; ++j) {
tet_verts[3] = edge_v[1 - j];
for (unsigned k = 0; k < 4; ++k)
*out++ = tet_verts[k];
unsigned tmp = tet_verts[0];
tet_verts[0] = tet_verts[1];
tet_verts[1] = tmp;
}
}
unsigned ntets = tris_per_mesh * 2;
assert(out - p == ntets * 4);
}
LOOP_IN static void get_swap_edges(
unsigned ring_size,
unsigned code,
unsigned const* ring_v,
unsigned* out)
{
unsigned nint_edges = swap_nint_edges[ring_size];
if (!nint_edges)
return;
unsigned const* edges = swap_int_edges[ring_size][code];
for (unsigned i = 0; i < nint_edges; ++i)
for (unsigned j = 0; j < 2; ++j)
out[i * 2 + j] = ring_v[edges[i * 2 + j]];
}
LOOP_IN static void get_swap_tris(
unsigned ring_size,
unsigned code,
unsigned const edge_v[2],
unsigned const* ring_v,
unsigned* out)
{
unsigned nint_edges = swap_nint_edges[ring_size];
if (nint_edges) {
unsigned const* edges = swap_int_edges[ring_size][code];
for (unsigned i = 0; i < nint_edges; ++i)
for (unsigned j = 0; j < 2; ++j) {
for (unsigned k = 0; k < 2; ++k)
out[i * 6 + j * 3 + k] = ring_v[edges[i * 2 + k]];
out[i * 6 + j * 3 + 2] = edge_v[j];
}
out += nint_edges * 6;
}
unsigned npoly_tris = swap_mesh_sizes[ring_size];
unsigned const* poly_mesh = swap_meshes[ring_size] + code * npoly_tris;
swap_tri_t const* tris = swap_triangles[ring_size];
for (unsigned i = 0; i < npoly_tris; ++i) {
unsigned tri = poly_mesh[i];
unsigned const* tri_verts = tris[tri];
for (unsigned j = 0; j < 3; ++j)
out[i * 3 + j] = ring_v[tri_verts[j]];
}
}
LOOP_IN void get_swap_ents(
unsigned ring_size,
unsigned code,
unsigned ent_dim,
unsigned const edge_v[2],
unsigned const* ring_v,
unsigned* out)
{
switch (ent_dim) {
case 1: get_swap_edges(ring_size, code, ring_v, out);
break;
case 2: get_swap_tris(ring_size, code, edge_v, ring_v, out);
break;
case 3: get_swap_tets(ring_size, code, edge_v, ring_v, out);
break;
default: assert(0);
}
}
LOOP_IN unsigned count_swap_ents(
unsigned ring_size,
unsigned ent_dim)
{
switch (ent_dim) {
case 1: return swap_nint_edges[ring_size];
case 2: return swap_mesh_sizes[ring_size] +
2 * swap_nint_edges[ring_size];
case 3: return 2 * swap_mesh_sizes[ring_size];
}
LOOP_NORETURN(42);
}
}
| 20.203085 | 73 | 0.593714 | [
"mesh"
] |
908fcc0a85088c79510c21e317eae69436861aff | 2,225 | cpp | C++ | nnforge/testing_complete_result_set.cpp | anshumang/nnForgeINST | 1e9ea1b539cadbb03daa39f5d81025c1b17c21d8 | [
"Apache-2.0"
] | 2 | 2015-08-19T08:02:59.000Z | 2017-06-18T21:10:36.000Z | nnforge/testing_complete_result_set.cpp | yanshanjing/nnForge | 6d2baa1174a90b8e5e8bf2a4b259ce8a37fbddf1 | [
"Apache-2.0"
] | null | null | null | nnforge/testing_complete_result_set.cpp | yanshanjing/nnForge | 6d2baa1174a90b8e5e8bf2a4b259ce8a37fbddf1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2011-2013 Maxim Milakov
*
* 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 "testing_complete_result_set.h"
namespace nnforge
{
testing_complete_result_set::testing_complete_result_set()
{
}
testing_complete_result_set::testing_complete_result_set(
const_error_function_smart_ptr ef,
output_neuron_value_set_smart_ptr actual_output_neuron_value_set)
: ef(ef)
, actual_output_neuron_value_set(actual_output_neuron_value_set)
, predicted_output_neuron_value_set(
new output_neuron_value_set(
static_cast<unsigned int>(actual_output_neuron_value_set->neuron_value_list.size()),
static_cast<unsigned int>(actual_output_neuron_value_set->neuron_value_list.begin()->size())))
{
}
void testing_complete_result_set::resize_predicted_output_neuron_value_set(unsigned int entry_count)
{
predicted_output_neuron_value_set->neuron_value_list.resize(entry_count, std::vector<float>(actual_output_neuron_value_set->neuron_value_list.begin()->size()));
}
void testing_complete_result_set::recalculate_mse()
{
tr = testing_result_smart_ptr(new testing_result(ef));
std::vector<std::vector<float> >::const_iterator it2 = predicted_output_neuron_value_set->neuron_value_list.begin();
for(std::vector<std::vector<float> >::const_iterator it1 = actual_output_neuron_value_set->neuron_value_list.begin(); it1 != actual_output_neuron_value_set->neuron_value_list.end(); ++it1, ++it2)
{
const float * it_actual = &(*it1->begin());
const float * it_predicted = &(*it2->begin());
tr->add_error(tr->ef->calculate_error(it_actual, it_predicted, static_cast<unsigned int>(it1->size())));
}
}
}
| 40.454545 | 198 | 0.755056 | [
"vector"
] |
909ec367a54b1e9b8bb96f7e1aef600595bd8549 | 3,379 | cc | C++ | thirdparty/SAM/processframes.cc | aqws3/gdsam-native | 17e5074a606ed50ec16d5f146a6f1ec3152e7639 | [
"MIT"
] | null | null | null | thirdparty/SAM/processframes.cc | aqws3/gdsam-native | 17e5074a606ed50ec16d5f146a6f1ec3152e7639 | [
"MIT"
] | null | null | null | thirdparty/SAM/processframes.cc | aqws3/gdsam-native | 17e5074a606ed50ec16d5f146a6f1ec3152e7639 | [
"MIT"
] | null | null | null | #include "render.h"
#include "state.h"
// From RenderTabs.h
extern unsigned char multtable[];
extern unsigned char sinus[];
extern unsigned char rectangle[];
extern void Output(struct SamState &state, int index, unsigned char A);
static void CombineGlottalAndFormants(struct SamState &state, unsigned char phase1, unsigned char phase2, unsigned char phase3, unsigned char Y)
{
unsigned int tmp;
tmp = multtable[sinus[phase1] | state.amplitude1[Y]];
tmp += multtable[sinus[phase2] | state.amplitude2[Y]];
tmp += tmp > 255 ? 1 : 0; // if addition above overflows, we for some reason add one;
tmp += multtable[rectangle[phase3] | state.amplitude3[Y]];
tmp += 136;
tmp >>= 4; // Scale down to 0..15 range of C64 audio.
Output(state, 0, tmp & 0xf);
}
// PROCESS THE FRAMES
//
// In traditional vocal synthesis, the glottal pulse drives filters, which
// are attenuated to the frequencies of the formants.
//
// SAM generates these formants directly with sin and rectangular waves.
// To simulate them being driven by the glottal pulse, the waveforms are
// reset at the beginning of each glottal pulse.
//
void ProcessFrames(struct SamState &state, unsigned char mem48)
{
unsigned char speedcounter = 72;
unsigned char phase1 = 0;
unsigned char phase2 = 0;
unsigned char phase3 = 0;
unsigned char mem66 = 0; //!! was not initialized
unsigned char Y = 0;
unsigned char glottal_pulse = state.pitches[0];
unsigned char mem38 = glottal_pulse - (glottal_pulse >> 2); // mem44 * 0.75
while(mem48) {
unsigned char flags = state.sampledConsonantFlag[Y];
// unvoiced sampled phoneme?
if(flags & 248) {
RenderSample(state, &mem66, flags,Y);
// skip ahead two in the phoneme buffer
Y += 2;
mem48 -= 2;
speedcounter = state.speed;
} else {
CombineGlottalAndFormants(state, phase1, phase2, phase3, Y);
speedcounter--;
if (speedcounter == 0) {
Y++; //go to next amplitude
// decrement the frame count
mem48--;
if(mem48 == 0) return;
speedcounter = state.speed;
}
--glottal_pulse;
if(glottal_pulse != 0) {
// not finished with a glottal pulse
--mem38;
// within the first 75% of the glottal pulse?
// is the count non-zero and the sampled flag is zero?
if((mem38 != 0) || (flags == 0)) {
// reset the phase of the formants to match the pulse
phase1 += state.frequency1[Y];
phase2 += state.frequency2[Y];
phase3 += state.frequency3[Y];
continue;
}
// voiced sampled phonemes interleave the sample with the
// glottal pulse. The sample flag is non-zero, so render
// the sample for the phoneme.
RenderSample(state, &mem66, flags,Y);
}
}
glottal_pulse = state.pitches[Y];
mem38 = glottal_pulse - (glottal_pulse>>2); // mem44 * 0.75
// reset the formant wave generators to keep them in
// sync with the glottal pulse
phase1 = 0;
phase2 = 0;
phase3 = 0;
}
}
| 33.127451 | 144 | 0.58538 | [
"render"
] |
909fcd922c863847c9261e93895d93d8dc9a57c2 | 1,517 | cpp | C++ | examples/simple.cpp | pcdangio/ros_qn-optimizer | 766797f8f95c604662c5ac960cc1c22140b84acd | [
"MIT"
] | null | null | null | examples/simple.cpp | pcdangio/ros_qn-optimizer | 766797f8f95c604662c5ac960cc1c22140b84acd | [
"MIT"
] | null | null | null | examples/simple.cpp | pcdangio/ros_qn-optimizer | 766797f8f95c604662c5ac960cc1c22140b84acd | [
"MIT"
] | null | null | null | #include "qn_optimizer/qn_optimizer.h"
#include <iostream>
// TUNABLE PARAMETERS
const double min_a = -4.75;
const double min_b = 2.0;
const double initial_guess_a = 0.0;
const double initial_guess_b = 0.0;
double objective_function(const Eigen::VectorXd& variables)
{
return std::pow(variables(0) - min_a, 2.0) + std::pow(variables(1) - min_b, 2.0);
}
void objective_gradient(const Eigen::VectorXd& operating_point, Eigen::VectorXd& gradient)
{
gradient(0) = 2*(operating_point(0) - min_a);
gradient(1) = 2*(operating_point(1) - min_b);
}
int32_t main(int32_t argc, char** argv)
{
//qn_optimizer qno(2, &objective_function);
qn_optimizer qno(2, &objective_function, &objective_gradient);
// Set up the variable vector and insert initial guess.
Eigen::VectorXd variables;
variables.setZero(2);
variables(0) = initial_guess_a;
variables(1) = initial_guess_b;
// Run optimization.
double score;
bool result = qno.optimize(variables, &score);
// Display result.
if(result)
{
std::cout << "minimized value: " << std::endl << variables << std::endl;
}
else
{
std::cout << "optimization failed" << std::endl;
}
// Display number of iterations.
auto iterations = qno.iterations();
std::cout << "total iterations: " << iterations.size() << std::endl;
for(auto iteration = iterations.cbegin(); iteration != iterations.cend(); ++iteration)
{
std::cout << *iteration << std::endl;
}
} | 28.622642 | 90 | 0.652604 | [
"vector"
] |
909fd91516ee3ba14bf3beb15730deda20549427 | 7,354 | cc | C++ | dreal/optimization/nlopt_optimizer.cc | em-mcg/dreal4 | d89ee2ebb2d879d08cab977496155a440782870a | [
"Apache-2.0"
] | 1 | 2019-01-09T17:21:14.000Z | 2019-01-09T17:21:14.000Z | dreal/optimization/nlopt_optimizer.cc | em-mcg/dreal4 | d89ee2ebb2d879d08cab977496155a440782870a | [
"Apache-2.0"
] | null | null | null | dreal/optimization/nlopt_optimizer.cc | em-mcg/dreal4 | d89ee2ebb2d879d08cab977496155a440782870a | [
"Apache-2.0"
] | null | null | null | #include "dreal/optimization/nlopt_optimizer.h"
#include <cmath>
#include <utility>
#include "dreal/util/assert.h"
#include "dreal/util/exception.h"
#include "dreal/util/logging.h"
namespace dreal {
using std::make_unique;
using std::move;
using std::ostream;
using std::vector;
namespace {
/// A function passed to nlopt (type = nlopt_func). Given a vector @p
/// x, returns the evaluation of @p f_data at @p x and updates @p grad
/// which is the gradient of the function @p f_data with respect to @p
/// x.
///
/// @see
/// http://nlopt.readthedocs.io/en/latest/NLopt_Reference/#objective-function.
double NloptOptimizerEvaluate(const unsigned n, const double* x, double* grad,
void* const f_data) {
DREAL_ASSERT(f_data);
auto& expression = *static_cast<CachedExpression*>(f_data);
const Box& box{expression.box()};
DREAL_ASSERT(n == static_cast<size_t>(box.size()));
DREAL_ASSERT(n > 0);
// Set up an environment.
Environment& env{expression.mutable_environment()};
for (size_t i = 0; i < n; ++i) {
const Variable& var{box.variable(i)};
if (std::isnan(x[i])) {
throw DREAL_RUNTIME_ERROR(
"NloptOptimizer: x[{}] = nan is detected during evaluation", i);
}
env[var] = x[i];
}
// Set up gradients.
if (grad) {
for (int i = 0; i < box.size(); ++i) {
const Variable& var{box.variable(i)};
grad[i] = expression.Differentiate(var).Evaluate(env);
}
}
// Return evaluation.
return expression.Evaluate(env);
}
} // namespace
// ----------------
// CachedExpression
// ----------------
CachedExpression::CachedExpression(Expression e, const Box& box)
: expression_{move(e)}, box_{&box} {
DREAL_ASSERT(box_);
}
const Box& CachedExpression::box() const {
DREAL_ASSERT(box_);
return *box_;
}
Environment& CachedExpression::mutable_environment() { return environment_; }
const Environment& CachedExpression::environment() const {
return environment_;
}
double CachedExpression::Evaluate(const Environment& env) const {
return expression_.Evaluate(env);
}
const Expression& CachedExpression::Differentiate(const Variable& x) {
auto it = gradient_.find(x);
if (it == gradient_.end()) {
// Not found.
return gradient_.emplace_hint(it, x, expression_.Differentiate(x))->second;
} else {
return it->second;
}
}
ostream& operator<<(ostream& os, const CachedExpression& expression) {
return os << expression.expression_;
}
// --------------
// NloptOptimizer
// --------------
NloptOptimizer::NloptOptimizer(const nlopt::algorithm algorithm, Box bound,
const Config& config)
: opt_{algorithm, static_cast<unsigned>(bound.size())},
box_{move(bound)},
delta_{config.precision()} {
DREAL_ASSERT(delta_ > 0.0);
DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: Box = \n{}", box_);
// Set tolerance.
opt_.set_ftol_rel(config.nlopt_ftol_rel());
opt_.set_ftol_abs(config.nlopt_ftol_abs());
opt_.set_maxeval(config.nlopt_maxeval());
opt_.set_maxtime(config.nlopt_maxtime());
DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: ftol_rel = {}",
config.nlopt_ftol_rel());
DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: ftol_abs = {}",
config.nlopt_ftol_abs());
DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: maxeval = {}",
config.nlopt_maxeval());
DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer: maxtime = {}",
config.nlopt_maxtime());
// Set bounds.
vector<double> lower_bounds(box_.size(), 0.0);
vector<double> upper_bounds(box_.size(), 0.0);
for (int i = 0; i < box_.size(); ++i) {
lower_bounds[i] = box_[i].lb();
upper_bounds[i] = box_[i].ub();
DREAL_LOG_DEBUG("NloptOptimizer::NloptOptimizer {} ∈ [{}, {}]",
box_.variable(i), lower_bounds[i], upper_bounds[i]);
}
opt_.set_lower_bounds(lower_bounds);
opt_.set_upper_bounds(upper_bounds);
}
void NloptOptimizer::SetMinObjective(const Expression& objective) {
DREAL_LOG_DEBUG("NloptOptimizer::SetMinObjective({})", objective);
objective_ = CachedExpression{objective, box_};
opt_.set_min_objective(NloptOptimizerEvaluate,
static_cast<void*>(&objective_));
}
void NloptOptimizer::AddConstraint(const Formula& formula) {
DREAL_LOG_DEBUG("NloptOptimizer::AddConstraint({})", formula);
if (is_conjunction(formula)) {
for (const Formula& f : get_operands(formula)) {
AddConstraint(f);
}
return;
}
if (is_relational(formula)) {
return AddRelationalConstraint(formula);
}
if (is_negation(formula)) {
const Formula& negated_formula{get_operand(formula)};
if (is_relational(negated_formula)) {
return AddRelationalConstraint(nnfizer_.Convert(negated_formula));
}
}
throw DREAL_RUNTIME_ERROR(
"NloptOptimizer::AddConstraint: Unsupported formula {}.", formula);
}
void NloptOptimizer::AddRelationalConstraint(const Formula& formula) {
DREAL_ASSERT(is_relational(formula));
DREAL_LOG_DEBUG("NloptOptimizer::AddRelationalconstraint({})", formula);
bool equality{false};
if (is_greater_than(formula) || is_greater_than_or_equal_to(formula)) {
// f := e₁ > e₂ –> e₂ - e₁ < 0.
const Expression& e1{get_lhs_expression(formula)};
const Expression& e2{get_rhs_expression(formula)};
auto cached_expression = make_unique<CachedExpression>(e2 - e1, box_);
constraints_.push_back(move(cached_expression));
} else if (is_less_than(formula) || is_less_than_or_equal_to(formula)) {
// f := e₁ < e₂ –> e₁ - e₂ < 0.
const Expression& e1{get_lhs_expression(formula)};
const Expression& e2{get_rhs_expression(formula)};
auto cached_expression = make_unique<CachedExpression>(e1 - e2, box_);
constraints_.push_back(move(cached_expression));
} else if (is_equal_to(formula)) {
// f := e₁ == e₂ -> e₁ - e₂ == 0
auto cached_expression = make_unique<CachedExpression>(
get_lhs_expression(formula) - get_rhs_expression(formula), box_);
constraints_.push_back(move(cached_expression));
equality = true;
} else {
throw DREAL_RUNTIME_ERROR(
"NloptOptimizer::AddRelationalConstraint: Unsupported formula {}.",
formula);
}
if (equality) {
opt_.add_equality_constraint(NloptOptimizerEvaluate,
static_cast<void*>(constraints_.back().get()),
delta_);
} else {
opt_.add_inequality_constraint(
&NloptOptimizerEvaluate, static_cast<void*>(constraints_.back().get()),
delta_);
}
}
void NloptOptimizer::AddConstraints(const vector<Formula>& formulas) {
for (const Formula& formula : formulas) {
AddConstraint(formula);
}
}
nlopt::result NloptOptimizer::Optimize(vector<double>* const x,
double* const opt_f) {
return opt_.optimize(*x, *opt_f);
}
nlopt::result NloptOptimizer::Optimize(vector<double>* const x,
double* const opt_f,
const Environment& env) {
// Update objective_ and constraints_ with env.
objective_.mutable_environment() = env;
for (auto& constraint_ptr : constraints_) {
constraint_ptr->mutable_environment() = env;
}
return Optimize(x, opt_f);
}
} // namespace dreal
| 33.579909 | 79 | 0.6644 | [
"vector"
] |
90a0f0f0e1b3ce5c1e19bc4162f006fbedb5226a | 2,768 | cpp | C++ | cpp/sololearn/s25_const/s25_const.cpp | bayramcicek/py-repo | e99d8881dd3eb5296ec5dcfba4de2c3418044897 | [
"Unlicense"
] | null | null | null | cpp/sololearn/s25_const/s25_const.cpp | bayramcicek/py-repo | e99d8881dd3eb5296ec5dcfba4de2c3418044897 | [
"Unlicense"
] | null | null | null | cpp/sololearn/s25_const/s25_const.cpp | bayramcicek/py-repo | e99d8881dd3eb5296ec5dcfba4de2c3418044897 | [
"Unlicense"
] | null | null | null | // C11 standard
// created by cicek on Feb 03, 2021 9:49 PM
#include <iostream>
#include <string>
#include "s25_const.h"
using namespace std;
/*
* Only non-const objects can call non-const functions.
A constant object can't call regular functions. Hence, for a constant object to work you need a constant function.
To specify a function as a const member, the const keyword must follow the function prototype,
outside of its parameters' closing parenthesis.
*/
class MyClassTest {
public:
MyClassTest() {
cout << "hii" << endl;
}
void TestFun() {
cout << "test" << endl;
}
};
// Now the myPrint() function is a constant member function
void s25_const::myPrint() const {
cout << "Hello const" << endl;
}
void s25_const::test1() {
cout << "Hello test1" << endl;
}
int main(int argc, char **argv) {
const double var = 3.14;
/*
* A constant is an expression with a fixed value. It cannot be changed while the program is running.
Use the const keyword to define a constant variable.
All constant variables must be initialized at the time of their creation.
*/
cout << var << endl;
/*
* As with the built-in data types, we can make class objects constant by using the const keyword.
*
* All const variables must be initialized when they're created. In the case of classes,
* this initialization is done via constructors. If a class is not initialized using a
* parameterized constructor, a public default constructor must be provided - if no public
* default constructor is provided, a compiler error will occur.
Once a const class object has been initialized via the constructor, you cannot modify
the object's member variables. This includes both directly making changes to
public member variables and calling member functions that set the value of member variables.
*
*/
const MyClassTest obj;
// MyClassTest obj;
// obj.TestFun(); // error with const
/*
* For const member functions that are defined outside of the class definition,
* the const keyword must be used on both the function prototype and definition.
*/
const s25_const obj2;
obj2.myPrint(); // Hello const
// Attempting to call a regular function from a constant object results in an error.
// obj2.test1(); // error
/*
* In addition, a compiler error is generated when any const
* member function attempts to change a member variable or to call a non-const member function.
*
* Defining constant objects and functions ensures that corresponding data members cannot be unexpectedly modified.
*
*/
// Constant member functions cannot modify any non-const members
return 0;
}
| 29.763441 | 119 | 0.692558 | [
"object"
] |
90a7c586c845213558c091f7922ec545a7440bf0 | 5,368 | cpp | C++ | storage/storage_builder.cpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 61 | 2015-12-05T19:34:20.000Z | 2021-06-25T09:07:09.000Z | storage/storage_builder.cpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 9 | 2016-02-19T23:22:20.000Z | 2017-01-03T18:41:04.000Z | storage/storage_builder.cpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 35 | 2015-12-17T00:09:14.000Z | 2021-01-27T10:47:11.000Z | #include "storage_builder.hpp"
#include "../env/writer.hpp"
#include "../env/assert.hpp"
#include "../env/logging.hpp"
#include "../env/latlon.hpp"
#include "../std/fstream.hpp"
#include "../std/iterator.hpp"
namespace
{
template <class ToDo>
void ProcessEntriesFile(string const & path, ToDo & toDo)
{
ifstream fs(path.c_str());
string str;
vector<string> entries;
while (!fs.eof())
{
getline(fs, str);
if (str.empty())
continue;
entries.clear();
str::Tokenize(str, "\t ", MakeBackInserter(entries));
toDo(entries);
}
}
bool EncodeTitle(string & s)
{
CHECK(!s.empty(), ());
// strip prefix before / or \.
size_t const i = s.find_last_of("\\/");
if (i != string::npos)
{
s = s.substr(i+1);
if (s.empty())
return false;
}
replace(s.begin(), s.end(), '_', ' ');
return true;
}
class DoAddEntries
{
StorageBuilder & m_storage;
public:
DoAddEntries(StorageBuilder & storage) : m_storage(storage) {}
void operator() (vector<string> const & entries)
{
CHECK(entries.size() == 8, (entries));
string title = entries[1];
if (!EncodeTitle(title))
return;
ArticleInfoBuilder builder(title);
builder.SetParams(entries);
m_storage.Add(builder);
}
};
class DoAddRedirects
{
StorageBuilder & m_storage;
public:
DoAddRedirects(StorageBuilder & storage) : m_storage(storage) {}
void operator() (vector<string> const & entries)
{
CHECK(entries.size() == 4, (entries));
ArticleInfoBuilder const * p = m_storage.GetArticle(entries[2]);
if (p)
{
string title = entries[1];
if (!EncodeTitle(title))
return;
m_storage.Add(ArticleInfoBuilder(title, *p, true));
}
else
LOG(WARNING, ("No article for url:", entries[2]));
}
};
class DoAddGeocodes
{
StorageBuilder & m_storage;
static double ToDouble(string const & s)
{
char * stop;
double const d = strtod(s.c_str(), &stop);
CHECK(stop && *stop == 0, (s));
return d;
}
public:
DoAddGeocodes(StorageBuilder & storage) : m_storage(storage) {}
void operator() (vector<string> const & entries)
{
CHECK(entries.size() == 3, (entries));
ArticleInfoBuilder * p = m_storage.GetArticle(entries[0]);
if (p)
{
double const lat = ToDouble(entries[1]);
double const lon = ToDouble(entries[2]);
if (ll::ValidLat(lat) && ll::ValidLon(lon))
p->SetLatLon(lat, lon);
else
LOG(WARNING, ("Bad Lat, Lon:", entries[1], entries[2]));
}
}
};
}
void ArticleInfoBuilder::SetParams(vector<string> const & entries)
{
m_url = entries[0];
m_length = atoi(entries[2].c_str());
CHECK(m_length != 0, (entries[2]));
m_parentUrl = entries[4];
}
void StorageBuilder::ParseEntries(string const & path)
{
DoAddEntries doAdd(*this);
ProcessEntriesFile(path, doAdd);
}
void StorageBuilder::ParseRedirects(string const & path)
{
DoAddRedirects doAdd(*this);
ProcessEntriesFile(path, doAdd);
}
void StorageBuilder::ParseGeocodes(string const & path)
{
DoAddGeocodes doAdd(*this);
ProcessEntriesFile(path, doAdd);
for (size_t i = 0; i < m_info.size(); ++i)
{
if (m_info[i].m_redirect)
{
ArticleInfoBuilder const * p = GetArticle(m_info[i].m_url);
CHECK(p, ());
m_info[i].SetLatLon(p->m_lat, p->m_lon);
}
}
}
void StorageBuilder::Add(ArticleInfoBuilder const & info)
{
m_info.push_back(info);
if (!info.m_redirect)
CHECK(m_url2info.insert(make_pair(info.m_url, m_info.size()-1)).second, (info.m_url));
}
void StorageBuilder::ProcessArticles()
{
sort(m_info.begin(), m_info.end(), ArticleInfo::LessStorage());
size_t const count = m_info.size();
for (size_t i = 0; i < count; ++i)
{
for (size_t j = 0; j < count; ++j)
{
if (i != j && !m_info[j].m_redirect && m_info[i].m_parentUrl == m_info[j].m_url)
{
m_info[i].m_parentIndex = j;
break;
}
}
}
}
void StorageBuilder::Save(string const & path)
{
ProcessArticles();
try
{
wr::FileWriter w(path);
size_t const count = m_info.size();
w.Write(static_cast<uint32_t>(count));
for (size_t i = 0; i < count; ++i)
m_info[i].Write(w);
}
catch (file::FileException const & ex)
{
LOG(ERROR, (ex));
}
}
void StorageBuilder::Load(string const & path)
{
Storage s;
s.Load(path);
m_info.assign(s.m_info.begin(), s.m_info.end());
}
void StorageBuilder::Assign(Storage & storage)
{
ProcessArticles();
storage.m_info.assign(m_info.begin(), m_info.end());
}
bool StorageBuilder::operator == (Storage const & s) const
{
if (m_info.size() != s.m_info.size())
return false;
for (size_t i = 0; i < m_info.size();++i)
if (!(m_info[i] == s.m_info[i]))
return false;
return true;
}
void StorageBuilder::InitMock()
{
ArticleInfoBuilder i1("London");
i1.m_url = "London";
i1.m_parentUrl = "Great_Britain";
i1.m_lat = 51.50726;
i1.m_lon = -0.12765;
Add(i1);
ArticleInfoBuilder i2("Lancaster");
i2.m_url = "Lancaster";
i2.m_parentUrl = "Great_Britain";
i2.m_lat = 54.04839;
i2.m_lon = -2.79904;
Add(i2);
ArticleInfoBuilder i3("Great Britain");
i3.m_url = "Great_Britain";
i3.m_lat = 54.70235;
i3.m_lon = -3.27656;
Add(i3);
}
StorageMock::StorageMock()
{
StorageBuilder builder;
builder.InitMock();
builder.Assign(*this);
}
| 19.881481 | 90 | 0.625931 | [
"vector"
] |
90ad1bb9db81c7e4d0ce8986b5d2d477ac7d50a6 | 1,483 | cpp | C++ | test/geo_test.cpp | hec12/nocow_library | 1993006627bc0f1d1e9d4678a00685ca6bd5e611 | [
"MIT"
] | null | null | null | test/geo_test.cpp | hec12/nocow_library | 1993006627bc0f1d1e9d4678a00685ca6bd5e611 | [
"MIT"
] | null | null | null | test/geo_test.cpp | hec12/nocow_library | 1993006627bc0f1d1e9d4678a00685ca6bd5e611 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)
#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)
#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))
#define popcount(n) (__builtin_popcountll(n))
using namespace std;
template<class T>bool chmax(T &a, const T &b) { return (a<b)?(a=b,1):0;}
template<class T>bool chmin(T &a, const T &b) { return (b<a)?(a=b,1):0;}
using ll=long long;
const int dx[8]={1,0,-1,0,1,-1,-1,1};
const int dy[8]={0,1,0,-1,1,1,-1,-1};
// Problem Specific Parameter:
using R=long double;
const R EPS=1e-9L; // [-1000,1000]->EPS=1e-8 [-10000,10000]->EPS=1e-7
inline int sgn(const R& r){return(r > EPS)-(r < -EPS);}
inline R sq(R x){return sqrt(max(x,0.0L));}
const R INF = 1E40L;
const R PI = acos(-1.0L);
using P=complex<R>;
const P O=0.0L;
using L=struct{P s,t;};
using VP=vector<P>;
using C=struct{P p;R c;};
auto pack(L a,L b){
using VLP=vector<tuple<L,P>>;
return VLP{{a,b.s},{a,b.t},{b,a.s},{b,a.t}};
}
int main(void){
L a={O,O},b={O,O};
auto res=pack(a,b);
return 0;
} | 29.078431 | 73 | 0.641268 | [
"vector"
] |
ff964b009032851fa4bd9cd5b7e8c9a2a917f272 | 16,210 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/core/test/unary_local_operation_test.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/core/test/unary_local_operation_test.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/core/test/unary_local_operation_test.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | // -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE fern algorithm algebra unary_local_operation
#include <boost/test/unit_test.hpp>
#include "fern/core/data_customization_point/scalar.h"
#include "fern/core/data_customization_point/vector.h"
#include "fern/feature/core/data_customization_point/array.h"
#include "fern/feature/core/data_customization_point/masked_array.h"
#include "fern/feature/core/data_customization_point/masked_scalar.h"
#include "fern/algorithm/algebra/elementary/absolute.h"
namespace fa = fern::algorithm;
using ArgumentValue = int32_t;
using ResultValue = int32_t;
template<
class ArgumentValue
>
using Algorithm = fa::absolute::detail::Algorithm<ArgumentValue>;
template<
class Value,
class Result
>
using OutOfRangePolicy = fa::absolute::OutOfRangePolicy<Value, Result>;
BOOST_AUTO_TEST_CASE(array_0d)
{
using InputNoDataPolicy = fa::InputNoDataPolicies<fa::SkipNoData>;
using OutputNoDataPolicy = fa::DontMarkNoData;
using Argument = ArgumentValue;
using Result = ResultValue;
fa::ParallelExecutionPolicy parallel;
fa::SequentialExecutionPolicy sequential;
OutputNoDataPolicy output_no_data_policy;
Argument argument{-5};
Result result{3};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result, 5);
result = 3;
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
parallel, argument, result);
BOOST_REQUIRE_EQUAL(result, 5);
}
BOOST_AUTO_TEST_CASE(array_0d_masked)
{
using InputNoDataPolicy = fa::InputNoDataPolicies<
fa::DetectNoDataByValue<bool>>;
using OutputNoDataPolicy = fa::MarkNoDataByValue<bool>;
using Argument = fern::MaskedScalar<ArgumentValue>;
using Result = fern::MaskedScalar<ResultValue>;
fa::SequentialExecutionPolicy sequential;
Argument argument;
Result result;
// Input is not masked.
{
argument.value() = -5;
argument.mask() = false;
result.value() = 3;
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask(), false);
BOOST_REQUIRE_EQUAL(result.value(), 5);
}
// Input is masked.
{
argument.value() = -5;
argument.mask() = true;
result.value() = 3;
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask(), true);
BOOST_REQUIRE_EQUAL(result.value(), 3);
}
// Input is out of domain.
{
// TODO Use sqrt, for example.
}
// Result goes out of range.
{
argument.value() = fern::min<ArgumentValue>();
argument.mask() = false;
result.value() = 3;
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
OutOfRangePolicy>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask(), true);
// Result value is max<ArgumentValue> + 1, which equals
// min<ArgumentValue>.
BOOST_REQUIRE_EQUAL(result.value(), fern::min<ArgumentValue>());
}
}
BOOST_AUTO_TEST_CASE(array_1d_sequential)
{
using InputNoDataPolicy = fa::InputNoDataPolicies<fa::SkipNoData>;
using OutputNoDataPolicy = fa::DontMarkNoData;
fa::SequentialExecutionPolicy sequential;
OutputNoDataPolicy output_no_data_policy;
// vector
{
using Argument = std::vector<ArgumentValue>;
using Result = std::vector<ResultValue>;
Argument argument{-5, 0, 5};
Result result{3, 3, 3};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result[0], 5);
BOOST_REQUIRE_EQUAL(result[1], 0);
BOOST_REQUIRE_EQUAL(result[2], 5);
}
// 1d array
{
using Argument = fern::Array<ArgumentValue, 1>;
using Result = fern::Array<ResultValue, 1>;
Argument argument{-5, 0, 5};
Result result{3, 3, 3};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result[0], 5);
BOOST_REQUIRE_EQUAL(result[1], 0);
BOOST_REQUIRE_EQUAL(result[2], 5);
}
// empty
{
using Argument = std::vector<ArgumentValue>;
using Result = std::vector<ResultValue>;
Argument argument;
Result result;
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
sequential, argument, result);
BOOST_CHECK(result.empty());
}
}
BOOST_AUTO_TEST_CASE(array_1d_parallel)
{
using InputNoDataPolicy = fa::InputNoDataPolicies<fa::SkipNoData>;
using OutputNoDataPolicy = fa::DontMarkNoData;
fa::ParallelExecutionPolicy parallel;
OutputNoDataPolicy output_no_data_policy;
// vector
{
using Argument = std::vector<ArgumentValue>;
using Result = std::vector<ResultValue>;
Argument argument{-5, 0, 5};
Result result{3, 3, 3};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
parallel, argument, result);
BOOST_REQUIRE_EQUAL(result[0], 5);
BOOST_REQUIRE_EQUAL(result[1], 0);
BOOST_REQUIRE_EQUAL(result[2], 5);
}
// 1d array
{
using Argument = fern::Array<ArgumentValue, 1>;
using Result = fern::Array<ResultValue, 1>;
Argument argument{-5, 0, 5};
Result result{3, 3, 3};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
parallel, argument, result);
BOOST_REQUIRE_EQUAL(result[0], 5);
BOOST_REQUIRE_EQUAL(result[1], 0);
BOOST_REQUIRE_EQUAL(result[2], 5);
}
// empty
{
using Argument = std::vector<ArgumentValue>;
using Result = std::vector<ResultValue>;
Argument argument;
Result result;
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
parallel, argument, result);
BOOST_CHECK(result.empty());
}
}
BOOST_AUTO_TEST_CASE(array_1d_masked)
{
using Argument = fern::MaskedArray<ArgumentValue, 1>;
using Result = fern::MaskedArray<ResultValue, 1>;
using InputNoDataPolicy = fa::InputNoDataPolicies<
fa::DetectNoDataByValue<fern::Mask<1>>>;
using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<1>>;
fa::SequentialExecutionPolicy sequential;
{
Argument argument{-5, 0, 5};
Result result(3);
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
result.fill(3);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask()[0], false);
BOOST_REQUIRE_EQUAL(result.mask()[1], false);
BOOST_REQUIRE_EQUAL(result.mask()[2], false);
BOOST_REQUIRE_EQUAL(result[0], 5);
BOOST_REQUIRE_EQUAL(result[1], 0);
BOOST_REQUIRE_EQUAL(result[2], 5);
result.fill(3);
argument.mask()[1] = true;
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask()[0], false);
BOOST_REQUIRE_EQUAL(result.mask()[1], true);
BOOST_REQUIRE_EQUAL(result.mask()[2], false);
BOOST_REQUIRE_EQUAL(result[0], 5);
BOOST_REQUIRE_EQUAL(result[1], 3);
BOOST_REQUIRE_EQUAL(result[2], 5);
}
// empty
{
Argument argument;
Result result;
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_CHECK_EQUAL(result.size(), 0u);
}
}
BOOST_AUTO_TEST_CASE(array_2d_sequential)
{
using InputNoDataPolicy = fa::InputNoDataPolicies<fa::SkipNoData>;
using OutputNoDataPolicy = fa::DontMarkNoData;
using Argument = fern::Array<ArgumentValue, 2>;
using Result = fern::Array<ResultValue, 2>;
fa::SequentialExecutionPolicy sequential;
OutputNoDataPolicy output_no_data_policy;
Argument argument{
{ -2, -1 },
{ 0, 9 },
{ 1, 2 }
};
Result result{
{ 3, 3 },
{ 3, 3 },
{ 3, 3 }
};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
sequential, argument, result);
BOOST_CHECK_EQUAL(result[0][0], 2);
BOOST_CHECK_EQUAL(result[0][1], 1);
BOOST_CHECK_EQUAL(result[1][0], 0);
BOOST_CHECK_EQUAL(result[1][1], 9);
BOOST_CHECK_EQUAL(result[2][0], 1);
BOOST_CHECK_EQUAL(result[2][1], 2);
}
BOOST_AUTO_TEST_CASE(array_2d_parallel)
{
using InputNoDataPolicy = fa::InputNoDataPolicies<fa::SkipNoData>;
using OutputNoDataPolicy = fa::DontMarkNoData;
using Argument = fern::Array<ArgumentValue, 2>;
using Result = fern::Array<ResultValue, 2>;
fa::ParallelExecutionPolicy parallel;
OutputNoDataPolicy output_no_data_policy;
Argument argument{
{ -2, -1 },
{ 0, 9 },
{ 1, 2 }
};
Result result{
{ 3, 3 },
{ 3, 3 },
{ 3, 3 }
};
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
InputNoDataPolicy{{}},
output_no_data_policy,
parallel, argument, result);
BOOST_CHECK_EQUAL(result[0][0], 2);
BOOST_CHECK_EQUAL(result[0][1], 1);
BOOST_CHECK_EQUAL(result[1][0], 0);
BOOST_CHECK_EQUAL(result[1][1], 9);
BOOST_CHECK_EQUAL(result[2][0], 1);
BOOST_CHECK_EQUAL(result[2][1], 2);
}
BOOST_AUTO_TEST_CASE(array_2d_masked)
{
using Argument = fern::MaskedArray<ArgumentValue, 2>;
using Result = fern::MaskedArray<ResultValue, 2>;
using InputNoDataPolicy = fa::InputNoDataPolicies<
fa::DetectNoDataByValue<fern::Mask<2>>>;
using OutputNoDataPolicy = fa::MarkNoDataByValue<fern::Mask<2>>;
fa::SequentialExecutionPolicy sequential;
{
Argument argument{
{ -2, -1 },
{ 0, 9 },
{ 1, 2 }
};
Result result{
{ 3, 3 },
{ 3, 3 },
{ 3, 3 }
};
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
result.fill(3);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask()[0][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[0][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[1][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[1][1], false);
BOOST_REQUIRE_EQUAL(result.mask()[2][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[2][1], false);
BOOST_CHECK_EQUAL(result[0][0], 2);
BOOST_CHECK_EQUAL(result[0][1], 1);
BOOST_CHECK_EQUAL(result[1][0], 0);
BOOST_CHECK_EQUAL(result[1][1], 9);
BOOST_CHECK_EQUAL(result[2][0], 1);
BOOST_CHECK_EQUAL(result[2][1], 2);
result.fill(3);
argument.mask()[1][1] = true;
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_REQUIRE_EQUAL(result.mask()[0][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[0][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[1][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[1][1], true);
BOOST_REQUIRE_EQUAL(result.mask()[2][0], false);
BOOST_REQUIRE_EQUAL(result.mask()[2][1], false);
BOOST_CHECK_EQUAL(result[0][0], 2);
BOOST_CHECK_EQUAL(result[0][1], 1);
BOOST_CHECK_EQUAL(result[1][0], 0);
BOOST_CHECK_EQUAL(result[1][1], 3);
BOOST_CHECK_EQUAL(result[2][0], 1);
BOOST_CHECK_EQUAL(result[2][1], 2);
}
// empty
{
Argument argument;
Result result;
InputNoDataPolicy input_no_data_policy{{argument.mask(), true}};
OutputNoDataPolicy output_no_data_policy(result.mask(), true);
fa::unary_local_operation<
Algorithm,
fa::unary::DiscardDomainErrors,
fa::unary::DiscardRangeErrors>(
input_no_data_policy,
output_no_data_policy,
sequential, argument, result);
BOOST_CHECK_EQUAL(result.size(), 0u);
}
}
| 29.634369 | 80 | 0.605552 | [
"vector"
] |
ff9a6d3269750f12d3d5f146d4534b638f3e63cb | 662 | cpp | C++ | C or C++/party.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-11-01T05:48:04.000Z | 2021-04-25T05:33:47.000Z | C or C++/party.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | null | null | null | C or C++/party.cpp | amitShindeGit/Miscellaneous-Programs | 11aa892628f44b51a8723d5f282d64f867b01be2 | [
"MIT"
] | 3 | 2020-10-31T05:29:55.000Z | 2021-06-19T09:33:53.000Z | #include <bits/stdc++.h>
//problem: https://codeforces.com/problemset/problem/115/A
using std::cin;
using std::cout;
using std::vector;
using std::ios_base;
using std::unordered_map;
using std::max;
using std::endl;
unordered_map<int,vector<int>> g;
int n;
int countDFS(int i)
{
int c=0;
for(auto k=g[i].begin();k != g[i].end();k++)
c = max(c,countDFS(*k)+1);
return c;
}
void solve()
{
int x;
cin >> n;
for(int i=1;i<=n;i++)
{
cin >> x;
g[x].push_back(i);
}
cout << countDFS(-1) << endl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
| 16.55 | 58 | 0.561934 | [
"vector"
] |
ff9f97c0266d4f647207e123f01d6c59c40aff2b | 3,205 | hpp | C++ | wrap.hpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 2 | 2019-11-23T12:35:49.000Z | 2022-02-10T08:27:54.000Z | wrap.hpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 8 | 2019-11-15T08:13:48.000Z | 2020-04-29T00:35:42.000Z | wrap.hpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | null | null | null | #ifndef WRAP_HPP
#define WRAP_HPP 1
#include "object.hpp"
#include "world_manager.hpp"
namespace isk {
template<class T>
class Wrap : public Object
{
public:
T _x; // the type being enabled for the ECS simulation
Wrap() = default;
Wrap(const Wrap& src) = default;
Wrap(Wrap&& src) = default;
Wrap(const T& src) : _x(src) {};
Wrap(T&& src) : _x(std::move(src)) {};
~Wrap() = default;
Wrap& operator=(const Wrap& src) = default;
Wrap& operator=(Wrap&& src) = default;
static std::weak_ptr<Wrap> track(const std::shared_ptr<Wrap>& src)
{
if (!src.get()) return std::weak_ptr<Wrap>();
{
const auto& _cache = cache();
auto& _staged = staging();
auto c_end = _cache.end();
auto s_end = _staged.end();
if ( s_end == std::find(_staged.begin(), s_end, src)
&& c_end == std::find(_cache.begin(), c_end, src))
_staged.push_back(src);
}
return src;
}
static void world_setup()
{
isk::WorldManager& cosmos = isk::WorldManager::get();
cosmos.register_update(update_all);
cosmos.register_gc(gc_all);
cosmos.register_load(load_all);
cosmos.register_save(save_all);
}
std::weak_ptr<Wrap> read_synthetic_id(FILE* src)
{
return isk::Object::read_synthetic_id(cache(), src);
}
void write_synthetic_id(const std::shared_ptr<Wrap>& src, FILE* dest)
{
isk::Object::write_synthetic_id(cache().size(), src, dest);
}
private:
static std::vector<std::shared_ptr<Wrap> >& cache()
{
static std::vector<std::shared_ptr<Wrap> > ooao; // std::vector<std::weak_ptr<Wrap> > fails on game load
return ooao;
}
static std::vector<std::shared_ptr<Wrap> >& staging()
{
static std::vector<std::shared_ptr<Wrap> > ooao;
return ooao;
}
static void take_live()
{
auto& staged = staging();
if (!staged.empty()) {
{
auto& _cache = cache();
_cache.insert(_cache.end(), staged.begin(), staged.end());
}
std::remove_reference_t<decltype(staged)> discard;
swap(staged, discard);
}
}
// save
static void update_all()
{
take_live();
for (auto i : cache()) {
Wrap* tmp = i.get();
if (!tmp) continue;
// just because it's going away doesn't mean it can't do things
// do not insert into cache() here, insert to staging instead
}
take_live();
}
static void gc_all() { isk::Object::gc_all(cache()); }
static void load_all(FILE* src)
{
{
std::remove_reference_t<decltype(staging())> discard;
swap(staging(), discard);
}
auto& _cache = cache();
{
std::remove_reference_t<decltype(staging())> discard;
swap(_cache, discard);
}
size_t tmp;
ZAIMONI_FREAD_OR_DIE(size_t, tmp, src)
if (0 == tmp) return;
std::vector<std::shared_ptr<Wrap> > dest;
while (0 < tmp--) dest.push_back(std::shared_ptr<Wrap>(new Wrap(zaimoni::read<T>(src))));
swap(dest, cache());
}
static void save_all(FILE* dest)
{
gc_all();
take_live();
auto& _cache = cache();
isk::Object::init_synthetic_ids(_cache);
size_t tmp = _cache.size();
ZAIMONI_FWRITE_OR_DIE(size_t, tmp, dest)
for (auto& i : _cache) zaimoni::write(i->_x,dest);
}
};
} // namespace isk
#endif
| 23.394161 | 107 | 0.626833 | [
"object",
"vector"
] |
ffa1c4d2bf38e4a40c43e700518f7b07090a330b | 13,402 | cpp | C++ | android-28/android/graphics/Bitmap.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/graphics/Bitmap.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-28/android/graphics/Bitmap.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JByteArray.hpp"
#include "../../JIntArray.hpp"
#include "./Bitmap_CompressFormat.hpp"
#include "./Bitmap_Config.hpp"
#include "./Canvas.hpp"
#include "./ColorSpace.hpp"
#include "./Matrix.hpp"
#include "./Paint.hpp"
#include "./Picture.hpp"
#include "../os/Parcel.hpp"
#include "../util/DisplayMetrics.hpp"
#include "../../java/io/OutputStream.hpp"
#include "../../java/nio/Buffer.hpp"
#include "./Bitmap.hpp"
namespace android::graphics
{
// Fields
JObject Bitmap::CREATOR()
{
return getStaticObjectField(
"android.graphics.Bitmap",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
jint Bitmap::DENSITY_NONE()
{
return getStaticField<jint>(
"android.graphics.Bitmap",
"DENSITY_NONE"
);
}
// QJniObject forward
Bitmap::Bitmap(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
android::graphics::Bitmap Bitmap::createBitmap(android::graphics::Bitmap arg0)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/graphics/Bitmap;)Landroid/graphics/Bitmap;",
arg0.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::graphics::Picture arg0)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/graphics/Picture;)Landroid/graphics/Bitmap;",
arg0.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(jint arg0, jint arg1, android::graphics::Bitmap_Config arg2)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0,
arg1,
arg2.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(JIntArray arg0, jint arg1, jint arg2, android::graphics::Bitmap_Config arg3)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"([IIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0.object<jintArray>(),
arg1,
arg2,
arg3.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::graphics::Picture arg0, jint arg1, jint arg2, android::graphics::Bitmap_Config arg3)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/graphics/Picture;IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::util::DisplayMetrics arg0, jint arg1, jint arg2, android::graphics::Bitmap_Config arg3)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/util/DisplayMetrics;IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(jint arg0, jint arg1, android::graphics::Bitmap_Config arg2, jboolean arg3)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(IILandroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;",
arg0,
arg1,
arg2.object(),
arg3
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::graphics::Bitmap arg0, jint arg1, jint arg2, jint arg3, jint arg4)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/graphics/Bitmap;IIII)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3,
arg4
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::util::DisplayMetrics arg0, JIntArray arg1, jint arg2, jint arg3, android::graphics::Bitmap_Config arg4)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/util/DisplayMetrics;[IIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0.object(),
arg1.object<jintArray>(),
arg2,
arg3,
arg4.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::util::DisplayMetrics arg0, jint arg1, jint arg2, android::graphics::Bitmap_Config arg3, jboolean arg4)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/util/DisplayMetrics;IILandroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3.object(),
arg4
);
}
android::graphics::Bitmap Bitmap::createBitmap(jint arg0, jint arg1, android::graphics::Bitmap_Config arg2, jboolean arg3, android::graphics::ColorSpace arg4)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(IILandroid/graphics/Bitmap$Config;ZLandroid/graphics/ColorSpace;)Landroid/graphics/Bitmap;",
arg0,
arg1,
arg2.object(),
arg3,
arg4.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(JIntArray arg0, jint arg1, jint arg2, jint arg3, jint arg4, android::graphics::Bitmap_Config arg5)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"([IIIIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0.object<jintArray>(),
arg1,
arg2,
arg3,
arg4,
arg5.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::util::DisplayMetrics arg0, jint arg1, jint arg2, android::graphics::Bitmap_Config arg3, jboolean arg4, android::graphics::ColorSpace arg5)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/util/DisplayMetrics;IILandroid/graphics/Bitmap$Config;ZLandroid/graphics/ColorSpace;)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3.object(),
arg4,
arg5.object()
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::graphics::Bitmap arg0, jint arg1, jint arg2, jint arg3, jint arg4, android::graphics::Matrix arg5, jboolean arg6)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/graphics/Bitmap;IIIILandroid/graphics/Matrix;Z)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3,
arg4,
arg5.object(),
arg6
);
}
android::graphics::Bitmap Bitmap::createBitmap(android::util::DisplayMetrics arg0, JIntArray arg1, jint arg2, jint arg3, jint arg4, jint arg5, android::graphics::Bitmap_Config arg6)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createBitmap",
"(Landroid/util/DisplayMetrics;[IIIIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;",
arg0.object(),
arg1.object<jintArray>(),
arg2,
arg3,
arg4,
arg5,
arg6.object()
);
}
android::graphics::Bitmap Bitmap::createScaledBitmap(android::graphics::Bitmap arg0, jint arg1, jint arg2, jboolean arg3)
{
return callStaticObjectMethod(
"android.graphics.Bitmap",
"createScaledBitmap",
"(Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;",
arg0.object(),
arg1,
arg2,
arg3
);
}
jboolean Bitmap::compress(android::graphics::Bitmap_CompressFormat arg0, jint arg1, java::io::OutputStream arg2) const
{
return callMethod<jboolean>(
"compress",
"(Landroid/graphics/Bitmap$CompressFormat;ILjava/io/OutputStream;)Z",
arg0.object(),
arg1,
arg2.object()
);
}
android::graphics::Bitmap Bitmap::copy(android::graphics::Bitmap_Config arg0, jboolean arg1) const
{
return callObjectMethod(
"copy",
"(Landroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;",
arg0.object(),
arg1
);
}
void Bitmap::copyPixelsFromBuffer(java::nio::Buffer arg0) const
{
callMethod<void>(
"copyPixelsFromBuffer",
"(Ljava/nio/Buffer;)V",
arg0.object()
);
}
void Bitmap::copyPixelsToBuffer(java::nio::Buffer arg0) const
{
callMethod<void>(
"copyPixelsToBuffer",
"(Ljava/nio/Buffer;)V",
arg0.object()
);
}
jint Bitmap::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
void Bitmap::eraseColor(jint arg0) const
{
callMethod<void>(
"eraseColor",
"(I)V",
arg0
);
}
android::graphics::Bitmap Bitmap::extractAlpha() const
{
return callObjectMethod(
"extractAlpha",
"()Landroid/graphics/Bitmap;"
);
}
android::graphics::Bitmap Bitmap::extractAlpha(android::graphics::Paint arg0, JIntArray arg1) const
{
return callObjectMethod(
"extractAlpha",
"(Landroid/graphics/Paint;[I)Landroid/graphics/Bitmap;",
arg0.object(),
arg1.object<jintArray>()
);
}
jint Bitmap::getAllocationByteCount() const
{
return callMethod<jint>(
"getAllocationByteCount",
"()I"
);
}
jint Bitmap::getByteCount() const
{
return callMethod<jint>(
"getByteCount",
"()I"
);
}
android::graphics::ColorSpace Bitmap::getColorSpace() const
{
return callObjectMethod(
"getColorSpace",
"()Landroid/graphics/ColorSpace;"
);
}
android::graphics::Bitmap_Config Bitmap::getConfig() const
{
return callObjectMethod(
"getConfig",
"()Landroid/graphics/Bitmap$Config;"
);
}
jint Bitmap::getDensity() const
{
return callMethod<jint>(
"getDensity",
"()I"
);
}
jint Bitmap::getGenerationId() const
{
return callMethod<jint>(
"getGenerationId",
"()I"
);
}
jint Bitmap::getHeight() const
{
return callMethod<jint>(
"getHeight",
"()I"
);
}
JByteArray Bitmap::getNinePatchChunk() const
{
return callObjectMethod(
"getNinePatchChunk",
"()[B"
);
}
jint Bitmap::getPixel(jint arg0, jint arg1) const
{
return callMethod<jint>(
"getPixel",
"(II)I",
arg0,
arg1
);
}
void Bitmap::getPixels(JIntArray arg0, jint arg1, jint arg2, jint arg3, jint arg4, jint arg5, jint arg6) const
{
callMethod<void>(
"getPixels",
"([IIIIIII)V",
arg0.object<jintArray>(),
arg1,
arg2,
arg3,
arg4,
arg5,
arg6
);
}
jint Bitmap::getRowBytes() const
{
return callMethod<jint>(
"getRowBytes",
"()I"
);
}
jint Bitmap::getScaledHeight(android::graphics::Canvas arg0) const
{
return callMethod<jint>(
"getScaledHeight",
"(Landroid/graphics/Canvas;)I",
arg0.object()
);
}
jint Bitmap::getScaledHeight(android::util::DisplayMetrics arg0) const
{
return callMethod<jint>(
"getScaledHeight",
"(Landroid/util/DisplayMetrics;)I",
arg0.object()
);
}
jint Bitmap::getScaledHeight(jint arg0) const
{
return callMethod<jint>(
"getScaledHeight",
"(I)I",
arg0
);
}
jint Bitmap::getScaledWidth(android::graphics::Canvas arg0) const
{
return callMethod<jint>(
"getScaledWidth",
"(Landroid/graphics/Canvas;)I",
arg0.object()
);
}
jint Bitmap::getScaledWidth(android::util::DisplayMetrics arg0) const
{
return callMethod<jint>(
"getScaledWidth",
"(Landroid/util/DisplayMetrics;)I",
arg0.object()
);
}
jint Bitmap::getScaledWidth(jint arg0) const
{
return callMethod<jint>(
"getScaledWidth",
"(I)I",
arg0
);
}
jint Bitmap::getWidth() const
{
return callMethod<jint>(
"getWidth",
"()I"
);
}
jboolean Bitmap::hasAlpha() const
{
return callMethod<jboolean>(
"hasAlpha",
"()Z"
);
}
jboolean Bitmap::hasMipMap() const
{
return callMethod<jboolean>(
"hasMipMap",
"()Z"
);
}
jboolean Bitmap::isMutable() const
{
return callMethod<jboolean>(
"isMutable",
"()Z"
);
}
jboolean Bitmap::isPremultiplied() const
{
return callMethod<jboolean>(
"isPremultiplied",
"()Z"
);
}
jboolean Bitmap::isRecycled() const
{
return callMethod<jboolean>(
"isRecycled",
"()Z"
);
}
void Bitmap::prepareToDraw() const
{
callMethod<void>(
"prepareToDraw",
"()V"
);
}
void Bitmap::reconfigure(jint arg0, jint arg1, android::graphics::Bitmap_Config arg2) const
{
callMethod<void>(
"reconfigure",
"(IILandroid/graphics/Bitmap$Config;)V",
arg0,
arg1,
arg2.object()
);
}
void Bitmap::recycle() const
{
callMethod<void>(
"recycle",
"()V"
);
}
jboolean Bitmap::sameAs(android::graphics::Bitmap arg0) const
{
return callMethod<jboolean>(
"sameAs",
"(Landroid/graphics/Bitmap;)Z",
arg0.object()
);
}
void Bitmap::setConfig(android::graphics::Bitmap_Config arg0) const
{
callMethod<void>(
"setConfig",
"(Landroid/graphics/Bitmap$Config;)V",
arg0.object()
);
}
void Bitmap::setDensity(jint arg0) const
{
callMethod<void>(
"setDensity",
"(I)V",
arg0
);
}
void Bitmap::setHasAlpha(jboolean arg0) const
{
callMethod<void>(
"setHasAlpha",
"(Z)V",
arg0
);
}
void Bitmap::setHasMipMap(jboolean arg0) const
{
callMethod<void>(
"setHasMipMap",
"(Z)V",
arg0
);
}
void Bitmap::setHeight(jint arg0) const
{
callMethod<void>(
"setHeight",
"(I)V",
arg0
);
}
void Bitmap::setPixel(jint arg0, jint arg1, jint arg2) const
{
callMethod<void>(
"setPixel",
"(III)V",
arg0,
arg1,
arg2
);
}
void Bitmap::setPixels(JIntArray arg0, jint arg1, jint arg2, jint arg3, jint arg4, jint arg5, jint arg6) const
{
callMethod<void>(
"setPixels",
"([IIIIIII)V",
arg0.object<jintArray>(),
arg1,
arg2,
arg3,
arg4,
arg5,
arg6
);
}
void Bitmap::setPremultiplied(jboolean arg0) const
{
callMethod<void>(
"setPremultiplied",
"(Z)V",
arg0
);
}
void Bitmap::setWidth(jint arg0) const
{
callMethod<void>(
"setWidth",
"(I)V",
arg0
);
}
void Bitmap::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::graphics
| 22.152066 | 195 | 0.677959 | [
"object"
] |
ffa32f44edbdb08d5ba7c2bfaa99bf725b950231 | 13,303 | hpp | C++ | include/hosts.hpp | dacom-core/unicore | 4fff619e3043f39d77e40d1612abb4dcbddc6649 | [
"MIT"
] | null | null | null | include/hosts.hpp | dacom-core/unicore | 4fff619e3043f39d77e40d1612abb4dcbddc6649 | [
"MIT"
] | null | null | null | include/hosts.hpp | dacom-core/unicore | 4fff619e3043f39d77e40d1612abb4dcbddc6649 | [
"MIT"
] | null | null | null |
// #include <eosio/transaction.hpp>
// #include <eosio.system/native.hpp>
#include "exchange_state.hpp"
#include "../src/exchange_state.cpp"
#include <eosio/crypto.hpp>
uint128_t combine_ids(const uint64_t &x, const uint64_t &y) {
return (uint128_t{x} << 64) | y;
};
/*!
\brief Структура основных параметров конфигурации Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] spiral{
uint64_t id;
uint64_t size_of_pool;
uint64_t quants_precision = 0;
uint64_t overlap;
uint64_t profit_growth;
uint64_t base_rate;
uint64_t loss_percent;
uint64_t pool_limit;
uint64_t pool_timeout;
uint64_t priority_seconds;
uint64_t primary_key() const {return id;}
EOSLIB_SERIALIZE(spiral, (id)(size_of_pool)(quants_precision)(overlap)(profit_growth)(base_rate)(loss_percent)(pool_limit)(pool_timeout)(priority_seconds))
};
typedef eosio::multi_index<"spiral"_n, spiral> spiral_index;
/*!
\brief Структура компенсационных параметров конфигурации Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] spiral2 {
uint64_t id;
uint64_t compensator_percent;
uint64_t primary_key() const {return id;}
EOSLIB_SERIALIZE(spiral2, (id)(compensator_percent))
};
typedef eosio::multi_index<"spiral2"_n, spiral2> spiral2_index;
/*!
\brief Структура курсов реализации внутренней конвертационной единицы и их возврата Протоколу.
*/
struct [[eosio::table, eosio::contract("unicore")]] rate {
uint64_t pool_id;
uint64_t buy_rate=0;
uint64_t sell_rate=0;
uint64_t convert_rate=0;
eosio::asset quant_buy_rate;
eosio::asset quant_sell_rate;
eosio::asset quant_convert_rate;
eosio::asset client_income;
eosio::asset delta;
eosio::asset pool_cost;
eosio::asset total_in_box;
// eosio::asset total_on_convert;
eosio::asset payment_to_wins;
eosio::asset payment_to_loss;
eosio::asset system_income;
eosio::asset live_balance_for_sale;
eosio::asset live_balance_for_convert;
uint64_t primary_key() const{return pool_id;}
EOSLIB_SERIALIZE(rate, (pool_id)(buy_rate)(sell_rate)(convert_rate)(quant_buy_rate)(quant_sell_rate)(quant_convert_rate)(client_income)(delta)(pool_cost)(total_in_box)(payment_to_wins)(payment_to_loss)(system_income)(live_balance_for_sale)(live_balance_for_convert))
};
typedef eosio::multi_index<"rate"_n, rate> rate_index;
/*!
\brief Структура хоста Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] hosts{
eosio::name username;
eosio::time_point_sec registered_at;
eosio::name architect;
eosio::name hoperator;
eosio::name type;
eosio::name chat_mode;
uint64_t consensus_percent;
uint64_t referral_percent;
uint64_t dacs_percent;
uint64_t cfund_percent;
uint64_t hfund_percent;
uint64_t sys_percent;
std::vector<uint64_t> levels;
std::vector<eosio::name> gsponsor_model;
bool direct_goal_withdraw = false;
uint64_t dac_mode;
uint64_t total_dacs_weight;
eosio::name ahost;
std::vector<eosio::name> chosts;
bool sale_is_enabled = false;
eosio::name sale_mode;
eosio::name sale_token_contract;
eosio::asset asset_on_sale;
uint64_t asset_on_sale_precision;
std::string asset_on_sale_symbol;
int64_t sale_shift = 0;
//Метод добавления хоста в фонд
//Метод включения сейла хостом
bool non_active_chost = false;
bool need_switch = false;
uint64_t fhosts_mode;
std::vector<eosio::name> fhosts;
std::string title;
std::string purpose;
bool voting_only_up = false;
eosio::name power_market_id;
uint64_t total_shares;
eosio::asset quote_amount;
eosio::name quote_token_contract;
std::string quote_symbol;
uint64_t quote_precision;
eosio::name root_token_contract;
eosio::asset root_token;
std::string symbol;
uint64_t precision;
eosio::asset to_pay;
bool payed = false;
uint64_t cycle_start_id = 0;
uint64_t current_pool_id = 0;
uint64_t current_cycle_num = 1;
uint64_t current_pool_num = 1;
bool parameters_setted = false;
bool activated = false;
bool priority_flag = false;
uint64_t total_goals = 0;
uint64_t achieved_goals = 0;
uint64_t total_tasks = 0;
uint64_t completed_tasks = 0;
uint64_t total_reports = 0;
uint64_t approved_reports = 0;
std::string meta;
EOSLIB_SERIALIZE( hosts, (username)(registered_at)(architect)(hoperator)(type)(chat_mode)(consensus_percent)(referral_percent)
(dacs_percent)(cfund_percent)(hfund_percent)(sys_percent)(levels)(gsponsor_model)(direct_goal_withdraw)(dac_mode)(total_dacs_weight)(ahost)(chosts)
(sale_is_enabled)(sale_mode)(sale_token_contract)(asset_on_sale)(asset_on_sale_precision)(asset_on_sale_symbol)(sale_shift)
(non_active_chost)(need_switch)(fhosts_mode)(fhosts)
(title)(purpose)(voting_only_up)(power_market_id)(total_shares)(quote_amount)(quote_token_contract)(quote_symbol)(quote_precision)(root_token_contract)(root_token)(symbol)(precision)
(to_pay)(payed)(cycle_start_id)(current_pool_id)
(current_cycle_num)(current_pool_num)(parameters_setted)(activated)(priority_flag)(total_goals)(achieved_goals)(total_tasks)(completed_tasks)(total_reports)(approved_reports)(meta))
uint64_t primary_key()const { return username.value; }
// eosoi::name gsponsor_model_is_exist(eosio::name model) const {
// auto it = std::find(gsponsor_model.begin(), gsponsor_model.end(), model);
// if (it == gsponsor_model.end())
// return false;
// else
// return true;
// }
eosio::name get_ahost() const {
if (ahost == username)
return username;
else
return ahost;
}
eosio::symbol get_root_symbol() const {
return root_token.symbol;
}
// bool is_account_in_whitelist(eosio::name username) const {
// auto it = std::find(whitelist.begin(), whitelist.end(), username);
// if (it == whitelist.end())
// return false;
// else
// return true;
// }
};
typedef eosio::multi_index <"hosts"_n, hosts> account_index;
/*!
\brief Расширение структуры хоста Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] hosts2 {
eosio::name username;
eosio::time_point_sec sale_price_updated_at;
uint64_t sale_price;
EOSLIB_SERIALIZE( hosts2, (username)(sale_price_updated_at)(sale_price))
uint64_t primary_key()const { return username.value; }
};
typedef eosio::multi_index <"hosts2"_n, hosts2> account2_index;
/*!
\brief Структура командных ролей протокола.
*/
struct [[eosio::table, eosio::contract("unicore")]] roles {
uint64_t role_id;
eosio::name model;
eosio::name lang;
std::string title;
std::string descriptor;
eosio::name suggester;
bool approved = false;
uint64_t primary_key() const {return role_id;}
EOSLIB_SERIALIZE(roles, (role_id)(model)(lang)(title)(descriptor)(suggester)(approved))
};
typedef eosio::multi_index <"roles"_n, roles> roles_index;
/*!
\brief Структура вакансии хоста Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] vacs {
uint64_t id;
eosio::name creator;
bool approved;
bool closed = false;
eosio::name limit_type;
eosio::asset income_limit;
uint64_t proposals;
uint64_t weight;
std::string role;
std::string description;
uint64_t primary_key() const {return id;}
uint64_t bycreator() const {return creator.value;}
EOSLIB_SERIALIZE(vacs, (id)(creator)(approved)(closed)(limit_type)(income_limit)(proposals)(weight)(role)(description))
};
typedef eosio::multi_index <"vacs"_n, vacs,
eosio::indexed_by<"bycreator"_n, eosio::const_mem_fun<vacs, uint64_t, &vacs::bycreator>>
> vacs_index;
/*!
\brief Структура заявки на вакансию хоста Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] vproposal {
uint64_t id;
uint64_t vac_id;
eosio::name creator;
eosio::name limit_type;
eosio::name income_limit;
uint64_t weight;
bool closed = false;
std::string why_me;
std::string contacts;
int64_t votes;
uint64_t primary_key() const {return id;}
uint64_t byusername() const {return creator.value;}
uint64_t byvacid() const {return vac_id;}
uint64_t byvotes() const {return votes;}
EOSLIB_SERIALIZE(vproposal, (id)(vac_id)(creator)(limit_type)(income_limit)(weight)(closed)(why_me)(contacts)(votes))
};
typedef eosio::multi_index <"vproposal"_n, vproposal,
eosio::indexed_by<"byusername"_n, eosio::const_mem_fun<vproposal, uint64_t, &vproposal::byusername>>,
eosio::indexed_by<"byvacid"_n, eosio::const_mem_fun<vproposal, uint64_t, &vproposal::byvacid>>,
eosio::indexed_by<"byvotes"_n, eosio::const_mem_fun<vproposal, uint64_t, &vproposal::byvotes>>
> vproposal_index;
/*!
\brief Структура команды хоста Двойной Спирали.
*/
struct [[eosio::table, eosio::contract("unicore")]] dacs {
eosio::name dac;
eosio::name limit_type;
uint64_t weight;
eosio::asset income;
uint128_t income_in_segments;
eosio::asset withdrawed;
eosio::asset income_limit;
eosio::time_point_sec last_pay_at;
eosio::time_point_sec created_at;
std::string role;
std::string description;
uint64_t primary_key() const {return dac.value;}
uint64_t bylimittype() const {return limit_type.value;}
EOSLIB_SERIALIZE(dacs, (dac)(limit_type)(weight)(income)(income_in_segments)(withdrawed)(income_limit)(last_pay_at)(created_at)(role)(description))
};
typedef eosio::multi_index <"dacs"_n, dacs> dacs_index;
/*!
\brief Структура параметров эмиссии целевого фонда хоста Двойной Спирали
*/
struct [[eosio::table, eosio::contract("unicore")]] emission {
eosio::name host;
uint64_t percent;
uint64_t gtop;
eosio::asset fund;
uint64_t primary_key() const {return host.value;}
EOSLIB_SERIALIZE(emission, (host)(percent)(gtop)(fund))
};
typedef eosio::multi_index<"emission"_n, emission> emission_index;
/*!
\brief Структура глобальных фондов владельцев жетонов, помещенных на распределение.
*/
struct [[eosio::table, eosio::contract("unicore")]] funds{
uint64_t id;
eosio::name issuer;
eosio::name token_contract;
eosio::asset fund;
std::string descriptor;
uint64_t primary_key()const { return id; }
uint64_t byissuer()const { return issuer.value; }
uint128_t codeandsmbl() const {return combine_ids(token_contract.value, fund.symbol.code().raw());}
EOSLIB_SERIALIZE(funds, (id)(issuer)(token_contract)(fund)(descriptor))
};
typedef eosio::multi_index<"funds"_n, funds,
eosio::indexed_by<"codeandsmbl"_n, eosio::const_mem_fun<funds, uint128_t,
&funds::codeandsmbl>>,
eosio::indexed_by<"byissuer"_n, eosio::const_mem_fun<funds, uint64_t,
&funds::byissuer>>
> funds_index;
// struct [[eosio::table, eosio::contract("unicore")]] histoffund{
// uint64_t id;
// uint64_t fund_id;
// eosio::name type;
// eosio::asset quantity;
// std::string memo;
// uint64_t primary_key()const { return id; }
// EOSLIB_SERIALIZE(histoffund, (id)(fund_id)(type)(quantity)(memo))
// }
/*!
\brief Структура хостов Двойной Спирали, подключенных к глобальным фондам распределения.
*/
struct [[eosio::table, eosio::contract("unicore")]] hostsonfunds{
uint64_t id;
uint64_t fund_id;
eosio::name host;
uint64_t primary_key()const { return id; }
uint128_t fundandhost() const {return combine_ids(fund_id, host.value);}
EOSLIB_SERIALIZE(hostsonfunds, (id)(fund_id)(host))
};
typedef eosio::multi_index<"hostsonfunds"_n, hostsonfunds,
eosio::indexed_by<"fundandhost"_n, eosio::const_mem_fun<hostsonfunds, uint128_t,
&hostsonfunds::fundandhost>>
> hostsonfunds_index;
| 32.055422 | 274 | 0.635421 | [
"vector",
"model"
] |
ffa5e9b91f4706442c6c2263a634367741468c38 | 2,028 | hpp | C++ | include/stats_incl/misc/matrix_ops/sum_absdiff.hpp | JohnGalbraith/stats | 309c0e92d2326a58cad4544124c614e6a8a46079 | [
"Apache-2.0"
] | 381 | 2017-07-16T17:34:02.000Z | 2022-03-30T09:47:58.000Z | include/stats_incl/misc/matrix_ops/sum_absdiff.hpp | myhhub/stats | 309c0e92d2326a58cad4544124c614e6a8a46079 | [
"Apache-2.0"
] | 29 | 2017-07-14T20:45:42.000Z | 2022-01-25T20:59:08.000Z | include/stats_incl/misc/matrix_ops/sum_absdiff.hpp | myhhub/stats | 309c0e92d2326a58cad4544124c614e6a8a46079 | [
"Apache-2.0"
] | 70 | 2017-10-25T14:16:11.000Z | 2022-01-25T20:57:02.000Z | /*################################################################################
##
## Copyright (C) 2011-2021 Keith O'Hara
##
## This file is part of the StatsLib C++ library.
##
## 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.
##
################################################################################*/
/*
* for internal use only; used to switch between the different matrix libraries
*/
//
// sum the absolute element-wise differences between two objects of the same dimensions
#ifdef STATS_ENABLE_STDVEC_WRAPPERS
template<typename eT>
statslib_inline
eT
sum_absdiff(const std::vector<eT>& X, const std::vector<eT>& Y)
{
eT val_out = eT(0);
ullint_t n_elem = X.size(); // assumes dim(X) = dim(Y)
for (ullint_t i=ullint_t(0); i < n_elem; ++i)
{
val_out += std::abs(X[i] - Y[i]);
}
return val_out;
}
#endif
#ifdef STATS_ENABLE_ARMA_WRAPPERS
template<typename eT>
statslib_inline
eT
sum_absdiff(const ArmaMat<eT>& X, const ArmaMat<eT>& Y)
{
return arma::accu(arma::abs(X - Y));
}
#endif
#ifdef STATS_ENABLE_BLAZE_WRAPPERS
template<typename eT, bool To>
statslib_inline
eT
sum_absdiff(const BlazeMat<eT,To>& X, const BlazeMat<eT,To>& Y)
{
return blaze::sum(blaze::abs(X-Y));
}
#endif
#ifdef STATS_ENABLE_EIGEN_WRAPPERS
template<typename eT, int iTr, int iTc>
statslib_inline
eT
sum_absdiff(const EigenMat<eT,iTr,iTc>& X, const EigenMat<eT,iTr,iTc>& Y)
{
return (X - Y).array().abs().sum();
}
#endif
| 27.04 | 87 | 0.631164 | [
"vector"
] |
ffa5f69aebaf21b2d6c75ae646ab695a6a974620 | 2,411 | inl | C++ | Math/Math/math/Vector3D.inl | sunshineheader/Math | 58578625465abfb91fc97ce7110328b41762c23f | [
"Apache-2.0"
] | null | null | null | Math/Math/math/Vector3D.inl | sunshineheader/Math | 58578625465abfb91fc97ce7110328b41762c23f | [
"Apache-2.0"
] | null | null | null | Math/Math/math/Vector3D.inl | sunshineheader/Math | 58578625465abfb91fc97ce7110328b41762c23f | [
"Apache-2.0"
] | null | null | null | #include "Vector3D.h"
using Math::Vector3D;
inline Vector3D::Vector3D()
:x(0.0f), y(0.0f), z(0.0f)
{}
inline Vector3D::Vector3D(const Vector3D & copy)
: x(copy.x), y(copy.y), z(copy.z)
{}
inline Vector3D::Vector3D(float xx, float yy, float zz)
: x(xx), y(yy), z(zz)
{}
inline Vector3D::~Vector3D()
{}
inline void Vector3D::add(const Vector3D & vector)
{
x += vector.x;
y += vector.y;
z += vector.z;
}
inline void Vector3D::subtract(const Vector3D & vector)
{
x -= vector.x;
y -= vector.y;
z -= vector.z;
}
inline void Vector3D::multiply(const Vector3D & vector)
{
x *= vector.x;
y *= vector.y;
z *= vector.z;
}
inline void Vector3D::divide(const Vector3D & vector)
{
x /= vector.x;
y /= vector.y;
z /= vector.z;
}
inline bool Vector3D::operator==(const Vector3D & vector)
{
return x == vector.x&&y == vector.y&&z == vector.z;
}
inline bool Vector3D::operator!=(const Vector3D & vector)
{
return x != vector.x || y != vector.y || z != vector.z;
}
inline const Vector3D Vector3D::operator+(const Vector3D & vector) const
{
Vector3D result(*this);
result.add(vector);
return result;
}
inline Vector3D& Vector3D::operator+=(const Vector3D & vector)
{
add(vector);
return *this;
}
inline const Vector3D Vector3D::operator-(const Vector3D & vector) const
{
Vector3D result(*this);
result.subtract(vector);
return result;
}
inline Vector3D& Vector3D::operator-=(const Vector3D & vector)
{
subtract(vector);
return *this;
}
inline const Vector3D Vector3D::operator*(const Vector3D & vector) const
{
Vector3D result(*this);
result.multiply(vector);
return result;
}
inline Vector3D& Vector3D::operator*=(const Vector3D & vector)
{
multiply(vector);
return *this;
}
inline const Vector3D Vector3D::operator/(const Vector3D & vector) const
{
Vector3D result(*this);
result.divide(vector);
return result;
}
inline Vector3D& Vector3D::operator/=(const Vector3D & vector)
{
divide(vector);
return *this;
}
inline void Vector3D::scale(float scalar)
{
x *= scalar;
y *= scalar;
z *= scalar;
}
inline void Vector3D::scale(const Vector3D & vector)
{
x *= vector.x;
y *= vector.y;
z *= vector.z;
}
inline const Vector3D operator*(float scalar, const Vector3D & right)
{
Vector3D result(right);
result.scale(scalar);
return result;
}
inline const Vector3D operator*(const Vector3D & left, float scalar)
{
Vector3D result(left);
result.scale(scalar);
return result;
}
| 19.443548 | 72 | 0.687681 | [
"vector"
] |
ffa6bbe65fd1c118de2dcb7d48b33e674c0e65ab | 254,987 | hpp | C++ | SDK/ARKSurvivalEvolved_SpaceDolphin_Character_BP_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_SpaceDolphin_Character_BP_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_SpaceDolphin_Character_BP_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_SpaceDolphin_Character_BP_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass SpaceDolphin_Character_BP.SpaceDolphin_Character_BP_C
// 0x1EB0 (0x4118 - 0x2268)
class ASpaceDolphin_Character_BP_C : public ADino_Character_BP_C
{
public:
class UAudioComponent* UnderwaterSound; // 0x2268(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UAudioComponent* ChargingHomingLaserSound; // 0x2270(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USkeletalMeshComponent* FPVSkelMesh; // 0x2278(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TailTrailLeftVFX; // 0x2280(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TailTrailCenterVFX; // 0x2288(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TailTrailRightVFX; // 0x2290(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* ChaffFireworks; // 0x2298(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* WaterSurfaceFX; // 0x22A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TailTrail; // 0x22A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* BarrelRollTrailRight; // 0x22B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* BarrelRollTrailLeft; // 0x22B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class URotatingMovementComponent* Rotating; // 0x22C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TurboJetLeftLow; // 0x22C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* OffGasLeftLow; // 0x22D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* JetLeftLow; // 0x22D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TurboJetRightLow; // 0x22E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* OffGasRightLow; // 0x22E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* JetRightLow; // 0x22F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TurboJetLeftHigh; // 0x22F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* OffGasLeftHigh; // 0x2300(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* JetLeftHigh; // 0x2308(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* RightJet; // 0x2310(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* LeftJet; // 0x2318(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Smoke; // 0x2320(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* ChargedLaserVFX; // 0x2328(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UDinoCharacterStatusComponent_BP_SpaceDolphin_C* DinoCharacterStatus_BP_SpaceDolphin_C1; // 0x2330(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UAudioComponent* AfterburnerLoop; // 0x2338(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UAudioComponent* ThrusterLoop; // 0x2340(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* MuzzleFlash; // 0x2348(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Right; // 0x2350(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Left; // 0x2358(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* TurboJetRightHigh; // 0x2360(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* OffGasRightHigh; // 0x2368(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* JetRightHigh; // 0x2370(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* RightTail; // 0x2378(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* LeftTail; // 0x2380(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
struct FVector TargetLatchingLoc; // 0x2388(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool LatchAnimStarted; // 0x2394(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x2395(0x0003) MISSED OFFSET
double LatchStartTime; // 0x2398(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsUnLatchingComplete; // 0x23A0(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData01[0x3]; // 0x23A1(0x0003) MISSED OFFSET
struct FVector LatchingDirection; // 0x23A4(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector LatchingSurfaceNormal; // 0x23B0(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool CanLatchOnGround; // 0x23BC(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool StartControllerRotation; // 0x23BD(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData02[0x2]; // 0x23BE(0x0002) MISSED OFFSET
float MaxLatchingAngle; // 0x23C0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData03[0x4]; // 0x23C4(0x0004) MISSED OFFSET
double UnlatchingStartTime; // 0x23C8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LatchingOffset; // 0x23D0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
bool bWasFirstPerson; // 0x23D4(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData04[0x3]; // 0x23D5(0x0003) MISSED OFFSET
float LatchInCameraTransitionDuration; // 0x23D8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LatchOutCameraTransitionDuration; // 0x23DC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bBrakeDinoPressed; // 0x23E0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool SuperFlight; // 0x23E1(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData05[0x2]; // 0x23E2(0x0002) MISSED OFFSET
struct FVector PrevCameraLoc; // 0x23E4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ServerRightAxisInput; // 0x23F0(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperFlightRightAxisInput; // 0x23F4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperFlightRollInterpSpeed; // 0x23F8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int LastFrameInterceptMoveRight; // 0x23FC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperFlightMaxRollAngle; // 0x2400(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CameraLookDeltaForSuperFlihtQuickTurn; // 0x2404(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeRequestedSuperFlightQuickTurn; // 0x2408(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperFlightQuickTurnCooldown; // 0x2410(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData06[0x4]; // 0x2414(0x0004) MISSED OFFSET
double LastSuperFlightQuickTurn; // 0x2418(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastSuperFlightQuickTurnStartTime; // 0x2420(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DefaultFOV; // 0x2428(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DotProductForDiving; // 0x242C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MinPercentDiveSpeedForDiving; // 0x2430(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float fovInterpSpeed; // 0x2434(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentFOV; // 0x2438(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData07[0x4]; // 0x243C(0x0004) MISSED OFFSET
double TimeStartedDive; // 0x2440(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DivingCameraShakeScale; // 0x2448(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DivingCameraShakeSpeed; // 0x244C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double TimeStoppedDiving; // 0x2450(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TamedWalkingSpeedMultiplierDiving; // 0x2458(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector TPVOffsetDiving; // 0x245C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<class UClass*> RiderBuffs; // 0x2468(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
float WindGustRadius; // 0x2478(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugWindGust; // 0x247C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData08[0x3]; // 0x247D(0x0003) MISSED OFFSET
class UClass* WindGustStructureSettingsClassForDamage; // 0x2480(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* WindGustTargetBuff; // 0x2488(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGustForwardOffset; // 0x2490(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData09[0x4]; // 0x2494(0x0004) MISSED OFFSET
class UParticleSystem* WindGustWindEmitter; // 0x2498(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* WindGustMontage; // 0x24A0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeRequestShootFlakCannon; // 0x24A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeTriggeredFlakCannon; // 0x24B0(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* FlakCannonProj; // 0x24B8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FName FlakCannonProjSpawnSocket; // 0x24C0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeAllyAOECheck; // 0x24C8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AllyAOERadius; // 0x24D0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PercentOfMaxSpeedForAllyAOE; // 0x24D4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* AllyAOEBuff; // 0x24D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AllyAOECheckCooldown; // 0x24E0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugAllyAOE; // 0x24E4(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData10[0x3]; // 0x24E5(0x0003) MISSED OFFSET
float TamedWalkingSpeedModifierNormalFlight; // 0x24E8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector WindGustScale; // 0x24EC(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperFlightAccelerationScale; // 0x24F8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlightDraftingRadius; // 0x24FC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsDrafting; // 0x2500(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData11[0x3]; // 0x2501(0x0003) MISSED OFFSET
float IsFlightDraftingDotProduct; // 0x2504(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastDraftingUpdateTime; // 0x2508(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FName SuperSaddleCustomTag; // 0x2510(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugDrawDrafting; // 0x2518(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData12[0x7]; // 0x2519(0x0007) MISSED OFFSET
class UClass* CarriedTargetBuff; // 0x2520(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* SaddleFuelItem; // 0x2528(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastConsumeFuelTime; // 0x2530(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FuelConsumeFrequency; // 0x2538(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector DefaultJetScale; // 0x253C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentZScale; // 0x2548(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData13[0x4]; // 0x254C(0x0004) MISSED OFFSET
double LastTimePlayedStruggleAnim; // 0x2550(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastWindGustRequestTime; // 0x2558(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* OnStruggleAnim; // 0x2560(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastForwardInputTime; // 0x2568(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RotationRateInterpSpeed; // 0x2570(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RotationRateMultSuperBoost; // 0x2574(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperBoostCameraShakeSpeed; // 0x2578(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperBoostCameraShakeScale; // 0x257C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector TPVOffsetSuperBoost; // 0x2580(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperBoostMaxRollAngle; // 0x258C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SuperFlightToggleEndDelay; // 0x2590(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData14[0x4]; // 0x2594(0x0004) MISSED OFFSET
double SuperFlightStartEndTime; // 0x2598(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FuelConsumeFrequencySuperBoost; // 0x25A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData15[0x4]; // 0x25A4(0x0004) MISSED OFFSET
class UParticleSystem* DraftingParticle; // 0x25A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpeedRequirementForDrafting; // 0x25B0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float UpdateDraftingInterval; // 0x25B4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector DraftingEmitterOffset; // 0x25B8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator DraftingParticleRotationOffset; // 0x25C4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastWindGustStart; // 0x25D0(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGustCooldown; // 0x25D8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGust180EndDelay; // 0x25DC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double WindGust180StartTime; // 0x25E0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UCurveFloat* WindGust180UpVelocityCurve; // 0x25E8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGust180UpVelocityScalar; // 0x25F0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGust180ForwardVelocityScalar; // 0x25F4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator WindGust180TargetRotation; // 0x25F8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RollAngleForTrailVisibility; // 0x2604(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* GroundGrindAnim; // 0x2608(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* FlyingGrindAnim; // 0x2610(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlakCannonCooldown; // 0x2618(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugChargedLaser; // 0x261C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData16[0x3]; // 0x261D(0x0003) MISSED OFFSET
float WindGust180Boost; // 0x2620(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData17[0x4]; // 0x2624(0x0004) MISSED OFFSET
class UAnimMontage* FlakCannonRecoilAnim; // 0x2628(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* FlakCannonAmmo; // 0x2630(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentCrosshairX; // 0x2638(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentCrosshairY; // 0x263C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CrosshairInterpSpeed; // 0x2640(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float NormalFlightTPVOffsetMultiplierZ; // 0x2644(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* _180Montage; // 0x2648(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double Last180Time; // 0x2650(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float _180CooldownTime; // 0x2658(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RunningSpeedModNormalFlight; // 0x265C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimePressedGamepadRightStick; // 0x2660(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeStartedRightThumbstickPress; // 0x2668(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool GamepadToggledSuperFlight; // 0x2670(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData18[0x3]; // 0x2671(0x0003) MISSED OFFSET
struct FRotator ReplicatedControlRotation; // 0x2674(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugAllowFireWeapons; // 0x2680(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData19[0x7]; // 0x2681(0x0007) MISSED OFFSET
double LastTimePressedJump; // 0x2688(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeReleasedJump; // 0x2690(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float IsDraftingDotProductForwardsMatching; // 0x2698(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData20[0x4]; // 0x269C(0x0004) MISSED OFFSET
TArray<class UAnimMontage*> BlockingAnim; // 0x26A0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
struct FName StartTamingBuff; // 0x26B0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StartTamingBuffDurationMultAdd; // 0x26B8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData21[0x4]; // 0x26BC(0x0004) MISSED OFFSET
double StartedRunningTime; // 0x26C0(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double StoppedRunningTime; // 0x26C8(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class USoundBase* AfterburnerOnSound; // 0x26D0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class USoundBase* AfterburnerOffSound; // 0x26D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class USoundBase* ThrusterOnSound; // 0x26E0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class USoundBase* ThrusterOffSound; // 0x26E8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class USoundAttenuation* ThrusterAttenuationSettings; // 0x26F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector TPVOffset180; // 0x26F8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CapsuleHalfHeightForDrafting; // 0x2704(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ThrusterVFXScaleAdditive; // 0x2708(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float JetFXScaleInterpSpeed; // 0x270C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float InitialThrusterVFXScaleAdditive; // 0x2710(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool Tameable; // 0x2714(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData22[0x3]; // 0x2715(0x0003) MISSED OFFSET
float AdditiveAccelerationOnDrafting; // 0x2718(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FuelConsumeFrequencyForwardInput; // 0x271C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UMaterialInstanceDynamic* SaddleDMIC; // 0x2720(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugSaddle; // 0x2728(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData23[0x3]; // 0x2729(0x0003) MISSED OFFSET
float LaserCooldown; // 0x272C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeTriggerLaserFire; // 0x2730(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* LaserAmmo; // 0x2738(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* LaserFireAnim; // 0x2740(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugLasers; // 0x2748(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData24[0x3]; // 0x2749(0x0003) MISSED OFFSET
float LaserRange; // 0x274C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LaserDamage; // 0x2750(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData25[0x4]; // 0x2754(0x0004) MISSED OFFSET
class UClass* LaserDamageType; // 0x2758(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UParticleSystem* LaserTrailVFX; // 0x2760(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastRequestFireLasers; // 0x2768(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FName LaserFireSocket; // 0x2770(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double TimeStartedCharge; // 0x2778(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxChargeTime; // 0x2780(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData26[0x4]; // 0x2784(0x0004) MISSED OFFSET
class UClass* ChargedLaserProjectile0; // 0x2788(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AActor* ChargedLaserTarget; // 0x2790(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserChargeTime; // 0x2798(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MinTimeForChargedLaser; // 0x279C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserBaseScale; // 0x27A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserRange; // 0x27A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserCrossHairRadius; // 0x27A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumPressedFwdCount; // 0x27AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsLooping; // 0x27B0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData27[0x7]; // 0x27B1(0x0007) MISSED OFFSET
class UCurveVector* LoopLocationCurve; // 0x27B8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double TimeStartLoop; // 0x27C0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LoopRadius; // 0x27C8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LoopSpeed; // 0x27CC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugLoop; // 0x27D0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData28[0x3]; // 0x27D1(0x0003) MISSED OFFSET
struct FVector LoopStartLocation; // 0x27D4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator StartLoopRotation; // 0x27E0(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsImmelmann; // 0x27EC(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData29[0x3]; // 0x27ED(0x0003) MISSED OFFSET
class UCurveVector* ImmelmannLocationCurve; // 0x27F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UCurveVector* ImmelmannRotationCurve; // 0x27F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ImmelmannSpeed; // 0x2800(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ImmelmannEndTime; // 0x2804(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentCrosshairSpread; // 0x2808(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CrosshairSpreadInterpSpeed; // 0x280C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AActor* CurrentChargedLaserTarget; // 0x2810(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
struct FAnchors TargetHUDAnchor; // 0x2818(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance)
int LaserLevel; // 0x2828(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData30[0x4]; // 0x282C(0x0004) MISSED OFFSET
double LastTimePlayedTerrainHitVFX; // 0x2830(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DistanceThresholdForLaserUpgradeSpawn; // 0x2838(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChanceToGetLaserUpgradeSpawn; // 0x283C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeSpawnedLaserUpgrade; // 0x2840(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LaserUpgradeSpawnCooldown; // 0x2848(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxLaserLevel; // 0x284C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool Damaged; // 0x2850(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData31[0x3]; // 0x2851(0x0003) MISSED OFFSET
struct FName StarFoxModeSplineTag; // 0x2854(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxModeRadius; // 0x285C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AMissionSpline* CurrentSpline; // 0x2860(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float CursorPlaneCameraOffset; // 0x2868(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxExtraRotationRateMult; // 0x286C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugStarFox; // 0x2870(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData32[0x7]; // 0x2871(0x0007) MISSED OFFSET
class AShooterProjectile* FiredProjectile; // 0x2878(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
struct FHUDElement CurrentChargedLaserHUDElement; // 0x2880(0x0150) (Edit, BlueprintVisible, DisableEditOnInstance)
class AShooterProjectile* FiredFlakCannonProjectile; // 0x29D0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float SpinningOffsetStarFoxMode; // 0x29D8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RotationRateMultSpinning; // 0x29DC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DefaultCrosshairSpread; // 0x29E0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MinCrosshairSpread; // 0x29E4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxCrossHairSpread; // 0x29E8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsBraking; // 0x29EC(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData33[0x3]; // 0x29ED(0x0003) MISSED OFFSET
float JetFXScaleBraking; // 0x29F0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BrakingSpeedMult; // 0x29F4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastPressedBrake; // 0x29F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RotationRateMultSpinningAndBraking; // 0x2A00(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RotationRateMultBraking; // 0x2A04(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UParticleSystem* StartedBrakingEmitter; // 0x2A08(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BrakingFOV; // 0x2A10(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData34[0x4]; // 0x2A14(0x0004) MISSED OFFSET
double TimeStartedBraking; // 0x2A18(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector TPVOffsetStarFoxMode; // 0x2A20(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator RotationRateStarFoxMode; // 0x2A2C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector TPVOffsetLooping; // 0x2A38(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector TPVOffsetImmelmann; // 0x2A44(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxAccelerationStarFoxMode; // 0x2A50(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData35[0x4]; // 0x2A54(0x0004) MISSED OFFSET
class UAnimMontage* BarrelRollLeftMontage; // 0x2A58(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BarrelRollCooldown; // 0x2A60(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData36[0x4]; // 0x2A64(0x0004) MISSED OFFSET
double LastBarrelRollTime; // 0x2A68(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BarrelRollSpeed; // 0x2A70(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool InfiniteFuel; // 0x2A74(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData37[0x3]; // 0x2A75(0x0003) MISSED OFFSET
float LasersTargetingRadius; // 0x2A78(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool LoopingHitWall; // 0x2A7C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData38[0x3]; // 0x2A7D(0x0003) MISSED OFFSET
float StarFoxModeCameraYOffsetScalar; // 0x2A80(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PrevClipX; // 0x2A84(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StructureBaseDamage; // 0x2A88(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxModeCameraRotationInterpSpeed; // 0x2A8C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxCameraCollisionOffsetScalar; // 0x2A90(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool StarFoxModeCameraDebugging; // 0x2A94(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData39[0x3]; // 0x2A95(0x0003) MISSED OFFSET
float StarFoxCameraCollisionScalarY; // 0x2A98(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxCameraCollisionRadius; // 0x2A9C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeChangedSpline; // 0x2AA0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator PrevCamRotation; // 0x2AA8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData40[0x4]; // 0x2AB4(0x0004) MISSED OFFSET
class AMissionSpline* PrevSpline; // 0x2AB8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
struct FName StarFoxModeDamageCollisionProfile; // 0x2AC0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FName StarFoxModePushCollisionProfile; // 0x2AC8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumStarFoxCollisions; // 0x2AD0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData41[0x4]; // 0x2AD4(0x0004) MISSED OFFSET
double LastTimeDidCollisionDamage; // 0x2AD8(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxCollisionDotDamage; // 0x2AE0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxModeZInterp; // 0x2AE4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double RiderSetTime; // 0x2AE8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RiderWarmupTime; // 0x2AF0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DamageOnTerrainCollision; // 0x2AF4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector DriftMovementInput; // 0x2AF8(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftSpeedBase; // 0x2B04(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftingInterpSpeed; // 0x2B08(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftAngleBase; // 0x2B0C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RotationRateMultSuperFlight; // 0x2B10(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpinningOffset; // 0x2B14(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftingMeshYawCurrent; // 0x2B18(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftingMeshInterpSpeed; // 0x2B1C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugDrifting; // 0x2B20(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData42[0x3]; // 0x2B21(0x0003) MISSED OFFSET
float DriftJetMaxScale; // 0x2B24(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftJetMinScale; // 0x2B28(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftBoostBaseSpeed; // 0x2B2C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double DriftStartTime; // 0x2B30(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftBoostMaxSpeed; // 0x2B38(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData43[0x4]; // 0x2B3C(0x0004) MISSED OFFSET
double DriftEndTime; // 0x2B40(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MostRecentDriftSpeed; // 0x2B48(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DriftingAllowedBoost; // 0x2B4C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData44[0x3]; // 0x2B4D(0x0003) MISSED OFFSET
double LastLaserLevelChangedTime; // 0x2B50(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData)
float LaserLevelDowngradeTime; // 0x2B58(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData45[0x4]; // 0x2B5C(0x0004) MISSED OFFSET
struct FScriptMulticastDelegate NewEventDispatcher; // 0x2B60(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
class UClass* SplineClass; // 0x2B70(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AddSuperBoostFOV; // 0x2B78(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData46[0x4]; // 0x2B7C(0x0004) MISSED OFFSET
class UAnimMontage* BarrelRollRightMontage; // 0x2B80(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool LastFrameMoveRightWasRight; // 0x2B88(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData47[0x3]; // 0x2B89(0x0003) MISSED OFFSET
struct FRotator CurrentDesiredRotation; // 0x2B8C(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxRotationRateDrifting; // 0x2B98(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData48[0x4]; // 0x2B9C(0x0004) MISSED OFFSET
class UCurveVector* DriftingRotationRateMultCurve; // 0x2BA0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AverageDriftingRotationDelta; // 0x2BA8(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData49[0x4]; // 0x2BAC(0x0004) MISSED OFFSET
class UCurveVector* DriftingTailWiggleCurve; // 0x2BB0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TailWiggleAmount; // 0x2BB8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TailWhipSpeed; // 0x2BBC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator RotatingMotionRotationRateCurrent; // 0x2BC0(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxExtraRotationRate; // 0x2BCC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector CurrentStarFoxCameraLoc; // 0x2BD0(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector PrevBarrelRollVelocity; // 0x2BDC(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool AllowBrakingInStarFoxMode; // 0x2BE8(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool AllowLoopInStarFoxMode; // 0x2BE9(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData50[0x2]; // 0x2BEA(0x0002) MISSED OFFSET
struct FVector StarFoxModeCameraDirection; // 0x2BEC(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxModeBarrelRollForwardSpeedMult; // 0x2BF8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxModeChargedLaserRange; // 0x2BFC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AMissionSpline* PrevMissionSpline; // 0x2C00(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
bool DisableStarFoxModeAfterLosingSplineTheFirstTime; // 0x2C08(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool StarFoxModeDisabled; // 0x2C09(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData51[0x2]; // 0x2C0A(0x0002) MISSED OFFSET
float MinFoV; // 0x2C0C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxFoV; // 0x2C10(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool LastFrameWasStarFoxCamera; // 0x2C14(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData52[0x3]; // 0x2C15(0x0003) MISSED OFFSET
struct FVector LastKnownUnCollidedLocStarFox; // 0x2C18(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxCollisionImpulseDirectionOffset; // 0x2C24(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxCollisionImpulseStrength; // 0x2C28(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxPushCollisionImpulseStrength; // 0x2C2C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeDidStarFoxCollisionImpulse; // 0x2C30(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugStarFoxCollision; // 0x2C38(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData53[0x3]; // 0x2C39(0x0003) MISSED OFFSET
float StarFoxCollisionImpulseCooldown; // 0x2C3C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugBarrelRoll; // 0x2C40(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData54[0x3]; // 0x2C41(0x0003) MISSED OFFSET
float LaserHitRadius; // 0x2C44(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector CrosshairAimStart; // 0x2C48(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector CrosshairAimEnd; // 0x2C54(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float groundFXOffset; // 0x2C60(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData55[0x4]; // 0x2C64(0x0004) MISSED OFFSET
double LastTimeTickedGroundFx; // 0x2C68(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugGroundFX; // 0x2C70(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData56[0x3]; // 0x2C71(0x0003) MISSED OFFSET
float WaterSurfaceTooHighThreshold; // 0x2C74(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UCurveVector* GroundFXScaleCurve; // 0x2C78(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeSplashVFXPlayed; // 0x2C80(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SplashVFXScale; // 0x2C88(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpashVFXDistanceThreshold; // 0x2C8C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float EchoLocationRadius; // 0x2C90(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData57[0x4]; // 0x2C94(0x0004) MISSED OFFSET
class UClass* EchoLocationEmitter; // 0x2C98(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeEchoLocation; // 0x2CA0(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float EchoLocationCooldown; // 0x2CA8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChaffDetectRadiusBase; // 0x2CAC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumChaffsToSpawn; // 0x2CB0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData58[0x4]; // 0x2CB4(0x0004) MISSED OFFSET
class UAnimMontage* ChaffAnim; // 0x2CB8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChaffExplosionScale; // 0x2CC0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData59[0x4]; // 0x2CC4(0x0004) MISSED OFFSET
double LastTimeChaff; // 0x2CC8(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChaffCooldown; // 0x2CD0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WaveMovementScale; // 0x2CD4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WaveMovementSpeed; // 0x2CD8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float NudgeImpulseWalking; // 0x2CDC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float NudgeImpulseFalling; // 0x2CE0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData60[0x4]; // 0x2CE4(0x0004) MISSED OFFSET
struct FMultiUseEntry WildPetMultiUseEntry; // 0x2CE8(0x0048) (Edit, BlueprintVisible, DisableEditOnInstance)
bool ForceFlee; // 0x2D30(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData61[0x3]; // 0x2D31(0x0003) MISSED OFFSET
float FleeFromPettingTime; // 0x2D34(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TimeToWildAnger; // 0x2D38(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData62[0x4]; // 0x2D3C(0x0004) MISSED OFFSET
class UAnimMontage* AngerMontage; // 0x2D40(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector BlowHoleEmitterScale; // 0x2D48(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float AngerRadius; // 0x2D54(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AShooterCharacter* AngryDolphinTarget; // 0x2D58(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
bool AngryDolphinBlowHoleTriggered; // 0x2D60(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData63[0x3]; // 0x2D61(0x0003) MISSED OFFSET
float TimeToDropAngryDinoAggro; // 0x2D64(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DistanceToAngryBlowHole; // 0x2D68(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxWildsToAnger; // 0x2D6C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumPetsWanted; // 0x2D70(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumFoodWanted; // 0x2D74(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int WildDemandLevel; // 0x2D78(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxWildDemandLevel; // 0x2D7C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UCurveVector* WildDemandsCurve; // 0x2D80(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FMultiUseEntry WildFoodMultiUseEntry; // 0x2D88(0x0048) (Edit, BlueprintVisible, DisableEditOnInstance)
double LastTimeMetDemands; // 0x2DD0(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* WildFoodItem; // 0x2DD8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LoopInterpSpeed; // 0x2DE0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChanceToSpawnSpaceWhale; // 0x2DE4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpaceWhaleSpawnOffset; // 0x2DE8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData64[0x4]; // 0x2DEC(0x0004) MISSED OFFSET
class AActor* SpaceWhaleIntroActorInstance; // 0x2DF0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float AngerTime; // 0x2DF8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool WildAngry; // 0x2DFC(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData65[0x3]; // 0x2DFD(0x0003) MISSED OFFSET
class UAnimMontage* WildSatisfiedAnim; // 0x2E00(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxDinoLevel; // 0x2E08(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float UntamedRunningSpeedModifierHasDemands; // 0x2E0C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugSpaceWhale; // 0x2E10(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData66[0x7]; // 0x2E11(0x0007) MISSED OFFSET
double LastTimeLoweredDino; // 0x2E18(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeRaisedDino; // 0x2E20(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsLoopingWithIncreasedRotationRate; // 0x2E28(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData67[0x3]; // 0x2E29(0x0003) MISSED OFFSET
float AffinityGainedOnElementFed; // 0x2E2C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TameIneffectivenessOnDamaged; // 0x2E30(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData68[0x4]; // 0x2E34(0x0004) MISSED OFFSET
class UClass* ChargedLaserProjectile1; // 0x2E38(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UClass* ChargedLaserProjectile2; // 0x2E40(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LaserLevelDowngradeTimeMax; // 0x2E48(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TamedWalkingSpeedModifierLaserLevel0; // 0x2E4C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TamedWalkingSpeedModifierLaserLevel2; // 0x2E50(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData69[0x4]; // 0x2E54(0x0004) MISSED OFFSET
TArray<struct FName> LaserSockets; // 0x2E58(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
float BarrelRollDamageRadius; // 0x2E68(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BarrelRollDamageBase; // 0x2E6C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool ChargedLaserRightSide; // 0x2E70(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData70[0x7]; // 0x2E71(0x0007) MISSED OFFSET
struct FScriptMulticastDelegate NewEventDispatcher0; // 0x2E78(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable)
float CurrentSuperFlightTransitionMaterialParam; // 0x2E88(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FPVFoV; // 0x2E8C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BarrelRollStaminaCost; // 0x2E90(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData71[0x4]; // 0x2E94(0x0004) MISSED OFFSET
double LastTimeChargedLaserHit; // 0x2E98(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserProgress; // 0x2EA0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentPowerMatParam; // 0x2EA4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor DefaultCrosshairColor; // 0x2EA8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentLockOnMatParam; // 0x2EB8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentEchoLocationMatParam; // 0x2EBC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAnimMontage* EchoLocationAnim; // 0x2EC0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PercentOfScreenToClampFPVCrosshair; // 0x2EC8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FPVCrosshairClampRadius; // 0x2ECC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentHasTargetMatParam; // 0x2ED0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentClipX; // 0x2ED4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentClipY; // 0x2ED8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentMouseX; // 0x2EDC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentMouseY; // 0x2EE0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugDrawMouseCursor; // 0x2EE4(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData72[0x3]; // 0x2EE5(0x0003) MISSED OFFSET
struct FVector CurrentLocalFPVCamLoc; // 0x2EE8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FPVLocalCamInterpSpeedX; // 0x2EF4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FPVLocalCamInterpSpeedY; // 0x2EF8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FLinearColor CurrentAimOffsetFromCenter; // 0x2EFC(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool AllowFlakCannonBackwardsFiring; // 0x2F0C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData73[0x3]; // 0x2F0D(0x0003) MISSED OFFSET
float GamepadMouseCursorInterpSpeed; // 0x2F10(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator PreOrbitCamDesiredRotation; // 0x2F14(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool LastFrameWasOrbitCam; // 0x2F20(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool BrakingInStarFoxModeEnablesOrbitCam; // 0x2F21(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool ResetStarFoxModeCamRotationAfterOrbitCam; // 0x2F22(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData74[0x1]; // 0x2F23(0x0001) MISSED OFFSET
float ImpactTerrainCameraShakeScale; // 0x2F24(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ImpactTerrainCamerShakeSpeed; // 0x2F28(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RunningCameraShakeScale; // 0x2F2C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float RunningCameraShakeSpeed; // 0x2F30(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGustCamerShakeScale; // 0x2F34(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WindGustCameraShakeSpeed; // 0x2F38(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftingBoostCameraShakeScale; // 0x2F3C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float DriftingBoostCamerShakeSpeed; // 0x2F40(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool StarFoxCollisionPushNeeded; // 0x2F44(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool HideHUDinFPV; // 0x2F45(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData75[0x2]; // 0x2F46(0x0002) MISSED OFFSET
float FuelPercent; // 0x2F48(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData76[0x4]; // 0x2F4C(0x0004) MISSED OFFSET
struct FHUDRichTextOverlayData SaddleActivationRichTextOverlay; // 0x2F50(0x0060) (Edit, BlueprintVisible, DisableEditOnInstance)
float SaddleActivationTextDisplayTime; // 0x2FB0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData77[0x4]; // 0x2FB4(0x0004) MISSED OFFSET
class AShooterHUD* RiderHUD; // 0x2FB8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
bool HasSaddleActivationRichTextOverlay; // 0x2FC0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool ReadyToDisplaySaddleActivationText; // 0x2FC1(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData78[0x6]; // 0x2FC2(0x0006) MISSED OFFSET
double LastSaddleActivationAddedTime; // 0x2FC8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bChachedIsSubmerged; // 0x2FD0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData79[0x7]; // 0x2FD1(0x0007) MISSED OFFSET
double ImmelmanEndTime; // 0x2FD8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PostImmelmanCameraControlTime; // 0x2FE0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PostImmelmanCameraRotInterpSpeed; // 0x2FE4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector ImmelmanCameraLocation; // 0x2FE8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData80[0x4]; // 0x2FF4(0x0004) MISSED OFFSET
class UCurveVector* ImmelmannCameraLocationCurve; // 0x2FF8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector ImmelmanCameraStartLocation; // 0x3000(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool ReactivateJetFXOneFrame; // 0x300C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData81[0x3]; // 0x300D(0x0003) MISSED OFFSET
class AShooterCharacter* TamingTarget; // 0x3010(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float SparksCooldown; // 0x3018(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData82[0x4]; // 0x301C(0x0004) MISSED OFFSET
double LastTimeTriggeredSparksVFX; // 0x3020(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector HUDChargedLaserTargetPosition; // 0x3028(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float HUDChargedLaserTargetPositionInterp; // 0x3034(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator LocalDesiredRotation; // 0x3038(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector FPVMeshOffset; // 0x3044(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator FPVMeshRotOffset; // 0x3050(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData83[0x4]; // 0x305C(0x0004) MISSED OFFSET
class UParticleSystem* LaserMuzzleVFX; // 0x3060(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector FPVSaddleMeshOffset; // 0x3068(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FRotator FPVSaddleRotOffset; // 0x3074(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool GamepadLeftTriggerPressed; // 0x3080(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData84[0x3]; // 0x3081(0x0003) MISSED OFFSET
struct FRotator PrevCamRot; // 0x3084(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FPVMeshRotInterpSpeed; // 0x3090(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxFPVMeshRotDelta; // 0x3094(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector FPVMeshInterpOffset; // 0x3098(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FPVShakeScalar; // 0x30A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAudioComponent* ThrusterOnSoundComp; // 0x30A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UAudioComponent* AfterburnerOnSoundComp; // 0x30B0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpinningPitch; // 0x30B8(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TimeUntilAffinityDrain; // 0x30BC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeDrainedCurrentAffinity; // 0x30C0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float PercentOfRequiredTameAffinityToTrainAffinity; // 0x30C8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TameIneffectivenessOnMetDemands; // 0x30CC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastBarrelRollEndTime; // 0x30D0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastLoopEndTime; // 0x30D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserCooldownBarrelRoll; // 0x30E0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserCooldownImmelmann; // 0x30E4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float ChargedLaserCooldownLoop; // 0x30E8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsInStarFoxMode; // 0x30EC(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bJustEnteredStarFoxMode; // 0x30ED(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData85[0x2]; // 0x30EE(0x0002) MISSED OFFSET
float StarFoxGamePadX; // 0x30F0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxGamePadY; // 0x30F4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxGamePadClipX; // 0x30F8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float StarFoxGamePadClipY; // 0x30FC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int SaddleMatIndex; // 0x3100(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool IsLockOnMePrevented; // 0x3104(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData86[0x3]; // 0x3105(0x0003) MISSED OFFSET
float LargeCircleInterpSpeedX; // 0x3108(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LargeCircleInterpSpeedY; // 0x310C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LargeCircleScale; // 0x3110(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float HasTargetInterpSpeed; // 0x3114(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugForceMouseCursorOn; // 0x3118(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData87[0x3]; // 0x3119(0x0003) MISSED OFFSET
struct FName SilenceImmunityTag; // 0x311C(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float LockOnInterpSpeed; // 0x3124(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool FiredChargedLaserAtTarget; // 0x3128(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TEnumAsByte<ECollisionChannel> LaserTraceChannel; // 0x3129(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData88[0x6]; // 0x312A(0x0006) MISSED OFFSET
class AMissionSpline* CallFunc_IsStarFoxMode_CurrentSpline; // 0x3130(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_ReturnValue; // 0x3138(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData89[0x7]; // 0x3139(0x0007) MISSED OFFSET
double CallFunc_IsStarFoxMode_RetRiderSetTime; // 0x3140(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_RetIsRiderWarmup; // 0x3148(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue; // 0x3149(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue; // 0x314A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue2; // 0x314B(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue3; // 0x314C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData90[0x3]; // 0x314D(0x0003) MISSED OFFSET
int Temp_int_Loop_Counter_Variable; // 0x3150(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int CallFunc_Add_IntInt_ReturnValue; // 0x3154(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_NotEqual_ObjectObject_ReturnValue; // 0x3158(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData91[0x3]; // 0x3159(0x0003) MISSED OFFSET
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue; // 0x315C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue; // 0x3168(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData92[0x4]; // 0x3174(0x0004) MISSED OFFSET
class APlayerController* CallFunc_GetPlayerController_ReturnValue; // 0x3178(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float K2Node_CustomEvent_DeltaSeconds2; // 0x3180(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue; // 0x3184(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Subtract_VectorVector_ReturnValue; // 0x3190(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData93[0x4]; // 0x319C(0x0004) MISSED OFFSET
class UPawnMovementComponent* CallFunc_GetMovementComponent_ReturnValue; // 0x31A0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_VSize_ReturnValue; // 0x31A8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData94[0x4]; // 0x31AC(0x0004) MISSED OFFSET
double CallFunc_GetGameTimeInSeconds_ReturnValue; // 0x31B0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue; // 0x31B8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_NegateVector_ReturnValue; // 0x31C4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AController* CallFunc_GetController_ReturnValue; // 0x31D0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue; // 0x31D8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue2; // 0x31E4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Pitch; // 0x31F0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw; // 0x31F4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll; // 0x31F8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_NegateVector_ReturnValue2; // 0x31FC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue3; // 0x3208(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue2; // 0x3214(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue4; // 0x3220(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Pitch2; // 0x322C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw2; // 0x3230(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll2; // 0x3234(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_ComposeRotators_ReturnValue; // 0x3238(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Subtract_FloatFloat_ReturnValue; // 0x3244(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Abs_ReturnValue; // 0x3248(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue3; // 0x324C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue; // 0x3258(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_SetActorRotation_ReturnValue; // 0x3259(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue; // 0x325A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue; // 0x325B(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue5; // 0x325C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Pitch3; // 0x3268(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw3; // 0x326C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll3; // 0x3270(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_NegateVector_ReturnValue3; // 0x3274(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue4; // 0x3280(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Pitch4; // 0x328C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw4; // 0x3290(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll4; // 0x3294(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Subtract_FloatFloat_ReturnValue2; // 0x3298(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Abs_ReturnValue2; // 0x329C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_NegateVector_ReturnValue4; // 0x32A0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue2; // 0x32AC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData95[0x3]; // 0x32AD(0x0003) MISSED OFFSET
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue5; // 0x32B0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue2; // 0x32BC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData96[0x3]; // 0x32BD(0x0003) MISSED OFFSET
float CallFunc_BreakRot_Pitch5; // 0x32C0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw5; // 0x32C4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll5; // 0x32C8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue2; // 0x32CC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue; // 0x32CD(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData97[0x2]; // 0x32CE(0x0002) MISSED OFFSET
float CallFunc_Dot_VectorVector_ReturnValue; // 0x32D0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_DegAcos_ReturnValue; // 0x32D4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AController* CallFunc_GetController_ReturnValue2; // 0x32D8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController; // 0x32E0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast_CastSuccess; // 0x32E8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData98[0x7]; // 0x32E9(0x0007) MISSED OFFSET
class AController* CallFunc_GetController_ReturnValue3; // 0x32F0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue; // 0x32F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData99[0x7]; // 0x32F9(0x0007) MISSED OFFSET
class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController2; // 0x3300(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast2_CastSuccess; // 0x3308(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue2; // 0x3309(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData100[0x2]; // 0x330A(0x0002) MISSED OFFSET
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue6; // 0x330C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Conv_RotatorToVector_ReturnValue; // 0x3318(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData101[0x4]; // 0x3324(0x0004) MISSED OFFSET
class USceneComponent* CallFunc_K2_GetRootComponent_ReturnValue; // 0x3328(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Dot_VectorVector_ReturnValue2; // 0x3330(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData102[0x4]; // 0x3334(0x0004) MISSED OFFSET
class AController* CallFunc_GetController_ReturnValue4; // 0x3338(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue3; // 0x3340(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData103[0x3]; // 0x3341(0x0003) MISSED OFFSET
struct FRotator CallFunc_MakeRotFromX_ReturnValue; // 0x3344(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimMontage_ReturnValue; // 0x3350(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float K2Node_CustomEvent_DeltaTime; // 0x3354(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FName K2Node_Event_CustomEventName; // 0x3358(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class USkeletalMeshComponent* K2Node_Event_MeshComp; // 0x3360(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAnimSequenceBase* K2Node_Event_Animation; // 0x3368(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAnimNotify* K2Node_Event_AnimNotifyObject; // 0x3370(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_NameName_ReturnValue; // 0x3378(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_NameName_ReturnValue2; // 0x3379(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_NameName_ReturnValue3; // 0x337A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_CustomEvent_LatchingInterrupted; // 0x337B(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimMontage_ReturnValue2; // 0x337C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue3; // 0x3380(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData104[0x3]; // 0x3381(0x0003) MISSED OFFSET
float CallFunc_PlayAnimMontage_ReturnValue3; // 0x3384(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_True_if_break_was_hit_Variable; // 0x3388(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue; // 0x3389(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData105[0x2]; // 0x338A(0x0002) MISSED OFFSET
float CallFunc_PlayAnimMontage_ReturnValue4; // 0x338C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue2; // 0x3390(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData106[0x3]; // 0x3391(0x0003) MISSED OFFSET
struct FVector CallFunc_NegateVector_ReturnValue5; // 0x3394(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue6; // 0x33A0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Dot_VectorVector_ReturnValue3; // 0x33AC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Pitch6; // 0x33B0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Yaw6; // 0x33B4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BreakRot_Roll6; // 0x33B8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_DegAcos_ReturnValue2; // 0x33BC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Add_FloatFloat_ReturnValue; // 0x33C0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue2; // 0x33C4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue3; // 0x33D0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData107[0x3]; // 0x33D1(0x0003) MISSED OFFSET
struct FVector CallFunc_Add_VectorVector_ReturnValue2; // 0x33D4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue3; // 0x33E0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsFirstPerson_ReturnValue; // 0x33EC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_K2_SetActorLocation_ReturnValue; // 0x33ED(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue4; // 0x33EE(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue4; // 0x33EF(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue5; // 0x33F0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue6; // 0x33F1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData108[0x2]; // 0x33F2(0x0002) MISSED OFFSET
float K2Node_CustomEvent_yaw; // 0x33F4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float K2Node_CustomEvent_Pitch; // 0x33F8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float K2Node_CustomEvent_Roll; // 0x33FC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int Temp_int_Loop_Counter_Variable2; // 0x3400(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Add_FloatFloat_ReturnValue2; // 0x3404(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int CallFunc_Add_IntInt_ReturnValue2; // 0x3408(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Add_FloatFloat_ReturnValue3; // 0x340C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasAuthority_ReturnValue; // 0x3410(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData109[0x7]; // 0x3411(0x0007) MISSED OFFSET
TArray<class APrimalCharacter*> CallFunc_GetPassengers_ReturnValue; // 0x3418(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
int CallFunc_Array_Length_ReturnValue; // 0x3428(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_CustomEvent_backwardsLatching; // 0x342C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData110[0x3]; // 0x342D(0x0003) MISSED OFFSET
float K2Node_CustomEvent_DeltaSeconds; // 0x3430(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_RInterpTo_ReturnValue; // 0x3434(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_MakeVector_ReturnValue; // 0x3440(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_SetActorRotation_ReturnValue2; // 0x344C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData111[0x3]; // 0x344D(0x0003) MISSED OFFSET
struct FVector CallFunc_MakeVector_ReturnValue2; // 0x3450(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue3; // 0x345C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue4; // 0x345D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue2; // 0x345E(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue5; // 0x345F(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetVelocity_ReturnValue; // 0x3460(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue7; // 0x346C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Normal_ReturnValue; // 0x3478(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetForwardVector_ReturnValue; // 0x3484(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Dot_VectorVector_ReturnValue4; // 0x3490(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float K2Node_CustomEvent_AxisValue2; // 0x3494(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_GreaterEqual_FloatFloat_ReturnValue; // 0x3498(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_FloatFloat_ReturnValue; // 0x3499(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData112[0x6]; // 0x349A(0x0006) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue; // 0x34A0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue2; // 0x34A8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Is_Quick_Turning_ReturnValue; // 0x34A9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData113[0x2]; // 0x34AA(0x0002) MISSED OFFSET
struct FVector K2Node_CustomEvent_Epicenter; // 0x34AC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode; // 0x34B8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum_CmpSuccess; // 0x34B9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode2; // 0x34BA(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData114[0x1]; // 0x34BB(0x0001) MISSED OFFSET
struct FVector CallFunc_GetWindGustEpicenter_ReturnValue; // 0x34BC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum2_CmpSuccess; // 0x34C8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData115[0x3]; // 0x34C9(0x0003) MISSED OFFSET
struct FVector K2Node_CustomEvent_Dir2; // 0x34CC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_Loc2; // 0x34D8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue8; // 0x34E4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue; // 0x34F0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasSaddle_Ret; // 0x34F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasSaddle_RetIsSuperSaddle; // 0x34F9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue6; // 0x34FA(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasFuel_ReturnValue; // 0x34FB(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int CallFunc_HasFuel_Quantity; // 0x34FC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue3; // 0x3500(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue4; // 0x3501(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData116[0x2]; // 0x3502(0x0002) MISSED OFFSET
float K2Node_InputAxisEvent_AxisValue; // 0x3504(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue3; // 0x3508(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData117[0x3]; // 0x3509(0x0003) MISSED OFFSET
float CallFunc_Multiply_FloatFloat_ReturnValue; // 0x350C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int Temp_int_Loop_Counter_Variable3; // 0x3510(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_IntInt_ReturnValue; // 0x3514(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData118[0x3]; // 0x3515(0x0003) MISSED OFFSET
class APrimalCharacter* CallFunc_Array_Get_Item; // 0x3518(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterCharacter* K2Node_DynamicCast_AsShooterCharacter; // 0x3520(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast3_CastSuccess; // 0x3528(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData119[0x3]; // 0x3529(0x0003) MISSED OFFSET
int CallFunc_Add_IntInt_ReturnValue3; // 0x352C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_NameName_ReturnValue4; // 0x3530(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData120[0x7]; // 0x3531(0x0007) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue2; // 0x3538(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue3; // 0x3540(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_K2_IsTimerActive_ReturnValue; // 0x3541(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData121[0x6]; // 0x3542(0x0006) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue3; // 0x3548(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue4; // 0x3550(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData122[0x7]; // 0x3551(0x0007) MISSED OFFSET
class APrimalCharacter* K2Node_CustomEvent_Target2; // 0x3558(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetActorForwardVector_ReturnValue; // 0x3560(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue2; // 0x356C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue3; // 0x3578(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue4; // 0x3584(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool Temp_bool_True_if_break_was_hit_Variable2; // 0x3590(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData123[0x7]; // 0x3591(0x0007) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAttached_ReturnValue; // 0x3598(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue7; // 0x35A0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData124[0x7]; // 0x35A1(0x0007) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue; // 0x35A8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_TimeSince_Network_ReturnValue; // 0x35B0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_GetWorldDeltaSeconds_ReturnValue; // 0x35B4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_GetFloatValue_ReturnValue; // 0x35B8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue2; // 0x35BC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue3; // 0x35C0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsServer_ReturnValue; // 0x35CC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData125[0x3]; // 0x35CD(0x0003) MISSED OFFSET
struct FVector CallFunc_GetActorUpVector_ReturnValue; // 0x35D0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FLinearColor CallFunc_SelectColor_ReturnValue; // 0x35DC(0x0010) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData126[0x4]; // 0x35EC(0x0004) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue2; // 0x35F0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_TimeSince_Network_ReturnValue2; // 0x35F8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetActorForwardVector_ReturnValue2; // 0x35FC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_GetFloatValue_ReturnValue2; // 0x3608(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue3; // 0x360C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue4; // 0x3610(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue4; // 0x3614(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue5; // 0x3620(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_K2_GetActorRotation_ReturnValue9; // 0x3624(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue5; // 0x3630(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue5; // 0x363C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_GetWorldDeltaSeconds_ReturnValue2; // 0x3648(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue6; // 0x364C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_QInterpTo_ReturnValue; // 0x3658(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_SetActorRotation_ReturnValue3; // 0x3664(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<EMovementMode> CallFunc_GetPrimalCharMovementMode_ReturnValue; // 0x3665(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_SetActorRotation_ReturnValue4; // 0x3666(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum3_CmpSuccess; // 0x3667(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue4; // 0x3668(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetActorForwardVector_ReturnValue3; // 0x3674(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Subtract_VectorVector_ReturnValue2; // 0x3680(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Dot_VectorVector_ReturnValue5; // 0x368C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_VSize_ReturnValue2; // 0x3690(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue5; // 0x3694(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue4; // 0x3695(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData127[0x2]; // 0x3696(0x0002) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue3; // 0x3698(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue5; // 0x36A0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData128[0x4]; // 0x36AC(0x0004) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue4; // 0x36B0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BPFastTrace_ReturnValue; // 0x36B8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue5; // 0x36B9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData129[0x2]; // 0x36BA(0x0002) MISSED OFFSET
struct FVector CallFunc_GetActorForwardVector_ReturnValue4; // 0x36BC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue6; // 0x36C8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData130[0x4]; // 0x36D4(0x0004) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue5; // 0x36D8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue7; // 0x36E0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Conv_RotatorToVector_ReturnValue2; // 0x36EC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsLocallyControlledByPlayer_ReturnValue; // 0x36F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData131[0x3]; // 0x36F9(0x0003) MISSED OFFSET
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue7; // 0x36FC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue7; // 0x3708(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData132[0x4]; // 0x3714(0x0004) MISSED OFFSET
class AController* CallFunc_GetController_ReturnValue5; // 0x3718(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController3; // 0x3720(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast4_CastSuccess; // 0x3728(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasAmmo_ReturnValue; // 0x3729(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData133[0x2]; // 0x372A(0x0002) MISSED OFFSET
int CallFunc_HasAmmo_Quantity; // 0x372C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UWorld* CallFunc_K2_GetWorld_ReturnValue4; // 0x3730(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_GetNetworkTimeInSeconds_ReturnValue6; // 0x3738(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue6; // 0x3740(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData134[0x3]; // 0x3741(0x0003) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue; // 0x3744(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue; // 0x3748(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData135[0x7]; // 0x3749(0x0007) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue7; // 0x3750(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_GetNetworkTimeInSeconds_ReturnValue8; // 0x3758(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UWorld* CallFunc_K2_GetWorld_ReturnValue5; // 0x3760(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue2; // 0x3768(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsUsingSuperFlight_Ret; // 0x3769(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData136[0x6]; // 0x376A(0x0006) MISSED OFFSET
double CallFunc_IsUsingSuperFlight_StartedEndingTime; // 0x3770(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_GetReplicatedControlRotation_ReturnValue; // 0x3778(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_RInterpTo_ReturnValue2; // 0x3784(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_GetReplicatedControlRotation_ReturnValue2; // 0x3790(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_RInterpTo_ReturnValue3; // 0x379C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue4; // 0x37A8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData137[0x7]; // 0x37A9(0x0007) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue9; // 0x37B0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APrimalBuff* CallFunc_GetBuffWithCustomTag_ReturnValue; // 0x37B8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue7; // 0x37C0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData138[0x3]; // 0x37C1(0x0003) MISSED OFFSET
float CallFunc_Multiply_FloatFloat_ReturnValue6; // 0x37C4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_ExtendBuffTime_ReturnValue; // 0x37C8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsPlayingBlockingAnim_ReturnVal; // 0x37C9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData139[0x6]; // 0x37CA(0x0006) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue10; // 0x37D0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue7; // 0x37D8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue8; // 0x37D9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData140[0x6]; // 0x37DA(0x0006) MISSED OFFSET
class UAudioComponent* CallFunc_PlaySoundAttached_ReturnValue; // 0x37E0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAudioComponent* CallFunc_PlaySoundAttached_ReturnValue2; // 0x37E8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAudioComponent* CallFunc_PlaySoundAttached_ReturnValue3; // 0x37F0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAudioComponent* CallFunc_PlaySoundAttached_ReturnValue4; // 0x37F8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode3; // 0x3800(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum4_CmpSuccess; // 0x3801(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData141[0x2]; // 0x3802(0x0002) MISSED OFFSET
struct FVector K2Node_CustomEvent_CameraHitLoc; // 0x3804(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_Start2; // 0x3810(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_end2; // 0x381C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_CustomEvent_PlayImpactFX; // 0x3828(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_CustomEvent_HitCharacterOrStructure; // 0x3829(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData142[0x2]; // 0x382A(0x0002) MISSED OFFSET
struct FName K2Node_CustomEvent_Socket; // 0x382C(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData143[0x4]; // 0x3834(0x0004) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue2; // 0x3838(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode4; // 0x3840(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum5_CmpSuccess; // 0x3841(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData144[0x6]; // 0x3842(0x0006) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue11; // 0x3848(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_Dir; // 0x3850(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_Loc; // 0x385C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AActor* K2Node_CustomEvent_Target; // 0x3868(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue6; // 0x3870(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue8; // 0x387C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData145[0x3]; // 0x387D(0x0003) MISSED OFFSET
struct FVector CallFunc_Subtract_VectorVector_ReturnValue3; // 0x3880(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData146[0x4]; // 0x388C(0x0004) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue12; // 0x3890(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_SelectVector_ReturnValue; // 0x3898(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Normal_ReturnValue2; // 0x38A4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_Subtract_DoubleDouble_ReturnValue; // 0x38B0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Conv_DoubleToFloat_ReturnValue; // 0x38B8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData147[0x4]; // 0x38BC(0x0004) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue6; // 0x38C0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FMin_ReturnValue; // 0x38C8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue7; // 0x38CC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BPFastTrace_ReturnValue2; // 0x38D8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData148[0x7]; // 0x38D9(0x0007) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue7; // 0x38E0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsPlayingBlockingAnim_ReturnVal2; // 0x38E8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData149[0x3]; // 0x38E9(0x0003) MISSED OFFSET
struct FVector CallFunc_K2_GetActorLocation_ReturnValue8; // 0x38EC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue3; // 0x38F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData150[0x3]; // 0x38F9(0x0003) MISSED OFFSET
struct FVector CallFunc_Subtract_VectorVector_ReturnValue4; // 0x38FC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_VSize_ReturnValue3; // 0x3908(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue5; // 0x390C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue5; // 0x390D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData151[0x2]; // 0x390E(0x0002) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue13; // 0x3910(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue9; // 0x3918(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData152[0x7]; // 0x3919(0x0007) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue8; // 0x3920(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_TimeSince_Network_ReturnValue3; // 0x3928(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FClamp_ReturnValue; // 0x392C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Add_FloatFloat_ReturnValue4; // 0x3930(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_CustomEvent_Immelmann2; // 0x3934(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData153[0x3]; // 0x3935(0x0003) MISSED OFFSET
struct FVector CallFunc_Conv_FloatToVector_ReturnValue; // 0x3938(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_CustomEvent_Immelmann; // 0x3944(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsLocallyControlledByPlayer_ReturnValue2; // 0x3945(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_CanLoop_ReturnValue; // 0x3946(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData154[0x1]; // 0x3947(0x0001) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue9; // 0x3948(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetUpVector_ReturnValue; // 0x3950(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData155[0x4]; // 0x395C(0x0004) MISSED OFFSET
class UPrimitiveComponent* K2Node_Event_MyComp; // 0x3960(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AActor* K2Node_Event_Other; // 0x3968(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UPrimitiveComponent* K2Node_Event_OtherComp; // 0x3970(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_Event_bSelfMoved; // 0x3978(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData156[0x3]; // 0x3979(0x0003) MISSED OFFSET
struct FVector K2Node_Event_HitLocation; // 0x397C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_Event_HitNormal; // 0x3988(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_Event_NormalImpulse; // 0x3994(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FHitResult K2Node_Event_Hit; // 0x39A0(0x0088) (OutParm, Transient, DuplicateTransient, ReferenceParm)
float CallFunc_Dot_VectorVector_ReturnValue6; // 0x3A28(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue4; // 0x3A2C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue6; // 0x3A2D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData157[0x2]; // 0x3A2E(0x0002) MISSED OFFSET
float CallFunc_GetCurrentPercentOfMaxFlySpeed_ReturnValue; // 0x3A30(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue6; // 0x3A34(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsLocallyControlledByPlayer_ReturnValue3; // 0x3A35(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData158[0x2]; // 0x3A36(0x0002) MISSED OFFSET
class AController* CallFunc_GetController_ReturnValue6; // 0x3A38(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController4; // 0x3A40(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast5_CastSuccess; // 0x3A48(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData159[0x3]; // 0x3A49(0x0003) MISSED OFFSET
struct FVector CallFunc_K2_GetActorLocation_ReturnValue9; // 0x3A4C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_RandomUnitVector_ReturnValue; // 0x3A58(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RandomFloat_ReturnValue; // 0x3A64(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_PickupLocation; // 0x3A68(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Multiply_FloatFloat_ReturnValue7; // 0x3A74(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue8; // 0x3A78(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData160[0x4]; // 0x3A84(0x0004) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue3; // 0x3A88(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Add_VectorVector_ReturnValue8; // 0x3A90(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData161[0x4]; // 0x3A9C(0x0004) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue4; // 0x3AA0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue10; // 0x3AA8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData162[0x4]; // 0x3AB4(0x0004) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue5; // 0x3AB8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetActorUpVector_ReturnValue2; // 0x3AC0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue11; // 0x3ACC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue9; // 0x3AD8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData163[0x7]; // 0x3AD9(0x0007) MISSED OFFSET
struct FHitResult CallFunc_MakeHitResult_ReturnValue; // 0x3AE0(0x0088) (Transient, DuplicateTransient)
bool K2Node_CustomEvent_AxisValue; // 0x3B68(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData164[0x3]; // 0x3B69(0x0003) MISSED OFFSET
int K2Node_CustomEvent_Direction3; // 0x3B6C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_CamDir; // 0x3B70(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue4; // 0x3B7C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData165[0x3]; // 0x3B7D(0x0003) MISSED OFFSET
int K2Node_CustomEvent_Direction2; // 0x3B80(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_CameraDir; // 0x3B84(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsLocallyControlledByPlayer_ReturnValue4; // 0x3B90(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_CanBarrelRoll_Res; // 0x3B91(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData166[0x6]; // 0x3B92(0x0006) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue14; // 0x3B98(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterProjectile* K2Node_CustomEvent_Projectile; // 0x3BA0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue10; // 0x3BA8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData167[0x3]; // 0x3BA9(0x0003) MISSED OFFSET
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue9; // 0x3BAC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue10; // 0x3BB8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData168[0x3]; // 0x3BB9(0x0003) MISSED OFFSET
struct FVector CallFunc_Normal_ReturnValue3; // 0x3BBC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue8; // 0x3BC8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_SetActorRotation_ReturnValue5; // 0x3BD4(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData169[0x3]; // 0x3BD5(0x0003) MISSED OFFSET
class AController* CallFunc_GetController_ReturnValue7; // 0x3BD8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_NearlyEqual_FloatFloat_ReturnValue; // 0x3BE0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData170[0x3]; // 0x3BE1(0x0003) MISSED OFFSET
float K2Node_CustomEvent_Speed; // 0x3BE4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_Direction; // 0x3BE8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue10; // 0x3BF4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AController* CallFunc_GetController_ReturnValue8; // 0x3C00(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsLocallyControlledByPlayer_ReturnValue5; // 0x3C08(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData171[0x7]; // 0x3C09(0x0007) MISSED OFFSET
class APlayerController* CallFunc_CastToPlayerController_ReturnValue; // 0x3C10(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetActorRightVector_ReturnValue; // 0x3C18(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue11; // 0x3C24(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetActorRightVector_ReturnValue2; // 0x3C30(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue12; // 0x3C3C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue13; // 0x3C48(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue14; // 0x3C54(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_Start; // 0x3C60(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_End; // 0x3C6C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Subtract_VectorVector_ReturnValue5; // 0x3C78(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue12; // 0x3C84(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_VSizeSquared_ReturnValue; // 0x3C90(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Subtract_VectorVector_ReturnValue6; // 0x3C94(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsPlayingBlockingAnim_ReturnVal3; // 0x3CA0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData172[0x3]; // 0x3CA1(0x0003) MISSED OFFSET
float CallFunc_VSize_ReturnValue4; // 0x3CA4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_FloatFloat_ReturnValue7; // 0x3CA8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData173[0x3]; // 0x3CA9(0x0003) MISSED OFFSET
struct FVector CallFunc_K2_GetActorLocation_ReturnValue13; // 0x3CAC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UWorld* CallFunc_K2_GetWorld_ReturnValue10; // 0x3CB8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AMissionSpline* CallFunc_IsStarFoxMode_CurrentSpline2; // 0x3CC0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_ReturnValue2; // 0x3CC8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData174[0x7]; // 0x3CC9(0x0007) MISSED OFFSET
double CallFunc_IsStarFoxMode_RetRiderSetTime2; // 0x3CD0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_RetIsRiderWarmup2; // 0x3CD8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BPFastTrace_ReturnValue3; // 0x3CD9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData175[0x6]; // 0x3CDA(0x0006) MISSED OFFSET
class AMissionSpline* CallFunc_IsStarFoxMode_CurrentSpline3; // 0x3CE0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_ReturnValue3; // 0x3CE8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData176[0x7]; // 0x3CE9(0x0007) MISSED OFFSET
double CallFunc_IsStarFoxMode_RetRiderSetTime3; // 0x3CF0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_RetIsRiderWarmup3; // 0x3CF8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData177[0x3]; // 0x3CF9(0x0003) MISSED OFFSET
float CallFunc_Multiply_FloatFloat_ReturnValue8; // 0x3CFC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_LessEqual_FloatFloat_ReturnValue; // 0x3D00(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData178[0x7]; // 0x3D01(0x0007) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue6; // 0x3D08(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class FString CallFunc_Conv_ObjectToString_ReturnValue; // 0x3D10(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
bool CallFunc_IsSubmerged_ReturnValue; // 0x3D20(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData179[0x3]; // 0x3D21(0x0003) MISSED OFFSET
int CallFunc_Conv_BoolToInt_ReturnValue; // 0x3D24(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TArray<struct FVector> K2Node_CustomEvent_Locations2; // 0x3D28(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
int CallFunc_Array_Length_ReturnValue2; // 0x3D38(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Array_Get_Item2; // 0x3D3C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_IntInt_ReturnValue2; // 0x3D48(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData180[0x7]; // 0x3D49(0x0007) MISSED OFFSET
struct UObject_FTransform CallFunc_Conv_VectorToTransform_ReturnValue; // 0x3D50(0x0030) (Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue5; // 0x3D80(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData181[0x7]; // 0x3D81(0x0007) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue11; // 0x3D88(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AActor* CallFunc_BeginSpawningActorFromClass_ReturnValue; // 0x3D90(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AActor* CallFunc_FinishSpawningActor_ReturnValue; // 0x3D98(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_GetNetworkTimeInSeconds_ReturnValue15; // 0x3DA0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue5; // 0x3DA8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue11; // 0x3DA9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue12; // 0x3DAA(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData182[0x5]; // 0x3DAB(0x0005) MISSED OFFSET
TArray<struct FVector> K2Node_CustomEvent_Locations; // 0x3DB0(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
int CallFunc_Array_Length_ReturnValue3; // 0x3DC0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Array_Get_Item3; // 0x3DC4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_IntInt_ReturnValue3; // 0x3DD0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData183[0x7]; // 0x3DD1(0x0007) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue12; // 0x3DD8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanAND_ReturnValue6; // 0x3DE0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue6; // 0x3DE1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData184[0x2]; // 0x3DE2(0x0002) MISSED OFFSET
struct FVector CallFunc_GetUpVector_ReturnValue2; // 0x3DE4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_GetSocketLocation_ReturnValue; // 0x3DF0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_Conv_VectorToRotator_ReturnValue9; // 0x3DFC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue7; // 0x3E08(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AController* CallFunc_GetController_ReturnValue9; // 0x3E10(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APrimalDinoAIController* K2Node_DynamicCast_AsPrimalDinoAIController; // 0x3E18(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast6_CastSuccess; // 0x3E20(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData185[0x7]; // 0x3E21(0x0007) MISSED OFFSET
class AActor* CallFunc_GetTarget_ReturnValue; // 0x3E28(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AShooterCharacter* K2Node_DynamicCast_AsShooterCharacter2; // 0x3E30(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast7_CastSuccess; // 0x3E38(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData186[0x7]; // 0x3E39(0x0007) MISSED OFFSET
class AController* CallFunc_GetController_ReturnValue10; // 0x3E40(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class APrimalDinoAIController* K2Node_DynamicCast_AsPrimalDinoAIController2; // 0x3E48(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast8_CastSuccess; // 0x3E50(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData187[0x7]; // 0x3E51(0x0007) MISSED OFFSET
class UBlackboardComponent* CallFunc_GetBlackboard_ReturnValue; // 0x3E58(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UWorld* CallFunc_K2_GetWorld_ReturnValue13; // 0x3E60(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int CallFunc_GetCharacterLevel_ReturnValue; // 0x3E68(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData188[0x4]; // 0x3E6C(0x0004) MISSED OFFSET
struct UObject_FTransform CallFunc_GetTransform_ReturnValue; // 0x3E70(0x0030) (Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_BreakTransform_Location; // 0x3EA0(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FRotator CallFunc_BreakTransform_Rotation; // 0x3EAC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_BreakTransform_Scale; // 0x3EB8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData189[0x4]; // 0x3EC4(0x0004) MISSED OFFSET
class APrimalDinoCharacter* CallFunc_SpawnDino_ReturnValue; // 0x3EC8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_GetNetworkTimeInSeconds_ReturnValue16; // 0x3ED0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue13; // 0x3ED8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData190[0x7]; // 0x3ED9(0x0007) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue17; // 0x3EE0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_DoubleDouble_ReturnValue14; // 0x3EE8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData191[0x7]; // 0x3EE9(0x0007) MISSED OFFSET
class AMissionSpline* CallFunc_IsStarFoxMode_CurrentSpline4; // 0x3EF0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_ReturnValue4; // 0x3EF8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData192[0x7]; // 0x3EF9(0x0007) MISSED OFFSET
double CallFunc_IsStarFoxMode_RetRiderSetTime4; // 0x3F00(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_RetIsRiderWarmup4; // 0x3F08(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData193[0x3]; // 0x3F09(0x0003) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue2; // 0x3F0C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimEx_ReturnValue3; // 0x3F10(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode5; // 0x3F14(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum6_CmpSuccess; // 0x3F15(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData194[0x2]; // 0x3F16(0x0002) MISSED OFFSET
struct FVector CallFunc_GetSocketLocation_ReturnValue2; // 0x3F18(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchInteger_CmpSuccess; // 0x3F24(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData195[0x3]; // 0x3F25(0x0003) MISSED OFFSET
class UParticleSystemComponent* CallFunc_SpawnEmitterAtLocation_ReturnValue8; // 0x3F28(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue11; // 0x3F30(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchInteger2_CmpSuccess; // 0x3F31(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue8; // 0x3F32(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue5; // 0x3F33(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData196[0x4]; // 0x3F34(0x0004) MISSED OFFSET
class AMissionSpline* CallFunc_IsStarFoxMode_CurrentSpline5; // 0x3F38(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_ReturnValue5; // 0x3F40(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData197[0x7]; // 0x3F41(0x0007) MISSED OFFSET
double CallFunc_IsStarFoxMode_RetRiderSetTime5; // 0x3F48(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsStarFoxMode_RetIsRiderWarmup5; // 0x3F50(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_HasFuel_ReturnValue2; // 0x3F51(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData198[0x2]; // 0x3F52(0x0002) MISSED OFFSET
int CallFunc_HasFuel_Quantity2; // 0x3F54(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue12; // 0x3F58(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsFPV_RetVal; // 0x3F59(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData199[0x2]; // 0x3F5A(0x0002) MISSED OFFSET
struct FVector CallFunc_IsFPV_CameraLoc; // 0x3F5C(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAnimMontage* K2Node_Select_ReturnValue; // 0x3F68(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_Select_CmpSuccess; // 0x3F70(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData200[0x3]; // 0x3F71(0x0003) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue4; // 0x3F74(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class AController* CallFunc_GetController_ReturnValue11; // 0x3F78(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsFlakCannonOnCooldown_ReturnValue; // 0x3F80(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData201[0x7]; // 0x3F81(0x0007) MISSED OFFSET
class APlayerController* K2Node_DynamicCast_AsPlayerController; // 0x3F88(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast9_CastSuccess; // 0x3F90(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData202[0x3]; // 0x3F91(0x0003) MISSED OFFSET
struct FLinearColor CallFunc_GetColorForColorizationRegion_ReturnValue; // 0x3F94(0x0010) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FLinearColor CallFunc_GetColorForColorizationRegion_ReturnValue2; // 0x3FA4(0x0010) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_H; // 0x3FB4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_S; // 0x3FB8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_V; // 0x3FBC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_A; // 0x3FC0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_H2; // 0x3FC4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_S2; // 0x3FC8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_V2; // 0x3FCC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_A2; // 0x3FD0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FLinearColor CallFunc_GetColorForColorizationRegion_ReturnValue3; // 0x3FD4(0x0010) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_H3; // 0x3FE4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_S3; // 0x3FE8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_V3; // 0x3FEC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_RGBToHSV_A3; // 0x3FF0(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_MakeVector_ReturnValue3; // 0x3FF4(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Not_PreBool_ReturnValue9; // 0x4000(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData203[0x7]; // 0x4001(0x0007) MISSED OFFSET
class UWorld* CallFunc_K2_GetWorld_ReturnValue14; // 0x4008(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
double CallFunc_GetNetworkTimeInSeconds_ReturnValue18; // 0x4010(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsTimeSince_Network_ReturnValue7; // 0x4018(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData204[0x3]; // 0x4019(0x0003) MISSED OFFSET
int CallFunc_Array_Length_ReturnValue4; // 0x401C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UParticleSystemComponent* CallFunc_SpawnEmitterAttached_ReturnValue2; // 0x4020(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_K2_IsTimerActive_ReturnValue2; // 0x4028(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsGamePadActive_Ret; // 0x4029(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsGamePadActive_Ret2; // 0x402A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue13; // 0x402B(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue14; // 0x402C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue15; // 0x402D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue16; // 0x402E(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData205[0x1]; // 0x402F(0x0001) MISSED OFFSET
int Temp_int_Loop_Counter_Variable4; // 0x4030(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Less_IntInt_ReturnValue4; // 0x4034(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData206[0x3]; // 0x4035(0x0003) MISSED OFFSET
class UMaterialInterface* CallFunc_Array_Get_Item4; // 0x4038(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UMaterialInstanceDynamic* CallFunc_CreateDynamicMaterialInstance_ReturnValue; // 0x4040(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
int CallFunc_Add_IntInt_ReturnValue4; // 0x4048(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<EMoveComponentAction> Temp_byte_Variable; // 0x404C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_IsValid_ReturnValue17; // 0x404D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode6; // 0x404E(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetModeBP> CallFunc_SwitchNetworkMode_OutNetworkMode7; // 0x404F(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum7_CmpSuccess; // 0x4050(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum8_CmpSuccess; // 0x4051(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData207[0x2]; // 0x4052(0x0002) MISSED OFFSET
struct FVector CallFunc_K2_GetActorLocation_ReturnValue14; // 0x4054(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class USceneComponent* CallFunc_K2_GetRootComponent_ReturnValue2; // 0x4060(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAudioComponent* CallFunc_PlaySoundAttached_ReturnValue5; // 0x4068(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class USceneComponent* CallFunc_K2_GetRootComponent_ReturnValue3; // 0x4070(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_K2_GetActorLocation_ReturnValue15; // 0x4078(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData208[0x4]; // 0x4084(0x0004) MISSED OFFSET
class UAudioComponent* CallFunc_PlaySoundAttached_ReturnValue6; // 0x4088(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Subtract_VectorVector_ReturnValue7; // 0x4090(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_VSize_ReturnValue5; // 0x409C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_Greater_FloatFloat_ReturnValue7; // 0x40A0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData209[0x7]; // 0x40A1(0x0007) MISSED OFFSET
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore_RefProperty; // 0x40A8(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore2_RefProperty; // 0x40B8(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore3_RefProperty; // 0x40C8(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore4_RefProperty; // 0x40D8(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore5_RefProperty; // 0x40E8(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore6_RefProperty; // 0x40F8(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_SphereOverlapActors_NEW_ActorsToIgnore_RefProperty;// 0x4108(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass SpaceDolphin_Character_BP.SpaceDolphin_Character_BP_C");
return ptr;
}
void GetHudData(bool* HasSaddle, bool* IsFPV, bool* HideHUDinFPV, int* LaserLevel, int* MaxLaserLevel, float* LaserDowngradeTime, float* LaserDowngradeTimerRemaining, bool* IsLaserDowngradeTimerActive, double* LastLaserLevelChangedTime, class UPrimalInventoryComponent** InventoryComponent, class UClass** SaddleFuelItem, class UClass** FlakCannonAmmoItem, bool* IsUsingSuperFlight, bool* IsUsingSuperFlightBoost, float* FuelPercent, float* CannonCooldownPercent, float* EchoOrChaffCooldownPercent, bool* IsSubmerged);
TEnumAsByte<ECameraStyle> BPForceCameraStyle(class APrimalCharacter** ForViewTarget);
void UpdateLocalSounds();
bool Is_Star_Fox_Mode_Public(class AMissionSpline** CurrentSpline, double* RetRiderSetTime, bool* RetIsRiderWarmup);
void UpdateMouseCursor();
void TurnOffMouseCursor();
bool BPHandlePoop();
bool IsSilenced();
void Server_Request_Fire_Lasers_Fn(const struct FVector& CameraHitLocation);
void ShouldPreventLockOnMe(bool* IsPrevented);
void IsCurrentlyInStarFoxModeWithGamepad(bool* Result);
float BPSetSimulatedInterpRollOverride();
void IsGamePadActive(bool* Ret);
void BPUnstasis();
void TryStartImmelmann();
void TryStartLoop();
void UpdateFPVMeshes();
struct FRotator Get_Desired_Rotation();
struct FVector STATIC_GetCameraHitLocationForProjectiles();
struct FLinearColor Get_Screen_Mouse_Position_as_MatParam();
void BPOnClearMountedDino();
void Update_Saddle_Shield_Material();
void STATIC_GetPercentTamed(float* Percemt, float* RequiredAmount);
bool STATIC_BPDinoTooltipCustomTamingProgressBar(bool* overrideTamingProgressBarIfActive, float* progressPercent, class FString* Label);
void BPNotifyInventoryItemChange(bool* bIsItemAdd, class UPrimalItem** theItem, bool* bEquipItem);
void AddSaddleActivationText();
void ClearSaddleActivationText();
void BPBecomeAdult();
void BPBecomeBaby();
void UpdateStarFoxCameraForGamepad();
bool BP_InterceptTurnInput(float* AxisValue);
void OnConsumeFood();
void BPUntamedConsumeFoodItem(class UPrimalItem** foodItem);
void BPTamedConsumeFoodItem(class UPrimalItem** foodItem);
bool BPModifyControlRotation(struct FRotator* ControlRotation, struct FRotator* outControlRotation);
void SetLastTimeChargedLaserHit(double val);
void Update_Materials(class UMaterialInterface* Material);
void Is_FPV_Public(bool* Retval);
void IsFPV(bool* Retval, struct FVector* CameraLoc);
void ReceiveEndPlay(TEnumAsByte<EEndPlayReason>* EndPlayReason);
void BPNotifyLevelUp(int* ExtraCharacterLevel);
bool IsSpinningPublic(bool* Right);
void UpdateBarrelRoll();
float GetLaserDamage();
void GetDamageReductionPercentFromLaserLevel(float* Ret);
void GetTamedWalkingSpeedModifierForLaserLevel(float* TamedWalkingSpeedModifier);
void GetLaserLevelDowngradeTime(float* LaserLevelDowngradeTime);
void GetChargedLaserProj(class UClass** ChargedLaserProjectile);
class UParticleSystem* GetLaserPFX(int* LaserLevel);
float BPGetTargetingDesirability(class AActor** Attacker);
float GetChanceToSpawnSpaceWhale();
void SpawnSpaceWhale();
void Try_Spawn_Space_Whale();
void UpdateWildDemands(bool ResetWildDemand);
void HasWildDemands(bool* HasDemands, int* NumPets, int* NumFood);
void TriggerWildAngerFn();
bool IsAngryWildDino(float* DistanceSq);
void NearbyAngryDolphin(class ASpaceDolphin_Character_BP_C* AngryDolphin, class AShooterCharacter* Target);
bool BPShouldForceFlee();
void UpdateWild();
bool BPTryMultiUse(class APlayerController** ForPC, int* UseIndex);
TArray<struct FMultiUseEntry> BPGetMultiUseEntries(class APlayerController** ForPC, TArray<struct FMultiUseEntry>* MultiUseEntries);
float BlueprintAdjustOutputDamage(int* AttackIndex, float* OriginalDamageAmount, class AActor** HitActor, class UClass** OutDamageType, float* OutDamageImpulse);
void FireChaff();
void EchoLocation();
void STATIC_UpdateGroundFX();
void STATIC_DoLaserTraceAndDamage(const struct FVector& Start, const struct FVector& End, struct FVector* RetStart, struct FVector* RetEnd, bool* Ret, bool* ImpactCharacterOrStructure);
void UpdateStarFoxCollision();
void UpateBarrelRollFX();
void UpdateRotatingComponent();
void OnRep_LastLaserLevelUpTime();
void Downgrade_Laser_Level();
bool Is_Drifting_Public(bool* DriftingInput, bool* Right, double* DriftEndTime);
void DeactiveDriftJets();
bool IsDrifting(bool* DriftingInput, bool* Right, double* DriftEndTime, bool* IsFinishingDrift);
float GetDriftInputStrength(float* ReturnValueBase);
void UpdateDrifting();
void UpdateSaddle();
void TryDoStarFoxModeCollisionDamage();
void ReceiveActorBeginOverlap(class AActor** OtherActor);
void ReceiveActorEndOverlap(class AActor** OtherActor);
void STATIC_Get_Camera_YScalar(float* StarFoxModeCameraXOffsetScalar);
void OnRep_CurrentSpline();
bool BP_PreventMovementMode(TEnumAsByte<EMovementMode>* NewMovementMode, unsigned char* NewCustomMode);
void CanBarrelRoll(bool* res);
void IsDoingBarrelRoll(bool* Ret, class UAnimMontage** Anim, double* LastBarrelRollStartTime);
void BarrelRoll(int Direction, const struct FVector& CameraDirection);
void Is_Braking_Public(bool* IsBraking, double* TimeStartedBraking);
void Is_Braking(bool* IsBraking, double* TimeStartedBraking);
void UpdateBraking();
void BPDrawToRiderHUD(class AShooterHUD** HUD);
void UpdateSpinning();
bool IsSpinning(bool* Right);
void DestroyProjectile();
void Get_Flak_Cannon_Parameters(class AShooterProjectile* Projectile);
bool IsStarFoxMode(class AMissionSpline** CurrentSpline, double* RetRiderSetTime, bool* RetIsRiderWarmup);
bool ValidateSpline(class AMissionSpline* Spline);
void UpdateSpline();
bool BPServerHandleNetExecCommand(class APlayerController** FromPC, struct FName* CommandName, struct FBPNetExecParams* ExecParams);
void BPKilledSomethingEvent(class APrimalCharacter** killedTarget);
void IsDualLasers(bool* DualLasers);
bool CanLoop();
bool IsChargingLaser();
float BPGetCrosshairSpread();
void UpdateLoop();
bool BPAcknowledgeServerCorrection(float* TimeStamp, struct FVector* NewLoc, struct FVector* NewVel, class UPrimitiveComponent** NewBase, struct FName* NewBaseBoneName, bool* bHasBase, bool* bBaseRelativePosition, unsigned char* ServerMovementMode);
void EndLoop();
void StartLoop(bool Immelmann);
struct FLinearColor BPGetCrosshairColor();
void Try_Get_ChargedLaserTarget(class AActor** Ret);
void OwningClientTryFireChargedLaser();
void GetChargedLaserParameters(class AShooterProjectile* Projectile, float* ChargeTime, class AActor** Target);
void STATIC_FireChargedLaser(const struct FVector& Dir, const struct FVector& Loc, class AActor* Target, float ChargeTime);
void STATIC_Owning_Client_Try_FireLasers();
void FireLasers(const struct FVector& Dir, const struct FVector& Loc, const struct FName& Socket);
void GetSaddleColor(int Region, struct FLinearColor* Ret);
void IsUsingWindGust(bool* Ret, double* StartTime);
void IsUsingForwardInput(bool* Ret);
void BPUnsetupDinoTameable();
void BSetupDinoTameable();
void UpdateRiderSocket();
struct FName GetOverrideSocket(struct FName* From);
bool AllowWakingTame(class APlayerController** ForPC);
void OwningClientTryFlakCannonFire();
void InterceptInputEvent(class FString* InputName);
bool AllowPlayMontage(class UAnimMontage** AnimMontage);
class UAnimMontage* GetDinoLevelUpAnimation();
void UpdateTaming();
bool BPShowTamingPanel(bool* currentVisibility);
void GetTamingBuff(bool* IsValid, class APrimalBuff** Buff);
bool BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget);
float BPAdjustDamage(float* IncomingDamage, struct FDamageEvent* TheDamageEvent, class AController** EventInstigator, class AActor** DamageCauser, bool* bIsPointDamage, struct FHitResult* PointHitInfo);
struct FRotator Get_Replicated_Control_Rotation_Public();
void IsPlayingBlockingAnim(bool* ReturnVal);
bool Is_Using_Drafting_Public(bool* DraftAcked);
bool IsUsingDrafting(bool* DraftAcked);
struct FName BPGetRiderSocket();
bool IsJumpHeld();
void BPOnDinoCheat(struct FName* CheatName, bool* bSetValue, float* Value);
struct FRotator GetReplicatedControlRotation();
void ReceiveTick(float* DeltaSeconds);
void BPDoAttack(int* AttackIndex);
float BPGetCrosshairAlpha();
bool IsFlakCannonOnCooldown();
void BPGetCrosshairLocation(float* CanvasClipX, float* CanvasClipY, float* OutX, float* OutY);
void ConsumeItem(class UClass* Item);
bool HasAmmo(int* Quantity);
bool BPOnStopJump();
void Fire_Flak_Cannon(const struct FVector& Dir, const struct FVector& Loc);
void Has_Saddle_Public(bool* Ret, bool* RetIsSuperSaddle);
void OnInventoryItemGrind();
void UpdateWindGustCooldownVFX();
int BPOverrideGetAttackAnimationIndex(int* AttackIndex, TArray<class UAnimMontage*>* AnimationArray);
void TryInterruptLanding(TEnumAsByte<EMovementMode> Selection);
void OnRep_SuperFlight();
void SetSuperFlight(bool Value, bool TriggerVFX);
float Get_Current_Percent_Of_Max_Fly_Speed_Public();
void Is_Using_Super_Flight_Public(bool* Ret, double* StartedEndingTime);
void IsUsingSuperFlight(bool* Ret, double* StartedEndingTime);
void UpdateSuperFlightBoost();
bool Is_Using_Super_Flight_Boost_Public();
bool IsUsingSuperFlightBoost(double* StartTime);
struct FName BPGetDragSocketName(class APrimalCharacter** DraggingChar);
void OnCarriedStruggle();
bool IsUsingWingGust();
void Update_Jet_FX();
bool HasFuel(int* Quantity);
void UpdateFuel();
void BPDidSetCarriedCharacter(class APrimalCharacter** PreviousCarriedCharacter);
void HasSaddle(bool* Ret, bool* RetIsSuperSaddle);
void UpdateDrafting();
struct FName BPGetDragSocketDinoName(class APrimalDinoCharacter** aGrabbedDino);
void UpdateSuperFlightStateData();
void UpdateAcceleration();
void UpdateRotationRate();
void UpdateAllyAOE();
struct FVector GetWindGustEpicenter();
void STATIC_DoWing_GustAOE();
void Is_Diving_Public(bool* Ret, double* TimeDiveStart);
void BPNotifySetRider(class AShooterCharacter** RiderSetting);
void UpdateTPVOffset();
void UpdateCheckQuickTurn();
void UpdateSpeed();
void UpdateDiving();
void IsDiving(bool* Ret, double* TimeDiveStart, double* TimeStoppedDiving);
void GetAnimBP(class USpaceDolphin_AnimationBP_C** Ret);
float GetCurrentPercentOfMaxFlySpeed();
void GetCDO(class ASpaceDolphin_Character_BP_C** Ret);
bool Is_Quick_Turning();
void EndQuickTurn();
void StartSuperFlightQuickTurn();
void OnRep_LastSuperFlightQuickTurn();
void UpdateSuperFlightRoll();
bool BP_InterceptMoveRight(float* AxisValue);
void UpdateTrails();
void ActivateTrails();
void DeactivateTrails();
void RidingTick(float* DeltaSeconds);
void BP_OnStartLandingNotify();
struct FVector BPOverrideFlyingVelocity(float* DeltaTime, struct FVector* InitialVelocity, struct FVector* Gravity);
void K2_OnMovementModeChanged(TEnumAsByte<EMovementMode>* PrevMovementMode, TEnumAsByte<EMovementMode>* NewMovementMode, unsigned char* PrevCustomMode, unsigned char* NewCustomMode);
bool BP_InterceptMoveForward(float* AxisValue);
void STATIC_BPGetHUDElements(class APlayerController** ForPC, TArray<struct FHUDElement>* OutElements);
void STATIC_BPOverrideCameraViewTarget(struct FName* CurrentCameraMode, struct FVector* DesiredCameraLocation, struct FRotator* DesiredCameraRotation, float* DesiredFOV, bool* bOverrideCameraLocation, struct FVector* CameraLocation, bool* bOverrideCameraRotation, struct FRotator* CameraRotation, bool* bOverrideCameraFOV, float* CameraFOV);
void BP_OnSetRunning(bool* bNewIsRunning);
void BPNotifyClearRider(class AShooterCharacter** RiderClearing);
bool BPHandleOnStopTargeting();
bool BPHandleControllerInitiatedAttack(int* AttackIndex);
bool BPModifyDesiredRotation(float* DeltaTime, struct FRotator* InDesiredRotation, struct FRotator* OutDesiredRotation);
void BPSetupTamed(bool* bWasJustTamed);
bool BPOnStartJump();
bool BPHandleUseButtonPress(class AShooterPlayerController** RiderController);
void DisableCameraInterpolation();
void OnRep_LatchingSurfaceNormal();
void UpdateLatchedDinoCamera();
void Controller_Follow_ActorRotation(float DeltaSeconds);
void STATIC_ReferenceLatchingObjects();
void LineTrace(class UMeshComponent* Mesh, const struct FName& SocketName, class AActor* Actor, const struct FVector& Offset, bool BackwardLatching, bool* Hit_Somthing, struct FVector* Location, struct FVector* Normal, class AActor** Hit_Actor);
void InterruptLatching();
void ProcessLatching(float DeltaSeconds);
void TryLatch(const struct FVector& Offset, bool backwardsLatching);
void UserConstructionScript();
void InpActEvt_AltFire_K2Node_InputActionEvent_348();
void InpActEvt_BrakeDino_K2Node_InputActionEvent_347();
void InpActEvt_BrakeDino_K2Node_InputActionEvent_346();
void InpActEvt_Crouch_K2Node_InputActionEvent_345();
void InpActEvt_Prone_K2Node_InputActionEvent_344();
void InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_343();
void InpActEvt_GamepadRightThumbstick_K2Node_InputActionEvent_342();
void InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_74();
void InpActEvt_Gamepad_LeftTrigger_K2Node_InputKeyEvent_73();
void InpActEvt_OrbitCam_K2Node_InputActionEvent_341();
void InpActEvt_OrbitCamToggle_K2Node_InputActionEvent_340();
void Latch(bool backwardsLatching);
void LatchStartAnimation();
void UnLatch(bool LatchingInterrupted);
void UnLatchStartAnimation();
void BlueprintAnimNotifyCustomEvent(struct FName* CustomEventName, class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation, class UAnimNotify** AnimNotifyObject);
void MoveToUsingDirection(float DeltaTime);
void UnLatchMoveAndRotate();
void LatchingStartEvent();
void LatchingEndEvent();
void StopMovement(float DeltaSeconds);
void DisableFaceLatchingObjectRotation();
void SetPassengersSurfaceCamera(float Yaw, float Pitch, float Roll);
void LocalFaceLatchingObject(float DeltaSeconds);
void StartedJump();
void ServerToggleSuperFlight();
void ServerSuperFightRightInput(float AxisValue);
void ServerRequestSuperFlightQuickTurn();
void UpdateQuickTurn();
void ServerRequestWindGust();
void AnimNotify_WindGust();
void ClientWindGust(const struct FVector& Epicenter);
void AnimNotify_WindGustVFX();
void ServerRequestFireFlakCannon(const struct FVector& Dir, const struct FVector& Loc);
void InpAxisEvt_MoveUp_K2Node_InputAxisEvent_181(float AxisValue);
void ServerUpdateLastForwardInputTime();
void DelayedSuperFlightEnd();
void MultiSuperFlightEnd();
void ClientTagDraftee(class APrimalCharacter* Target);
void WindGust180End();
void WindGust180Tick();
void AnimNotify_WindGustCheckFor180();
void AnimNotify_WindGustBoost();
void ServerRequest180();
void GamepadRightStickPressed();
void ServerSetLastTimePressedJump();
void ServerSetLastTimeReleasedJump();
void QueueLanding();
void ServerRequestLanding();
void OnBola();
void ServerUpdateRunningStartTime();
void ServerUpdateRunningStopTime();
void MultiOnRunStarted();
void MultiOnRunStopped();
void MultiOnSuperFlightStart();
void QueueGrabAttack();
void MultiThrusterVFXBoost();
void ServerRequestFireLasers(const struct FVector& CameraHitLoc);
void ClientSpawnLaserFireFX(const struct FVector& Start, const struct FVector& End, bool PlayImpactFX, bool HitCharacterOrStructure, const struct FName& Socket);
void ServerPressedFire();
void ServerFireChargedLaser(const struct FVector& Dir, const struct FVector& Loc, class AActor* Target);
void TickChargedLaserFX();
void ClearNumPressedFwdCount();
void ServerRequestStartLoop(bool Immelmann);
void MultiStartLoop(bool Immelmann);
void ReceiveHit(class UPrimitiveComponent** MyComp, class AActor** Other, class UPrimitiveComponent** OtherComp, bool* bSelfMoved, struct FVector* HitLocation, struct FVector* HitNormal, struct FVector* NormalImpulse, struct FHitResult* Hit);
void MultiImpactedTerrain();
void ClientPickupUpgrade(const struct FVector& PickupLocation);
void ServerRequestDestroyProjectile();
void MultiDestroyPorjectile();
void ServerSuperFightIsBraking(bool AxisValue);
void ServerRequestBarrelRoll(int Direction, const struct FVector& CamDir);
void MultiBarrelRoll(int Direction, const struct FVector& CameraDir);
void MultiReflectProjectile(class AShooterProjectile* Projectile);
void ClientDamagedByTerrain();
void MultiDriftingBoost(float Speed, const struct FVector& Direction);
void AnimNotifty_BarrelRollLeft();
void AnimNotifty_BarrelRollRight();
void ServerStartJump();
void StarFoxServerRequestFireLasers(const struct FVector& Start, const struct FVector& End);
void AnimNotify_Echo();
void ClientEchoLocations(TArray<struct FVector>* Locations);
void AnimNotify_FireChaff();
void MultiSpawnChaffs(TArray<struct FVector>* Locations);
void AnimNotify_Nudge();
void StopWildFlee();
void TriggerWildAnger();
void AnimNotify_BlowHole();
void ExpireAngryDinoTarget();
void MultiAngryBlowHole();
void SpaceWhaleIntroEnd();
void ExpireAnger();
void ServerUpdateLastElevateTime();
void ServerUpdateLastLowerTime();
void AnimNotify_ToggleSuperFlight();
void ServerForceClearRider();
void CenterMouse();
void ReceiveBeginPlay();
void MultiSaddleActivationText();
void UpdateLoopingEvent();
void ExecuteUbergraph_SpaceDolphin_Character_BP(int EntryPoint);
void NewEventDispatcher0__DelegateSignature();
void NewEventDispatcher__DelegateSignature();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 158.475451 | 519 | 0.553969 | [
"mesh"
] |
ffac79455ef70221e1d5ab12cee96c559d8f4ae2 | 5,251 | hpp | C++ | include/Org/BouncyCastle/Asn1/Asn1TaggedObject.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Asn1/Asn1TaggedObject.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Asn1/Asn1TaggedObject.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Org.BouncyCastle.Asn1.Asn1Object
#include "Org/BouncyCastle/Asn1/Asn1Object.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Org::BouncyCastle::Asn1
namespace Org::BouncyCastle::Asn1 {
// Skipping declaration: Asn1Encodable because it is already included!
}
// Completed forward declares
// Type namespace: Org.BouncyCastle.Asn1
namespace Org::BouncyCastle::Asn1 {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Asn1.Asn1TaggedObject
class Asn1TaggedObject : public Org::BouncyCastle::Asn1::Asn1Object {
public:
// System.Int32 tagNo
// Size: 0x4
// Offset: 0x10
int tagNo;
// Field size check
static_assert(sizeof(int) == 0x4);
// System.Boolean explicitly
// Size: 0x1
// Offset: 0x14
bool explicitly;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: explicitly and: obj
char __padding1[0x3] = {};
// Org.BouncyCastle.Asn1.Asn1Encodable obj
// Size: 0x8
// Offset: 0x18
Org::BouncyCastle::Asn1::Asn1Encodable* obj;
// Field size check
static_assert(sizeof(Org::BouncyCastle::Asn1::Asn1Encodable*) == 0x8);
// Creating value type constructor for type: Asn1TaggedObject
Asn1TaggedObject(int tagNo_ = {}, bool explicitly_ = {}, Org::BouncyCastle::Asn1::Asn1Encodable* obj_ = {}) noexcept : tagNo{tagNo_}, explicitly{explicitly_}, obj{obj_} {}
// static public Org.BouncyCastle.Asn1.Asn1TaggedObject GetInstance(Org.BouncyCastle.Asn1.Asn1TaggedObject obj, System.Boolean explicitly)
// Offset: 0x16DFF68
static Org::BouncyCastle::Asn1::Asn1TaggedObject* GetInstance(Org::BouncyCastle::Asn1::Asn1TaggedObject* obj, bool explicitly);
// static public Org.BouncyCastle.Asn1.Asn1TaggedObject GetInstance(System.Object obj)
// Offset: 0x16E0010
static Org::BouncyCastle::Asn1::Asn1TaggedObject* GetInstance(::Il2CppObject* obj);
// protected System.Void .ctor(System.Int32 tagNo, Org.BouncyCastle.Asn1.Asn1Encodable obj)
// Offset: 0x16E011C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Asn1TaggedObject* New_ctor(int tagNo, Org::BouncyCastle::Asn1::Asn1Encodable* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("Org::BouncyCastle::Asn1::Asn1TaggedObject::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Asn1TaggedObject*, creationType>(tagNo, obj)));
}
// protected System.Void .ctor(System.Boolean explicitly, System.Int32 tagNo, Org.BouncyCastle.Asn1.Asn1Encodable obj)
// Offset: 0x16E0164
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Asn1TaggedObject* New_ctor(bool explicitly, int tagNo, Org::BouncyCastle::Asn1::Asn1Encodable* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("Org::BouncyCastle::Asn1::Asn1TaggedObject::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Asn1TaggedObject*, creationType>(explicitly, tagNo, obj)));
}
// public System.Int32 get_TagNo()
// Offset: 0x16E0360
int get_TagNo();
// public System.Boolean IsExplicit()
// Offset: 0x16E0368
bool IsExplicit();
// public System.Boolean IsEmpty()
// Offset: 0x16E0370
bool IsEmpty();
// public Org.BouncyCastle.Asn1.Asn1Object GetObject()
// Offset: 0x16DD2D4
Org::BouncyCastle::Asn1::Asn1Object* GetObject();
// protected override System.Boolean Asn1Equals(Org.BouncyCastle.Asn1.Asn1Object asn1Object)
// Offset: 0x16E0200
// Implemented from: Org.BouncyCastle.Asn1.Asn1Object
// Base method: System.Boolean Asn1Object::Asn1Equals(Org.BouncyCastle.Asn1.Asn1Object asn1Object)
bool Asn1Equals(Org::BouncyCastle::Asn1::Asn1Object* asn1Object);
// protected override System.Int32 Asn1GetHashCode()
// Offset: 0x16E031C
// Implemented from: Org.BouncyCastle.Asn1.Asn1Object
// Base method: System.Int32 Asn1Object::Asn1GetHashCode()
int Asn1GetHashCode();
// public override System.String ToString()
// Offset: 0x16E0378
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::Il2CppString* ToString();
}; // Org.BouncyCastle.Asn1.Asn1TaggedObject
#pragma pack(pop)
static check_size<sizeof(Asn1TaggedObject), 24 + sizeof(Org::BouncyCastle::Asn1::Asn1Encodable*)> __Org_BouncyCastle_Asn1_Asn1TaggedObjectSizeCheck;
static_assert(sizeof(Asn1TaggedObject) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Asn1::Asn1TaggedObject*, "Org.BouncyCastle.Asn1", "Asn1TaggedObject");
| 51.480392 | 176 | 0.71015 | [
"object"
] |
ffade530593d1c3baaf6616e2c0de078e5dfe44e | 7,127 | cc | C++ | bess/core/dpdk.cc | JackKuo-tw/BESSGreatFirewall | 5a2d814df8ce508263eba1fcd4a2641c8f625402 | [
"BSD-3-Clause"
] | 1 | 2020-06-22T13:21:43.000Z | 2020-06-22T13:21:43.000Z | bess/core/dpdk.cc | JackKuo-tw/BESSGreatFirewall | 5a2d814df8ce508263eba1fcd4a2641c8f625402 | [
"BSD-3-Clause"
] | null | null | null | bess/core/dpdk.cc | JackKuo-tw/BESSGreatFirewall | 5a2d814df8ce508263eba1fcd4a2641c8f625402 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2014-2016, The Regents of the University of California.
// Copyright (c) 2016-2017, Nefeli Networks, 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 names of the copyright holders nor the names of their
// 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 "dpdk.h"
#include <syslog.h>
#include <unistd.h>
#include <glog/logging.h>
#include <rte_config.h>
#include <rte_cycles.h>
#include <rte_eal.h>
#include <rte_ethdev.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "memory.h"
#include "opts.h"
#include "worker.h"
namespace bess {
namespace {
void disable_syslog() {
setlogmask(0x01);
}
void enable_syslog() {
setlogmask(0xff);
}
// for log messages during rte_eal_init()
ssize_t dpdk_log_init_writer(void *, const char *data, size_t len) {
enable_syslog();
LOG(INFO) << std::string(data, len);
disable_syslog();
return len;
}
ssize_t dpdk_log_writer(void *, const char *data, size_t len) {
LOG(INFO) << std::string(data, len);
return len;
}
class CmdLineOpts {
public:
explicit CmdLineOpts(std::initializer_list<std::string> args)
: args_(), argv_({nullptr}) {
Append(args);
}
void Append(std::initializer_list<std::string> args) {
for (const std::string &arg : args) {
args_.emplace_back(arg.begin(), arg.end());
args_.back().push_back('\0');
argv_.insert(argv_.begin() + argv_.size() - 1, args_.back().data());
}
}
char **Argv() { return argv_.data(); }
int Argc() const { return args_.size(); }
std::string Dump() {
std::ostringstream os;
os << "[";
for (size_t i = 0; i < args_.size(); i++) {
os << (i == 0 ? "" : ", ") << '"' << args_[i].data() << '"';
}
os << "]";
return os.str();
}
private:
// Contains a copy of each argument.
std::vector<std::vector<char>> args_;
// Pointer to each argument (in `args_`), plus an extra `nullptr`.
std::vector<char *> argv_;
};
void init_eal(int dpdk_mb_per_socket, std::string nonworker_corelist) {
CmdLineOpts rte_args{
"bessd",
"--master-lcore",
std::to_string(RTE_MAX_LCORE - 1),
"--lcore",
std::to_string(RTE_MAX_LCORE - 1) + "@" + nonworker_corelist,
// Do not bother with /var/run/.rte_config and .rte_hugepage_info,
// since we don't want to interfere with other DPDK applications.
"--no-shconf",
// TODO(sangjin) switch to dynamic memory mode
"--legacy-mem",
};
if (dpdk_mb_per_socket <= 0) {
rte_args.Append({"--iova", (FLAGS_iova != "") ? FLAGS_iova : "va"});
rte_args.Append({"--no-huge"});
// even if we opt out of using hugepages, many DPDK libraries still rely on
// rte_malloc (e.g., rte_lpm), so we need to reserve some (normal page)
// memory in advance. We allocate 512MB (this is shared among nodes).
rte_args.Append({"-m", "512"});
} else {
rte_args.Append({"--iova", (FLAGS_iova != "") ? FLAGS_iova : "pa"});
std::string opt_socket_mem = std::to_string(dpdk_mb_per_socket);
for (int i = 1; i < NumNumaNodes(); i++) {
opt_socket_mem += "," + std::to_string(dpdk_mb_per_socket);
}
rte_args.Append({"--socket-mem", opt_socket_mem});
// Unlink mapped hugepage files so that memory can be reclaimed as soon as
// bessd terminates.
rte_args.Append({"--huge-unlink"});
}
// reset getopt()
optind = 0;
// DPDK creates duplicated outputs (stdout and syslog).
// We temporarily disable syslog, then set our log handler
cookie_io_functions_t dpdk_log_init_funcs;
cookie_io_functions_t dpdk_log_funcs;
std::memset(&dpdk_log_init_funcs, 0, sizeof(dpdk_log_init_funcs));
std::memset(&dpdk_log_funcs, 0, sizeof(dpdk_log_funcs));
dpdk_log_init_funcs.write = &dpdk_log_init_writer;
dpdk_log_funcs.write = &dpdk_log_writer;
FILE *org_stdout = stdout;
stdout = fopencookie(nullptr, "w", dpdk_log_init_funcs);
disable_syslog();
LOG(INFO) << "Initializing DPDK EAL with options: " << rte_args.Dump();
int ret = rte_eal_init(rte_args.Argc(), rte_args.Argv());
if (ret < 0) {
LOG(FATAL) << "rte_eal_init() failed: ret = " << ret
<< " rte_errno = " << rte_errno << " ("
<< rte_strerror(rte_errno) << ")";
}
enable_syslog();
fclose(stdout);
stdout = org_stdout;
rte_openlog_stream(fopencookie(nullptr, "w", dpdk_log_funcs));
}
// Returns the current affinity set of the process as a string,
// in the "corelist" format (e.g., "0-12,16-28")
std::string GetNonWorkerCoreList() {
std::string corelist;
cpu_set_t set;
int ret = pthread_getaffinity_np(pthread_self(), sizeof(set), &set);
if (ret < 0) {
PLOG(WARNING) << "pthread_getaffinity_np()";
return 0; // Core 0 as a fallback
}
// Choose the last core available
for (int i = 0; i < CPU_SETSIZE; i++) {
if (CPU_ISSET(i, &set)) {
int start = i;
while (i < CPU_SETSIZE && CPU_ISSET(i, &set)) {
i++;
}
int end = i - 1;
std::string group = std::to_string(start);
if (start < end) {
group += "-" + std::to_string(end);
}
if (corelist == "") {
corelist += group;
} else {
corelist += "," + group;
}
}
}
if (corelist == "") {
// This should never happen, but just in case...
PLOG(WARNING) << "No core is allowed for the process?";
corelist = "0";
}
return corelist;
}
bool is_initialized = false;
} // namespace
bool IsDpdkInitialized() {
return is_initialized;
}
void InitDpdk(int dpdk_mb_per_socket) {
current_worker.SetNonWorker();
if (!is_initialized) {
is_initialized = true;
init_eal(dpdk_mb_per_socket, GetNonWorkerCoreList());
}
}
} // namespace bess
| 29.329218 | 80 | 0.660727 | [
"vector"
] |
ffb05415cc03e6c49b67b148cd26c16598679c77 | 3,980 | cpp | C++ | src/make_groundtruth_in_ascii.cpp | kampersanda/consistent_weighted_sampling | 6fbcf372a23d778b4f346e1c181004d7a9e555c0 | [
"MIT"
] | 6 | 2019-07-22T08:53:14.000Z | 2021-12-21T22:03:37.000Z | src/make_groundtruth_in_ascii.cpp | tonellotto/consistent_weighted_sampling | 7d006b484ee4f3dfa048036210028fd239d2500a | [
"MIT"
] | null | null | null | src/make_groundtruth_in_ascii.cpp | tonellotto/consistent_weighted_sampling | 7d006b484ee4f3dfa048036210028fd239d2500a | [
"MIT"
] | 2 | 2021-02-17T17:09:58.000Z | 2021-03-01T11:09:33.000Z | #include "cmdline.h"
#include "misc.hpp"
using namespace ascii_format;
template <int Flags>
int run(const cmdline::parser& p) {
auto base_fn = p.get<string>("base_fn");
auto query_fn = p.get<string>("query_fn");
auto groundtruth_fn = p.get<string>("groundtruth_fn");
auto begin_id = p.get<uint32_t>("begin_id");
auto topk = p.get<uint32_t>("topk");
auto progress = p.get<size_t>("progress");
const auto base_vecs = load_vecs<Flags>(base_fn, begin_id);
size_t N = base_vecs.size();
const auto query_vecs = load_vecs<Flags>(query_fn, begin_id);
size_t M = query_vecs.size();
struct id_sim_t {
uint32_t id;
float sim;
};
vector<id_sim_t> id_sims(N);
groundtruth_fn += ".txt";
ofstream ofs(groundtruth_fn);
if (!ofs) {
cerr << "open error: " << groundtruth_fn << endl;
return 1;
}
ofs << M << '\n' << topk << '\n';
auto start_tp = chrono::system_clock::now();
size_t progress_point = progress;
for (size_t j = 0; j < M; ++j) {
if (j == progress_point) {
progress_point += progress;
auto cur_tp = chrono::system_clock::now();
auto dur_cnt = chrono::duration_cast<chrono::seconds>(cur_tp - start_tp).count();
cout << j << " queries processed in ";
cout << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s" << endl;
}
const auto& query = query_vecs[j];
#pragma omp parallel for
for (size_t i = 0; i < N; ++i) {
const auto& base = base_vecs[i];
id_sims[i].id = uint32_t(i);
id_sims[i].sim = calc_minmax_sim<Flags>(base, query);
}
sort(id_sims.begin(), id_sims.end(), [](const id_sim_t& a, const id_sim_t& b) {
if (a.sim != b.sim) {
return a.sim > b.sim;
}
return a.id < b.id;
});
for (uint32_t i = 0; i < topk; ++i) {
ofs << id_sims[i].id << ':' << id_sims[i].sim << ',';
}
ofs << '\n';
}
auto cur_tp = chrono::system_clock::now();
auto dur_cnt = chrono::duration_cast<chrono::seconds>(cur_tp - start_tp).count();
cout << "Completed!! --> " << M << " queries processed in ";
cout << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s!!" << endl;
cout << "Output " << groundtruth_fn << endl;
return 0;
}
template <int Flags = 0>
int run_with_flags(int flags, const cmdline::parser& p) {
if constexpr (Flags > FLAGS_MAX) {
cerr << "Error: invalid flags\n";
return 1;
} else {
if (flags == Flags) {
return run<Flags>(p);
}
return run_with_flags<Flags + 1>(flags, p);
}
}
int main(int argc, char** argv) {
ios::sync_with_stdio(false);
cout << "num threads: " << omp_get_max_threads() << endl;
cmdline::parser p;
p.add<string>("base_fn", 'i', "input file name of database vectors (in ASCII format)", true);
p.add<string>("query_fn", 'q', "input file name of query vectors (in ASCII format)", true);
p.add<string>("groundtruth_fn", 'o', "output file name of the groundtruth", true);
p.add<uint32_t>("begin_id", 'b', "beginning ID of data column", false, 0);
p.add<bool>("weighted", 'w', "Does the input data have weight?", false, false);
p.add<bool>("generalized", 'g', "Does the input data need to be generalized?", false, false);
p.add<bool>("labeled", 'l', "Does each input vector have a label at the head?", false, false);
p.add<uint32_t>("topk", 'k', "k-nearest neighbors", false, 100);
p.add<size_t>("progress", 'p', "step of printing progress", false, 100);
p.parse_check(argc, argv);
auto weighted = p.get<bool>("weighted");
auto generalized = p.get<bool>("generalized");
auto labeled = p.get<bool>("labeled");
auto flags = make_flags(weighted, generalized, labeled);
return run_with_flags(flags, p);
} | 34.912281 | 101 | 0.573618 | [
"vector"
] |
ffb1809070fef638b3bf261f03e00b01aab6b188 | 5,917 | cpp | C++ | serialization.cpp | edahlseng/duperagent | 2dc0f4f41aa897c46aa42b4f6d76aa69c0a0c1d9 | [
"MIT"
] | 54 | 2016-01-12T15:12:32.000Z | 2021-11-09T11:46:39.000Z | serialization.cpp | edahlseng/duperagent | 2dc0f4f41aa897c46aa42b4f6d76aa69c0a0c1d9 | [
"MIT"
] | 21 | 2016-08-03T22:14:47.000Z | 2021-04-08T07:36:32.000Z | serialization.cpp | edahlseng/duperagent | 2dc0f4f41aa897c46aa42b4f6d76aa69c0a0c1d9 | [
"MIT"
] | 27 | 2016-02-10T10:36:06.000Z | 2021-07-02T05:46:29.000Z | // Copyright 2016 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QStringBuilder>
#include <QtCore/QUrlQuery>
#include <QtQml/QQmlEngine>
#include "serialization.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
#include "jsvalueiterator.h"
#else
#include <QtQml/QJSValueIterator>
typedef QJSValueIterator JSValueIterator;
#endif
namespace com { namespace cutehacks { namespace duperagent {
static const QChar OPEN_SQUARE('[');
static const QChar CLOSE_SQUARE(']');
BodyCodec::BodyCodec(QQmlEngine *engine) : m_engine(engine) {}
JsonCodec::JsonCodec(QQmlEngine *engine) : BodyCodec(engine) {}
QJSValue JsonCodec::parse(const QByteArray &data) {
QJsonDocument doc = QJsonDocument::fromJson(data, 0);
return parseJsonDocument(doc);
}
QJSValue JsonCodec::parseJsonDocument(const QJsonDocument &doc)
{
if (doc.isObject()) {
return parseJsonObject(doc.object());
} else if (doc.isArray()) {
return parseJsonArray(doc.array());
} else if(doc.isNull()){
return QJSValue(QJSValue::NullValue);
} else {
return QJSValue();
}
}
QJSValue JsonCodec::parseJsonArray(const QJsonArray &array) {
QJSValue a = m_engine->newArray(array.size());
int i = 0;
for (QJsonArray::ConstIterator it = array.constBegin(); it != array.constEnd(); it++) {
a.setProperty(i++, parseJsonValue(*it));
}
return a;
}
QJSValue JsonCodec::parseJsonObject(const QJsonObject &object)
{
QJSValue o = m_engine->newObject();
for (QJsonObject::ConstIterator it = object.constBegin(); it != object.constEnd(); it++) {
o.setProperty(it.key(), parseJsonValue(it.value()));
}
return o;
}
QJSValue JsonCodec::parseJsonValue(const QJsonValue &val)
{
switch (val.type()) {
case QJsonValue::Array:
return parseJsonArray(val.toArray());
case QJsonValue::Object:
return parseJsonObject(val.toObject());
case QJsonValue::Bool:
return QJSValue(val.toBool());
case QJsonValue::Double:
return QJSValue(val.toDouble());
case QJsonValue::String:
return QJSValue(val.toString());
case QJsonValue::Null:
return QJSValue(QJSValue::NullValue);
case QJsonValue::Undefined:
default:
return QJSValue(QJSValue::UndefinedValue);
}
}
QByteArray JsonCodec::stringify(const QJSValue &json)
{
QJsonDocument doc;
if (json.isArray()) {
doc.setArray(stringifyArray(json));
} else if (json.isObject()) {
doc.setObject(stringifyObject(json));
}
return doc.toJson(QJsonDocument::Compact);
}
QJsonObject JsonCodec::stringifyObject(const QJSValue &json) const
{
QJsonObject object;
JSValueIterator it(json);
while (it.next()) {
object.insert(it.name(), stringifyValue(it.value()));
}
return object;
}
QJsonArray JsonCodec::stringifyArray(const QJSValue &json) const
{
QJsonArray array;
JSValueIterator it(json);
while (it.next()) {
if (it.hasNext()) // skip last item which is length
array.append(stringifyValue(it.value()));
}
return array;
}
QJsonValue JsonCodec::stringifyValue(const QJSValue &json) const
{
if (json.isArray()) {
return QJsonValue(stringifyArray(json));
} else if (json.isObject()) {
QJSValue toJSON = json.property("toJSON");
if (toJSON.isCallable())
return stringifyValue(toJSON.callWithInstance(json));
else
return QJsonValue(stringifyObject(json));
} else if (json.isBool()) {
return QJsonValue(json.toBool());
} else if (json.isNumber()) {
return QJsonValue(json.toNumber());
} else {
return QJsonValue(json.toString());
}
}
FormUrlEncodedCodec::FormUrlEncodedCodec(QQmlEngine *engine) : BodyCodec(engine)
{ }
QByteArray FormUrlEncodedCodec::stringify(const QJSValue &json)
{
QueryItems items;
JSValueIterator it(json);
while (it.next()) {
QString key = it.name();
items << stringifyValue(key, it.value());
}
QUrlQuery query;
query.setQueryItems(items);
return query.toString(QUrl::FullyEncoded).toUtf8();
}
QueryItems FormUrlEncodedCodec::stringifyObject(const QString& prefix, const QJSValue &json) const
{
QueryItems items;
JSValueIterator it(json);
while (it.next()) {
items << stringifyValue(prefix % OPEN_SQUARE % it.name() % CLOSE_SQUARE, it.value());
}
return items;
}
QueryItems FormUrlEncodedCodec::stringifyArray(const QString& prefix, const QJSValue &json) const
{
QueryItems items;
JSValueIterator it(json);
while (it.next()) {
if (it.hasNext()) //skip last item which is length
items << stringifyValue(prefix % OPEN_SQUARE % it.name() % CLOSE_SQUARE, it.value());
}
return items;
}
QueryItems FormUrlEncodedCodec::stringifyValue(const QString& prefix, const QJSValue &json) const
{
if (json.isArray()) {
return stringifyArray(prefix, json);
} else if (json.isObject()) {
QJSValue toJSON = json.property("toJSON");
if (toJSON.isCallable())
return stringifyValue(prefix, toJSON.callWithInstance(json));
else
return stringifyObject(prefix, json);
} else if (json.isNull()) {
return QueryItems() << QPair<QString, QString>(prefix, QString());
} else if (json.hasProperty("toJSON") && json.property("toJSON").isCallable()){
return QueryItems() << QPair<QString, QString>(
prefix, json.property("toJSON").callWithInstance(json).toString());
} else {
return QueryItems() << QPair<QString, QString>(prefix, json.toString());
}
}
QJSValue FormUrlEncodedCodec::parse(const QByteArray &)
{
QJSValue json = m_engine->newObject();
return json;
}
} } }
| 29.004902 | 98 | 0.664526 | [
"object"
] |
ffb7741f11e5e09834f3d49666c2b37016401d6f | 2,939 | cpp | C++ | Sources/Elastos/LibCore/src/org/apache/harmony/security/x501/CAttributeTypeAndValueComparator.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/src/org/apache/harmony/security/x501/CAttributeTypeAndValueComparator.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/src/org/apache/harmony/security/x501/CAttributeTypeAndValueComparator.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "CAttributeTypeAndValueComparator.h"
using Elastos::Core::EIID_IComparator;
using Elastos::IO::EIID_ISerializable;
namespace Org {
namespace Apache {
namespace Harmony {
namespace Security {
namespace X501 {
CAR_OBJECT_IMPL(CAttributeTypeAndValueComparator)
CAR_INTERFACE_IMPL_2(CAttributeTypeAndValueComparator, Object, IComparator, ISerializable)
ECode CAttributeTypeAndValueComparator::Compare(
/* [in] */ IInterface * atav1,
/* [in] */ IInterface * atav2,
/* [out] */ Int32 * result)
{
VALIDATE_NOT_NULL(result);
if (atav1 == atav2) {
*result = 0;
return NOERROR;
}
AutoPtr<IObjectIdentifier> type1;
AutoPtr<IObjectIdentifier> type2;
IAttributeTypeAndValue::Probe(atav1)->GetType((IObjectIdentifier**)&type1);
IAttributeTypeAndValue::Probe(atav2)->GetType((IObjectIdentifier**)&type2);
String kw1;
type1->GetName(&kw1);
String kw2;
type2->GetName(&kw2);
if (kw1 != NULL && kw2 == NULL) {
*result = -1;
return NOERROR;
}
if (kw1 == NULL && kw2 != NULL) {
*result = 1;
return NOERROR;
}
if (kw1 != NULL && kw2 != NULL) {
*result = kw1.Compare(kw2);
return NOERROR;
}
*result = CompateOids(type1, type2);
return NOERROR;
}
Int32 CAttributeTypeAndValueComparator::CompateOids(
/* [in] */ IObjectIdentifier* oid1,
/* [in] */ IObjectIdentifier* oid2)
{
if (oid1 == oid2) {
return 0;
}
AutoPtr<ArrayOf<Int32> > ioid1;
oid1->GetOid((ArrayOf<Int32>**)&ioid1);
AutoPtr<ArrayOf<Int32> > ioid2;
oid2->GetOid((ArrayOf<Int32>**)&ioid2);
Int32 min = ioid1->GetLength() < ioid2->GetLength() ? ioid1->GetLength() : ioid2->GetLength();
for (Int32 i = 0; i < min; ++i) {
if ((*ioid1)[i] < (*ioid2)[i]) {
return -1;
}
if ((*ioid1)[i] > (*ioid2)[i]) {
return 1;
}
if ((i + 1) == ioid1->GetLength() && (i + 1) < ioid2->GetLength()) {
return -1;
}
if ((i + 1) < ioid1->GetLength() && (i + 1) == ioid2->GetLength()) {
return 1;
}
}
return 0;
}
}
}
}
}
}
| 28.533981 | 98 | 0.585573 | [
"object"
] |
ffbf5b1a7ea5a2e7fcfce90f7a7017326efabeae | 2,148 | hpp | C++ | include/public/coherence/io/pof/ThrowablePofSerializer.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | include/public/coherence/io/pof/ThrowablePofSerializer.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | include/public/coherence/io/pof/ThrowablePofSerializer.hpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_THROWABLE_POF_SERIALIZER_HPP
#define COH_THROWABLE_POF_SERIALIZER_HPP
#include "coherence/lang.ns"
#include "coherence/io/pof/PofReader.hpp"
#include "coherence/io/pof/PofWriter.hpp"
#include "coherence/util/Collection.hpp"
COH_OPEN_NAMESPACE3(coherence,io,pof)
using coherence::util::Collection;
/**
* PofSerializer implementation that can serialize and deserialize an
* Exception to/from a POF stream.
*
* This serializer is provides a catch-all mechanism for serializing exceptions.
* Any deserialized exception will loose type information, and simply be
* represented as a PortableException. The basic detail information of the
* exception are retained.
*
* PortableException and this class work asymmetricly to provide the
* serialization routines for exceptions.
*
* @author mf 2008.08.25
*/
class COH_EXPORT ThrowablePofSerializer
: public class_spec<ThrowablePofSerializer,
extends<Object>,
implements<PofSerializer> >
{
friend class factory<ThrowablePofSerializer>;
// ----- constructors ---------------------------------------------------
protected:
/**
* Default constructor.
*/
ThrowablePofSerializer();
// ----- PofSerializer interface ----------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual void serialize(PofWriter::Handle hOut, Object::View v) const;
/**
* {@inheritDoc}
*/
virtual Object::Holder deserialize(PofReader::Handle hIn) const;
// ----- helpers --------------------------------------------------------
public:
/**
* Write the Exception to the specified stream.
*
* @param hOut the stream to write to
* @param ve the Exception to write
*/
static void writeThrowable(PofWriter::Handle hOut, Exception::View ve);
};
COH_CLOSE_NAMESPACE3
#endif // COH_THROWABLE_POF_SERIALIZER_HPP
| 26.85 | 79 | 0.635009 | [
"object"
] |
ffc87767f281cc31be43bc807fdae4d44c83e900 | 2,885 | cpp | C++ | modules/Render/RenderBootstrap/test/FixtureBase.cpp | akb825/DeepSea | fff790d0a472cf2f9f89de653e0b4470ce605d24 | [
"Apache-2.0"
] | 5 | 2018-11-17T23:13:22.000Z | 2021-09-30T13:37:04.000Z | modules/Render/RenderBootstrap/test/FixtureBase.cpp | akb825/DeepSea | fff790d0a472cf2f9f89de653e0b4470ce605d24 | [
"Apache-2.0"
] | null | null | null | modules/Render/RenderBootstrap/test/FixtureBase.cpp | akb825/DeepSea | fff790d0a472cf2f9f89de653e0b4470ce605d24 | [
"Apache-2.0"
] | 2 | 2019-09-23T12:23:35.000Z | 2020-04-07T05:31:06.000Z | /*
* Copyright 2019-2021 Aaron Barany
*
* 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 "FixtureBase.h"
#include <DeepSea/Core/Streams/Path.h>
#include <DeepSea/Render/Renderer.h>
#include <DeepSea/RenderBootstrap/RenderBootstrap.h>
static std::vector<dsRendererType> getSupportedRenderers()
{
std::vector<dsRendererType> renderers;
for (int i = 0; i < dsRendererType_Default; ++i)
{
if (dsRenderBootstrap_isSupported((dsRendererType)i))
renderers.push_back((dsRendererType)i);
}
return renderers;
}
testing::internal::ParamGenerator<dsRendererType> FixtureBase::getRendererTypes()
{
static std::vector<dsRendererType> rendererTypes = getSupportedRenderers();
return testing::ValuesIn(rendererTypes);
}
void FixtureBase::SetUp()
{
dsSystemAllocator_initialize(&allocator, DS_ALLOCATOR_NO_LIMIT);
dsRendererOptions options;
dsRenderer_defaultOptions(&options, "deepsea_test_render_bootstrap", 0);
adjustRendererOptions(options);
renderer = dsRenderBootstrap_createRenderer(GetParam(), &allocator.allocator, &options);
ASSERT_TRUE(renderer);
resourceManager = renderer->resourceManager;
dsShaderVersion shaderVersions[] =
{
{DS_VK_RENDERER_ID, DS_ENCODE_VERSION(1, 0, 0)},
{DS_MTL_RENDERER_ID, DS_ENCODE_VERSION(1, 1, 0)},
{DS_GL_RENDERER_ID, DS_ENCODE_VERSION(1, 1, 0)},
{DS_GL_RENDERER_ID, DS_ENCODE_VERSION(1, 5, 0)},
{DS_GL_RENDERER_ID, DS_ENCODE_VERSION(4, 3, 0)},
{DS_GLES_RENDERER_ID, DS_ENCODE_VERSION(1, 0, 0)},
{DS_GLES_RENDERER_ID, DS_ENCODE_VERSION(3, 0, 0)},
{DS_GLES_RENDERER_ID, DS_ENCODE_VERSION(3, 2, 0)},
};
const dsShaderVersion* shaderVersion = dsRenderer_chooseShaderVersion(renderer, shaderVersions,
DS_ARRAY_SIZE(shaderVersions));
ASSERT_TRUE(shaderVersion);
ASSERT_TRUE(dsRenderer_shaderVersionToString(m_buffer, sizeof(m_buffer), renderer,
shaderVersion));
ASSERT_TRUE(dsPath_combine(m_shaderDir, sizeof(m_shaderDir), "RenderBootstrapTest-assets",
m_buffer));
EXPECT_TRUE(dsRenderer_beginFrame(renderer));
}
void FixtureBase::TearDown()
{
EXPECT_TRUE(dsRenderer_endFrame(renderer));
dsRenderer_destroy(renderer);
EXPECT_EQ(0U, allocator.allocator.size);
}
void FixtureBase::adjustRendererOptions(dsRendererOptions&)
{
}
const char* FixtureBase::getShaderPath(const char* fileName) const
{
dsPath_combine(m_buffer, sizeof(m_buffer), m_shaderDir, fileName);
return m_buffer;
}
| 32.41573 | 96 | 0.776776 | [
"render",
"vector"
] |
ffd02eb75c65c7eecbce4d1ac380a5ea7e55e3d7 | 4,066 | hpp | C++ | semantic_icp/impl/semantic_point_cloud.hpp | kxhit/semantic-icp | 1405daacd92becafe1d3e589c6eeb90c893787a4 | [
"BSD-3-Clause"
] | 21 | 2020-03-09T04:21:32.000Z | 2022-03-24T07:16:41.000Z | semantic_icp/impl/semantic_point_cloud.hpp | jtpils/semantic-icp | 1405daacd92becafe1d3e589c6eeb90c893787a4 | [
"BSD-3-Clause"
] | null | null | null | semantic_icp/impl/semantic_point_cloud.hpp | jtpils/semantic-icp | 1405daacd92becafe1d3e589c6eeb90c893787a4 | [
"BSD-3-Clause"
] | 9 | 2019-04-19T06:28:56.000Z | 2022-03-21T05:18:32.000Z | #ifndef SEMANTIC_POINT_CLOUD_HPP_
#define SEMANTIC_POINT_CLOUD_HPP_
#include <cmath>
#include <iostream>
#include <pcl/common/transforms.h>
namespace semanticicp
{
template<typename PointT, typename SemanticT>
void SemanticPointCloud<PointT, SemanticT>::addSemanticCloud(
SemanticT label, PointCloudPtr cloud_ptr,
bool computeKd, bool computeCov) {
semanticLabels.push_back(label);
labeledPointClouds[label] = cloud_ptr;
if( computeKd == true) {
KdTreePtr tree(new KdTree());
tree->setInputCloud(cloud_ptr);
labeledKdTrees[label] = tree;
if( computeCov == true) {
Eigen::Vector3d mean;
std::vector<int> nn_indecies; nn_indecies.reserve (k_correspondences_);
std::vector<float> nn_dist_sq; nn_dist_sq.reserve (k_correspondences_);
typename pcl::PointCloud<PointT>::const_iterator points_iterator =
cloud_ptr->begin ();
MatricesVectorPtr cloud_covariances(new MatricesVector);
for(;points_iterator != cloud_ptr->end (); ++points_iterator) {
const PointT &query_point = *points_iterator;
Eigen::Matrix3d cov;
cov.setZero();
mean.setZero();
tree->nearestKSearch(query_point, k_correspondences_, nn_indecies, nn_dist_sq);
for(int index: nn_indecies) {
const PointT &pt = (*cloud_ptr)[index];
mean[0] += pt.x;
mean[1] += pt.y;
mean[2] += pt.z;
cov(0,0) += pt.x*pt.x;
cov(1,0) += pt.y*pt.x;
cov(1,1) += pt.y*pt.y;
cov(2,0) += pt.z*pt.x;
cov(2,1) += pt.z*pt.y;
cov(2,2) += pt.z*pt.z;
}
mean /= static_cast<double> (k_correspondences_);
for (int k = 0; k < 3; k++){
for (int l = 0; l <= k; l++)
{
cov(k,l) /= static_cast<double> (k_correspondences_);
cov(k,l) -= mean[k]*mean[l];
cov(l,k) = cov(k,l);
}
}
Eigen::JacobiSVD<Eigen::Matrix3d> svd(cov, Eigen::ComputeFullU);
cov.setZero();
Eigen::Matrix3d U = svd.matrixU();
for(int k = 0; k<3; k++) {
Eigen::Vector3d col = U.col(k);
double v = 1.;
if(k == 2)
v = epsilon_;
cov+= v*col*col.transpose();
}
cloud_covariances->push_back(cov);
}
labeledCovariances[label] = cloud_covariances;
}
}
};
template<typename PointT, typename SemanticT>
pcl::PointCloud<pcl::PointXYZL>::Ptr SemanticPointCloud<PointT, SemanticT>::getpclPointCloud (){
pcl::PointCloud<pcl::PointXYZL>::Ptr cloudPtr(new pcl::PointCloud<pcl::PointXYZL>());
for( SemanticT s: semanticLabels) {
for ( PointT p: *(labeledPointClouds[s]) ) {
pcl::PointXYZL tempP;
tempP.x = p.x;
tempP.y = p.y;
tempP.z = p.z;
tempP.label = uint32_t(s);
cloudPtr->push_back(tempP);
}
}
return cloudPtr;
};
template<typename PointT, typename SemanticT>
void SemanticPointCloud<PointT, SemanticT>::transform(Eigen::Matrix4f trans) {
for( SemanticT s: semanticLabels) {
pcl::transformPointCloud (*(labeledPointClouds[s]), *(labeledPointClouds[s]),
trans);
}
};
} // namespace semanticicp
#endif //SEMANTIC_POINT_COULD_HPP_
| 35.051724 | 100 | 0.482784 | [
"vector",
"transform"
] |
ffd3dea8acf6798bfdba46d698dceabd150159ff | 1,844 | cpp | C++ | modules/core/exponential/cover/simd/expx2.cpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 34 | 2017-05-19T18:10:17.000Z | 2022-01-04T02:18:13.000Z | modules/core/exponential/cover/simd/expx2.cpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/core/exponential/cover/simd/expx2.cpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 7 | 2017-12-02T12:59:17.000Z | 2021-07-31T12:46:14.000Z | //==============================================================================
// Copyright 2003 - 2014 LASMEA UMR 6602 CNRS/UBP
// Copyright 2009 - 2014 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
// cover for functor expx2 in simd mode
#include <nt2/exponential/include/functions/expx2.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <cmath>
#include <iostream>
#include <nt2/sdk/unit/args.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/cover.hpp>
#include <vector>
NT2_TEST_CASE_TPL(expx2_0, NT2_SIMD_REAL_TYPES)
{
using boost::simd::native;
typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t;
typedef native<T,ext_t> vT;
using nt2::unit::args;
const std::size_t NR = args("samples", NT2_NB_RANDOM_TEST);
const double ulpd = args("ulpd", 2.5);
const T min = args("min", T(1));
const T max = args("max", T(5));
std::cout << "Argument samples #0 chosen in range: [" << min << ", " << max << "]" << std::endl;
NT2_CREATE_BUF(a0,T, NR, min, max);
std::vector<T> ref1(NR), ref2(NR);
std::vector<T> a1(NR);
for(std::size_t i=0; i!=NR; ++i)
{
ref1[i] = T(nt2::expx2(a0[i]));
ref2[i] = T(nt2::expx2(a0[i], T(-1)));
a1[i] = T(-1.0);
}
NT2_COVER_ULP_EQUAL(nt2::tag::expx2_, ((vT, a0)), ref1, ulpd);
std::cout << "Argument samples #0 chosen in range: [" << min << ", " << max << "]" << std::endl;
std::cout << "Argument #1 is -1" << std::endl;
NT2_COVER_ULP_EQUAL(nt2::tag::expx2_, ((T, a0))((T, a1)), ref2, ulpd);
}
| 36.156863 | 99 | 0.558568 | [
"vector"
] |
ffda8218a2924ae966b73699297c74f35ef21f1a | 871 | hpp | C++ | include/RavEngine/RMLFileInterface.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 48 | 2020-11-18T23:14:25.000Z | 2022-03-11T09:13:42.000Z | include/RavEngine/RMLFileInterface.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 1 | 2020-11-17T20:53:10.000Z | 2020-12-01T20:27:36.000Z | include/RavEngine/RMLFileInterface.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 3 | 2020-12-22T02:40:39.000Z | 2021-10-08T02:54:22.000Z | #pragma once
#include <RmlUi/Core/FileInterface.h>
#include "VirtualFileSystem.hpp"
namespace RavEngine{
class VFSInterface : public Rml::FileInterface{
private:
struct VFShandle{
RavEngine::Vector<uint8_t> filedata;
long offset = 0;
inline size_t size_bytes() const{
return filedata.size() * sizeof(decltype(filedata)::value_type);
}
};
public:
// Opens a file.
Rml::FileHandle Open(const Rml::String& path) override;
// Closes a previously opened file.
void Close(Rml::FileHandle file) override;
// Reads data from a previously opened file.
size_t Read(void* buffer, size_t size, Rml::FileHandle file) override;
// Seeks to a point in a previously opened file.
bool Seek(Rml::FileHandle file, long offset, int origin) override;
// Returns the current position of the file pointer.
size_t Tell(Rml::FileHandle file) override;
};
}
| 26.393939 | 71 | 0.731343 | [
"vector"
] |
ffdd5271b6232273bd5726dbdfe64739b8e41b21 | 14,895 | cpp | C++ | src/graphlab/docs/distgl.cpp | iivek/graphlab-cmu-mirror | 028321757ea979e6a0859687e37933be375153eb | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-08-01T06:32:58.000Z | 2018-08-01T06:32:58.000Z | src/graphlab/docs/distgl.cpp | iivek/graphlab-cmu-mirror | 028321757ea979e6a0859687e37933be375153eb | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/graphlab/docs/distgl.cpp | iivek/graphlab-cmu-mirror | 028321757ea979e6a0859687e37933be375153eb | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2009 Carnegie Mellon University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
/**
\page distributed_gl Using Distributed GraphLab
Distributed GraphLab is necessarily more complex than the shared memory
version, though much effort has gone into making it as useable as possible.
The distributed GraphLab implementation is built on top of the \ref RPC "RPC"
framework, and at least a cursory glance at \ref Spawning
as well \ref graphlab::distributed_control might be useful.
\li \ref page_distributed_graph_creation
\li \ref page_distributed_graphlab
\page page_distributed_graph_creation Distributed Graph Creation
The goal of distributed GraphLab is to both handle graphs that exceed the memory
capacity, and to make use of more processors than what is available on a
single node. Since the number of machines available may
vary with performance demands, the graph representation must
support loading of the data graph on varying sized cluster deployments.
To resolve these issues, we developed an on-disk graph representation based
on a two-phased partitioning scheme.
\section sec_disk_graph_atom Atom partitioning
The initial user graph must first be over-partitioned into
more parts than the largest cluster deployment you will ever use for the data.
Each of these parts is called an <b> atom </b>. An atom not just contains the
vertices and edges within its partition, but also contains information about the
vertices and edges immediately adjacent to the partition (also called the
<b> ghost </b> of the partition.)
A collection of atoms which make up a complete graph is called a <b> disk graph </b>.
The atom file names are of the form "[basename].0", "[basename].1",
"[basename].2", etc. Each atom is stored a binary format
Kyoto Cabinet (http://fallabs.com/kyotocabinet/) hash table.
The user should almost never have to interact with the atoms directly, but the format
is documented briefly in graphlab::disk_atom.
A proper disk graph must also include an <b> atom index file </b> with
filename "[basename].idx". The atom index is an additional human readable/modifiable
text file which provides some basic
information about the graph (number of vertices, number of edges), the adjacency
structure of the atoms, and most importantly, the <b> file location / URL </b>
of the atom files themselves. (Currently only the file:// URL protocol is supported,
but future enhancements might support additional protocols.)
\note In cases where the atom index is missing, the \ref graphlab::disk_graph does
provide a constructor to load a disk graph without an atom index. After which
finalization will re-generate the atom index.
\section sec_disk_graph_creation Graph Creation
There are three different methods of creating a disk graph, targeted at three different
use cases.
\li \ref sec_memory_to_disk_graph Graph is small enough to <b>fit in memory</b> on one machine.
This case is common when the user is testing a distributed GraphLab implementation,
or when computation time is large compared to the graph size.
\li \ref sec_disk_graph Graph is small enough to be <b>created on one machine</b>.
This case is the middle ground between the methods above and below this. The graph is small
enough that it can be written to disk in reasonable time on one machine.
\li \ref sec_distributed_disk_graph Graph is too large to create on one machine. Distributed
processing is necessary to even construct the graph in reasonable time. This is the most complex
case and requires more user effort than the above two.
\subsection sec_memory_to_disk_graph Conversion of In Memory Graph to Disk Graph
This is the simplest case and the user only has to instantiate a regular in-memory graph
using graphlab::graph. Following which an atom partitioning could be generated
using any one of the partition methods in graphlab::graph.
Calling graphlab::graph_partition_to_atomindex will convert the graph to a disk graph.
\subsection sec_disk_graph Direct Creation of Disk Graph
\copydoc graphlab::disk_graph
\subsection sec_distributed_disk_graph Distributed Graph Creation
A MapReduce style distributed graph construction method is provided
by graphlab::mr_disk_graph_construction. The basic requirement is that all the machines
have a shared file storage (NFS / SMBFS / etc).
The user first has to create a subclass of the \ref graphlab::igraph_constructor
which simply provides a iteration mechanism over an arbitrary subset of the vertices/edges
of the graph. Some restrictions on the graph constructor are necessary since it must be
"distributed-aware".
After which \ref graphlab::mr_disk_graph_construction will use the graph constructor to
perform a highly parallel/distributed construction of the disk graph.
This is best illustrated using an example
\ref distributed_dg_construction_test.cpp
*/
/**
\page page_distributed_graphlab Distributed GraphLab
To work with distributed GraphLab, MPI is needed. We have tested with MPICH2 and the MPI
distribution that comes with OS X. However, other distributions of MPI (Open MPI) should
work as well.
Distributed GraphLab is functionally quite similar to the regular GraphLab. But due to the
law of leaky abstractions (http://www.joelonsoftware.com/articles/LeakyAbstractions.html),
there are some issues the user will have to take into consideration.
Firstly, the graph cannot be created on the fly, and must be created before-hand and loaded from
an atom index file ( \ref page_distributed_graph_creation ).
Next, since multiple instances of the program is started across the network, some amount of
coordination is needed to ensure that all instances behave identically. We strongly encourage
the use of graphlab::core (which is the distributed setting is graphlab::distributed_core) since
that simplifies the amount of management needed.
\attention The general rule is that any operation which affect operation on a global scale
(for instance, a configuration setting) should be called by all instances simultaneously.
For users who have read the shared memory detailed_example, or are already familiar with
the shared memory GraphLab, can simply read on.
Otherwise here is a distributed version of the shared memory detailed_example:
\ref distributed_detailed_example
Depending on the complexity of your program, moving from the
shared memory version to the distributed version can be quite mechanical.
The key differences are listed here.
An easy way to see what changes you have to make to move a shared memory version
to a distributed version is to take a diff between tests/demo/demo.cpp and tests/dist_demo/dist_demo.cpp
\section sec_distributed_types Types
Instead of including <tt>graphlab.hpp</tt>, you should include <tt>distributed_graphlab.hpp</tt>
Similarly, the distributed version core is called <tt>dgraphlab::istributed_core</tt> and the distributed
version of the types struct is <tt>graphlab::distributed_types</tt>.
We recommend using the <tt>graphlabb::distributed_types</tt> system,
\code
typedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;
typedef graphlab::distributed_types<graph_type> gl;
\endcode
since it this will allow you to "copy and paste" code from your shared memory implementation
easily while the type system changes the back-end implementations.
For instance, your update function should not use <tt>graphlab::edge_list</tt>, but should
use <tt>gl::edge_list</tt> since the exact type is different for the shared memory graph
and for the distributed graph.
Similarly, <tt>gl::distributed_core</tt> should be used instead of <tt>core</tt> and
<Tt>gl::distributed_glshared</tt> should be used instead of <tt>glshared</tt>
\section sec_distributed_use_disk_graph Use The Disk Graph
Unlike the shared memory version, the graph cannot be created on the fly. The user must first
create a disk graph, then construct the distributed_core / distributed_graph from the disk graph.
\section sec_distributed_build_parallel_execution Distributed Execution
The user must constantly keep in mind that in the distributed setting, there are a collection
of "independent" copies of the program being executed, all communicating through MPI or
through the \ref RPC "GraphLab RPC" system.
All distributed_core / engine functions generally require all machines to execute the exact
same code path, running the same functions at the same time. For instance, the following code:
\code
core.set_sync(...);
core.set_engine_options(clopts);
core.build_engine();
\endcode
should be executed by all machines in the same order at the same time. Some of these functions
(for instance <tt>core.build_engine()</tt> ) has an internal distributed barrier which ensures that
all machines must reach the <tt>build_engine()</tt> call before execution can proceed.
There are a few exceptions to this rule (such as <tt>add_task()</tt>) and these are documented.
\section sec_distributed_graph_limitations Distributed Graph Limitations
The regular graph has functions which permit obtaining vertex and edge data by reference.
The distributed_graph has similar functions but for obvious reasons, it is restricted to
vertex and edge data "owned" by the local partition. The alternate functions
get_vertex_data() / set_vertex_data() as well as the edge varieties should be used instead.
These return by value and can get/set vertex and edge data from across the network.
The user should keep in mind that these remote network gets/sets are inherently slow
and is where the Law of Leaky Abstractions slip through. If a large number of vertex/edge reads
and writes are needed, it is recommended that the user make use of the \ref RPC "RPC" operations
to gather/scatter the information in bulk instead of accessing the data one at a time. Alternatively,
the graph can be saved to disk and loaded using one machine making use of the disk_graph
class.
\section sec_distributed_graphlab_build_the_engine Build The Engine
The shared memory core automatically destroys and reconstructs the engine as options change.
This is unfortunately difficult to coordinate in the distributed setting. Therefore the user
must explicitly construct the engine once all options are set through the \ref graphlab::distributed_core::build_engine()
function.
Once the engine has been constructed, it can be used repeatedly. However, engine options
can no longer be modified.
\section sec_distributed_graphlab_command_line_options Distributed Command Line Options
The graphlab::command_line_options object automatically injects options for the shared
memory engines. To get options for the distributed engine,
\code
opts.use_distributed_options();
\endcode
must be called prior to calling <tt>opts.parse()</tt>
\section sec_distributed_graphlab_engine_types Distributed Engine Types
The user will notice that the new command line options include a <tt>--engine</tt> option.
Distributed Graphlab implements two engines with very different characteristics. One is
called the chromatic engine (<tt>--engine=dist_chromatic</tt>), the other is called the locking engine
<tt>--engine=dist_locking</tt>. The chromatic engine is the default.
\subsection sec_distributed_graphlab_chromatic Chromatic Engine
The chromatic engine operates by associating an update_task with each vertex. It then makes
use of the graph coloring to run update tasks in parallel. For instance if my graph has 3 colors,
it will run all update tasks on vertices of color 0 in parallel. Stop, then run all tasks
on vertices of color 1 in parallel, etc.
The chromatic engine therefore does not use a scheduler since it essentially has a built in
chromatic scheduler. However, it assumes that <b>The graph coloring is valid for the
scope type requested</b>. In other words, if an edge scope is requested, then the graph coloring
must ensure that neighboring vertices do not have the same color. If a full scope is requested,
then the graph coloring must ensure that vertices one hop away from each other do not have the
same color. If coloring constraints are violated, the engine will still run properly, though
consistency guarantees do not hold.
\subsubsection chromatic_engine_options Engine Options
The max iteration count and whether to permute
the vertex update order can be set. There are two engine options, "max_iterations=N"
and "randomize_schedule=0 or 1" and these can be set on the command line:
\verbatim
--engine="dist_chromatic(max_iterations=10,randomize_schedule=1)"
\endverbatim
\subsubsection chromatic_engine_limitations Limitations
The chromatic engine is therefore somewhat limited in its scheduling capabilities
(only supporting a chromatic schedule), supports only one update function type, and requires
a valid graph coloring. However, it benefits from having a much smaller overhead than the
other more general Locking engine. It is therefore the default engine.
\subsection sec_distributed_graphlab_locking Locking Engine
The locking engine is the generalization of the shared memory implementation to the distributed
setting. It makes use of distributed locking to ensure consistency, and uses a variety of pipelining
methods to keep a large number of operations in flight at any time. It can work with a subset of the
shared memory schedulers.
The locking engine is much more general and operates almost identically to the shared memory
engines. However, the implementation complexity leads to some loss of efficiency.
\subsubsection locking_engine_options Engine Options
The locking engine takes one option: max_deferred_tasks_per_node which is the maximum number
of update tasks to keep in flight in the locking pipeline. The default value is 1000.
This can be set on the command line using:
\verbatim
--engine=dist_locking(max_deferred_tasks_per_node=10)"
\endverbatim
\section sec_distributed_graphlab_not_yet_implemented Incomplete Implementations
<tt>distributed_glshared_const</tt> is not yet implemented. The user can "emulate" this by
simply having a regular global variable and ensuring that all processes set the value of the
global variable on start up. Alternatively, <tt>distributed_glshared</tt> can be used as well.
Engine / core's sync_now() operation is not yet implemented.
*/
| 52.08042 | 121 | 0.8047 | [
"object"
] |
ffde5d7d31715a233063ec5390fa91bfa4b160e2 | 16,057 | cpp | C++ | Code/Source/blocks.cpp | aparis69/Rock-fracturing | 3f0d626cb63fb184a07384dd5d443e863ef7c4b9 | [
"MIT"
] | 41 | 2020-10-08T00:16:10.000Z | 2022-01-27T19:31:44.000Z | Code/Source/blocks.cpp | aparis69/Rock-fracturing | 3f0d626cb63fb184a07384dd5d443e863ef7c4b9 | [
"MIT"
] | 1 | 2020-12-15T12:14:35.000Z | 2021-01-05T08:55:27.000Z | Code/Source/blocks.cpp | aparis69/Rock-fracturing | 3f0d626cb63fb184a07384dd5d443e863ef7c4b9 | [
"MIT"
] | 3 | 2021-02-17T01:05:10.000Z | 2022-01-27T19:31:41.000Z | #include "blocks.h"
#include <queue>
// Source: https://github.com/leomccormack/convhull_3d
#define CONVHULL_3D_ENABLE
#include "convhull_3d.h"
// Source: https://github.com/aparis69/MarchingCubeCpp
#define MC_IMPLEM_ENABLE
#include "MC.h"
// Source: http://nothings.org/stb
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
// Multithread field function computation
#include <omp.h>
// Warping displacement strength stored as global
static ScalarField2D warpingField;
/*!
\brief Default constructor for node.
*/
SDFNode::SDFNode()
{
}
/*!
\brief Constructor from a bounding box.
\param box the bounding box.
*/
SDFNode::SDFNode(const Box& box) : box(box)
{
}
/*!
\brief Computes the gradient numerically at a given point.
\param p point
*/
Vector3 SDFNode::Gradient(const Vector3& p) const
{
static const double Epsilon = 0.01f;
double x = Signed(Vector3(p[0] - Epsilon, p[1], p[2])) - Signed(Vector3(p[0] + Epsilon, p[1], p[2]));
double y = Signed(Vector3(p[0], p[1] - Epsilon, p[2])) - Signed(Vector3(p[0], p[1] + Epsilon, p[2]));
double z = Signed(Vector3(p[0], p[1], p[2] - Epsilon)) - Signed(Vector3(p[0], p[1], p[2] + Epsilon));
return Vector3(x, y, z) * (0.5f / Epsilon);
}
/*!
\brief Constructor for a binary bounding sphere node.
\param a, b child nodes
\param re transition radius
*/
SDFUnionSphereLOD::SDFUnionSphereLOD(SDFNode* a, SDFNode* b, double re) : SDFNode(Box(a->box, b->box).Extended(Vector3(re))), re(re), sphere(Sphere(box.Center(), box.Size().Max()))
{
e[0] = a;
e[1] = b;
}
/*!
\brief Evaluates the node.
\param p point
*/
double SDFUnionSphereLOD::Signed(const Vector3& p) const
{
// Signed distance to bounding sphere
double sd = sphere.Distance(p);
if (sd > re)
return sd;
// Returns only sub-trees
double se = Math::Min(e[0]->Signed(p), e[1]->Signed(p));
if (sd < sphere.Radius())
return se;
// Interpolate between bounding sphere and sub-trees
double a = (sd - sphere.Radius()) / (re - sphere.Radius());
return (1.0 - a) * se + a * sd;
}
/*!
\brief Computes the bounding volume hiearchy using bounding sphere binary nodes.
\param nodes the nodes to organize
\param re transition radius
*/
SDFNode* SDFUnionSphereLOD::OptimizedBVH(std::vector<SDFNode*>& nodes, double re)
{
if (nodes.size() == 0)
return nullptr;
return OptimizedBVHRecursive(nodes, 0, int(nodes.size()), re);
}
/*!
\brief
*/
SDFNode* SDFUnionSphereLOD::OptimizedBVHRecursive(std::vector<SDFNode*>& pts, int begin, int end, double re)
{
/*
\brief BVH space partition predicate. Could also use a lambda function to avoid the structure.
*/
struct BVHPartitionPredicate
{
int axis;
double cut;
BVHPartitionPredicate(int a, double c) : axis(a), cut(c)
{
}
bool operator()(SDFNode* p) const
{
return (p->box.Center()[axis] < cut);
}
};
// If leaf, returns primitive
int nodeCount = end - begin;
if (nodeCount <= 1)
return pts[begin];
// Bounding box of primitive in [begin, end] range
Box bbox = pts[begin]->box;
for (int i = begin + 1; i < end; i++)
bbox = Box(bbox, pts[i]->box);
// Find the most stretched axis of the bounding box
// Cut the box in the middle of this stretched axis
int stretchedAxis = bbox.Diagonal().MaxIndex();
double axisMiddleCut = (bbox[0][stretchedAxis] + bbox[1][stretchedAxis]) / 2.0;
// Partition our primitives in relation to the axisMiddleCut
auto pmid = std::partition(pts.begin() + begin, pts.begin() + end, BVHPartitionPredicate(stretchedAxis, axisMiddleCut));
// Ensure the partition is not degenerate : all primitives on the same side
unsigned int midIndex = std::distance(pts.begin(), pmid);
if (midIndex == begin || midIndex == end)
midIndex = (begin + end) / 2;
// Recursive construction of sub trees
SDFNode* left = OptimizedBVHRecursive(pts, begin, midIndex, re);
SDFNode* right = OptimizedBVHRecursive(pts, midIndex, end, re);
// Union of the two child nodes
return new SDFUnionSphereLOD(left, right, re);
}
/*!
\brief Constructor from a node.
\param e child node
*/
SDFGradientWarp::SDFGradientWarp(SDFNode* e) : e(e)
{
box = e->box;
}
/*!
\brief Computes the warping strength as a triplanar parameterization of the texture.
\param p point
\param n normal
*/
double SDFGradientWarp::WarpingStrength(const Vector3& p, const Vector3& n) const
{
const double texScale = 0.1642f; // Hardcoded because it looks good
Vector2 x = Abs(Vector2(p[2], p[1])) * texScale;
Vector2 y = Abs(Vector2(p[0], p[2])) * texScale;
Vector2 z = Abs(Vector2(p[1], p[0])) * texScale;
double tmp;
x = Vector2(modf(x[0], &tmp), modf(x[1], &tmp));
y = Vector2(modf(y[0], &tmp), modf(y[1], &tmp));
z = Vector2(modf(z[0], &tmp), modf(z[1], &tmp));
// Blend weights
Vector3 ai = Abs(n);
ai = ai / (ai[0] + ai[1] + ai[2]);
// Blend everything
return ai[0] * warpingField.GetValueBilinear(x)
+ ai[1] * warpingField.GetValueBilinear(y)
+ ai[2] * warpingField.GetValueBilinear(z);
}
/*!
\brief Evalutes the warped signed distance to the node.
\param p point
*/
double SDFGradientWarp::Signed(const Vector3& p) const
{
// First compute gradient-based warping
Vector3 g = e->Gradient(p);
float s = 0.65 * WarpingStrength(p, -Normalize(g));
// Then compute contribution from the convex block
return e->Signed(p + g * s);
}
/*!
\brief Constructor for a smooth block, from a set of (closed) planes and a smoothing radius.
\param pl the planes
\param sr smoothing radius
*/
SDFBlock::SDFBlock(const std::vector<Plane>& pl, double sr) : SDFNode(Box(Plane::ConvexPoints(pl)).Extended(Vector3(0.01f)))
{
planes = pl;
smoothRadius = sr;
box = box.Extended(Vector3(sr));
}
/*!
\brief Generalized polynomial smoothing function between two distances.
Union: SmoothingPolynomial(a, b, smooth);
Inter: -SmoothingPolynomial(-a, -b, smooth);
Diffe: SmoothingPolynomial(-d1, d2, smooth);
\param a first distance
\param b second distance
\param sr smoothing radius
*/
double SDFBlock::SmoothingPolynomial(double d1, double d2, double sr) const
{
double h = Math::Max(sr - Math::Abs(d1 - d2), 0.0) / sr;
return Math::Min(d1, d2) - h * h * sr * 0.25;
}
/*!
\brief Compute the signed distance to the block primitive.
\param p point
*/
double SDFBlock::Signed(const Vector3& p) const
{
double d = planes.at(0).Signed(p);
for (int i = 1; i < planes.size(); i++)
{
double dd = planes.at(i).Signed(p);
d = -SmoothingPolynomial(-d, -dd, smoothRadius);
}
return d;
}
/*!
\brief Check if a given point can be linked to a candidate.
\param p point
\param c the candidate
\param fractures fracture set
*/
static bool BreakFractureConstraint(const Vector3& p, const Vector3& c, const FractureSet& fractures)
{
bool intersect = false;
double tmax = Magnitude(p - c);
Ray ray = Ray(p, Normalize(c - p));
for (int c = 0; c < fractures.Size(); c++)
{
double t;
if (fractures.At(c).Intersect(ray, t) && t < tmax)
{
intersect = true;
break;
}
}
return intersect;
}
/*!
\brief Check if the candidate can be linked to all other node in the cluster, without breaking a constraint or being too far.
*/
static bool CanBeLinkedToCluster(const Vector3& candidate, const std::vector<Vector3>& cluster, const FractureSet& fractures, double R_Max)
{
bool canBeLinked = true;
for (int i = 0; i < cluster.size(); i++)
{
Vector3 p = cluster[i];
// Distance criteria
if (SquaredMagnitude(candidate - p) > R_Max)
{
canBeLinked = false;
break;
}
// Fracture criteria
for (int c = 0; c < fractures.Size(); c++)
{
double tmax = Magnitude(p - candidate);
double t;
if (fractures.At(c).Intersect(Ray(p, Normalize(candidate - p)), t) && t < tmax)
{
canBeLinked = false;
break;
}
}
if (!canBeLinked)
break;
}
return canBeLinked;
}
/*!
\brief Load a greyscale image file for later use in gradient-based warping.
\param str image path
\param a min
\param b max
*/
void LoadImageFileForWarping(const char* str, double a, double b)
{
int nx, ny, n;
unsigned char* idata = stbi_load(str, &nx, &ny, &n, 1);
warpingField = ScalarField2D(nx, ny, Box2D(Vector2(0), Vector2(1)));
for (int i = 0; i < nx; i++)
{
for (int j = 0; j < ny; j++)
{
unsigned char g = idata[i * ny + j];
double t = double(g) / 255.0f;
warpingField.Set(i, j, t);
}
}
}
/*!
\brief Poisson sampling inside a 3D box, using dart-throwing.
\param box
\param r poisson radius
\param n number of try
*/
PointSet3 PoissonSamplingBox(const Box& box, double r, int n)
{
PointSet3 set;
double c = 4.0f * r * r;
for (int i = 0; i < n; i++)
{
Vector3 t = box.RandomInside();
bool hit = false;
for (int j = 0; j < set.Size(); j++)
{
if (SquaredMagnitude(t - set.At(j)) < c)
{
hit = true;
break;
}
}
if (hit == false)
set.pts.push_back(t);
}
return set;
}
/*!
\brief Fracture generation inside a box, from the fracture type.
Code is sometimes duplicated in this function.
\param type fracture type
\param box the box in which to distribute fractures
\param r radius influencing the distance between fracture centers.
*/
FractureSet GenerateFractures(FractureType type, const Box& box, double r)
{
FractureSet set;
if (type == FractureType::Equidimensional)
{
// "Three dominant sets of joints, approximately orthogonal, with occasional irregular joints, giving equidimensional blocks"
Box inflatedRockDomain = box.Extended(Vector3(-3.0));
PointSet3 samples = PoissonSamplingBox(inflatedRockDomain, 3.0, 1000);
for (int i = 0; i < samples.Size(); i++)
{
int a = Random::Integer() % 3;
Vector3 axis = a == 0 ? Vector3(1, 0, 0) : a == 1 ? Vector3(0, 1, 0) : Vector3(0, 0, 1);
double r = Random::Uniform(10.0f, 15.0f);
set.fractures.push_back(Circle(samples.At(i), axis, r));
}
}
else if (type == FractureType::Rhombohedral)
{
// "Three (or more) dominant mutually oblique sets of joints, giving oblique-shaped, equidimensional blocks."
Box inflatedRockDomain = box.Extended(Vector3(-3.0));
PointSet3 samples = PoissonSamplingBox(inflatedRockDomain, 3.0, 1000);
for (int i = 0; i < samples.Size(); i++)
{
int a = Random::Integer() % 3;
Vector3 axis = a == 0 ? Vector3(0.5, 0.5, 0) : a == 1 ? Vector3(0, 0.5, 0.5) : Vector3(0.5, 0, 0.5);
double r = Random::Uniform(10.0f, 15.0f);
set.fractures.push_back(Circle(samples.At(i), axis, r));
}
}
else if (type == FractureType::Polyhedral)
{
// "Irregular jointing without arrangement into distinct sets, and of small joints"
PointSet3 samples = PoissonSamplingBox(box, 1.0, 1000);
for (int i = 0; i < samples.Size(); i++)
{
double r = Random::Uniform(2.0f, 12.0f);
Vector3 axis = Sphere(Vector3(0), 1.0).RandomSurface();
set.fractures.push_back(Circle(samples.At(i), axis, r));
}
}
else if (type == FractureType::Tabular)
{
// "One dominant set of parallel joints, for example bedding planes, with other non-persistent joints; thickness of blocks much less than length or width."
// Y Axis
const int fracturing = 10;
Vector3 p = box[0];
p.x += box.Diagonal()[0] / 2.0f;
p.z += box.Diagonal()[1] / 2.0f;
double step = box.Size()[2] / float(fracturing);
double noiseStep = step / 10.0f;
for (int i = 0; i < fracturing - 1; i++)
{
p.y += step + Random::Uniform(-noiseStep, noiseStep);
Vector3 axis = Vector3(0, -1, 0);
set.fractures.push_back(Circle(p, axis, 20.0));
}
}
return set;
}
/*!
\brief Clustering step of the algorithm. We first build the constrained nearest neighbour graph
between samples, then perform a flood fill algorithm to get isolated clusters of points.
\param set samples of the cubic tile
\param frac the fractures
*/
std::vector<BlockCluster> ComputeBlockClusters(PointSet3& set, const FractureSet& frac)
{
const int allPtsSize = set.Size();
const float R_Neighborhood = 2.5f * 2.5f;
// Build constrained nearest neighor graph on tiled points
std::vector<std::vector<int>> graph;
graph.resize(allPtsSize);
for (int i = 0; i < allPtsSize; i++)
{
Vector3 p = set.At(i);
for (int j = 0; j < allPtsSize; j++)
{
if (i == j)
continue;
Vector3 q = set.At(j);
if (SquaredMagnitude(p - q) < R_Neighborhood && !BreakFractureConstraint(p, q, frac))
graph[i].push_back(j);
}
}
// Flood fill algorithm to find clusters
const float R_Max_Block = 10.5f * 10.5f;
std::vector<bool> visitedFlags;
visitedFlags.resize(allPtsSize, false);
std::vector<BlockCluster> clusters;
for (int j = 0; j < allPtsSize; j++)
{
std::queue<int> toVisit;
toVisit.push(j);
std::vector<Vector3> cluster;
while (toVisit.empty() == false)
{
int index = toVisit.front();
toVisit.pop();
if (visitedFlags[index])
continue;
Vector3 q = set.At(index);
if (!CanBeLinkedToCluster(q, cluster, frac, R_Max_Block))
continue;
cluster.push_back(q);
visitedFlags[index] = true;
for (int i = 0; i < graph[index].size(); i++)
{
if (visitedFlags[graph[index][i]])
continue;
toVisit.push(graph[index][i]);
}
}
if (cluster.size() > 10)
{
clusters.push_back({ cluster });
}
}
return clusters;
}
/*!
\brief Implicit primitive generation from the block clusters. This function is very similar to ComputeBlockMeshes,
but instead of extracting a mesh, we create an implicit primitive for each block defined as the smooth intersection
of half spaces. This is the function used in the paper - ComputeBlockMeshes is only here if you want to play with the
raw meshes.
\param clusters
*/
SDFNode* ComputeBlockSDF(const std::vector<BlockCluster>& clusters)
{
std::vector<SDFNode*> primitives;
for (int k = 0; k < clusters.size(); k++)
{
std::vector<Plane> ret;
std::vector<Vector3> allPts = clusters[k].pts;
// Compute convex hull
int n = int(allPts.size());
if (n <= 4)
continue;
ch_vertex* vertices = new ch_vertex[n];
for (int i = 0; i < n; i++)
vertices[i] = { allPts[i][0], allPts[i][1], allPts[i][2] };
int* faceIndices = NULL;
int nFaces;
convhull_3d_build(vertices, n, &faceIndices, &nFaces);
if (nFaces == 0)
continue;
// Extract planes from hull triangle
std::vector<Plane> planes;
for (int i = 0; i < nFaces; i++)
{
const int j = i * 3;
Vector3 v1 = Vector3(float(vertices[faceIndices[j + 0]].x), float(vertices[faceIndices[j + 0]].y), float(vertices[faceIndices[j + 0]].z));
Vector3 v2 = Vector3(float(vertices[faceIndices[j + 1]].x), float(vertices[faceIndices[j + 1]].y), float(vertices[faceIndices[j + 1]].z));
Vector3 v3 = Vector3(float(vertices[faceIndices[j + 2]].x), float(vertices[faceIndices[j + 2]].y), float(vertices[faceIndices[j + 2]].z));
Vector3 pn = Triangle(v1, v2, v3).Normal();
Vector3 pc = Triangle(v1, v2, v3).Center();
planes.push_back(Plane(pc, pn));
}
// Discard if domain is not closed.
auto convex = Plane::ConvexPoints(planes);
if (convex.size() > 0)
{
// @Warning: this cannot work in all cases: the correct smoothing radius must depend on
// The actual size of the convex primitive formed by the intersection of planes.
// So artifacts may occur by using a constant.
const double smoothRadius = 0.25;
primitives.push_back(new SDFGradientWarp(new SDFBlock(planes, smoothRadius)));
}
// Free memory
delete[] vertices;
delete[] faceIndices;
}
return SDFUnionSphereLOD::OptimizedBVH(primitives, 0.5);
}
/*!
\brief Polygonization function of the implicit primitives using marching cubes.
\param sdf implicit block functions
*/
MC::mcMesh PolygonizeSDF(const Box& box, SDFNode* node)
{
// Compute field function
const int n = 200;
MC::MC_FLOAT* field = new MC::MC_FLOAT[n * n * n];
Vector3 cellDiagonal = (box[1] - box[0]) / (n - 1);
{
#pragma omp parallel for num_threads(16) shared(field)
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
Vector3 p = Vector3(box[0][0] + i * cellDiagonal[0], box[0][1] + j * cellDiagonal[1], box[0][2] + k * cellDiagonal[2]);
field[(k * n + j) * n + i] = node->Signed(p);
}
}
}
}
// Polygonize
MC::mcMesh mesh;
MC::marching_cube(field, n, n, n, mesh);
return mesh;
}
| 27.925217 | 180 | 0.668929 | [
"mesh",
"vector",
"3d"
] |
ffe1b044134a68a22d7dd778be9d0a0616bbf1bd | 1,227 | cpp | C++ | test/aoj/0343.test.cpp | toyama1710/cpp_library | 867a6da52f51ed38ee295a451a1b102c9b000743 | [
"CC0-1.0"
] | 10 | 2019-08-11T11:03:47.000Z | 2022-02-08T07:01:31.000Z | test/aoj/0343.test.cpp | toyama1710/cpp_library | 867a6da52f51ed38ee295a451a1b102c9b000743 | [
"CC0-1.0"
] | null | null | null | test/aoj/0343.test.cpp | toyama1710/cpp_library | 867a6da52f51ed38ee295a451a1b102c9b000743 | [
"CC0-1.0"
] | 1 | 2020-03-02T06:40:06.000Z | 2020-03-02T06:40:06.000Z | #define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0343"
#include <iostream>
#include <vector>
#include "../../bbst/avl_set.hpp"
#define _overload(_1, _2, _3, _4, name, ...) name
#define _rep1(Itr, N) _rep3(Itr, 0, N, 1)
#define _rep2(Itr, a, b) _rep3(Itr, a, b, 1)
#define _rep3(Itr, a, b, step) for (i64 Itr = a; Itr < b; Itr += step)
#define repeat(...) _overload(__VA_ARGS__, _rep3, _rep2, _rep1)(__VA_ARGS__)
#define rep(...) repeat(__VA_ARGS__)
#define ALL(X) begin(X), end(X)
using namespace std;
using i64 = long long;
using u64 = unsigned long long;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
i64 n, c;
cin >> n >> c;
using P = pair<i64, i64>;
AVLSet<P> st;
rep(i, n) st.insert(P(0, i));
vector<i64> score(n);
i64 com, t, m, p;
rep(_, c) {
cin >> com;
if (com == 0) {
cin >> t >> p;
--t;
st.erase(P(-score[t], t));
score[t] += p;
st.insert(P(-score[t], t));
} else if (com == 1) {
cin >> m;
auto s = st.find_Kth(m - 1).value();
cout << s.second + 1 << ' ' << -s.first << '\n';
}
}
return 0;
} | 25.040816 | 80 | 0.520782 | [
"vector"
] |
ffebbc93cd6e6d1e141e78e203e76ca2ba397d50 | 480 | cpp | C++ | Dataset/Leetcode/test/94/240.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/94/240.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/94/240.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> XXX(TreeNode* root) {
stack<TreeNode*> s;
TreeNode * p = root;
vector<int> ret;
while(!s.empty()||p!=nullptr){
if(p!=nullptr) {
s.push(p);
p = p->left;
}
else{
p = s.top();
s.pop();
ret.push_back(p->val);
p = p->right;
}
}
return ret;
}
};
| 20 | 38 | 0.35 | [
"vector"
] |
ffede502093d274707427a9333f9912867e273ed | 15,034 | cpp | C++ | src/renderer/vulkan/Device.cpp | suijingfeng/bsp_vulkan | 8f96b164b30d6860e2a2861e1809bf693f0c8de0 | [
"MIT"
] | 2 | 2021-07-29T19:56:03.000Z | 2021-09-13T12:06:06.000Z | src/renderer/vulkan/Device.cpp | suijingfeng/bsp_vulkan | 8f96b164b30d6860e2a2861e1809bf693f0c8de0 | [
"MIT"
] | null | null | null | src/renderer/vulkan/Device.cpp | suijingfeng/bsp_vulkan | 8f96b164b30d6860e2a2861e1809bf693f0c8de0 | [
"MIT"
] | null | null | null | #include "Device.hpp"
#include "Validation.hpp"
#include "../../Utils.hpp"
#include <algorithm>
#include <cstring>
namespace vk
{
// helper struct to avoid passing tons of args to functions
struct SwapChainInfo
{
VkSurfaceCapabilitiesKHR surfaceCaps = {};
VkSurfaceFormatKHR *formats = nullptr;
uint32_t formatCount = 0;
VkPresentModeKHR *presentModes = nullptr;
uint32_t presentModesCount = 0;
~SwapChainInfo()
{
delete[] formats;
delete[] presentModes;
}
};
// requested device extensions
static std::vector<const char *> devExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
// internal helper functions for device and swapchain creation
static VkResult selectPhysicalDevice(const VkInstance &instance, const VkSurfaceKHR &surface, Device *device);
static VkResult createLogicalDevice(Device *device);
static VkPhysicalDevice getBestPhysicalDevice(const VkPhysicalDevice *devices, size_t count, const VkSurfaceKHR &surface, Device *device);
static bool deviceExtensionsSupported(const VkPhysicalDevice &device, const char **requested, size_t count);
static void getSwapChainInfo(const VkPhysicalDevice devices, const VkSurfaceKHR &surface, SwapChainInfo *scInfo);
static void getSwapSurfaceFormat(const SwapChainInfo &scInfo, VkSurfaceFormatKHR *surfaceFormat);
static void getSwapPresentMode(const SwapChainInfo &scInfo, VkPresentModeKHR *presentMode);
static void getSwapExtent(const SwapChainInfo &scInfo, VkExtent2D *swapExtent, const VkExtent2D ¤tSize);
Device createDevice(const VkInstance &instance, const VkSurfaceKHR &surface)
{
Device device;
VK_VERIFY(selectPhysicalDevice(instance, surface, &device));
VK_VERIFY(createLogicalDevice(&device));
vkGetDeviceQueue(device.logical, device.queueFamilyIndex, 0, &device.graphicsQueue);
vkGetDeviceQueue(device.logical, device.presentFamilyIndex, 0, &device.presentQueue);
return device;
}
VkResult createSwapChain(const Device &device, const VkSurfaceKHR &surface, SwapChain *swapChain, VkSwapchainKHR oldSwapchain)
{
SwapChainInfo scInfo = {};
VkSurfaceFormatKHR surfaceFormat = {};
VkPresentModeKHR presentMode = {};
VkExtent2D extent = {};
VkExtent2D currentSize = swapChain->extent;
getSwapChainInfo(device.physical, surface, &scInfo);
getSwapSurfaceFormat(scInfo, &surfaceFormat);
getSwapPresentMode(scInfo, &presentMode);
getSwapExtent(scInfo, &extent, currentSize);
// add 1 if going for triple buffering
uint32_t imageCount = scInfo.surfaceCaps.minImageCount;
VkSwapchainCreateInfoKHR scCreateInfo = {};
scCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
scCreateInfo.surface = surface;
scCreateInfo.minImageCount = imageCount;
scCreateInfo.imageFormat = surfaceFormat.format;
scCreateInfo.imageColorSpace = surfaceFormat.colorSpace;
scCreateInfo.imageExtent = extent;
scCreateInfo.imageArrayLayers = 1;
scCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
scCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
scCreateInfo.queueFamilyIndexCount = 0;
scCreateInfo.pQueueFamilyIndices = nullptr;
if (device.presentFamilyIndex != device.queueFamilyIndex)
{
uint32_t queueFamilyIndices[] = { (uint32_t)device.queueFamilyIndex, (uint32_t)device.presentFamilyIndex };
scCreateInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
scCreateInfo.queueFamilyIndexCount = 2;
scCreateInfo.pQueueFamilyIndices = queueFamilyIndices;
}
scCreateInfo.preTransform = scInfo.surfaceCaps.currentTransform;
scCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
scCreateInfo.presentMode = presentMode;
scCreateInfo.clipped = VK_TRUE;
scCreateInfo.oldSwapchain = oldSwapchain;
VK_VERIFY(vkCreateSwapchainKHR(device.logical, &scCreateInfo, nullptr, &swapChain->sc));
swapChain->format = surfaceFormat.format;
swapChain->extent = extent;
// retrieve swap chain images
VK_VERIFY(vkGetSwapchainImagesKHR(device.logical, swapChain->sc, &imageCount, nullptr));
LOG_MESSAGE_ASSERT(imageCount != 0, "No available images in the swap chain?");
swapChain->images.resize(imageCount);
VkResult result = vkGetSwapchainImagesKHR(device.logical, swapChain->sc, &imageCount, swapChain->images.data());
// release old swap chain if it was specified
if(oldSwapchain != VK_NULL_HANDLE)
vkDestroySwapchainKHR(device.logical, oldSwapchain, nullptr);
return result;
}
VkResult selectPhysicalDevice(const VkInstance &instance, const VkSurfaceKHR &surface, Device *device)
{
uint32_t physicalDeviceCount = 0;
VK_VERIFY(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr));
if (physicalDeviceCount == 0)
{
LOG_MESSAGE_ASSERT(false, "No Vulkan-capable devices found!");
return VK_RESULT_MAX_ENUM;
}
VkPhysicalDevice *physicalDevices = new VkPhysicalDevice[physicalDeviceCount];
VK_VERIFY(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices));
device->physical = getBestPhysicalDevice(physicalDevices, physicalDeviceCount, surface, device);
LOG_MESSAGE_ASSERT(device->physical != VK_NULL_HANDLE, "Could not find a suitable physical device!");
delete[] physicalDevices;
return VK_SUCCESS;
}
VkResult createLogicalDevice(Device *device)
{
LOG_MESSAGE_ASSERT(device->physical != VK_NULL_HANDLE, "Invalid physical device!");
float queuePriority = 1.f;
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = device->queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.fillModeNonSolid = VK_TRUE; // for wireframe rendering
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
deviceCreateInfo.ppEnabledExtensionNames = devExtensions.data();
deviceCreateInfo.enabledExtensionCount = devExtensions.size();
// a single queue can draw and present? Provide single create info, otherwise create two separate queues
if (device->queueFamilyIndex == device->presentFamilyIndex)
{
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
}
else
{
VkDeviceQueueCreateInfo queues[] = { queueCreateInfo, queueCreateInfo };
deviceCreateInfo.queueCreateInfoCount = 2;
deviceCreateInfo.pQueueCreateInfos = queues;
}
#ifdef VALIDATION_LAYERS_ON
deviceCreateInfo.enabledLayerCount = 1;
deviceCreateInfo.ppEnabledLayerNames = vk::validationLayers;
#else
deviceCreateInfo.enabledLayerCount = 0;
#endif
return vkCreateDevice(device->physical, &deviceCreateInfo, nullptr, &device->logical);
}
VkPhysicalDevice getBestPhysicalDevice(const VkPhysicalDevice *devices, size_t count, const VkSurfaceKHR &surface, Device *device)
{
VkPhysicalDeviceProperties deviceProperties;
VkPhysicalDeviceFeatures deviceFeatures;
uint32_t queueFamilyCount = 0;
for (size_t i = 0; i < count; ++i)
{
vkGetPhysicalDeviceProperties(devices[i], &deviceProperties);
vkGetPhysicalDeviceFeatures(devices[i], &deviceFeatures);
vkGetPhysicalDeviceQueueFamilyProperties(devices[i], &queueFamilyCount, nullptr);
// prefer discrete GPU but if it's the only one available then don't be picky
if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU || count == 1)
{
LOG_MESSAGE_ASSERT(queueFamilyCount != 0, "No queue families for the device!");
// check if requested device extensions are present
bool extSupported = deviceExtensionsSupported(devices[i], devExtensions.data(), devExtensions.size());
// no required extensions? try next device
if (!extSupported || !deviceFeatures.samplerAnisotropy || !deviceFeatures.fillModeNonSolid)
continue;
// if extensions are fine, query swap chain details and see if we can use this device
SwapChainInfo scInfo = {};
getSwapChainInfo(devices[i], surface, &scInfo);
if (scInfo.formatCount == 0 || scInfo.presentModesCount == 0)
continue;
VkQueueFamilyProperties *queueFamilies = new VkQueueFamilyProperties[queueFamilyCount];
vkGetPhysicalDeviceQueueFamilyProperties(devices[i], &queueFamilyCount, queueFamilies);
// secondary check - device is OK if there's at least on queue with VK_QUEUE_GRAPHICS_BIT set
for (size_t j = 0; j < queueFamilyCount; ++j)
{
// check if this queue family has support for presentation
VkBool32 presentSupported;
VK_VERIFY(vkGetPhysicalDeviceSurfaceSupportKHR(devices[i], j, surface, &presentSupported));
// good optimization would be to find a queue where presentIdx == queueIdx for less overhead
if (queueFamilies[j].queueCount > 0 && presentSupported)
{
device->presentFamilyIndex = j;
}
if (queueFamilies[j].queueCount > 0 && queueFamilies[j].queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
device->queueFamilyIndex = j;
}
// accept only device that has support for presentation and drawing
if (device->presentFamilyIndex >= 0 && device->queueFamilyIndex >= 0)
{
delete[] queueFamilies;
return devices[i];
}
}
delete[] queueFamilies;
}
}
return VK_NULL_HANDLE;
}
bool deviceExtensionsSupported(const VkPhysicalDevice &device, const char **requested, size_t count)
{
uint32_t extCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extCount, nullptr);
if (extCount > 0)
{
VkExtensionProperties *extensions = new VkExtensionProperties[extCount];
vkEnumerateDeviceExtensionProperties(device, nullptr, &extCount, extensions);
for (size_t i = 0; i < count; ++i)
{
bool available = false;
for (uint32_t j = 0; j < extCount; ++j)
{
available |= !strcmp(extensions[j].extensionName, requested[i]);
}
// all requested extensions must be available
if (!available)
return false;
}
}
return true;
}
void getSwapChainInfo(VkPhysicalDevice device, const VkSurfaceKHR &surface, SwapChainInfo *scInfo)
{
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &scInfo->surfaceCaps);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &scInfo->formatCount, nullptr);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &scInfo->presentModesCount, nullptr);
if (scInfo->formatCount > 0)
{
scInfo->formats = new VkSurfaceFormatKHR[scInfo->formatCount];
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &scInfo->formatCount, scInfo->formats);
}
if (scInfo->presentModesCount > 0)
{
scInfo->presentModes = new VkPresentModeKHR[scInfo->presentModesCount];
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &scInfo->presentModesCount, scInfo->presentModes);
}
}
void getSwapSurfaceFormat(const SwapChainInfo &scInfo, VkSurfaceFormatKHR *surfaceFormat)
{
for (size_t i = 0; i < scInfo.formatCount; ++i)
{
if (scInfo.formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR &&
scInfo.formats[i].format == VK_FORMAT_B8G8R8A8_UNORM)
{
surfaceFormat->colorSpace = scInfo.formats[i].colorSpace;
surfaceFormat->format = scInfo.formats[i].format;
return;
}
}
// no preferred format, so get the first one from list
surfaceFormat->colorSpace = scInfo.formats[0].colorSpace;
surfaceFormat->format = scInfo.formats[0].format;
}
void getSwapPresentMode(const SwapChainInfo &scInfo, VkPresentModeKHR *presentMode)
{
*presentMode = VK_PRESENT_MODE_FIFO_KHR;
for (uint32_t i = 0; i < scInfo.presentModesCount; ++i)
{
if (scInfo.presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR)
{
*presentMode = scInfo.presentModes[i];
break;
}
else if (scInfo.presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)
{
*presentMode = scInfo.presentModes[i];
break;
}
}
}
void getSwapExtent(const SwapChainInfo &scInfo, VkExtent2D *swapExtent, const VkExtent2D ¤tSize)
{
#undef min
#undef max
if (scInfo.surfaceCaps.currentExtent.width != std::numeric_limits<uint32_t>::max())
{
*swapExtent = scInfo.surfaceCaps.currentExtent;
return;
}
// special case when w/h are set to max uint32_t for some WMs - compare against current window size
swapExtent->width = std::max(scInfo.surfaceCaps.minImageExtent.width, std::min(scInfo.surfaceCaps.maxImageExtent.width, currentSize.width));
swapExtent->height = std::max(scInfo.surfaceCaps.minImageExtent.height, std::min(scInfo.surfaceCaps.maxImageExtent.height, currentSize.height));
LOG_MESSAGE("WM sets extent width and height to max uint32!");
}
}
| 44.877612 | 153 | 0.64547 | [
"vector"
] |
fff53a870e1ee7a4c21a8fd0e46593f2618a45ef | 6,932 | cpp | C++ | simulation_program/basins.cpp | lydiasteiner/epimem | 2df5f4807acf4e3044848e0b04cff357cbe77db7 | [
"CC0-1.0"
] | null | null | null | simulation_program/basins.cpp | lydiasteiner/epimem | 2df5f4807acf4e3044848e0b04cff357cbe77db7 | [
"CC0-1.0"
] | null | null | null | simulation_program/basins.cpp | lydiasteiner/epimem | 2df5f4807acf4e3044848e0b04cff357cbe77db7 | [
"CC0-1.0"
] | 1 | 2020-08-17T11:44:26.000Z | 2020-08-17T11:44:26.000Z | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <deque>
#include <time.h> /* time */
#include "model.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cstring>
#include <map>
#include <vector>
#include <cmath>
#include <random>
#include <utility>
#include <chrono>
int noncelldivisiondiffs(int* parent, int* child, int length){
int i, nonallowedtransitions = 0;
for(i = 0; i < length;i++)if(parent[i] == 0 && child[i] == 1)nonallowedtransitions++;
return nonallowedtransitions;
}
void int2nary(int num, int* bin, int length, int states){
int i;
for(i = 0; i < length; i++){
bin[i] = num % states;
num = (int)(num/states);
}
}
int nary2int(int* bin, int length, int states){
int i;
int num = 0;
for(i = 0; i < length; i++){
num += bin[i]*(int)pow(states,i);
}
return num;
}
void setState(int* target,int mask,int masklength,int* init,int length){
int* maskArray = (int*)malloc(sizeof(int)*masklength);
int2nary(mask,maskArray,masklength,2);
int c = 0;
int i;
for(i = 0; i < length; i++){
if(init[i] > 0){
if(maskArray[c] == 0)target[i] = 0;
else target[i] = init[i];
c++;
}else target[i] = init[i];
}
free(maskArray);
}
int main(int argc, char* argv[]){
srand (time(NULL));
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rng(seed); /*default uniform random number generator */
if(argc != 2){
std::cerr<<"./basins <outputprefix>"<<std::endl;
return EXIT_FAILURE;
}
Pottsmodel* model = (Pottsmodel*)malloc(sizeof(Pottsmodel));
initialize(model,10,2);
//int temp[2] = {(int)pow(2,0)+(int)pow(2,1)+(int)pow(2,2),(int)pow(2,9)+(int)pow(2,8)+(int)pow(2,7)};
unsigned int i,j,t;
int numberofpatterns = 2;
int totalmemories = 10;//(int)pow(model->states,model->length)/2;
int largest = (int)pow(model->states,model->length) - 1;
for(numberofpatterns = 1; numberofpatterns < totalmemories; numberofpatterns++){
std::string filename(argv[1]);
std::ostringstream fileno;
fileno<<filename<<"_"<<numberofpatterns<<".original";
std::ostringstream filencd;
filencd<<filename<<"_"<<numberofpatterns<<".celldivision";
std::ostringstream filebasin;
filebasin<<filename<<"_"<<numberofpatterns<<".basins";;
std::ostringstream filebasincd;
filebasincd<<filename<<"_"<<numberofpatterns<<".basinscd";
std::ofstream org;
org.open(fileno.str().c_str());
std::ofstream cd;
cd.open(filencd.str().c_str());
std::ofstream basins;
basins.open(filebasin.str().c_str());
std::ofstream basinscd;
basinscd.open(filebasincd.str().c_str());
/*reset*/
for(i = 0; i < model->length; i++){
for(j = 0; j < model->length; j++){
model->interactions[i][j] = 0.0;
}
}
int maxpattern = (int)pow(model->states,model->length)/2 - 1;
std::vector<int> patterns;
for(i = 0; i < numberofpatterns; i++){
int newp = rand() % maxpattern;
maxpattern--;
bool inserted = false;
for(j = 0; j < patterns.size(); j++){
if(newp > patterns[j])newp++;
else{
patterns.insert(patterns.begin()+j,newp);
inserted = true;
break;
}
}
if(!inserted)patterns.push_back(newp);
}
std::cout<<"number of patterns to remember:"<<patterns.size()<<std::endl;
for(t = 0; t < patterns.size(); t++){
int2nary(patterns[t],model->modelstring,model->length,model->states);
for(i = 0; i < model->length; i++){
//std::cout<<model->modelstring[i];
for(j = 0; j < model->length; j++){
if(i != j)
if(model->modelstring[i] == model->modelstring[j])model->interactions[i][j] += 1.0/(double)patterns.size();
else model->interactions[i][j] -= 1.0/(double)patterns.size();
}
}
//std::cout<<std::endl;
}
/****RANDOM INTERACTIONS****/
/*for(i = 0; i < model->length; i++){
for(j = 0; j < model->length; j++){
if(i != j)model->interactions[i][j] = 2.0*((double)rand()/(double)RAND_MAX) - 1.0;
}
}
*/
std::cout<<model->length<<std::endl;
for(i = 0; i < model->length; i++){
for(j = 0; j < model->length; j++){
std::cout<<model->interactions[i][j]<<"\t";
}
std::cout<<std::endl;
}
/* do monte carlo simulation to find the distribution of the states */
//TODO
//std::map<int,int> states;
int samples = 1000;
int upbou = 1000000;
int max = pow(model->states,model->length);
int b;
int tmep = patterns.size();
//std::cout<<"ORIGINAL"<<std::endl;
for(b = 0; b < tmep; b++)patterns.push_back((int)pow(model->states,model->length)-1-patterns[b]);
for(b = 0; b < patterns.size(); b++){
int unstable = 0;
int diff = 0;
int same = 0;
for(i = 0; i < samples; i++){
int2nary(patterns[b],model->modelstring,model->length,model->states);
int changes = mh(model,rng,upbou);
int curstate = nary2int(model->modelstring,model->length,model->states);
if(changes > 0){
unstable++;
}else{
//if(states.find(curstate) == states.end())states[curstate] = 1;
//else states[curstate]++;
if(curstate == patterns[b]){
same++;
}else{
diff++;
}
}
}
org<<patterns[b]<<"\t"<<same<<"\t"<<diff<<"\t"<<unstable<<std::endl;
}
/* basins of original model */
for(b = 0; b < (int)pow(model->states,model->length); b++){
for( i = 0; i < samples; i++){
int2nary(b,model->modelstring,model->length,model->states);
int changes = mh(model,rng,upbou);
int curstate = nary2int(model->modelstring,model->length,model->states);
if(changes == 0)basins<<b<<"\t"<<curstate<<std::endl;
}
}
int* init = (int*)malloc(sizeof(int)*model->length);
//std::cout<<"#CELLDIVISION"<<std::endl;
for(b = 0; b < patterns.size(); b++){
int backtoorigin = 0;
int converttodifferent = 0;
int unstable = 0;
int2nary(patterns[b],init,model->length,model->states);
int notzero = 0;
for(i = 0; i < model->length; i++)if(init[i] > 0)notzero++;
int celldivstates = pow(2,notzero);
for(i = 0; i < celldivstates; i++){
for(j = 0; j < samples; j++){
setState(model->modelstring,i,notzero,init,model->length);
int celldivstate = nary2int(model->modelstring,model->length,model->states);
int changes = mh(model,rng,upbou);
if(changes > 0){
unstable++;
}else{
int res = nary2int(model->modelstring,model->length,model->states);
basinscd<<patterns[b]<<"\t"<<celldivstate<<"\t"<<res<<std::endl;
if(patterns[b] == res)backtoorigin++;
else converttodifferent++;
}
}
}
cd<<patterns[b]<<"\t"<<backtoorigin<<"\t"<<converttodifferent<<"\t"<<unstable<<std::endl;
}
org.close();
cd.close();
basins.close();
basinscd.close();
}
del(model);
return EXIT_SUCCESS;
}
| 29.751073 | 112 | 0.597952 | [
"vector",
"model"
] |
fff90e505b16e6212e7039a95606817f9c7c85e4 | 2,623 | cpp | C++ | src/chrono/physics/ChLoadContainer.cpp | jcmadsen/chrono | d332a6941dc6046bfc5f2caceb2d5e43709b9334 | [
"BSD-3-Clause"
] | null | null | null | src/chrono/physics/ChLoadContainer.cpp | jcmadsen/chrono | d332a6941dc6046bfc5f2caceb2d5e43709b9334 | [
"BSD-3-Clause"
] | null | null | null | src/chrono/physics/ChLoadContainer.cpp | jcmadsen/chrono | d332a6941dc6046bfc5f2caceb2d5e43709b9334 | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 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: Alessandro Tasora, Radu Serban
// =============================================================================
#include "chrono/physics/ChLoadContainer.h"
namespace chrono {
// Register into the object factory, to enable run-time dynamic creation and persistence
CH_FACTORY_REGISTER(ChLoadContainer)
ChLoadContainer::ChLoadContainer(const ChLoadContainer& other) : ChPhysicsItem(other) {
loadlist = other.loadlist;
}
void ChLoadContainer::Add(std::shared_ptr<ChLoadBase> newload) {
//TODO Radu: I don't think find can be used on a container of shared pointers which does not support the == operator.
//TODO Radu: check if this is still true, now that we switched to std::shared_ptr
//assert(std::find<std::vector<std::shared_ptr<ChLoadBase>>::iterator>(loadlist.begin(), loadlist.end(), newload)
///== loadlist.end());
loadlist.push_back(newload);
}
void ChLoadContainer::Update(double mytime, bool update_assets) {
for (size_t i = 0; i < loadlist.size(); ++i) {
loadlist[i]->Update();
}
// Overloading of base class:
ChPhysicsItem::Update(mytime, update_assets);
}
void ChLoadContainer::IntLoadResidual_F(const unsigned int off, // offset in R residual
ChVectorDynamic<>& R, // result: the R residual, R += c*F
const double c // a scaling factor
) {
for (size_t i = 0; i < loadlist.size(); ++i) {
loadlist[i]->LoadIntLoadResidual_F(R, c);
}
}
void ChLoadContainer::InjectKRMmatrices(ChSystemDescriptor& mdescriptor) {
for (size_t i = 0; i < loadlist.size(); ++i) {
loadlist[i]->InjectKRMmatrices(mdescriptor);
}
}
void ChLoadContainer::KRMmatricesLoad(double Kfactor, double Rfactor, double Mfactor) {
for (size_t i = 0; i < loadlist.size(); ++i) {
loadlist[i]->KRMmatricesLoad(Kfactor, Rfactor, Mfactor);
}
}
void ChLoadContainer::ArchiveOUT(ChArchiveOut& marchive) {
//***TODO***
}
void ChLoadContainer::ArchiveIN(ChArchiveIn& marchive) {
//***TODO***
}
} // end namespace chrono
| 35.931507 | 121 | 0.599314 | [
"object",
"vector"
] |
fffbd3205af64748952b5db10e70bdb7c78d528d | 16,979 | hpp | C++ | c++/include/corelib/ncbi_safe_static.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/include/corelib/ncbi_safe_static.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/include/corelib/ncbi_safe_static.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | #ifndef NCBI_SAFE_STATIC__HPP
#define NCBI_SAFE_STATIC__HPP
/* $Id: ncbi_safe_static.hpp 337189 2011-09-09 13:04:25Z lavr $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksey Grichenko
*
* File Description:
* Static variables safety - create on demand, destroy on termination
*
* CSafeStaticPtr_Base:: -- base class for CSafePtr<> and CSafeRef<>
* CSafeStaticPtr<>:: -- create variable on demand, destroy on program
* termination (see NCBIOBJ for CSafeRef<> class)
* CSafeStaticRef<>:: -- create variable on demand, destroy on program
* termination (see NCBIOBJ for CSafeRef<> class)
* CSafeStaticGuard:: -- guarantee for CSafePtr<> and CSafeRef<>
* destruction and cleanup
*
*/
/// @file ncbi_safe_static.hpp
/// Static variables safety - create on demand, destroy on application
/// termination.
#include <corelib/ncbiobj.hpp>
#include <corelib/ncbimtx.hpp>
#include <corelib/ncbi_limits.h>
#include <set>
BEGIN_NCBI_SCOPE
/////////////////////////////////////////////////////////////////////////////
///
/// CSafeStaticLifeSpan::
///
/// Class for specifying safe static object life span.
///
class NCBI_XNCBI_EXPORT CSafeStaticLifeSpan
{
public:
/// Predefined life spans for the safe static objects
enum ELifeSpan {
eLifeSpan_Min = kMin_Int, ///< std static, not adjustable
eLifeSpan_Shortest = -20000,
eLifeSpan_Short = -10000,
eLifeSpan_Normal = 0,
eLifeSpan_Long = 10000,
eLifeSpan_Longest = 20000
};
/// Constructs a life span object from basic level and adjustment.
/// Generates warning (and assertion in debug mode) if the adjustment
/// argument is too big (<= -5000 or >= 5000). If span is eLifeSpan_Min
/// "adjust" is ignored.
CSafeStaticLifeSpan(ELifeSpan span, int adjust = 0);
/// Get life span value.
int GetLifeSpan(void) const { return m_LifeSpan; }
/// Get default life span (set to eLifeSpan_Min).
static CSafeStaticLifeSpan& GetDefault(void);
private:
int m_LifeSpan;
};
/////////////////////////////////////////////////////////////////////////////
///
/// CSafeStaticPtr_Base::
///
/// Base class for CSafeStaticPtr<> and CSafeStaticRef<> templates.
///
class NCBI_XNCBI_EXPORT CSafeStaticPtr_Base
{
public:
/// User cleanup function type
typedef void (*FUserCleanup)(void* ptr);
/// Life span
typedef CSafeStaticLifeSpan TLifeSpan;
~CSafeStaticPtr_Base(void);
protected:
/// Cleanup function type used by derived classes
typedef void (*FSelfCleanup)(void** ptr);
/// Constructor.
///
/// @param self_cleanup
/// Cleanup function to be executed on destruction,
/// provided by a derived class.
/// @param user_cleanup
/// User-provided cleanup function to be executed on destruction.
/// @param life_span
/// Life span allows to control destruction of objects. Objects with
/// the same life span are destroyed in the order reverse to their
/// creation order.
/// @sa CSafeStaticLifeSpan
CSafeStaticPtr_Base(FSelfCleanup self_cleanup,
FUserCleanup user_cleanup = 0,
TLifeSpan life_span = TLifeSpan::GetDefault())
: m_SelfCleanup(self_cleanup),
m_UserCleanup(user_cleanup),
m_LifeSpan(life_span.GetLifeSpan()),
m_CreationOrder(x_GetCreationOrder())
{}
/// Pointer to the data
void* m_Ptr;
/// Prepare to the object initialization: check current thread, lock
/// the mutex and store its state to "mutex_locked", return "true"
/// if the object must be created or "false" if already created.
bool Init_Lock(bool* mutex_locked);
/// Finalize object initialization: release the mutex if "mutex_locked".
void Init_Unlock(bool mutex_locked);
private:
friend class CSafeStatic_Less;
FSelfCleanup m_SelfCleanup; // Derived class' cleanup function
FUserCleanup m_UserCleanup; // User-provided cleanup function
int m_LifeSpan; // Life span of the object
int m_CreationOrder; // Creation order of the object
static int x_GetCreationOrder(void);
// Return true if the object should behave like regular static
// (no delayed destruction).
bool x_IsStdStatic(void) const
{
return m_LifeSpan == int(CSafeStaticLifeSpan::eLifeSpan_Min);
}
// To be called by CSafeStaticGuard on the program termination
friend class CSafeStaticGuard;
void x_Cleanup(void)
{
if ( m_UserCleanup )
m_UserCleanup(m_Ptr);
if ( m_SelfCleanup )
m_SelfCleanup(&m_Ptr);
}
};
/// Comparison for safe static ptrs. Defines order of objects' destruction:
/// short living objects go first; if life span of several objects is the same,
/// the order of destruction is reverse to the order of their creation.
class CSafeStatic_Less
{
public:
typedef CSafeStaticPtr_Base* TPtr;
bool operator()(const TPtr& ptr1, const TPtr& ptr2) const
{
if (ptr1->m_LifeSpan == ptr2->m_LifeSpan) {
return ptr1->m_CreationOrder > ptr2->m_CreationOrder;
}
return ptr1->m_LifeSpan < ptr2->m_LifeSpan;
}
};
/////////////////////////////////////////////////////////////////////////////
///
/// CSafeStaticPtr<>::
///
/// For simple on-demand variables.
/// Create the variable of type "T" on demand,
/// destroy it on the program termination.
/// Should be used only as static object. Otherwise
/// the correct initialization is not guaranteed.
template <class T>
class CSafeStaticPtr : public CSafeStaticPtr_Base
{
public:
typedef CSafeStaticLifeSpan TLifeSpan;
/// Constructor.
///
/// @param user_cleanup
/// User-provided cleanup function to be executed on destruction.
/// @param life_span
/// Life span allows to control destruction of objects.
/// @sa CSafeStaticPtr_Base
CSafeStaticPtr(FUserCleanup user_cleanup = 0,
TLifeSpan life_span = TLifeSpan::GetDefault())
: CSafeStaticPtr_Base(x_SelfCleanup, user_cleanup, life_span)
{}
/// Create the variable if not created yet, return the reference.
T& Get(void)
{
if ( !m_Ptr ) {
x_Init();
}
return *static_cast<T*> (m_Ptr);
}
/// Get the existing object or create a new one using the provided
/// FUserCreate object.
template <class FUserCreate>
T& Get(FUserCreate user_create)
{
if ( !m_Ptr ) {
x_Init(user_create);
}
return *static_cast<T*> (m_Ptr);
}
T* operator -> (void) { return &Get(); }
T& operator * (void) { return Get(); }
/// Initialize with an existing object. The object MUST be
/// allocated with "new T" -- it will be destroyed with
/// "delete object" in the end. Set() works only for
/// not yet initialized safe-static variables.
void Set(T* object);
private:
// Initialize the object
void x_Init(void);
template <class FUserCreate>
void x_Init(FUserCreate user_create);
// "virtual" cleanup function
static void x_SelfCleanup(void** ptr)
{
T* tmp = static_cast<T*> (*ptr);
*ptr = 0;
delete tmp;
}
};
/////////////////////////////////////////////////////////////////////////////
///
/// CSafeStaticRef<>::
///
/// For on-demand CObject-derived object.
/// Create the variable of type "T" using CRef<>
/// (to avoid premature destruction).
/// Should be used only as static object. Otherwise
/// the correct initialization is not guaranteed.
template <class T>
class CSafeStaticRef : public CSafeStaticPtr_Base
{
public:
typedef CSafeStaticLifeSpan TLifeSpan;
/// Constructor.
///
/// @param user_cleanup
/// User-provided cleanup function to be executed on destruction.
/// @param life_span
/// Life span allows to control destruction of objects.
/// @sa CSafeStaticPtr_Base
CSafeStaticRef(FUserCleanup user_cleanup = 0,
TLifeSpan life_span = TLifeSpan::GetDefault())
: CSafeStaticPtr_Base(x_SelfCleanup, user_cleanup, life_span)
{}
/// Create the variable if not created yet, return the reference.
T& Get(void)
{
if ( !m_Ptr ) {
x_Init();
}
return *static_cast<T*>(m_Ptr);
}
/// Get the existing object or create a new one using the provided
/// FUserCreate object.
template <class FUserCreate>
T& Get(FUserCreate user_create)
{
if ( !m_Ptr ) {
x_Init(user_create);
}
return *static_cast<T*>(m_Ptr);
}
T* operator -> (void) { return &Get(); }
T& operator * (void) { return Get(); }
/// Initialize with an existing object. The object MUST be
/// allocated with "new T" to avoid premature destruction.
/// Set() works only for un-initialized safe-static variables.
void Set(T* object);
private:
// Initialize the object and the reference
void x_Init(void);
template <class FUserCreate>
void x_Init(FUserCreate user_create);
// "virtual" cleanup function
static void x_SelfCleanup(void** ptr)
{
T* tmp = static_cast<T*>(*ptr);
if ( tmp ) {
tmp->RemoveReference();
*ptr = 0;
}
}
};
/////////////////////////////////////////////////////////////////////////////
///
/// CSafeStaticGuard::
///
/// Register all on-demand variables,
/// destroy them on the program termination.
class NCBI_XNCBI_EXPORT CSafeStaticGuard
{
public:
/// Check if already initialized. If not - create the stack,
/// otherwise just increment the reference count.
CSafeStaticGuard(void);
/// Check reference count, and if it is zero, then destroy
/// all registered variables.
~CSafeStaticGuard(void);
/// Add new on-demand variable to the cleanup stack.
static void Register(CSafeStaticPtr_Base* ptr)
{
if ( ptr->x_IsStdStatic() ) {
// Do not add the object to the stack
return;
}
if ( !sm_Stack ) {
x_Get();
}
sm_Stack->insert(ptr);
}
private:
// Initialize the guard, return pointer to it.
static CSafeStaticGuard* x_Get(void);
// Stack to keep registered variables.
typedef multiset<CSafeStaticPtr_Base*, CSafeStatic_Less> TStack;
static TStack* sm_Stack;
// Reference counter. The stack is destroyed when
// the last reference is removed.
static int sm_RefCount;
};
/////////////////////////////////////////////////////////////////////////////
///
/// This static variable must be present in all modules using
/// on-demand static variables. The guard must be created first
/// regardless of the modules initialization order.
static CSafeStaticGuard s_CleanupGuard;
/////////////////////////////////////////////////////////////////////////////
//
// Large inline methods
template <class T>
inline
void CSafeStaticPtr<T>::Set(T* object)
{
bool mutex_locked = false;
if ( Init_Lock(&mutex_locked) ) {
// Set the new object and register for cleanup
try {
m_Ptr = object;
CSafeStaticGuard::Register(this);
}
catch (CException& e) {
Init_Unlock(mutex_locked);
NCBI_RETHROW_SAME(e, "CSafeStaticPtr::Set: Register() failed");
}
catch (...) {
Init_Unlock(mutex_locked);
NCBI_THROW(CCoreException,eCore,
"CSafeStaticPtr::Set: Register() failed");
}
}
Init_Unlock(mutex_locked);
}
template <class T>
inline
void CSafeStaticPtr<T>::x_Init(void)
{
bool mutex_locked = false;
if ( Init_Lock(&mutex_locked) ) {
// Create the object and register for cleanup
T* ptr = 0;
try {
ptr = new T;
CSafeStaticGuard::Register(this);
m_Ptr = ptr;
}
catch (CException& e) {
delete ptr;
Init_Unlock(mutex_locked);
NCBI_RETHROW_SAME(e, "CSafeStaticPtr::Init: Register() failed");
}
catch (...) {
delete ptr;
Init_Unlock(mutex_locked);
NCBI_THROW(CCoreException,eCore,
"CSafeStaticPtr::Init: Register() failed");
}
}
Init_Unlock(mutex_locked);
}
template <class T>
template <class FUserCreate>
inline
void CSafeStaticPtr<T>::x_Init(FUserCreate user_create)
{
bool mutex_locked = false;
if ( Init_Lock(&mutex_locked) ) {
// Create the object and register for cleanup
try {
T* ptr = user_create();
m_Ptr = ptr;
if ( m_Ptr ) {
CSafeStaticGuard::Register(this);
}
}
catch (CException& e) {
Init_Unlock(mutex_locked);
NCBI_RETHROW_SAME(e, "CSafeStaticPtr::Init: Register() failed");
}
catch (...) {
Init_Unlock(mutex_locked);
NCBI_THROW(CCoreException,eCore,
"CSafeStaticPtr::Init: Register() failed");
}
}
Init_Unlock(mutex_locked);
}
template <class T>
inline
void CSafeStaticRef<T>::Set(T* object)
{
bool mutex_locked = false;
if ( Init_Lock(&mutex_locked) ) {
// Set the new object and register for cleanup
try {
if ( object ) {
object->AddReference();
m_Ptr = object;
CSafeStaticGuard::Register(this);
}
}
catch (CException& e) {
Init_Unlock(mutex_locked);
NCBI_RETHROW_SAME(e, "CSafeStaticRef::Set: Register() failed");
}
catch (...) {
Init_Unlock(mutex_locked);
NCBI_THROW(CCoreException,eCore,
"CSafeStaticRef::Set: Register() failed");
}
}
Init_Unlock(mutex_locked);
}
template <class T>
inline
void CSafeStaticRef<T>::x_Init(void)
{
bool mutex_locked = false;
if ( Init_Lock(&mutex_locked) ) {
// Create the object and register for cleanup
try {
T* ptr = new T;
ptr->AddReference();
m_Ptr = ptr;
CSafeStaticGuard::Register(this);
}
catch (CException& e) {
Init_Unlock(mutex_locked);
NCBI_RETHROW_SAME(e, "CSafeStaticRef::Init: Register() failed");
}
catch (...) {
Init_Unlock(mutex_locked);
NCBI_THROW(CCoreException,eCore,
"CSafeStaticRef::Init: Register() failed");
}
}
Init_Unlock(mutex_locked);
}
template <class T>
template <class FUserCreate>
inline
void CSafeStaticRef<T>::x_Init(FUserCreate user_create)
{
bool mutex_locked = false;
if ( Init_Lock(&mutex_locked) ) {
// Create the object and register for cleanup
try {
CRef<T> ref(user_create());
if ( ref ) {
ref->AddReference();
m_Ptr = ref.Release();
CSafeStaticGuard::Register(this);
}
}
catch (CException& e) {
Init_Unlock(mutex_locked);
NCBI_RETHROW_SAME(e, "CSafeStaticRef::Init: Register() failed");
}
catch (...) {
Init_Unlock(mutex_locked);
NCBI_THROW(CCoreException,eCore,
"CSafeStaticRef::Init: Register() failed");
}
}
Init_Unlock(mutex_locked);
}
END_NCBI_SCOPE
#endif /* NCBI_SAFE_STATIC__HPP */
| 29.683566 | 79 | 0.593675 | [
"object"
] |
fffd9fab5da4532f8d436e65a20ca00decf1abac | 7,966 | cpp | C++ | demo/waveplot/flatui.cpp | HangYongmao/quc | ce33d0e0bd36ec5b777ca312d0c88f27169bace1 | [
"MIT"
] | 19 | 2019-09-05T07:11:16.000Z | 2021-12-17T09:30:50.000Z | demo/waveplot/flatui.cpp | zhoujuan-ht17/quc | ce33d0e0bd36ec5b777ca312d0c88f27169bace1 | [
"MIT"
] | null | null | null | demo/waveplot/flatui.cpp | zhoujuan-ht17/quc | ce33d0e0bd36ec5b777ca312d0c88f27169bace1 | [
"MIT"
] | 22 | 2019-08-13T06:50:31.000Z | 2022-03-22T12:52:22.000Z | #include "flatui.h"
#include "qpushbutton.h"
#include "qlineedit.h"
#include "qprogressbar.h"
#include "qslider.h"
#include "qradiobutton.h"
#include "qcheckbox.h"
#include "qscrollbar.h"
FlatUI *FlatUI::self = 0;
FlatUI::FlatUI(QObject *parent) : QObject(parent)
{
}
void FlatUI::setPushButtonQss(QPushButton *btn,
QString normalColor, QString normalTextColor,
QString hoverColor, QString hoverTextColor,
QString pressedColor, QString pressedTextColor)
{
QStringList qss;
qss.append(QString("QPushButton{border-style:none;padding:10px;border-radius:5px;color:%1;background:%2;}").arg(normalTextColor).arg(normalColor));
qss.append(QString("QPushButton:hover{color:%1;background:%2;}").arg(hoverTextColor).arg(hoverColor));
qss.append(QString("QPushButton:pressed{color:%1;background:%2;}").arg(pressedTextColor).arg(pressedColor));
btn->setStyleSheet(qss.join(""));
}
void FlatUI::setLineEditQss(QLineEdit *txt, QString normalColor, QString focusColor)
{
QStringList qss;
qss.append(QString("QLineEdit{border-style:none;padding:3px;border-radius:5px;border:2px solid %1;}").arg(normalColor));
qss.append(QString("QLineEdit:focus{border:2px solid %1;}").arg(focusColor));
txt->setStyleSheet(qss.join(""));
}
void FlatUI::setProgressBarQss(QProgressBar *bar, QString normalColor, QString chunkColor)
{
int barHeight = 8;
int barRadius = 5;
QStringList qss;
qss.append(QString("QProgressBar{font:9pt;max-height:%2px;background:%1;border-radius:%3px;text-align:center;border:1px solid %1;}")
.arg(normalColor).arg(barHeight).arg(barRadius));
qss.append(QString("QProgressBar:chunk{border-radius:%2px;background-color:%1;}")
.arg(chunkColor).arg(barRadius));
bar->setStyleSheet(qss.join(""));
}
void FlatUI::setSliderQss(QSlider *slider, QString normalColor, QString grooveColor, QString handleColor)
{
int sliderHeight = 8;
int sliderRadius = sliderHeight / 2;
int handleWidth = (sliderHeight * 3) / 2 + (sliderHeight / 5);
int handleRadius = handleWidth / 2;
int handleOffset = handleRadius / 2;
QStringList qss;
qss.append(QString("QSlider::groove:horizontal{background:%1;height:%2px;border-radius:%3px;}")
.arg(normalColor).arg(sliderHeight).arg(sliderRadius));
qss.append(QString("QSlider::add-page:horizontal{background:%1;height:%2px;border-radius:%3px;}")
.arg(normalColor).arg(sliderHeight).arg(sliderRadius));
qss.append(QString("QSlider::sub-page:horizontal{background:%1;height:%2px;border-radius:%3px;}")
.arg(grooveColor).arg(sliderHeight).arg(sliderRadius));
qss.append(QString("QSlider::handle:horizontal{width:%2px;margin-top:-%3px;margin-bottom:-%3px;border-radius:%4px;"
"background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.6 #FFFFFF,stop:0.8 %1);}")
.arg(handleColor).arg(handleWidth).arg(handleOffset).arg(handleRadius));
//偏移一个像素
handleWidth = handleWidth + 1;
qss.append(QString("QSlider::groove:vertical{width:%2px;border-radius:%3px;background:%1;}")
.arg(normalColor).arg(sliderHeight).arg(sliderRadius));
qss.append(QString("QSlider::add-page:vertical{width:%2px;border-radius:%3px;background:%1;}")
.arg(grooveColor).arg(sliderHeight).arg(sliderRadius));
qss.append(QString("QSlider::sub-page:vertical{width:%2px;border-radius:%3px;background:%1;}")
.arg(normalColor).arg(sliderHeight).arg(sliderRadius));
qss.append(QString("QSlider::handle:vertical{height:%2px;margin-left:-%3px;margin-right:-%3px;border-radius:%4px;"
"background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.6 #FFFFFF,stop:0.8 %1);}")
.arg(handleColor).arg(handleWidth).arg(handleOffset).arg(handleRadius));
slider->setStyleSheet(qss.join(""));
}
void FlatUI::setRadioButtonQss(QRadioButton *rbtn, QString normalColor, QString checkColor)
{
int indicatorRadius = 8;
int indicatorWidth = indicatorRadius * 2;
QStringList qss;
qss.append(QString("QRadioButton::indicator{border-radius:%1px;width:%2px;height:%2px;}")
.arg(indicatorRadius).arg(indicatorWidth));
qss.append(QString("QRadioButton::indicator::unchecked{background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,"
"stop:0.6 #FFFFFF,stop:0.7 %1);}").arg(normalColor));
qss.append(QString("QRadioButton::indicator::checked{background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,"
"stop:0 %1,stop:0.3 %1,stop:0.4 #FFFFFF,stop:0.6 #FFFFFF,stop:0.7 %1);}").arg(checkColor));
rbtn->setStyleSheet(qss.join(""));
}
void FlatUI::setCheckBoxQss(QCheckBox *ck, QString normalColor, QString checkColor)
{
int indicatorRadius = 3;
int indicatorWidth = indicatorRadius * 6;
QStringList qss;
qss.append(QString("QCheckBox::indicator{border-radius:%1px;width:%2px;height:%2px;}")
.arg(indicatorRadius).arg(indicatorWidth));
qss.append(QString("QCheckBox::indicator::unchecked{background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,"
"stop:0.6 #FFFFFF,stop:0.7 %1);}").arg(normalColor));
qss.append(QString("QCheckBox::indicator::checked{background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,"
"stop:0 %1,stop:0.3 %1,stop:0.4 #FFFFFF,stop:0.6 #FFFFFF,stop:0.7 %1);}").arg(checkColor));
ck->setStyleSheet(qss.join(""));
}
void FlatUI::setScrollBarQss(QScrollBar *scroll, QString bgColor, QString handleNormalColor, QString handleHoverColor, QString handlePressedColor)
{
//圆角角度
int radius = 6;
//指示器最小长度
int min = 120;
//滚动条最大长度
int max = 12;
//滚动条离背景间隔
int padding = 0;
QStringList qss;
//handle:指示器,滚动条拉动部分 add-page:滚动条拉动时增加的部分 sub-page:滚动条拉动时减少的部分 add-line:递增按钮 sub-line:递减按钮
//横向滚动条部分
qss.append(QString("QScrollBar:horizontal{background:%1;padding:%2px;border-radius:%3px;max-height:%4px;}")
.arg(bgColor).arg(padding).arg(radius).arg(max));
qss.append(QString("QScrollBar::handle:horizontal{background:%1;min-width:%2px;border-radius:%3px;}")
.arg(handleNormalColor).arg(min).arg(radius));
qss.append(QString("QScrollBar::handle:horizontal:hover{background:%1;}")
.arg(handleHoverColor));
qss.append(QString("QScrollBar::handle:horizontal:pressed{background:%1;}")
.arg(handlePressedColor));
qss.append(QString("QScrollBar::add-page:horizontal{background:none;}"));
qss.append(QString("QScrollBar::sub-page:horizontal{background:none;}"));
qss.append(QString("QScrollBar::add-line:horizontal{background:none;}"));
qss.append(QString("QScrollBar::sub-line:horizontal{background:none;}"));
//纵向滚动条部分
qss.append(QString("QScrollBar:vertical{background:%1;padding:%2px;border-radius:%3px;max-width:%4px;}")
.arg(bgColor).arg(padding).arg(radius).arg(max));
qss.append(QString("QScrollBar::handle:vertical{background:%1;min-height:%2px;border-radius:%3px;}")
.arg(handleNormalColor).arg(min).arg(radius));
qss.append(QString("QScrollBar::handle:vertical:hover{background:%1;}")
.arg(handleHoverColor));
qss.append(QString("QScrollBar::handle:vertical:pressed{background:%1;}")
.arg(handlePressedColor));
qss.append(QString("QScrollBar::add-page:vertical{background:none;}"));
qss.append(QString("QScrollBar::sub-page:vertical{background:none;}"));
qss.append(QString("QScrollBar::add-line:vertical{background:none;}"));
qss.append(QString("QScrollBar::sub-line:vertical{background:none;}"));
scroll->setStyleSheet(qss.join(""));
}
| 49.7875 | 151 | 0.679011 | [
"solid"
] |
fffe324359b1e301337fd61027798c5a23060590 | 8,521 | cpp | C++ | cdb/src/v20170320/model/AuditRule.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cdb/src/v20170320/model/AuditRule.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cdb/src/v20170320/model/AuditRule.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdb/v20170320/model/AuditRule.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
AuditRule::AuditRule() :
m_ruleIdHasBeenSet(false),
m_createTimeHasBeenSet(false),
m_modifyTimeHasBeenSet(false),
m_ruleNameHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_ruleFiltersHasBeenSet(false),
m_auditAllHasBeenSet(false)
{
}
CoreInternalOutcome AuditRule::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("RuleId") && !value["RuleId"].IsNull())
{
if (!value["RuleId"].IsString())
{
return CoreInternalOutcome(Error("response `AuditRule.RuleId` IsString=false incorrectly").SetRequestId(requestId));
}
m_ruleId = string(value["RuleId"].GetString());
m_ruleIdHasBeenSet = true;
}
if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull())
{
if (!value["CreateTime"].IsString())
{
return CoreInternalOutcome(Error("response `AuditRule.CreateTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_createTime = string(value["CreateTime"].GetString());
m_createTimeHasBeenSet = true;
}
if (value.HasMember("ModifyTime") && !value["ModifyTime"].IsNull())
{
if (!value["ModifyTime"].IsString())
{
return CoreInternalOutcome(Error("response `AuditRule.ModifyTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_modifyTime = string(value["ModifyTime"].GetString());
m_modifyTimeHasBeenSet = true;
}
if (value.HasMember("RuleName") && !value["RuleName"].IsNull())
{
if (!value["RuleName"].IsString())
{
return CoreInternalOutcome(Error("response `AuditRule.RuleName` IsString=false incorrectly").SetRequestId(requestId));
}
m_ruleName = string(value["RuleName"].GetString());
m_ruleNameHasBeenSet = true;
}
if (value.HasMember("Description") && !value["Description"].IsNull())
{
if (!value["Description"].IsString())
{
return CoreInternalOutcome(Error("response `AuditRule.Description` IsString=false incorrectly").SetRequestId(requestId));
}
m_description = string(value["Description"].GetString());
m_descriptionHasBeenSet = true;
}
if (value.HasMember("RuleFilters") && !value["RuleFilters"].IsNull())
{
if (!value["RuleFilters"].IsArray())
return CoreInternalOutcome(Error("response `AuditRule.RuleFilters` is not array type"));
const rapidjson::Value &tmpValue = value["RuleFilters"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
AuditFilter item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_ruleFilters.push_back(item);
}
m_ruleFiltersHasBeenSet = true;
}
if (value.HasMember("AuditAll") && !value["AuditAll"].IsNull())
{
if (!value["AuditAll"].IsBool())
{
return CoreInternalOutcome(Error("response `AuditRule.AuditAll` IsBool=false incorrectly").SetRequestId(requestId));
}
m_auditAll = value["AuditAll"].GetBool();
m_auditAllHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AuditRule::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_ruleIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_ruleId.c_str(), allocator).Move(), allocator);
}
if (m_createTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreateTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator);
}
if (m_modifyTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ModifyTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_modifyTime.c_str(), allocator).Move(), allocator);
}
if (m_ruleNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_ruleName.c_str(), allocator).Move(), allocator);
}
if (m_descriptionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Description";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_description.c_str(), allocator).Move(), allocator);
}
if (m_ruleFiltersHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleFilters";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_ruleFilters.begin(); itr != m_ruleFilters.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_auditAllHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AuditAll";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_auditAll, allocator);
}
}
string AuditRule::GetRuleId() const
{
return m_ruleId;
}
void AuditRule::SetRuleId(const string& _ruleId)
{
m_ruleId = _ruleId;
m_ruleIdHasBeenSet = true;
}
bool AuditRule::RuleIdHasBeenSet() const
{
return m_ruleIdHasBeenSet;
}
string AuditRule::GetCreateTime() const
{
return m_createTime;
}
void AuditRule::SetCreateTime(const string& _createTime)
{
m_createTime = _createTime;
m_createTimeHasBeenSet = true;
}
bool AuditRule::CreateTimeHasBeenSet() const
{
return m_createTimeHasBeenSet;
}
string AuditRule::GetModifyTime() const
{
return m_modifyTime;
}
void AuditRule::SetModifyTime(const string& _modifyTime)
{
m_modifyTime = _modifyTime;
m_modifyTimeHasBeenSet = true;
}
bool AuditRule::ModifyTimeHasBeenSet() const
{
return m_modifyTimeHasBeenSet;
}
string AuditRule::GetRuleName() const
{
return m_ruleName;
}
void AuditRule::SetRuleName(const string& _ruleName)
{
m_ruleName = _ruleName;
m_ruleNameHasBeenSet = true;
}
bool AuditRule::RuleNameHasBeenSet() const
{
return m_ruleNameHasBeenSet;
}
string AuditRule::GetDescription() const
{
return m_description;
}
void AuditRule::SetDescription(const string& _description)
{
m_description = _description;
m_descriptionHasBeenSet = true;
}
bool AuditRule::DescriptionHasBeenSet() const
{
return m_descriptionHasBeenSet;
}
vector<AuditFilter> AuditRule::GetRuleFilters() const
{
return m_ruleFilters;
}
void AuditRule::SetRuleFilters(const vector<AuditFilter>& _ruleFilters)
{
m_ruleFilters = _ruleFilters;
m_ruleFiltersHasBeenSet = true;
}
bool AuditRule::RuleFiltersHasBeenSet() const
{
return m_ruleFiltersHasBeenSet;
}
bool AuditRule::GetAuditAll() const
{
return m_auditAll;
}
void AuditRule::SetAuditAll(const bool& _auditAll)
{
m_auditAll = _auditAll;
m_auditAllHasBeenSet = true;
}
bool AuditRule::AuditAllHasBeenSet() const
{
return m_auditAllHasBeenSet;
}
| 28.029605 | 133 | 0.667058 | [
"vector",
"model"
] |
080a30344bd7dd691079c7e9e9df1ee8a7ff3a20 | 123,465 | cpp | C++ | ds/security/services/ca/initlib/initlib.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/services/ca/initlib/initlib.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/services/ca/initlib/initlib.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1995 - 1999
//
// File: initlib.cpp
//
// Contents: Install cert server
//
//--------------------------------------------------------------------------
#include <pch.cpp>
#pragma hdrstop
// C Run-Time Includes
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <winldap.h>
#include <ntldap.h>
// Windows System Includes
#include <winsvc.h>
#include <rpc.h>
#include <tchar.h>
#include <lmaccess.h>
#include <lmwksta.h>
#include <csdisp.h>
#include <wincrypt.h>
#include <objbase.h>
#include <initguid.h>
#include <userenv.h>
#include <cainfop.h>
#define SECURITY_WIN32
#include <security.h>
#include <lmerr.h>
// Application Includes
#include "setupids.h"
#include "certmsg.h"
#include "certca.h"
#include "certhier.h"
#include "tfc.h"
#include "cscsp.h"
#include "csldap.h"
#include "certacl.h"
#define __dwFILE__ __dwFILE_INITLIB_INITLIB_CPP__
WCHAR const g_szSlash[] = L"\\";
DWORD g_dwNameEncodeFlags = CERT_RDN_ENABLE_UTF8_UNICODE_FLAG;
#define MAX_COMPUTER_DNS_NAME 256
using namespace CertSrv;
//+=====================================================================
// DS DNs:
//
// DomainDN Example (no longer used for Cert server DS objects):
// DC=pksdom2,DC=nttest,DC=microsoft,DC=com
//
// ConfigDN Example:
// CN=Configuration,DC=pksdom2,DC=nttest,DC=microsoft,DC=com
//
// Cert server DS objects reside in Public Key Services container under
// the Configuraton container:
// CN=Public Key Services,CN=Services,<ConfigDN>
//
//
// In the Public Key Services container:
//
// Root Trust container:
// Each Root CA creates a Root Trust object in this container to store trusted
// Root CA certificates downloaded by all DS clients.
// Renewed CAs and CAs on multiple machines using the same CA name may use the
// same Root Trust object, because certs are always added -- they are never
// removed.
//
// CN=Certification Authorities
// CN=CA foo
// CN=CA bar
// ...
//
//
// Authority Information Access container:
// Each CA creates an AIA object in this container to store CA certs for chain
// building. Renewed CAs and CAs on multiple machines using the same CA name
// may use the same AIA object, because certs are always added -- they are
// never removed.
//
// CN=AIA
// CN=CA foo
// CN=CA bar
// ...
//
//
// CRL Distribution Point containers:
// Each CA creates a CDP object in this container for each unique CA key to
// store CRLs for revocation checking. Only one base CRL and zero or one
// delta CRL are stored in each CDP object, due to potential size constraints,
// and because the attribute is single valued. When a CA is renewed and a new
// CA key is generated during the renewal, a new CDP object is created with
// the CA's key index (in parentheses) appended to the CN. A nested container
// is created for each machine with the CN set to the short machine name
// (first component of the machine's full DNS name).
//
// CN=CDP
// CN=<CA foo's MachineName>
// CN=CA foo
// CN=CA foo(1)
// CN=CA foo(3)
// CN=<CA bar's MachineName>
// CN=CA bar
// CN=CA bar(1)
//
//
// Enrollment Services container:
// Each CA creates an Enrollment Services object in this container. A flags
// attribute indicates whether the CA supports autoenrollment (an Enterprise
// CA) or not (Standalone CA). The Enrollment Services object publishes the
// existence of the CA to all DS clients. Enrollment Services objects are
// created and managed by the certca.h CA APIs.
//
// CN=Enrollment Services
// CN=CA foo
// CN=CA bar
// ...
//
// Enterprise Trust object:
// A single Enterprise Trust object contains certificates for all
// autoenrollment-enabled CAs (root and subordinate Entrprise CAs).
//
// CN=NTAuthCertificates
//
//======================================================================
WCHAR const s_wszRootCAs[] =
L","
L"CN=Certification Authorities,"
L"CN=Public Key Services,"
L"CN=Services,";
WCHAR const s_wszEnterpriseCAs[] =
L"CN=NTAuthCertificates,"
L"CN=Public Key Services,"
L"CN=Services,";
//+-------------------------------------------------------------------------
// Write an encoded DER blob to a file
//--------------------------------------------------------------------------
BOOL
csiWriteDERToFile(
IN WCHAR const *pwszFileName,
IN BYTE const *pbDER,
IN DWORD cbDER,
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd)
{
BOOL fResult = FALSE;
HRESULT hr;
HANDLE hLocalFile;
DWORD dwBytesWritten;
hr = S_OK;
// Write the Encoded Blob to the file
hLocalFile = CreateFile(
pwszFileName,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
0);
if (INVALID_HANDLE_VALUE == hLocalFile)
{
hr = myHLastError();
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_CREATEFILE,
hr,
pwszFileName);
_JumpError(hr, error, "CreateFile");
}
if (!WriteFile(hLocalFile, pbDER, cbDER, &dwBytesWritten, NULL))
{
hr = myHLastError();
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_WRITEFILE,
hr,
pwszFileName);
_JumpError(hr, error, "WriteFile");
}
fResult = TRUE;
error:
if (INVALID_HANDLE_VALUE != hLocalFile)
{
CloseHandle(hLocalFile);
}
if (!fResult)
{
SetLastError(hr);
}
return(fResult);
}
BOOL
CreateKeyUsageExtension(
BYTE bIntendedKeyUsage,
OUT BYTE **ppbEncoded,
IN OUT DWORD *pcbEncoded,
HINSTANCE hInstance,
BOOL fUnattended,
HWND hwnd)
{
BOOL fResult = FALSE;
HRESULT hr;
BYTE *pbEncoded = NULL;
DWORD cbEncoded;
CRYPT_BIT_BLOB KeyUsage;
KeyUsage.pbData = &bIntendedKeyUsage;
KeyUsage.cbData = 1;
KeyUsage.cUnusedBits = 0;
hr = S_OK;
if (!myEncodeKeyUsage(
X509_ASN_ENCODING,
&KeyUsage,
CERTLIB_USE_LOCALALLOC,
&pbEncoded,
&cbEncoded))
{
hr = myHLastError();
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_ENCODEKEYATTR,
hr,
NULL);
cbEncoded = 0;
goto error;
}
fResult = TRUE;
error:
if (!fResult)
{
SetLastError(hr);
}
*ppbEncoded = pbEncoded;
*pcbEncoded = cbEncoded;
return(fResult);
}
#ifdef USE_NETSCAPE_TYPE_EXTENSION
BOOL
CreateNetscapeTypeExtension(
OUT BYTE **ppbEncoded,
OUT DWORD *pcbEncoded)
{
BOOL fResult = FALSE;
CRYPT_BIT_BLOB NetscapeType;
BYTE temp = NETSCAPE_SSL_CA_CERT_TYPE | NETSCAPE_SMIME_CA_CERT_TYPE;
NetscapeType.pbData = &temp;
NetscapeType.cbData = 1;
NetscapeType.cUnusedBits = 0;
if (!myEncodeObject(
X509_ASN_ENCODING,
X509_BITS,
&NetscapeType,
0,
CERTLIB_USE_LOCALALLOC,
ppbEncoded,
pcbEncoded))
{
goto exit;
}
fResult = TRUE;
exit:
return(fResult);
}
#endif
HRESULT
GetRegCRLDistributionPoints(
IN WCHAR const *pwszSanitizedName,
OUT WCHAR **ppwszz)
{
HRESULT hr;
WCHAR *pwszz = NULL;
WCHAR *pwsz;
WCHAR *pwszzCopy;
DWORD cwc;
DWORD Flags;
WCHAR *pwszT;
*ppwszz = NULL;
hr = myGetCertRegMultiStrValue(
pwszSanitizedName,
NULL,
NULL,
wszREGCRLPUBLICATIONURLS,
&pwszz);
if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
{
hr = S_OK;
goto error;
}
_JumpIfErrorStr(
hr,
error,
"myGetCertRegMultiStrValue",
wszREGCRLPUBLICATIONURLS);
cwc = 0;
for (pwsz = pwszz; L'\0' != *pwsz; pwsz += wcslen(pwsz) + 1)
{
Flags = _wtoi(pwsz);
if (CSURL_ADDTOCERTCDP & Flags)
{
pwszT = pwsz;
while (iswdigit(*pwszT))
{
pwszT++;
}
if (pwszT > pwsz && L':' == *pwszT)
{
pwszT++;
cwc += wcslen(pwszT) + 1;
}
}
}
if (0 == cwc)
{
hr = S_OK;
goto error;
}
pwszzCopy = (WCHAR *) LocalAlloc(LMEM_FIXED, (cwc + 1) * sizeof(WCHAR));
if (NULL == pwszzCopy)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
*ppwszz = pwszzCopy;
for (pwsz = pwszz; L'\0' != *pwsz; pwsz += wcslen(pwsz) + 1)
{
Flags = _wtoi(pwsz);
if (CSURL_ADDTOCERTCDP & Flags)
{
pwszT = pwsz;
while (iswdigit(*pwszT))
{
pwszT++;
}
if (pwszT > pwsz && L':' == *pwszT)
{
pwszT++;
wcscpy(pwszzCopy, pwszT);
pwszzCopy += wcslen(pwszT) + 1;
}
}
}
*pwszzCopy = L'\0';
CSASSERT(SAFE_SUBTRACT_POINTERS(pwszzCopy, *ppwszz) == cwc);
error:
if (NULL != pwszz)
{
LocalFree(pwszz);
}
return(hr);
}
HRESULT
FormatTemplateURLs(
IN WCHAR const *pwszSanitizedName,
IN DWORD iCert,
IN DWORD iCRL,
IN BOOL fUseDS,
IN WCHAR const *pwszzIn,
OUT DWORD *pcpwsz,
OUT WCHAR ***ppapwszOut)
{
HRESULT hr;
DWORD i;
WCHAR const **papwszTemplate = NULL;
WCHAR const *pwsz;
WCHAR **papwszOut = NULL;
DWORD cpwsz = 0;
WCHAR *pwszServerName = NULL;
LDAP *pld = NULL;
BSTR strConfigDN = NULL;
BSTR strDomainDN = NULL;
*pcpwsz = 0;
*ppapwszOut = NULL;
cpwsz = 0;
if (NULL != pwszzIn)
{
for (pwsz = pwszzIn; L'\0' != *pwsz; pwsz += wcslen(pwsz) + 1)
{
cpwsz++;
}
}
if (0 == cpwsz)
{
hr = S_FALSE;
goto error;
}
papwszTemplate = (WCHAR const **) LocalAlloc(
LMEM_FIXED,
cpwsz * sizeof(papwszTemplate[0]));
if (NULL == papwszTemplate)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
i = 0;
for (pwsz = pwszzIn; L'\0' != *pwsz; pwsz += wcslen(pwsz) + 1)
{
papwszTemplate[i++] = pwsz;
}
CSASSERT(i == cpwsz);
papwszOut = (WCHAR **) LocalAlloc(
LMEM_FIXED | LMEM_ZEROINIT,
cpwsz * sizeof(papwszOut[0]));
if (NULL == papwszOut)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
hr = myGetMachineDnsName(&pwszServerName);
_JumpIfError(hr, error, "myGetMachineDnsName");
// bind to ds -- even for !fUseDS, just in case the URLs need to domain DN
hr = myLdapOpen(
NULL, // pwszDomainName
RLBF_REQUIRE_SECURE_LDAP, // dwFlags
&pld,
&strDomainDN,
&strConfigDN);
if (S_OK != hr)
{
_PrintError(hr, "myLdapOpen");
if (fUseDS)
{
_JumpError(hr, error, "myLdapOpen");
}
strDomainDN = SysAllocString(L"");
strConfigDN = SysAllocString(L"");
if (NULL == strDomainDN || NULL == strConfigDN)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "SysAllocString");
}
}
hr = myFormatCertsrvStringArray(
TRUE, // fURL
pwszServerName, // pwszServerName_p1_2
pwszSanitizedName, // pwszSanitizedName_p3_7
iCert, // iCert_p4
MAXDWORD, // iCertTarget_p4
strDomainDN, // pwszDomainDN_p5
strConfigDN, // pwszConfigDN_p6
iCRL, // iCRL_p8
FALSE, // fDeltaCRL_p9
TRUE, // fDSAttrib_p10_11
cpwsz, // cStrings
papwszTemplate, // apwszStringsIn
papwszOut); // apwszStringsOut
_JumpIfError(hr, error, "myFormatCertsrvStringArray");
*pcpwsz = cpwsz;
*ppapwszOut = papwszOut;
papwszOut = NULL;
error:
if (NULL != pwszServerName)
{
LocalFree(pwszServerName);
}
myLdapClose(pld, strDomainDN, strConfigDN);
if (NULL != papwszTemplate)
{
LocalFree(papwszTemplate);
}
if (NULL != papwszOut)
{
for (i = 0; i < cpwsz; i++)
{
if (papwszOut[i])
{
LocalFree(papwszOut[i]);
}
}
LocalFree(papwszOut);
}
return(hr);
}
//+--------------------------------------------------------------------------
// CreateRevocationExtension
//
// Return S_OK if extension has been constructed.
// Return S_FALSE if empty section detected in INF file
// Return other error if no section detected in INF file
//+--------------------------------------------------------------------------
HRESULT
CreateRevocationExtension(
IN HINF hInf,
IN WCHAR const *pwszSanitizedName,
IN DWORD iCert,
IN DWORD iCRL,
IN BOOL fUseDS,
IN DWORD dwRevocationFlags,
OUT BOOL *pfCritical,
OUT BYTE **ppbEncoded,
OUT DWORD *pcbEncoded)
{
HRESULT hr;
DWORD i;
WCHAR *pwszzCDP = NULL;
WCHAR **papwszURL = NULL;
CRL_DIST_POINTS_INFO CRLDistInfo;
CRL_DIST_POINT CRLDistPoint;
CERT_ALT_NAME_INFO *pAltInfo;
ZeroMemory(&CRLDistPoint, sizeof(CRLDistPoint));
pAltInfo = &CRLDistPoint.DistPointName.FullName;
*ppbEncoded = NULL;
*pcbEncoded = 0;
hr = E_HANDLE;
if (INVALID_HANDLE_VALUE != hInf)
{
hr = myInfGetCRLDistributionPoints(hInf, pfCritical, &pwszzCDP);
csiLogInfError(hInf, hr);
}
if (S_OK != hr)
{
if (S_FALSE == hr)
{
_JumpError2(hr, error, "myInfGetCRLDistributionPoints", hr);
}
hr = GetRegCRLDistributionPoints(
pwszSanitizedName,
&pwszzCDP);
_JumpIfError(hr, error, "GetRegCRLDistributionPoints");
}
if (0 == (REVEXT_CDPENABLE & dwRevocationFlags))
{
hr = S_OK;
goto error;
}
hr = FormatTemplateURLs(
pwszSanitizedName,
iCert,
iCRL,
fUseDS,
pwszzCDP,
&pAltInfo->cAltEntry,
&papwszURL);
_JumpIfError(hr, error, "FormatTemplateURLs");
CRLDistInfo.cDistPoint = 1;
CRLDistInfo.rgDistPoint = &CRLDistPoint;
CRLDistPoint.DistPointName.dwDistPointNameChoice = CRL_DIST_POINT_FULL_NAME;
pAltInfo->rgAltEntry = (CERT_ALT_NAME_ENTRY *) LocalAlloc(
LMEM_FIXED | LMEM_ZEROINIT,
pAltInfo->cAltEntry * sizeof(pAltInfo->rgAltEntry[0]));
if (NULL == pAltInfo->rgAltEntry)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
for (i = 0; i < pAltInfo->cAltEntry; i++)
{
pAltInfo->rgAltEntry[i].pwszURL = papwszURL[i];
pAltInfo->rgAltEntry[i].dwAltNameChoice = CERT_ALT_NAME_URL;
DBGPRINT((DBG_SS_CERTLIB, "CDP[%u] = '%ws'\n", i, papwszURL[i]));
}
if (!myEncodeObject(
X509_ASN_ENCODING,
X509_CRL_DIST_POINTS,
&CRLDistInfo,
0,
CERTLIB_USE_LOCALALLOC,
ppbEncoded,
pcbEncoded))
{
hr = myHLastError();
_JumpIfError(hr, error, "myEncodeObject");
}
hr = S_OK;
error:
if (NULL != pAltInfo->rgAltEntry)
{
LocalFree(pAltInfo->rgAltEntry);
}
if (NULL != papwszURL)
{
for (i = 0; i < pAltInfo->cAltEntry; i++)
{
if (NULL != papwszURL[i])
{
LocalFree(papwszURL[i]);
}
}
LocalFree(papwszURL);
}
if (NULL != pwszzCDP)
{
LocalFree(pwszzCDP);
}
return(hr);
}
//+--------------------------------------------------------------------------
// CreateAuthorityInformationAccessExtension
//
// Return S_OK if extension has been constructed.
// Return S_FALSE if empty section detected in INF file
// Return other error if no section detected in INF file
//+--------------------------------------------------------------------------
HRESULT
CreateAuthorityInformationAccessExtension(
IN HINF hInf,
IN WCHAR const *pwszSanitizedName,
IN DWORD iCert,
IN DWORD iCRL,
IN BOOL fUseDS,
OUT BOOL *pfCritical,
OUT BYTE **ppbEncoded,
OUT DWORD *pcbEncoded)
{
HRESULT hr;
DWORD i;
WCHAR *pwszzAIA = NULL;
WCHAR **papwszURL = NULL;
CERT_AUTHORITY_INFO_ACCESS caio;
caio.cAccDescr = 0;
caio.rgAccDescr = NULL;
*ppbEncoded = NULL;
*pcbEncoded = 0;
hr = E_HANDLE;
if (INVALID_HANDLE_VALUE != hInf)
{
hr = myInfGetAuthorityInformationAccess(hInf, pfCritical, &pwszzAIA);
csiLogInfError(hInf, hr);
}
_JumpIfError3(
hr,
error,
"myInfGetAuthorityInformationAccess",
E_HANDLE,
S_FALSE);
hr = FormatTemplateURLs(
pwszSanitizedName,
iCert,
iCRL,
fUseDS,
pwszzAIA,
&caio.cAccDescr,
&papwszURL);
_JumpIfError(hr, error, "FormatTemplateURLs");
caio.rgAccDescr = (CERT_ACCESS_DESCRIPTION *) LocalAlloc(
LMEM_FIXED | LMEM_ZEROINIT,
caio.cAccDescr * sizeof(CERT_ACCESS_DESCRIPTION));
if (NULL == caio.rgAccDescr)
{
hr = E_OUTOFMEMORY;
_JumpIfError(hr, error, "LocalAlloc");
}
for (i = 0; i < caio.cAccDescr; i++)
{
caio.rgAccDescr[i].pszAccessMethod = szOID_PKIX_CA_ISSUERS;
caio.rgAccDescr[i].AccessLocation.dwAltNameChoice = CERT_ALT_NAME_URL;
caio.rgAccDescr[i].AccessLocation.pwszURL = papwszURL[i];
DBGPRINT((DBG_SS_CERTLIB, "AIA[%u] = '%ws'\n", i, papwszURL[i]));
}
if (!myEncodeObject(
X509_ASN_ENCODING,
X509_AUTHORITY_INFO_ACCESS,
&caio,
0,
CERTLIB_USE_LOCALALLOC,
ppbEncoded,
pcbEncoded))
{
hr = myHLastError();
_JumpIfError(hr, error, "myEncodeObject");
}
error:
if (NULL != caio.rgAccDescr)
{
LocalFree(caio.rgAccDescr);
}
if (NULL != papwszURL)
{
for (i = 0; i < caio.cAccDescr; i++)
{
if (NULL != papwszURL[i])
{
LocalFree(papwszURL[i]);
}
}
LocalFree(papwszURL);
}
if (NULL != pwszzAIA)
{
LocalFree(pwszzAIA);
}
return(hr);
}
HRESULT
FillRDN(
IN char const *pszObjId,
IN WCHAR const *pwszRDN,
IN OUT CERT_RDN *prgRDN)
{
HRESULT hr;
CERT_RDN_ATTR *prgAttr = NULL;
prgAttr = (CERT_RDN_ATTR *) LocalAlloc(LMEM_FIXED, sizeof(*prgAttr));
if (NULL == prgAttr)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
prgAttr->pszObjId = const_cast<char *>(pszObjId);
prgAttr->dwValueType = 0;
prgAttr->Value.pbData = (BYTE *) pwszRDN;
prgAttr->Value.cbData = 0;
prgRDN->cRDNAttr = 1;
prgRDN->rgRDNAttr = prgAttr;
hr = S_OK;
error:
return(hr);
}
VOID
csiFreeCertNameInfo(
CERT_NAME_INFO *pNameInfo)
{
DWORD iRDN;
if (NULL != pNameInfo)
{
if (NULL != pNameInfo->rgRDN)
{
for (iRDN = 0; iRDN < pNameInfo->cRDN; ++iRDN)
{
if (NULL != pNameInfo->rgRDN[iRDN].rgRDNAttr)
{
LocalFree(pNameInfo->rgRDN[iRDN].rgRDNAttr);
}
}
LocalFree(pNameInfo->rgRDN);
}
LocalFree(pNameInfo);
}
}
HRESULT
FillExtension(
IN OUT CERT_EXTENSION *pDesExt,
IN OUT DWORD *pdwIndex,
IN CERT_EXTENSION *pSrcExt)
{
CSASSERT(NULL != pDesExt && NULL != pSrcExt);
if (NULL != pSrcExt->Value.pbData && 0 != pSrcExt->Value.cbData)
{
pDesExt[*pdwIndex].pszObjId = pSrcExt->pszObjId;
pDesExt[*pdwIndex].fCritical = pSrcExt->fCritical;
pDesExt[*pdwIndex].Value = pSrcExt->Value;
++(*pdwIndex);
}
return(S_OK);
}
HRESULT
EncodeCertAndSign(
IN HCRYPTPROV hProv,
IN CERT_INFO *pCert,
IN char const *pszAlgId,
OUT BYTE **ppbSigned,
OUT DWORD *pcbSigned,
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd)
{
HRESULT hr;
BYTE *pbEncoded = NULL;
DWORD cbEncoded;
*ppbSigned = NULL;
if (!myEncodeToBeSigned(
X509_ASN_ENCODING,
pCert,
CERTLIB_USE_LOCALALLOC,
&pbEncoded,
&cbEncoded))
{
hr = myHLastError();
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_ENCODETOBESIGNED,
hr,
NULL);
_JumpError(hr, error, "myEncodeToBeSigned");
}
hr = myEncodeSignedContent(
hProv,
X509_ASN_ENCODING,
pszAlgId,
pbEncoded,
cbEncoded,
CERTLIB_USE_LOCALALLOC,
ppbSigned,
pcbSigned);
_JumpIfError(hr, error, "myEncodeSignedContent");
error:
if (NULL != pbEncoded)
{
LocalFree(pbEncoded);
}
return(hr);
}
HRESULT
EncodeCACert(
IN CASERVERSETUPINFO const *pSetupInfo,
IN HCRYPTPROV hProv,
IN const WCHAR *pwszCAType,
OUT BYTE **ppbEncoded,
OUT DWORD *pcbEncoded,
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd)
{
HRESULT hr = E_FAIL;
BYTE *pbSubjectEncoded = NULL;
DWORD cbSubjectEncoded = 0;
BYTE *pbIssuerEncoded = NULL;
DWORD cbIssuerEncoded = 0;
CERT_PUBLIC_KEY_INFO *pPubKey = NULL;
DWORD cbPubKey;
HINF hInf = INVALID_HANDLE_VALUE;
DWORD ErrorLine;
DWORD cExtInf = 0;
CERT_EXTENSION *rgExtInf = NULL;
DWORD cExtMerged;
CERT_EXTENSION *rgExtMerged = NULL;
CERT_EXTENSIONS *pStdExts = NULL;
CERT_EXTENSION *pAllExts = NULL;
CERT_EXTENSION extKeyUsage =
{szOID_KEY_USAGE, FALSE, 0, NULL};
CERT_EXTENSION extBasicConstraints =
{NULL, FALSE, 0, NULL};
CERT_EXTENSION extAKI =
{szOID_AUTHORITY_KEY_IDENTIFIER2, FALSE, 0, NULL};
CERT_EXTENSION extSKI =
{szOID_SUBJECT_KEY_IDENTIFIER, FALSE, 0, NULL};
CERT_EXTENSION extCDP =
{szOID_CRL_DIST_POINTS, FALSE, 0, NULL};
CERT_EXTENSION extCCDP =
{szOID_CROSS_CERT_DIST_POINTS, FALSE, 0, NULL};
CERT_EXTENSION extVersion =
{szOID_CERTSRV_CA_VERSION, FALSE, 0, NULL};
CERT_EXTENSION extPolicy =
{szOID_CERT_POLICIES, FALSE, 0, NULL};
CERT_EXTENSION extAIA =
{szOID_AUTHORITY_INFO_ACCESS, FALSE, 0, NULL};
CERT_EXTENSION extEKU =
{NULL, FALSE, 0, NULL};
#ifdef USE_NETSCAPE_TYPE_EXTENSION
CERT_EXTENSION extNetscape =
{szOID_NETSCAPE_CERT_TYPE, FALSE, 0, NULL};
#endif
DWORD cExtension;
HCERTTYPE hCertType = NULL;
DWORD i;
DWORD j;
GUID guidSerialNumber;
CERT_INFO Cert;
*ppbEncoded = NULL;
hr = myInfOpenFile(NULL, &hInf, &ErrorLine);
_PrintIfError2(
hr,
"myInfOpenFile",
HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
if (INVALID_HANDLE_VALUE != hInf)
{
BOOL fUTF8;
hr = myInfGetBooleanValue(
hInf,
wszINFSECTION_CERTSERVER,
wszINFKEY_UTF8,
TRUE,
&fUTF8);
csiLogInfError(hInf, hr);
if (S_OK == hr)
{
g_dwNameEncodeFlags = fUTF8? CERT_RDN_ENABLE_UTF8_UNICODE_FLAG : 0;
}
}
// SUBJECT
hr = AddCNAndEncode(
pSetupInfo->pwszCACommonName,
pSetupInfo->pwszDNSuffix,
&pbSubjectEncoded,
&cbSubjectEncoded);
_JumpIfError(hr, error, "AddCNAndEncodeCertStrToName");
// ISSUER
hr = AddCNAndEncode(
pSetupInfo->pwszCACommonName,
pSetupInfo->pwszDNSuffix,
&pbIssuerEncoded,
&cbIssuerEncoded);
_JumpIfError(hr, error, "AddCNAndEncodeCertStrToName");
if (!myCryptExportPublicKeyInfo(
hProv,
AT_SIGNATURE,
CERTLIB_USE_LOCALALLOC,
&pPubKey,
&cbPubKey))
{
hr = myHLastError();
_JumpError(hr, error, "myCryptExportPublicKeyInfo");
}
// get cert type
hr = CAFindCertTypeByName(
pwszCAType,
NULL,
CT_FIND_LOCAL_SYSTEM |
CT_ENUM_MACHINE_TYPES |
CT_ENUM_USER_TYPES,
&hCertType);
if (HRESULT_FROM_WIN32(ERROR_NOT_FOUND) == hr)
{
hr = CAFindCertTypeByName(
pwszCAType,
NULL,
CT_FIND_LOCAL_SYSTEM |
CT_ENUM_MACHINE_TYPES |
CT_ENUM_USER_TYPES |
CT_FIND_BY_OID,
&hCertType);
}
if (S_OK == hr)
{
// get cert type standard extensions
hr = CAGetCertTypeExtensions(hCertType, &pStdExts);
_JumpIfErrorStr(hr, error, "CAGetCertTypeExtensions", pwszCAType);
cExtension = pStdExts->cExtension;
}
else
{
cExtension = 0;
DBGERRORPRINTLINE("CAFindCertTypeByName", hr);
}
if (NULL == pStdExts)
{
// standard extensions not available from CAGetCertTypeExtensions
if (!CreateKeyUsageExtension(
myCASIGN_KEY_USAGE,
&extKeyUsage.Value.pbData,
&extKeyUsage.Value.cbData,
hInstance,
fUnattended,
hwnd))
{
hr = myHLastError();
_JumpError(hr, error, "CreateKeyUsageExtension");
}
++cExtension;
}
hr = myInfGetBasicConstraints2CAExtensionOrDefault(hInf, &extBasicConstraints);
csiLogInfError(hInf, hr);
_JumpIfError(hr, error, "myInfGetBasicConstraints2CAExtensionOrDefault");
++cExtension;
// Subject Key Identifier extension:
hr = myCreateSubjectKeyIdentifierExtension(
pPubKey,
&extSKI.Value.pbData,
&extSKI.Value.cbData);
_JumpIfError(hr, error, "myCreateSubjectKeyIdentifierExtension");
++cExtension;
hr = CreateRevocationExtension(
hInf,
pSetupInfo->pwszSanitizedName,
0, // iCert
0, // iCRL
pSetupInfo->fUseDS,
pSetupInfo->dwRevocationFlags,
&extCDP.fCritical,
&extCDP.Value.pbData,
&extCDP.Value.cbData);
_PrintIfError(hr, "CreateRevocationExtension");
CSASSERT((NULL == extCDP.Value.pbData) ^ (S_OK == hr));
if (S_OK == hr)
{
++cExtension;
}
hr = myInfGetCrossCertDistributionPointsExtension(hInf, &extCCDP);
csiLogInfError(hInf, hr);
_PrintIfError(hr, "myInfGetCrossCertDistributionPointsExtension");
CSASSERT((NULL == extCCDP.Value.pbData) ^ (S_OK == hr));
if (S_OK == hr)
{
++cExtension;
}
// Build the CA Version extension
if (!myEncodeObject(
X509_ASN_ENCODING,
X509_INTEGER,
&pSetupInfo->dwCertNameId,
0,
CERTLIB_USE_LOCALALLOC,
&extVersion.Value.pbData,
&extVersion.Value.cbData))
{
hr = myHLastError();
_JumpError(hr, error, "myEncodeObject");
}
++cExtension;
hr = myInfGetPolicyStatementExtension(hInf, &extPolicy);
csiLogInfError(hInf, hr);
_PrintIfError(hr, "myInfCreatePolicyStatementExtension");
CSASSERT((NULL == extPolicy.Value.pbData) ^ (S_OK == hr));
if (S_OK == hr)
{
++cExtension;
}
hr = CreateAuthorityInformationAccessExtension(
hInf,
pSetupInfo->pwszSanitizedName,
0, // iCert
0, // iCRL
pSetupInfo->fUseDS,
&extAIA.fCritical,
&extAIA.Value.pbData,
&extAIA.Value.cbData);
_PrintIfError(hr, "CreateAuthorityInformationAccessExtension");
CSASSERT((NULL == extAIA.Value.pbData) ^ (S_OK == hr));
if (S_OK == hr)
{
++cExtension;
}
hr = myInfGetEnhancedKeyUsageExtension(hInf, &extEKU);
csiLogInfError(hInf, hr);
_PrintIfError(hr, "myInfGetEnhancedKeyUsageExtension");
CSASSERT((NULL == extEKU.Value.pbData) ^ (S_OK == hr));
if (S_OK == hr)
{
++cExtension;
}
#ifdef USE_NETSCAPE_TYPE_EXTENSION
// Netscape Cert Type extension:
if (!CreateNetscapeTypeExtension(
&extNetscape.Value.pbData,
&extNetscape.Value.cbData))
{
hr = myHLastError();
_JumpError(hr, error, "CreateNetscapeTypeExtension");
}
++cExtension;
#endif
hr = myInfGetExtensions(hInf, &cExtInf, &rgExtInf);
csiLogInfError(hInf, hr);
_PrintIfError(hr, "myInfGetExtensions");
// put all extensions together
pAllExts = (CERT_EXTENSION *) LocalAlloc(
LMEM_FIXED | LMEM_ZEROINIT,
cExtension * sizeof(CERT_EXTENSION));
if (NULL == pAllExts)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
i = 0;
if (NULL != pStdExts)
{
for (j = 0 ; j < pStdExts->cExtension; j++)
{
if (0 == strcmp(szOID_BASIC_CONSTRAINTS2, pStdExts->rgExtension[j].pszObjId))
{
continue;
}
pAllExts[i].pszObjId = pStdExts->rgExtension[j].pszObjId;
pAllExts[i].fCritical = pStdExts->rgExtension[j].fCritical;
pAllExts[i].Value = pStdExts->rgExtension[j].Value;
i++;
}
}
FillExtension(pAllExts, &i, &extKeyUsage);
FillExtension(pAllExts, &i, &extBasicConstraints);
FillExtension(pAllExts, &i, &extAKI);
FillExtension(pAllExts, &i, &extSKI);
FillExtension(pAllExts, &i, &extCDP);
FillExtension(pAllExts, &i, &extCCDP);
FillExtension(pAllExts, &i, &extVersion);
FillExtension(pAllExts, &i, &extPolicy);
FillExtension(pAllExts, &i, &extAIA);
FillExtension(pAllExts, &i, &extEKU);
#ifdef USE_NETSCAPE_TYPE_EXTENSION
FillExtension(pAllExts, &i, &extKeyNetscape);
#endif
CSASSERT(i <= cExtension);
// CERT
ZeroMemory(&Cert, sizeof(Cert));
Cert.dwVersion = CERT_V3;
myGenerateGuidSerialNumber(&guidSerialNumber);
Cert.SerialNumber.pbData = (BYTE *) &guidSerialNumber;
Cert.SerialNumber.cbData = sizeof(guidSerialNumber);
Cert.SignatureAlgorithm.pszObjId = pSetupInfo->pszAlgId;
Cert.Issuer.pbData = pbIssuerEncoded;
Cert.Issuer.cbData = cbIssuerEncoded;
GetSystemTimeAsFileTime(&Cert.NotBefore);
myMakeExprDateTime(
&Cert.NotBefore,
-CCLOCKSKEWMINUTESDEFAULT,
ENUM_PERIOD_MINUTES);
if (0 < CompareFileTime(&Cert.NotBefore, &pSetupInfo->NotBefore))
{
Cert.NotBefore = pSetupInfo->NotBefore;
}
Cert.NotAfter = pSetupInfo->NotAfter;
Cert.Subject.pbData = pbSubjectEncoded;
Cert.Subject.cbData = cbSubjectEncoded;
Cert.SubjectPublicKeyInfo = *pPubKey; // Structure assignment
Cert.cExtension = i;
Cert.rgExtension = pAllExts;
if (0 != cExtInf)
{
hr = myMergeExtensions(
Cert.cExtension,
Cert.rgExtension,
cExtInf,
rgExtInf,
&cExtMerged,
&rgExtMerged);
_JumpIfError(hr, error, "myMergeExtensions");
Cert.cExtension = cExtMerged;
Cert.rgExtension = rgExtMerged;
}
if (0 == Cert.cExtension)
{
Cert.dwVersion = CERT_V1;
}
hr = EncodeCertAndSign(
hProv,
&Cert,
pSetupInfo->pszAlgId,
ppbEncoded,
pcbEncoded,
hInstance,
fUnattended,
hwnd);
_JumpIfError(hr, error, "EncodeCertAndSign");
error:
if (INVALID_HANDLE_VALUE != hInf)
{
myInfCloseFile(hInf);
}
if (NULL != rgExtMerged)
{
LocalFree(rgExtMerged);
}
myInfFreeExtensions(cExtInf, rgExtInf);
if (NULL != extKeyUsage.Value.pbData)
{
LocalFree(extKeyUsage.Value.pbData);
}
if (NULL != extBasicConstraints.Value.pbData)
{
LocalFree(extBasicConstraints.Value.pbData);
}
if (NULL != extAKI.Value.pbData)
{
LocalFree(extAKI.Value.pbData);
}
if (NULL != extSKI.Value.pbData)
{
LocalFree(extSKI.Value.pbData);
}
if (NULL != extCDP.Value.pbData)
{
LocalFree(extCDP.Value.pbData);
}
if (NULL != extCCDP.Value.pbData)
{
LocalFree(extCCDP.Value.pbData);
}
if (NULL != extVersion.Value.pbData)
{
LocalFree(extVersion.Value.pbData);
}
if (NULL != extPolicy.Value.pbData)
{
LocalFree(extPolicy.Value.pbData);
}
if (NULL != extAIA.Value.pbData)
{
LocalFree(extAIA.Value.pbData);
}
if (NULL != extEKU.Value.pbData)
{
LocalFree(extEKU.Value.pbData);
}
#ifdef USE_NETSCAPE_TYPE_EXTENSION
if (NULL != extKeyNetscape.Value.pbData)
{
LocalFree(extKeyNetscape.Value.pbData);
}
#endif
if (NULL != hCertType)
{
if (NULL != pStdExts)
{
CAFreeCertTypeExtensions(hCertType, pStdExts);
}
CACloseCertType(hCertType);
}
if (NULL != pAllExts)
{
LocalFree(pAllExts);
}
if (NULL != pbSubjectEncoded)
{
LocalFree(pbSubjectEncoded);
}
if (NULL != pbIssuerEncoded)
{
LocalFree(pbIssuerEncoded);
}
if (NULL != pPubKey)
{
LocalFree(pPubKey);
}
CSILOG(hr, IDS_ILOG_BUILDCERT, NULL, NULL, NULL);
return(hr);
}
HRESULT
csiGetCRLPublicationParams(
BOOL fBaseCRL,
WCHAR **ppwszCRLPeriodString,
DWORD *pdwCRLPeriodCount)
{
HRESULT hr;
HINF hInf = INVALID_HANDLE_VALUE;
DWORD ErrorLine;
static WCHAR const * const s_apwszKeys[] =
{
wszINFKEY_CRLPERIODSTRING,
wszINFKEY_CRLDELTAPERIODSTRING,
wszINFKEY_CRLPERIODCOUNT,
wszINFKEY_CRLDELTAPERIODCOUNT,
NULL
};
hr = myInfOpenFile(NULL, &hInf, &ErrorLine);
_JumpIfError2(
hr,
error,
"myInfOpenFile",
HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
if (INVALID_HANDLE_VALUE != hInf)
{
HRESULT hr2;
hr = myInfGetCRLPublicationParams(
hInf,
fBaseCRL? wszINFKEY_CRLPERIODSTRING : wszINFKEY_CRLDELTAPERIODSTRING,
fBaseCRL? wszINFKEY_CRLPERIODCOUNT : wszINFKEY_CRLDELTAPERIODCOUNT,
ppwszCRLPeriodString,
pdwCRLPeriodCount);
// log any error, but befre returning the eorror, also log any
// unexpected Keys in the same INF file section, so the log will
// describe any Key name typos.
csiLogInfError(hInf, hr);
_PrintIfErrorStr(
hr,
"myInfGetCRLPublicationParams",
fBaseCRL? L"Base" : L"Delta");
hr2 = myInfGetKeyList(
hInf,
wszINFSECTION_CERTSERVER,
NULL, // pwszKey
s_apwszKeys,
NULL, // pfCritical
NULL); // ppwszzTemplateList
csiLogInfError(hInf, hr2);
_PrintIfErrorStr(hr2, "myInfGetKeyList", wszINFSECTION_CERTSERVER);
_JumpIfError(hr, error, "myInfGetCRLPublicationParams");
}
hr = S_OK;
error:
if (INVALID_HANDLE_VALUE != hInf)
{
myInfCloseFile(hInf);
}
return hr;
}
HRESULT
csiBuildFileName(
IN WCHAR const *pwszDirPath,
IN WCHAR const *pwszSanitizedName,
IN WCHAR const *pwszExt,
IN DWORD iCert,
OUT WCHAR **ppwszOut,
HINSTANCE hInstance,
BOOL fUnattended,
IN HWND hwnd)
{
HRESULT hr;
DWORD cwc;
WCHAR *pwszServerName = NULL;
WCHAR wszIndex[cwcFILENAMESUFFIXMAX]; // L"(%u)"
*ppwszOut = NULL;
wszIndex[0] = L'\0';
if (0 != iCert)
{
wsprintf(wszIndex, L"(%u)", iCert);
}
hr = myGetMachineDnsName(&pwszServerName);
if (S_OK != hr)
{
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_GETCOMPUTERNAME,
hr,
NULL);
_JumpError(hr, error, "myGetMachineDnsName");
}
cwc = wcslen(pwszDirPath) +
WSZARRAYSIZE(g_szSlash) +
wcslen(pwszServerName) +
WSZARRAYSIZE(L"_") +
wcslen(pwszSanitizedName) +
wcslen(wszIndex) +
wcslen(pwszExt) +
1; // NULL term
*ppwszOut = (WCHAR *) LocalAlloc(LMEM_FIXED, cwc * sizeof(WCHAR));
if (NULL == *ppwszOut)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
wcscpy(*ppwszOut, pwszDirPath);
wcscat(*ppwszOut, g_szSlash);
wcscat(*ppwszOut, pwszServerName);
wcscat(*ppwszOut, L"_");
wcscat(*ppwszOut, pwszSanitizedName);
wcscat(*ppwszOut, wszIndex);
wcscat(*ppwszOut, pwszExt);
hr = S_OK;
error:
if (NULL != pwszServerName)
{
LocalFree(pwszServerName);
}
return(hr);
}
HRESULT
csiBuildCACertFileName(
IN HINSTANCE hInstance,
IN HWND hwnd,
IN BOOL fUnattended,
OPTIONAL IN WCHAR const *pwszSharedFolder,
IN WCHAR const *pwszSanitizedName,
IN WCHAR const *pwszExt,
IN DWORD iCert,
OUT WCHAR **ppwszCACertFile)
{
HRESULT hr;
WCHAR *pwszCACertFile = NULL;
WCHAR const *pwszDir = pwszSharedFolder;
WCHAR *pwszDirAlloc = NULL;
CSASSERT(NULL != ppwszCACertFile);
*ppwszCACertFile = NULL;
if (NULL == pwszDir)
{
// no shared folder, go system drive
hr = myGetEnvString(&pwszDirAlloc, L"SystemDrive");
_JumpIfError(hr, error, "myGetEnvString");
pwszDir = pwszDirAlloc;
}
// build ca cert file name here
hr = csiBuildFileName(
pwszDir,
pwszSanitizedName,
pwszExt,
iCert,
&pwszCACertFile,
hInstance,
fUnattended,
hwnd);
_JumpIfError(hr, error, "csiBuildFileName");
CSASSERT(NULL != pwszCACertFile);
*ppwszCACertFile = pwszCACertFile;
hr = S_OK;
error:
if (NULL != pwszDirAlloc)
{
LocalFree(pwszDirAlloc);
}
return(hr);
}
HRESULT
csiBuildAndWriteCert(
IN HCRYPTPROV hCryptProv,
IN CASERVERSETUPINFO const *pServer,
OPTIONAL IN WCHAR const *pwszFile,
IN WCHAR const *pwszEnrollFile,
OPTIONAL IN CERT_CONTEXT const *pCertContextFromStore,
OPTIONAL OUT CERT_CONTEXT const **ppCertContextOut,
IN WCHAR const *pwszCAType,
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd)
{
BYTE *pbEncoded = NULL;
DWORD cbEncoded;
CERT_CONTEXT const *pccCA = NULL;
HRESULT hr;
if (NULL != ppCertContextOut)
{
*ppCertContextOut = NULL;
}
if (NULL == pCertContextFromStore)
{
// create cert
hr = EncodeCACert(
pServer,
hCryptProv,
pwszCAType,
&pbEncoded,
&cbEncoded,
hInstance,
fUnattended,
hwnd);
_JumpIfError(hr, error, "EncodeCACert");
pccCA = CertCreateCertificateContext(
X509_ASN_ENCODING,
pbEncoded,
cbEncoded);
if (NULL == pccCA)
{
hr = myHLastError();
_JumpError(hr, error, "CertCreateCertificateContext");
}
}
else
{
pccCA = CertDuplicateCertificateContext(pCertContextFromStore);
if (NULL == pccCA)
{
hr = myHLastError();
_JumpError(hr, error, "CertDuplicateCertificateContext");
}
}
if (NULL != pwszFile && !csiWriteDERToFile(
pwszFile,
pccCA->pbCertEncoded,
pccCA->cbCertEncoded,
hInstance,
fUnattended,
hwnd))
{
hr = myHLastError();
_JumpError(hr, error, "csiWriteDERToFile");
}
if (!csiWriteDERToFile(
pwszEnrollFile,
pccCA->pbCertEncoded,
pccCA->cbCertEncoded,
hInstance,
fUnattended,
hwnd))
{
hr = myHLastError();
_JumpError(hr, error, "csiWriteDERToFile(enroll)");
}
if (NULL != ppCertContextOut)
{
*ppCertContextOut = pccCA;
pccCA = NULL;
}
hr = S_OK;
error:
if (NULL != pccCA)
{
if (!CertFreeCertificateContext(pccCA))
{
HRESULT hr2;
hr2 = myHLastError();
_PrintError(hr2, "CertFreeCertificateContext");
CSASSERT(S_OK == hr2);
}
}
if (NULL != pbEncoded)
{
LocalFree(pbEncoded);
}
return(hr);
}
HRESULT
IsCACert(
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd,
IN CERT_CONTEXT const *pCert,
IN ENUM_CATYPES CAType)
{
HRESULT hr;
BOOL fCA;
CERT_EXTENSION *pExt;
DWORD cb;
CERT_BASIC_CONSTRAINTS2_INFO Constraints;
fCA = FALSE;
hr = S_OK;
pExt = CertFindExtension(
szOID_BASIC_CONSTRAINTS2,
pCert->pCertInfo->cExtension,
pCert->pCertInfo->rgExtension);
if (NULL == pExt)
{
if (IsRootCA(CAType) && CERT_V1 == pCert->pCertInfo->dwVersion)
{
_PrintError(hr, "V1 root cert");
hr = S_OK;
goto error;
}
hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
_PrintError(hr, "No Basic Constraints Extension");
}
else
{
cb = sizeof(Constraints);
if (!CryptDecodeObject(
X509_ASN_ENCODING,
X509_BASIC_CONSTRAINTS2,
pExt->Value.pbData,
pExt->Value.cbData,
0,
&Constraints,
&cb))
{
hr = myHLastError();
_PrintError(hr, "CryptDecodeObject");
}
else
{
fCA = Constraints.fCA;
if (!fCA)
{
hr = CERTSRV_E_INVALID_CA_CERTIFICATE;
_PrintError(hr, "fCA not set");
}
}
}
if (!fCA)
{
CertMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_NOTCACERT,
S_OK,
MB_OK | MB_ICONERROR | CMB_NOERRFROMSYS,
NULL);
_JumpError(hr, error, "not a CA cert");
}
hr = S_OK;
error:
return(hr);
}
HRESULT
ExtractCACertFromPKCS7(
IN WCHAR const *pwszCommonName,
IN BYTE const *pbPKCS7,
IN DWORD cbPKCS7,
OPTIONAL OUT CERT_CONTEXT const **ppccCA)
{
HRESULT hr;
CERT_CONTEXT const *pCert = NULL;
HCERTSTORE hChainStore = NULL;
CRYPT_DATA_BLOB chainBlob;
CERT_RDN_ATTR rdnAttr = { szOID_COMMON_NAME, CERT_RDN_ANY_TYPE, };
CERT_RDN rdn = { 1, &rdnAttr };
CERT_CHAIN_PARA ChainPara;
CERT_CHAIN_CONTEXT const *pChainContext = NULL;
CERT_CHAIN_CONTEXT const *pLongestChainContext = NULL;
*ppccCA = NULL;
if (NULL == pbPKCS7 || 0 == cbPKCS7)
{
hr = E_INVALIDARG;
_JumpError(hr, error, "Invalid input parameters");
}
chainBlob.pbData = const_cast<BYTE *>(pbPKCS7);
chainBlob.cbData = cbPKCS7;
hChainStore = CertOpenStore(
CERT_STORE_PROV_PKCS7,
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
NULL, // hProv
0,
(const void*) &chainBlob);
if (NULL == hChainStore)
{
hr = myHLastError();
_JumpError(hr, error, "CertOpenStore");
}
rdnAttr.Value.pbData = (BYTE *) pwszCommonName;
rdnAttr.Value.cbData = 0;
// Find the longest chain in the passed PKCS7 with a leaf CA cert that
// matches the passed common name
for (;;)
{
pCert = CertFindCertificateInStore(
hChainStore,
X509_ASN_ENCODING,
CERT_UNICODE_IS_RDN_ATTRS_FLAG |
CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG,
CERT_FIND_SUBJECT_ATTR,
&rdn,
pCert);
if (NULL == pCert)
{
if (NULL == pLongestChainContext)
{
hr = E_INVALIDARG;
_JumpError(hr, error, "can't find matched cert in chain");
}
break; // most common case, done here
}
ZeroMemory(&ChainPara, sizeof(ChainPara));
ChainPara.cbSize = sizeof(CERT_CHAIN_PARA);
ChainPara.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;
//ChainPara.RequestedUsage.Usage.cUsageIdentifier = 0;
//ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = NULL;
if (!CertGetCertificateChain(
HCCE_LOCAL_MACHINE,
pCert,
NULL,
hChainStore,
&ChainPara,
0,
NULL,
&pChainContext))
{
// couldn't get the chain
if (NULL == pLongestChainContext)
{
// fail to find a chain
hr = myHLastError();
_JumpError(hr, error, "CertGetCertificateChain");
}
break; // done with it
}
// we have assumed each chain context contains
// only one simple chain, ie. pChainContext->cChain = 1
CSASSERT(1 == pChainContext->cChain);
if (NULL == pLongestChainContext ||
pChainContext->rgpChain[0]->cElement >
pLongestChainContext->rgpChain[0]->cElement)
{
if (NULL != pLongestChainContext)
{
CertFreeCertificateChain(pLongestChainContext);
}
// save pointer to this chain
pLongestChainContext = pChainContext;
}
else
{
CertFreeCertificateChain(pChainContext);
}
}
CSASSERT(NULL == pCert);
if (NULL != pLongestChainContext &&
0 < pLongestChainContext->rgpChain[0]->cElement)
{
*ppccCA = CertDuplicateCertificateContext(
pLongestChainContext->rgpChain[0]->rgpElement[0]->pCertContext);
if (NULL == *ppccCA)
{
hr = myHLastError();
_JumpError(hr, error, "CertDuplicateCertificateContext");
}
}
hr = S_OK;
error:
if (NULL != pCert)
{
CertFreeCertificateContext(pCert);
}
if (NULL != pLongestChainContext)
{
CertFreeCertificateChain(pLongestChainContext);
}
if (hChainStore)
{
CertCloseStore(hChainStore, CERT_CLOSE_STORE_CHECK_FLAG);
}
CSILOG(hr, IDS_ILOG_SAVECHAINANDKEYS, pwszCommonName, NULL, NULL);
return(hr);
}
#define ENTERPRISECATEMPLATELIST \
wszCERTTYPE_ADMIN, \
wszCERTTYPE_SUBORDINATE_CA, \
wszCERTTYPE_USER, \
wszCERTTYPE_MACHINE, \
wszCERTTYPE_WEBSERVER, \
wszCERTTYPE_DC, \
wszCERTTYPE_EFS, \
wszCERTTYPE_EFS_RECOVERY
WCHAR *s_apwszCertTypeServer[] =
{
ENTERPRISECATEMPLATELIST,
NULL
};
WCHAR *s_apwszCertTypeAdvancedServer[] =
{
ENTERPRISECATEMPLATELIST,
wszCERTTYPE_DC_AUTH,
wszCERTTYPE_DS_EMAIL_REPLICATION,
NULL
};
WCHAR *s_apwszCertTypeEmpty[] =
{
L" ",
NULL
};
HRESULT
GetValidCRLIndexes(
IN LPCWSTR pwszSanitizedCAName,
OUT DWORD **ppdwCRLIndexes,
OUT DWORD *pnCRLIndexes)
{
HRESULT hr;
DWORD dwHashCount;
HCERTSTORE hMyStore = NULL;
CERT_CONTEXT const *pccCert = NULL;
DWORD NameId;
DWORD nCRLIndexes;
DWORD *pdwCRLIndexes = NULL;
*ppdwCRLIndexes = NULL;
*pnCRLIndexes = 0;
hr = myGetCARegHashCount(pwszSanitizedCAName, CSRH_CASIGCERT, &dwHashCount);
_JumpIfError(hr, error, "myGetCARegHashCount");
pdwCRLIndexes = (DWORD *) LocalAlloc(LMEM_FIXED, dwHashCount*sizeof(DWORD));
_JumpIfAllocFailed(pdwCRLIndexes, error);
hMyStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM_W,
X509_ASN_ENCODING,
NULL, // hProv
CERT_SYSTEM_STORE_LOCAL_MACHINE |
CERT_STORE_READONLY_FLAG |
CERT_STORE_ENUM_ARCHIVED_FLAG,
wszMY_CERTSTORE);
if (NULL == hMyStore)
{
hr = myHLastError();
_JumpError(hr, error, "CertOpenStore");
}
for(DWORD dwCount=0; dwCount<dwHashCount; dwCount++)
{
hr = myFindCACertByHashIndex(
hMyStore,
pwszSanitizedCAName,
CSRH_CASIGCERT,
dwCount,
&NameId,
&pccCert);
if (S_FALSE == hr)
{
continue;
}
_JumpIfError(hr, error, "myFindCACertByHashIndex");
if (MAXDWORD==NameId)
{
pdwCRLIndexes[dwCount] = dwCount;
}
else
{
pdwCRLIndexes[dwCount] = CANAMEIDTOIKEY(NameId);
}
CertFreeCertificateContext(pccCert);
pccCert = NULL;
}
// The index list looks like this: 0 1 2 2 3 4 5 5 5 6. Compact it
// in place, eliminating duplicates.
nCRLIndexes = 0;
for(DWORD dwCount=0; dwCount<dwHashCount;dwCount++)
{
if(dwCount>0 &&
pdwCRLIndexes[dwCount] == pdwCRLIndexes[dwCount-1])
{
continue;
}
pdwCRLIndexes[nCRLIndexes] = pdwCRLIndexes[dwCount];
nCRLIndexes++;
}
*pnCRLIndexes = nCRLIndexes;
*ppdwCRLIndexes = pdwCRLIndexes;
hr = S_OK;
error:
if(S_OK != hr &&
NULL != pdwCRLIndexes)
{
LocalFree(pdwCRLIndexes);
}
if(NULL != pccCert)
{
CertFreeCertificateContext(pccCert);
}
if (NULL != hMyStore)
{
CertCloseStore(hMyStore, CERT_CLOSE_STORE_CHECK_FLAG);
}
return hr;
}
HRESULT
CreateCDPAndAIAAndKRAEntry(
IN WCHAR const *pwszSanitizedCAName,
IN WCHAR const *pwszServerName,
IN DWORD iCert,
IN DWORD iCRL,
IN BYTE const *pbCert,
IN DWORD cbCert,
IN PSECURITY_DESCRIPTOR pSD,
IN PSECURITY_DESCRIPTOR pContainerSD)
{
HRESULT hr;
LDAP *pld = NULL;
BSTR strConfigDN = NULL;
BSTR strDomainDN = NULL;
WCHAR *pwszCDPDN = NULL;
WCHAR *pwszAIADN;
WCHAR *pwszKRADN;
WCHAR const *apwszIn[2];
WCHAR *apwszOut[2];
DWORD i;
DWORD dwDisp;
WCHAR *pwszError = NULL;
DWORD *pdwCRLIndexes = NULL;
DWORD nCRLIndexes;
ZeroMemory(apwszOut, sizeof(apwszOut));
hr = myLdapOpen(
NULL, // pwszDomainName
RLBF_REQUIRE_SECURE_LDAP, // dwFlags
&pld,
&strDomainDN,
&strConfigDN);
_JumpIfError(hr, error, "myLdapOpen");
DBGPRINT((DBG_SS_CERTLIBI, "DomainDN='%ws'\n", strDomainDN));
DBGPRINT((DBG_SS_CERTLIBI, "ConfigDN='%ws'\n", strConfigDN));
//+=====================================================================
// Create the CDP container and objects:
hr = GetValidCRLIndexes(
pwszSanitizedCAName,
&pdwCRLIndexes,
&nCRLIndexes);
_JumpIfError(hr, error, "GetValidCRLIndexes");
apwszIn[0] = g_wszCDPDNTemplate;
for(DWORD dwCount=0; dwCount<nCRLIndexes; dwCount++)
{
hr = myFormatCertsrvStringArray(
FALSE, // fURL
pwszServerName, // pwszServerName_p1_2
pwszSanitizedCAName,// pwszSanitizedName_p3_7
iCert, // iCert_p4
MAXDWORD, // iCertTarget_p4
strDomainDN, // pwszDomainDN_p5
strConfigDN, // pwszConfigDN_p6
pdwCRLIndexes[dwCount], // iCRL_p8
FALSE, // fDeltaCRL_p9
FALSE, // fDSAttrib_p10_11
1, // cStrings
(LPCWSTR *) apwszIn,// apwszStringsIn
apwszOut); // apwszStringsOut
_JumpIfError(hr, error, "myFormatCertsrvStringArray");
// attemp to create container just once
if(0==dwCount)
{
hr = myLdapCreateContainer(
pld,
apwszOut[0],
TRUE,
1,
pContainerSD,
&pwszError);
_JumpIfError(hr, error, "myLdapCreateContainer");
CSASSERT(NULL == pwszError);
}
DBGPRINT((DBG_SS_CERTLIBI, "CDPDN='%ws'\n", apwszOut[0]));
hr = myLdapCreateCDPObject(pld, apwszOut[0], pSD, &dwDisp, &pwszError);
_JumpIfErrorStr(hr, error, "myLdapCreateCDPObject", apwszOut[0]);
CSASSERT(NULL == pwszError);
LocalFree(apwszOut[0]);
apwszOut[0] = NULL;
}
//+=====================================================================
// Create the KRA and AIA containers and objects
apwszIn[0] = g_wszAIADNTemplate;
apwszIn[1] = g_wszKRADNTemplate;
// Format the KRA and AIA templates into real names
hr = myFormatCertsrvStringArray(
FALSE, // fURL
pwszServerName, // pwszServerName_p1_2
pwszSanitizedCAName, // pwszSanitizedName_p3_7
iCert, // iCert_p4
MAXDWORD, // iCertTarget_p4
strDomainDN, // pwszDomainDN_p5
strConfigDN, // pwszConfigDN_p6
iCRL, // iCRL_p8
FALSE, // fDeltaCRL_p9
FALSE, // fDSAttrib_p10_11
ARRAYSIZE(apwszIn), // cStrings
(LPCWSTR *) apwszIn, // apwszStringsIn
apwszOut); // apwszStringsOut
_JumpIfError(hr, error, "myFormatCertsrvStringArray");
pwszAIADN = apwszOut[0];
pwszKRADN = apwszOut[1];
DBGPRINT((DBG_SS_CERTLIBI, "AIADN='%ws'\n", pwszAIADN));
DBGPRINT((DBG_SS_CERTLIBI, "KRADN='%ws'\n", pwszKRADN));
//+=====================================================================
// Create the container and AIA object:
hr = myLdapCreateContainer(
pld,
pwszAIADN,
TRUE,
0,
pContainerSD,
&pwszError);
_JumpIfError(hr, error, "myLdapCreateContainer");
CSASSERT(NULL == pwszError);
hr = myLdapCreateCAObject(
pld,
pwszAIADN,
pbCert,
cbCert,
pSD,
&dwDisp,
&pwszError);
_JumpIfErrorStr(hr, error, "myLdapCreateCAObject", pwszAIADN);
hr = myLdapFilterCertificates(
pld,
pwszAIADN,
wszDSCACERTATTRIBUTE,
&dwDisp,
&pwszError);
_JumpIfErrorStr(hr, error, "myLdapFilterCertificates", pwszAIADN);
CSASSERT(NULL == pwszError);
//+=====================================================================
// Create the KRA container and object:
hr = myLdapCreateContainer(
pld,
pwszKRADN,
TRUE,
0,
pContainerSD,
&pwszError);
_JumpIfError(hr, error, "myLdapCreateContainer");
CSASSERT(NULL == pwszError);
hr = myLdapCreateUserObject(
pld,
pwszKRADN,
NULL,
0,
pSD,
LPC_KRAOBJECT,
&dwDisp,
&pwszError);
//_JumpIfErrorStr(hr, error, "myLdapCreateUserObject", pwszKRADN);
_PrintIfErrorStr(hr, "myLdapCreateUserObject", pwszKRADN);
CSASSERT(S_OK == hr || NULL != pwszError);
hr = S_OK;
error:
CSILOG(hr, IDS_ILOG_CREATECDP, pwszCDPDN, pwszError, NULL);
if (NULL != pdwCRLIndexes)
{
LocalFree(pdwCRLIndexes);
}
if (NULL != pwszError)
{
LocalFree(pwszError);
}
for (i = 0; i < ARRAYSIZE(apwszOut); i++)
{
if (NULL != apwszOut[i])
{
LocalFree(apwszOut[i]);
}
}
myLdapClose(pld, strDomainDN, strConfigDN);
return(hr);
}
HRESULT
CreateEnterpriseAndRootEntry(
IN WCHAR const *pwszSanitizedDSName,
IN CERT_CONTEXT const *pccPublish,
IN ENUM_CATYPES caType,
IN PSECURITY_DESCRIPTOR pSD,
IN PSECURITY_DESCRIPTOR pContainerSD)
{
HRESULT hr;
LDAP *pld = NULL;
BSTR strConfig = NULL;
BSTR strDomainDN = NULL;
WCHAR *pwszRootDN = NULL;
WCHAR *pwszEnterpriseDN = NULL;
PSECURITY_DESCRIPTOR pNTAuthSD = NULL;
DWORD cwc;
DWORD dwDisp;
WCHAR *pwszError = NULL;
if (!IsEnterpriseCA(caType) && !IsRootCA(caType))
{
hr = S_OK;
goto error;
}
hr = myLdapOpen(
NULL, // pwszDomainName
RLBF_REQUIRE_SECURE_LDAP, // dwFlags
&pld,
&strDomainDN,
&strConfig);
_JumpIfError(hr, error, "myLdapOpen");
cwc = WSZARRAYSIZE(L"CN=") +
wcslen(pwszSanitizedDSName) +
WSZARRAYSIZE(s_wszRootCAs) +
wcslen(strConfig);
pwszRootDN = (WCHAR *) LocalAlloc(LMEM_FIXED, (cwc + 1) * sizeof(WCHAR));
if (pwszRootDN == NULL)
{
hr = E_OUTOFMEMORY;
_JumpIfError(hr, error, "LocalAlloc");
}
wcscpy(pwszRootDN, L"CN=");
wcscat(pwszRootDN, pwszSanitizedDSName);
wcscat(pwszRootDN, s_wszRootCAs);
wcscat(pwszRootDN, strConfig);
CSASSERT(wcslen(pwszRootDN) == cwc);
cwc = wcslen(s_wszEnterpriseCAs) + wcslen(strConfig);
pwszEnterpriseDN = (WCHAR *) LocalAlloc(
LMEM_FIXED,
(cwc + 1) * sizeof(WCHAR));
if (pwszEnterpriseDN == NULL)
{
hr = E_OUTOFMEMORY;
_JumpIfError(hr, error, "LocalAlloc");
}
wcscpy(pwszEnterpriseDN, s_wszEnterpriseCAs);
wcscat(pwszEnterpriseDN, strConfig);
CSASSERT(wcslen(pwszEnterpriseDN) == cwc);
//+=====================================================================
// Create the root trust CA container and entry (Root only):
if (IsRootCA(caType))
{
DBGPRINT((DBG_SS_CERTLIBI, "Creating Services Containers: '%ws'\n", pwszRootDN));
hr = myLdapCreateContainer(
pld,
pwszRootDN,
TRUE,
1,
pContainerSD,
&pwszError);
_JumpIfError(hr, error, "myLdapCreateContainer");
CSASSERT(NULL == pwszError);
DBGPRINT((DBG_SS_CERTLIBI, "Creating DS Root Trust: '%ws'\n", pwszRootDN));
hr = myLdapCreateCAObject(
pld,
pwszRootDN,
pccPublish->pbCertEncoded,
pccPublish->cbCertEncoded,
pSD,
&dwDisp,
&pwszError);
_JumpIfErrorStr(hr, error, "myLdapCreateCAObject", pwszRootDN);
}
//+=====================================================================
// Create the NTAuth trust entry (Enterprise only):
if (IsEnterpriseCA(caType))
{
DBGPRINT((
DBG_SS_CERTLIBI,
"Creating DS Enterprise Trust: '%ws'\n",
pwszEnterpriseDN));
hr = myGetSDFromTemplate(WSZ_DEFAULT_NTAUTH_SECURITY, NULL, &pNTAuthSD);
_JumpIfError(hr, error, "myGetSDFromTemplate");
hr = myLdapCreateCAObject(
pld,
pwszEnterpriseDN,
NULL,
0,
pNTAuthSD,
&dwDisp,
&pwszError);
_JumpIfErrorStr(hr, error, "myLdapCreateCAObject", pwszEnterpriseDN);
hr = AddCertToAttribute(
pld,
pccPublish,
pwszEnterpriseDN,
wszDSCACERTATTRIBUTE,
FALSE, // fDelete
&dwDisp,
&pwszError);
_JumpIfErrorStr(hr, error, "AddCertToAttribute", pwszEnterpriseDN);
CSILOG(S_OK, IDS_ILOG_CREATENTAUTHTRUST, pwszEnterpriseDN, NULL, NULL);
}
error:
CSILOG(hr, IDS_ILOG_CREATEROOTTRUST, pwszRootDN, pwszError, NULL);
if (NULL != pwszError)
{
LocalFree(pwszError);
}
if (NULL != pwszEnterpriseDN)
{
LocalFree(pwszEnterpriseDN);
}
if (NULL != pwszRootDN)
{
LocalFree(pwszRootDN);
}
myLdapClose(pld, strDomainDN, strConfig);
if (NULL != pNTAuthSD)
{
LocalFree(pNTAuthSD);
}
return(hr);
}
#define wszCOLON L":"
// Suppress FILE URLs if a DS is available, as LDAP access within the
// enterprise should suffice, and http: should work outside the enterprise.
// Certs with too many URLs don't always fit on smart cards.
#define wszCRLPATHDEFAULT \
wszCERTENROLLSHAREPATH \
L"\\" \
wszFCSAPARM_SANITIZEDCANAME \
wszFCSAPARM_CRLFILENAMESUFFIX \
wszFCSAPARM_CRLDELTAFILENAMESUFFIX \
L".crl"
CSURLTEMPLATE const s_aRevURL[] = {
{
CSURL_SERVERPUBLISH | CSURL_SERVERPUBLISHDELTA | CSURL_ADDSYSTEM32DIR,
wszCRLPATHDEFAULT,
},
{
CSURL_SERVERPUBLISH | CSURL_SERVERPUBLISHDELTA | CSURL_ADDTOCERTCDP | CSURL_ADDTOFRESHESTCRL | CSURL_ADDTOCRLCDP | CSURL_DSONLY,
const_cast<WCHAR *>(g_wszzLDAPRevocationURLTemplate),
},
{
CSURL_ADDTOCERTCDP | CSURL_ADDTOFRESHESTCRL,
const_cast<WCHAR *>(g_wszHTTPRevocationURLTemplate),
},
{
CSURL_ADDTOCERTCDP | CSURL_ADDTOFRESHESTCRL | CSURL_NODS,
const_cast<WCHAR *>(g_wszFILERevocationURLTemplate),
},
#if 0
{
CSURL_SERVERPUBLISH | CSURL_SERVERPUBLISHDELTA | CSURL_DSONLY,
const_cast<WCHAR *>(g_wszCDPDNTemplate),
},
#endif
{ 0, NULL }
};
#define wszCACERTPATHDEFAULT \
wszCERTENROLLSHAREPATH \
L"\\" \
wszFCSAPARM_SERVERDNSNAME \
L"_" \
wszFCSAPARM_SANITIZEDCANAME \
wszFCSAPARM_CERTFILENAMESUFFIX \
L".crt"
CSURLTEMPLATE const s_aCACertURL[] = {
{
CSURL_SERVERPUBLISH | CSURL_ADDSYSTEM32DIR,
wszCACERTPATHDEFAULT,
},
{
CSURL_SERVERPUBLISH | CSURL_ADDTOCERTCDP | CSURL_DSONLY,
const_cast<WCHAR *>(g_wszzLDAPIssuerCertURLTemplate),
},
{
CSURL_ADDTOCERTCDP,
const_cast<WCHAR *>(g_wszHTTPIssuerCertURLTemplate),
},
{
CSURL_ADDTOCERTCDP | CSURL_NODS,
const_cast<WCHAR *>(g_wszFILEIssuerCertURLTemplate),
},
#if 0
{
CSURL_SERVERPUBLISH | CSURL_DSONLY,
const_cast<WCHAR *>(g_wszAIADNTemplate),
},
#endif
{ 0, NULL }
};
#define CSURL_DSDEPENDENT \
(CSURL_SERVERPUBLISH | \
CSURL_SERVERPUBLISHDELTA | \
CSURL_ADDTOCERTCDP | \
CSURL_ADDTOFRESHESTCRL)
HRESULT
GetPublicationURLTemplates(
IN CSURLTEMPLATE const *aTemplate,
IN BOOL fUseDS,
IN WCHAR const *pwszSystem32,
OUT WCHAR **ppwszz)
{
HRESULT hr;
WCHAR *pwszz;
DWORD cwc;
CSURLTEMPLATE const *pTemplate;
WCHAR awc[cwcDWORDSPRINTF];
DWORD Flags;
*ppwszz = NULL;
cwc = 1; // final trailing L'\0'
for (pTemplate = aTemplate; NULL != pTemplate->pwszURL; pTemplate++)
{
Flags = ~CSURL_INITMASK & pTemplate->Flags;
if ((!fUseDS && (CSURL_DSONLY & pTemplate->Flags)) ||
(fUseDS && (CSURL_NODS & pTemplate->Flags)))
{
Flags &= ~CSURL_DSDEPENDENT;
}
cwc += wsprintf(awc, L"%u", Flags);
cwc += WSZARRAYSIZE(wszCOLON);
if (CSURL_ADDSYSTEM32DIR & pTemplate->Flags)
{
cwc += wcslen(pwszSystem32);
}
cwc += wcslen(pTemplate->pwszURL);
cwc += 1; // trailing L'\0'
}
pwszz = (WCHAR *) LocalAlloc(LMEM_FIXED, cwc * sizeof(WCHAR));
if (NULL == pwszz)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
*ppwszz = pwszz;
for (pTemplate = aTemplate; NULL != pTemplate->pwszURL; pTemplate++)
{
Flags = ~CSURL_INITMASK & pTemplate->Flags;
if ((!fUseDS && (CSURL_DSONLY & pTemplate->Flags)) ||
(fUseDS && (CSURL_NODS & pTemplate->Flags)))
{
Flags &= ~CSURL_DSDEPENDENT;
}
DBGPRINT((
DBG_SS_CERTLIB,
"URL Template: %x %x:%ws\n",
Flags,
pTemplate->Flags,
pTemplate->pwszURL));
wsprintf(pwszz, L"%u", Flags);
wcscat(pwszz, wszCOLON);
if (CSURL_ADDSYSTEM32DIR & pTemplate->Flags)
{
wcscat(pwszz, pwszSystem32);
}
wcscat(pwszz, pTemplate->pwszURL);
pwszz += wcslen(pwszz) + 1; // skip L'\0'
}
*pwszz = L'\0';
CSASSERT(cwc == (DWORD) (pwszz - *ppwszz + 1));
#ifdef DBG_CERTSRV_DEBUG_PRINT
{
DWORD i = 0;
WCHAR const *pwsz;
for (pwsz = *ppwszz; L'\0' != *pwsz; pwsz += wcslen(pwsz) + 1)
{
DBGPRINT((
DBG_SS_CERTLIB,
"URL Template[%u]: %ws\n",
i,
pwsz));
i++;
}
}
#endif // DBG_CERTSRV_DEBUG_PRINT
hr = S_OK;
error:
return(hr);
}
HRESULT
csiGetCRLPublicationURLTemplates(
IN BOOL fUseDS,
IN WCHAR const *pwszSystem32,
OUT WCHAR **ppwszz)
{
HRESULT hr;
hr = GetPublicationURLTemplates(s_aRevURL, fUseDS, pwszSystem32, ppwszz);
_JumpIfError(hr, error, "GetPublicationURLTemplates");
error:
return(hr);
}
HRESULT
csiGetCACertPublicationURLTemplates(
IN BOOL fUseDS,
IN WCHAR const *pwszSystem32,
OUT WCHAR **ppwszz)
{
HRESULT hr;
hr = GetPublicationURLTemplates(s_aCACertURL, fUseDS, pwszSystem32, ppwszz);
_JumpIfError(hr, error, "GetPublicationURLTemplates");
error:
return(hr);
}
HRESULT
csiSetupCAInDS(
IN WCHAR const *pwszCAServer,
IN WCHAR const *pwszSanitizedCAName,
IN WCHAR const *pwszCADisplayName,
IN BOOL fLoadDefaultTemplates,
IN ENUM_CATYPES caType,
IN DWORD iCert,
IN DWORD iCRL,
IN BOOL fRenew,
IN CERT_CONTEXT const *pCert)
{
HRESULT hr;
HCAINFO hCAInfo = NULL;
WCHAR *pCAProp[2];
WCHAR *pCertSubjectString = NULL;
CAutoLPWSTR wszNameBuffer;
WCHAR wszDomainNameBuffer[MAX_PATH];
DWORD cDomainNameBuffer;
DWORD cbSid;
BYTE pSid[MAX_SID_LEN];
SID_NAME_USE SidUse;
WCHAR *pwszStringSid = NULL;
PSECURITY_DESCRIPTOR pContainerSD = NULL;
PSECURITY_DESCRIPTOR pCDPSD = NULL;
CERT_CONTEXT const *pCertForDS = NULL;
WCHAR *pwszSanitizedDSName = NULL;
hr = mySanitizedNameToDSName(pwszSanitizedCAName, &pwszSanitizedDSName);
_JumpIfError(hr, error, "mySanitizedNameToDSName");
// Get the SID of the local machine.
hr = myGetComputerObjectName(NameSamCompatible, &wszNameBuffer);
_JumpIfError(hr, error, "myGetComputerObjectName");
DBGPRINT((DBG_SS_CERTLIB, "GetComputerObjectName: '%ws'\n", wszNameBuffer));
cbSid = sizeof(pSid);
cDomainNameBuffer = ARRAYSIZE(wszDomainNameBuffer);
if (!LookupAccountName(NULL,
wszNameBuffer,
pSid,
&cbSid,
wszDomainNameBuffer,
&cDomainNameBuffer,
&SidUse))
{
hr = myHLastError();
_JumpErrorStr(hr, error, "LookupAccountName", wszNameBuffer);
}
if (!myConvertSidToStringSid(pSid, &pwszStringSid))
{
hr = myHLastError();
_JumpError(hr, error, "myConvertSidToStringSid");
}
// get default DS CDP security descriptor
hr = myGetSDFromTemplate(WSZ_DEFAULT_CDP_DS_SECURITY,
pwszStringSid,
&pCDPSD);
_JumpIfError(hr, error, "myGetSDFromTemplate");
// get default DS AIA security descriptor
hr = myGetSDFromTemplate(WSZ_DEFAULT_CA_DS_SECURITY,
NULL,
&pContainerSD);
_JumpIfError(hr, error, "myGetSDFromTemplate");
hr = CreateEnterpriseAndRootEntry(
pwszSanitizedDSName,
pCert,
caType,
pContainerSD,
pContainerSD);
_JumpIfError(hr, error, "CreateEnterpriseAndRootEntry");
hr = CreateCDPAndAIAAndKRAEntry(
pwszSanitizedCAName,
pwszCAServer,
iCert,
iCRL,
pCert->pbCertEncoded,
pCert->cbCertEncoded,
pCDPSD,
pContainerSD);
_JumpIfError(hr, error, "CreateCDPAndAIAAndKRAEntry");
// Add enterprise
// service publish entry
hr = CAFindByName(
pwszSanitizedDSName,
NULL,
CA_FIND_INCLUDE_UNTRUSTED | CA_FIND_INCLUDE_NON_TEMPLATE_CA,
&hCAInfo);
if (S_OK != hr || NULL == hCAInfo)
{
hCAInfo = NULL;
fRenew = FALSE; // recreate security settings, etc.
hr = CACreateNewCA(pwszSanitizedDSName, NULL, NULL, &hCAInfo);
_JumpIfError(hr, error, "CACreateNewCA");
if (NULL == hCAInfo)
{
hr = E_INVALIDARG;
_JumpError(hr, error, "hCAInfo(NULL)");
}
}
if (!fRenew)
{
pCAProp[0] = const_cast<WCHAR *>(pwszCAServer);
pCAProp[1] = NULL;
hr = CASetCAProperty(hCAInfo, CA_PROP_DNSNAME, pCAProp);
_JumpIfError(hr, error, "CASetCAProperty(CA_PROP_DNSNAME)");
pCAProp[0] = const_cast<WCHAR *>(pwszCADisplayName);
pCAProp[1] = NULL;
hr = CASetCAProperty(hCAInfo, CA_PROP_DISPLAY_NAME, pCAProp);
_JumpIfError(hr, error, "CASetCAProperty(CA_PROP_DISPLAY_NAME)");
hr = myCertNameToStr(
X509_ASN_ENCODING,
&pCert->pCertInfo->Subject,
CERT_X500_NAME_STR | CERT_NAME_STR_NO_QUOTING_FLAG,
&pCertSubjectString);
_JumpIfError(hr, error, "myCertNameToStr");
pCAProp[0] = pCertSubjectString;
pCAProp[1] = NULL;
hr = CASetCAProperty(hCAInfo, CA_PROP_CERT_DN, pCAProp);
_JumpIfError(hr, error, "CASetCAProperty(CA_PROP_CERT_DN)");
switch (caType)
{
case ENUM_ENTERPRISE_ROOTCA:
hr = CASetCAFlags(hCAInfo, CA_FLAG_SUPPORTS_NT_AUTHENTICATION);
_JumpIfError(hr, error, "CASetCAFlags");
break;
case ENUM_ENTERPRISE_SUBCA:
hr = CASetCAFlags(hCAInfo, CA_FLAG_SUPPORTS_NT_AUTHENTICATION);
_JumpIfError(hr, error, "CASetCAFlags");
break;
case ENUM_STANDALONE_ROOTCA:
hr = CASetCAFlags(hCAInfo, CA_FLAG_NO_TEMPLATE_SUPPORT | CA_FLAG_CA_SUPPORTS_MANUAL_AUTHENTICATION);
_JumpIfError(hr, error, "CASetCAFlags");
break;
case ENUM_STANDALONE_SUBCA:
hr = CASetCAFlags(hCAInfo, CA_FLAG_NO_TEMPLATE_SUPPORT | CA_FLAG_CA_SUPPORTS_MANUAL_AUTHENTICATION);
_JumpIfError(hr, error, "CASetCAFlags");
break;
default:
hr = E_INVALIDARG;
_JumpError(hr, error, "Invalid CA Type");
}
if (IsEnterpriseCA(caType))
{
hr = CASetCAProperty(
hCAInfo,
CA_PROP_CERT_TYPES,
fLoadDefaultTemplates?
(FIsAdvancedServer()?
s_apwszCertTypeAdvancedServer :
s_apwszCertTypeServer):
s_apwszCertTypeEmpty);
_JumpIfError(hr, error, "CASetCAProperty(CA_PROP_CERT_TYPES)");
}
}
// create a new cert context without key prov info
pCertForDS = CertCreateCertificateContext(X509_ASN_ENCODING,
pCert->pbCertEncoded,
pCert->cbCertEncoded);
if (NULL == pCertForDS)
{
hr = myHLastError();
_JumpError(hr, error, "CertCreateCertificateContext");
}
hr = CASetCACertificate(hCAInfo, pCertForDS);
_JumpIfError(hr, error, "CASetCACertificate");
if (!fRenew)
{
hr = CASetCASecurity(hCAInfo, pCDPSD);
_JumpIfError(hr, error, "CASetCASecurity");
}
hr = CAUpdateCA(hCAInfo);
_JumpIfError(hr, error, "CAUpdateCA");
error:
if (NULL != pwszStringSid)
{
LocalFree(pwszStringSid);
}
if (NULL != pwszSanitizedDSName)
{
LocalFree(pwszSanitizedDSName);
}
if (NULL != pCertSubjectString)
{
LocalFree(pCertSubjectString);
}
if (NULL != hCAInfo)
{
CACloseCA(hCAInfo);
}
if (NULL != pCDPSD)
{
LocalFree(pCDPSD);
}
if (NULL != pContainerSD)
{
LocalFree(pContainerSD);
}
if (NULL != pCertForDS)
{
CertFreeCertificateContext(pCertForDS);
}
CSILOG(hr, IDS_ILOG_PUBLISHCA, NULL, NULL, NULL);
return(hr);
}
BOOL
csiIsAnyDSCAAvailable(VOID)
{
// this is an expensive call; cache result
static BOOL available = FALSE; // static inits to FALSE
static BOOL fKnowAvailable = FALSE; // static inits to FALSE
HCAINFO hCAInfo = NULL;
if (!fKnowAvailable)
{
HRESULT hr;
fKnowAvailable = TRUE;
hr = CAEnumFirstCA(
NULL,
CA_FIND_INCLUDE_UNTRUSTED | CA_FIND_INCLUDE_NON_TEMPLATE_CA,
&hCAInfo);
_JumpIfError(hr, error, "CAEnumFirstCA");
if (NULL == hCAInfo)
{
goto error;
}
available = TRUE;
}
error:
if (NULL != hCAInfo)
CACloseCA(hCAInfo);
return available;
}
HRESULT
csiSetKeyContainerSecurity(
IN HCRYPTPROV hProv)
{
HRESULT hr;
hr = mySetKeyContainerSecurity(hProv);
_JumpIfError(hr, error, "mySetKeyContainerSecurity");
error:
CSILOG(hr, IDS_ILOG_SETKEYSECURITY, NULL, NULL, NULL);
return(hr);
}
HRESULT
csiSetAdminOnlyFolderSecurity(
IN LPCWSTR szFolderPath,
IN BOOL fAllowEveryoneRead,
IN BOOL fUseDS)
{
HRESULT hr;
PSECURITY_DESCRIPTOR pSD = NULL;
// choose which access we want to allow
LPCWSTR pwszDescriptor;
if (fUseDS)
if (fAllowEveryoneRead)
pwszDescriptor = WSZ_DEFAULT_SF_USEDS_EVERYONEREAD_SECURITY;
else
pwszDescriptor = WSZ_DEFAULT_SF_USEDS_SECURITY;
else
if (fAllowEveryoneRead)
pwszDescriptor = WSZ_DEFAULT_SF_EVERYONEREAD_SECURITY;
else
pwszDescriptor = WSZ_DEFAULT_SF_SECURITY;
hr = myGetSDFromTemplate(pwszDescriptor, NULL, &pSD);
_JumpIfError(hr, error, "myGetSDFromTemplate");
if (!SetFileSecurity(
szFolderPath,
DACL_SECURITY_INFORMATION,
pSD))
{
hr = myHLastError();
_JumpError(hr, error, "SetFileSecurity");
}
hr = S_OK;
error:
if (NULL != pSD)
{
LocalFree(pSD);
}
CSILOG(hr, IDS_ILOG_SETADMINONLYFOLDERSECURITY, szFolderPath, NULL, NULL);
return(hr);
}
HRESULT
csiSaveCertAndKeys(
IN CERT_CONTEXT const *pCert,
IN HCERTSTORE hAdditionalStore,
IN CRYPT_KEY_PROV_INFO const *pkpi,
IN ENUM_CATYPES CAType)
{
HRESULT hr;
CERT_CHAIN_CONTEXT const *pCertChain = NULL;
CERT_CHAIN_PARA CertChainPara;
HCERTSTORE hNTAuthStore = NULL;
ZeroMemory(&CertChainPara, sizeof(CertChainPara));
CertChainPara.cbSize = sizeof(CertChainPara);
if (!CertGetCertificateChain(
HCCE_LOCAL_MACHINE,
pCert,
NULL,
hAdditionalStore,
&CertChainPara,
0,
NULL,
&pCertChain))
{
hr = myHLastError();
_JumpError(hr, error, "CertGetCertificateChain");
}
// make sure there is at least 1 simple chain
if (0 == pCertChain->cChain)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
_JumpError(hr, error, "pCertChain->cChain");
}
hr = mySaveChainAndKeys(
pCertChain->rgpChain[0],
wszMY_CERTSTORE,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
pkpi,
NULL);
_JumpIfError(hr, error, "mySaveChainAndKeys");
if (IsEnterpriseCA(CAType))
{
hNTAuthStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM_REGISTRY_W,
X509_ASN_ENCODING,
NULL, // hProv
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
wszNTAUTH_CERTSTORE);
if (NULL == hNTAuthStore)
{
hr = myHLastError();
_JumpErrorStr(hr, error, "CertOpenStore", wszNTAUTH_CERTSTORE);
}
if (!CertAddEncodedCertificateToStore(
hNTAuthStore,
X509_ASN_ENCODING,
pCert->pbCertEncoded,
pCert->cbCertEncoded,
CERT_STORE_ADD_REPLACE_EXISTING,
NULL))
{
hr = myHLastError();
_JumpError(hr, error, "CertAddEncodedCertificateToStore");
}
}
error:
if (pCertChain != NULL)
{
CertFreeCertificateChain(pCertChain);
}
if (NULL != hNTAuthStore)
{
CertCloseStore(hNTAuthStore, CERT_CLOSE_STORE_CHECK_FLAG);
}
return(hr);
}
HRESULT
AddCertBlobToMemAndRootStores(
IN OUT HCERTSTORE hStore,
IN BYTE const *pb,
IN DWORD cb)
{
HRESULT hr;
CERT_CONTEXT const *pCert = NULL;
HCERTSTORE hStoreRoot = NULL;
BOOL fRoot;
pCert = CertCreateCertificateContext(X509_ASN_ENCODING, pb, cb);
if (NULL == pCert)
{
hr = myHLastError();
_JumpError(hr, error, "CertCreateCertificateContext");
}
if (!CertAddCertificateContextToStore(
hStore,
pCert,
CERT_STORE_ADD_REPLACE_EXISTING,
NULL))
{
hr = myHLastError();
_JumpError(hr, error, "CertAddCertificateContextToStore");
}
fRoot = CertCompareCertificateName(
X509_ASN_ENCODING,
&pCert->pCertInfo->Subject,
&pCert->pCertInfo->Issuer);
if (fRoot)
{
hStoreRoot = CertOpenStore(
CERT_STORE_PROV_SYSTEM_REGISTRY_W,
X509_ASN_ENCODING,
NULL, // hProv
CERT_SYSTEM_STORE_LOCAL_MACHINE |
CERT_STORE_ENUM_ARCHIVED_FLAG,
wszROOT_CERTSTORE);
if (NULL == hStoreRoot)
{
hr = myHLastError();
_JumpError(hr, error, "CertOpenStore");
}
if (!CertAddCertificateContextToStore(
hStoreRoot,
pCert,
CERT_STORE_ADD_REPLACE_EXISTING,
NULL))
{
hr = myHLastError();
_JumpError(hr, error, "CertAddCertificateContextToStore");
}
}
hr = S_OK;
error:
if (NULL != pCert)
{
CertFreeCertificateContext(pCert);
}
if (NULL != hStoreRoot)
{
CertCloseStore(hStoreRoot, CERT_CLOSE_STORE_CHECK_FLAG);
}
return(hr);
}
HRESULT
LoadMissingCertBlob(
IN OUT HCERTSTORE hStore,
IN BYTE const *pb,
IN DWORD cb)
{
HRESULT hr;
BYTE *pbDecoded = NULL;
DWORD cbDecoded;
CERT_CONTEXT const *pCert = NULL;
HCERTSTORE hStorePKCS7 = NULL;
BOOL fTryPKCS7 = TRUE;
if (myDecodeObject(
X509_ASN_ENCODING,
X509_CERT_TO_BE_SIGNED,
pb,
cb,
CERTLIB_USE_LOCALALLOC,
(VOID **) &pbDecoded,
&cbDecoded))
{
hr = AddCertBlobToMemAndRootStores(hStore, pb, cb);
_JumpIfError(hr, error, "AddCertBlobToMemAndRootStores");
fTryPKCS7 = FALSE;
}
else
if (myDecodeObject(
X509_ASN_ENCODING,
PKCS_CONTENT_INFO_SEQUENCE_OF_ANY,
pb,
cb,
CERTLIB_USE_LOCALALLOC,
(VOID **) &pbDecoded,
&cbDecoded))
{
CRYPT_CONTENT_INFO_SEQUENCE_OF_ANY const *pSeq;
DWORD iCert;
pSeq = (CRYPT_CONTENT_INFO_SEQUENCE_OF_ANY const *) pbDecoded;
if (0 == strcmp(szOID_NETSCAPE_CERT_SEQUENCE, pSeq->pszObjId))
{
fTryPKCS7 = FALSE;
for (iCert = 0; iCert < pSeq->cValue; iCert++)
{
hr = AddCertBlobToMemAndRootStores(
hStore,
pSeq->rgValue[iCert].pbData,
pSeq->rgValue[iCert].cbData);
_JumpIfError(hr, error, "AddCertBlobToMemAndRootStores");
}
}
}
if (fTryPKCS7)
{
CRYPT_DATA_BLOB blobPKCS7;
blobPKCS7.pbData = const_cast<BYTE *>(pb);
blobPKCS7.cbData = cb;
hStorePKCS7 = CertOpenStore(
CERT_STORE_PROV_PKCS7,
PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
NULL, // hCryptProv
0, // dwFlags
&blobPKCS7);
if (NULL == hStorePKCS7)
{
hr = myHLastError();
_JumpError(hr, error, "CertOpenStore");
}
for (;;)
{
pCert = CertEnumCertificatesInStore(hStorePKCS7, pCert);
if (NULL == pCert)
{
break;
}
hr = AddCertBlobToMemAndRootStores(
hStore,
pCert->pbCertEncoded,
pCert->cbCertEncoded);
_JumpIfError(hr, error, "AddCertBlobToMemAndRootStores");
}
}
hr = S_OK;
error:
if (NULL != pbDecoded)
{
LocalFree(pbDecoded);
}
if (NULL != pCert)
{
CertFreeCertificateContext(pCert);
}
if (NULL != hStorePKCS7)
{
CertCloseStore(hStorePKCS7, CERT_CLOSE_STORE_CHECK_FLAG);
}
return(hr);
}
HRESULT
LoadMissingCert(
IN HINSTANCE hInstance,
IN HWND hwnd,
IN OUT HCERTSTORE hStore,
IN OPTIONAL WCHAR const *pwszMissingIssuer)
{
HRESULT hr;
WCHAR *pwszFile = NULL;
BYTE *pb = NULL;
DWORD cb;
hr = myGetOpenFileNameEx(
hwnd,
hInstance,
IDS_CAHIER_INSTALL_MISIINGCERT_TITLE,
pwszMissingIssuer,
IDS_CAHIER_CERTFILE_FILTER,
0, // no def ext
OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
NULL, // no default file
&pwszFile);
if (S_OK == hr && NULL == pwszFile)
{
hr = E_INVALIDARG;
}
_JumpIfError(hr, error, "myGetOpenFileName");
hr = DecodeFileW(pwszFile, &pb, &cb, CRYPT_STRING_ANY);
_JumpIfError(hr, error, "DecodeFileW");
hr = LoadMissingCertBlob(hStore, pb, cb);
_JumpIfError(hr, error, "LoadMissingCertBlob");
error:
if (NULL != pb)
{
LocalFree(pb);
}
if (NULL != pwszFile)
{
LocalFree(pwszFile);
}
return(hr);
}
HRESULT
InstallCAChain(
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd,
IN PCCERT_CONTEXT pCert,
IN CRYPT_KEY_PROV_INFO const *pKeyProvInfo,
IN ENUM_CATYPES CAType,
OPTIONAL IN BYTE const *pbChain,
IN DWORD cbChain)
{
HRESULT hr;
WCHAR *pwszMissingIssuer = NULL;
HCERTSTORE hTempMemoryStore = NULL;
if (IsSubordinateCA(CAType))
{
hTempMemoryStore = CertOpenStore(
CERT_STORE_PROV_MEMORY,
X509_ASN_ENCODING,
NULL,
0,
NULL);
if (NULL == hTempMemoryStore)
{
hr = myHLastError();
_JumpError(hr, error, "CertOpenSystemStore");
}
if (NULL != pbChain)
{
hr = LoadMissingCertBlob(hTempMemoryStore, pbChain, cbChain);
_JumpIfError(hr, error, "LoadMissingCertBlob");
}
// see if CA chain can be built
for (;;)
{
if (NULL != pwszMissingIssuer)
{
LocalFree(pwszMissingIssuer);
pwszMissingIssuer = NULL;
}
hr = myVerifyCertContext(
pCert, // pCert
0, // dwFlags
0, // cUsageOids
NULL, // apszUsageOids
HCCE_LOCAL_MACHINE, // hChainEngine
hTempMemoryStore, // hAdditionalStore
&pwszMissingIssuer);
if (S_OK != hr)
{
if (NULL != pwszMissingIssuer)
{
if (IDCANCEL == CertMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_INCOMPLETECHAIN,
hr,
MB_OKCANCEL | MB_ICONWARNING,
pwszMissingIssuer) ||
fUnattended)
{
_JumpError(hr, error, "cannot build CA chain");
}
hr = LoadMissingCert(
hInstance,
hwnd,
hTempMemoryStore,
pwszMissingIssuer);
_PrintIfError(hr, "LoadMissingCert");
continue;
}
else
{
// recommend not continue
if (IDCANCEL == CertMessageBox(
hInstance,
fUnattended,
hwnd,
CERT_E_UNTRUSTEDROOT == hr?
IDS_ERR_UNTRUSTEDROOT :
IDS_ERR_INVALIDCHAIN,
hr,
MB_OKCANCEL | MB_ICONWARNING,
NULL))
{
_JumpError(hr, error, "cannot verify CA chain");
}
break;
}
}
break;
}
}
hr = csiSaveCertAndKeys(pCert, hTempMemoryStore, pKeyProvInfo, CAType);
if (S_OK != hr)
{
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_CERTADDCERTIFICATECONTEXTTOSTORE,
hr,
NULL);
_JumpError(hr, error, "csiSaveCertAndKeys");
}
error:
if (NULL != pwszMissingIssuer)
{
LocalFree(pwszMissingIssuer);
}
if (NULL != hTempMemoryStore)
{
CertCloseStore(hTempMemoryStore, CERT_CLOSE_STORE_CHECK_FLAG);
}
return(hr);
}
HRESULT
VerifyPublicKeyMatch(
IN CERT_CONTEXT const *pCert,
IN CRYPT_KEY_PROV_INFO const *pKeyProvInfo)
{
HRESULT hr;
hr = myVerifyPublicKey(
NULL, // pCert
FALSE, // fV1Cert
pKeyProvInfo,
&pCert->pCertInfo->SubjectPublicKeyInfo,
NULL); // pfMatchingKey
return(S_OK);
}
HRESULT
BuildCAChainFromCert(
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd,
IN CRYPT_KEY_PROV_INFO const *pKeyProvInfo,
IN WCHAR const *pwszSanitizedCAName,
IN WCHAR const *pwszCommonName,
IN const ENUM_CATYPES CAType,
IN DWORD iCert,
IN DWORD iCRL,
OPTIONAL IN BYTE const *pbChain,
IN DWORD cbChain,
IN CERT_CONTEXT const *pCert)
{
HRESULT hr;
UINT idserr;
CERT_NAME_INFO *pNameInfo = NULL;
DWORD cbNameInfo;
WCHAR const *pwszCN;
HCERTSTORE hMyStore = NULL;
CERT_CONTEXT const *pccPrevious = NULL;
// make sure the cert file matches current ca name
if (!myDecodeName(
X509_ASN_ENCODING,
X509_UNICODE_NAME,
pCert->pCertInfo->Subject.pbData,
pCert->pCertInfo->Subject.cbData,
CERTLIB_USE_LOCALALLOC,
&pNameInfo,
&cbNameInfo))
{
hr = myHLastError();
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_MYDECODENAME,
hr,
NULL);
_JumpError(hr, error, "myDecodeName");
}
hr = myGetCertNameProperty(FALSE, pNameInfo, szOID_COMMON_NAME, &pwszCN);
_PrintIfError(hr, "myGetCertNameProperty");
if (S_OK == hr && 0 != lstrcmp(pwszCommonName, pwszCN))
{
hr = E_INVALIDARG;
_PrintErrorStr(hr, "lstrcmp", pwszCN);
}
idserr = IDS_ERR_NOT_MATCH_COMMONNAME;
// If renewing and reusing the old key, verify the binary subject matches
// the previous cert subject, to prevent CRL Issuer and cert Issuer
// mismatches when verifying chains.
if (S_OK == hr && 0 < iCert && iCert != iCRL)
{
DWORD NameId;
hMyStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM_W,
X509_ASN_ENCODING,
NULL, // hProv
CERT_SYSTEM_STORE_LOCAL_MACHINE |
CERT_STORE_MAXIMUM_ALLOWED_FLAG |
CERT_STORE_READONLY_FLAG,
wszMY_CERTSTORE);
if (NULL == hMyStore)
{
hr = myHLastError();
_JumpError(hr, error, "CertOpenStore");
}
hr = myFindCACertByHashIndex(
hMyStore,
pwszSanitizedCAName,
CSRH_CASIGCERT,
iCert - 1,
&NameId,
&pccPrevious);
_PrintIfError(hr, "myFindCACertByHashIndex");
if (S_OK == hr &&
!CertCompareCertificateName(
X509_ASN_ENCODING,
&pCert->pCertInfo->Subject,
&pccPrevious->pCertInfo->Subject))
{
hr = E_INVALIDARG;
idserr = IDS_ERR_NOT_MATCH_BINARYNAME;
_PrintErrorStr(hr, "CertCompareCertificateName", pwszCN);
}
}
if (S_OK != hr)
{
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
idserr,
hr,
NULL);
_JumpError(hr, error, "cert common/binary name mismatch");
}
hr = myVerifyPublicKey(
NULL, // pCert
FALSE, // fV1Cert
pKeyProvInfo,
&pCert->pCertInfo->SubjectPublicKeyInfo,
NULL); // pfMatchingKey
if (S_OK != hr)
{
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_NOT_MATCH_KEY,
hr,
NULL);
_JumpError(hr, error, "myVerifyPublicKey");
}
hr = IsCACert(hInstance, fUnattended, hwnd, pCert, CAType);
_JumpIfError(hr, error, "IsCACert");
hr = InstallCAChain(
hInstance,
fUnattended,
hwnd,
pCert,
pKeyProvInfo,
CAType,
pbChain,
cbChain);
_JumpIfError(hr, error, "InstallCAChain");
error:
if (NULL != pccPrevious)
{
CertFreeCertificateContext(pccPrevious);
}
if (NULL != hMyStore)
{
CertCloseStore(hMyStore, CERT_CLOSE_STORE_CHECK_FLAG);
}
if (NULL != pNameInfo)
{
LocalFree(pNameInfo);
}
CSILOG(hr, IDS_ILOG_SAVECERTANDKEYS, NULL, NULL, NULL);
return(hr);
}
HRESULT
csiFinishInstallationFromPKCS7(
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd,
IN WCHAR const *pwszSanitizedCAName,
IN WCHAR const *pwszCACommonName,
IN CRYPT_KEY_PROV_INFO const *pKeyProvInfo,
IN ENUM_CATYPES CAType,
IN DWORD iCert,
IN DWORD iCRL,
IN BOOL fUseDS,
IN BOOL fRenew,
IN WCHAR const *pwszServerName,
IN BYTE const *pbChainOrCert,
IN DWORD cbChainOrCert,
OPTIONAL IN WCHAR const *pwszCACertFile)
{
HRESULT hr;
CERT_CONTEXT const *pCert = NULL;
WCHAR *pwszWebCACertFile = NULL;
WCHAR *pwszKeyContainer = NULL;
WCHAR wszTemp[MAX_PATH];
WCHAR wszBuffer[MAX_PATH];
DWORD NameId;
WCHAR *pwszRequestFile = NULL;
DWORD cwc;
hr = E_FAIL;
if (!IsRootCA(CAType)) // skip PKCS7 code for known raw X509 root cert
{
hr = ExtractCACertFromPKCS7(
pwszCACommonName,
pbChainOrCert,
cbChainOrCert,
&pCert);
_PrintIfError(hr, "ExtractCACertFromPKCS7");
}
if (NULL == pCert)
{
pCert = CertCreateCertificateContext(
X509_ASN_ENCODING,
pbChainOrCert,
cbChainOrCert);
if (NULL == pCert)
{
hr = myHLastError();
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_CERTCREATECERTIFICATECONTEXT,
hr,
NULL);
_JumpError(hr, error, "CertCreateCertificateContext");
}
pbChainOrCert = NULL; // Don't need to process this cert any further
}
hr = myGetNameId(pCert, &NameId);
_PrintIfError(hr, "myGetNameId");
if (S_OK == hr && MAKECANAMEID(iCert, iCRL) != NameId)
{
// get request file name
hr = csiGetCARequestFileName(
hInstance,
hwnd,
pwszSanitizedCAName,
iCert,
iCRL,
&pwszRequestFile);
_PrintIfError(hr, "csiGetCARequestFileName");
hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_RENEWEDCERTCAVERSION,
hr,
pwszRequestFile);
_JumpError(hr, error, "CA Version");
}
// build a chain and install it
hr = BuildCAChainFromCert(
hInstance,
fUnattended,
hwnd,
pKeyProvInfo,
pwszSanitizedCAName,
pwszCACommonName,
CAType,
iCert,
iCRL,
pbChainOrCert,
cbChainOrCert,
pCert);
_JumpIfError(hr, error, "BuildCAChainFromCert");
// store CA cert hash
hr = mySetCARegHash(pwszSanitizedCAName, CSRH_CASIGCERT, iCert, pCert);
_JumpIfError(hr, error, "mySetCARegHash");
if (fUseDS)
{
// save in ds
hr = csiSetupCAInDS(
pwszServerName,
pwszSanitizedCAName,
pwszCACommonName,
TRUE,
CAType,
iCert,
iCRL,
fRenew,
pCert);
_JumpIfError(hr, error, "csiSetupCAInDS");
}
if (NULL != pwszCACertFile)
{
// write this CA cert into shared folder
if (!DeleteFile(pwszCACertFile))
{
hr = myHLastError();
_PrintErrorStr2(
hr,
"DeleteFile",
pwszCACertFile,
HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
}
if (!csiWriteDERToFile(
pwszCACertFile,
(BYTE *) pCert->pbCertEncoded,
pCert->cbCertEncoded,
hInstance,
fUnattended,
hwnd))
{
hr = myHLastError();
_PrintErrorStr(hr, "csiWriteDERToFile", pwszCACertFile);
}
}
// write cert file for web pages
cwc = GetEnvironmentVariable(L"SystemRoot", wszTemp, ARRAYSIZE(wszTemp));
if (0 == cwc || ARRAYSIZE(wszTemp) <= cwc)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_ENV_NOT_SET,
hr,
NULL);
_JumpError(hr, error, "GetEnvironmentVariable");
}
if(ARRAYSIZE(wszBuffer)<wcslen(wszTemp)+wcslen(L"\\System32\\")+
wcslen(wszCERTENROLLSHAREPATH)+1)
{
hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
_JumpError(hr, error, "file name too long");
}
wcscpy(wszBuffer, wszTemp);
wcscat(wszBuffer, L"\\System32\\" wszCERTENROLLSHAREPATH);
hr = csiBuildFileName(
wszBuffer,
pwszSanitizedCAName,
L".crt",
iCert,
&pwszWebCACertFile,
hInstance,
fUnattended,
NULL);
_JumpIfError(hr, error, "csiBuildFileName");
hr = EncodeToFileW(
pwszWebCACertFile,
pCert->pbCertEncoded,
pCert->cbCertEncoded,
DECF_FORCEOVERWRITE | CRYPT_STRING_BINARY);
if (S_OK != hr)
{
CertErrorMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_WRITEDERTOFILE,
hr,
pwszWebCACertFile);
_JumpError(hr, error, "EncodeToFileW");
}
// Set the security on the ds/registry/files etc.
if (!fRenew)
{
hr = myAllocIndexedName(
pwszSanitizedCAName,
iCRL,
MAXDWORD, // IndexTarget
&pwszKeyContainer);
_JumpIfError(hr, error, "myAllocIndexedName");
hr = csiInitializeCertSrvSecurity(
pwszSanitizedCAName,
fUseDS,
fUseDS); // set DS security if using DS
_JumpIfError(hr, error, "csiInitializeCertSrvSecurity");
}
error:
if (NULL != pCert)
{
CertFreeCertificateContext(pCert);
}
if (NULL != pwszRequestFile)
{
LocalFree(pwszRequestFile);
}
if (NULL != pwszKeyContainer)
{
LocalFree(pwszKeyContainer);
}
if (NULL != pwszWebCACertFile)
{
LocalFree(pwszWebCACertFile);
}
return(hr);
}
HRESULT
FormRequestHelpMessage(
IN HINSTANCE hInstance,
IN LONG lRequestId,
IN BSTR bStrMsgFromServer,
IN WCHAR const *pwszParentConfig,
OUT WCHAR **ppwszHelpMsg)
{
#define wszHELPNEWLINE L"\n"
#define wszCOMMASPACE L", "
HRESULT hr;
WCHAR wszRequestIdValue[16];
WCHAR *pwszMsgConfigPrefix = NULL;
WCHAR *pwszMsgRequestIdPrefix = NULL;
WCHAR *pwszHelpMsg = NULL;
DWORD cwc;
*ppwszHelpMsg = NULL;
// load some format strings in help msg
hr = myLoadRCString(hInstance, IDS_MSG_PARENTCA_CONFIG, &pwszMsgConfigPrefix);
_JumpIfError(hr, error, "myLoadRCString");
hr = myLoadRCString(hInstance, IDS_MSG_REQUEST_ID, &pwszMsgRequestIdPrefix);
_JumpIfError(hr, error, "myLoadRCString");
swprintf(wszRequestIdValue, L"%ld", lRequestId);
cwc = wcslen(pwszMsgConfigPrefix) +
wcslen(pwszParentConfig) +
WSZARRAYSIZE(wszCOMMASPACE) +
wcslen(pwszMsgRequestIdPrefix) +
wcslen(wszRequestIdValue) +
1;
if (NULL != bStrMsgFromServer)
{
cwc += SysStringLen(bStrMsgFromServer) + WSZARRAYSIZE(wszHELPNEWLINE);
}
pwszHelpMsg = (WCHAR *) LocalAlloc(LMEM_FIXED, cwc * sizeof(WCHAR));
if (NULL == pwszHelpMsg)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
// form help message
pwszHelpMsg[0] = L'\0';
if (NULL != bStrMsgFromServer)
{
wcscpy(pwszHelpMsg, bStrMsgFromServer);
wcscat(pwszHelpMsg, wszHELPNEWLINE);
}
wcscat(pwszHelpMsg, pwszMsgConfigPrefix);
wcscat(pwszHelpMsg, pwszParentConfig);
wcscat(pwszHelpMsg, wszCOMMASPACE);
wcscat(pwszHelpMsg, pwszMsgRequestIdPrefix);
wcscat(pwszHelpMsg, wszRequestIdValue);
CSASSERT(wcslen(pwszHelpMsg) + 1 == cwc);
*ppwszHelpMsg = pwszHelpMsg;
pwszHelpMsg = NULL;
hr = S_OK;
error:
if (NULL != pwszMsgConfigPrefix)
{
LocalFree(pwszMsgConfigPrefix);
}
if (NULL != pwszMsgRequestIdPrefix)
{
LocalFree(pwszMsgRequestIdPrefix);
}
if (NULL != pwszHelpMsg)
{
LocalFree(pwszHelpMsg);
}
return(hr);
}
HRESULT
HandleSubmitOrRetrieveNotIssued(
IN HWND hwnd,
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN WCHAR const *pwszSanitizedCAName,
IN WCHAR const *pwszParentCAConfig,
IN LONG disposition,
IN BSTR strDispositionMessage,
IN BOOL fRenew,
IN DWORD iCert,
IN LONG requestId,
IN HRESULT hrSubmit,
IN HRESULT hrLastStatus,
IN int iMsgId)
{
HRESULT hr;
WCHAR *pwszHelpMsg = NULL;
DWORD dwStatusDisable;
DWORD dwStatusEnable;
BOOL fPopup = FALSE;
// form custom message
hr = FormRequestHelpMessage(
hInstance,
requestId,
strDispositionMessage,
pwszParentCAConfig,
&pwszHelpMsg);
_JumpIfError(hr, error, "FromRequestHelpMessage");
// Assume suspended install, denied request:
dwStatusEnable = SETUP_DENIED_FLAG | SETUP_REQUEST_FLAG;
if (!fRenew && 0 == iCert)
{
dwStatusEnable |= SETUP_SUSPEND_FLAG;
}
// Assume the pending request is denied, don't use online parent any more
dwStatusDisable = SETUP_ONLINE_FLAG;
// now handle disposition
switch (disposition)
{
case CR_DISP_UNDER_SUBMISSION:
// the online request is pending, not denied
dwStatusEnable &= ~SETUP_DENIED_FLAG;
dwStatusEnable |= SETUP_ONLINE_FLAG;
// online is still enabled
dwStatusDisable &= ~SETUP_ONLINE_FLAG;
iMsgId = IDS_ERR_REQUEST_PENDING;
break;
case CR_DISP_DENIED:
// request id is no good any more
hr = myDeleteCertRegValue(
pwszSanitizedCAName,
NULL,
NULL,
wszREGREQUESTID);
_PrintIfErrorStr(hr, "myDeleteCertRegValue", wszREGREQUESTID);
if (0 == iMsgId)
{
iMsgId = IDS_ERR_REQUEST_DENIED;
}
break;
case CR_DISP_INCOMPLETE:
iMsgId = IDS_ERR_REQUEST_INCOMPLETE;
break;
case CR_DISP_ERROR:
iMsgId = IDS_ERR_REQUEST_ERROR;
break;
case CR_DISP_ISSUED_OUT_OF_BAND:
// same as pending request, but not denied
dwStatusEnable &= ~SETUP_DENIED_FLAG;
iMsgId = IDS_ERR_REQUEST_OUTOFBAND;
break;
case CR_DISP_REVOKED:
iMsgId = IDS_ERR_REQUEST_REVOKED;
break;
default:
hr = E_INVALIDARG;
_JumpError(hr, error, "Internal error");
}
if (0 != dwStatusDisable)
{
// fix status, unset
hr = SetSetupStatus(pwszSanitizedCAName, dwStatusDisable, FALSE);
_JumpIfError(hr, error, "SetSetupStatus");
}
if (0 != dwStatusEnable)
{
// fix status, set
hr = SetSetupStatus(pwszSanitizedCAName, dwStatusEnable, TRUE);
_JumpIfError(hr, error, "SetSetupStatus");
}
// pop up a warning for generic error
CertWarningMessageBox(
hInstance,
fUnattended,
hwnd,
iMsgId,
hrLastStatus,
pwszHelpMsg);
fPopup = TRUE;
// use proper error code
if (S_OK == hrSubmit)
{
// for any disposition, use not ready as error
hr = HRESULT_FROM_WIN32(ERROR_NOT_READY);
}
else
{
// use submit error
hr = hrSubmit;
}
// note, never return S_OK
error:
if (!fPopup)
{
// a generic one because we won't have any popup later
CertWarningMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_SUBMIT_REQUEST_FAIL,
hr,
L"");
}
if (NULL != pwszHelpMsg)
{
LocalFree(pwszHelpMsg);
}
CSILOG(hr, IDS_ILOG_RETRIEVECERT, NULL, NULL, NULL);
return(hr);
}
HRESULT
csiSubmitCARequest(
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN HWND hwnd,
IN BOOL fRenew,
IN DWORD iCert,
IN BOOL fRetrievePending,
IN WCHAR const *pwszSanitizedCAName,
IN WCHAR const *pwszParentCAMachine,
IN WCHAR const *pwszParentCAName,
IN BYTE const *pbRequest,
IN DWORD cbRequest,
OUT BSTR *pbStrChain)
{
HRESULT hr;
HRESULT hrSubmit;
HRESULT hrLastStatus;
WCHAR *pwszParentCAConfig = NULL;
LONG disposition = CR_DISP_INCOMPLETE;
LONG requestId = 0;
int iMsgId;
ICertRequest *pICertRequest = NULL;
BOOL fCoInit = FALSE;
BSTR bstrConfig = NULL;
BSTR bstrRequest = NULL;
BSTR strDispositionMessage = NULL;
// register parent ca config
hr = mySetCertRegStrValue(
pwszSanitizedCAName,
NULL,
NULL,
wszREGPARENTCAMACHINE,
pwszParentCAMachine);
_JumpIfErrorStr(hr, error, "mySetCertRegStrValue", wszREGPARENTCAMACHINE);
hr = mySetCertRegStrValue(
pwszSanitizedCAName,
NULL,
NULL,
wszREGPARENTCANAME,
pwszParentCAName);
_JumpIfErrorStr(hr, error, "mySetCertRegStrValue", wszREGPARENTCANAME);
if (fRetrievePending)
{
// get request id
hr = myGetCertRegDWValue(
pwszSanitizedCAName,
NULL,
NULL,
wszREGREQUESTID,
(DWORD *) &requestId);
if (S_OK != hr)
{
fRetrievePending = FALSE;
requestId = 0;
}
}
hr = CoInitialize(NULL);
if (S_OK != hr && S_FALSE != hr)
{
_JumpError(hr, error, "CoInitialize");
}
fCoInit = TRUE;
hr = CoCreateInstance(
CLSID_CCertRequest,
NULL,
CLSCTX_INPROC_SERVER,
IID_ICertRequest,
(VOID **) &pICertRequest);
_JumpIfError(hr, error, "CoCreateInstance");
// get config string
hr = myFormConfigString(
pwszParentCAMachine,
pwszParentCAName,
&pwszParentCAConfig);
_JumpIfError(hr, error, "myFormConfigString");
// to bstr
bstrConfig = SysAllocString(pwszParentCAConfig);
if (NULL == bstrConfig)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
// request to bstr
bstrRequest = SysAllocStringByteLen((CHAR *) pbRequest, cbRequest);
if (NULL == bstrRequest)
{
hr = E_OUTOFMEMORY;
_JumpError(hr, error, "LocalAlloc");
}
myDeleteCertRegValue(pwszSanitizedCAName, NULL, NULL, wszREGREQUESTID);
{
CWaitCursor cwait;
if (fRetrievePending)
{
// retrieve the request
hr = pICertRequest->RetrievePending(
requestId,
bstrConfig,
&disposition);
}
else
{
hr = pICertRequest->Submit(
CR_IN_BINARY | CR_IN_PKCS10,
bstrRequest,
NULL,
bstrConfig,
&disposition);
}
hrSubmit = hr;
hrLastStatus = hr;
}
hr = pICertRequest->GetDispositionMessage(&strDispositionMessage);
_PrintIfError(hr, "pICertRequest->GetDispositionMessage");
if (S_OK == hrSubmit)
{
hr = pICertRequest->GetLastStatus(&hrLastStatus);
_PrintIfError(hr, "pICertRequest->GetLastStatus");
}
CSILOG(
hrLastStatus,
fRetrievePending? IDS_ILOG_RETRIEVEPENDING : IDS_ILOG_SUBMITREQUEST,
bstrConfig,
strDispositionMessage,
(DWORD const *) &disposition);
iMsgId = 0;
if (S_OK != hrSubmit)
{
// default to a generic message
iMsgId = fRetrievePending?
IDS_ERR_RETRIEVE_PENDING : IDS_ERR_SUBMIT_REQUEST_FAIL;
if (HRESULT_FROM_WIN32(ERROR_NO_SUCH_USER) == hrSubmit)
{
iMsgId = IDS_ERR_NOT_ENTERPRISE_USER;
}
// if failed, treat as denied
disposition = CR_DISP_DENIED;
}
if (CR_DISP_ISSUED != disposition)
{
if (!fRetrievePending)
{
pICertRequest->GetRequestId(&requestId);
}
hr = mySetCertRegDWValue(
pwszSanitizedCAName,
NULL,
NULL,
wszREGREQUESTID,
requestId);
_JumpIfErrorStr(hr, error, "mySetCertRegDWValue", wszREGREQUESTID);
hr = HandleSubmitOrRetrieveNotIssued(
hwnd,
hInstance,
fUnattended,
pwszSanitizedCAName,
pwszParentCAConfig,
disposition,
strDispositionMessage,
fRenew,
iCert,
requestId,
hrSubmit,
hrLastStatus,
iMsgId);
// not issued, always exit with error
_JumpError(hr, error, "Cert is not issued");
}
// get pkcs7 chain
hr = pICertRequest->GetCertificate(
CR_OUT_CHAIN | CR_OUT_BINARY,
pbStrChain);
_JumpIfError(hr, error, "pICertRequest->GetCertificate");
error:
if (NULL != strDispositionMessage)
{
SysFreeString(strDispositionMessage);
}
if (NULL != pwszParentCAConfig)
{
LocalFree(pwszParentCAConfig);
}
if (NULL != bstrConfig)
{
SysFreeString(bstrConfig);
}
if (NULL != bstrRequest)
{
SysFreeString(bstrRequest);
}
if (NULL != pICertRequest)
{
pICertRequest->Release();
}
if (fCoInit)
{
CoUninitialize();
}
CSILOG(
hr,
fRetrievePending? IDS_ILOG_RETRIEVEPENDING : IDS_ILOG_SUBMITREQUEST,
pwszParentCAMachine,
pwszParentCAName,
(DWORD const *) &disposition);
return(hr);
}
HRESULT
csiInitializeCertSrvSecurity(
IN WCHAR const *pwszSanitizedCAName,
BOOL fUseEnterpriseACL, // which ACL to use
BOOL fSetDsSecurity) // whether to set security on DS object
{
HRESULT hr;
PSECURITY_DESCRIPTOR pSD = NULL;
CCertificateAuthoritySD CASD;
hr = CASD.InitializeFromTemplate(
fUseEnterpriseACL?
WSZ_DEFAULT_CA_ENT_SECURITY :
WSZ_DEFAULT_CA_STD_SECURITY,
pwszSanitizedCAName);
_JumpIfError(hr, error, "CProtectedSecurityDescriptor::InitializeFromTemplate");
hr = CASD.Save();
_JumpIfError(hr, error, "CProtectedSecurityDescriptor::Save");
hr = CASD.MapAndSetDaclOnObjects(fSetDsSecurity?true:false);
_JumpIfError(hr, error, "CProtectedSecurityDescriptor::MapAndSetDaclOnObjects");
error:
if (pSD)
{
LocalFree(pSD);
}
CSILOG(hr, IDS_ILOG_SETSECURITY, NULL, NULL, NULL);
return(hr);
}
HRESULT
csiGenerateKeysOnly(
IN WCHAR const *pwszContainer,
IN WCHAR const *pwszProvName,
IN DWORD dwProvType,
IN BOOL fMachineKeyset,
IN DWORD dwKeyLength,
IN BOOL fUnattended,
IN BOOL fEnableKeyCounting,
OUT HCRYPTPROV *phProv,
OUT int *piMsg)
{
HRESULT hr;
HCRYPTKEY hKey = NULL;
DWORD dwKeyGenFlags;
DWORD dwAcquireFlags;
BOOL fExists;
*phProv = NULL;
*piMsg = 0;
// see if the container already exists
dwAcquireFlags = 0;
if (fMachineKeyset)
{
dwAcquireFlags |= CRYPT_MACHINE_KEYSET;
}
if (fUnattended)
{
dwAcquireFlags |= CRYPT_SILENT;
}
fExists = CryptAcquireContext(
phProv,
pwszContainer,
pwszProvName,
dwProvType,
CRYPT_SILENT | dwAcquireFlags);
if (NULL != *phProv)
{
CryptReleaseContext(*phProv, 0);
*phProv = NULL;
}
if (fExists)
{
// container exists, but we did not choose to reuse keys,
// so remove old keys and generate new ones.
if (!CryptAcquireContext(
phProv,
pwszContainer,
pwszProvName,
dwProvType,
CRYPT_DELETEKEYSET | dwAcquireFlags))
{
hr = myHLastError();
*piMsg = IDS_ERR_DELETEKEY;
_JumpError(hr, error, "CryptAcquireContext");
}
}
// create new container
if (!CryptAcquireContext(
phProv,
pwszContainer,
pwszProvName,
dwProvType,
CRYPT_NEWKEYSET | dwAcquireFlags)) // force new container
{
hr = myHLastError();
if (NTE_TOKEN_KEYSET_STORAGE_FULL == hr)
{
// Smart cards can only hold a limited number of keys
// The user must pick an existing key or use a blank card
*piMsg = IDS_ERR_FULL_TOKEN;
_JumpError(hr, error, "CryptAcquireContext");
}
else if (HRESULT_FROM_WIN32(ERROR_CANCELLED) == hr)
{
// user must have clicked cancel on a smart card dialog.
// go to previous page, and display no error message
_JumpError(hr, error, "CryptAcquireContext");
}
else if (NTE_EXISTS == hr)
{
// since fExists shows NOT, it is likely the current user
// doesn't have access permission for this existing key
*piMsg = IDS_ERR_NO_KEY_ACCESS;
_JumpError(hr, error, "CryptAcquireContext");
}
else
{
// Unexpected error in CryptAcquireContext.
*piMsg = IDS_ERR_BADCSP;
_JumpError(hr, error, "CryptAcquireContext");
}
}
// enable key usage count for audit purposes
if (fEnableKeyCounting)
{
hr = mySetEnablePrivateKeyUsageCount(*phProv, TRUE);
_JumpIfError(hr, error, "mySetEnablePrivateKeyUsageCount");
}
// set key length
dwKeyGenFlags = (dwKeyLength << 16) | CRYPT_EXPORTABLE;
// create signature keys
if (!CryptGenKey(*phProv, AT_SIGNATURE, dwKeyGenFlags, &hKey))
{
hr = myHLastError();
_PrintError(hr, "CryptGenKey(exportable)");
dwKeyGenFlags &= ~CRYPT_EXPORTABLE;
if (!CryptGenKey(*phProv, AT_SIGNATURE, dwKeyGenFlags, &hKey))
{
hr = myHLastError();
*piMsg = IDS_ERR_GENKEYFAIL;
_JumpError(hr, error, "CryptGenKey");
}
}
hr = S_OK;
error:
if (NULL != hKey)
{
CryptDestroyKey(hKey);
}
CSILOG(hr, IDS_ILOG_GENERATEKEYS, pwszContainer, pwszProvName, &dwKeyLength);
return(hr);
}
HRESULT
csiGenerateCAKeys(
IN WCHAR const *pwszContainer,
IN WCHAR const *pwszProvName,
IN DWORD dwProvType,
IN BOOL fMachineKeyset,
IN DWORD dwKeyLength,
IN HINSTANCE hInstance,
IN BOOL fUnattended,
IN BOOL fEnableKeyCounting,
IN HWND hwnd,
OUT BOOL *pfKeyGenFailed)
{
HRESULT hr;
HCRYPTPROV hProv = NULL;
int iMsg;
// generate key first
hr = csiGenerateKeysOnly(
pwszContainer,
pwszProvName,
dwProvType,
fMachineKeyset,
dwKeyLength,
fUnattended,
fEnableKeyCounting,
&hProv,
&iMsg);
if (S_OK != hr)
{
CertWarningMessageBox(
hInstance,
fUnattended,
hwnd,
iMsg,
hr,
pwszContainer);
*pfKeyGenFailed = TRUE;
_JumpError(hr, error, "csiGenerateKeysOnly");
}
*pfKeyGenFailed = FALSE;
// now apply acl on key
// BUG, this is not necessary, CertSrvSetSecurity will reset
hr = csiSetKeyContainerSecurity(hProv);
if (S_OK != hr)
{
CertWarningMessageBox(
hInstance,
fUnattended,
hwnd,
IDS_ERR_KEYSECURITY,
hr,
pwszContainer);
_PrintError(hr, "csiSetKeyContainerSecurity");
}
hr = S_OK;
error:
if (NULL != hProv)
{
CryptReleaseContext(hProv, 0);
}
return(hr);
}
HRESULT
csiGetProviderTypeFromProviderName(
IN WCHAR const *pwszName,
OUT DWORD *pdwType)
{
HRESULT hr;
DWORD i;
DWORD dwProvType;
WCHAR *pwszProvName = NULL;
// Provider name should not be null. This could be changed to ...
CSASSERT(NULL != pwszName);
*pdwType = 0;
dwProvType = 0;
for (i = 0; ; i++)
{
// get provider name
hr = myEnumProviders(i, NULL, 0, &dwProvType, &pwszProvName);
if (S_OK != hr)
{
hr = myHLastError();
CSASSERT(
HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS) == hr ||
NTE_FAIL == hr);
if(HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS) == hr ||
NTE_FAIL == hr)
{
// no more providers, terminate loop
hr = E_INVALIDARG;
CSILOG(
hr,
IDS_ILOG_MISSING_PROVIDER,
pwszName,
NULL,
NULL);
_JumpErrorStr(hr, error, "not found", pwszName);
}
}
else
{
CSASSERT(NULL != pwszProvName);
if (0 == mylstrcmpiL(pwszName, pwszProvName))
{
break; // found it
}
LocalFree(pwszProvName);
pwszProvName = NULL;
}
}
*pdwType = dwProvType;
hr = S_OK;
error:
if (NULL != pwszProvName)
{
LocalFree(pwszProvName);
}
return(hr);
}
HRESULT
csiUpgradeCertSrvSecurity(
IN WCHAR const *pwszSanitizedCAName,
BOOL fUseEnterpriseACL, // which ACL to use
BOOL fSetDsSecurity, // whether to set security on DS object
CS_ENUM_UPGRADE UpgradeType)
{
HRESULT hr = S_OK;
CertSrv::CCertificateAuthoritySD CASD;
PSECURITY_DESCRIPTOR pDefaultSD = NULL;
hr = CASD.Initialize(pwszSanitizedCAName);
_PrintIfError(hr, "CASD.Initialize");
if(S_OK==hr)
{
if(CS_UPGRADE_WHISTLER==UpgradeType)
{
// validate the SD
hr = CASD.Validate(CASD.Get());
_PrintIfError(hr, "CASD.Validate");
}
else // win2k
{
hr = CASD.UpgradeWin2k(fUseEnterpriseACL?true:false);
_PrintIfError(hr, "CASD.UpgradeWin2k");
}
}
// never fail, fall back to a default SD
if(S_OK!=hr)
{
CASD.Uninitialize();
hr = CASD.InitializeFromTemplate(
fUseEnterpriseACL?
WSZ_DEFAULT_CA_ENT_SECURITY :
WSZ_DEFAULT_CA_STD_SECURITY,
pwszSanitizedCAName);
_JumpIfError(hr, error,
"CProtectedSecurityDescriptor::InitializeFromTemplate");
}
hr = CASD.Save();
_JumpIfError(hr, error, "CASD.Save");
hr = CASD.MapAndSetDaclOnObjects(fSetDsSecurity? true:false);
_PrintIfError(hr, "CASD::MapAndSetDaclOnObjects");
// When upgrading from win2k we need to upgrade security in DS. Usually
// DS is unavailable during upgrade.
if ((hr != S_OK) && fSetDsSecurity && (UpgradeType == CS_UPGRADE_WIN2000))
{
// if asked to set security on DS and this is UPGRADE, we can't touch DS.
// Leave security changes to the certsrv snapin
// set a flag so certmmc knows to do something
hr = SetSetupStatus(pwszSanitizedCAName, SETUP_W2K_SECURITY_NOT_UPGRADED_FLAG, TRUE);
_JumpIfError(hr, error, "SetSetupStatus");
hr = HRESULT_FROM_WIN32(ERROR_CAN_NOT_COMPLETE);
_PrintError(hr, "DS unavailable");
}
else
{
// make sure this bit is cleared
hr = SetSetupStatus(pwszSanitizedCAName, SETUP_W2K_SECURITY_NOT_UPGRADED_FLAG, FALSE);
_JumpIfError(hr, error, "SetSetupStatus");
}
error:
LOCAL_FREE(pDefaultSD);
return hr;
}
DefineAutoClass(CAutoPCERT_NAME_INFO, PCERT_NAME_INFO, LocalFree);
DefineAutoClass(CAutoPCERT_RDN, PCERT_RDN, LocalFree);
HRESULT AddCNAndEncode(
LPCWSTR pcwszName,
LPCWSTR pcwszDNSuffix,
BYTE** ppbEncodedDN,
DWORD *pcbEncodedDN)
{
HRESULT hr;
CAutoPBYTE pbDNSuffix;
CAutoPCERT_NAME_INFO pCertNameInfo;
DWORD cbCertNameInfo;
CAutoPCERT_RDN pCertRDN;
CERT_RDN_ATTR attrDN;
CAutoPBYTE pbEncodedDN;
DWORD cbEncodedDN;
attrDN.pszObjId = szOID_COMMON_NAME;
attrDN.dwValueType = CERT_RDN_ANY_TYPE;
attrDN.Value.cbData = 0;
attrDN.Value.pbData = (PBYTE)pcwszName;
hr = myCertStrToName(
X509_ASN_ENCODING,
pcwszDNSuffix,
CERT_X500_NAME_STR |
CERT_NAME_STR_COMMA_FLAG |
CERT_NAME_STR_REVERSE_FLAG |
((g_dwNameEncodeFlags&CERT_RDN_ENABLE_UTF8_UNICODE_FLAG)?
CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG:0),
NULL,
&pbEncodedDN,
&cbEncodedDN,
NULL);
_JumpIfError(hr, error, "myCertStrToName");
if (!myDecodeName(
X509_ASN_ENCODING,
X509_UNICODE_NAME,
pbEncodedDN,
cbEncodedDN,
CERTLIB_USE_LOCALALLOC,
&pCertNameInfo,
&cbCertNameInfo))
{
hr = myHLastError();
_JumpError(hr, error, "myDecodeName");
}
pCertRDN = (PCERT_RDN)LocalAlloc(
LMEM_FIXED,
(pCertNameInfo->cRDN+1)*sizeof(CERT_RDN));
_JumpIfAllocFailed(pCertRDN, error);
CopyMemory(
pCertRDN,
pCertNameInfo->rgRDN,
pCertNameInfo->cRDN*sizeof(CERT_RDN));
pCertRDN[pCertNameInfo->cRDN].cRDNAttr = 1;
pCertRDN[pCertNameInfo->cRDN].rgRDNAttr = &attrDN;
pCertNameInfo->cRDN++;
pCertNameInfo->rgRDN = pCertRDN;
if (!myEncodeName(
X509_ASN_ENCODING,
pCertNameInfo,
g_dwNameEncodeFlags,
CERTLIB_USE_LOCALALLOC,
ppbEncodedDN,
pcbEncodedDN))
{
hr = myHLastError();
_JumpError(hr, error, "myEncodeName");
}
error:
return hr;
}
HRESULT
myLDAPAddOrRemoveMachine(
bool fAdd,
LPWSTR pwszCertPublishersFilter)
{
HRESULT hr = S_OK;
LPWSTR pwszComputerDN = NULL;
LDAP *pld = NULL;
LPWSTR pwszComputerDomainDN; // no free
LDAPMessage* pResult = NULL;
LDAPMessage *pEntry;
LPWSTR pwszAttrArray[2];
LPWSTR pwszDNAttr = L"distinguishedName";
LPWSTR pwszMemberAttr = L"member";
LPWSTR* pwszCertPublishersDN = NULL;
LDAPMod *mods[2];
LDAPMod member;
LPWSTR memberVals[2];
hr = myGetComputerObjectName(
NameFullyQualifiedDN,
&pwszComputerDN);
_JumpIfError(hr, error, "myGetComputerObjectName");
pwszComputerDomainDN = wcsstr(pwszComputerDN, L"DC=");
pwszAttrArray[0] = pwszDNAttr;
pwszAttrArray[1] = NULL;
hr = myLdapOpen(
NULL, // pwszDomainName
RLBF_REQUIRE_SECURE_LDAP, // dwFlags
&pld,
NULL, // pstrDomainDN
NULL); // pstrConfigDN
_JumpIfError(hr, error, "myLdapOpen");
hr = ldap_search_s(
pld,
pwszComputerDomainDN,
LDAP_SCOPE_SUBTREE,
pwszCertPublishersFilter,
pwszAttrArray,
FALSE,
&pResult);
hr = myHLdapError(pld, hr, NULL);
_JumpIfError(hr, error, "ldap_search_sW");
pEntry = ldap_first_entry(pld, pResult);
if (NULL == pEntry)
{
hr = ERROR_NO_SUCH_GROUP;
_JumpErrorStr(hr, error, "ldap_search", pwszCertPublishersFilter);
}
pwszCertPublishersDN = ldap_get_values(
pld,
pEntry,
pwszDNAttr);
if (NULL == pwszCertPublishersDN || NULL==*pwszCertPublishersDN)
{
hr = myHLdapLastError(pld, NULL);
_JumpError(hr, error, "ldap_get_values");
}
memberVals[0] = pwszComputerDN;
memberVals[1] = NULL;
member.mod_op = fAdd?LDAP_MOD_ADD:LDAP_MOD_DELETE;
member.mod_type = pwszMemberAttr;
member.mod_values = memberVals;
mods[0] = &member;
mods[1] = NULL;
hr = ldap_modify_ext_s(
pld,
*pwszCertPublishersDN,
mods,
NULL,
NULL);
// don't fail if already member of cert publishers
if(((HRESULT)LDAP_ALREADY_EXISTS)==hr)
hr = LDAP_SUCCESS;
hr = myHLdapError(pld, hr, NULL);
_JumpIfErrorStr(hr, error, "ldap_modify_exts", *pwszCertPublishersDN);
error:
LOCAL_FREE(pwszComputerDN);
if (NULL != pwszCertPublishersDN)
{
ldap_value_free(pwszCertPublishersDN);
}
if (NULL != pResult)
{
ldap_msgfree(pResult);
}
myLdapClose(pld, NULL, NULL);
return hr;
}
HRESULT AddOrRemoveMachineToGroup(
PSID pGroupSid,
bool fAdd)
{
HRESULT hr;
LPWSTR pwszFilter = NULL;
LPWSTR pwszEscapedGroupSid = NULL;
ULONG len;
static LPCWSTR pcwszFilterFormat =
L"(&(objectCategory=group)(objectSid=%s))";
len = ldap_escape_filter_element(
(PCHAR)pGroupSid,
GetLengthSid(pGroupSid),
NULL,
0);
len *= sizeof(WCHAR);
pwszEscapedGroupSid = (LPWSTR) LocalAlloc(LMEM_FIXED, len);
_JumpIfAllocFailed(pwszEscapedGroupSid, error);
ldap_escape_filter_element(
(PCHAR)pGroupSid,
GetLengthSid(pGroupSid),
pwszEscapedGroupSid,
len);
pwszFilter = (LPWSTR)LocalAlloc(
LMEM_FIXED,
sizeof(WCHAR) *
(wcslen(pcwszFilterFormat) +
wcslen(pwszEscapedGroupSid) +
1));
_JumpIfAllocFailed(pwszFilter, error);
wsprintf(
pwszFilter,
pcwszFilterFormat,
pwszEscapedGroupSid);
hr = myLDAPAddOrRemoveMachine(fAdd, pwszFilter);
_JumpIfError(hr, error, "myLDAPAddOrRemoveMachine");
error:
LOCAL_FREE(pwszFilter);
LOCAL_FREE(pwszEscapedGroupSid);
return hr;
}
HRESULT AddOrRemoveMachineToGroup(
LPCWSTR pcwszGroupSid,
bool fAdd)
{
HRESULT hr;
PSID pGroupSid = NULL;
if(!ConvertStringSidToSid(
pcwszGroupSid,
&pGroupSid))
{
hr = myHLastError();
_JumpErrorStr(hr, error, "ConvertStringSidToSid", pcwszGroupSid);
}
myRegisterMemAlloc(pGroupSid, -1, CSM_LOCALALLOC);
hr = AddOrRemoveMachineToGroup(
pGroupSid,
fAdd);
_JumpIfError(hr, error, "AddOrRemoveMachineToGroup");
error:
LOCAL_FREE(pGroupSid);
return hr;
}
HRESULT
AddOrRemoveMachineToDomainGroup(
IN bool fAdd)
{
HRESULT hr;
PSID pGroupSid = NULL;
hr = myGetSidFromRid(
DOMAIN_GROUP_RID_CERT_ADMINS,
&pGroupSid,
NULL);
_JumpIfError(hr, error, "myGetSidFromRid");
hr = AddOrRemoveMachineToGroup(pGroupSid, fAdd);
_JumpIfError(hr, error, "AddOrRemoveMachineToGroup");
error:
LOCAL_FREE(pGroupSid);
return hr;
}
HRESULT
AddCAMachineToCertPublishers()
{
return AddOrRemoveMachineToDomainGroup(true);
}
HRESULT
RemoveCAMachineFromCertPublishers(VOID)
{
return AddOrRemoveMachineToDomainGroup(false);
}
static LPCWSTR pcwszPreWin2kSid = L"S-1-5-32-554";
HRESULT AddCAMachineToPreWin2kGroup(VOID)
{
return AddOrRemoveMachineToGroup(
pcwszPreWin2kSid,
true);
}
HRESULT RemoveCAMachineFromPreWin2kGroup(VOID)
{
return AddOrRemoveMachineToGroup(
pcwszPreWin2kSid,
false);
}
| 24.912228 | 130 | 0.586563 | [
"object"
] |
08197aadcdbd9f3734c65ef561f53cd3e915f110 | 2,534 | cpp | C++ | inference-engine/src/transformations/src/transformations/convert_opset3_to_opset2/convert_topk3.cpp | vladimir-paramuzov/openvino | b6a05c232ed8536689be5e67d7fc597a4f654fef | [
"Apache-2.0"
] | null | null | null | inference-engine/src/transformations/src/transformations/convert_opset3_to_opset2/convert_topk3.cpp | vladimir-paramuzov/openvino | b6a05c232ed8536689be5e67d7fc597a4f654fef | [
"Apache-2.0"
] | 1 | 2021-09-09T08:43:57.000Z | 2021-09-10T12:39:16.000Z | inference-engine/src/transformations/src/transformations/convert_opset3_to_opset2/convert_topk3.cpp | vladimir-paramuzov/openvino | b6a05c232ed8536689be5e67d7fc597a4f654fef | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "transformations/convert_opset3_to_opset2/convert_topk3.hpp"
#include <memory>
#include <vector>
#include <ngraph/opsets/opset1.hpp>
#include <ngraph/opsets/opset2.hpp>
#include <ngraph/opsets/opset3.hpp>
#include <ngraph/rt_info.hpp>
void ngraph::pass::ConvertTopK3::convert_topk3() {
auto input = std::make_shared<pattern::op::Label>(element::i64, Shape{1, 1, 1, 1});
auto k = ngraph::opset3::Constant::create(element::i64, Shape{}, {10});
auto topk = std::make_shared<ngraph::opset3::TopK>(input, k, 0, "min", "value", element::i64);
// this is a temporary workaround to avoid bug that TopK-3 does not have clone_with_new_inputs so the TopK-3 clone
// generates TopK-1 operation
auto topk_v1 = std::make_shared<ngraph::opset1::TopK>(input, k, 0, "min", "value", element::i64);
ngraph::graph_rewrite_callback callback = [](pattern::Matcher& m) {
std::shared_ptr<ngraph::op::v1::TopK> topk = std::dynamic_pointer_cast<ngraph::opset3::TopK> (m.get_match_root());
if (!topk) {
topk = std::dynamic_pointer_cast<ngraph::opset1::TopK> (m.get_match_root());
}
if (!topk) {
return false;
}
Output<Node> last;
ngraph::NodeVector new_ops;
auto new_topk = std::make_shared<ngraph::opset2::TopK>(topk->input_value(0), topk->input_value(1),
topk->get_axis(), topk->get_mode(), topk->get_sort_type(), element::i32);
new_ops.push_back(new_topk);
// if the output is the i32 then it matches behavior of the v1::TopK otherwise need to insert Convert
if (topk->get_index_element_type() == element::i32) {
last = new_topk->output(1);
} else {
last = std::make_shared<ngraph::opset2::Convert>(new_topk->output(1), topk->get_index_element_type());
new_ops.push_back(last.get_node_shared_ptr());
}
new_topk->set_friendly_name(topk->get_friendly_name());
ngraph::copy_runtime_info(topk, new_ops);
topk->output(0).replace(new_topk->output(0));
topk->output(1).replace(last);
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(topk, "ConvertTopK3");
this->add_matcher(m, callback, PassProperty::CHANGE_DYNAMIC_STATE);
auto m2 = std::make_shared<ngraph::pattern::Matcher>(topk_v1, "ConvertTopK3");
this->add_matcher(m2, callback, PassProperty::CHANGE_DYNAMIC_STATE);
}
| 44.45614 | 122 | 0.6618 | [
"shape",
"vector"
] |
08199ece96c0680b027eec33ec756a7401ee3a52 | 6,567 | cpp | C++ | tests/unit/sdk/test_pixie_util.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 2 | 2021-04-14T13:58:50.000Z | 2021-08-09T19:42:25.000Z | tests/unit/sdk/test_pixie_util.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 1 | 2021-08-31T10:32:07.000Z | 2021-09-03T15:03:00.000Z | tests/unit/sdk/test_pixie_util.cpp | xiallc/pixie_sdk | a6cf38b0a0d73a55955f4f906f789ee16eb848d4 | [
"Apache-2.0"
] | 1 | 2022-03-25T12:32:52.000Z | 2022-03-25T12:32:52.000Z | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright 2021 XIA LLC, 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.
*/
/** @file test_pixie_util.cpp
* @brief Provides test coverage for SDK utility functions
*/
#include <doctest/doctest.h>
#include <pixie/util.hpp>
TEST_SUITE("xia::util") {
TEST_CASE("Verify ostream_guard") {
std::ios_base::fmtflags expected(std::cout.flags());
xia::util::ostream_guard ostream_guard(std::cout);
CHECK(ostream_guard.flags == expected);
}
TEST_CASE("ieee_float") {
SUBCASE("Initialization") {
CHECK(xia::util::ieee_float(0.5) == 0.5);
CHECK(xia::util::ieee_float(xia::util::ieee_float(0.5)) == 0.5);
CHECK(xia::util::ieee_float(0x3f000000u) == 0.5);
}
SUBCASE("Equality Operator") {
CHECK(xia::util::ieee_float(0.5) == xia::util::ieee_float(0.5));
}
SUBCASE("Cast operator / out()") {
CHECK(static_cast<double>(xia::util::ieee_float(0.5)) == 0.5);
CHECK(static_cast<double>(xia::util::ieee_float(-0.5)) == -0.5);
}
SUBCASE("Sign Bit 0 / Exponent > 0") {
CHECK(doctest::Approx(xia::util::ieee_float(0x40490fdbu)) == 3.14159);
CHECK(doctest::Approx(xia::util::ieee_float(3.14159)) ==
xia::util::ieee_float(0x40490fdbu));
}
SUBCASE("Sign Bit 1 / Exponent > 0") {
CHECK(doctest::Approx(xia::util::ieee_float(0xc958a450u)) == -887365);
CHECK(doctest::Approx(xia::util::ieee_float(-887365.)) ==
xia::util::ieee_float(0xc958a450u));
}
SUBCASE("Sign Bit 0 / Exponent < 0") {
CHECK(doctest::Approx(xia::util::ieee_float(0x3e22d0e5u)) == 0.159);
CHECK(doctest::Approx(xia::util::ieee_float(0.159)) ==
xia::util::ieee_float(0x3e22d0e5u));
}
SUBCASE("Sign Bit 1 / Exponent < 0") {
CHECK(doctest::Approx(xia::util::ieee_float(0xbe22d0e5u)) == -0.159);
CHECK(doctest::Approx(xia::util::ieee_float(-0.159)) ==
xia::util::ieee_float(0xbe22d0e5u));
}
SUBCASE("Sign Bit 0 / Exponent = 0") {
CHECK(xia::util::ieee_float(0x3f800000u) == 1.0);
CHECK(xia::util::ieee_float(1.0) == xia::util::ieee_float(0x3f800000u));
}
SUBCASE("Sign Bit 1 / Exponent = 0") {
CHECK(xia::util::ieee_float(0xbf800000u) == -1.0);
CHECK(xia::util::ieee_float(-1.0) == xia::util::ieee_float(0xbf800000u));
}
}
TEST_CASE("dequote") {
std::string good = "\"quoted\"";
xia::util::dequote(good);
CHECK(good == "quoted");
std::string bad = "\"quoted\'";
CHECK_THROWS_WITH_AS(xia::util::dequote(bad), "invalid quoting: \"quoted\'",
std::runtime_error);
}
TEST_CASE("ltrim") {
std::string test = " trim";
xia::util::ltrim(test);
CHECK(test == "trim");
}
TEST_CASE("rtrim") {
std::string test = "trim ";
xia::util::rtrim(test);
CHECK(test == "trim");
}
TEST_CASE("split") {
std::string test = "a,b,c,d";
xia::util::strings result;
SUBCASE("Basic split") {
xia::util::split(result, test, ',', 0, false, false, false);
CHECK(result == xia::util::strings{"a", "b", "c", "d"});
}
SUBCASE("Split with limit") {
xia::util::split(result, test, ',', 2, false, false, true);
CHECK(result == xia::util::strings{"a", "b"});
}
SUBCASE("Split with spaces") {
std::string test_w_spaces = " a,b ,c,d";
xia::util::split(result, test_w_spaces, ',', 0, true, false, true);
CHECK(result == xia::util::strings{"a", "b", "c", "d"});
}
SUBCASE("Split with quotes") {
std::string test_w_quotes = "\"a\",b,\'c\',d";
xia::util::split(result, test_w_quotes, ',', 0, false, true, true);
CHECK(result == xia::util::strings{"a", "b", "c", "d"});
}
SUBCASE("Split with bad quotes") {
std::string test_w_quotes = "\"a\",b,\'c\",d";
CHECK_THROWS_WITH_AS(xia::util::split(result, test_w_quotes, ',', 0, false, true, true),
"invalid quoting: \'c\"", std::runtime_error);
}
SUBCASE("Split with quotes and spaces - in element") {
result.clear();
std::string test_w_quotes_and_space = "\" a\", b,\'c \', d";
xia::util::split(result, test_w_quotes_and_space, ',', 0, true, true, true);
CHECK(result == xia::util::strings{" a", "b", "c ", "d"});
}
SUBCASE("Split with quotes and spaces - around element") {
result.clear();
std::string test_w_quotes_and_space_outside = " \"a\", b ,\'c \' , d";
xia::util::split(result, test_w_quotes_and_space_outside, ',', 0, true, true, true);
CHECK(result == xia::util::strings{"a", "b", "c ", "d"});
}
}
TEST_CASE("crc32") {
std::vector<unsigned char> vec_val = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
const uint32_t expected = 0xcbf43926;
const std::string expected_str = "cbf43926";
SUBCASE("Update with a vector") {
auto chksum1 = xia::util::crc32();
chksum1.update(vec_val);
CHECK(chksum1.value == expected);
CHECK(static_cast<std::string>(chksum1) == expected_str);
}
SUBCASE("Update with a stream") {
auto chksum2 = xia::util::crc32();
for (const auto val : vec_val)
chksum2 << val;
CHECK(chksum2.value == expected);
}
SUBCASE("Clear") {
auto chksum3 = xia::util::crc32();
chksum3.value = expected;
chksum3.clear();
CHECK(chksum3.value == 0);
}
}
}
| 40.042683 | 100 | 0.540429 | [
"vector"
] |
081fd0c2fa9041e4c11db2a70f93c7389ff7d215 | 17,234 | cpp | C++ | Engine/source/interior/pathedInterior.cpp | baktubak/Torque3D | c26235c5b81ed55b231af86254d740ce17540d25 | [
"MIT"
] | 6 | 2015-06-01T15:44:43.000Z | 2021-01-07T06:50:21.000Z | Engine/source/interior/pathedInterior.cpp | timmgt/Torque3D | ebc6c9cf3a2c7642b2cd30be3726810a302c3deb | [
"Unlicense"
] | null | null | null | Engine/source/interior/pathedInterior.cpp | timmgt/Torque3D | ebc6c9cf3a2c7642b2cd30be3726810a302c3deb | [
"Unlicense"
] | 10 | 2015-01-05T15:58:31.000Z | 2021-11-20T14:05:46.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "interior/pathedInterior.h"
#include "core/stream/stream.h"
#include "console/consoleTypes.h"
#include "scene/sceneRenderState.h"
#include "math/mathIO.h"
#include "core/stream/bitStream.h"
#include "interior/interior.h"
#include "scene/simPath.h"
#include "scene/pathManager.h"
#include "core/frameAllocator.h"
#include "scene/sceneManager.h"
#include "sfx/sfxSystem.h"
#include "sfx/sfxProfile.h"
#include "sfx/sfxSource.h"
#include "core/resourceManager.h"
IMPLEMENT_CO_NETOBJECT_V1(PathedInterior);
IMPLEMENT_CO_DATABLOCK_V1(PathedInteriorData);
ConsoleDocClass( PathedInterior,
"@brief Legacy interior related class, soon to be deprecated.\n\n"
"Not intended for game development, for editors or internal use only.\n\n "
"@internal");
ConsoleDocClass( PathedInteriorData,
"@brief Legacy interior related class, soon to be deprecated.\n\n"
"Not intended for game development, for editors or internal use only.\n\n "
"@internal");
//--------------------------------------------------------------------------
PathedInteriorData::PathedInteriorData()
{
for(U32 i = 0; i < MaxSounds; i++)
sound[i] = NULL;
}
void PathedInteriorData::initPersistFields()
{
addField("StartSound", TYPEID< SFXProfile >(), Offset(sound[StartSound], PathedInteriorData));
addField("SustainSound", TYPEID< SFXProfile >(), Offset(sound[SustainSound], PathedInteriorData));
addField("StopSound", TYPEID< SFXProfile >(), Offset(sound[StopSound], PathedInteriorData));
Parent::initPersistFields();
}
void PathedInteriorData::packData(BitStream *stream)
{
for (S32 i = 0; i < MaxSounds; i++)
{
if (stream->writeFlag(sound[i]))
stream->writeRangedU32(packed? SimObjectId(sound[i]):
sound[i]->getId(),DataBlockObjectIdFirst,DataBlockObjectIdLast);
}
Parent::packData(stream);
}
void PathedInteriorData::unpackData(BitStream* stream)
{
for (S32 i = 0; i < MaxSounds; i++) {
sound[i] = NULL;
if (stream->readFlag())
sound[i] = (SFXProfile*)stream->readRangedU32(DataBlockObjectIdFirst,
DataBlockObjectIdLast);
}
Parent::unpackData(stream);
}
bool PathedInteriorData::preload(bool server, String &errorStr)
{
if(!Parent::preload(server, errorStr))
return false;
// Resolve objects transmitted from server
if (!server)
{
for (S32 i = 0; i < MaxSounds; i++)
if (sound[i])
Sim::findObject(SimObjectId(sound[i]),sound[i]);
}
return true;
}
PathedInterior::PathedInterior()
{
mNetFlags.set(Ghostable);
mTypeMask = InteriorObjectType;
mCurrentPosition = 0;
mTargetPosition = 0;
mPathKey = 0xFFFFFFFF;
mStopped = false;
mSustainSound = NULL;
}
PathedInterior::~PathedInterior()
{
//
}
PathedInterior *PathedInterior::mClientPathedInteriors = NULL;
//--------------------------------------------------------------------------
void PathedInterior::initPersistFields()
{
addField("interiorResource", TypeFilename, Offset(mInteriorResName, PathedInterior));
addField("interiorIndex", TypeS32, Offset(mInteriorResIndex, PathedInterior));
addField("basePosition", TypeMatrixPosition, Offset(mBaseTransform, PathedInterior));
addField("baseRotation", TypeMatrixRotation, Offset(mBaseTransform, PathedInterior));
addField("baseScale", TypePoint3F, Offset(mBaseScale, PathedInterior));
Parent::initPersistFields();
}
//--------------------------------------------------------------------------
bool PathedInterior::onAdd()
{
if(!Parent::onAdd())
return false;
// Load the interior resource and extract the interior that is us.
mInteriorRes = ResourceManager::get().load(mInteriorResName);
if (bool(mInteriorRes) == false)
return false;
mInterior = mInteriorRes->getSubObject(mInteriorResIndex);
if (mInterior == NULL)
return false;
// Setup bounding information
mObjBox = mInterior->getBoundingBox();
resetWorldBox();
setScale(mBaseScale);
setTransform(mBaseTransform);
if (isClientObject()) {
mNextClientPI = mClientPathedInteriors;
mClientPathedInteriors = this;
mInterior->prepForRendering(mInteriorRes.getPath().getFullPath().c_str());
// gInteriorLMManager.addInstance(mInterior->getLMHandle(), mLMHandle, NULL, this);
}
if(isClientObject())
{
Point3F initialPos( 0.0, 0.0, 0.0 );
mBaseTransform.getColumn(3, &initialPos);
Point3F pathPos( 0.0, 0.0, 0.0 );
//gClientPathManager->getPathPosition(mPathKey, 0, pathPos);
mOffset = initialPos - pathPos;
//gClientPathManager->getPathPosition(mPathKey, mCurrentPosition, pathPos);
MatrixF mat = getTransform();
mat.setColumn(3, pathPos + mOffset);
setTransform(mat);
}
addToScene();
return true;
}
bool PathedInterior::onNewDataBlock( GameBaseData *dptr, bool reload )
{
mDataBlock = dynamic_cast<PathedInteriorData*>(dptr);
if ( isClientObject() )
{
SFX_DELETE( mSustainSound );
if ( mDataBlock->sound[PathedInteriorData::SustainSound] )
mSustainSound = SFX->createSource( mDataBlock->sound[PathedInteriorData::SustainSound], &getTransform() );
if ( mSustainSound )
mSustainSound->play();
}
return Parent::onNewDataBlock(dptr,reload);
}
void PathedInterior::onRemove()
{
if(isClientObject())
{
SFX_DELETE( mSustainSound );
PathedInterior **walk = &mClientPathedInteriors;
while(*walk)
{
if(*walk == this)
{
*walk = mNextClientPI;
break;
}
walk = &((*walk)->mNextClientPI);
}
/* if(bool(mInteriorRes) && mLMHandle != 0xFFFFFFFF)
{
if (mInterior->getLMHandle() != 0xFFFFFFFF)
gInteriorLMManager.removeInstance(mInterior->getLMHandle(), mLMHandle);
}*/
}
removeFromScene();
Parent::onRemove();
}
//------------------------------------------------------------------------------
bool PathedInterior::buildPolyList(AbstractPolyList* list, const Box3F& wsBox, const SphereF&)
{
if (bool(mInteriorRes) == false)
return false;
// Setup collision state data
list->setTransform(&getTransform(), getScale());
list->setObject(this);
return mInterior->buildPolyList(list, wsBox, mWorldToObj, getScale());
}
//--------------------------------------------------------------------------
void PathedInterior::prepRenderImage( SceneRenderState* state )
{
if (mPathKey == SimPath::Path::NoPathIndex)
return;
/*
SceneRenderImage* image = new SceneRenderImage;
image->obj = this;
state->insertRenderImage(image);
*/
}
extern ColorF gInteriorFogColor;
void PathedInterior::renderObject(SceneRenderState* state)
{
}
void PathedInterior::resolvePathKey()
{
if(mPathKey == 0xFFFFFFFF && !isGhost())
{
mPathKey = getPathKey();
Point3F pathPos( 0.0, 0.0, 0.0 );
Point3F initialPos( 0.0, 0.0, 0.0 );
mBaseTransform.getColumn(3, &initialPos);
//gServerPathManager->getPathPosition(mPathKey, 0, pathPos);
mOffset = initialPos - pathPos;
}
}
//--------------------------------------------------------------------------
U32 PathedInterior::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
resolvePathKey();
if (stream->writeFlag(mask & InitialUpdateMask))
{
// Inital update...
stream->writeString(mInteriorResName);
stream->write(mInteriorResIndex);
stream->writeAffineTransform(mBaseTransform);
mathWrite(*stream, mBaseScale);
stream->write(mPathKey);
}
if(stream->writeFlag((mask & NewPositionMask) && mPathKey != SimPath::Path::NoPathIndex))
stream->writeInt(S32(mCurrentPosition), gServerPathManager->getPathTimeBits(mPathKey));
if(stream->writeFlag((mask & NewTargetMask) && mPathKey != SimPath::Path::NoPathIndex))
{
if(stream->writeFlag(mTargetPosition < 0))
{
stream->writeFlag(mTargetPosition == -1);
}
else
stream->writeInt(S32(mTargetPosition), gServerPathManager->getPathTimeBits(mPathKey));
}
return retMask;
}
void PathedInterior::unpackUpdate(NetConnection* con, BitStream* stream)
{
Parent::unpackUpdate(con, stream);
MatrixF tempXForm;
Point3F tempScale;
if (stream->readFlag())
{
// Initial
mInteriorResName = stream->readSTString();
stream->read(&mInteriorResIndex);
stream->readAffineTransform(&tempXForm);
mathRead(*stream, &tempScale);
mBaseTransform = tempXForm;
mBaseScale = tempScale;
stream->read(&mPathKey);
}
if(stream->readFlag())
{
Point3F pathPos(0.0f, 0.0f, 0.0f);
mCurrentPosition = stream->readInt(gClientPathManager->getPathTimeBits(mPathKey));
if(isProperlyAdded())
{
//gClientPathManager->getPathPosition(mPathKey, mCurrentPosition, pathPos);
MatrixF mat = getTransform();
mat.setColumn(3, pathPos + mOffset);
setTransform(mat);
}
}
if(stream->readFlag())
{
if(stream->readFlag())
{
mTargetPosition = stream->readFlag() ? -1 : -2;
}
else
mTargetPosition = stream->readInt(gClientPathManager->getPathTimeBits(mPathKey));
}
}
void PathedInterior::processTick(const Move* move)
{
if(isServerObject())
{
S32 timeMs = 32;
if(mCurrentPosition != mTargetPosition)
{
S32 delta;
if(mTargetPosition == -1)
delta = timeMs;
else if(mTargetPosition == -2)
delta = -timeMs;
else
{
delta = mTargetPosition - (S32)mCurrentPosition;
if(delta < -timeMs)
delta = -timeMs;
else if(delta > timeMs)
delta = timeMs;
}
mCurrentPosition += delta;
U32 totalTime = gClientPathManager->getPathTotalTime(mPathKey);
while(mCurrentPosition > totalTime)
mCurrentPosition -= totalTime;
while(mCurrentPosition < 0)
mCurrentPosition += totalTime;
}
}
}
void PathedInterior::computeNextPathStep(U32 timeDelta)
{
S32 timeMs = timeDelta;
mStopped = false;
if(mCurrentPosition == mTargetPosition)
{
mExtrudedBox = getWorldBox();
mCurrentVelocity.set(0,0,0);
}
else
{
S32 delta = 0;
if(mTargetPosition < 0)
{
if(mTargetPosition == -1)
delta = timeMs;
else if(mTargetPosition == -2)
delta = -timeMs;
mCurrentPosition += delta;
U32 totalTime = gClientPathManager->getPathTotalTime(mPathKey);
while(mCurrentPosition >= totalTime)
mCurrentPosition -= totalTime;
while(mCurrentPosition < 0)
mCurrentPosition += totalTime;
}
else
{
delta = mTargetPosition - (S32)mCurrentPosition;
if(delta < -timeMs)
delta = -timeMs;
else if(delta > timeMs)
delta = timeMs;
mCurrentPosition += delta;
}
Point3F curPoint;
Point3F newPoint( 0.0, 0.0, 0.0 );
MatrixF mat = getTransform();
mat.getColumn(3, &curPoint);
//gClientPathManager->getPathPosition(mPathKey, mCurrentPosition, newPoint);
newPoint += mOffset;
Point3F displaceDelta = newPoint - curPoint;
mExtrudedBox = getWorldBox();
if(displaceDelta.x < 0)
mExtrudedBox.minExtents.x += displaceDelta.x;
else
mExtrudedBox.maxExtents.x += displaceDelta.x;
if(displaceDelta.y < 0)
mExtrudedBox.minExtents.y += displaceDelta.y;
else
mExtrudedBox.maxExtents.y += displaceDelta.y;
if(displaceDelta.z < 0)
mExtrudedBox.minExtents.z += displaceDelta.z;
else
mExtrudedBox.maxExtents.z += displaceDelta.z;
mCurrentVelocity = displaceDelta * 1000 / F32(timeDelta);
}
Point3F pos;
mExtrudedBox.getCenter(&pos);
MatrixF mat = getTransform();
mat.setColumn(3, pos);
if ( mSustainSound )
{
mSustainSound->setTransform( mat );
mSustainSound->setVelocity( getVelocity() );
}
}
Point3F PathedInterior::getVelocity()
{
return mCurrentVelocity;
}
void PathedInterior::advance(F64 timeDelta)
{
if(mStopped)
return;
if(mCurrentVelocity.len() == 0)
{
// if(mSustainHandle)
// {
// alxStop(mSustainHandle);
// mSustainHandle = 0;
// }
return;
}
MatrixF mat = getTransform();
Point3F newPoint;
mat.getColumn(3, &newPoint);
newPoint += mCurrentVelocity * timeDelta / 1000.0f;
//gClientPathManager->getPathPosition(mPathKey, mCurrentPosition, newPoint);
mat.setColumn(3, newPoint);// + mOffset);
setTransform(mat);
setRenderTransform(mat);
}
U32 PathedInterior::getPathKey()
{
AssertFatal(isServerObject(), "Error, must be a server object to call this...");
SimGroup* myGroup = getGroup();
AssertFatal(myGroup != NULL, "No group for this object?");
for (SimGroup::iterator itr = myGroup->begin(); itr != myGroup->end(); itr++) {
SimPath::Path* pPath = dynamic_cast<SimPath::Path*>(*itr);
if (pPath != NULL) {
U32 pathKey = pPath->getPathIndex();
AssertFatal(pathKey != SimPath::Path::NoPathIndex, "Error, path must have event over at this point...");
return pathKey;
}
}
return SimPath::Path::NoPathIndex;
}
void PathedInterior::setPathPosition(S32 newPosition)
{
resolvePathKey();
if(newPosition < 0)
newPosition = 0;
if(newPosition > S32(gServerPathManager->getPathTotalTime(mPathKey)))
newPosition = S32(gServerPathManager->getPathTotalTime(mPathKey));
mCurrentPosition = mTargetPosition = newPosition;
setMaskBits(NewPositionMask | NewTargetMask);
}
void PathedInterior::setTargetPosition(S32 newPosition)
{
resolvePathKey();
if(newPosition < -2)
newPosition = 0;
if(newPosition > S32(gServerPathManager->getPathTotalTime(mPathKey)))
newPosition = gServerPathManager->getPathTotalTime(mPathKey);
if(mTargetPosition != newPosition)
{
mTargetPosition = newPosition;
setMaskBits(NewTargetMask);
}
}
ConsoleMethod(PathedInterior, setPathPosition, void, 3, 3, "")
{
((PathedInterior *) object)->setPathPosition(dAtoi(argv[2]));
}
ConsoleMethod(PathedInterior, setTargetPosition, void, 3, 3, "")
{
((PathedInterior *) object)->setTargetPosition(dAtoi(argv[2]));
}
//--------------------------------------------------------------------------
bool PathedInterior::readPI(Stream& stream)
{
mName = stream.readSTString();
mInteriorResName = stream.readSTString();
stream.read(&mInteriorResIndex);
stream.read(&mPathIndex);
mathRead(stream, &mOffset);
U32 numTriggers;
stream.read(&numTriggers);
mTriggers.setSize(numTriggers);
for (S32 i = 0; i < mTriggers.size(); i++)
mTriggers[i] = stream.readSTString();
return (stream.getStatus() == Stream::Ok);
}
bool PathedInterior::writePI(Stream& stream) const
{
stream.writeString(mName);
stream.writeString(mInteriorResName);
stream.write(mInteriorResIndex);
stream.write(mPathIndex);
mathWrite(stream, mOffset);
stream.write(mTriggers.size());
for (S32 i = 0; i < mTriggers.size(); i++)
stream.writeString(mTriggers[i]);
return (stream.getStatus() == Stream::Ok);
}
PathedInterior* PathedInterior::clone() const
{
PathedInterior* pClone = new PathedInterior;
pClone->mName = mName;
pClone->mInteriorResName = mInteriorResName;
pClone->mInteriorResIndex = mInteriorResIndex;
pClone->mPathIndex = mPathIndex;
pClone->mOffset = mOffset;
return pClone;
}
| 29.359455 | 115 | 0.63189 | [
"object"
] |
08285e8aed79a860772fb66d6d1a54fb7f178875 | 5,755 | cpp | C++ | src/libpkg/example_qt/server.cpp | rock16/brlcad | 8bdec337e490b31b16b638838f429160d6b877e8 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libpkg/example_qt/server.cpp | rock16/brlcad | 8bdec337e490b31b16b638838f429160d6b877e8 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libpkg/example_qt/server.cpp | rock16/brlcad | 8bdec337e490b31b16b638838f429160d6b877e8 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* S E R V E R . C
* BRL-CAD
*
* Copyright (c) 2006-2022 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file libpkg/example/server.c
*
* Basic pkg server.
*
*/
#include "common.h"
/* system headers */
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include "bio.h"
/* interface headers */
#include "bu/log.h"
#include "bu/str.h"
#include "bu/malloc.h"
#include "bu/getopt.h"
#include "bu/vls.h"
#include "bu/snooze.h"
#include "pkg.h"
#include "ncp.h"
#include <QApplication>
PKGServer::PKGServer()
: QTcpServer()
{
client = NULL;
}
PKGServer::~PKGServer()
{
if (client->pkc_inbuf)
free(client->pkc_inbuf);
BU_PUT(client, struct pkg_conn);
bu_vls_free(&buffer);
}
void
PKGServer::pgetc()
{
// Have a new connection pending, accept it.
s = nextPendingConnection();
int fd = s->socketDescriptor();
bu_log("fd: %d\n", fd);
BU_GET(client, struct pkg_conn);
client->pkc_magic = PKG_MAGIC;
client->pkc_fd = fd;
client->pkc_switch = callbacks;
client->pkc_errlog = 0;
client->pkc_left = -1;
client->pkc_buf = (char *)0;
client->pkc_curpos = (char *)0;
client->pkc_strpos = 0;
client->pkc_incur = client->pkc_inend = 0;
int have_hello = 0;
do {
/* got a connection, process it */
msgbuffer = pkg_bwaitfor (MSG_HELO, client);
if (msgbuffer == NULL) {
bu_log("Failed to process the client connection, still waiting\n");
} else {
bu_log("msgbuffer: %s\n", msgbuffer);
have_hello = 1;
/* validate magic header that client should have sent */
if (!BU_STR_EQUAL(msgbuffer, MAGIC_ID)) {
bu_log("Bizarre corruption, received a HELO without at matching MAGIC ID!\n");
}
}
} while (!have_hello);
// Kick things off with a message
psend(MSG_DATA, "This is a message from the server.");
// For subsequent communications, when the client sends us something
// trigger the print_and_respond slot.
QObject::connect(s, &QTcpSocket::readyRead, this, &PKGServer::print_and_respond);
}
void
PKGServer::print_and_respond()
{
// Grab what the client sent us. We use Qt's mechanisms for this rather than
// libpkg - pkg_suckin doesn't appear to work with the Qt socket.
QByteArray dbuff = s->read(client->pkc_inlen);
// Now that we have the data using Qt, prepare it for processing by libpkg
client->pkc_inbuf = (char *)realloc(client->pkc_inbuf, dbuff.length());
memcpy(client->pkc_inbuf, dbuff.data(), dbuff.length());
client->pkc_incur = 0;
client->pkc_inlen = client->pkc_inend = dbuff.length();
// Buffer is read and staged - process
pkg_process(client);
// Once we have confirmation from the client it got the done message, exit
if (client->pkc_type == MSG_CIAO) {
bu_log("MSG_CIAO\n");
bu_exit(0, "done");
}
// We should have gotten a MSG_DATA input
if (client->pkc_type == MSG_DATA) {
bu_log("MSG_DATA\n");
}
// We want to go back and forth a bit before quitting - count up
// communications cycles and once we hit the threshold send the client the
// DONE message.
if (cycles < 10) {
psend(MSG_DATA, "Acknowledged");
cycles++;
} else {
psend(MSG_CIAO, "DONE");
}
}
int
PKGServer::psend(int type, const char *data)
{
bu_vls_sprintf(&buffer, "%s ", data);
return pkg_send(type, bu_vls_addr(&buffer), (size_t)bu_vls_strlen(&buffer)+1, client);
}
/*
* callback when a HELO message packet is received.
*
* We should not encounter this packet specifically since we listened
* for it before beginning processing of packets as part of a simple
* handshake setup.
*/
void
server_helo(struct pkg_conn *UNUSED(connection), char *buf)
{
bu_log("Unexpected HELO encountered\n");
free(buf);
}
/* callback when a DATA message packet is received */
void
server_data(struct pkg_conn *UNUSED(connection), char *buf)
{
bu_log("Received message from client: %s\n", buf);
free(buf);
}
/* callback when a CIAO message packet is received */
void
server_ciao(struct pkg_conn *UNUSED(connection), char *buf)
{
bu_log("CIAO encountered: %s\n", buf);
free(buf);
}
int
main(int argc, char *argv[])
{
QApplication app(argc, argv);
PKGServer *tcps = new PKGServer;
/* ignore broken pipes, on platforms where we have SIGPIPE */
#ifdef SIGPIPE
(void)signal(SIGPIPE, SIG_IGN);
#endif
/** our server callbacks for each message type */
struct pkg_switch callbacks[] = {
{MSG_HELO, server_helo, "HELO", NULL},
{MSG_DATA, server_data, "DATA", NULL},
{MSG_CIAO, server_ciao, "CIAO", NULL},
{0, 0, (char *)0, (void*)0}
};
tcps->callbacks = (struct pkg_switch *)callbacks;
QObject::connect(
tcps, &PKGServer::newConnection,
tcps, &PKGServer::pgetc,
Qt::QueuedConnection
);
// Start listening for a connection on the default port
tcps->listen(QHostAddress::LocalHost, tcps->port);
app.exec();
}
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
| 26.040724 | 90 | 0.669505 | [
"cad"
] |
082a97395f6afe0cc6d0f721b6880ae19d4c884d | 8,775 | cpp | C++ | lib/lambdapure/ReferenceRewritePattern.cpp | bollu/lz | f5d09b70956072a56c1d9cc0e6907a0261c108a5 | [
"Apache-2.0"
] | 12 | 2020-12-12T17:54:33.000Z | 2022-01-12T00:34:37.000Z | lib/lambdapure/ReferenceRewritePattern.cpp | bollu/lz | f5d09b70956072a56c1d9cc0e6907a0261c108a5 | [
"Apache-2.0"
] | 23 | 2020-11-27T18:53:24.000Z | 2021-12-03T15:29:24.000Z | lib/lambdapure/ReferenceRewritePattern.cpp | bollu/lz | f5d09b70956072a56c1d9cc0e6907a0261c108a5 | [
"Apache-2.0"
] | 1 | 2020-12-12T17:56:56.000Z | 2020-12-12T17:56:56.000Z | #include "Hask/HaskDialect.h"
#include "Hask/HaskOps.h"
#include "lambdapure/Dialect.h"
#include "lambdapure/Passes.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/PatternMatch.h"
#include <iostream>
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
using namespace mlir;
namespace {
class ReferenceRewriterPattern
: public mlir::PassWrapper<ReferenceRewriterPattern, FunctionPass> {
public:
void runOnFunction() override {
auto f = getFunction();
std::vector<mlir::Value> args;
std::vector<int> consumes;
for (int i = 0; i < (int)f.getNumArguments(); ++i) {
args.push_back(f.getArgument(i));
consumes.push_back(-1); // assume ownerships => starts with -1
}
assert(args.size() == consumes.size());
runOnRegion(args, consumes, f.getBody());
}
void runOnRegion(std::vector<mlir::Value> args, std::vector<int> consumes,
mlir::Region ®ion) {
assert(args.size() == consumes.size());
for (Operation &o : region.getOps()) {
MLIRContext *context = o.getContext();
mlir::OpBuilder builder = mlir::OpBuilder(context);
if (mlir::standalone::HaskReturnOp op =
mlir::dyn_cast<standalone::HaskReturnOp>(o)) {
// vv HACK TODO: refactor to use this->context
mlir::Value val = op.getOperand();
onValue(op.getOperation(), args, consumes, val, builder);
addAllDecs(op.getOperation(), args, consumes, builder);
}
if (auto op = mlir::dyn_cast<standalone::HaskConstructOp>(o)) {
MLIRContext *context = op.getContext();
mlir::OpBuilder builder = mlir::OpBuilder(context);
args.push_back(op.getResult());
consumes.push_back(0); // TODO HACK: is this correct?
for (int i = 0; i < (int)op.getNumOperands(); ++i) {
onValue(op.getOperation(), args, consumes, op.getOperand(i), builder);
}
}
if (auto op = mlir::dyn_cast<standalone::CaseOp>(o)) {
for (int i = 0; i < (int)op->getNumRegions(); ++i) {
std::vector<mlir::Value> new_args(args);
std::vector<int> new_consumes(consumes);
Region ®ion = op->getRegion(i);
runOnRegion(new_args, new_consumes, region);
}
}
// who inserts ResetOp??
if (auto op = mlir::dyn_cast<standalone::ResetOp>(o)) {
// TODO HACK: doesn't a reset region have exactly 2 regions?!
// TODO HACK What the fuck is this LOOP?
for (int i = 0; i < (int)op->getNumRegions(); ++i) {
std::vector<mlir::Value> new_args(args);
std::vector<int> new_consumes(consumes);
auto ®ion = op->getRegion(i);
if (i == 0) {
runOnResetRegion(op.getOperand(), new_args, new_consumes, region);
} else {
runOnRegion(new_args, new_consumes, region);
}
}
}
if (mlir::isa<mlir::CallOp>(o) || mlir::isa<standalone::ApOp>(o) ||
mlir::isa<standalone::PapOp>(o)) {
for (int i = 0; i < (int)o.getNumOperands(); ++i) {
onValue(&o, args, consumes, o.getOperand(i), builder);
}
}
} // end for loop over operations
// for (auto it = region.op_begin(); it != region.op_end(); ++it) {
// auto context = it->getContext();
// auto builder = mlir::OpBuilder(context);
// // We start with args consume at -1
// // check for return,ReuseConstructorOp, Constructor, call,
// // application,partial application
// auto name = it->getName().getStringRef().str();
// if (name == "lambdapure.ReturnOp") {
// mlir::Value val = it->getOperand(0);
// onValue(&*it, args, consumes, val, builder);
// addAllDecs(&*it, args, consumes, builder);
// } else if (name == "lambdapure.ReuseConstructorOp") {
// // change the value of in args to the new value
// for (int i = 0; i < (int)args.size(); ++i) {
// if (args[i] == it->getOperand(0)) {
// args[i] = it->getOpResult(0);
// }
// }
// } else if (name == "lambdapure.ConstructorOp") {
// args.push_back(it->getOpResult(0));
// consumes.push_back(0); // TODO HACK: is this correct?
// for (int i = 0; i < (int)it->getNumOperands(); ++i) {
// onValue(&*it, args, consumes, it->getOperand(i), builder);
// }
// } else if (name == "lambdapure.CallOp" || name == "lambdapure.AppOp" ||
// name == "lambdapure.PapOp") {
// for (int i = 0; i < (int)it->getNumOperands(); ++i) {
// onValue(&*it, args, consumes, it->getOperand(i), builder);
// }
// } else if (name == "lambdapure.CaseOp") {
// for (int i = 0; i < (int)it->getNumRegions(); ++i) {
// std::vector<mlir::Value> new_args(args);
// std::vector<int> new_consumes(consumes);
// auto ®ion = it->getRegion(i);
// runOnRegion(new_args, new_consumes, region);
// }
// } else if (name == "lambdapure.ResetOp") {
// for (int i = 0; i < (int)it->getNumRegions(); ++i) {
// std::vector<mlir::Value> new_args(args);
// std::vector<int> new_consumes(consumes);
// auto ®ion = it->getRegion(i);
// if (i == 0) {
// runOnResetRegion(it->getOperand(0), new_args, new_consumes,
// region);
// } else {
// runOnRegion(new_args, new_consumes, region);
// }
// }
// }
// }
}
void runOnResetRegion(mlir::Value resetValue, std::vector<mlir::Value> args,
std::vector<int> consumes, mlir::Region ®ion) {
assert(args.size() == consumes.size());
assert(false && "upgrade this code");
// for (auto it = region.op_begin(); it != region.op_end(); ++it) {
// auto name = it->getName().getStringRef().str();
// if (name == "lambdapure.ProjectionOp" &&
// it->getOperand(0) == resetValue) {
// args.push_back(it->getOpResult(0));
// consumes.push_back(-1);
// }
// }
std::vector<mlir::Value> new_args(args);
std::vector<int> new_consumes(consumes);
runOnRegion(new_args, new_consumes, region);
}
// TODO HACK: should be opOperand?
void onValue(Operation *op, std::vector<mlir::Value> &args,
std::vector<int> &consumes, mlir::Value val,
mlir::OpBuilder &builder) {
assert(args.size() == consumes.size());
if (isIn(args, val)) {
int c = consume(args, consumes, val);
if (c >= 1) {
builder.setInsertionPoint(op);
builder.create<mlir::standalone::IncOp>(builder.getUnknownLoc(), val, 1);
}
} else {
llvm::errs() << "val.getType(): " << val.getType() << "|\n";
builder.setInsertionPoint(op);
builder.create<mlir::standalone::IncOp>(builder.getUnknownLoc(), val, 1);
}
}
int consume(std::vector<mlir::Value> &args, std::vector<int> &consumes,
mlir::Value val) {
std::cerr << "consumes: " << consumes.size() << " |args: " << args.size()
<< "\n";
assert(args.size() == consumes.size());
for (int i = 0; i < (int)args.size(); ++i) {
if (args[i] == val) {
consumes[i]++;
return consumes[i];
}
}
return 0;
// assert(false && "should not reach here.");
}
void addAllDecs(Operation *op, std::vector<mlir::Value> &args,
std::vector<int> &consumes, mlir::OpBuilder &builder) {
assert(args.size() == consumes.size());
builder.setInsertionPoint(op);
for (int i = 0; i < (int)args.size(); ++i) {
if (consumes[i] == -1) {
// HACK: don't really understand why the current code does not handle
// this
if (!args[i].getType().isa<standalone::ValueType>()) {
llvm::errs() << "arg of incorrect type: |" << args[i] << "|\n";
continue;
}
builder.create<mlir::standalone::DecOp>(builder.getUnknownLoc(),
args[i], 1);
}
assert(consumes[i] >= -1);
}
}
bool isIn(std::vector<mlir::Value> vec, mlir::Value val) {
for (auto v : vec) {
if (v == val)
return true;
}
return false;
}
};
} // end anonymous namespace
std::unique_ptr<Pass> mlir::lambdapure::createReferenceRewriterPattern() {
return std::make_unique<ReferenceRewriterPattern>();
}
| 37.340426 | 82 | 0.543476 | [
"vector"
] |
082cbbf645427573827ab77a133d79317dd3ed4e | 3,115 | cc | C++ | code/Homa/src/TubTest.cc | Lossless-Virtual-Switching/Backdraft | 99e8f7acf833d1755a109898eb397c3412fff159 | [
"MIT"
] | 66 | 2018-08-07T12:04:24.000Z | 2022-03-20T15:20:55.000Z | code/Homa/src/TubTest.cc | Lossless-Virtual-Switching/Backdraft | 99e8f7acf833d1755a109898eb397c3412fff159 | [
"MIT"
] | 10 | 2018-04-25T19:10:01.000Z | 2021-01-24T20:41:48.000Z | code/Homa/src/TubTest.cc | Lossless-Virtual-Switching/Backdraft | 99e8f7acf833d1755a109898eb397c3412fff159 | [
"MIT"
] | 14 | 2018-10-19T00:47:41.000Z | 2022-03-01T01:54:17.000Z | /* Copyright (c) 2010-2018, Stanford University
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Tub.h"
#include <gtest/gtest.h>
#include <vector>
namespace Homa {
static_assert(__alignof__(Tub<char>) == 1, "Alignment of Tub<char> is wrong");
static_assert(__alignof__(Tub<uint64_t>) == 8,
"Alignment of Tub<uint64_t> is wrong");
struct Foo {
Foo(int x, int y, int z = 0)
: x(x)
, y(y)
, z(z)
{
++liveCount;
}
~Foo()
{
--liveCount;
}
int getX()
{
return x;
}
int x, y, z;
static int liveCount;
};
int Foo::liveCount = 0;
struct Bar {
Bar()
: x(123456789)
{}
Bar& operator=(const Bar& other)
{
if (this == &other)
return *this;
EXPECT_EQ(123456789, x);
x = other.x;
EXPECT_EQ(123456789, x);
return *this;
}
int x;
};
typedef Tub<Foo> FooTub;
typedef Tub<int> IntTub;
TEST(Tub, basics)
{
{
FooTub fooTub;
EXPECT_FALSE(fooTub);
EXPECT_FALSE(fooTub.get());
Foo* foo = fooTub.construct(1, 2, 3);
EXPECT_TRUE(fooTub);
EXPECT_EQ(1, foo->x);
EXPECT_EQ(2, foo->y);
EXPECT_EQ(3, foo->z);
EXPECT_EQ(foo, fooTub.get());
EXPECT_EQ(foo, &*fooTub);
EXPECT_EQ(1, fooTub->getX());
EXPECT_EQ(foo, fooTub.construct(5, 6));
EXPECT_EQ(5, foo->x);
EXPECT_EQ(6, foo->y);
EXPECT_EQ(0, foo->z);
}
EXPECT_EQ(0, Foo::liveCount);
}
TEST(Tub, copyAndAssign)
{
IntTub x;
x.construct(5);
IntTub y;
y = x;
IntTub z(y);
EXPECT_EQ(5, *y);
EXPECT_EQ(5, *z);
int p = 5;
IntTub q(p);
EXPECT_EQ(5, *q);
Tub<Bar> b1;
Tub<Bar> b2;
b2.construct();
// Assignment to a tub with an unconstructed value needs
// to use the copy constructor instead of assignment operator.
b1 = b2;
}
TEST(Tub, putInVector)
{
std::vector<IntTub> v;
v.push_back(IntTub());
IntTub eight;
eight.construct(8);
v.push_back(eight);
v.insert(v.begin(), IntTub());
EXPECT_FALSE(v[0]);
EXPECT_FALSE(v[1]);
EXPECT_TRUE(v[2]);
EXPECT_EQ(static_cast<void*>(&v[2]), static_cast<void*>(v[2].get()));
EXPECT_EQ(8, *v[2]);
}
TEST(Tub, boolConversion)
{
IntTub x;
EXPECT_FALSE(x);
x.construct(5);
EXPECT_TRUE(x);
}
} // namespace Homa
| 22.737226 | 78 | 0.598074 | [
"vector"
] |
082f59a5bad6c4ebe6eea5e8dda841239c7d50e6 | 3,236 | cpp | C++ | codechef/CLMTRO/Compilation Error.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codechef/CLMTRO/Compilation Error.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codechef/CLMTRO/Compilation Error.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 27-02-2019 21:26:10
* solution_verdict: Compilation Error language: C++14
* run_time: 0.00 sec memory_used: 0M
* problem: https://www.codechef.com/problems/CLMTRO
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=5e3;
const long inf=1e18;
int aa[N+2],bb[N+2],sz[N+2];
long dp[N+2][3][N+2];
vector<int>adj[N+2];
bool cmp(int a,int b)
{
return sz[a]>sz[b];
}
void dfs(int node,int par)
{
sz[node]=1;
for(auto x:adj[node])
{
if(x==par)continue;
dfs(x,node);sz[node]+=sz[x];
}
dp[node][0][0]=0;
dp[node][0][1]=aa[node];
dp[node][2][1]=bb[node];
dp[node][1][0]=0;
dp[node][2][0]=0;
sort(adj[node].begin(),adj[node].end());
int f=0;
for(auto x:adj[node])
{
if(x==par)continue;
if(!f)
{
for(int i=sz[x]+1;i>=1;i--)
{
dp[node][0][i]=min(dp[node][0][i],dp[x][0][i]);
dp[node][0][i]=min(dp[node][0][i],dp[x][0][i-1]+aa[node]);
dp[node][0][i]=min(dp[node][0][i],dp[x][1][i]);
dp[node][0][i]=min(dp[node][0][i],dp[x][1][i-1]+aa[node]);
dp[node][1][i]=min(dp[node][1][i],dp[x][1][i-1]+bb[node]);
dp[node][1][i]=min(dp[node][1][i],dp[x][2][i-1]+bb[node]);
dp[node][2][i]=min(dp[node][2][i],dp[x][0][i-1]+bb[node]);
dp[node][2][i]=min(dp[node][2][i],dp[x][1][i-1]+bb[node]);
dp[node][2][i]=min(dp[node][2][i],dp[x][2][i-1]+bb[node]);
}
f=1;continue;
}
for(int i=sz[node];i>=1;i--)
{
for(int j=0;j<=min(i-1,sz[x]);j++)
{
dp[node][0][i]=min(dp[node][0][i],dp[x][0][j]+dp[node][0][i-j]);
dp[node][0][i]=min(dp[node][0][i],dp[x][1][j]+dp[node][0][i-j]);
dp[node][1][i]=min(dp[node][1][i],dp[x][1][j]+dp[node][1][i-j-1]+bb[i]);
dp[node][1][i]=min(dp[node][1][i],dp[x][2][j]+dp[node][1][i-j-1]+bb[i]);
dp[node][2][i]=min(dp[node][2][i],dp[x][0][j]+dp[node][2][i-j-1]+bb[i]);
dp[node][2][i]=min(dp[node][2][i],dp[x][1][j]+dp[node][2][i-j-1]+bb[i]);
dp[node][2][i]=min(dp[node][2][i],dp[x][2][j]+dp[node][2][i-j-1]+bb[i]);
}
}
}
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
dont complie
int t;cin>>t;
while(t--)
{
int n;long k;cin>>n>>k;
for(int i=1;i<=n;i++)cin>>aa[i];
for(int i=1;i<=n;i++)cin>>bb[i];
for(int i=1;i<=n;i++)
adj[i].clear();
for(int i=1;i<n;i++)
{
int u,v;cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i=0;i<=n;i++)
for(int j=0;j<3;j++)
for(int l=0;l<=n;l++)
dp[i][j][l]=inf;
dfs(1,-1);int ans=0;
for(int i=1;i<=n;i++)
{
if(min(dp[1][0][i],dp[1][1][i])<=k)
ans=i;
}
int x=1;
for(int i=1;i<=n;i++)
{
cout<<dp[x][0][i]<<" "<<dp[x][1][i]<<" "<<dp[x][2][i]<<endl;
}
cout<<ans<<endl;
}
return 0;
} | 31.115385 | 111 | 0.425525 | [
"vector"
] |
0837c6c45e33cb7c64acd3b6a0612fcff04a09fd | 5,052 | cpp | C++ | src/util/file.cpp | jasonwhite/peclean | adc6cacdc2405a217f9ea2178b6ec3e2cdc6200c | [
"MIT"
] | 251 | 2016-11-28T15:45:33.000Z | 2022-02-25T01:56:27.000Z | src/util/file.cpp | wjk/ducible | adc6cacdc2405a217f9ea2178b6ec3e2cdc6200c | [
"MIT"
] | 11 | 2016-09-19T03:00:35.000Z | 2020-04-30T01:43:26.000Z | src/util/file.cpp | wjk/ducible | adc6cacdc2405a217f9ea2178b6ec3e2cdc6200c | [
"MIT"
] | 20 | 2016-10-23T12:36:42.000Z | 2021-02-02T07:53:18.000Z | /*
* Copyright (c) 2016 Jason White
*
* 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 "util/file.h"
#include <codecvt>
#include <iostream>
#include <locale>
#include <sstream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#endif
const FileMode<char> FileMode<char>::readExisting("rb");
const FileMode<char> FileMode<char>::writeEmpty("wb");
const FileMode<wchar_t> FileMode<wchar_t>::readExisting(L"rb");
const FileMode<wchar_t> FileMode<wchar_t>::writeEmpty(L"wb");
/**
* Deletion object to be used with shared_ptr.
*/
class FileCloser {
public:
void operator()(FILE* f) const { fclose(f); }
};
#ifdef _WIN32
FileRef openFile(const char* path, FileMode<char> mode) {
FILE* f = NULL;
if (fopen_s(&f, path, mode.mode) != 0) {
auto err = errno;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "Failed to open file '" << path << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
return FileRef(f, FileCloser());
}
FileRef openFile(const wchar_t* path, FileMode<wchar_t> mode) {
FILE* f = NULL;
if (_wfopen_s(&f, path, mode.mode) != 0) {
auto err = errno;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "Failed to open file '" << converter.to_bytes(path) << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
return FileRef(f, FileCloser());
}
void renameFile(const char* src, const char* dest) {
if (!MoveFileExA(src, dest, MOVEFILE_REPLACE_EXISTING)) {
throw std::system_error(GetLastError(), std::system_category(),
"failed to rename file");
}
}
void renameFile(const wchar_t* src, const wchar_t* dest) {
if (!MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING)) {
auto err = GetLastError();
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "failed to rename file '" << converter.to_bytes(src) << "' to '"
<< converter.to_bytes(dest) << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
}
void deleteFile(const char* path) {
if (!DeleteFileA(path)) {
auto err = GetLastError();
std::stringbuf buf;
std::ostream msg(&buf);
msg << "failed to delete file '" << path << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
}
void deleteFile(const wchar_t* path) {
if (!DeleteFileW(path)) {
auto err = GetLastError();
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "failed to delete file '" << converter.to_bytes(path) << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
}
#else // !_WIN32
FileRef openFile(const char* path, FileMode<char> mode) {
FILE* f = fopen(path, mode.mode);
if (!f) {
auto err = errno;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "Failed to open file '" << path << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
return FileRef(f, FileCloser());
}
void renameFile(const char* src, const char* dest) {
if (rename(src, dest) != 0) {
auto err = errno;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "failed to rename file '" << src << "' to '" << dest << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
}
void deleteFile(const char* path) {
if (remove(path) != 0) {
auto err = errno;
std::stringbuf buf;
std::ostream msg(&buf);
msg << "failed to delete file '" << path << "'";
throw std::system_error(err, std::system_category(), buf.str());
}
}
#endif // _WIN32
| 27.606557 | 80 | 0.628068 | [
"object"
] |
0838c795f0cdfdb14406da2c49a1b6873c30010f | 31,296 | cpp | C++ | pepnovo/src/PepNovo_main.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | pepnovo/src/PepNovo_main.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | pepnovo/src/PepNovo_main.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null |
/*
Copyright 2008, The Regents of the University of California
All Rights Reserved
Permission to use, copy, modify and distribute any part of this
program for educational, research and non-profit purposes, without fee,
and without a written agreement is hereby granted, provided that the
above copyright notice, this paragraph and the following three paragraphs
appear in all copies.
Those desiring to incorporate this work into commercial
products or use for commercial purposes should contact the Technology
Transfer & Intellectual Property Services, University of California,
San Diego, 9500 Gilman Drive, Mail Code 0910, La Jolla, CA 92093-0910,
Ph: (858) 534-5815, FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE, EVEN
IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
THE SOFTWARE PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE UNIVERSITY
OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS. THE UNIVERSITY OF CALIFORNIA MAKES NO
REPRESENTATIONS AND EXTENDS NO WARRANTIES OF ANY KIND, EITHER IMPLIED OR
EXPRESS, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT THE USE OF
THE SOFTWARE WILL NOT INFRINGE ANY PATENT, TRADEMARK OR OTHER RIGHTS.
*/
#include "AllScoreModels.h"
#include "PeptideRankScorer.h"
#include "FileManagement.h"
#include "DeNovoDp.h"
#include "DeNovoSolutions.h"
#include "auxfun.h"
#include "includes.h"
#include "MSBlast.h"
const string build_name = "20101117";
void print_help(const char *message)
{
printf("***************************************************************************\n\n%s\n",message);
printf("\nPepNovo+ - de Novo peptide sequencing and\nMS-Filter - spectal quality scoring, precursor mass correction and chage determination.\n");
printf("Release %s.\nAll rights reserved to the Regents of the University of California.\n\n",build_name.c_str());
printf("Required arguments:\n");
printf("-------------------\n\n");
printf("-model <model name>\n\n");
printf("-file <path to input file> - PepNovo can analyze dta,mgf and mzXML files\n");
printf(" OR\n");
printf("-list <path to text file listing input files>\n\n");
printf("\nOptional PepNovo arguments: \n");
printf("----------------------------- \n");
printf("-prm - only print spectrum graph nodes with scores.\n");
printf("-prm_norm - prints spectrum graph scores after normalization and removal of negative scores.\n");
printf("-correct_pm - finds optimal precursor mass and charge values.\n");
printf("-use_spectrum_charge - does not correct charge.\n");
printf("-use_spectrum_mz - does not correct the precursor m/z value that appears in the file.\n");
printf("-no_quality_filter - does not remove low quality spectra.\n");
printf("-output_aa_probs - calculates the probabilities of individual amino acids.\n");
printf("-output_cum_probs - calculates the cumulative probabilities (that at least one sequence upto rank X is correct).\n");
printf("-fragment_tolerance < 0-0.75 > - the fragment tolerance (each model has a default setting)\n");
printf("-pm_tolerance < 0-5.0 > - the precursor masss tolerance (each model has a default setting)\n");
printf("-PTMs <PTM string> - seprated by a colons (no spaces) e.g., M+16:S+80:N+1\n");
printf("-digest <NON_SPECIFIC,TRYPSIN> - default TRYPSIN\n");
printf("-num_solutions < 1-2000 > - default 20\n");
printf("-tag_length < 3-6> - returns peptide sequence of the specified length (only lengths 3-6 are allowed).\n");
printf("-model_dir < path > - directory where model files are kept (default ./Models)\n\n");
printf("-max_pm <X> - X is the maximal precursor mass to be considered (good for shorty searhces).\n");
printf("\nOptional MS-Filter arguments:\n");
printf( "-----------------------------\n");
printf("-min_filter_prob <xx=0-1.0> - filter out spectra from denovo/tag/prm run with a quality probability less than x (e.g., x=0.1)\n");
printf("-pmcsqs_only - only output the corrected precursor mass, charge and filtering values\n");
printf("-filter_spectra <sqs thresh> <out dir> - outputs MGF files for spectra that have a minimal qulaity score above *thresh* (it is recomended to use a value of 0.05-0.1).");
printf(" These MGF files will be sent to the directory given in out_dir and have a name with the prefix given in the third argument.\n");
printf(" NOTE: this option must be used in conjuction with \"-pmcsqs_only\" the latter option will also correct the m/z value and assign a charge to the spectrum.\n\n");
printf("-pmcsqs_and_prm <min prob> - print spectrum graph nodes for spectra that have an SQS probability score of at least <min prob> (typically should have a value 0-0.2)\n\n");
// printf("\nTag file for InsPecT:\n");
// printf( "---------------------\n");
// printf("PepNovo can create a tag file that can be read and used by InsPecT.\n");
// printf("To generate such tags you must use the -file option and supply the following command:\n");
// printf("-inspect_tags len1:num1:len2:num2...\n");
// printf(" For example, -inspect_tags 4:5:5:20:6:50, will generate 5 tags of length 4, 20 tags of length 5 and 50 tags of length 6.\n");
// printf("-tag_suffix <X> - This command will genrate a file with the same name as the input file, but with a suffix \"X.txt\" (default suffix tags.txt).\n\n");
// printf("\nRescoring InsPecT results:\n");
// printf( "--------------------------\n");
// printf("PepNovo can rescore an InsPecT raw results file, replacing the MQScore and delta score fields with the scores obtained with the rank modesl.");
// printf("To run in this mode you need to supply a model (\"-model\") a list of PTMs (\"-PTMs\") and the following flag:\n");
// printf("-rescore_inspect <X> <Y> - where <X> is the complete path to the original results file and <Y> is the path to the new score file.\n");
// printf("-large_db_model - if rescoring searches of large databases (e.g., 300MB+), this flag can later scoring to give better results.\n");
printf("\nPredicting fragmentation patterns:\n");
printf( "----------------------------------\n");
printf("-predict_fragmentation <X> - X is the input file with a list of peptides and charges (one per line)\n");
printf("-num_peaks <N> - N is the maximal number of fragment peaks to predict\n\n");
printf("\nParameters for Blast:\n");
printf( "---------------------\n");
printf("-msb_generate_query - performs denovo sequencing and generates a BLAST query.\n");
printf("-msb_merge_queries - takes a list of PepNovo \"_full.txt\" files, merges them and creates queries(list should be given with -list flag).\n");
printf("-msb_query_name <X> - the name to be given to the main output file.\n");
printf("-msb_query_size <X> - max size of MSB query allowed (default X=1000000).\n");
printf("-msb_num_solutions <X> - number of sequences to generate per spectrum (default X=7).\n");
printf("-msb_min_score <X> - the minimal MS-Blast score to be included in the query, default X=4.0 .\n");
// printf("-msb_exclude_file <X> - X is a file with protein names (or parts , ids, ec.) to exclude (exclude peptides that are assigned to these proteins in final query)\n");
// printf("\nParameters for \"get shorty\":\n");
// printf( "----------------------------\n");
// printf("-shorty_fasta <X> - path to fasta file with protein db\n");
// printf("-shorty_num_proteins <X> - searches only the first X proteins in the fasta file.\n");
// printf("-shorty_name <X> - prefix name for shorty output files.\n");
printf("\nCitations:\n");
printf( "----------\n");
printf("- Frank, A. and Pevzner, P. \"PepNovo: De Novo Peptide Sequencing via Probabilistic Network Modeling\", Analytical Chemistry 77:964-973, 2005.\n");
printf("- Frank, A., Tanner, S., Bafna, V. and Pevzner, P. \"Peptide sequence tags for fast database search in mass-spectrometry\", J. Proteome Res. 2005 Jul-Aug;4(4):1287-95.\n");
printf("- Frank, A.M., Savitski, M.M., Nielsen, L.M., Zubarev, R.A., Pevzner, P.A. \"De Novo Peptide Sequencing and Identification with Precision Mass Spectrometry\", J. Proteome Res. 6:114-123, 2007.\n");
printf("- Frank, A.M. \"A Ranking-Based Scoring Function for Peptide-Spectrum Matches\", J.Proteome Res. 8:2241-2252, 2009.\n");
printf("\nPlease send comments and bug reports to Ari Frank (arf@cs.ucsd.edu).\n\n");
exit(1);
}
int main(int argc, char **argv)
{
AllScoreModels model;
int i;
char ann_file[256];
char out_file[256];
char input_file[256];
char inspect_results_file[256];
char list_file[256];
char model_file[256];
char initial_model[256];
char model_dir[256];
char PTM_string[256];
char mgf_out_dir[256];
char neg_spec_list[256];
char tag_string[64];
char tag_suffix[64];
string msb_query_name = std::string();
string msb_exclude_file = std::string();
string fragmentation_file = std::string();
int num_frag_peaks = 25;
bool got_input_file=false,got_model_file=false, got_list_file=false;
bool got_model_dir=false, got_initial_model=false, got_PTM_string = false, got_neg_spec_list=false;
bool prm_only=false;
bool prm_norm=false;
bool pmcsqs_only = false;
bool got_filter_spectra = false;
bool pmcsqs_and_prm = false;
bool train_flag = false;
bool correct_pm = false;
bool use_spectrum_charge = false;
bool use_spectrum_mz = false;
bool use_large_db_model = false;
bool perform_filter = true;
bool output_aa_probs = false;
bool indOutputCumulativeProbs = false;
bool make_inspect_tags = false;
bool make_training_fa = false;
bool test_tags = false;
bool got_make_ann_mgf = false;
bool got_make_training_mgf = false;
bool got_rescore_inspect = false;
bool got_recalibrate_inspect = false;
bool got_make_peak_examples = false;
bool got_msb = false;
bool got_msb_generate_query = false;
bool got_msb_merge_queries = false;
bool got_fragmentation_prediction = false;
int start_train_idx=0;
int end_train_idx = POS_INF;
int specific_charge=-1;
int specific_size=-1;
int specific_region=-1;
int specific_idx = -1;
int file_start_idx =0;
int tag_length = 0;
int num_solutions = 20;
int digest_type = TRYPSIN_DIGEST;
mass_t train_tolerance=2.0;
float min_pmcsqs_prob = -1.0;
mass_t fragment_tolerance = -1.0;
mass_t pm_tolerance = -1.0;
float sqs_filter_thresh = 0.0;
float min_filter_prob = 0.0;
int num_test_cases=-1;
int num_training_spectra=-1;
int msb_query_size = 1000000;
int msb_num_solutions = 7;
float msb_min_score = 4.0;
float max_pm = 0.0;
seedRandom(112233);
strcpy(tag_suffix,"tags");
// read command line arguments
i=1;
while (i<argc)
{
if (! strcmp(argv[i],"-make_ann_mgf"))
{
if (++i == argc)
print_help("Missing file ann file!");
strcpy(ann_file,argv[i]);
if (++i == argc)
print_help("Missing file out file!");
strcpy(out_file,argv[i]);
got_make_ann_mgf=true;
}
else
if (! strcmp(argv[i],"-predict_fragmentation"))
{
if (++i == argc)
print_help("Missing fragmentation file!");
fragmentation_file = std::string(argv[i]);
got_fragmentation_prediction = true;
}
else if (! strcmp(argv[i],"-num_peaks"))
{
if (++i == argc)
print_help("Missing num peaks!");
num_frag_peaks = atoi(argv[i]);
if (num_frag_peaks<1)
error("-num_peaks must be>0");
}
else
if (! strcmp(argv[i],"-make_training_mgf"))
{
if (++i == argc)
print_help("Missing file out file!");
strcpy(out_file,argv[i]);
if (++i == argc)
print_help("Missing num training spectra!");
num_training_spectra = atoi(argv[i]);
if (num_training_spectra<=0)
print_help("Error: -make_training_mgf [out_file] [num spectra>0]\n");
got_make_training_mgf=true;
}
else if (!strcmp(argv[i],"-file"))
{
if (++i == argc)
print_help("Missing file name!");
strcpy(input_file,argv[i]);
got_input_file=true;
}
else
if (!strcmp(argv[i],"-list"))
{
if (++i == argc)
print_help("Missing list name!");
strcpy(list_file,argv[i]);
got_list_file=true;
}
else if (!strcmp(argv[i],"-file_start_idx"))
{
if (++i == argc)
print_help("Missing file start idx!");
file_start_idx = atoi(argv[i]);
}
else if (!strcmp(argv[i],"-model"))
{
if (++i == argc)
print_help("Missing model name!");
strcpy(model_file,argv[i]);
got_model_file=true;
}
else if (! strcmp(argv[i],"-model_dir"))
{
if (++i == argc)
print_help("Missing model dir name!");
strcpy(model_dir,argv[i]);
got_model_dir=true;
}
else if (! strcmp(argv[i],"-fragment_tolerance"))
{
if (++i == argc)
print_help("Missing model dir name!");
fragment_tolerance = atof(argv[i]);
if (fragment_tolerance<0 || fragment_tolerance>0.75)
print_help("Error: -fragment_toelerance should be 0-0.75\n");
}
else if (! strcmp(argv[i],"-pm_tolerance"))
{
if (++i == argc)
print_help("Missing model dir name!");
pm_tolerance = atof(argv[i]);
if (pm_tolerance<0 || pm_tolerance>5.0)
print_help("Error: -pm_toelerance should be 0-5.0\n");
}
else if (!strcmp(argv[i],"-num_solutions"))
{
if (++i == argc)
print_help("Missing number of solutions!");
num_solutions = atoi(argv[i]);
if (num_solutions<=0 || num_solutions> 2000)
print_help("Error: -num_solutions should be 1-2000\n");
}
else if (!strcmp(argv[i],"-tag_length"))
{
if (++i == argc)
print_help("Missing minimum length parameter!");
tag_length = atoi(argv[i]);
if (tag_length<3 || tag_length>6)
print_help("Error: -tag_length value must be 3-6\n");
}
else if (!strcmp(argv[i],"-digest"))
{
if (++i == argc)
print_help("Missing digest type parameter : NON_SPECIFIC, TRYPSIN, Gluc\n");
if (! strcmp(argv[i],"NON_SPECIFIC"))
{
digest_type = NON_SPECIFIC_DIGEST;
}
else if (! strcmp(argv[i],"TRYPSIN"))
{
digest_type = TRYPSIN_DIGEST;
}
else if (! strcmp(argv[i],"GluC"))
{
digest_type = GLUC_DIGEST;
}
else
{
printf("Error: bad digest type: %s\n",argv[i]);
print_help("Supported digest types: NON_SPECIFIC, TRYPSIN, GluC.");
}
}
else if (! strcmp(argv[i],"-use_spectrum_charge"))
{
use_spectrum_charge = true;
}
else if (! strcmp(argv[i],"-use_spectrum_mz"))
{
use_spectrum_mz = true;
}
else if (! strcmp(argv[i],"-no_quality_filter"))
{
perform_filter = false;
}
else if (! strcmp(argv[i],"-correct_pm"))
{
correct_pm = true;
}
else if (! strcmp(argv[i],"-prm"))
{
prm_only = true;
}
else if (! strcmp(argv[i],"-prm_norm"))
{
prm_norm = true;
prm_only = true;
}
else if (! strcmp(argv[i],"-output_aa_probs"))
{
output_aa_probs=true;
}
else if (! strcmp(argv[i],"-output_cum_probs"))
{
indOutputCumulativeProbs=true;
}
else if (! strcmp(argv[i],"-pmcsqs_only"))
{
pmcsqs_only = true;
}
else if (! strcmp(argv[i],"-min_filter_prob"))
{
if (++i == argc)
print_help("Missing minimum probability parmater after -min_filter_prob !\n");
min_filter_prob = -1.0;
min_filter_prob = atof(argv[i]);
if (min_filter_prob<0.0 || min_filter_prob>=1.0 || argv[i][0] != '0')
{
print_help("The flag -min_filter_prob should be followed by a minimal probability value [0-1.0]\n");
exit(1);
}
}
else if ( ! strcmp(argv[i],"-filter_spectra"))
{
got_filter_spectra = true;
if (++i == argc)
print_help("Missing minimum probability parmater after -filter_spectra !\n");
sqs_filter_thresh=atof(argv[i]);
if (sqs_filter_thresh <0 || sqs_filter_thresh>1.0)
print_help("Error: the sqs threshold should be in the range 0-1 (recommended below 0.1)\n");
if (++i == argc)
print_help("Missing output directory for MGF files (second argument after -filter_spectra)!\n");
strcpy(mgf_out_dir,argv[i]);
}
else if (! strcmp(argv[i],"-specific_idx"))
{
if (++i == argc)
print_help("Missing idx!");
specific_idx=atoi(argv[i]);
}
else if (! strcmp(argv[i],"-train_model"))
{
train_flag = true;
}
else if (! strcmp(argv[i],"-train_tolerance"))
{
if (++i == argc)
print_help("Missing training tolerance!");
train_tolerance = atof(argv[i]);
if (train_tolerance<0.001 || train_tolerance>1.0)
print_help("Error: training tolerance should be in the range 0.001 - 1.0\n");
}
else if (! strcmp(argv[i],"-start_train_idx"))
{
if (++i == argc)
print_help("Missing start_train_idx!");
start_train_idx = atoi(argv[i]);
}
else if (! strcmp(argv[i],"-end_train_idx"))
{
if (++i == argc)
print_help("end_train_idx!");
end_train_idx = atoi(argv[i]);
}
else if (! strcmp(argv[i],"-specific_reigon_model"))
{
if (++i == argc)
print_help("specific_reigon_model!");
specific_charge = atoi(argv[i++]);
specific_size = atoi(argv[i++]);
specific_region = atoi(argv[i]);
}
else if (! strcmp(argv[i],"-specific_charge"))
{
if (++i == argc)
print_help("specific_charge!");
specific_charge = atoi(argv[i]);
}
else if (! strcmp(argv[i],"-specific_size"))
{
if (++i == argc)
print_help("specific_size!");
specific_size = atoi(argv[i]);
}
else if (! strcmp(argv[i],"-initial_model"))
{
got_initial_model = true;
if (++i == argc)
print_help("Missing initial model name!");
strcpy(initial_model,argv[i]);
}
else if (! strcmp(argv[i],"-neg_spec_list"))
{
got_neg_spec_list = true;
if (++i == argc)
print_help("Missing neg spec list!");
strcpy(neg_spec_list,argv[i]);
}
else if (! strcmp(argv[i],"-PTMs"))
{
got_PTM_string = true;
if (++i == argc)
print_help("Missing PTM list!");
strcpy(PTM_string,argv[i]);
}
else if (! strcmp(argv[i],"-inspect_tags"))
{
make_inspect_tags=true;
if (++i == argc)
print_help("inspect_tags!");
strcpy(tag_string,argv[i]);
}
else if (! strcmp(argv[i],"-rescore_inspect"))
{
got_rescore_inspect = true;
if (++i == argc)
print_help("Missing results file!");
strcpy(inspect_results_file,argv[i]);
if (++i == argc)
print_help("Missing new results file!");
strcpy(out_file,argv[i]);
}
else if (! strcmp(argv[i],"-large_db_model"))
{
use_large_db_model = true;
}
else if (! strcmp(argv[i],"-recalibrate_inspect"))
{
got_recalibrate_inspect = true;
if (++i == argc)
print_help("Missing results file!");
strcpy(inspect_results_file,argv[i]);
if (++i == argc)
print_help("Missing new results file!");
strcpy(out_file,argv[i]);
}
else if ( ! strcmp(argv[i],"-make_peak_examples"))
{
got_make_peak_examples=true;
}
else if (! strcmp(argv[i],"-make_training_fa"))
{
make_training_fa=true;
}
else if (! strcmp(argv[i],"-test_tags"))
{
test_tags=true;
if (++i == argc)
print_help("test_tags!");
strcpy(tag_string,argv[i]);
}
else if (! strcmp(argv[i],"-num_test_cases"))
{
if (++i == argc)
print_help("num_test_cases!");
num_test_cases = atoi(argv[i]);
}
else if (! strcmp(argv[i],"-tag_suffix"))
{
if (++i == argc)
print_help("tag suffix!");
strcpy(tag_suffix,argv[i]);
}
else if (! strcmp(argv[i],"-msb_query_name"))
{
if (++i == argc)
print_help("msb query name!");
msb_query_name=std::string(argv[i]);
got_msb=true;
}
else if (! strcmp(argv[i],"-msb_query_size"))
{
if (++i == argc)
print_help("msb_query_size!");
msb_query_size = atoi(argv[i]);
got_msb=true;
}
else if (! strcmp(argv[i],"-msb_num_solutions"))
{
if (++i == argc)
print_help("msb_num_solutions!");
msb_num_solutions = atoi(argv[i]);
got_msb=true;
}
else if (! strcmp(argv[i],"-msb_min_score"))
{
if (++i == argc)
print_help("msb_min_score!");
msb_min_score = atof(argv[i]);
got_msb=true;
}
else if (! strcmp(argv[i],"-msb_merge_queries"))
{
got_msb_merge_queries = true;
}
else if (! strcmp(argv[i],"-msb_generate_query"))
{
got_msb_generate_query = true;
}
else if (! strcmp(argv[i],"-msb_exclude_file"))
{
if (++i == argc)
print_help("missing exclude!");
msb_exclude_file = std::string(argv[i]);
got_msb=true;
}
else if (! strcmp(argv[i],"-max_pm"))
{
if (++i == argc)
print_help("-max_pm!");
max_pm=atof(argv[i]);
}
else
{
printf("**********************************************************\n");
printf("\nError: Unkown command line option: %s\n\n",argv[i]);
print_help("");
exit(0);
}
i++;
}
if ((got_msb_generate_query || got_msb_merge_queries ) && msb_query_name.length() == 0)
print_help("Error: must provide query name (-msb_query_name)!");
if (! got_model_file)
print_help("Error: Missing model name!");
if (! got_input_file && ! got_list_file && ! got_fragmentation_prediction)
print_help("Error: missing input file (either -file or -list must be used).");
Config *config = model.get_config();
if (got_model_dir)
config->set_resource_dir(string(model_dir));
///////////////////////////////////////////////////////////////////
// Make input file list
vector<string> list_vector;
if (got_list_file)
{
read_paths_into_list(list_file, list_vector);
}
else
list_vector.push_back(input_file);
//////////////////////////////////////////////////////////////////
// Mergr MS-BLAST Queries
if (got_msb_merge_queries)
{
if (list_vector.size() <1)
error("Must supply multiple paths to \"full.txt\" files with -list!");
MSBlastCollector msbc;
msbc.mergeAndSplitQueries(msb_query_name.c_str(), list_vector, msb_num_solutions, msb_query_size, msb_min_score);
return(0);
}
//////////////////////////////////////////////////////////////////
// Model Training
if (train_flag)
{
if (start_train_idx>0 && ! got_initial_model)
{
strcpy(initial_model, model_file);
got_initial_model = true;
}
if (got_initial_model)
{
model.read_model(initial_model);
if (got_PTM_string)
config->apply_selected_PTMs(PTM_string);
model.read_rank_models(initial_model,true);
model.read_cum_seq_prob_models(initial_model,true);
}
else
{
if (train_tolerance > 1.0)
{
cout << "Error: must supply approximate fragment tolerance when training new model (e.g., -train_tolerance 0.5)" << endl;
exit(1);
}
config->init_with_defaults();
config->set_tolerance(train_tolerance);
config->set_digest_type(digest_type);
if (got_PTM_string)
config->apply_selected_PTMs(PTM_string);
}
model.set_model_name(string(model_file));
FileManager fm;
SpectraAggregator sa;
if (! got_list_file)
{
if (got_input_file)
{
sa.initializeFromSpectraFilePath(input_file, config);
}
else
error("Must supply a list of annotated spectra for training!");
}
else
{
sa.initializeFromTextFile(list_file, config);
}
model.trainModelsInStages(model_file,fm, sa,
train_tolerance,
start_train_idx,
end_train_idx,
specific_charge,
specific_size,
specific_region,
(got_neg_spec_list ? neg_spec_list : NULL));
model.write_model();
exit(0);
}
///////////////////////////////////////////////////////////////////
// Model initializing (running some sort of de novo, need a model)
//
const time_t start_time = time(NULL);
cout << "PepNovo+ Build " << build_name << endl;
cout << "Copyright 2010, The Regents of the University of California. All Rights Reserved." << endl;
cout << "Created by Ari Frank (arf@cs.ucsd.edu)" << endl << endl;
cout << "Initializing models (this might take a few seconds)... " << flush;
// TODO: incorporate PTM line into the model reading and also the other model stuff below
model.read_model(model_file,true);
if (got_PTM_string)
config->apply_selected_PTMs(PTM_string);
model.getPeptideCompositionAssigner().init_aa_translations();
model.read_rank_models(model_file, true, use_large_db_model);
model.read_cum_seq_prob_models(model_file,true);
cout << "Done." << endl;
config = model.get_config();
config->set_digest_type(digest_type);
if (fragment_tolerance>0)
config->set_tolerance(fragment_tolerance);
if (pm_tolerance>0)
config->setPrecursorMassTolerance(pm_tolerance);
if (correct_pm)
config->set_need_to_estimate_pm(1);
if (use_spectrum_mz)
config->set_use_spectrum_mz(1);
if (use_spectrum_charge)
config->set_use_spectrum_charge(1);
if (! perform_filter)
config->set_filter_flag(0);
if (config->get_pm_tolerance()<0.1)
config->set_need_to_estimate_pm(0);
cout << setprecision(4) << fixed;
cout << "Fragment tolerance : " << config->getTolerance() << endl;
cout << "PM tolernace : " << config->get_pm_tolerance() << endl;
cout << "PTMs considered : " ;
if (got_PTM_string)
{
cout << PTM_string << endl;
}
else
{
cout << "None" << endl;
}
//////////////////////////////////////////////////////////////////
// Generaqte MS-BLAST Queries
if (got_msb || got_msb_merge_queries || got_msb_generate_query)
{
if (! (got_msb_merge_queries || got_msb_generate_query))
error("Must use one of the following flags for BLAST queries: -msb_generate_query or -msb_merge_queries");
if (list_vector.size() <1)
error("Must supply multiple paths to \"full.txt\" files with -list!");
MSBlastCollector msbc;
if (got_msb_generate_query)
{
msbc.generateMsBlastSequences(msb_query_name.c_str(), list_vector, &model, min_filter_prob,
msb_num_solutions, indOutputCumulativeProbs);
msbc.writeMsBlastQuery(msb_query_name.c_str(), msb_query_size, msb_min_score);
return(0);
}
if (got_msb_merge_queries)
{
msbc.mergeAndSplitQueries(msb_query_name.c_str(), list_vector, msb_num_solutions, msb_query_size, msb_min_score);
}
else
msbc.generateMsBlastFinalQuery(msb_query_name.c_str(), list_vector);
return(0);
}
///////////////////////////////////////////////////////////////////
// Training fa
if (make_training_fa)
{
make_denovo_training_fa(model,input_file);
exit(0);
}
///////////////////////////////////////////////////////////////////
// Inspect tags
if (make_inspect_tags)
{
create_tag_file_for_inspect(model,input_file,tag_string,tag_suffix);
exit(0);
}
if (test_tags)
{
benchmark_tags(model,list_file,tag_string,num_test_cases);
exit(0);
}
////////////////////////////////////////////////////////////////////
// Rescore InsPecT
if (got_rescore_inspect)
{
PeptideRankScorer *db_score = (PeptideRankScorer *)model.get_rank_model_ptr(0);
error("This version does not support this function. Please contact arf@cs.ucsd.edu to obtain the version of PepNovo that rescores InsPecT\n");
db_score->rescore_inspect_results(input_file,inspect_results_file,out_file);
exit(0);
}
if (got_recalibrate_inspect)
{
cout << "Recalibrating delta scores in " << input_file << endl;
PeptideRankScorer *db_score = (PeptideRankScorer *)model.get_rank_model_ptr(0);
db_score->recalibrate_inspect_delta_scores(input_file,inspect_results_file,out_file);
exit(0);
}
if (got_make_peak_examples)
{
cout << "Making peak examples " << input_file << endl;
PeptideRankScorer *db_score = (PeptideRankScorer *)model.get_rank_model_ptr(0);
db_score->make_peak_table_examples(input_file);
exit(0);
}
if (got_fragmentation_prediction)
{
cout << "Predicting fragmentation for input file: " << fragmentation_file << endl;
model.predict_fragmentation(fragmentation_file.c_str(), num_frag_peaks);
exit(0);
}
int correct_benchmark =0;
int total_benchmark =0;
int counter=0;
if (got_make_training_mgf)
{
make_training_mgf(config,list_file,num_training_spectra,out_file);
exit(0);
}
if (got_filter_spectra || pmcsqs_only)
{
PMCSQS_Scorer *pmcsqs = (PMCSQS_Scorer *)model.get_pmcsqs_ptr();
if (! pmcsqs || ! pmcsqs->getIndInitializedPmcr() || ! pmcsqs->getIndInitializedSqs())
{
cout << "Error: no parent mass correction (PMCR) and/or quality score (SQS) for this model!" << endl;
exit(1);
}
}
///////////////////////////////////////////////////////////////////
// FILTER SPECTRA
if (got_filter_spectra)
{
int num_written =0;
int num_read = 0;
PMCSQS_Scorer *pmcsqs = (PMCSQS_Scorer *)model.get_pmcsqs_ptr();
pmcsqs->output_filtered_spectra_to_mgfs(config, list_vector, mgf_out_dir, sqs_filter_thresh, num_written, num_read);
time_t curr_time = time(NULL);
double elapsed_time = (curr_time - start_time);
cout << "Processed " << list_vector.size() << " (" << num_read << " spectra)." << endl;
cout << "Wrote " << num_written << " spectra to mgfs in " << mgf_out_dir << endl;
cout << "Elapsed time " << fixed << elapsed_time << " seconds." << endl;
return 0;
}
//////////////////////////////////////////////////////////////////
// PRM
if (prm_only)
{
perform_prm_on_list_of_files(model, list_vector, min_filter_prob, file_start_idx, prm_norm);
return 0;
}
if (fabs(config->get_aa2mass()[Cys]-103.0)<1)
{
cout << endl <<"*** Warning: searching with unmodified cystine, usually the PTM C+57 should be included ***" << endl << endl;
}
cout << endl;
//////////////////////////////////////////////////////////////////
// PMCSQS
if (pmcsqs_only)
{
perform_pmcsqs_on_list_of_files(model, list_vector, file_start_idx);
return 0;
}
//////////////////////////////////////////////////////////////////
// DENOVO AND TAGS
if (tag_length<=0)
{
// perform_denovo_on_list_of_files(model, list_vector, file_start_idx, num_solutions, 7, 16,
// false, min_filter_prob, output_aa_probs, indOutputCumulativeProbs, cout);
new_perform_denovo_on_list_of_files(model, list_vector, file_start_idx, num_solutions, 7, 16, max_pm,
false, min_filter_prob, output_aa_probs, indOutputCumulativeProbs, cout);
}
else
{
perform_tags_on_list_of_files(model,list_vector,file_start_idx,num_solutions,tag_length,
false, min_filter_prob, output_aa_probs, indOutputCumulativeProbs, cout);
}
return 0;
}
| 31.421687 | 207 | 0.634714 | [
"vector",
"model"
] |
083c5328b8d443a9da63ed928bc44aed47c7fec9 | 566 | cpp | C++ | src/ejemplo-pai-encapsulation2.cpp | ULL-ESIT-INF-PAI-2019-2020/2019-2020-pai-trabajo-oopp-solid-grupo-solid | dd3fa1991a86f70e8edf7aab60bc5925dc617582 | [
"MIT"
] | null | null | null | src/ejemplo-pai-encapsulation2.cpp | ULL-ESIT-INF-PAI-2019-2020/2019-2020-pai-trabajo-oopp-solid-grupo-solid | dd3fa1991a86f70e8edf7aab60bc5925dc617582 | [
"MIT"
] | null | null | null | src/ejemplo-pai-encapsulation2.cpp | ULL-ESIT-INF-PAI-2019-2020/2019-2020-pai-trabajo-oopp-solid-grupo-solid | dd3fa1991a86f70e8edf7aab60bc5925dc617582 | [
"MIT"
] | null | null | null | /* Universidad de La Laguna
Escuela Superior de Ingeniería y Tecnología
Grado en Ingeniería Informática
Asignatura: Programación de Aplicaciones Interactivas
Curso: 3º
Presentación SOLID - OOP
Autor: Sergio Guerra Arencibia
Correo: alu0101133201@ull.edu.es
Fecha: 28/03/2020
Contenido: Programas teóricos usados para representar
los distintos principios SOLID
*/
class Person {
public:
std::string name;
std::vector<int> dni;
person(std::string, int);
~person();
};
Person panadero(Juan, 51100000);
panadero.dni = 51100001; | 23.583333 | 56 | 0.734982 | [
"vector",
"solid"
] |
0845ac86a4b9f4b0219a3aa3ee40c9d25d8ea852 | 16,295 | cc | C++ | maistra/vendor/com_google_cel_cpp/eval/public/set_util_test.cc | knm3000/proxy | f2bb57b7294aea2cb344824785be42849d7d63c9 | [
"Apache-2.0"
] | 3 | 2020-11-30T15:35:37.000Z | 2022-01-06T14:17:18.000Z | maistra/vendor/com_google_cel_cpp/eval/public/set_util_test.cc | knm3000/proxy | f2bb57b7294aea2cb344824785be42849d7d63c9 | [
"Apache-2.0"
] | 54 | 2020-06-23T17:34:04.000Z | 2022-03-31T02:04:06.000Z | maistra/vendor/com_google_cel_cpp/eval/public/set_util_test.cc | knm3000/proxy | f2bb57b7294aea2cb344824785be42849d7d63c9 | [
"Apache-2.0"
] | 12 | 2020-07-14T23:59:57.000Z | 2022-03-22T09:59:18.000Z | #include "eval/public/set_util.h"
#include <cstddef>
#include "google/protobuf/empty.pb.h"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/message.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "eval/public/cel_value.h"
#include "eval/public/containers/container_backed_list_impl.h"
#include "eval/public/containers/container_backed_map_impl.h"
#include "eval/public/structs/cel_proto_wrapper.h"
#include "eval/public/unknown_set.h"
namespace google {
namespace api {
namespace expr {
namespace runtime {
namespace {
using google::protobuf::Arena;
using protobuf::Empty;
using protobuf::ListValue;
using protobuf::Struct;
constexpr char kExampleText[] = "abc";
constexpr char kExampleText2[] = "abd";
std::string* ExampleStr() {
static std::string* example = new std::string(kExampleText);
return example;
}
std::string* ExampleStr2() {
static std::string* example = new std::string(kExampleText2);
return example;
}
// Returns a vector that has an example for each type, ordered by the type
// ordering in |CelValueLessThan|. Length 13
std::vector<CelValue> TypeExamples(Arena* arena) {
Empty* empty = Arena::Create<Empty>(arena);
Struct* proto_map = Arena::CreateMessage<Struct>(arena);
ListValue* proto_list = Arena::CreateMessage<ListValue>(arena);
UnknownSet* unknown_set = Arena::Create<UnknownSet>(arena);
return {CelValue::CreateBool(false),
CelValue::CreateInt64(0),
CelValue::CreateUint64(0),
CelValue::CreateDouble(0.0),
CelValue::CreateStringView(kExampleText),
CelValue::CreateBytes(ExampleStr()),
CelProtoWrapper::CreateMessage(empty, arena),
CelValue::CreateDuration(absl::ZeroDuration()),
CelValue::CreateTimestamp(absl::Now()),
CelProtoWrapper::CreateMessage(proto_list, arena),
CelProtoWrapper::CreateMessage(proto_map, arena),
CelValue::CreateUnknownSet(unknown_set),
CreateErrorValue(arena, "test", absl::StatusCode::kInternal)};
}
// Parameterized test for confirming type orderings are correct. Compares all
// pairs of type examples to confirm the expected type priority.
class TypeOrderingTest : public testing::TestWithParam<std::tuple<int, int>> {
public:
TypeOrderingTest() {
i_ = std::get<0>(GetParam());
j_ = std::get<1>(GetParam());
}
protected:
int i_;
int j_;
Arena arena_;
};
TEST_P(TypeOrderingTest, TypeLessThan) {
auto examples = TypeExamples(&arena_);
CelValue lhs = examples[i_];
CelValue rhs = examples[j_];
// Strict less than.
EXPECT_EQ(CelValueLessThan(lhs, rhs), i_ < j_);
// Equality.
EXPECT_EQ(CelValueEqual(lhs, rhs), i_ == j_);
}
std::string TypeOrderingTestName(
testing::TestParamInfo<std::tuple<int, int>> param) {
int i = std::get<0>(param.param);
int j = std::get<1>(param.param);
return absl::StrCat(CelValue::TypeName(CelValue::Type(i)), "_",
CelValue::TypeName(CelValue::Type(j)));
}
INSTANTIATE_TEST_SUITE_P(TypePairs, TypeOrderingTest,
testing::Combine(testing::Range(0, 13),
testing::Range(0, 13)),
&TypeOrderingTestName);
TEST(CelValueLessThanComparator, StdSetSupport) {
Arena arena;
auto examples = TypeExamples(&arena);
std::set<CelValue, CelValueLessThanComparator> value_set(&CelValueLessThan);
for (CelValue value : examples) {
auto insert = value_set.insert(value);
bool was_inserted = insert.second;
EXPECT_TRUE(was_inserted)
<< absl::StrCat("Insertion failed ", CelValue::TypeName(value.type()));
}
for (CelValue value : examples) {
auto insert = value_set.insert(value);
bool was_inserted = insert.second;
EXPECT_FALSE(was_inserted) << absl::StrCat(
"Re-insertion succeeded ", CelValue::TypeName(value.type()));
}
}
enum class ExpectedCmp { kEq, kLt, kGt };
struct PrimitiveCmpTestCase {
CelValue lhs;
CelValue rhs;
ExpectedCmp expected;
};
// Test for primitive types that just use operator< for the underlying value.
class PrimitiveCmpTest : public testing::TestWithParam<PrimitiveCmpTestCase> {
public:
PrimitiveCmpTest() {
lhs_ = GetParam().lhs;
rhs_ = GetParam().rhs;
expected_ = GetParam().expected;
}
protected:
CelValue lhs_;
CelValue rhs_;
ExpectedCmp expected_;
};
TEST_P(PrimitiveCmpTest, Basic) {
switch (expected_) {
case ExpectedCmp::kLt:
EXPECT_TRUE(CelValueLessThan(lhs_, rhs_));
break;
case ExpectedCmp::kGt:
EXPECT_TRUE(CelValueGreaterThan(lhs_, rhs_));
break;
case ExpectedCmp::kEq:
EXPECT_TRUE(CelValueEqual(lhs_, rhs_));
break;
}
}
std::string PrimitiveCmpTestName(
testing::TestParamInfo<PrimitiveCmpTestCase> info) {
absl::string_view cmp_name;
switch (info.param.expected) {
case ExpectedCmp::kEq:
cmp_name = "Eq";
break;
case ExpectedCmp::kLt:
cmp_name = "Lt";
break;
case ExpectedCmp::kGt:
cmp_name = "Gt";
break;
}
return absl::StrCat(CelValue::TypeName(info.param.lhs.type()), "_", cmp_name);
}
INSTANTIATE_TEST_SUITE_P(
Pairs, PrimitiveCmpTest,
testing::ValuesIn(std::vector<PrimitiveCmpTestCase>{
{CelValue::CreateStringView(kExampleText),
CelValue::CreateStringView(kExampleText), ExpectedCmp::kEq},
{CelValue::CreateStringView(kExampleText),
CelValue::CreateStringView(kExampleText2), ExpectedCmp::kLt},
{CelValue::CreateStringView(kExampleText2),
CelValue::CreateStringView(kExampleText), ExpectedCmp::kGt},
{CelValue::CreateBytes(ExampleStr()),
CelValue::CreateBytes(ExampleStr()), ExpectedCmp::kEq},
{CelValue::CreateBytes(ExampleStr()),
CelValue::CreateBytes(ExampleStr2()), ExpectedCmp::kLt},
{CelValue::CreateBytes(ExampleStr2()),
CelValue::CreateBytes(ExampleStr()), ExpectedCmp::kGt},
{CelValue::CreateBool(false), CelValue::CreateBool(false),
ExpectedCmp::kEq},
{CelValue::CreateBool(false), CelValue::CreateBool(true),
ExpectedCmp::kLt},
{CelValue::CreateBool(true), CelValue::CreateBool(false),
ExpectedCmp::kGt},
{CelValue::CreateInt64(1), CelValue::CreateInt64(1), ExpectedCmp::kEq},
{CelValue::CreateInt64(1), CelValue::CreateInt64(2), ExpectedCmp::kLt},
{CelValue::CreateInt64(2), CelValue::CreateInt64(1), ExpectedCmp::kGt},
{CelValue::CreateUint64(1), CelValue::CreateUint64(1),
ExpectedCmp::kEq},
{CelValue::CreateUint64(1), CelValue::CreateUint64(2),
ExpectedCmp::kLt},
{CelValue::CreateUint64(2), CelValue::CreateUint64(1),
ExpectedCmp::kGt},
{CelValue::CreateDuration(absl::Minutes(1)),
CelValue::CreateDuration(absl::Minutes(1)), ExpectedCmp::kEq},
{CelValue::CreateDuration(absl::Minutes(1)),
CelValue::CreateDuration(absl::Minutes(2)), ExpectedCmp::kLt},
{CelValue::CreateDuration(absl::Minutes(2)),
CelValue::CreateDuration(absl::Minutes(1)), ExpectedCmp::kGt},
{CelValue::CreateTimestamp(absl::FromUnixSeconds(1)),
CelValue::CreateTimestamp(absl::FromUnixSeconds(1)), ExpectedCmp::kEq},
{CelValue::CreateTimestamp(absl::FromUnixSeconds(1)),
CelValue::CreateTimestamp(absl::FromUnixSeconds(2)), ExpectedCmp::kLt},
{CelValue::CreateTimestamp(absl::FromUnixSeconds(2)),
CelValue::CreateTimestamp(absl::FromUnixSeconds(1)),
ExpectedCmp::kGt}}),
&PrimitiveCmpTestName);
TEST(CelValueLessThan, PtrCmpMessage) {
Arena arena;
CelValue lhs =
CelProtoWrapper::CreateMessage(Arena::Create<Empty>(&arena), &arena);
CelValue rhs =
CelProtoWrapper::CreateMessage(Arena::Create<Empty>(&arena), &arena);
if (lhs.MessageOrDie() > rhs.MessageOrDie()) {
std::swap(lhs, rhs);
}
EXPECT_TRUE(CelValueLessThan(lhs, rhs));
EXPECT_FALSE(CelValueLessThan(rhs, lhs));
EXPECT_FALSE(CelValueLessThan(lhs, lhs));
}
TEST(CelValueLessThan, PtrCmpUnknownSet) {
Arena arena;
CelValue lhs = CelValue::CreateUnknownSet(Arena::Create<UnknownSet>(&arena));
CelValue rhs = CelValue::CreateUnknownSet(Arena::Create<UnknownSet>(&arena));
if (lhs.UnknownSetOrDie() > rhs.UnknownSetOrDie()) {
std::swap(lhs, rhs);
}
EXPECT_TRUE(CelValueLessThan(lhs, rhs));
EXPECT_FALSE(CelValueLessThan(rhs, lhs));
EXPECT_FALSE(CelValueLessThan(lhs, lhs));
}
TEST(CelValueLessThan, PtrCmpError) {
Arena arena;
CelValue lhs = CreateErrorValue(&arena, "test", absl::StatusCode::kInternal);
CelValue rhs = CreateErrorValue(&arena, "test", absl::StatusCode::kInternal);
if (lhs.ErrorOrDie() > rhs.ErrorOrDie()) {
std::swap(lhs, rhs);
}
EXPECT_TRUE(CelValueLessThan(lhs, rhs));
EXPECT_FALSE(CelValueLessThan(rhs, lhs));
EXPECT_FALSE(CelValueLessThan(lhs, lhs));
}
TEST(CelValueLessThan, CelListSameSize) {
ContainerBackedListImpl cel_list_1(std::vector<CelValue>{
CelValue::CreateInt64(1), CelValue::CreateInt64(2)});
ContainerBackedListImpl cel_list_2(std::vector<CelValue>{
CelValue::CreateInt64(1), CelValue::CreateInt64(3)});
EXPECT_TRUE(CelValueLessThan(CelValue::CreateList(&cel_list_1),
CelValue::CreateList(&cel_list_2)));
}
TEST(CelValueLessThan, CelListDifferentSizes) {
ContainerBackedListImpl cel_list_1(
std::vector<CelValue>{CelValue::CreateInt64(2)});
ContainerBackedListImpl cel_list_2(std::vector<CelValue>{
CelValue::CreateInt64(1), CelValue::CreateInt64(3)});
EXPECT_TRUE(CelValueLessThan(CelValue::CreateList(&cel_list_1),
CelValue::CreateList(&cel_list_2)));
}
TEST(CelValueLessThan, CelListEqual) {
ContainerBackedListImpl cel_list_1(std::vector<CelValue>{
CelValue::CreateInt64(1), CelValue::CreateInt64(2)});
ContainerBackedListImpl cel_list_2(std::vector<CelValue>{
CelValue::CreateInt64(1), CelValue::CreateInt64(2)});
EXPECT_FALSE(CelValueLessThan(CelValue::CreateList(&cel_list_1),
CelValue::CreateList(&cel_list_2)));
EXPECT_TRUE(CelValueEqual(CelValue::CreateList(&cel_list_2),
CelValue::CreateList(&cel_list_1)));
}
TEST(CelValueLessThan, CelListSupportProtoListCompatible) {
Arena arena;
ListValue list_value;
list_value.add_values()->set_bool_value(true);
list_value.add_values()->set_number_value(1.0);
list_value.add_values()->set_string_value("abc");
CelValue proto_list = CelProtoWrapper::CreateMessage(&list_value, &arena);
ASSERT_TRUE(proto_list.IsList());
std::vector<CelValue> list_values{CelValue::CreateBool(true),
CelValue::CreateDouble(1.0),
CelValue::CreateStringView("abd")};
ContainerBackedListImpl list_backing(list_values);
CelValue cel_list = CelValue::CreateList(&list_backing);
EXPECT_TRUE(CelValueLessThan(proto_list, cel_list));
}
TEST(CelValueLessThan, CelMapSameSize) {
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(3), CelValue::CreateInt64(6)}};
auto cel_map_backing_1 = CreateContainerBackedMap(absl::MakeSpan(values));
std::vector<std::pair<CelValue, CelValue>> values2{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(4), CelValue::CreateInt64(6)}};
auto cel_map_backing_2 = CreateContainerBackedMap(absl::MakeSpan(values2));
std::vector<std::pair<CelValue, CelValue>> values3{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(3), CelValue::CreateInt64(8)}};
auto cel_map_backing_3 = CreateContainerBackedMap(absl::MakeSpan(values3));
CelValue map1 = CelValue::CreateMap(cel_map_backing_1.get());
CelValue map2 = CelValue::CreateMap(cel_map_backing_2.get());
CelValue map3 = CelValue::CreateMap(cel_map_backing_3.get());
EXPECT_TRUE(CelValueLessThan(map1, map2));
EXPECT_TRUE(CelValueLessThan(map1, map3));
EXPECT_TRUE(CelValueLessThan(map3, map2));
}
TEST(CelValueLessThan, CelMapDifferentSizes) {
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(2), CelValue::CreateInt64(4)}};
auto cel_map_1 = CreateContainerBackedMap(absl::MakeSpan(values));
std::vector<std::pair<CelValue, CelValue>> values2{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(2), CelValue::CreateInt64(4)},
{CelValue::CreateInt64(3), CelValue::CreateInt64(6)}};
auto cel_map_2 = CreateContainerBackedMap(absl::MakeSpan(values2));
EXPECT_TRUE(CelValueLessThan(CelValue::CreateMap(cel_map_1.get()),
CelValue::CreateMap(cel_map_2.get())));
}
TEST(CelValueLessThan, CelMapEqual) {
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(2), CelValue::CreateInt64(4)},
{CelValue::CreateInt64(3), CelValue::CreateInt64(6)}};
auto cel_map_1 = CreateContainerBackedMap(absl::MakeSpan(values));
std::vector<std::pair<CelValue, CelValue>> values2{
{CelValue::CreateInt64(1), CelValue::CreateInt64(2)},
{CelValue::CreateInt64(2), CelValue::CreateInt64(4)},
{CelValue::CreateInt64(3), CelValue::CreateInt64(6)}};
auto cel_map_2 = CreateContainerBackedMap(absl::MakeSpan(values2));
EXPECT_FALSE(CelValueLessThan(CelValue::CreateMap(cel_map_1.get()),
CelValue::CreateMap(cel_map_2.get())));
EXPECT_TRUE(CelValueEqual(CelValue::CreateMap(cel_map_2.get()),
CelValue::CreateMap(cel_map_1.get())));
}
TEST(CelValueLessThan, CelMapSupportProtoMapCompatible) {
Arena arena;
const std::vector<std::string> kFields = {"field1", "field2", "field3"};
Struct value_struct;
auto& value1 = (*value_struct.mutable_fields())[kFields[0]];
value1.set_bool_value(true);
auto& value2 = (*value_struct.mutable_fields())[kFields[1]];
value2.set_number_value(1.0);
auto& value3 = (*value_struct.mutable_fields())[kFields[2]];
value3.set_string_value("test");
CelValue proto_struct = CelProtoWrapper::CreateMessage(&value_struct, &arena);
ASSERT_TRUE(proto_struct.IsMap());
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateStringView(kFields[2]),
CelValue::CreateStringView("test")},
{CelValue::CreateStringView(kFields[1]), CelValue::CreateDouble(1.0)},
{CelValue::CreateStringView(kFields[0]), CelValue::CreateBool(true)}};
auto backing_map = CreateContainerBackedMap(absl::MakeSpan(values));
CelValue cel_map = CelValue::CreateMap(backing_map.get());
EXPECT_TRUE(!CelValueLessThan(cel_map, proto_struct) &&
!CelValueGreaterThan(cel_map, proto_struct));
}
TEST(CelValueLessThan, NestedMap) {
Arena arena;
ListValue list_value;
list_value.add_values()->set_bool_value(true);
list_value.add_values()->set_number_value(1.0);
list_value.add_values()->set_string_value("test");
std::vector<CelValue> list_values{CelValue::CreateBool(true),
CelValue::CreateDouble(1.0),
CelValue::CreateStringView("test")};
ContainerBackedListImpl list_backing(list_values);
CelValue cel_list = CelValue::CreateList(&list_backing);
Struct value_struct;
*(value_struct.mutable_fields()->operator[]("field").mutable_list_value()) =
list_value;
std::vector<std::pair<CelValue, CelValue>> values{
{CelValue::CreateStringView("field"), cel_list}};
auto backing_map = CreateContainerBackedMap(absl::MakeSpan(values));
CelValue cel_map = CelValue::CreateMap(backing_map.get());
CelValue proto_map = CelProtoWrapper::CreateMessage(&value_struct, &arena);
EXPECT_TRUE(!CelValueLessThan(cel_map, proto_map) &&
!CelValueLessThan(proto_map, cel_map));
}
} // namespace
} // namespace runtime
} // namespace expr
} // namespace api
} // namespace google
| 34.892934 | 80 | 0.69371 | [
"vector"
] |
36b2f867b0d09bef858f56c4a66cdf4bb5962852 | 2,700 | cc | C++ | caffe2/operators/math_ops.cc | chocjy/caffe2 | 1a6cef392495d969d135945d6749e6b99b37d4d9 | [
"Apache-2.0"
] | 585 | 2015-08-10T02:48:52.000Z | 2021-12-01T08:46:59.000Z | caffe2/operators/math_ops.cc | mingzhe09088/caffe2 | 8f41717c46d214aaf62b53e5b3b9b308b5b8db91 | [
"Apache-2.0"
] | 23 | 2015-08-30T11:54:51.000Z | 2017-03-06T03:01:07.000Z | caffe2/operators/math_ops.cc | mingzhe09088/caffe2 | 8f41717c46d214aaf62b53e5b3b9b308b5b8db91 | [
"Apache-2.0"
] | 183 | 2015-08-10T02:49:04.000Z | 2021-12-01T08:47:13.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "caffe2/operators/math_ops.h"
#include "caffe2/utils/math.h"
namespace caffe2 {
struct SqrCPUFunctor {
template <typename T>
inline void
operator()(const int n, const T* x, T* y, CPUContext* device_context) {
math::Sqr<T, CPUContext>(n, x, y, device_context);
}
};
REGISTER_CPU_OPERATOR(
Sqr,
UnaryElementwiseOp<TensorTypes<float>, CPUContext, SqrCPUFunctor>);
OPERATOR_SCHEMA(Sqr)
.NumInputs(1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.IdenticalTypeAndShape()
.SetDoc("Square (x^2) the elements of the input")
.Input(0, "input", "Input tensor")
.Output(0, "output", "Squared elements of the input");
class GetSqrGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
Argument scale_arg;
scale_arg.set_name("scale");
scale_arg.set_f(2.0);
return vector<OperatorDef>{CreateOperatorDef(
"Scale",
"",
std::vector<string>{GO(0)},
std::vector<string>{GO(0)},
std::vector<Argument>{scale_arg}),
CreateOperatorDef(
"Mul",
"",
std::vector<string>{GO(0), I(0)},
std::vector<string>{GI(0)})};
}
};
REGISTER_GRADIENT(Sqr, GetSqrGradient);
struct SignCPUFunctor {
template <typename T>
inline void
operator()(const int n, const T* x, T* y, CPUContext* device_context) {
for (int i = 0; i < n; ++i) {
y[i] = (-T(1) * (x[i] < 0)) + (x[i] > 0);
}
}
};
REGISTER_CPU_OPERATOR(
Sign,
UnaryElementwiseOp<TensorTypes<float>, CPUContext, SignCPUFunctor>);
OPERATOR_SCHEMA(Sign)
.NumInputs(1)
.NumOutputs(1)
.SetDoc("Computes sign for each element of the input: -1, 0 or 1.")
.IdenticalTypeAndShape();
SHOULD_NOT_DO_GRADIENT(Sign);
} // namespace caffe2
| 31.395349 | 75 | 0.601111 | [
"vector"
] |
36b63ea12c97d2dc490492acf52464585d52324d | 1,226 | cpp | C++ | 2020-11-27/poker.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | 2 | 2020-12-12T00:02:40.000Z | 2021-04-21T19:49:59.000Z | 2020-11-27/poker.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | 2020-11-27/poker.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct hand_t {
int v[4];
int set, pair, single;
void setup(int a, int b, int c) {
v[0] = a;
v[1] = b;
v[2] = c;
set=0;
pair=0;
single=0;
sort(v, v+3);
if (v[0] == v[2]) {
set = v[0];
} else if (v[0] == v[1]) {
pair = v[0];
single = v[2];
} else if (v[1] == v[2]) {
pair = v[1];
single = v[0];
}
}
};
bool operator<(const hand_t a, const hand_t b) {
if (a.set != b.set)
return a.set < b.set;
if (a.pair != b.pair)
return a.pair < b.pair;
return a.single < b.single;
}
int main() {
int a, b, c;
hand_t x;
vector<hand_t> hand;
for(int i=1; i<=13; ++i) {
for(int j=1; j<=13; ++j) {
x.setup(i, i, j);
hand.push_back(x);
}
}
sort(hand.begin(), hand.end());
while(true){
scanf(" %d %d %d", &a, &b, &c);
if (a==0 && b==0 && c==0)
break;
x.setup(a, b, c);
auto it = upper_bound(hand.begin(), hand.end(), x);
if (it == hand.end())
printf("*\n");
else
printf("%d %d %d\n", it->v[0], it->v[1], it->v[2]);
}
return 0;
}
| 20.098361 | 58 | 0.442088 | [
"vector"
] |
36b850c6a6fc4e53e0645426d0070151319f82d8 | 6,110 | cpp | C++ | slackbot/HttpService.cpp | mogemimi/daily-snippets | d9da3db8c62538e4a37f0f6b69c5d46d55c4225f | [
"MIT"
] | 14 | 2017-06-16T22:52:38.000Z | 2022-02-14T04:11:06.000Z | slackbot/HttpService.cpp | mogemimi/daily-snippets | d9da3db8c62538e4a37f0f6b69c5d46d55c4225f | [
"MIT"
] | 2 | 2016-03-13T14:50:04.000Z | 2019-04-01T09:53:17.000Z | slackbot/HttpService.cpp | mogemimi/daily-snippets | d9da3db8c62538e4a37f0f6b69c5d46d55c4225f | [
"MIT"
] | 2 | 2016-03-13T14:05:17.000Z | 2018-09-18T01:28:42.000Z | // Copyright (c) 2015 mogemimi. Distributed under the MIT license.
#include "HttpService.h"
#include <algorithm>
#include <cassert>
namespace somera {
HttpRequest::HttpRequest(
const HttpRequestOptions& options,
std::function<void(bool error, const std::vector<std::uint8_t>& data)> callbackIn)
: callback(callbackIn)
, curl(nullptr)
{
curl = curl_easy_init();
if (curl == nullptr) {
throw std::runtime_error("curl_easy_init() failed");
}
std::string uri;
if (options.hostname) {
uri += *options.hostname;
}
if (options.path) {
uri += *options.path;
}
if (!uri.empty()) {
curl_easy_setopt(curl, CURLOPT_URL, uri.c_str());
}
if (options.postFields && !options.postFields->empty()) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, options.postFields->c_str());
}
if (options.agent && !options.agent->empty()) {
curl_easy_setopt(curl, CURLOPT_USERAGENT, options.agent->c_str());
}
if (options.port) {
curl_easy_setopt(curl, CURLOPT_PORT, *options.port);
}
if (options.method) {
if (*options.method == HttpRequestMethod::POST) {
curl_easy_setopt(curl, CURLOPT_POST, 1);
}
else if (*options.method == HttpRequestMethod::GET) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
}
}
if (!options.headers.empty()) {
// TODO: Please add implementation.
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
// curl_easy_setopt(curl, CURLOPT_HEADER, 0L);
// curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);
}
HttpRequest::HttpRequest(
const std::string& uri,
std::function<void(bool error, const std::vector<std::uint8_t>& data)> callbackIn)
: callback(callbackIn)
, curl(nullptr)
{
curl = curl_easy_init();
if (curl == nullptr) {
throw std::runtime_error("curl_easy_init() failed");
}
curl_easy_setopt(curl, CURLOPT_URL, uri.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
}
HttpRequest::~HttpRequest()
{
if (curl != nullptr) {
curl_easy_cleanup(curl);
curl = nullptr;
}
}
CURL* HttpRequest::getCurl() const
{
return curl;
}
void HttpRequest::setTimeout(const std::chrono::seconds& timeout)
{
if (timeout >= timeout.zero()) {
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout.count());
}
}
size_t HttpRequest::writeCallback(
void const* contents,
size_t size,
size_t nmemb,
void* userPointer)
{
auto userData = reinterpret_cast<HttpRequest*>(userPointer);
auto & blob = userData->blob;
const auto inputSize = size * nmemb;
blob.resize(blob.size() + inputSize);
std::memcpy(blob.data() + blob.size() - inputSize, contents, inputSize);
return inputSize;
}
void HttpRequest::onCompleted()
{
if (callback) {
callback(false, blob);
}
}
void HttpRequest::onError()
{
if (callback) {
callback(true, {});
}
}
HttpService::HttpService()
: multiHandle(nullptr)
, timeout(decltype(timeout)::zero())
{
multiHandle = curl_multi_init();
}
HttpService::~HttpService()
{
if (multiHandle != nullptr) {
curl_multi_cleanup(multiHandle);
multiHandle = nullptr;
}
}
void HttpService::poll()
{
assert(multiHandle != nullptr);
int runningCount = 0;
curl_multi_perform(multiHandle, &runningCount);
int messageCount = 0;
CURLMsg* message = nullptr;
while ((message = curl_multi_info_read(multiHandle, &messageCount)) != nullptr)
{
CURL* curl = message->easy_handle;
curl_multi_remove_handle(multiHandle, curl);
auto pair = sessions.find(curl);
assert(pair != std::end(sessions));
if (pair != std::end(sessions)) {
auto request = std::move(pair->second);
if (message->msg != CURLMSG_DONE) {
//std::fprintf(stderr, "CURL error in %s, %d\n", __FILE__, __LINE__);
request->onError();
}
else if (message->data.result != CURLE_OK) {
//std::fprintf(stderr, "CURL error in %s, %d\n", __FILE__, __LINE__);
request->onError();
}
else {
request->onCompleted();
}
sessions.erase(pair);
}
}
}
void HttpService::waitAll()
{
for (;;) {
this->poll();
if (this->empty()) {
break;
}
// {
// int n = 0;
// curl_multi_wait(multiHandle, nullptr, 0, 30 * 1000, &n);
// }
std::this_thread::sleep_for(std::chrono::microseconds(500));
}
}
void HttpService::request(
const HttpRequestOptions& options,
std::function<void(bool, const std::vector<std::uint8_t>&)> callback)
{
auto request = std::make_unique<HttpRequest>(options, callback);
if (timeout > decltype(timeout)::zero()) {
request->setTimeout(timeout);
}
auto result = curl_multi_add_handle(multiHandle, request->getCurl());
if (result != CURLE_OK) {
throw std::runtime_error("curl_multi_add_handle() failed");
}
sessions.emplace(request->getCurl(), std::move(request));
}
void HttpService::get(
const std::string& uri,
std::function<void(bool, const std::vector<std::uint8_t>&)> callback)
{
auto request = std::make_unique<HttpRequest>(uri, callback);
if (timeout > decltype(timeout)::zero()) {
request->setTimeout(timeout);
}
auto result = curl_multi_add_handle(multiHandle, request->getCurl());
if (result != CURLE_OK) {
throw std::runtime_error("curl_multi_add_handle() failed");
}
sessions.emplace(request->getCurl(), std::move(request));
}
bool HttpService::empty() const
{
return sessions.size() <= 0;
}
void HttpService::setTimeout(const std::chrono::seconds& timeoutIn)
{
assert(timeout >= timeout.zero());
this->timeout = timeoutIn;
}
} // namespace somera
| 26.223176 | 86 | 0.618494 | [
"vector"
] |
36bdfa1e2442fca4776433616896d23651d315f3 | 11,319 | cpp | C++ | src/parser.cpp | delpini/bypass | fe9c1723595432e0b69fc7172fc566695e0be509 | [
"Apache-2.0"
] | 2 | 2021-11-14T14:47:14.000Z | 2021-11-14T14:47:18.000Z | src/parser.cpp | delpini/bypass | fe9c1723595432e0b69fc7172fc566695e0be509 | [
"Apache-2.0"
] | null | null | null | src/parser.cpp | delpini/bypass | fe9c1723595432e0b69fc7172fc566695e0be509 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2013 Uncodin, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "parser.h"
using namespace std;
static void rndr_blockcode(struct buf *ob, struct buf *text, void *opaque);
static void rndr_blockquote(struct buf *ob, struct buf *text, void *opaque);
static void rndr_header(struct buf *ob, struct buf *text, int level, void *opaque);
static void rndr_list(struct buf *ob, struct buf *text, int flags, void *opaque);
static void rndr_listitem(struct buf *ob, struct buf *text, int flags, void *opaque);
static void rndr_paragraph(struct buf *ob, struct buf *text, void *opaque);
static int rndr_codespan(struct buf *ob, struct buf *text, void *opaque);
static int rndr_double_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_triple_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_linebreak(struct buf *ob, void *opaque);
static int rndr_link(struct buf *ob, struct buf *link, struct buf *title, struct buf *content, void *opaque);
static void rndr_normal_text(struct buf *ob, struct buf *text, void *opaque);
struct mkd_renderer mkd_callbacks = {
/* document-level callbacks */
NULL, // prolog
NULL, // epilogue
/* block-level callbacks */
rndr_blockcode, // block code
rndr_blockquote, // block quote
NULL, // block html
rndr_header, // header
NULL, // hrule
rndr_list, // list
rndr_listitem, // listitem
rndr_paragraph, // paragraph
NULL, // table
NULL, // table cell
NULL, // table row
/* span-level callbacks */
NULL, // autolink
rndr_codespan, // codespan
rndr_double_emphasis, // double emphasis
rndr_emphasis, // emphasis
NULL, // image
rndr_linebreak, // line break
rndr_link, // link
NULL, // raw html tag
rndr_triple_emphasis, // triple emphasis
/* low-level callbacks */
NULL, // entity
rndr_normal_text, // normal text
/* renderer data */
64, // max stack
"*_~",
NULL // opaque
};
namespace Bypass {
const static std::string TWO_SPACES = " ";
const static std::string NEWLINE = "\n";
Parser::Parser()
: elementSoup()
{
elementCount = 1;
}
Parser::~Parser() {
}
Document Parser::parse(const char* mkd) {
document = Document();
if (mkd) {
struct buf *ib, *ob;
ib = bufnew(INPUT_UNIT);
bufputs(ib, mkd);
ob = bufnew(OUTPUT_UNIT);
mkd_callbacks.opaque = this;
//parse and assemble document
markdown(ob, ib, &mkd_callbacks);
for (std::map<int, Element>::iterator it = elementSoup.begin(); it != elementSoup.end(); ++it) {
document.append(it->second);
}
bufrelease(ib);
bufrelease(ob);
}
return document;
}
Document Parser::parse(const string& markdown) {
return parse(markdown.c_str());
}
void Parser::eraseTrailingControlCharacters(const std::string& controlCharacters) {
std::map<int, Element>::iterator it = elementSoup.find(elementCount);
if ( it != elementSoup.end() ) {
Element * element = &((*it).second);
if (boost::ends_with(element->text, controlCharacters)) {
boost::erase_tail(element->text, controlCharacters.size());
}
}
}
// Block Element Callbacks
void Parser::handleBlock(Type type, struct buf *ob, struct buf *text, int extra) {
Element block;
block.setType(type);
if (type == HEADER) {
char levelStr[2];
snprintf(levelStr, 2, "%d", extra);
block.addAttribute("level", levelStr);
}
std::string textString(text->data, text->data + text->size);
std::vector<std::string> strs;
boost::split(strs, textString, boost::is_any_of("|"));
for(vector<std::string>::iterator it = strs.begin(); it != strs.end(); it++) {
int pos = atoi((*it).c_str());
std::map<int, Element>::iterator elit = elementSoup.find(pos);
if ( elit != elementSoup.end() ) {
block.append((*elit).second);
elementSoup.erase(pos);
}
}
elementCount++;
std::ostringstream oss;
oss << elementCount;
elementSoup[elementCount] = block;
oss << '|';
bufputs(ob, oss.str().c_str());
}
void Parser::parsedBlockCode(struct buf *ob, struct buf *text) {
if(!text) return; // Analyze seems to believe that text can be null here
parsedNormalText(ob, text);
eraseTrailingControlCharacters(NEWLINE);
std::ostringstream oss;
oss << elementCount << '|';
bufreset(text);
bufputs(text, oss.str().c_str());
handleBlock(BLOCK_CODE, ob, text);
}
void Parser::parsedBlockQuote(struct buf *ob, struct buf *text) {
handleBlock(BLOCK_QUOTE, ob, text);
}
void Parser::parsedHeader(struct buf *ob, struct buf *text, int level) {
handleBlock(HEADER, ob, text, level);
}
void Parser::parsedList(struct buf *ob, struct buf *text, int flags) {
handleBlock(LIST, ob, text);
}
void Parser::parsedListItem(struct buf *ob, struct buf *text, int flags) {
handleBlock(LIST_ITEM, ob, text);
}
void Parser::parsedParagraph(struct buf *ob, struct buf *text) {
handleBlock(PARAGRAPH, ob, text);
}
// Span Element Callbacks
void Parser::handleSpan(Type type, struct buf *ob, struct buf *text, struct buf *extra, struct buf *extra2, bool output) {
std::vector<std::string> strs;
std::string textString;
if (text) {
textString = std::string(text->data, text->data + text->size);
boost::split(strs, textString, boost::is_any_of("|"));
}
if (strs.size() > 0) {
std::string str0 = strs[0];
if (str0.length() > 0) {
int pos = atoi(str0.c_str());
std::map<int, Element>::iterator elit = elementSoup.find(pos);
Element element = elit->second;
element.setType(type);
if (extra != NULL && extra->size) {
if (element.getType() == LINK) {
element.addAttribute("link", std::string(extra->data, extra->data + extra->size));
}
}
if (extra2 != NULL && extra2->size) {
if (element.getType() == LINK) {
element.addAttribute("title", std::string(extra2->data, extra2->data + extra2->size));
}
}
elementSoup.erase(pos);
if (output) {
elementSoup[pos] = element;
}
}
if (output) {
bufputs(ob, textString.c_str());
}
}
else {
Element element;
element.setType(type);
createSpan(element, ob);
}
}
void Parser::createSpan(const Element& element, struct buf *ob) {
elementCount++;
std::ostringstream oss;
oss << elementCount;
elementSoup[elementCount] = element;
oss << '|';
bufputs(ob, oss.str().c_str());
}
int Parser::parsedDoubleEmphasis(struct buf *ob, struct buf *text, char c) {
if (c == '~') {
handleSpan(STRIKETHROUGH, ob, text);
} else {
handleSpan(DOUBLE_EMPHASIS, ob, text);
}
return 1;
}
int Parser::parsedEmphasis(struct buf *ob, struct buf *text, char c) {
if (c == '~') {
handleSpan(STRIKETHROUGH, ob, text, NULL, NULL, false);
return 0;
} else {
handleSpan(EMPHASIS, ob, text);
return 1;
}
}
int Parser::parsedTripleEmphasis(struct buf *ob, struct buf *text, char c) {
if (c == '~') {
handleSpan(STRIKETHROUGH, ob, text, NULL, NULL, false);
return 0;
} else {
handleSpan(TRIPLE_EMPHASIS, ob, text);
return 1;
}
}
int Parser::parsedLink(struct buf *ob, struct buf *link, struct buf *title, struct buf *content) {
handleSpan(LINK, ob, content, link, title);
return 1;
}
int Parser::parsedCodeSpan(struct buf *ob, struct buf *text) {
if (text && text->size > 0) {
Element codeSpan;
codeSpan.setType(CODE_SPAN);
codeSpan.text.assign(text->data, text->data + text->size);
createSpan(codeSpan, ob);
}
return 1;
}
int Parser::parsedLinebreak(struct buf *ob) {
eraseTrailingControlCharacters(TWO_SPACES);
handleSpan(LINEBREAK, ob, NULL);
return 1;
}
// Low Level Callbacks
void Parser::parsedNormalText(struct buf *ob, struct buf *text) {
// The parser will spuriously emit a text callback for an empty string
// that butts up against a span-level element. This will ignore it.
if (text && text->size > 0) {
Element normalText;
normalText.setType(TEXT);
normalText.text.assign(text->data, text->data + text->size);
createSpan(normalText, ob);
}
}
}
// Block Element callbacks
static void rndr_blockcode(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedBlockCode(ob, text);
}
static void rndr_blockquote(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedBlockQuote(ob, text);
}
static void rndr_header(struct buf *ob, struct buf *text, int level, void *opaque) {
((Bypass::Parser*) opaque)->parsedHeader(ob, text, level);
}
static void rndr_list(struct buf *ob, struct buf *text, int flags, void *opaque) {
((Bypass::Parser*) opaque)->parsedList(ob, text, flags);
}
static void rndr_listitem(struct buf *ob, struct buf *text, int flags, void *opaque) {
((Bypass::Parser*) opaque)->parsedListItem(ob, text, flags);
}
static void rndr_paragraph(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedParagraph(ob, text);
}
// Span Element callbacks
static int rndr_codespan(struct buf *ob, struct buf *text, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedCodeSpan(ob, text);
}
static int rndr_double_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedDoubleEmphasis(ob, text, c);
}
static int rndr_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedEmphasis(ob, text, c);
}
static int rndr_triple_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedTripleEmphasis(ob, text, c);
}
static int rndr_linebreak(struct buf *ob, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedLinebreak(ob);
}
static int rndr_link(struct buf *ob, struct buf *link, struct buf *title, struct buf *content, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedLink(ob, link, title, content);
}
// Low Level Callbacks
static void rndr_normal_text(struct buf *ob, struct buf *text, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedNormalText(ob, text);
}
| 29.63089 | 123 | 0.635745 | [
"vector"
] |
36c32370f508e5cbf916c442ced7f4a36c71c26d | 5,704 | cpp | C++ | graph-source-code/152-E/1235568.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/152-E/1235568.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/152-E/1235568.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair <int,int> ii;
typedef pair <ii,ii> i4;
int n, m, s, M[128][128];
vector<vector<int> > dist[128][128];
vector<vector<ii> > paidist[128][128];
short int terminal[128][128];
ii S[12];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
int PD[(1<<7)][101][101][2];
bool split[(1<<7)][101][101][2];
i4 pai[(1<<7)][101][101][2];
char R[128][128];
inline void imprime() {
for (int i=0;i<n;i++)
printf("%s\n",R[i]);
}
void pinta_caminho(int i1, int j1, int i2, int j2) {
if (i1 == i2 and j1 == j2) {
R[i1][j1] = 'X';
return;
}
ii p = paidist[i1][j1][i2][j2];
if (p.first == i1 and p.second == j1) { // 1 aresta
R[i1][j1] = 'X';
R[i2][j2] = 'X';
return;
}
pinta_caminho(i1,j1,p.first,p.second);
pinta_caminho(p.first,p.second,i2,j2);
}
void pinta_arvore(int bm, int i, int j, int pfolha) {
if (bm == 0) { R[i][j] = 'X'; return; }
if (__builtin_popcount(bm) == 1) {
int t = __builtin_ctz(bm);
pinta_caminho(S[t].first,S[t].second,i,j);
return;
}
i4 u = pai[bm][i][j][pfolha];
int nbm = u.first.first, npfolha = u.first.second;
int ni = u.second.first, nj = u.second.second;
if (split[bm][i][j][pfolha]) {
//por split
pinta_arvore(nbm,i,j,npfolha);
pinta_arvore(bm^nbm,i,j,npfolha);
return;
}
// por folha
pinta_caminho(i,j,ni,nj);
pinta_arvore(nbm,ni,nj,npfolha);
}
int calc(int bm, int i, int j, int pfolha) {
if (bm == 0) return M[i][j];
int &pd = PD[bm][i][j][pfolha];
i4 &papai = pai[bm][i][j][pfolha];
bool &sp = split[bm][i][j][pfolha];
if (pd != -1) return pd;
if (__builtin_popcount(bm) == 1) {
int t = __builtin_ctz(bm);
return pd = dist[S[t].first][S[t].second][i][j];
}
//splita?
int best = 0x3f3f3f3f;
int x = (bm-1)&bm;
while (x) {
int t1 = calc(x,i,j,1);
int t2 = calc(bm^x,i,j,1);
int opc = t1+t2-M[i][j]; // conta M[i][j] 2x
if (opc < best) {
best = opc;
papai = i4(ii(x,1),ii(i,j));
sp = true;
}
x = (x-1)&bm;
}
if (pfolha) {
// 1. liga em terminal q pode ser folha da arvore "dele"
for (int k=0;k<s;k++) if (bm&(1<<k)) {
int opc = dist[i][j][S[k].first][S[k].second] +
calc(bm^(1<<k),S[k].first,S[k].second,1) -
M[S[k].first][S[k].second]; // aki tb
if (opc < best) {
best = opc;
sp = false;
papai = i4(ii(bm^(1<<k),1),ii(S[k].first,S[k].second));
}
}
//2. axa pai nao terminal que com certeza spliteia
for (int k=0;k<n;k++)
for (int l=0;l<m;l++) if ((k!=i or l!=j) and terminal[k][l] < 0) {
int opc = dist[i][j][k][l] + calc(bm,k,l,0) - M[k][l]; // aki tb
if (opc < best) {
best = opc;
sp = false;
papai = i4(ii(bm,0),ii(k,l));
}
}
}
return pd = best;
}
int main() {
scanf("%d %d %d",&n,&m,&s);
for (int i=0;i<n;i++) {
for (int j=0;j<m;j++) {
R[i][j] = '.';
dist[i][j].resize(n);
paidist[i][j].resize(n);
for (int k=0;k<n;k++) {
dist[i][j][k].resize(m);
paidist[i][j][k].resize(m);
for (int l=0;l<m;l++)
dist[i][j][k][l] = 0x3f3f3f3f;
}
}
R[i][m] = '\0';
}
for (int i=0;i<n;i++)
for (int j=0;j<m;j++) {
scanf("%d",&M[i][j]);
dist[i][j][i][j] = M[i][j];
}
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
for (int k=0;k<4;k++) {
int ni = i+dx[k];
int nj = j+dy[k];
if (!(0 <= ni and ni < n and 0 <= nj and nj < m)) continue;
dist[i][j][ni][nj] = M[i][j] + M[ni][nj];
paidist[i][j][ni][nj] = ii(i,j);
}
for (int k1=0;k1<n;k1++)
for (int k2=0;k2<m;k2++)
for (int i1=0;i1<n;i1++)
for (int i2=0;i2<m;i2++)
for (int j1=0;j1<n;j1++)
for (int j2=0;j2<m;j2++) {
int opc = dist[i1][i2][k1][k2] + dist[k1][k2][j1][j2] - M[k1][k2];
if (opc < dist[i1][i2][j1][j2]) {
dist[i1][i2][j1][j2] = opc;
paidist[i1][i2][j1][j2] = ii(k1,k2);
}
}
memset(terminal,0xff,sizeof(terminal));
for (int i=0;i<s;i++) {
int a, b;
scanf("%d %d",&a,&b); a--; b--;
terminal[a][b] = i;
S[i] = ii(a,b);
}
if (s == 1) {
printf("%d\n",M[S[0].first][S[0].second]);
R[S[0].first][S[0].second] = 'X';
imprime();
return 0;
}
if (s == 2) {
printf("%d\n",dist[S[0].first][S[0].second][S[1].first][S[1].second]);
pinta_caminho(S[0].first,S[0].second,S[1].first,S[1].second);
imprime();
return 0;
}
memset(PD,0xff,sizeof(PD));
int resp = calc((1<<s)-1-1,S[0].first,S[0].second,1);
//arg
int bm = (1<<s)-1-1, i = S[0].first, j = S[0].second, pf = 1;
pinta_arvore(bm,i,j,pf);
printf("%d\n",resp);
imprime();
int tot = 0;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (R[i][j] == 'X')
tot += M[i][j];
if (resp != tot)
printf("PAU! resp = %d, cert = %d\n",resp,tot);
return 0;
}
| 27.033175 | 82 | 0.430224 | [
"vector"
] |
36c9e314a911f4d57861c7888281aa11e95fa3d8 | 3,343 | hpp | C++ | test/comparison/libtess2.hpp | amessing/earcut.hpp | 387fdf1250e9b154cab141d1bf9ccd08e134ff06 | [
"ISC"
] | null | null | null | test/comparison/libtess2.hpp | amessing/earcut.hpp | 387fdf1250e9b154cab141d1bf9ccd08e134ff06 | [
"ISC"
] | null | null | null | test/comparison/libtess2.hpp | amessing/earcut.hpp | 387fdf1250e9b154cab141d1bf9ccd08e134ff06 | [
"ISC"
] | null | null | null | #pragma once
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
#include "libtess2/tesselator.h"
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#include <memory>
#include <vector>
#include <array>
#include <stdexcept>
template <typename Coord, typename Polygon>
class Libtess2Tesselator {
using Vertex = std::array<Coord, 2>;
using Triangles = std::vector<Vertex>;
using Vertices = std::vector<Vertex>;
using Indices = std::vector<uint32_t>;
public:
Libtess2Tesselator(const Polygon &polygon)
: tess(std::unique_ptr<TESStesselator, tessDeleter>(tessNewTess(nullptr)))
{
// Convert the polygon to Libtess2 format.
for (const auto &ring : polygon) {
std::vector<TESSreal> tessRing;
for (const auto &pt : ring) {
tessRing.push_back(static_cast<TESSreal>(pt.first));
tessRing.push_back(static_cast<TESSreal>(pt.second));
}
tessPolygon.push_back(tessRing);
}
}
void run() {
dirty = true;
// Add polygon data
for (const auto &tessRing : tessPolygon) {
tessAddContour(tess.get(), vertexSize, tessRing.data(), stride, (int)tessRing.size() / vertexSize);
}
int status = tessTesselate(tess.get(), TESS_WINDING_POSITIVE, TESS_POLYGONS, verticesPerTriangle, vertexSize, 0);
if (!status) {
#if defined(__cpp_exceptions) || defined(__EXCEPTIONS)
throw std::runtime_error("tesselation failed");
#else
assert(false && "tesselation failed");
#endif
}
}
auto indices() -> const Indices & {
if (dirty) {
indexData.clear();
const auto elements = tessGetElements(tess.get());
const auto elementCount = tessGetElementCount(tess.get());
for (int i = 0; i < elementCount; i++) {
const TESSindex *group = &elements[i * verticesPerTriangle];
if (group[0] != TESS_UNDEF && group[1] != TESS_UNDEF && group[2] != TESS_UNDEF) {
indexData.push_back(static_cast<uint32_t>(group[0]));
indexData.push_back(static_cast<uint32_t>(group[1]));
indexData.push_back(static_cast<uint32_t>(group[2]));
}
}
}
return indexData;
}
auto vertices() -> const Vertices & {
if (dirty) {
vertexData.clear();
const auto vertices = tessGetVertices(tess.get());
const auto vertexCount = tessGetVertexCount(tess.get());
for (int i = 0; i < vertexCount; i++) {
vertexData.emplace_back(Vertex{{ Coord(vertices[i * vertexSize]),
Coord(vertices[i * vertexSize + 1]) }});
}
}
return vertexData;
}
private:
static const int vertexSize = 2;
static const int stride = sizeof(TESSreal) * vertexSize;
static const int verticesPerTriangle = 3;
struct tessDeleter {
void operator()(TESStesselator *t) const { tessDeleteTess(t); }
};
std::vector<std::vector<TESSreal>> tessPolygon;
const std::unique_ptr<TESStesselator, tessDeleter> tess;
bool dirty = true;
Vertices vertexData;
Indices indexData;
};
| 31.537736 | 121 | 0.595573 | [
"vector"
] |
36cf2de4810aa427569b57f525c11d44a3b18105 | 2,308 | hpp | C++ | ZeroLibraries/Common/Math/SimMatrix3.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1 | 2022-03-26T21:08:19.000Z | 2022-03-26T21:08:19.000Z | ZeroLibraries/Common/Math/SimMatrix3.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ZeroLibraries/Common/Math/SimMatrix3.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// \file SimMatrix3.hpp
/// Declaration of the SimMat3 functionality.
///
/// Authors: Joshua Davis
/// Copyright 2012, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Math
{
namespace Simd
{
//loading
SimMat3 LoadMat3(const scalar vals[12]);
SimMat3 SetMat3(scalar m00, scalar m01, scalar m02,
scalar m10, scalar m11, scalar m12,
scalar m20, scalar m21, scalar m22);
SimMat3 UnAlignedLoadMat3(const scalar vals[12]);
//storing
void StoreMat3(scalar vals[12], SimMat3Param mat);
void UnAlignedStoreMat3(scalar vals[12], SimMat3Param mat);
//default matrix sets
SimMat3 ZeroOutMat3();
SimMat3 IdentityMat3();
//basis elements
SimVec BasisX(SimMat3Param mat);
SimVec BasisY(SimMat3Param mat);
SimVec BasisZ(SimMat3Param mat);
SimMat3 SetBasisX(SimMat3Param mat, SimVecParam value);
SimMat3 SetBasisY(SimMat3Param mat, SimVecParam value);
SimMat3 SetBasisZ(SimMat3Param mat, SimVecParam value);
//basic arithmetic
SimMat3 Add(SimMat3Param lhs, SimMat3Param rhs);
SimMat3 Subtract(SimMat3Param lhs, SimMat3Param rhs);
SimMat3 Multiply(SimMat3Param lhs, SimMat3Param rhs);
SimMat3 Scale(SimMat3Param mat, scalar scale);
SimMat3 ComponentScale(SimMat3Param lhs, SimMat3Param rhs);
SimMat3 ComponentDivide(SimMat3Param lhs, SimMat3Param rhs);
//matrix vector arithmetic
SimVec Transform(SimMat3Param mat, SimVecParam vec);
SimVec TransposeTransform(SimMat3Param mat, SimVecParam vec);
//transform building
SimMat3 BuildScale3(SimVecParam scale);
SimMat3 BuildRotation3(SimVecParam axis, scalar angle);
SimMat3 BuildRotation3(SimVecParam quat);
SimMat3 BuildTransform3(SimVecParam axis, scalar angle, SimVecParam scale);
SimMat3 BuildTransform3(SimVecParam quat, SimVecParam scale);
SimMat3 BuildTransform3(SimMat3Param rot, SimVecParam scale);
//transposes the upper 3x3 of the 4x4 and leaves the remaining elements alone
SimMat3 Transpose3(SimMat3Param mat);
SimMat3 AffineInverse3(SimMat3Param transform);
SimMat3 AffineInverseWithScale3(SimMat3Param transform);
//basic logic
SimMat3 Equal(SimMat3Param mat1, SimMat3Param mat2);
}//namespace Simd
}//namespace Math
#include "Math/SimMatrix3.inl"
| 34.969697 | 79 | 0.740468 | [
"vector",
"transform"
] |
36d316de47884a5056f711332c78a9e9779104ff | 44,505 | cpp | C++ | inetsrv/msmq/src/trigger/trigobjs/trigset.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/msmq/src/trigger/trigobjs/trigset.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/msmq/src/trigger/trigobjs/trigset.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //************************************************************************************
//
// Class Name : CMSMQTriggerSet
//
// Author : James Simpson (Microsoft Consulting Services)
//
// Description : This is the implementation of the MSMQTriggerSet object. This is the
// main object by which trigger definitons are maintained.
//
// When | Who | Change Description
// ------------------------------------------------------------------
// 12/09/98 | jsimpson | Initial Release
//
//************************************************************************************
#include "stdafx.h"
#include "stdfuncs.hpp"
#include "mqtrig.h"
#include "mqsymbls.h"
#include "mqtg.h"
#include "trigset.hpp"
#include "QueueUtil.hpp"
#include "clusfunc.h"
#include "cm.h"
#include "trigset.tmh"
using namespace std;
//************************************************************************************
//
// Method : InterfaceSupportsErrorInfo
//
// Description : Standard interface for rich error info.
//
//************************************************************************************
STDMETHODIMP CMSMQTriggerSet::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IMSMQTriggerSet
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
//************************************************************************************
//
// Method : Constructor
//
// Description : Initializes an instance of the MSMQTriggerSet object.
//
//************************************************************************************
CMSMQTriggerSet::CMSMQTriggerSet()
{
m_pUnkMarshaler = NULL;
m_hHostRegistry = NULL;
// Set the name of this class for future reference in tracing & logging etc..
m_bstrThisClassName = _T("MSMQTriggerSet");
m_fHasInitialized = false;
}
//************************************************************************************
//
// Method : Destructor
//
// Description : Destroys an instance of the MSMQTriggerSet object.
//
//************************************************************************************
CMSMQTriggerSet::~CMSMQTriggerSet()
{
// Release resources currently held by the trigger cache
ClearTriggerMap();
// Close the registry handle
if (m_hHostRegistry != NULL)
{
RegCloseKey(m_hHostRegistry);
}
}
//************************************************************************************
//
// Method : Init
//
// Description : Initialization of the object
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::Init(
BSTR bstrMachineName
)
{
bool fRes = CMSMQTriggerNotification::Init(bstrMachineName);
if ( !fRes )
{
TrERROR(GENERAL, "Failed to initialize CMSMQTriggerSet object");
SetComClassError(MQTRIG_ERROR_INIT_FAILED);
return MQTRIG_ERROR_INIT_FAILED;
}
return S_OK;
}
//************************************************************************************
//
// Method : ClearTriggerMap
//
// Description : This method destroys the contents of the current trigger map.
//
//************************************************************************************
void
CMSMQTriggerSet::ClearTriggerMap(
VOID
)
{
m_mapTriggers.erase(m_mapTriggers.begin(), m_mapTriggers.end());
}
//************************************************************************************
//
// Method : Refresh
//
// Description : This method retrieves a fresh snapshot of the trigger data from the
// database. It will rebuild it's list of triggers, rules, and the
// associations between triggers and rules. This method needs to be
// called before the client of this object can browse trigger info.
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::Refresh(
VOID
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Release resources currently held by the trigger cache
ClearTriggerMap();
if (PopulateTriggerMap() == false)
{
TrERROR(GENERAL, "Failed to refresh trigger set");
SetComClassError(MQTRIG_ERROR_COULD_NOT_RETREIVE_TRIGGER_DATA);
return MQTRIG_ERROR_COULD_NOT_RETREIVE_TRIGGER_DATA;
}
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to refresg rule set due to insufficient resources");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//************************************************************************************
//
// Method : FindTriggerInMap
//
// Description :
//
//************************************************************************************
HRESULT
CMSMQTriggerSet::FindTriggerInMap(
BSTR sTriggerID,
R<CRuntimeTriggerInfo>& pTrigger,
TRIGGER_MAP::iterator &it
)
{
pTrigger.free();
//
// Validate the supplied method parameters.
//
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "CMSMQTriggerSet::FindTriggerInMap, invalid parameter");
return MQTRIG_INVALID_TRIGGER_ID;
}
//
// Convert the BSTR rule ID to an STL basic string.
//
wstring bsTriggerID = (wchar_t*)sTriggerID;
//
// Attempt to find this trigger id in the map.
//
it = m_mapTriggers.find(bsTriggerID);
if (it == m_mapTriggers.end())
{
TrERROR(GENERAL, "Trigger id wasn't found");
return MQTRIG_TRIGGER_NOT_FOUND;
}
pTrigger = it->second;
ASSERT(pTrigger.get() != NULL);
ASSERT(pTrigger->IsValid());
return(S_OK);
}
//************************************************************************************
//
// Method : get_Count
//
// Description : Returns the number of trigger definitions currently cached by this
// object instance. This is not the same as going to the database to
// determine how many triggers are defined.
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::get_Count(
long *pVal
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
if (pVal == NULL)
{
TrERROR(GENERAL, "CMSMQTriggerSet::get_Count, invalid parameter");
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
// Get the size from the map structure.
(*pVal) = numeric_cast<long>(m_mapTriggers.size());
return S_OK;
}
///************************************************************************************
//
// Method :
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::GetTriggerDetailsByID(
/*[in]*/ BSTR sTriggerID,
/*[out]*/ BSTR * psTriggerName,
/*[out]*/ BSTR * psQueueName,
/*[out]*/ SystemQueueIdentifier* pSystemQueue,
/*[out]*/ long * plNumberOfRules,
/*[out]*/ long * plEnabledStatus,
/*[out]*/ long * plSerialized,
/*[out]*/ MsgProcessingType* pMsgProcType
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
//
// attempt to find this trigger in the map.
//
HRESULT hr = FindTriggerInMap(sTriggerID, pTrigger, it);
if (FAILED(hr))
{
TrERROR(GENERAL, "The supplied trigger id was not found in the trigger store. trigger: %ls", (LPCWSTR)sTriggerID);
SetComClassError(hr);
return hr;
}
// Populate out parameters if they have been supplied.
if (psTriggerName != NULL)
{
TrigReAllocString(psTriggerName,pTrigger->m_bstrTriggerName);
}
if(pSystemQueue != NULL)
{
(*pSystemQueue) = pTrigger->m_SystemQueue;
}
if (psQueueName != NULL)
{
TrigReAllocString(psQueueName,pTrigger->m_bstrQueueName);
}
if (plEnabledStatus != NULL)
{
(*plEnabledStatus) = (long)pTrigger->IsEnabled();
}
if (plSerialized != NULL)
{
(*plSerialized) = (long)pTrigger->IsSerialized();
}
if (plNumberOfRules != NULL)
{
(*plNumberOfRules) = pTrigger->GetNumberOfRules();
}
if (pMsgProcType != NULL)
{
(*pMsgProcType) = pTrigger->GetMsgProcessingType();
}
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to refresh trigger set due to insufficient resources");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//************************************************************************************
//
// Method :
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::GetTriggerDetailsByIndex(
/*[in]*/ long lTriggerIndex ,
/*[out]*/ BSTR * psTriggerID ,
/*[out]*/ BSTR * psTriggerName ,
/*[out]*/ BSTR * psQueueName,
/*[out]*/SystemQueueIdentifier* pSystemQueue,
/*[out]*/ long * plNumberOfRules,
/*[out]*/ long * plEnabledStatus,
/*[out]*/ long * plSerialized,
/*[out]*/ MsgProcessingType* pMsgProcType
)
{
long lCounter = 0;
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Check that the supplied index is within range.
if ((lTriggerIndex < 0) || (numeric_cast<DWORD>(lTriggerIndex) > m_mapTriggers.size()))
{
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
TRIGGER_MAP::iterator it = m_mapTriggers.begin();
// Move to the lTriggerIndex-th location in the triggers map
for (lCounter=0; lCounter < lTriggerIndex;lCounter++,++it)
{
NULL;
}
// Cast to a Trigger object reference
R<CRuntimeTriggerInfo> pTrigger = it->second;
// We should never have nulls in the map
ASSERT(pTrigger.get() != NULL);
// We should only store valid triggers
ASSERT(pTrigger->IsValid());
// Populate out parameters if they have been supplied.
if (psTriggerID != NULL)
{
TrigReAllocString(psTriggerID,pTrigger->m_bstrTriggerID);
}
if (psTriggerName != NULL)
{
TrigReAllocString(psTriggerName,pTrigger->m_bstrTriggerName);
}
if(pSystemQueue != NULL)
{
(*pSystemQueue) = pTrigger->m_SystemQueue;
}
if (psQueueName != NULL)
{
TrigReAllocString(psQueueName,pTrigger->m_bstrQueueName);
}
if (plEnabledStatus != NULL)
{
(*plEnabledStatus) = (long)pTrigger->IsEnabled();
}
if (plSerialized != NULL)
{
(*plSerialized) = (long)pTrigger->IsSerialized();
}
if (plNumberOfRules != NULL)
{
(*plNumberOfRules) = pTrigger->GetNumberOfRules();
}
if (pMsgProcType != NULL)
{
(*pMsgProcType) = pTrigger->GetMsgProcessingType();
}
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//************************************************************************************
//
// Method :
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::GetRuleDetailsByTriggerIndex(
long lTriggerIndex,
long lRuleIndex,
BSTR *psRuleID,
BSTR *psRuleName,
BSTR *psDescription,
BSTR *psCondition,
BSTR *psAction ,
BSTR *psImplementationProgID,
BOOL *pfShowWindow
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
HRESULT hr = S_OK;
long lCounter = 0;
CRuntimeRuleInfo * pRule = NULL;
try
{
// We need to validate that the supplied rule index is within range
if ((lTriggerIndex < 0) || (numeric_cast<DWORD>(lTriggerIndex) > m_mapTriggers.size()))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetRuleDetailsByTriggerIndex. lTriggerIndex = %d", lTriggerIndex);
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
if SUCCEEDED(hr)
{
// Get a reference to the beginging of the map
TRIGGER_MAP::iterator i = m_mapTriggers.begin();
// Iterate through to the correct index.
for (lCounter = 0; lCounter < lTriggerIndex ; ++i,lCounter++)
{
NULL;
}
// Cast to a rule object reference
R<CRuntimeTriggerInfo> pTrigger = i->second;
// We should never have nulls in the map
ASSERT(pTrigger.get() != NULL);
// We should only store valid triggers.
ASSERT(pTrigger->IsValid());
// Validate the supplied rule index against the number rule attached to this trigger
if ((lRuleIndex < 0) || (lRuleIndex > pTrigger->GetNumberOfRules()))
{
TrERROR(GENERAL, "Invalid rule index passed to GetRuleDetailsByTriggerIndex. lRuleIndex = %d", lRuleIndex);
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
pRule = pTrigger->GetRule(lRuleIndex);
// We should never get a null rule after validating the index.
ASSERT(pRule != NULL);
// We should never get invalid rule definitions
ASSERT(pRule->IsValid());
// Populate out parameters if they have been supplied.
if (psRuleID != NULL)
{
TrigReAllocString(psRuleID,pRule->m_bstrRuleID);
}
if (psRuleName != NULL)
{
TrigReAllocString(psRuleName,pRule->m_bstrRuleName);
}
if(psDescription != NULL)
{
TrigReAllocString(psDescription,pRule->m_bstrRuleDescription);
}
if (psCondition != NULL)
{
TrigReAllocString(psCondition,pRule->m_bstrCondition);
}
if (psAction != NULL)
{
TrigReAllocString(psAction,pRule->m_bstrAction);
}
if (psImplementationProgID != NULL)
{
TrigReAllocString(psImplementationProgID,pRule->m_bstrImplementationProgID);
}
if(pfShowWindow != NULL)
{
*pfShowWindow = pRule->m_fShowWindow;
}
}
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
return hr;
}
//************************************************************************************
//
// Method :
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::GetRuleDetailsByTriggerID(
BSTR sTriggerID,
long lRuleIndex,
BSTR *psRuleID,
BSTR *psRuleName,
BSTR *psDescription,
BSTR *psCondition,
BSTR *psAction,
BSTR *psImplementationProgID,
BOOL *pfShowWindow
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
// find this trigger in the trigger map
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
HRESULT hr = FindTriggerInMap(sTriggerID, pTrigger, it);
if (hr != S_OK)
{
SetComClassError(hr);
return hr;
}
// Validate that the specified trigger actually has rules.
if (pTrigger->GetNumberOfRules() < 1)
{
TrERROR(GENERAL, "The supplied trigger id has no rules attached. trigger: %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_RULE_NOT_ATTACHED);
return MQTRIG_RULE_NOT_ATTACHED;
}
// Validate the supplied rule index against the number rule attached to this trigger
if ((lRuleIndex < 0) || (lRuleIndex >= pTrigger->GetNumberOfRules()))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
// Get a reference to the rule at the specified index.
CRuntimeRuleInfo* pRule = pTrigger->GetRule(lRuleIndex);
// We should never get a null rule after validating the index.
ASSERT(pRule != NULL);
// We should never get invalid rule definitions
ASSERT(pRule->IsValid());
// Populate out parameters if they have been supplied.
if (psRuleID != NULL)
{
TrigReAllocString(psRuleID,pRule->m_bstrRuleID);
}
if (psRuleName != NULL)
{
TrigReAllocString(psRuleName,pRule->m_bstrRuleName);
}
if(psDescription != NULL)
{
TrigReAllocString(psDescription,pRule->m_bstrRuleDescription);
}
if (psCondition != NULL)
{
TrigReAllocString(psCondition,pRule->m_bstrCondition);
}
if (psAction != NULL)
{
TrigReAllocString(psAction,pRule->m_bstrAction);
}
if (psImplementationProgID != NULL)
{
TrigReAllocString(psImplementationProgID,pRule->m_bstrImplementationProgID);
}
if(pfShowWindow != NULL)
{
*pfShowWindow = pRule->m_fShowWindow;
}
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//************************************************************************************
//
// Method : AddTrigger
//
// Description : This method will add a new trigger to the underlying trigger store. It
// will create a new trigger (a GUID in string form) and attempt to insert
// this into the registry.
//
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::AddTrigger(
BSTR sTriggerName,
BSTR sQueueName,
SystemQueueIdentifier SystemQueue,
long lEnabled,
long lSerialized,
MsgProcessingType msgProcType,
BSTR * psTriggerID
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
HRESULT hr = S_OK;
TRIGGER_MAP::iterator i;
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerName(sTriggerName))
{
TrERROR(GENERAL, "Invalid trigger name passed to AddTrigger. sTriggerName = %ls", (LPCWSTR)sTriggerName);
SetComClassError(MQTRIG_INVALID_TRIGGER_NAME);
return MQTRIG_INVALID_TRIGGER_NAME;
}
if SUCCEEDED(hr)
{
if(SystemQueue == SYSTEM_QUEUE_NONE)
{
if (!CRuntimeTriggerInfo::IsValidTriggerQueueName(sQueueName))
{
TrERROR(GENERAL, "Invalid queue name passed to AddTrigger. sQueueName = %ls", (LPCWSTR)sQueueName);
SetComClassError(MQTRIG_INVALID_TRIGGER_QUEUE);
return MQTRIG_INVALID_TRIGGER_QUEUE;
}
}
}
if SUCCEEDED(hr)
{
_bstr_t bstrUpdatedQueueName;
_bstr_t bstrMachineName;
if(SystemQueue != SYSTEM_QUEUE_NONE) //one of the system queues is selected
{
//generate format name for the selected system queue
hr = GenSystemQueueFormatName(SystemQueue, &bstrUpdatedQueueName);
if(hr != S_OK)
{
TrERROR(GENERAL, "Failed to generate system queue format name. Error=0x%x", hr);
SetComClassError(MQTRIG_ERROR_COULD_NOT_ADD_TRIGGER);
return MQTRIG_ERROR_COULD_NOT_ADD_TRIGGER;
}
}
else //queue path given
{
//
// if queue name contains "." as machine name, replace it with the
// local machine name
//
DWORD dwError = GetLocalMachineName(&bstrMachineName);
if(dwError != 0)
{
TrERROR(GENERAL, "Failed to retreive local machine queue. Error=0x%x", dwError);
SetComClassError(MQTRIG_ERROR_COULD_NOT_ADD_TRIGGER);
return MQTRIG_ERROR_COULD_NOT_ADD_TRIGGER;
}
UpdateMachineNameInQueuePath(
sQueueName,
bstrMachineName,
&bstrUpdatedQueueName );
}
//
// Allow only one receive trigger per queue
//
if (msgProcType != PEEK_MESSAGE &&
ExistTriggersForQueue(bstrUpdatedQueueName))
{
TrERROR(GENERAL, "Failed to add new trigger. Multiple trigger isn't allowed on receive trigger");
SetComClassError(MQTRIG_ERROR_MULTIPLE_RECEIVE_TRIGGER );
return MQTRIG_ERROR_MULTIPLE_RECEIVE_TRIGGER;
}
if (msgProcType == PEEK_MESSAGE &&
ExistsReceiveTrigger(bstrUpdatedQueueName))
{
TrERROR(GENERAL, "Failed to add new trigger. Multiple trigger isn't allowed on receive trigger");
SetComClassError(MQTRIG_ERROR_MULTIPLE_RECEIVE_TRIGGER );
return MQTRIG_ERROR_MULTIPLE_RECEIVE_TRIGGER;
}
//
// Force serialized trigger for transactional receive
//
if ( msgProcType == RECEIVE_MESSAGE_XACT )
{
lSerialized = 1;
}
//
// Allocate a new trigger object
//
R<CRuntimeTriggerInfo> pTrigger = new CRuntimeTriggerInfo(
CreateGuidAsString(),
sTriggerName,
bstrUpdatedQueueName,
m_wzRegPath,
SystemQueue,
(lEnabled != 0),
(lSerialized != 0),
msgProcType
);
if (pTrigger->Create(m_hHostRegistry) == true)
{
//
// Keep trigger ID and Queue name for later use
//
BSTR bstrQueueName = pTrigger->m_bstrQueueName;
BSTR bstrTriggerID = pTrigger->m_bstrTriggerID;
//
// Add this trigger to map.
//
m_mapTriggers.insert(TRIGGER_MAP::value_type(bstrTriggerID, pTrigger));
//
// If we have been supplied a out parameter pointer for the new rule ID use it.
//
if (psTriggerID != NULL)
{
TrigReAllocString(psTriggerID, bstrTriggerID);
}
//
// send a notification indicating that a trigger has been added to the trigger store.
//
NotifyTriggerAdded(bstrTriggerID, sTriggerName, bstrQueueName);
return S_OK;
}
else
{
// We need to delete the trigger instance object as the create failed.
TrERROR(GENERAL, "Failed to store trigger data in registry");
SetComClassError(MQTRIG_ERROR_STORE_DATA_FAILED );
return MQTRIG_ERROR_STORE_DATA_FAILED;
}
}
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
return hr;
}
//************************************************************************************
//
// Method : DeleteTrigger
//
// Description : This method removes a trigger definiton from the database. It will not
// delete any rules that are attached to this trigger, however it will
// delete any associations between the supplied trigger id and existing
// rules in the database.
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::DeleteTrigger(
BSTR sTriggerID
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
// find this trigger in the map.
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
long hr = FindTriggerInMap(sTriggerID,pTrigger,it);
if (hr != S_OK)
{
SetComClassError(hr);
return hr;
}
// Delete the Trigger from the underlying data store.
bool f = pTrigger->Delete(m_hHostRegistry);
if (!f)
{
TrERROR(GENERAL, "Failed to delete trigger from trigger set. trigget %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_ERROR_COULD_NOT_DELETE_TRIGGER);
return MQTRIG_ERROR_COULD_NOT_DELETE_TRIGGER;
}
// Send a notification that a trigger has been deleted from the trigger store.
NotifyTriggerDeleted(pTrigger->m_bstrTriggerID);
// Now remove this Trigger from our map.
m_mapTriggers.erase(it);
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
return S_OK;
}
//************************************************************************************
//
// Method :
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::UpdateTrigger(
BSTR sTriggerID,
BSTR sTriggerName,
BSTR sQueueName,
SystemQueueIdentifier SystemQueue,
long lEnabled,
long lSerialized,
MsgProcessingType msgProcType
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
if (!CRuntimeTriggerInfo::IsValidTriggerName(sTriggerName))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_NAME);
return MQTRIG_INVALID_TRIGGER_NAME;
}
if(SystemQueue == SYSTEM_QUEUE_NONE)
{
if(sQueueName != NULL)
{
if (!CRuntimeTriggerInfo::IsValidTriggerQueueName(sQueueName))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_QUEUE);
return MQTRIG_INVALID_TRIGGER_QUEUE;
}
}
}
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
HRESULT hr = FindTriggerInMap(sTriggerID, pTrigger, it);
if (hr != S_OK)
{
SetComClassError(hr);
return hr;
}
_bstr_t bstrUpdatedQueueName;
SystemQueueIdentifier queueType = SYSTEM_QUEUE_NONE;
if(SystemQueue != SYSTEM_QUEUE_NONE) //one of the system queues is selected
{
//generate format name for the selected system queue
hr = GenSystemQueueFormatName(SystemQueue, &bstrUpdatedQueueName);
if(hr != S_OK)
{
TrERROR(GENERAL, "Failed to generate system queue format name. Error=0x%x", hr);
SetComClassError(MQTRIG_ERROR);
return MQTRIG_ERROR;
}
queueType = SystemQueue;
}
else if (sQueueName != NULL) //queue path given
{
_bstr_t bstrMachineName;
//
// if queue name contains "." as machine name, replace it with the
// local machine name
//
DWORD dwError = GetLocalMachineName(&bstrMachineName);
if(dwError != 0)
{
TrERROR(GENERAL, "Failed to retreive local machine queue. Error=0x%x", dwError);
SetComClassError(MQTRIG_ERROR);
return MQTRIG_ERROR;
}
UpdateMachineNameInQueuePath(
sQueueName,
bstrMachineName,
&bstrUpdatedQueueName );
queueType = SYSTEM_QUEUE_NONE;
}
//
// Allow only one receive trigger per queue
//
if ((msgProcType != PEEK_MESSAGE) &&
(GetNoOfTriggersForQueue(bstrUpdatedQueueName) > 1))
{
TrERROR(GENERAL, "Failed to add new trigger. Multiple trigger isn't allowed on receive trigger");
SetComClassError(MQTRIG_ERROR_MULTIPLE_RECEIVE_TRIGGER );
return MQTRIG_ERROR_MULTIPLE_RECEIVE_TRIGGER;
}
//
// Force serialized trigger for transactional receive
//
if ( msgProcType == RECEIVE_MESSAGE_XACT )
{
lSerialized = 1;
}
//
// Update values
//
pTrigger->m_bstrTriggerName = (wchar_t*)sTriggerName;
pTrigger->m_SystemQueue = queueType;
pTrigger->m_bstrQueueName = (wchar_t*)bstrUpdatedQueueName;
pTrigger->m_bEnabled = (lEnabled != 0)?true:false;
pTrigger->m_bSerialized = (lSerialized != 0)?true:false;
pTrigger->SetMsgProcessingType(msgProcType);
if (pTrigger->Update(m_hHostRegistry) == true)
{
// send a notification indicating that a trigger in the trigger store has been updated.
NotifyTriggerUpdated(
pTrigger->m_bstrTriggerID,
pTrigger->m_bstrTriggerName,
pTrigger->m_bstrQueueName
);
return S_OK;
}
TrERROR(GENERAL, "Failed to store the updated data for trigger: %ls in registry", (LPCWSTR)pTrigger->m_bstrTriggerID);
SetComClassError(MQTRIG_ERROR_STORE_DATA_FAILED);
return MQTRIG_ERROR_STORE_DATA_FAILED;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//************************************************************************************
//
// Method : DetachAllRules
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::DetachAllRules(
BSTR sTriggerID
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
//
// find this trigger in the map
//
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
HRESULT hr = FindTriggerInMap(sTriggerID, pTrigger, it);
if (hr != S_OK)
{
SetComClassError(hr);
return hr;
}
// Attempt to detach the rule.
if (!pTrigger->DetachAllRules(m_hHostRegistry))
{
TrERROR(GENERAL, "Failed to store the updated data for trigger: %ls in registry", (LPCWSTR)pTrigger->m_bstrTriggerID);
SetComClassError(MQTRIG_ERROR_STORE_DATA_FAILED);
return MQTRIG_ERROR_STORE_DATA_FAILED;
}
NotifyTriggerUpdated(sTriggerID, pTrigger->m_bstrTriggerName, pTrigger->m_bstrQueueName);
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
return S_OK;
}
//************************************************************************************
//
// Method : AttachRule
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::AttachRule(
BSTR sTriggerID,
BSTR sRuleID,
long lPriority
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
if (!CRuntimeRuleInfo::IsValidRuleID(sRuleID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_RULEID);
return MQTRIG_INVALID_RULEID;
}
// find this trigger in the map
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
HRESULT hr = FindTriggerInMap(sTriggerID, pTrigger, it);
if (hr != S_OK)
{
SetComClassError(hr);
return hr;
}
// Ensure that this rule is not allready attached.
if (pTrigger->IsRuleAttached(sRuleID) == true)
{
TrERROR(GENERAL, "Unable to attach rule because it is already attached.");
SetComClassError(MQTRIG_RULE_ALLREADY_ATTACHED);
return MQTRIG_RULE_ALLREADY_ATTACHED;
}
// We should only store valid triggers.
ASSERT(pTrigger->IsValid());
if(lPriority > pTrigger->GetNumberOfRules())
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
// Attempt to attach the rule.
if (pTrigger->Attach(m_hHostRegistry,sRuleID,lPriority) == false)
{
TrERROR(GENERAL, "Failed to store the updated data for trigger: %ls in registry", (LPCWSTR)pTrigger->m_bstrTriggerID);
SetComClassError(MQTRIG_ERROR_STORE_DATA_FAILED);
return MQTRIG_ERROR_STORE_DATA_FAILED;
}
// send a notification indicating that a trigger in the trigger store has been updated.
NotifyTriggerUpdated(pTrigger->m_bstrTriggerID,pTrigger->m_bstrTriggerName,pTrigger->m_bstrQueueName);
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//************************************************************************************
//
// Method :
//
// Description :
//
//************************************************************************************
STDMETHODIMP
CMSMQTriggerSet::DetachRule(
BSTR sTriggerID,
BSTR sRuleID
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
try
{
// Validate the supplied method parameters.
if (!CRuntimeTriggerInfo::IsValidTriggerID(sTriggerID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_TRIGGER_ID);
return MQTRIG_INVALID_TRIGGER_ID;
}
if (!CRuntimeRuleInfo::IsValidRuleID(sRuleID))
{
TrERROR(GENERAL, "Invalid trigger ID passed to GetTriggerDetailsByID. sTriggerID = %ls", (LPCWSTR)sTriggerID);
SetComClassError(MQTRIG_INVALID_RULEID);
return MQTRIG_INVALID_RULEID;
}
TRIGGER_MAP::iterator it;
R<CRuntimeTriggerInfo> pTrigger;
HRESULT hr = FindTriggerInMap(sTriggerID, pTrigger, it);
if (hr != S_OK)
{
SetComClassError(hr);
return hr;
}
// Check that this rule is really attached.
if (pTrigger->IsRuleAttached(sRuleID) == false)
{
TrERROR(GENERAL, "Unable to detach rule because it is not currently attached.");
SetComClassError(MQTRIG_RULE_NOT_ATTACHED);
return MQTRIG_RULE_NOT_ATTACHED;
}
// We should only store valid triggers.
ASSERT(pTrigger->IsValid());
// Attempt to detach the rule.
if (pTrigger->Detach(m_hHostRegistry,sRuleID) == false)
{
TrERROR(GENERAL, "Failed to store the updated data for trigger: %ls in registry", (LPCWSTR)pTrigger->m_bstrTriggerID);
SetComClassError(MQTRIG_ERROR_STORE_DATA_FAILED);
return MQTRIG_ERROR_STORE_DATA_FAILED;
}
//
// send a notification indicating that a trigger in the trigger store has been updated.
//
NotifyTriggerUpdated(pTrigger->m_bstrTriggerID,pTrigger->m_bstrTriggerName,pTrigger->m_bstrQueueName);
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to get trigger details by index");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
//*******************************************************************
//
// Method : PopulateTriggerMap
//
// Description : This method will populate the rule map with instances
// of the CRuntimeTriggerInfo class based on the data found
// in the registry. Note that this method will create the
// triggers data registry key if it does not already exist.
//
//*******************************************************************
bool
CMSMQTriggerSet::PopulateTriggerMap(
VOID
)
{
HKEY hTrigKey;
try
{
RegEntry regMsmqTrig(m_wzRegPath, L"", 0, RegEntry::MustExist, HKEY_LOCAL_MACHINE);
HKEY hKey = CmOpenKey(regMsmqTrig, KEY_READ);
CRegHandle ark(hKey);
RegEntry regTrig(REG_SUBKEY_TRIGGERS, L"", 0, RegEntry::MustExist, hKey);
hTrigKey = CmOpenKey(regTrig, KEY_READ);
}
catch(const exception&)
{
TrERROR(GENERAL, "Failed to open the registry key: %ls\\%ls", m_wzRegPath, REG_SUBKEY_TRIGGERS);
return false;
}
CRegHandle ar(hTrigKey);
//
// Enumerate through the keys under the REG_SUBKEY_RULES key.
// Each Key here should be a RuleID. As we enumerate through these keys,
// we will populate the rules list with instance of the CRuntimeRuleInfo class.
// If any rule fails to load, we remove it from the list.
//
for(DWORD index =0;; ++index)
{
WCHAR trigName[MAX_REGKEY_NAME_SIZE];
DWORD len = TABLE_SIZE(trigName);
LONG rc = RegEnumKeyEx(
hTrigKey,
index,
trigName,
&len,
NULL,
NULL,
NULL,
NULL
);
if(rc == ERROR_NO_MORE_ITEMS)
{
return true;
}
if ((rc == ERROR_NOTIFY_ENUM_DIR) || (rc== ERROR_KEY_DELETED))
{
ClearTriggerMap();
return PopulateTriggerMap();
}
if (rc != ERROR_SUCCESS)
{
TrERROR(GENERAL, "Failed to enumerate trigger. Error=%!winerr!", rc);
return false;
}
R<CRuntimeTriggerInfo> pTrigger = new CRuntimeTriggerInfo(m_wzRegPath);
HRESULT hr = pTrigger->Retrieve(m_hHostRegistry, trigName);
if (FAILED(hr))
{
//
// If trigger was deleted between enumeration and retrieval, just ignore
// it. Another notification message will be recieved.
//
if (hr == MQTRIG_TRIGGER_NOT_FOUND)
{
continue;
}
//
// Failed to load the rule. Log an error and delete the rule object.
//
TrERROR(GENERAL, "PopulateTriggerMap failed to load trigger %ls from registry.", trigName);
return false;
}
//
// At this point we have successfully loaded the rule, now insert it into the rule map.
//
wstring sTriggerID = pTrigger->m_bstrTriggerID;
//
// Check if this rule is already in the map.
//
if(m_mapTriggers.find(sTriggerID) == m_mapTriggers.end())
{
//
// if queue name contains "." as machine name, replace it with the
// store machine name
//
_bstr_t bstrOldQueueName = pTrigger->m_bstrQueueName;
bool fUpdated = UpdateMachineNameInQueuePath(
bstrOldQueueName,
m_bstrMachineName,
&(pTrigger->m_bstrQueueName) );
//
// if queue name was updated, update registry as well
//
if(fUpdated)
{
if ( !pTrigger->Update(m_hHostRegistry) )
{
TrERROR(GENERAL, "CMSMQTriggerSet::PopulateTriggerMap() failed becuse a duplicate rule id was found. The rule id was (%ls).", (LPCWSTR)pTrigger->m_bstrTriggerID);
}
}
m_mapTriggers.insert(TRIGGER_MAP::value_type(sTriggerID,pTrigger));
}
}
ASSERT(("this code shouldn't reach", 0));
return true;
}
STDMETHODIMP
CMSMQTriggerSet::get_TriggerStoreMachineName(
BSTR *pVal
)
{
if(!m_fHasInitialized)
{
TrERROR(GENERAL, "trigger set object wasn't initialized. Before calling any method of TriggerSet you must initialize the object.");
SetComClassError(MQTRIG_ERROR_TRIGGERSET_NOT_INIT);
return MQTRIG_ERROR_TRIGGERSET_NOT_INIT;
}
if(pVal == NULL)
{
TrERROR(GENERAL, "Inavlid parameter to get_TriggerStoreMachineName");
SetComClassError(MQTRIG_INVALID_PARAMETER);
return MQTRIG_INVALID_PARAMETER;
}
try
{
TrigReAllocString(pVal, (TCHAR*)m_bstrMachineName);
return S_OK;
}
catch(const bad_alloc&)
{
TrERROR(GENERAL, "Failed to refresg rule set due to insufficient resources");
SetComClassError(MQTRIG_ERROR_INSUFFICIENT_RESOURCES);
return MQTRIG_ERROR_INSUFFICIENT_RESOURCES;
}
}
DWORD
CMSMQTriggerSet::GetNoOfTriggersForQueue(
const BSTR& bstrQueueName
) const
{
DWORD noOfTriggers = 0;
for(TRIGGER_MAP::const_iterator it = m_mapTriggers.begin(); it != m_mapTriggers.end(); it++)
{
R<CRuntimeTriggerInfo> pTrigger = it->second;
if ( _wcsicmp( pTrigger->m_bstrQueueName, bstrQueueName ) == 0 )
{
++noOfTriggers;
}
}
return noOfTriggers;
}
bool
CMSMQTriggerSet::ExistTriggersForQueue(
const BSTR& bstrQueueName
) const
{
for (TRIGGER_MAP::const_iterator it = m_mapTriggers.begin(); it != m_mapTriggers.end(); it++)
{
R<CRuntimeTriggerInfo> pTrigger = it->second;
if ( _wcsicmp( pTrigger->m_bstrQueueName, bstrQueueName ) == 0 )
{
return true;
}
}
return false;
}
bool
CMSMQTriggerSet::ExistsReceiveTrigger(
const BSTR& bstrQueueName
) const
{
for (TRIGGER_MAP::const_iterator it = m_mapTriggers.begin(); it != m_mapTriggers.end(); it++)
{
R<CRuntimeTriggerInfo> pTrigger = it->second;
// We should never have null pointers in this map.
ASSERT(("NULL trigger in triggers list\n", pTrigger.get() != NULL));
if ((_wcsicmp( pTrigger->m_bstrQueueName, bstrQueueName) == 0) &&
(pTrigger->GetMsgProcessingType() != PEEK_MESSAGE))
{
return true;
}
}
return false;
}
void CMSMQTriggerSet::SetComClassError(HRESULT hr)
{
WCHAR errMsg[256];
DWORD size = TABLE_SIZE(errMsg);
GetErrorDescription(hr, errMsg, size);
Error(errMsg, GUID_NULL, hr);
}
| 27.523191 | 168 | 0.631637 | [
"object"
] |
36d7d7b3be08200635e823fbe41b6dbbc5e6bdb7 | 2,869 | cc | C++ | vod/src/model/GetMediaAuditAudioResultDetailResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | vod/src/model/GetMediaAuditAudioResultDetailResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | vod/src/model/GetMediaAuditAudioResultDetailResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vod/model/GetMediaAuditAudioResultDetailResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Vod;
using namespace AlibabaCloud::Vod::Model;
GetMediaAuditAudioResultDetailResult::GetMediaAuditAudioResultDetailResult() :
ServiceResult()
{}
GetMediaAuditAudioResultDetailResult::GetMediaAuditAudioResultDetailResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetMediaAuditAudioResultDetailResult::~GetMediaAuditAudioResultDetailResult()
{}
void GetMediaAuditAudioResultDetailResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto mediaAuditAudioResultDetailNode = value["MediaAuditAudioResultDetail"];
if(!mediaAuditAudioResultDetailNode["Total"].isNull())
mediaAuditAudioResultDetail_.total = std::stoi(mediaAuditAudioResultDetailNode["Total"].asString());
if(!mediaAuditAudioResultDetailNode["PageTotal"].isNull())
mediaAuditAudioResultDetail_.pageTotal = std::stoi(mediaAuditAudioResultDetailNode["PageTotal"].asString());
auto allListNode = mediaAuditAudioResultDetailNode["List"]["ListItem"];
for (auto mediaAuditAudioResultDetailNodeListListItem : allListNode)
{
MediaAuditAudioResultDetail::ListItem listItemObject;
if(!mediaAuditAudioResultDetailNodeListListItem["StartTime"].isNull())
listItemObject.startTime = std::stol(mediaAuditAudioResultDetailNodeListListItem["StartTime"].asString());
if(!mediaAuditAudioResultDetailNodeListListItem["EndTime"].isNull())
listItemObject.endTime = std::stol(mediaAuditAudioResultDetailNodeListListItem["EndTime"].asString());
if(!mediaAuditAudioResultDetailNodeListListItem["Text"].isNull())
listItemObject.text = mediaAuditAudioResultDetailNodeListListItem["Text"].asString();
if(!mediaAuditAudioResultDetailNodeListListItem["Label"].isNull())
listItemObject.label = mediaAuditAudioResultDetailNodeListListItem["Label"].asString();
mediaAuditAudioResultDetail_.list.push_back(listItemObject);
}
}
GetMediaAuditAudioResultDetailResult::MediaAuditAudioResultDetail GetMediaAuditAudioResultDetailResult::getMediaAuditAudioResultDetail()const
{
return mediaAuditAudioResultDetail_;
}
| 41.57971 | 141 | 0.805856 | [
"model"
] |
36db5c9ee72957efe649b98d05a5b2bf8e2281f8 | 599 | cpp | C++ | splitStringByWhitespaces.cpp | nileshleve/CompCoding | e082533e57c9d6aa55845d733e6f5ff7d99ea057 | [
"MIT"
] | null | null | null | splitStringByWhitespaces.cpp | nileshleve/CompCoding | e082533e57c9d6aa55845d733e6f5ff7d99ea057 | [
"MIT"
] | null | null | null | splitStringByWhitespaces.cpp | nileshleve/CompCoding | e082533e57c9d6aa55845d733e6f5ff7d99ea057 | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str("Split me by whitespaces");
string buf; // Have a buffer string
stringstream ss(str); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
}
/* Something Complementary
string s="12345";
int x=0;
stringstream convert(s);//object from the class stringstream.
convert>>x; //the object has the value 12345 and stream it to the integer x.
//now the variable x holds the value 12345.
*/ | 19.966667 | 76 | 0.689482 | [
"object",
"vector"
] |
36dc99850558bad99142936f193aa89e55c7a5dd | 2,321 | hpp | C++ | src/libsessionutility/sessionutility.hpp | publiqnet/mesh.pp | a85e393c0de82b5b477b48bf23f0b89f6ac82c26 | [
"MIT"
] | 1 | 2020-02-22T16:50:11.000Z | 2020-02-22T16:50:11.000Z | src/libsessionutility/sessionutility.hpp | publiqnet/mesh.pp | a85e393c0de82b5b477b48bf23f0b89f6ac82c26 | [
"MIT"
] | null | null | null | src/libsessionutility/sessionutility.hpp | publiqnet/mesh.pp | a85e393c0de82b5b477b48bf23f0b89f6ac82c26 | [
"MIT"
] | null | null | null | #pragma once
#include "global.hpp"
#include <belt.pp/packet.hpp>
#include <belt.pp/isocket.hpp>
#include <string>
#include <vector>
#include <exception>
#include <stdexcept>
#include <chrono>
#include <unordered_map>
#include <memory>
namespace meshpp
{
class SESSIONUTILITYSHARED_EXPORT nodeid_session_header
{
public:
beltpp::ip_address address;
std::string peerid;
std::string nodeid;
bool operator == (nodeid_session_header const& other) const
{
return address == other.address &&
peerid == other.peerid &&
nodeid == other.nodeid;
}
bool operator != (nodeid_session_header const& other) const
{
return !(operator == (other));
}
};
class SESSIONUTILITYSHARED_EXPORT session_header
{
public:
std::string peerid;
bool operator == (session_header const& other) const
{
return peerid == other.peerid;
}
bool operator != (session_header const& other) const
{
return !(operator == (other));
}
};
template <typename T_session_header>
class SESSIONUTILITYSHARED_EXPORT session_action
{
public:
session_action() = default;
session_action(session_action const&) = default;
virtual ~session_action()
{
if (errored)
{
assert(initiated);
}
}
virtual void initiate(T_session_header& header) = 0;
virtual bool process(beltpp::packet&& package, T_session_header& header) = 0;
virtual bool permanent() const = 0;
bool initiated = false;
bool completed = false;
bool errored = false;
size_t expected_next_package_type = size_t(-1);
};
namespace detail
{
template <typename T_session_header>
class session_manager_impl;
}
template <typename T_session_header>
class SESSIONUTILITYSHARED_EXPORT session_manager
{
public:
session_manager();
~session_manager();
bool add(T_session_header const& header,
std::vector<std::unique_ptr<session_action<T_session_header>>>&& actions,
std::chrono::steady_clock::duration wait_duration);
void remove(std::string const& peerid);
bool process(std::string const& peerid,
beltpp::packet&& package);
void erase_all_pending();
std::unique_ptr<detail::session_manager_impl<T_session_header>> m_pimpl;
};
}
| 21.896226 | 86 | 0.672555 | [
"vector"
] |
36dcf87890fc7db0ee53c041315d81b2b2c6ffaf | 803 | cpp | C++ | Libraries/Arrays/Inversion.cpp | ankitdixit/code-gems | bdb30ba5c714f416dbf54d479d055458bde36085 | [
"MIT"
] | null | null | null | Libraries/Arrays/Inversion.cpp | ankitdixit/code-gems | bdb30ba5c714f416dbf54d479d055458bde36085 | [
"MIT"
] | null | null | null | Libraries/Arrays/Inversion.cpp | ankitdixit/code-gems | bdb30ba5c714f416dbf54d479d055458bde36085 | [
"MIT"
] | 2 | 2017-09-30T06:26:02.000Z | 2020-08-20T14:41:55.000Z | #include <vector>
using namespace std;
template <class T>
int imerge(vector<T> &ary, int left, int mid, int right, vector<T> &tmp) {
int l = left, r = mid + 1, i = left, inv = 0;
while (l <= mid && r <= right) {
if (ary[l] <= ary[r])
tmp[i++] = ary[l++];
else {
tmp[i++] = ary[r++];
inv += mid - l + 1;
}
}
while (l <= mid)
tmp[i++] = ary[l++];
while (r <= right)
tmp[i++] = ary[r++];
std::copy(tmp.begin() + left, tmp.begin() + right + 1, ary.begin() + left);
return inv;
}
template <class T>
int inversions(vector<T> &ary, int left, int right, vector<T> &tmp) {
if (right <= left)
return 0;
int mid = (left + right) / 2;
int i = inversions(ary, left, mid, tmp);
i += inversions(ary, mid + 1, right, tmp);
i += imerge(ary, left, mid, right, tmp);
return i;
} | 20.075 | 76 | 0.547945 | [
"vector"
] |
36df2830315246144b58a1033c334b547273b6d4 | 5,023 | hpp | C++ | src/mlpack/core/util/mlpack_main.hpp | MJ10/mlpack | 3f87ab1d419493dead8ef59250c02cc7aacc0adb | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-05-02T21:10:55.000Z | 2021-05-02T21:10:55.000Z | src/mlpack/core/util/mlpack_main.hpp | MJ10/mlpack | 3f87ab1d419493dead8ef59250c02cc7aacc0adb | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/core/util/mlpack_main.hpp | MJ10/mlpack | 3f87ab1d419493dead8ef59250c02cc7aacc0adb | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @param mlpack_cli_main.hpp
* @author Ryan Curtin
*
* This file, based on the value of the macro BINDING_TYPE, will define the
* macro MLPACK_CLI_MAIN() accordingly. If BINDING_TYPE is not set, then the
* behavior will be that MLPACK_CLI_MAIN() is equivalent to int main(int argc,
* char** argv) with CLI::ParseCommandLine() automatically called on entry and
* CLI::Destroy() automatically called on exit.
*
* This file should *only* be included by a program that is meant to be a
* command-line program or a binding to another language. This file also
* includes param_checks.hpp, which contains functions that are used to check
* parameter values at runtime.
*/
#ifndef MLPACK_CORE_UTIL_MLPACK_MAIN_HPP
#define MLPACK_CORE_UTIL_MLPACK_MAIN_HPP
#define BINDING_TYPE_CLI 0
#define BINDING_TYPE_TEST 1
#define BINDING_TYPE_PYX 2
#define BINDING_TYPE_UNKNOWN -1
#ifndef BINDING_TYPE
#define BINDING_TYPE BINDING_TYPE_UNKNOWN
#endif
#if (BINDING_TYPE == BINDING_TYPE_CLI) // This is a command-line executable.
#include <mlpack/bindings/cli/cli_option.hpp>
#include <mlpack/bindings/cli/print_doc_functions.hpp>
#define PRINT_PARAM_STRING mlpack::bindings::cli::ParamString
#define PRINT_PARAM_VALUE mlpack::bindings::cli::PrintValue
#define PRINT_CALL mlpack::bindings::cli::ProgramCall
#define PRINT_DATASET mlpack::bindings::cli::PrintDataset
#define PRINT_MODEL mlpack::bindings::cli::PrintModel
#define BINDING_IGNORE_CHECK mlpack::bindings::cli::IgnoreCheck
namespace mlpack {
namespace util {
template<typename T>
using Option = mlpack::bindings::cli::CLIOption<T>;
}
}
static const std::string testName = "";
#include <mlpack/core/util/param.hpp>
#include <mlpack/bindings/cli/parse_command_line.hpp>
#include <mlpack/bindings/cli/end_program.hpp>
static void mlpackMain(); // This is typically defined after this include.
int main(int argc, char** argv)
{
// Parse the command-line options; put them into CLI.
mlpack::bindings::cli::ParseCommandLine(argc, argv);
// Enable timing.
mlpack::Timer::EnableTiming();
// A "total_time" timer is run by default for each mlpack program.
mlpack::Timer::Start("total_time");
mlpackMain();
// Print output options, print verbose information, save model parameters,
// clean up, and so forth.
mlpack::bindings::cli::EndProgram();
}
#elif(BINDING_TYPE == BINDING_TYPE_TEST) // This is a unit test.
#include <mlpack/bindings/tests/test_option.hpp>
#include <mlpack/bindings/tests/ignore_check.hpp>
#include <mlpack/bindings/tests/clean_memory.hpp>
// These functions will do nothing.
#define PRINT_PARAM_STRING(A) std::string(" ")
#define PRINT_PARAM_VALUE(A, B) std::string(" ")
#define PRINT_DATASET(A) std::string(" ")
#define PRINT_MODEL(A) std::string(" ")
#define PRINT_CALL(...) std::string(" ")
#define BINDING_IGNORE_CHECK mlpack::bindings::tests::IgnoreCheck
namespace mlpack {
namespace util {
template<typename T>
using Option = mlpack::bindings::tests::TestOption<T>;
}
}
// testName symbol should be defined in each binding test file
#include <mlpack/core/util/param.hpp>
#undef PROGRAM_INFO
#define PROGRAM_INFO(NAME, DESC) static mlpack::util::ProgramDoc \
cli_programdoc_dummy_object = mlpack::util::ProgramDoc(NAME, \
[]() { return DESC; });
#elif(BINDING_TYPE == BINDING_TYPE_PYX) // This is a Python binding.
#include <mlpack/bindings/python/py_option.hpp>
#include <mlpack/bindings/python/print_doc_functions.hpp>
#define PRINT_PARAM_STRING mlpack::bindings::python::ParamString
#define PRINT_PARAM_VALUE mlpack::bindings::python::PrintValue
#define PRINT_DATASET mlpack::bindings::python::PrintDataset
#define PRINT_MODEL mlpack::bindings::python::PrintModel
#define PRINT_CALL mlpack::bindings::python::ProgramCall
#define BINDING_IGNORE_CHECK mlpack::bindings::python::IgnoreCheck
namespace mlpack {
namespace util {
template<typename T>
using Option = mlpack::bindings::python::PyOption<T>;
}
}
static const std::string testName = "";
#include <mlpack/core/util/param.hpp>
#undef PROGRAM_INFO
#define PROGRAM_INFO(NAME, DESC) static mlpack::util::ProgramDoc \
cli_programdoc_dummy_object = mlpack::util::ProgramDoc(NAME, \
[]() { return DESC; }); \
namespace mlpack { \
namespace bindings { \
namespace python { \
std::string programName = NAME; \
} \
} \
}
PARAM_FLAG("verbose", "Display informational messages and the full list of "
"parameters and timers at the end of execution.", "v");
PARAM_FLAG("copy_all_inputs", "If specified, all input parameters will be deep"
" copied before the method is run. This is useful for debugging problems "
"where the input parameters are being modified by the algorithm, but can "
"slow down the code.", "");
// Nothing else needs to be defined---the binding will use mlpackMain() as-is.
#else
#error "Unknown binding type! Be sure BINDING_TYPE is defined if you are " \
"including <mlpack/core/util/mlpack_main.hpp>.";
#endif
#include "param_checks.hpp"
#endif
| 31.591195 | 79 | 0.748955 | [
"model"
] |
36e086f01be1dc53ea22edbd43da683d5d49e57d | 4,605 | cpp | C++ | Game/src_lib/Tile/TileMap.cpp | andershub4/forestadventure | 5efb3f831a94d7ed3e45cee4ef7cf6b32f3e4157 | [
"MIT"
] | null | null | null | Game/src_lib/Tile/TileMap.cpp | andershub4/forestadventure | 5efb3f831a94d7ed3e45cee4ef7cf6b32f3e4157 | [
"MIT"
] | 9 | 2021-01-06T19:24:40.000Z | 2021-12-25T13:38:19.000Z | Game/src_lib/Tile/TileMap.cpp | andershub4/forestadventure | 5efb3f831a94d7ed3e45cee4ef7cf6b32f3e4157 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021 Anders Wennmo
* This file is part of forestadventure which is released under MIT license.
* See file LICENSE for full license details.
*/
#include "TileMap.h"
#include "Folder.h"
#include "Logging.h"
#include "Resource/TextureManager.h"
namespace FA {
namespace Tile {
TileMap::TileMap(TextureManager& textureManager, unsigned int scale)
: textureManager_(textureManager)
, scale_(scale)
{}
TileMap::~TileMap() = default;
void TileMap::Create(const TileMapData& tileMapData)
{
LOG_INFO("Create tile map");
tileMapData_ = tileMapData;
CreateTileSets();
CreateLayers();
CreateObjectGroups();
}
void TileMap::CreateTileSets()
{
for (const auto& tileSet : tileMapData_.tileSets_) {
TileMap::TileSet s;
s.firstGid_ = tileSet.firstGid_;
s.columns_ = tileSet.columns_;
s.tileSize_ = sf::Vector2u(tileSet.tileWidth_, tileSet.tileHeight_);
auto p = tileSet.textureFilePath_;
auto name = GetHead(p);
textureManager_.Add(name, p);
s.texture_ = textureManager_.Get(name);
tileSets_.push_back(s);
}
}
void TileMap::CreateLayers()
{
auto nCols = tileMapData_.mapProperties_.width_;
auto tileWidth = tileMapData_.mapProperties_.tileWidth_;
auto tileHeight = tileMapData_.mapProperties_.tileHeight_;
for (const auto& layer : tileMapData_.layers_) {
int inx = 0;
auto layerName = layer.name_;
for (auto it = layer.tileIds_.begin(); layer.tileIds_.end() != it; ++it, ++inx) {
auto tileId = *it;
if (tileId == 0) continue;
float x = static_cast<float>((inx % nCols) * tileWidth * scale_);
float y = static_cast<float>((inx / nCols) * tileHeight * scale_);
auto tileInfo = GetTileInfo(tileId);
if (tileInfo.texture_ != nullptr) {
sf::Sprite tile;
tile.setTexture(*tileInfo.texture_);
tile.setTextureRect(tileInfo.uvRect_);
tile.setPosition(x, y);
tile.setScale(static_cast<float>(scale_), static_cast<float>(scale_));
layers_[layerName].push_back(tile);
}
}
}
}
void TileMap::CreateObjectGroups()
{
for (const auto& group : tileMapData_.objectGroups_) {
auto groupName = group.name_;
std::vector<TileMap::ObjectData> objectDatas;
for (const auto& object : group.objects_) {
TileMap::ObjectData objectData;
objectData.position_ = {object.x_ * scale_, object.y_ * scale_};
objectData.type_ = ObjTypeStrToEnum(object.typeStr_);
objectData.faceDir_ = FaceDirStrToEnum(object.properties_.at("FaceDirection"));
objectDatas.push_back(objectData);
}
objectGroups_[groupName] = objectDatas;
}
}
const std::vector<sf::Sprite>& TileMap::GetLayer(const std::string& name)
{
return layers_.at(name);
}
const std::vector<TileMap::ObjectData> TileMap::GetObjectGroup(const std::string& name)
{
return objectGroups_.at(name);
}
sf::Vector2u TileMap::GetSize() const
{
auto nCols = tileMapData_.mapProperties_.width_;
auto nRows = tileMapData_.mapProperties_.height_;
auto tileWidth = tileMapData_.mapProperties_.tileWidth_;
auto tileHeight = tileMapData_.mapProperties_.tileHeight_;
return {nCols * tileWidth * scale_, nRows * tileHeight * scale_};
}
TileMap::TileInfo TileMap::GetTileInfo(int id)
{
auto it = tileSets_.begin();
id--;
auto texture = it->texture_;
auto column = id % it->columns_;
auto row = id / it->columns_;
auto u = column * it->tileSize_.x;
auto v = row * it->tileSize_.y;
sf::IntRect uvRect = sf::IntRect(u, v, it->tileSize_.x, it->tileSize_.y);
return {texture, uvRect};
}
EntityType TileMap::ObjTypeStrToEnum(const std::string& typeStr) const
{
auto result = EntityType::Unknown;
if (typeStr == "Mole") {
result = EntityType::Mole;
}
else if (typeStr == "Player") {
result = EntityType::Player;
}
return result;
}
FaceDirection TileMap::FaceDirStrToEnum(const std::string& faceDirStr) const
{
auto result = FaceDirection::Down;
if (faceDirStr == "Up") {
result = FaceDirection::Up;
}
else if (faceDirStr == "Down") {
result = FaceDirection::Down;
}
else if (faceDirStr == "Right") {
result = FaceDirection::Right;
}
else if (faceDirStr == "Left") {
result = FaceDirection::Left;
}
return result;
}
} // namespace Tile
} // namespace FA
| 28.079268 | 91 | 0.638871 | [
"object",
"vector"
] |
36e59eae772bfeb183ce8f935e221a07a741c675 | 3,452 | cc | C++ | spectator/registry.cc | dmuino/spectator-cpp | 0a0482b720a88699a58b0dd6367ab8f9760391a7 | [
"Apache-2.0"
] | null | null | null | spectator/registry.cc | dmuino/spectator-cpp | 0a0482b720a88699a58b0dd6367ab8f9760391a7 | [
"Apache-2.0"
] | null | null | null | spectator/registry.cc | dmuino/spectator-cpp | 0a0482b720a88699a58b0dd6367ab8f9760391a7 | [
"Apache-2.0"
] | null | null | null | #include <utility>
#include "logger.h"
#include "registry.h"
#include <fmt/ostream.h>
namespace spectator {
Registry::Registry(Config config) noexcept
: config_{std::move(config)}, publisher_(this) {}
const Config& Registry::GetConfig() const noexcept { return config_; }
IdPtr Registry::CreateId(std::string name, Tags tags) noexcept {
return std::make_shared<Id>(name, tags);
}
std::shared_ptr<Counter> Registry::GetCounter(IdPtr id) noexcept {
return create_and_register_as_needed<Counter>(std::move(id));
}
std::shared_ptr<Counter> Registry::GetCounter(std::string name) noexcept {
return GetCounter(CreateId(std::move(name), Tags{}));
}
std::shared_ptr<DistributionSummary> Registry::GetDistributionSummary(
IdPtr id) noexcept {
return create_and_register_as_needed<DistributionSummary>(std::move(id));
}
std::shared_ptr<DistributionSummary> Registry::GetDistributionSummary(
std::string name) noexcept {
return GetDistributionSummary(CreateId(std::move(name), Tags{}));
}
std::shared_ptr<Gauge> Registry::GetGauge(IdPtr id) noexcept {
return create_and_register_as_needed<Gauge>(std::move(id));
}
std::shared_ptr<Gauge> Registry::GetGauge(std::string name) noexcept {
return GetGauge(CreateId(std::move(name), Tags{}));
}
std::shared_ptr<MaxGauge> Registry::GetMaxGauge(IdPtr id) noexcept {
return create_and_register_as_needed<MaxGauge>(std::move(id));
}
std::shared_ptr<MaxGauge> Registry::GetMaxGauge(std::string name) noexcept {
return GetMaxGauge(CreateId(name, Tags{}));
}
std::shared_ptr<MonotonicCounter> Registry::GetMonotonicCounter(
IdPtr id) noexcept {
return create_and_register_as_needed<MonotonicCounter>(std::move(id));
}
std::shared_ptr<MonotonicCounter> Registry::GetMonotonicCounter(
std::string name) noexcept {
return GetMonotonicCounter(CreateId(std::move(name), Tags{}));
}
std::shared_ptr<Timer> Registry::GetTimer(IdPtr id) noexcept {
return create_and_register_as_needed<Timer>(std::move(id));
}
std::shared_ptr<Timer> Registry::GetTimer(std::string name) noexcept {
return GetTimer(CreateId(std::move(name), Tags{}));
}
// only insert if it doesn't exist, otherwise return the existing meter
std::shared_ptr<Meter> Registry::insert_if_needed(
std::shared_ptr<Meter> meter) noexcept {
std::lock_guard<std::mutex> lock(meters_mutex);
auto insert_result = meters_.emplace(meter->MeterId(), meter);
auto ret = insert_result.first->second;
return ret;
}
void Registry::log_type_error(const Id& id, MeterType prev_type,
MeterType attempted_type) const noexcept {
Logger()->error(
"Attempted to register meter {} as type {} but previously registered as "
"{}",
id, attempted_type, prev_type);
}
void Registry::Start() noexcept { publisher_.Start(); }
void Registry::Stop() noexcept { publisher_.Stop(); }
std::vector<Measurement> Registry::Measurements() const noexcept {
std::vector<Measurement> res;
std::lock_guard<std::mutex> lock{meters_mutex};
for (const auto& pair : meters_) {
auto ms = pair.second->Measure();
std::move(ms.begin(), ms.end(), std::back_inserter(res));
}
return res;
}
std::vector<std::shared_ptr<Meter>> Registry::Meters() const noexcept {
std::vector<std::shared_ptr<Meter>> res;
std::lock_guard<std::mutex> lock{meters_mutex};
for (const auto& pair : meters_) {
res.emplace_back(pair.second);
}
return res;
}
} // namespace spectator
| 31.099099 | 79 | 0.727404 | [
"vector"
] |
36e8a6738d48a61fa339b7e72f7202b0713800ae | 1,442 | hpp | C++ | src/libcvpg/imageproc/scripting/detail/compiler.hpp | franz-alt/cv-playground | d6c3bbdb500bf121c28299d117e459730b2b912d | [
"MIT"
] | null | null | null | src/libcvpg/imageproc/scripting/detail/compiler.hpp | franz-alt/cv-playground | d6c3bbdb500bf121c28299d117e459730b2b912d | [
"MIT"
] | null | null | null | src/libcvpg/imageproc/scripting/detail/compiler.hpp | franz-alt/cv-playground | d6c3bbdb500bf121c28299d117e459730b2b912d | [
"MIT"
] | null | null | null | // Copyright (c) 2020-2021 Franz Alt
// This code is licensed under MIT license (see LICENSE.txt for details).
#ifndef LIBCVPG_IMAGEPROC_SCRIPTING_DETAIL_COMPILER_HPP
#define LIBCVPG_IMAGEPROC_SCRIPTING_DETAIL_COMPILER_HPP
#include <cstdint>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <libcvpg/imageproc/scripting/algorithm_set.hpp>
#include <libcvpg/imageproc/scripting/detail/handler.hpp>
#include <libcvpg/imageproc/scripting/detail/parser.hpp>
namespace cvpg::imageproc::scripting::detail {
class sequence_node;
class compiler : public std::enable_shared_from_this<compiler>
{
public:
struct result
{
std::shared_ptr<sequence_node> flow;
std::unordered_map<std::uint32_t, handler> handlers;
};
compiler(algorithm_set algorithms);
result operator()();
void register_handler(std::uint32_t item_id, std::string name, handler h);
handler get_handler(std::uint32_t item_id) const;
parser::item get_item(std::uint32_t item_id) const;
std::shared_ptr<detail::parser> get_parser() const;
private:
std::shared_ptr<detail::parser> m_parser;
std::unordered_map<std::uint32_t, parser::item> m_items;
std::unordered_map<std::uint32_t, handler> m_handlers;
std::unordered_set<std::uint32_t> m_compiled;
};
} // namespace cvpg::imageproc::scripting::detail
#endif // LIBCVPG_IMAGEPROC_SCRIPTING_DETAIL_COMPILER_HPP
| 26.218182 | 78 | 0.755201 | [
"vector"
] |
36ed678abdeb827d707c4fecb60a22f09d549014 | 8,479 | cpp | C++ | JniOpenGL/app/src/main/cpp/stringsjnidemo.cpp | crescojeff/Android_Jni_OpenGL_Sample | 9eb0611d39df0be202d3e87b4c57622b01042442 | [
"MIT"
] | null | null | null | JniOpenGL/app/src/main/cpp/stringsjnidemo.cpp | crescojeff/Android_Jni_OpenGL_Sample | 9eb0611d39df0be202d3e87b4c57622b01042442 | [
"MIT"
] | null | null | null | JniOpenGL/app/src/main/cpp/stringsjnidemo.cpp | crescojeff/Android_Jni_OpenGL_Sample | 9eb0611d39df0be202d3e87b4c57622b01042442 | [
"MIT"
] | null | null | null | #include <jni.h>
#include <string>
#include <random>
#include <iostream>
#include <android/log.h>
/**
* These will be the first adjective, with a -ly added to modify the second adjective
*/
std::string adjective1Corpus[] = {
"Abaft",
"Abandoned",
"Abased",
"Abashed",
"Abasic",
"Abbatial",
"Abdicable",
"Abdicant",
"Abdicative",
"Abdominal",
"Abdominous",
"Abducent",
"Aberrant",
"Aberrational",
"Abeyant",
"Abhorrent",
"Abiotic",
"Ablaze",
"Able",
"Ablebodied",
"Ablutophobic",
"Abnormal",
"Abolitionary",
"Abominable",
"Aboriginal",
"Above",
"Aboveground",
"Abrupt",
"Absent",
"Absentminded",
"Absolute",
"Absolutistic",
"Abstract",
"Abstracted",
"Absurd",
"Abusive",
"Abysmal",
"Abyssal"
};
/**
* These will be the primary adjectives to modify the animal
*/
std::string adjective2Corpus[] = {
"Nyctophobic",
"Nylon",
"OAFISH",
"OBEDIENT",
"OBELISKOID",
"OBESE",
"OBJECTIVE",
"OBLIVIOUS",
"OBLONG",
"OBNOXIOUS",
"OBSCENE",
"OBSEQUIOUS",
"OBSERVANT",
"OBSESSIVE",
"OBSIDIAN",
"OBSOLETE",
"OBTUSE",
"OBVIOUS",
"OCCASIONAL",
"OCCUPATIONAL",
"OCEANGOING",
"OCEANIC",
"OCEANLIKE",
"OCEANOGRAPHIC",
"OCEANOGRAPHICAL",
"OCHRE",
"OCTAGONAL"
};
/**
* Animals to be described
*/
std::string animalCorpus[] = {
"maltesedog",
"mamba",
"mamenchisaurus",
"mammal",
"mammoth",
"manatee",
"mandrill",
"mangabey",
"manta",
"mantaray",
"mantid",
"mantis",
"mantisray",
"manxcat",
"mara",
"marabou",
"marbledmurrelet",
"mare",
"marlin",
"marmoset",
"marmot",
"marten",
"martin",
"massasauga",
"massospondylus",
"mastiff",
"mastodon",
"mayfly",
"meadowhawk",
"meadowlark",
"mealworm",
"meerkat",
"megalosaurus",
"megalotomusquinquespinosus",
"megaraptor",
"merganser",
"merlin",
"metalmarkbutterfly",
"metamorphosis",
"mice",
"microvenator",
"midge",
"milksnake",
"milkweedbug",
"millipede",
"minibeast",
"mink",
"minnow",
"mite",
"moa",
"mockingbird",
"mole",
"mollies",
"mollusk",
"molly",
"monarch",
"mongoose",
"mongrel"
};
std::string testStrings[] = {"hello","world"};
extern "C" JNIEXPORT jstring JNICALL
Java_com_jeffcreswell_jniopengl_jni_JniHooks_randomString(
JNIEnv *env,
jobject thiz) {
// random value from 0 to the size of our text corpi, which is calculated
// as the entire size of each array divided by the size of String object
//Will be used to obtain a seed for the random number engine
std::random_device rd;
// mersenne_twister_engine seeded with rd()
std::mt19937 randomIndexGenerator(rd());
// uniform distributions from 0 to array length-1 for each array
std::uniform_int_distribution<> randomAdj1IndexDistribution(0,
(sizeof(adjective1Corpus) / sizeof(std::string))-1);
std::uniform_int_distribution<> randomAdj2IndexDistribution(0,
(sizeof(adjective2Corpus) / sizeof(std::string))-1);
std::uniform_int_distribution<> randomAnimalIndexDistribution(0,
(sizeof(animalCorpus) / sizeof(std::string))-1);
// range of string count
std::uniform_int_distribution<> randomStringCountDistribution(1,3);
// generate a random index for each array
int adj1Index = randomAdj1IndexDistribution(randomIndexGenerator);
int adj2Index = randomAdj2IndexDistribution(randomIndexGenerator);
int animalIndex = randomAnimalIndexDistribution(randomIndexGenerator);
// choose randomly between 1 and 3 strings
int stringCount = randomStringCountDistribution(randomIndexGenerator);
// concat randomly selected strings into a random silly phrase
// that includes at least then noun and up to 2 adjectives.
// Naturally, the code doesn't work without the animal (or, at least,
// it shouldn't).
std::string animalWorthyOfWindyDescription;
if(stringCount == 3){
animalWorthyOfWindyDescription = adjective1Corpus[adj1Index] +
"ly " + adjective2Corpus[adj2Index] + " " +
animalCorpus[animalIndex];
}else if(stringCount == 2){
animalWorthyOfWindyDescription = adjective2Corpus[adj2Index] +
" " + animalCorpus[animalIndex];
}else{
animalWorthyOfWindyDescription = animalCorpus[animalIndex];
}
// native logcat API logging
__android_log_print(ANDROID_LOG_DEBUG, "jnigldemo", "JNI returning random adj: %s",
animalWorthyOfWindyDescription.c_str());
// return jstring of our result std::string to Java
return env->NewStringUTF(animalWorthyOfWindyDescription.c_str());
}
/*
extern "C" JNIEXPORT void JNICALL
Java_com_jeffcreswell_jniopengl_jni_JniHooks_testString(
JNIEnv *env,
jobject ) {
*/
// todox: whelp, apparently the NDK's hello world example crashes... good old JNI.
// Anyway, it looks like the workaround is to receive/create a jstring and then
// call env->GetStringUTFChars(jstr, 0) to get the modified UTF 8 encoded version as char*
// and then create a std::string over that char*. THEN we should be able do the NewStringUTF() shuffle.
// Alternatively, either receive the string from Java so we don't have to worry about encoding
// or create and return a jobject that is actually a java.land.String based on the actual string data
// we want to use. Even that requires GetStringUTFChars() over the encoding string, though, so
// there's not really a nice solution AFAICS
// UPDATE: it turns out my app was crashing over an attempt to access the as-yet unimplemented GlSurfaceView.
// The myriad NewStringUTF crash logs were presumably from other processes. I'm nervous about the whole
// expected input is modified UTF-8 thing now, though, so to be safe I may just go ahead with providing
// jstring array corpus arg with pre-javified strings and then do the interesting bits here.
// TODO: why were all those other crashes present, though? Were they all trying to use supplementary
// unicode chars (U+10000 and above)?
/* // crash over "JNI DETECTED ERROR IN APPLICATION: use of invalid jobject"?
std::string helloString = "hello strings from JNI";
jstring javifiedString = env->NewStringUTF(helloString.c_str());
const char* actualString = env->GetStringUTFChars(javifiedString,nullptr);
__android_log_print(ANDROID_LOG_DEBUG, "jnigldemo", "NewStringUTF successfully made java string: %s",
actualString);
env->ReleaseStringUTFChars(javifiedString,actualString);
*/
/*
// also explodes when we try NewStringUTF just to get the character encoding string
std::string helloString = "hello strings from JNI";
jbyteArray array = env->NewByteArray(helloString.size());
env->SetByteArrayRegion(array, 0, helloString.size(), (const jbyte*)helloString.c_str());
jstring strEncode = env->NewStringUTF("UTF-8");
jclass cls = env->FindClass("java/lang/String");
jmethodID ctor = env->GetMethodID(cls, "<init>", "([BLjava/lang/String;)V");
jstring object = (jstring) env->NewObject(cls, ctor, array, strEncode);
return object;
*/
/* // wheee! This works a treat. However, relying on system default charset seems less than ideal.
std::string helloString = "hello strings from JNI";
jbyteArray array = env->NewByteArray(helloString.size());
env->SetByteArrayRegion(array, 0, helloString.size(), (const jbyte*)helloString.c_str());
jclass cls = env->FindClass("java/lang/String");
jmethodID ctor = env->GetMethodID(cls, "<init>", "([B)V");
jstring object = (jstring) env->NewObject(cls, ctor, array);
return object;
*/
/*
}
*/
| 32.48659 | 113 | 0.619177 | [
"object"
] |
36f283385dd94ce681299e6a5c81538f143b3949 | 1,679 | cc | C++ | renderer/gl/utils.cc | rrobbyflya330/House3D | 258d155ba4d6c7399ed463de73bb1f1fae52979f | [
"Apache-2.0"
] | 1,163 | 2017-12-07T17:45:44.000Z | 2022-03-29T13:34:42.000Z | renderer/gl/utils.cc | rrobbyflya330/House3D | 258d155ba4d6c7399ed463de73bb1f1fae52979f | [
"Apache-2.0"
] | 55 | 2018-01-11T20:01:48.000Z | 2021-03-10T08:41:01.000Z | renderer/gl/utils.cc | harunpehlivan/House3D | dea99540cf8edde41820718863429c58d9189b3f | [
"Apache-2.0"
] | 181 | 2017-12-07T18:25:31.000Z | 2022-03-25T12:51:43.000Z | // Copyright 2017-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//File: utils.cc
#include "utils.hh"
#include "lib/debugutils.hh"
#include <vector>
namespace render {
bool tryEnableGLDebug() {
#ifdef DEBUG
#ifdef GL_KHR_debug
if (checkExtension("GL_ARB_debug_output")) {
glEnable(GL_DEBUG_OUTPUT);
return true;
}
#else
print_debug("KHR_debug extension unavailable!");
#endif
#endif
return false;
}
void printGLDebugMsg(GLuint num) {
#ifdef GL_KHR_debug
GLint maxMsgLen = 0;
glGetIntegerv(GL_MAX_DEBUG_MESSAGE_LENGTH, &maxMsgLen);
std::vector<GLchar> msgData(num * maxMsgLen);
std::vector<GLenum> sources(num);
std::vector<GLenum> types(num);
std::vector<GLenum> severities(num);
std::vector<GLuint> ids(num);
std::vector<GLsizei> lengths(num);
GLuint num_fetched = glGetDebugMessageLog(num,
msgData.size(),
&sources[0], &types[0],
&ids[0], &severities[0],
&lengths[0], &msgData[0]);
lengths.resize(num_fetched);
GLchar* currPos = msgData.data();
for(auto& l : lengths) {
print_debug("%s\n", std::string(currPos, currPos + l - 1).c_str());
currPos = currPos + l;
}
#else
print_debug("KHR_debug extension unavailable!");
#endif
}
bool checkExtension(const std::string& ext) {
GLint n;
glGetIntegerv(GL_NUM_EXTENSIONS, &n);
for (int i = 0; i < n; ++i) {
const GLubyte* s = glGetStringi(GL_EXTENSIONS, i);
std::string sname{reinterpret_cast<const char*>(s)};
if (ext.compare(sname) == 0)
return true;
}
return false;
}
} // namespace render
| 23.319444 | 71 | 0.681954 | [
"render",
"vector"
] |
36f4809dbd788a5582f6495b851ea5d13ee0aa3d | 47,794 | cpp | C++ | groups/bsl/bslstl/bslstl_treenodepool.t.cpp | zhanzju/bsl | 1bb79982cff9bbaa3fb6d038604f04283ba76f07 | [
"MIT"
] | 1 | 2015-11-06T05:25:03.000Z | 2015-11-06T05:25:03.000Z | groups/bsl/bslstl/bslstl_treenodepool.t.cpp | zhanzju/bsl | 1bb79982cff9bbaa3fb6d038604f04283ba76f07 | [
"MIT"
] | null | null | null | groups/bsl/bslstl/bslstl_treenodepool.t.cpp | zhanzju/bsl | 1bb79982cff9bbaa3fb6d038604f04283ba76f07 | [
"MIT"
] | null | null | null | // bslstl_treenodepool.t.cpp -*-C++-*-
#include <bslstl_treenodepool.h>
#include <bslstl_allocator.h>
#include <bslalg_rbtreenode.h>
#include <bslalg_rbtreeanchor.h>
#include <bslalg_rbtreeutil.h>
#include <bslma_allocator.h>
#include <bslma_testallocator.h>
#include <bslma_testallocatormonitor.h>
#include <bslma_defaultallocatorguard.h>
#include <bslma_default.h>
#include <bsls_assert.h>
#include <bsls_asserttest.h>
#include <bsls_bsltestutil.h>
#include <bsltf_templatetestfacility.h>
#include <bsltf_stdtestallocator.h>
#include <bsltf_testvaluesarray.h>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
using namespace BloombergLP;
using namespace std;
using namespace bslstl;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
//
// Global Concerns:
//: o Pointer/reference parameters are declared 'const'.
//: o No memory is ever allocated.
//: o Precondition violations are detected in appropriate build modes.
//-----------------------------------------------------------------------------
// CREATORS
// [ 2] explicit TreeNodePool(const ALLOCATOR& allocator);
//
// MANIPULATORS
// [ 4] AllocatorType& allocator();
// [ 2] bslalg::RbTreeNode *createNode();
// [ 7] bslalg::RbTreeNode *createNode(const bslalg::RbTreeNode& original);
// [ 7] bslalg::RbTreeNode *createNode(const VALUE& value);
// [ 5] void deleteNode(bslalg::RbTreeNode *node);
// [ 6] void reserveNodes(std::size_t numNodes);
// [ 8] void swap(TreeNodePool<VALUE, ALLOCATOR>& other);
//
// ACCESSORS
// [ 4] const AllocatorType& allocator() const;
// ----------------------------------------------------------------------------
// [ 1] BREATHING TEST
//-----------------------------------------------------------------------------
//=============================================================================
//=============================================================================
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;
namespace {
void aSsErT(bool b, const char *s, int i) {
if (b) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
} // close unnamed namespace
//=============================================================================
// STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
// ============================================================================
// GLOBAL TEST VALUES
// ----------------------------------------------------------------------------
static bool verbose;
static bool veryVerbose;
static bool veryVeryVerbose;
static bool veryVeryVeryVerbose;
//=============================================================================
// GLOBAL HELPER FUNCTIONS FOR TESTING
//-----------------------------------------------------------------------------
typedef bslalg::RbTreeNode RbNode;
namespace {
bool expectToAllocate(int n)
// Return 'true' if the container is expected to allocate memory on the
// specified 'n'th element, and 'false' otherwise.
{
if (n > 32) {
return (0 == n % 32); // RETURN
}
return (((n - 1) & n) == 0); // Allocate when 'n' is a power of 2
}
} // close unnamed namespace
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
class AllocatingIntType {
// DATA
bslma::Allocator *d_allocator_p;
int *d_value_p;
private:
// NOT IMPLEMENTED
AllocatingIntType(const AllocatingIntType&);
public:
// CREATORS
AllocatingIntType(bslma::Allocator *allocator)
: d_allocator_p(bslma::Default::allocator(allocator))
{
d_value_p = static_cast<int *>(d_allocator_p->allocate(sizeof(int)));
*d_value_p = 0xabcd;
}
AllocatingIntType(const AllocatingIntType& original,
bslma::Allocator *allocator)
: d_allocator_p(bslma::Default::allocator(allocator))
{
d_value_p = static_cast<int *>(d_allocator_p->allocate(sizeof(int)));
*d_value_p = *original.d_value_p;
}
~AllocatingIntType()
{
BSLS_ASSERT(0 != d_value_p);
d_allocator_p->deleteObject(d_value_p);
}
int& value() { return *d_value_p; }
const int& value() const { return *d_value_p; }
};
namespace BloombergLP {
namespace bslma {
template <>
struct UsesBslmaAllocator<AllocatingIntType> : bsl::true_type {};
}
}
//=============================================================================
// TEST FACILITIES
//-----------------------------------------------------------------------------
class Stack
{
enum { CAPACITY = 128 };
RbNode *d_data[CAPACITY];
int d_size;
public:
// CREATORS
Stack() : d_size(0) {}
Stack(const Stack& original)
{
d_size = original.d_size;
memcpy(d_data, original.d_data, d_size * sizeof(*d_data));
}
// MANIPULATORS
void push(RbNode *value)
{
BSLS_ASSERT(CAPACITY != d_size);
d_data[d_size] = value;
++d_size;
}
void pop()
{
BSLS_ASSERT(0 != d_size);
--d_size;
}
// ACCESSORS
bool empty() { return 0 == d_size; }
int size() { return d_size; }
RbNode *back()
{
BSLS_ASSERT(0 != d_size);
return d_data[d_size - 1];
}
RbNode *operator[](size_t index)
{
return d_data[index];
}
};
template <class VALUE>
class TestDriver {
// This templatized struct provide a namespace for testing the 'map'
// container. The parameterized 'VALUE' specifies the value type for this
// object. Each "testCase*" method test a specific aspect of
// 'SimplePool<VALUE>'. Every test cases should be invoked with various
// parameterized type to fully test the container.
private:
// TYPES
typedef bslstl::TreeNodePool<VALUE, bsl::allocator<VALUE> > Obj;
// Type under testing.
typedef bsltf::StdTestAllocator<VALUE> StlAlloc;
typedef bslstl::TreeNode<VALUE> ValueNode;
private:
// PRIVATE CLASS METHODS
static
const Obj& init(Obj *result,
Stack *usedBlocks,
Stack *freeBlocks,
int numAllocs,
int numDealloc);
static
void createFreeBlocks(Obj *result, Stack *usedBlocks, int numBlocks);
public:
// TEST CASES
// static void testCase10();
// Reserved for BSLX.
static void testCase9();
// Test usage example.
static void testCase8();
// Test 'swap' member.
static void testCase7();
// Test 'release'.
static void testCase6();
// Test 'reserve'.
static void testCase5();
// Test 'deallocate'.
static void testCase4();
// Test basic accessors ('allocator').
static void testCase3();
// Test generator functions 'ggg', and 'gg'.
static void testCase2();
// Test primary manipulators.
};
template <class VALUE>
const bslstl::TreeNodePool<VALUE, bsl::allocator<VALUE> >&
TestDriver<VALUE>::init(Obj *result,
Stack *usedBlocks,
Stack *freeBlocks,
int numAllocs,
int numDealloc)
{
BSLS_ASSERT(result);
BSLS_ASSERT(usedBlocks);
BSLS_ASSERT(freeBlocks);
BSLS_ASSERT(numDealloc <= numAllocs);
for (int i = 0; i < numAllocs; ++i) {
RbNode *ptr = result->createNode();
usedBlocks->push(ptr);
}
for (int i = 0; i < numDealloc; ++i) {
RbNode *ptr = usedBlocks->back();
result->deleteNode(ptr);
freeBlocks->push(ptr);
usedBlocks->pop();
}
return *result;
}
template <class VALUE>
void TestDriver<VALUE>::createFreeBlocks(Obj *result,
Stack *usedBlocks,
int numBlocks)
{
// Allocate blocks.
for (int i = 0; i < numBlocks; ++i) {
RbNode *ptr = result->createNode();
usedBlocks->push(ptr);
}
// Use up all the free blocks.
while (!expectToAllocate(usedBlocks->size() + 1)) {
RbNode *ptr = result->createNode();
usedBlocks->push(ptr);
}
// Free up the necessary number of blocks.
for (int i = 0; i < numBlocks; ++i) {
result->deleteNode(usedBlocks->back());
usedBlocks->pop();
}
}
template<class VALUE>
void TestDriver<VALUE>::testCase8()
{
// --------------------------------------------------------------------
// MANIPULATOR 'swap'
//
// Concerns:
//: 1 'swap' exchange the free list and chunk list of the objects.
//:
//: 2 The common object allocator address held by both objects is
//: unchanged.
//:
//: 3 No memory is allocated from any allocator.
//:
//: 4 Swapping an object with itself does not affect the value of the
//: object (alias-safety).
//:
//: 5 Memory is deallocated on the destruction of the object.
//:
//: 6 QoI: Asserted precondition violations are detected when enabled.
//
// Plan:
//: 1 Using a table-based approach:
//:
//: 1 Create two objects of which memory has been allocated and
//: deallocated various number of times.
//:
//: 2 Swap the two objects, verify allocator is not changed. (C-2)
//:
//: 3 Verify no memory is allocated (C-3)
//:
//: 4 Verify the free list of the objects have been swapped by calling
//: 'allocate and checking the address of the allocated memory blocks.
//:
//: 5 Delete one of the objects and verify the memory of the other have
//: not been deallocated. (C-1, 5)
//:
//: 6 Swap an object with itself and verify the object is unchanged.
//: (C-4)
//:
//: 2 Verify that, in appropriate build modes, defensive checks are
//: triggered (using the 'BSLS_ASSERTTEST_*' macros). (C-6)
//
// Testing:
// void swap(TreeNodePool<VALUE, ALLOCATOR>& other);
// --------------------------------------------------------------------
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
struct {
int d_line;
int d_numAlloc;
int d_numDealloc;
} DATA[] = {
//LINE ALLOC DEALLOC
//---- ----- -------
{ L_, 0, 0 },
{ L_, 1, 0 },
{ L_, 1, 1 },
{ L_, 2, 0 },
{ L_, 2, 1 },
{ L_, 2, 2 },
{ L_, 3, 0 },
{ L_, 3, 1 },
{ L_, 3, 2 },
{ L_, 3, 3 },
{ L_, 4, 0 },
{ L_, 4, 1 },
{ L_, 4, 2 },
{ L_, 4, 3 },
{ L_, 4, 4 }
};
int NUM_DATA = sizeof DATA / sizeof *DATA;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE1 = DATA[ti].d_line;
const int ALLOCS1 = DATA[ti].d_numAlloc;
const int DEALLOCS1 = DATA[ti].d_numDealloc;
for (int tj = 0; tj < NUM_DATA; ++tj) {
const int LINE2 = DATA[tj].d_line;
const int ALLOCS2 = DATA[tj].d_numAlloc;
const int DEALLOCS2 = DATA[tj].d_numDealloc;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
Stack usedX;
Stack freeX;
Obj mX(&oa);
const Obj& X = init(&mX, &usedX, &freeX, ALLOCS1, DEALLOCS1);
Stack usedY;
Stack freeY;
{
Obj mY(&oa);
const Obj& Y = init(&mY, &usedY, &freeY, ALLOCS2, DEALLOCS2);
if (veryVerbose) { T_ P_(LINE1) P(LINE2) }
bslma::TestAllocatorMonitor oam(&oa);
mX.swap(mY);
ASSERTV(LINE1, LINE2, &oa == X.allocator());
ASSERTV(LINE1, LINE2, &oa == Y.allocator());
ASSERTV(LINE1, LINE2, oam.isTotalSame());
ASSERTV(LINE1, LINE2, oam.isInUseSame());
// Verify the free lists are swapped
while(!freeX.empty()) {
RbNode *ptr = mY.createNode();
ASSERTV(LINE1, LINE2, freeX.back() == ptr);
freeX.pop();
usedX.push(ptr);
}
while(!freeY.empty()) {
RbNode *ptr = mX.createNode();
ASSERTV(LINE1, LINE2, freeY.back() == ptr);
freeY.pop();
usedY.push(ptr);
}
// Cleanup up memory used by the object in the node.
while(!usedX.empty()) {
mX.deleteNode(usedX.back());
usedX.pop();
}
}
// 'Y' is now destroyed, its blocks should be deallocated. Verify
// Blocks in 'X' (which used to be in 'Y' before the swap) is not
// deallocated.
char SCRIBBLED_MEMORY[sizeof(VALUE)];
memset(SCRIBBLED_MEMORY, 0xA5, sizeof(VALUE));
while (!usedY.empty()) {
RbNode *ptr = usedY.back();
ASSERTV(0 != strncmp((char *)ptr,
SCRIBBLED_MEMORY,
sizeof(VALUE)));
mX.deleteNode(ptr);
usedY.pop();
}
}
}
// Verify no memory is allocated from the default allocator.
ASSERTV(da.numBlocksTotal(), 0 == da.numBlocksTotal());
if (verbose) printf("\nNegative Testing.\n");
{
bsls::AssertFailureHandlerGuard hG(bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\t'swap' member function\n");
{
bslma::TestAllocator oa1("object1", veryVeryVeryVerbose);
bslma::TestAllocator oa2("object2", veryVeryVeryVerbose);
Obj mA(&oa1); Obj mB(&oa1);
Obj mZ(&oa2);
ASSERT_SAFE_PASS(mA.swap(mB));
ASSERT_SAFE_FAIL(mA.swap(mZ));
}
}
}
template<class VALUE>
void TestDriver<VALUE>::testCase7()
{
// -----------------------------------------------------------------------
// MANIPULATOR 'createNode'
//
// Concerns:
//: 1 'createNode' invokes the copy constructor of the parameterized 'TYPE'
//:
//: 2 Any memory allocation is from the object allocator.
//:
//: 3 There is no temporary allocation from any allocator.
//:
//: 4 Every object releases any allocated memory at destruction.
//
// Plan:
//: 1 Create an array of distinct object. For each object in the array:
//:
//: 1 Invoke 'createNode' on the object.
//:
//: 2 Verify memory is allocated only when expected. (C-2..3)
//:
//: 3 Verify the new node contains a copy of the object.
//:
//: 2 Create another 'TreeNodePool'.
//:
//: 3 For each node that was created:
//:
//: 1 Invoke 'createNode' on the node that was created previously
//:
//: 2 Verify the newly created node has the same value as the old one.
//: (C-1)
//:
//: 4 Verify all memory is released on destruction. (C-4)
//
// Testing:
// bslalg::RbTreeNode *createNode(const bslalg::RbTreeNode& original);
// bslalg::RbTreeNode *createNode(const VALUE& value);
// -----------------------------------------------------------------------
if (verbose) printf("\nMANIPULATOR 'createNode'"
"\n========================\n");
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<
VALUE>::value;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
{
bsltf::TestValuesArray<VALUE> VALUES;
Obj mX(&oa);
Stack usedX;
for (int i = 0; i < 16; ++i) {
bslma::TestAllocatorMonitor oam(&oa);
RbNode *ptr = mX.createNode(VALUES[i]);
if (expectToAllocate(i + 1)) {
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksInUseChange());
}
else {
ASSERTV(TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(TYPE_ALLOC == oam.numBlocksInUseChange());
}
usedX.push(ptr);
ValueNode *node = static_cast<ValueNode *>(ptr);
ASSERTV(i, VALUES[i] == node->value());
}
Obj mY(&oa);
Stack usedY;
for (int i = 0; i < 16; ++i) {
bslma::TestAllocatorMonitor oam(&oa);
RbNode *ptr = mY.createNode(*usedX[i]);
if (expectToAllocate(i + 1)) {
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksInUseChange());
}
else {
ASSERTV(TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(TYPE_ALLOC == oam.numBlocksInUseChange());
}
usedY.push(ptr);
ValueNode *nodeY = static_cast<ValueNode *>(ptr);
ASSERTV(i, VALUES[i] == nodeY->value());
ValueNode *nodeX = static_cast<ValueNode *>(ptr);
ASSERTV(i, nodeX->value() == nodeY->value());
}
while(!usedX.empty()) {
mX.deleteNode(usedX.back());
usedX.pop();
}
while(!usedY.empty()) {
mY.deleteNode(usedY.back());
usedY.pop();
}
}
// Verify all memory is released on object destruction.
ASSERTV(oa.numBlocksInUse(), 0 == oa.numBlocksInUse());
}
template<class VALUE>
void TestDriver<VALUE>::testCase6()
{
// --------------------------------------------------------------------
// MANIPULATOR 'reserveNodes'
//
// Concerns:
//: 1 'reserve' allocate exactly the specified number of blocks such that
//: subsequent 'allocate' does not get memory from the heap.
//:
//: 2 Free blocks that was allocated before 'reserve' is not destroyed.
//:
//: 3 All memory allocation comes from the object allocator.
//:
//: 4 Memory is deallocated on the destruction of the object.
//:
//: 5 QoI: Asserted precondition violations are detected when enabled.
//
// Plan:
//: 1 For each different values of i from 1 to 7:
//:
//: 1 For each different values of j from 0 to 7:
//:
//: 1 Create 'j' memory blocks in the free list.
//:
//: 2 Call 'reserveNode' for 'i' blocks.
//:
//: 3 Invoke 'createNode' 'i + j' times, and verify no memory is
//: allocated.
//:
//: 4 Invoke 'createNode' again and verify memory is allocated from the
//: heap. (C-1..3)
//:
//: 2 Verify all memory is deallocated on destruction. (C-4)
//:
//: 3 Verify that, in appropriate build modes, defensive checks are
//: triggered (using the 'BSLS_ASSERTTEST_*' macros). (C-5)
//
// Testing:
// void reserveNodes(std::size_t numNodes);
// --------------------------------------------------------------------
if (verbose) printf("\nMANIPULATOR 'reserve'"
"\n======================\n");
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<
VALUE>::value;
for (int ti = 1; ti < 8; ++ti) {
for(int tj = 0; tj < 8; ++tj) {
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj mX(&oa);
Stack usedBlocks;
createFreeBlocks(&mX, &usedBlocks, tj);
mX.reserveNodes(ti);
for (int tk = 0; tk < ti + tj; ++tk) {
bslma::TestAllocatorMonitor oam(&oa);
usedBlocks.push(mX.createNode());
ASSERTV(ti, tj, tk, TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(ti, tj, tk, TYPE_ALLOC == oam.numBlocksInUseChange());
}
{
bslma::TestAllocatorMonitor oam(&oa);
usedBlocks.push(mX.createNode());
ASSERTV(ti, tj, 1 + TYPE_ALLOC == oam.numBlocksInUseChange());
}
while(!usedBlocks.empty()) {
mX.deleteNode(usedBlocks.back());
usedBlocks.pop();
}
}
}
if (verbose) printf("\nNegative Testing.\n");
{
bsls::AssertFailureHandlerGuard hG(bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\t'reserve'\n");
{
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
Obj mX(&oa);
ASSERT_SAFE_FAIL(mX.reserveNodes(0));
ASSERT_SAFE_PASS(mX.reserveNodes(1));
}
}
}
template<class VALUE>
void TestDriver<VALUE>::testCase5()
{
// --------------------------------------------------------------------
// MANIPULATOR 'deleteNode'
//
// Concerns:
//: 1 'deleteNode' invokes the destructor of the value in the node.
//:
//: 2 'createNode' does not allocate from the heap when there are still
//: blocks in the free list.
//:
//: 3 'createNode' retrieve the last block that was deallocated.
//:
//: 4 'allocate' will retrieve memory from the heap once so that the next
//: allocation will not allocate from the heap.
//:
//: 5 'deleteNode' does not allocate or release any memory other than those
//: caused by the destructor of the value.
//:
//: 6 QoI: Asserted precondition violations are detected when enabled.
//
// Plan:
//: 1 Create a list of sequences to allocate and deallocate memory. For
//: each sequence:
//:
//: 1 Invoke 'createNode' and 'deleteNode' according to the sequence.
//:
//: 2 Verify that each allocate returns the last block that was
//: deallocated if 'deleteNode' was called. (C-1..3)
//:
//: 3 Verify no memory was allocated from the heap on 'deleteNode'.
//: (C-5)
//:
//: 4 Verify 'createNode' will get memory from the heap only when
//: expected.
//:
//: 2 Verify that, in appropriate build modes, defensive checks are
//: triggered (using the 'BSLS_ASSERTTEST_*' macros). (C-6)
// --------------------------------------------------------------------
if (verbose) printf("\nMANIPULATOR 'deleteNode'"
"\n========================");
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<
VALUE>::value;
struct {
int d_line;
const char *d_sequence;
} DATA[] = {
//LINE SEQUENCE
//---- --------
{ L_, "ADA" },
{ L_, "AADDAA" },
{ L_, "ADADA" },
{ L_, "ADAADDAAA" },
{ L_, "AAADDDAAA" },
{ L_, "AADADA" }
};
int NUM_DATA = sizeof DATA / sizeof *DATA;
for (int ti = 0; ti < NUM_DATA; ++ti) {
const int LINE = DATA[ti].d_line;
const char *const SEQUENCE = DATA[ti].d_sequence;
const int LENGTH = strlen(SEQUENCE);
Stack usedBlocks;
Stack freeBlocks;
bslma::TestAllocator oa("object", veryVeryVeryVerbose);
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj mX(&oa);
for (int tj = 0; tj < LENGTH; ++tj) {
bslma::TestAllocatorMonitor oam(&oa);
if (SEQUENCE[tj] == 'A') {
RbNode *ptr = mX.createNode();
usedBlocks.push(ptr);
if (!freeBlocks.empty()) {
ASSERTV(LINE, tj, freeBlocks.back() == ptr);
freeBlocks.pop();
}
else {
if (expectToAllocate(usedBlocks.size())) {
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksInUseChange());
}
else {
ASSERTV(TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(TYPE_ALLOC == oam.numBlocksInUseChange());
}
}
}
else {
ASSERTV(LINE, !usedBlocks.empty());
RbNode *ptr = usedBlocks.back();
mX.deleteNode(ptr);
freeBlocks.push(ptr);
usedBlocks.pop();
ASSERTV(LINE, tj, oam.isTotalSame());
ASSERTV(LINE, tj,
-TYPE_ALLOC == oam.numBlocksInUseChange());
}
}
ASSERTV(LINE, 0 == da.numBlocksTotal());
// Cleanup up memory used by the object in the node.
while(!usedBlocks.empty()) {
mX.deleteNode(usedBlocks.back());
usedBlocks.pop();
}
}
if (verbose) printf("\nNegative Testing.\n");
{
bsls::AssertFailureHandlerGuard hG(bsls::AssertTest::failTestDriver);
if (veryVerbose) printf("\t'allocate' member function\n");
{
Obj mX(0);
RbNode *ptr = mX.createNode();
ASSERT_SAFE_FAIL(mX.deleteNode(0));
ASSERT_SAFE_PASS(mX.deleteNode(ptr));
}
}
}
template<class VALUE>
void TestDriver<VALUE>::testCase4()
{
// ------------------------------------------------------------------------
// BASIC ACCESSORS
//
// Concerns:
//: 1 'allocator' returns the allocator that was supplied on construction.
//:
//: 2 The accessor is declared 'const'.
//:
//: 3 The accessor does not allocate any memory from any allocator.
//
// Plan:
//: 1 For each allocator configuration:
//:
//: 1 Create a 'bslstl_TreeNodePool' with an allocator.
//:
//: 2 Use the basic accessor to verify the allocator is installed
//: properly. (C-1..2)
//:
//: 3 Verify no memory is allocated from any allocator. (C-3)
//
// Testing:
// AllocatorType& allocator();
// ------------------------------------------------------------------------
for (char cfg = 'a'; cfg <= 'c'; ++cfg) {
const char CONFIG = cfg;
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa1("supplied1", veryVeryVeryVerbose);
bslma::TestAllocator sa2("supplied2", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj(0);
objAllocatorPtr = &da;
} break;
case 'b': {
objPtr = new (fa) Obj(&sa1);
objAllocatorPtr = &sa1;
} break;
case 'c': {
objPtr = new (fa) Obj(&sa2);
objAllocatorPtr = &sa2;
} break;
default: {
ASSERTV(CONFIG, !"Bad allocator config.");
return;
} break;
}
Obj& mX = *objPtr; const Obj& X = mX;
bslma::TestAllocator& oa = *objAllocatorPtr;
// --------------------------------------------------------
// Verify basic accessor
bslma::TestAllocatorMonitor oam(&oa);
ASSERTV(CONFIG, &oa == X.allocator());
ASSERT(oam.isTotalSame());
// --------------------------------------------------------
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
ASSERTV(CONFIG, da.numBlocksInUse(), 0 == da.numBlocksInUse());
ASSERTV(CONFIG, fa.numBlocksInUse(), 0 == fa.numBlocksInUse());
ASSERTV(CONFIG, sa1.numBlocksInUse(), 0 == sa1.numBlocksInUse());
ASSERTV(CONFIG, sa2.numBlocksInUse(), 0 == sa2.numBlocksInUse());
}
}
template<class VALUE>
void TestDriver<VALUE>::testCase3()
{
// ------------------------------------------------------------------------
// RESERVED FOR TEST APPARATUS TESTING
// ------------------------------------------------------------------------
}
template<class VALUE>
void TestDriver<VALUE>::testCase2()
{
// --------------------------------------------------------------------
// CTOR, PRIMARY MANIPULATORS, & DTOR
// Ensure that we can use the default constructor to create an
// object (having the default-constructed value), use the primary
// manipulators to put that object into any state relevant for
// thorough testing, and use the destructor to destroy it safely.
//
// Concerns:
//: 1 An object created with the constructor has the specified
//: allocator.
//:
//: 2 Any memory allocation is from the object allocator.
//:
//: 3 There is no temporary allocation from any allocator.
//:
//: 4 Every object releases any allocated memory at destruction.
//:
//: 5 Allocation starts at one block, up to a maximum of 32 blocks.
//:
//: 6 Constructor allocates no memory.
//:
//: 7 Any memory allocation is exception neutral.
//
// Plan:
//: 1 For each allocator configuration:
//:
//: 1 Create a pool object and verify no memory is allocated. (C-1, 8)
//:
//: 2 Call 'allocate' 96 times in the presence of exception, for each
//: time:
//:
//: 1 Verify memory is only allocated from object allocator and only
//: when expected. (C-2..3, 6, 9)
//:
//: 2 If memory is not allocated, the address is the max of
//: 'sizeof(VALUE)' and 'sizeof(void *) larger than the previous
//: address. (C-7)
//:
//: 3 Delete the object and verify all memory is deallocated. (C-4)
//
// Testing:
// explicit TreeNodePool(const ALLOCATOR& allocator);
// ~TreeNodePool();
// VALUE *createNode();
// --------------------------------------------------------------------
if (verbose) printf(
"\nDEFAULT CTOR, PRIMARY MANIPULATORS, & DTOR"
"\n==========================================\n");
if (verbose) printf("\nTesting with various allocator configurations.\n");
const int TYPE_ALLOC = bslma::UsesBslmaAllocator<VALUE>::value;
for (char cfg = 'a'; cfg <= 'b'; ++cfg) {
const char CONFIG = cfg; // how we specify the allocator
bslma::TestAllocator da("default", veryVeryVeryVerbose);
bslma::TestAllocator fa("footprint", veryVeryVeryVerbose);
bslma::TestAllocator sa("supplied", veryVeryVeryVerbose);
bslma::DefaultAllocatorGuard dag(&da);
Obj *objPtr;
bslma::TestAllocator *objAllocatorPtr;
switch (CONFIG) {
case 'a': {
objPtr = new (fa) Obj(0);
objAllocatorPtr = &da;
} break;
case 'b': {
objPtr = new (fa) Obj(&sa);
objAllocatorPtr = &sa;
} break;
default: {
ASSERTV(CONFIG, !"Bad allocator config.");
return;
} break;
}
Obj& mX = *objPtr; const Obj& X = mX;
bslma::TestAllocator& oa = *objAllocatorPtr;
bslma::TestAllocator& noa = 'b' != CONFIG ? sa : da;
// ---------------------------------------
// Verify allocator is installed properly.
// ---------------------------------------
ASSERTV(CONFIG, &oa == X.allocator());
// Verify no allocation from the object/non-object allocators.
ASSERTV(CONFIG, oa.numBlocksTotal(), 0 == oa.numBlocksTotal());
ASSERTV(CONFIG, noa.numBlocksTotal(), 0 == noa.numBlocksTotal());
Stack usedBlocks;
for (int i = 0; i < 96; ++i) {
bslma::TestAllocatorMonitor oam(&oa);
RbNode *ptr = mX.createNode();
if (expectToAllocate(i + 1)) {
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(1 + TYPE_ALLOC == oam.numBlocksInUseChange());
}
else {
ASSERTV(TYPE_ALLOC == oam.numBlocksTotalChange());
ASSERTV(TYPE_ALLOC == oam.numBlocksInUseChange());
}
usedBlocks.push(ptr);
}
// Verify no temporary memory is allocated from the object
// allocator.
ASSERTV(CONFIG, oa.numBlocksTotal(), oa.numBlocksInUse(),
oa.numBlocksTotal() == oa.numBlocksInUse());
// Free up used blocks.
for (int i = 0; i < 96; ++i) {
bslma::TestAllocatorMonitor oam(&oa);
mX.deleteNode(usedBlocks.back());
ASSERTV(-TYPE_ALLOC == oam.numBlocksInUseChange());
usedBlocks.pop();
}
// Reclaim dynamically allocated object under test.
fa.deleteObject(objPtr);
// Verify all memory is released on object destruction.
ASSERTV(fa.numBlocksInUse(), 0 == fa.numBlocksInUse());
ASSERTV(oa.numBlocksInUse(), 0 == oa.numBlocksInUse());
ASSERTV(noa.numBlocksTotal(), 0 == noa.numBlocksTotal());
}
}
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Creating a 'IntSet' Container
/// - - - - - - - - - - - - - - - - - - - -
// This example demonstrates how to create a container type, 'IntSet' using
// 'bslalg::RbTreeUtil'.
//
// First, we define a comparison functor for comparing a
// 'bslstl::RbTreeNode<int>' object and an 'int' value. This functor conforms
// to the requirements of 'bslalg::RbTreeUtil':
//..
struct IntNodeComparator {
// This class defines a comparator providing comparison operations
// between 'bslstl::TreeNode<int>' objects, and 'int' values.
//
private:
// PRIVATE TYPES
typedef bslstl::TreeNode<int> Node;
// Alias for a node type containing an 'int' value.
//
public:
// CLASS METHODS
bool operator()(const bslalg::RbTreeNode& lhs, int rhs) const
{
return static_cast<const Node&>(lhs).value() < rhs;
}
//
bool operator()(int lhs, const bslalg::RbTreeNode& rhs) const
{
return lhs < static_cast<const Node&>(rhs).value();
}
};
//..
// Then, we define the public interface of 'IntSet'. Note that it contains a
// 'TreeNodePool' that will be used by 'bslalg::RbTreeUtil' as a 'FACTORY' to
// create and delete nodes. Also note that a number of simplifications have
// been made for the purpose of illustration. For example, this implementation
// provides only a minimal set of critical operations, and it does not use the
// empty base-class optimization for the comparator.
//..
template <class ALLOCATOR = bsl::allocator<int> >
class IntSet {
// // This class implements a set of (unique) 'int' values.
//
// PRIVATE TYPES
typedef bslstl::TreeNodePool<int, ALLOCATOR> TreeNodePool;
//
// DATA
bslalg::RbTreeAnchor d_tree; // tree of node objects
TreeNodePool d_nodePool; // allocator for node objects
//
// NOT IMPLEMENTED
IntSet(const IntSet&);
IntSet& operator=(const IntSet&);
//
public:
// CREATORS
IntSet(const ALLOCATOR& allocator = ALLOCATOR());
// Create an empty set. Optionally specify an 'allocator' used to
// supply memory. If 'allocator' is not specified, a default
// constructed 'ALLOCATOR' object is used.
//
//! ~IntSet() = 0;
// Destroy this object.
//
// MANIPULATORS
void insert(int value);
// Insert the specified 'value' into this set.
//
bool remove(int value);
// If 'value' is a member of this set, then remove it from the set
// and return 'true'. Otherwise, return 'false' with no effect.
//
// ACCESSORS
bool isElement(int value) const;
// Return 'true' if the specified 'value' is a member of this set,
// and 'false' otherwise.
//
int numElements() const;
// Return the number of elements in this set.
};
//..
// Now, we implement the methods of 'IntSet' using 'RbTreeUtil'.
//..
// CREATORS
template <class ALLOCATOR>
inline
IntSet<ALLOCATOR>::IntSet(const ALLOCATOR& allocator)
: d_tree()
, d_nodePool(allocator)
{
}
//
// MANIPULATORS
template <class ALLOCATOR>
void IntSet<ALLOCATOR>::insert(int value)
{
int comparisonResult;
IntNodeComparator comp;
bslalg::RbTreeNode *parent =
bslalg::RbTreeUtil::findUniqueInsertLocation(&comparisonResult,
&d_tree,
comp,
value);
//..
// Here we use the 'TreeNodePool' object, 'd_nodePool', to create the node that
// was inserted into the set.
//..
if (0 != comparisonResult) {
bslalg::RbTreeNode *node = d_nodePool.createNode(value);
bslalg::RbTreeUtil::insertAt(&d_tree,
parent,
comparisonResult < 0,
node);
}
}
//
template <class ALLOCATOR>
bool IntSet<ALLOCATOR>::remove(int value)
{
IntNodeComparator comparator;
bslalg::RbTreeNode *node =
bslalg::RbTreeUtil::find(d_tree, comparator, value);
//..
// Here we use the 'TreeNodePool' object, 'd_nodePool', to delete a node that
// was removed from the set.
//..
if (node) {
bslalg::RbTreeUtil::remove(&d_tree, node);
d_nodePool.deleteNode(node);
}
return node;
}
//
// ACCESSORS
template <class ALLOCATOR>
inline
bool IntSet<ALLOCATOR>::isElement(int value) const
{
IntNodeComparator comp;
return bslalg::RbTreeUtil::find(d_tree, comp, value);
}
//
template <class ALLOCATOR>
inline
int IntSet<ALLOCATOR>::numElements() const
{
return d_tree.numNodes();
}
//..
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
veryVeryVeryVerbose = argc > 5;
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0:
case 9: {
if (verbose) printf("\nUSAGE EXAMPLE"
"\n=============\n");
// Finally, we create a sample 'IntSet' object and insert 3 values into the
// 'IntSet'. We verify the attributes of the 'Set' before and after each
// insertion.
//..
bslma::TestAllocator defaultAllocator("defaultAllocator");
bslma::DefaultAllocatorGuard defaultGuard(&defaultAllocator);
//
bslma::TestAllocator objectAllocator("objectAllocator");
//
IntSet<bsl::allocator<int> > set(&objectAllocator);
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 == objectAllocator.numBytesInUse());
ASSERT(0 == set.numElements());
//
set.insert(1);
ASSERT(set.isElement(1));
ASSERT(1 == set.numElements());
//
set.insert(1);
ASSERT(set.isElement(1));
ASSERT(1 == set.numElements());
//
set.insert(2);
ASSERT(set.isElement(1));
ASSERT(set.isElement(2));
ASSERT(2 == set.numElements());
//
ASSERT(0 == defaultAllocator.numBytesInUse());
ASSERT(0 < objectAllocator.numBytesInUse());
//..
} break;
case 8: {
TestDriver<bsltf::AllocTestType>::testCase8();
} break;
case 7: {
TestDriver<bsltf::AllocTestType>::testCase7();
} break;
case 6: {
TestDriver<bsltf::AllocTestType>::testCase6();
} break;
case 5: {
TestDriver<bsltf::AllocTestType>::testCase5();
} break;
case 4: {
TestDriver<bsltf::AllocTestType>::testCase4();
} break;
case 3: {
TestDriver<bsltf::AllocTestType>::testCase3();
} break;
case 2: {
TestDriver<bsltf::AllocTestType>::testCase2();
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST:
// Developers' Sandbox.
//
// Plan:
// Perform and ad-hoc test of the primary modifiers and accessors.
//
// Testing:
// This "test" *exercises* basic functionality, but *tests* nothing.
// --------------------------------------------------------------------
if (verbose) printf("\nBREATHING TEST"
"\n==============\n");
{
if (veryVerbose) {
printf("\tTest int-node w/ bslma::Allocator\n");
}
typedef TreeNodePool<int, bsl::allocator<int> > Obj;
typedef TreeNode<int> Node;
bslma::TestAllocator da, ta;
bslma::DefaultAllocatorGuard daGuard(&da);
Obj x(&ta);
Node *value = (Node *)x.createNode();
ASSERT(0 != value);
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
x.deleteNode(value);
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
value = (Node *)x.createNode(0xabcd);
ASSERT(0 != value);
ASSERT(0xabcd == value->value());
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
x.deleteNode(value);
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
}
{
if (veryVerbose) {
printf("\tTest allocating-node w/ bslma::Allocator\n");
}
typedef AllocatingIntType AllocType;
typedef TreeNodePool<AllocType, bsl::allocator<AllocType> > Obj;
typedef TreeNode<AllocatingIntType> Node;
bslma::TestAllocator da, ta;
bslma::DefaultAllocatorGuard daGuard(&da);
Obj x(&ta);
Node *value = (Node *)x.createNode();
ASSERT(0 != value);
ASSERT(0xabcd == value->value().value());
ASSERT(0 == da.numBlocksInUse());
ASSERT(2 == ta.numBlocksInUse());
x.deleteNode(value);
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
bslma::TestAllocator ta2;
AllocType myInt(&ta2);
myInt.value() = 0xdbca;
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
value = (Node *)x.createNode(myInt);
ASSERT(0 != value);
ASSERT(0xdbca == value->value().value());
ASSERT(0 == da.numBlocksInUse());
ASSERT(2 == ta.numBlocksInUse());
x.deleteNode(value);
ASSERT(0 == da.numBlocksInUse());
ASSERT(1 == ta.numBlocksInUse());
}
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright (C) 2013 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 32.162853 | 79 | 0.517722 | [
"object"
] |
36f54429c0dff033dec4e4d01933b8bd6f19c72a | 3,400 | cpp | C++ | ccore/src/interface/metric_interface.cpp | JosephChataignon/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 1,013 | 2015-01-26T19:50:14.000Z | 2022-03-31T07:38:48.000Z | ccore/src/interface/metric_interface.cpp | peterlau0626/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 542 | 2015-01-20T16:44:32.000Z | 2022-01-29T14:57:20.000Z | ccore/src/interface/metric_interface.cpp | peterlau0626/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 262 | 2015-03-19T07:28:12.000Z | 2022-03-30T07:28:24.000Z | /*!
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
*/
#include <pyclustering/interface/metric_interface.h>
#include <pyclustering/utils/metric.hpp>
using namespace pyclustering;
using namespace pyclustering::utils::metric;
void * metric_create(const std::size_t p_type,
const pyclustering_package * const p_arguments,
double (*p_solver)(const void *, const void *))
{
switch(p_type) {
case EUCLIDEAN: {
distance_metric<point> metric = distance_metric_factory<point>::euclidean();
return new distance_metric<point>(std::move(metric));
}
case EUCLIDEAN_SQUARE: {
distance_metric<point> metric = distance_metric_factory<point>::euclidean_square();
return new distance_metric<point>(std::move(metric));
}
case MANHATTAN: {
distance_metric<point> metric = distance_metric_factory<point>::manhattan();
return new distance_metric<point>(std::move(metric));
}
case CHEBYSHEV: {
distance_metric<point> metric = distance_metric_factory<point>::chebyshev();
return new distance_metric<point>(std::move(metric));
}
case MINKOWSKI: {
std::vector<double> arguments;
p_arguments->extract(arguments);
distance_metric<point> metric = distance_metric_factory<point>::minkowski(arguments[0]);
return new distance_metric<point>(std::move(metric));
}
case CANBERRA: {
distance_metric<point> metric = distance_metric_factory<point>::canberra();
return new distance_metric<point>(std::move(metric));
}
case CHI_SQUARE: {
distance_metric<point> metric = distance_metric_factory<point>::chi_square();
return new distance_metric<point>(std::move(metric));
}
case GOWER: {
point max_range;
p_arguments->extract(max_range);
distance_metric<point> metric = distance_metric_factory<point>::gower(max_range);
return new distance_metric<point>(std::move(metric));
}
case USER_DEFINED: {
auto functor_wrapper = [p_solver](const point & p1, const point & p2) {
pyclustering_package * point1 = create_package(&p1);
pyclustering_package * point2 = create_package(&p2);
const double distance = p_solver(point1, point2);
delete point1;
delete point2;
return distance;
};
distance_metric<point> metric = distance_metric_factory<point>::user_defined(functor_wrapper);
return new distance_metric<point>(std::move(metric));
}
default:
return nullptr;
}
}
void metric_destroy(const void * p_pointer_metric) {
delete (distance_metric<point> *) p_pointer_metric;
}
double metric_calculate(const void * p_pointer_metric,
const pyclustering_package * const p_point1,
const pyclustering_package * const p_point2)
{
point point1, point2;
p_point1->extract(point1);
p_point2->extract(point2);
distance_metric<point> & metric = *((distance_metric<point> *) p_pointer_metric);
return metric(point1, point2);
}
| 30.909091 | 106 | 0.623235 | [
"vector"
] |
36f969b313358f8fb3d846a743a4948a787a5a03 | 2,458 | hpp | C++ | tools/compute_mean/walltimes.hpp | andy-yoo/lbann-andy | 237c45c392e7a5548796ac29537ab0a374e7e825 | [
"Apache-2.0"
] | null | null | null | tools/compute_mean/walltimes.hpp | andy-yoo/lbann-andy | 237c45c392e7a5548796ac29537ab0a374e7e825 | [
"Apache-2.0"
] | null | null | null | tools/compute_mean/walltimes.hpp | andy-yoo/lbann-andy | 237c45c392e7a5548796ac29537ab0a374e7e825 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 _TOOLS_COMPUTE_MEAN_WALLTIMES_HPP_
#define _TOOLS_COMPUTE_MEAN_WALLTIMES_HPP_
#include <chrono>
#include <vector>
#include "mpi_states.hpp"
namespace tools_compute_mean {
/** Return time in fractional seconds since an epoch. */
inline double get_time() {
using namespace std::chrono;
return duration_cast<duration<double>>(
steady_clock::now().time_since_epoch()).count();
}
class walltimes {
public:
double m_total;
double m_load;
double m_decode;
double m_preprocess;
double m_write;
walltimes() :
m_total(0.0),
m_load(0.0),
m_decode(0.0),
m_preprocess(0.0),
m_write(0.0) {}
std::vector<double> get() const {
return {m_total, m_load, m_decode, m_preprocess, m_write};
}
std::vector<std::string> get_names() const {
return {"total", "load", "decode", "preprocess", "write"};
}
};
void collect_times(const std::vector<double>& localTimes,
std::vector<double>& avgTimes, std::vector<double>& minTimes,
std::vector<double>& maxTimes, std::vector<double>& stdTimes,
const mpi_states& ms);
void summarize_walltimes(walltimes& wt, mpi_states& ms);
} // end of namespace tools_compute_mean
#endif // _TOOLS_COMPUTE_MEAN_WALLTIMES_HPP_
| 31.922078 | 80 | 0.6607 | [
"vector"
] |
36fa109941b14b90ac2d7c3bc2c3b297a7ef69ac | 14,560 | cpp | C++ | client/src/gapi/particles.cpp | egslava/arena_shooter | c93245441ed72c63a7f628d99b766ff005b8a3dc | [
"MIT"
] | 1 | 2021-05-11T09:06:05.000Z | 2021-05-11T09:06:05.000Z | client/src/gapi/particles.cpp | egslava/arena_shooter | c93245441ed72c63a7f628d99b766ff005b8a3dc | [
"MIT"
] | null | null | null | client/src/gapi/particles.cpp | egslava/arena_shooter | c93245441ed72c63a7f628d99b766ff005b8a3dc | [
"MIT"
] | null | null | null | #include "gapi/gapi.h"
#include <chrono>
const char *particles_vertex_shader_code =
"#version 330 core\n"
"layout (location = 0) in vec3 _init_pos;\n"
"layout (location = 1) in vec3 _in_w;\n"
"layout (location = 2) in vec2 _init_size;\n"
"layout (location = 3) in vec3 _init_velocity;\n"
"layout (location = 4) in vec4 _start_color;\n"
"layout (location = 5) in vec4 _end_color;\n"
"layout (location = 6) in vec2 _particle_timing;\n"
"out vec2 _tex_coords;"
"out vec4 _interpolated_color;"
"uniform mat4 model;\n"
"uniform mat4 projection;\n"
"uniform mat4 camera;\n"
"uniform float _time; \n" // time %= 24x3600, eps = (2**17-2**16)/2**23 = 0.0078125
"uniform vec4 _gravity;\n"
"float _start_time = _particle_timing[0];\n"
"float _end_time = _particle_timing[1];\n"
"float _start_size = _init_size[0];\n"
"float _end_size = _init_size[1];\n"
"float normed_time = (_time - _start_time) / (_end_time - _start_time);\n"
"const float _sp = 1.0; // shift power \n"
"const vec4 _shift[6] = vec4[6](\n"
" vec4( _sp, _sp, 0, 0), vec4(-_sp, _sp, 0, 0), vec4(-_sp, -_sp, 0, 0), \n"
" vec4(-_sp, -_sp, 0, 0), vec4( _sp, -_sp, 0, 0), vec4( _sp, _sp, 0, 0));\n"
"\n"
// "const float _angles[6*2] = float[6*2](\n"
// " 45, 135, -135, \n"
// " -135, -45, 45,\n"
// " 135, 45, -45, \n"
// " -45, -135, 135 );\n"
// "\n"
"const float _angles[6] = float[6](\n"
" 45, 135, -135, \n"
" -135, -45, 45);\n"
"const vec2 _texcoords[6] = vec2[6](\n"
" vec2( 1, 1), vec2( 0, 1), vec2( 0, 0), \n"
" vec2( 0, 0), vec2( 1, 0), vec2( 1, 1));\n"
"\n"
"float angular_velocity = mix(_in_w.y, _in_w.z, normed_time);\n"
"vec4 cam_pos = inverse(camera) * vec4(0,0,0,1);\n"
"void main() {\n"
// " float size = _start_size;\n"
// " float size = normed_time;//0.5+t*3;\n"
" float size = mix(_start_size, _end_size, normed_time);\n"
" vec4 pos = vec4(_init_pos + _init_velocity*normed_time, 1) + vec4( (_gravity*normed_time*normed_time).xyz,0);\n"
" vec3 screen_size_lb = (projection * ((camera * pos)-vec4(size, size, 0, 0))).xyz;\n"
" vec2 screen_size_tr = (projection * ((camera * pos)+vec4(size, size, 0, 0))).xy;\n"
" float screen_size = length(screen_size_lb.xy - screen_size_tr) / screen_size_lb.z;\n"
" _interpolated_color = mix(_start_color, _end_color, normed_time);\n"
// " int discard2 = 1-int((clamp (length(pos-cam_pos) / 25, 0, 1)));\n"
// " int discard2 = 0;\n"
// screen_size > 2.35 ||
// (gl_VertexID % 18 < 12) &&
// 2 уроня: 1/3, 2/3, 3/3, не: 6/12, 6/18, 6/24 и т.п. (оставлять)
//
//
" bool discard3 = ((gl_VertexID % 60 < 54) && (length(pos - cam_pos) < 4.00) && (screen_size > 0.25));\n" // first level
" bool discard4 = ((gl_VertexID % 60 < 30) && (length(pos - cam_pos) < 8.00) && (screen_size > 0.25));\n" // first level
" int discard2 = (discard3 || discard4)?1:0;\n"
// " int discard2 = 1;\n"
// " "
// " float angle = _in_w.x + angular_velocity*normed_time + _angles[(gl_VertexID % 6 + discard2*6)] / 180 * 3.141529;\n"
" float angle = _in_w.x + angular_velocity*normed_time + _angles[(gl_VertexID % 6)] / 180 * 3.141529;\n"
" vec4 rot = vec4(cos(angle), sin(angle), 0, 0);\n"
// " _interpolated_color.a = 0.0; //alpha;\n"
" pos = camera * pos;\n"
" pos += size * rot * (discard2>0?0.1:1);\n" // _shift[gl_VertexID % 6] *
" pos = projection * pos;\n"
// " if ( screen_size < 0.5) pos.x *= -1;\n"
" gl_Position = pos; // * (1-discard2);\n"
" _tex_coords = _texcoords[gl_VertexID % 6];\n"
"}\n"
;
const char *particles_fragment_shader_code =
"#version 330 core\n"
"uniform sampler2D texture0;\n"
"uniform vec4 _ambient_color;\n"
"in vec2 _tex_coords;\n"
"in vec4 _interpolated_color;\n"
"out vec4 FragColor;\n"
"\n"
"void main() {\n"
" FragColor = _ambient_color + _interpolated_color * texture(texture0, _tex_coords);\n"
// " FragColor = vec4(1,1,1,1); //_ambient_color + * texture(texture0, _tex_coords);\n"
"}\n";
double now(){
using timer = std::chrono::high_resolution_clock;
using ns = std::chrono::nanoseconds;
return static_cast<double>(std::chrono::duration_cast<ns>( timer::now().time_since_epoch() ).count()) / 1e9;
}
void reborn(const Ball &position_range, const float emitter_time, const Emitter &emitter, Particle &particle, bool random_init_time){
// if (random_init_time){
// particle.init_time = rand(emitter.time(), emitter.time() + emitter.max_live_time);
// } else {
// particle.init_time = emitter.time();
// }
// particle.end_time = rand(particle.init_time, particle.init_time + emitter.max_live_time);
float init_time = emitter_time;
float end_time = init_time + rand(emitter.min_live_time, emitter.max_live_time);
if (random_init_time){
float current_normed_time = rand(0.0f, 1.0f);
float current_time_from_init = (end_time - init_time) * current_normed_time;
end_time -= current_time_from_init;
init_time -= current_time_from_init;
}
particle.start_time = init_time;
particle.end_time = end_time;
particle.init_position = rand(position_range);
particle.angle = Vec3(
rand(emitter.min_start_angle, emitter.max_start_angle),
rand(emitter.min_start_angular_velocity, emitter.max_start_angular_velocity),
rand(emitter.min_end_angular_velocity, emitter.min_end_angular_velocity));
particle.init_velocity = rand(emitter.velocity_range);
particle.start_color = rand(emitter.start_color_range);
particle.end_color = rand(emitter.end_color_range);
particle.start_size = rand(emitter.min_start_size, emitter.max_start_size);
particle.end_size = rand(emitter.min_end_size, emitter.max_end_size);
}
bool is_dead(float time, const Emitter &emitter, const Particle &particle){
// return (emitter.time() - particle.init_time > emitter.max_live_time );
return (time > particle.end_time);
}
void Particles::update_particles_state(const Vec3 &position, bool update) {
bool kill = !update || this->should_explode;
bool random_init_time = !update && this->emitter.type == EmitterType::FOUNTAIN;
Ball position_range{ position, this->emitter.position_range };
if (kill){
this->num_to_update = this->particles.size();
this->num_dead = 0;
for (Particle &particle : particles)
reborn(position_range, this->_uniform_emitter_time, this->emitter, particle, random_init_time);
return;
}
switch (emitter.type) {
case EmitterType::EXPLOSION:
for (int i = 0; i < particles.size() - this->num_dead; i++){
Particle &particle = particles[i];
// should_explode should influence on 'update'. So, it should just respawn
// the whole Particle System and that's all
if (is_dead(this->_uniform_emitter_time, this->emitter, particle)){
this->num_dead += 1;
if (this->num_dead == this->particles.size())
return;
particle = particles[particles.size() - 1 - num_dead];
// reborn(position, this->_uniform_emitter_time, this->emitter, particle, false);
}
}
break;
case EmitterType::FOUNTAIN:{
for (Particle &particle : particles) {
if (is_dead(this->_uniform_emitter_time, this->emitter, particle)){
reborn(position_range, this->_uniform_emitter_time, this->emitter, particle, random_init_time);
}
}
} break;
#ifndef NDEBUG
default:
throw MyIllegalStateException("Emitter type can be only EXPLOSION or FOUNTAIN");
#endif
}
}
double Emitter::time() const {
return now() - base_time;
}
Emitter::Emitter():
base_time( now() ),
min_live_time(0),
max_live_time(1),
max_particles(1),
position_range(0),
min_start_size(0),
max_start_size(0),
min_end_size(1),
max_end_size(3),
gravity(0, 0, 0),
type(EmitterType::EXPLOSION)
{
this->velocity_range.C = Vec3(0, 2, 0);
this->velocity_range.R = 1.0;
}
void Particles::_link_programs(){
Shader vertex_shader, fragment_shader;
vertex_shader.compile(Shader::Type::VERTEX_SHADER, particles_vertex_shader_code);
fragment_shader.compile(Shader::Type::FRAGMENT_SHADER, particles_fragment_shader_code);
particle_shader.link(std::move(vertex_shader), std::move(fragment_shader) );
}
void Particles::_resize_vectors(){
position_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 3); // 6 points with 3 coords
angle_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 3);
size_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 2);
velocity_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 3);
start_color_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 4);
end_color_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 4);
time_buffer.resize(particles.size() * _POINTS_PER_PRIMITIVE * 2);
}
void Particles::_particles_to_vectors() {
for (int i_part = 0; i_part < this->particles.size(); i_part++) {
const Particle &particle = this->particles[i_part];
for(int i_vertex = 0; i_vertex < _POINTS_PER_PRIMITIVE; i_vertex++){
position_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 0] = particle.init_position._x;
position_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 1] = particle.init_position._y;
position_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 2] = particle.init_position._z;
angle_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 0] = particle.angle._x;
angle_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 1] = particle.angle._y;
angle_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 2] = particle.angle._z;
velocity_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 0] = particle.init_velocity._x;
velocity_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 1] = particle.init_velocity._y;
velocity_buffer[i_part*_POINTS_PER_PRIMITIVE*3 + i_vertex * 3 + 2] = particle.init_velocity._z;
start_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 0] = particle.start_color._x;
start_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 1] = particle.start_color._y;
start_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 2] = particle.start_color._z;
start_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 3] = particle.start_color._w;
end_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 0] = particle.end_color._x;
end_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 1] = particle.end_color._y;
end_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 2] = particle.end_color._z;
end_color_buffer[i_part*_POINTS_PER_PRIMITIVE*4 + i_vertex * 4 + 3] = particle.end_color._w;
time_buffer[i_part*_POINTS_PER_PRIMITIVE*2 + i_vertex * 2 + 0] = particle.start_time;
time_buffer[i_part*_POINTS_PER_PRIMITIVE*2 + i_vertex * 2 + 1] = particle.end_time;
size_buffer[i_part*_POINTS_PER_PRIMITIVE*2 + i_vertex * 2 + 0] = particle.start_size;
size_buffer[i_part*_POINTS_PER_PRIMITIVE*2 + i_vertex * 2 + 1] = particle.end_size;
}
}
}
void Particles::init(const Vec3 &pos){
particles.resize(emitter.max_particles);
this->_uniform_emitter_time = emitter.time();
update_particles_state(pos, false);
this->_resize_vectors();
this->_particles_to_vectors();
std::vector<VBO> gpu_vbos;
gpu_vbos.push_back( VBO().data(position_buffer, 3) );
gpu_vbos.push_back( VBO().data(angle_buffer, 3) );
gpu_vbos.push_back( VBO().data(size_buffer, 2 ) );
gpu_vbos.push_back( VBO().data(velocity_buffer, 3) );
gpu_vbos.push_back( VBO().data(start_color_buffer, 4) );
gpu_vbos.push_back( VBO().data(end_color_buffer, 4) );
gpu_vbos.push_back( VBO().data(time_buffer, 2) );
this->_vao.data( std::move(gpu_vbos) );
_link_programs();
this->_pos_cache = pos;
this->_is_inited = true;
}
void Particles::reinit(const Vec3 &pos){
if (!this->_is_inited) {
init(pos);
return;
}
this->_uniform_emitter_time = emitter.time();
update_particles_state(pos, false);
this->_pos_cache = pos;
}
void Particles::explode()
{
#ifndef NDEBUG
if (this->emitter.type != EmitterType::EXPLOSION){
throw MyIllegalStateException("Only particles of type EXPLOSION can be exploded!");
}
#endif
this->should_explode = true;
}
void Particles::update(const Vec3 &pos, bool is_visible)
{
this->_uniform_emitter_time = emitter.time();
update_particles_state(pos, true);
this->should_explode = false;
if (is_visible){
this->_particles_to_vectors();
this->vectors2vbos();
}
this->_pos_cache = pos;
}
void Particles::vectors2vbos(){
this->_vao._vbos[0].data(position_buffer, 3);
this->_vao._vbos[1].data(angle_buffer, 3);
this->_vao._vbos[2].data(size_buffer, 2);
this->_vao._vbos[3].data(velocity_buffer, 3);
this->_vao._vbos[4].data(start_color_buffer, 4);
this->_vao._vbos[5].data(end_color_buffer, 4);
this->_vao._vbos[6].data(time_buffer, 2);
}
void Particles::draw(const Camera &camera, const Vec3 &ambient_color) {
this->particle_shader.use(camera, ambient_color);
this->particle_shader.uniform("_time", this->_uniform_emitter_time);
this->particle_shader.uniform("_ambient_color", ambient_color);
this->particle_shader.uniform("_gravity", this->emitter.gravity);
// vectors2vbos();
this->_vao.bind();
this->_tex.bind();
glDepthMask(GL_FALSE);
// printf("%d == particles.size()\n", this->particles.size());
float d = (camera._pos - this->_pos_cache).len3();
float visible_percent = fmin(1, d*d/1);
float tri_draw = (this->particles.size() - this->num_dead) * 2 * 3;
float tri_skip = 0; // tri_draw * (1-visible_percent);
glDrawArrays(GL_TRIANGLES, tri_skip, tri_draw - tri_skip);
glDepthMask(GL_TRUE);
}
| 40.670391 | 133 | 0.645192 | [
"vector",
"model"
] |
36ffd44eef8c9c65202d8de973490c3bfd56987f | 3,400 | cpp | C++ | analysis/semantic/input-generation/generators/egret/src/main.cpp | SBULeeLab/LinguaFranca-FSE19 | a75bd51713d14aa9b48c32e103a3da500854f518 | [
"MIT"
] | 2 | 2021-08-03T12:15:39.000Z | 2021-09-27T22:03:36.000Z | analysis/semantic/input-generation/generators/egret/src/main.cpp | SBULeeLab/LinguaFranca-FSE19 | a75bd51713d14aa9b48c32e103a3da500854f518 | [
"MIT"
] | null | null | null | analysis/semantic/input-generation/generators/egret/src/main.cpp | SBULeeLab/LinguaFranca-FSE19 | a75bd51713d14aa9b48c32e103a3da500854f518 | [
"MIT"
] | 2 | 2020-10-15T16:48:20.000Z | 2020-12-30T12:57:45.000Z | /* main.cpp: test driver for EGRET engine (used for debugging)
Copyright (C) 2016-2018 Eric Larson and Anna Kirk
elarson@seattleu.edu
This file is part of EGRET.
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "egret.h"
using namespace std;
static char *get_arg(int &idx, int argc, char **argv);
int
main(int argc, char *argv[])
{
cout << "RUNNING PROGRAM" << endl;
int idx = 1;
string regex = "";
string base_substring = "evil";
bool check_mode = false;
bool web_mode = false;
bool debug_mode = false;
bool stat_mode = false;
// Process arguments
while (idx < argc) {
char *arg = get_arg(idx, argc, argv);
// -r: regular expression
if (strcmp(arg, "-r") == 0) {
if (regex != "") {
cerr << "USAGE: Can only have one regular expression to process" << endl;
return -1;
}
regex = get_arg(idx, argc, argv);
}
// -f: file that contains a single regular expression
else if (strcmp(arg, "-f") == 0) {
ifstream regexFile;
char *file_name = get_arg(idx, argc, argv);
regexFile.open(file_name);
if (!regexFile.is_open()) {
cerr << "USAGE: Unable to open file " << file_name << endl;
return -1;
}
if (regex != "") {
cerr << "USAGE: Can only have one regular expression to process" << endl;
return -1;
}
getline(regexFile, regex);
regexFile.close();
}
// -b: base substring for regex strings
else if (strcmp(arg, "-b") == 0) {
base_substring = get_arg(idx, argc, argv);
}
// -c: run check mode
else if (strcmp(arg, "-c") == 0) {
check_mode = true;
}
// -d: print debug information based on the given mode
else if (strcmp(arg, "-d") == 0) {
debug_mode = true;
}
// -s: print stats
else if (strcmp(arg, "-s") == 0) {
stat_mode = true;
}
// -w: run web mode
else if (strcmp(arg, "-w") == 0) {
web_mode = true;
}
// everything else is invalid
else {
cerr << "USAGE: Invalid command line option: " << arg << endl;
return -1;
}
}
if (regex == "") {
cerr << "USAGE: Did not find a regular expression to process" << endl;
return -1;
}
vector <string> test_strings =
run_engine(regex, base_substring, check_mode, web_mode, debug_mode, stat_mode);
vector <string>::iterator it;
for (it = test_strings.begin(); it != test_strings.end(); it++) {
cout << *it << endl;
}
return 0;
}
static char *
get_arg(int &idx, int argc, char **argv)
{
char *arg;
if (idx >= argc) {
cerr << "USAGE: Invalid command line" << endl << endl;
}
arg = argv[idx];
idx++;
return arg;
}
| 24.113475 | 83 | 0.608235 | [
"vector"
] |
3c007ee168ab57a124cbb7b9efabc7338f8c57f2 | 11,427 | cpp | C++ | src/components.cpp | dgkimura/dafs | 20273ea13d71bbb9ca8f6e85045c0abb1cf45aba | [
"MIT"
] | 2 | 2018-06-29T05:59:16.000Z | 2018-07-01T05:58:14.000Z | src/components.cpp | dgkimura/dafs | 20273ea13d71bbb9ca8f6e85045c0abb1cf45aba | [
"MIT"
] | 7 | 2018-06-04T16:26:37.000Z | 2018-11-03T00:47:08.000Z | src/components.cpp | dgkimura/dafs | 20273ea13d71bbb9ca8f6e85045c0abb1cf45aba | [
"MIT"
] | null | null | null | #include <chrono>
#include <cstring>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include "dafs/constants.hpp"
#include "dafs/commit.hpp"
#include "dafs/customhash.hpp"
#include "dafs/details.hpp"
#include "dafs/disk.hpp"
#include "dafs/components.hpp"
#include "dafs/serialization.hpp"
namespace dafs
{
ReplicatedStorage::ReplicatedStorage(
dafs::Replication& replication,
dafs::Root root)
: replication(replication),
root(root),
blocklist((boost::filesystem::path(root.directory) /
boost::filesystem::path(Constant::BlockListName)).string())
{
}
ReplicatedStorage::ReplicatedStorage(
const ReplicatedStorage& other)
: replication(other.replication),
root(other.root)
{
}
BlockFormat
ReplicatedStorage::ReadBlock(BlockInfo info)
{
return dafs::ReadBlock(rooted(info));
}
void
ReplicatedStorage::DeleteBlock(BlockInfo info)
{
replication.Write
(
dafs::serialize<dafs::Proposal>
(
CreateProposal
(
dafs::ProposalType::DeleteBlock,
"",
info,
info.revision,
std::hash<dafs::BlockInfo>{}(rooted(info))
)
)
);
}
void
ReplicatedStorage::InsertIndex(BlockInfo info)
{
std::fstream stream(blocklist,
std::ios::in | std::ios::out | std::ios::binary);
Delta delta = dafs::Insert(stream, info);
Write(dafs::BlockInfo{Constant::BlockListName}, delta);
}
void
ReplicatedStorage::RemoveIndex(BlockInfo info)
{
std::fstream stream(blocklist,
std::ios::in | std::ios::out | std::ios::binary);
Delta delta = dafs::Remove(stream, info);
Write(dafs::BlockInfo{Constant::BlockListName}, delta);
}
BlockIndex
ReplicatedStorage::GetIndex()
{
std::fstream stream(blocklist,
std::ios::in | std::ios::out | std::ios::binary);
std::stringstream buffer;
buffer << stream.rdbuf();
return dafs::deserialize<BlockIndex>(buffer.str());
}
void
ReplicatedStorage::WriteBlock(BlockInfo info, BlockFormat data)
{
BlockFormat was = dafs::ReadBlock(rooted(info));
Delta delta = CreateDelta(was.contents, data.contents);
Write(info, delta);
}
void
ReplicatedStorage::Write(BlockInfo info, Delta delta)
{
replication.Write
(
dafs::serialize<dafs::Proposal>
(
CreateProposal
(
dafs::ProposalType::WriteBlock,
dafs::serialize(delta),
info,
info.revision,
std::hash<dafs::BlockInfo>{}(rooted(info))
)
)
);
}
BlockInfo
ReplicatedStorage::rooted(
BlockInfo info)
{
info.path = (boost::filesystem::path(root.directory) /
boost::filesystem::path(info.path)).string();
return info;
}
ReplicatedNodeSet::ReplicatedNodeSet(
dafs::Replication& replication)
: replication_(replication)
{
}
void
ReplicatedNodeSet::RemoveNode(dafs::Address address)
{
replication_.RemoveReplica(address);
}
dafs::ReplicatedEndpoints
ReplicatedNodeSet::SetMinus(
const dafs::Address management,
const dafs::Address replication,
const dafs::Identity identity,
const std::string fault_domain,
const std::string location,
dafs::ReplicatedEndpoints details)
{
replication_.AddReplica(replication, location);
details.minus.management = management;
details.minus.replication = replication;
details.minus.identity = identity;
details.minus.fault_domain = fault_domain;
return details;
}
dafs::ReplicatedEndpoints
ReplicatedNodeSet::SetZero(
const dafs::Address management,
const dafs::Address replication,
const dafs::Identity identity,
const std::string fault_domain,
const std::string location,
dafs::ReplicatedEndpoints details)
{
replication_.AddReplica(replication, location);
details.zero.management = management;
details.zero.replication = replication;
details.zero.identity = identity;
details.zero.fault_domain = fault_domain;
return details;
}
dafs::ReplicatedEndpoints
ReplicatedNodeSet::SetPlus(
const dafs::Address management,
const dafs::Address replication,
const dafs::Identity identity,
const std::string fault_domain,
const std::string location,
dafs::ReplicatedEndpoints details)
{
replication_.AddReplica(replication, location);
details.plus.management = management;
details.plus.replication = replication;
details.plus.identity = identity;
details.plus.fault_domain = fault_domain;
return details;
}
ReplicatedPing::ReplicatedPing(
dafs::Replication& replication,
dafs::Address address,
std::function<dafs::ReplicatedEndpoints(void)> get_endpoints,
std::function<bool(void)> is_partition_locked,
std::chrono::seconds ping_interval)
: replication(replication),
address_(address),
get_endpoints(get_endpoints),
is_partition_locked(is_partition_locked),
ping_interval(ping_interval),
should_continue(true)
{
}
void
ReplicatedPing::Start()
{
std::thread([this]()
{
auto sender = std::make_shared<dafs::NetworkSender>();
while (should_continue)
{
if (replication.GetReplicaCount() > 1 && !is_partition_locked())
{
SendPing(sender);
}
std::this_thread::sleep_for(ping_interval);
}
}).detach();
}
void
ReplicatedPing::SendPing(std::shared_ptr<dafs::Sender> sender)
{
replication.Write
(
dafs::serialize<dafs::Proposal>
(
Proposal
{
dafs::ProposalType::Ping,
dafs::serialize(dafs::ProposalContent{})
}
)
);
for (auto a : replication.GetMissingReplicas())
{
auto endpoint = get_failover_endpoint(a);
if (endpoint.replication.ip == dafs::EmptyAddress().ip &&
endpoint.replication.port == dafs::EmptyAddress().port)
{
break;
}
//
// XXX: Propose exit cluster assumes the evicted node is in the
// plus slot. Otherwise this message is treated as a no-op.
// Thus we can iterate over all failover endpoints and let
// the approporiate one take action.
//
sender->Send(
endpoint.management,
dafs::Message
{
dafs::MessageType::_ProposeExitCluster,
std::vector<dafs::MetaData>
{
dafs::MetaData
{
dafs::AddressKey,
dafs::serialize(a)
}
}
}
);
}
}
std::vector<dafs::Address>
ReplicatedPing::NonresponsiveMembers(int last_elections)
{
return replication.GetMissingReplicas();
}
dafs::Endpoint
ReplicatedPing::get_failover_endpoint(dafs::Address inactive)
{
auto endpoints = get_endpoints();
return GetFailover(endpoints, address_, inactive);
}
ReplicatedLock::ReplicatedLock(
dafs::Replication& replication,
dafs::Address address,
dafs::Root root)
: replication(replication),
address(address),
root(root)
{
}
bool
ReplicatedLock::Acquire()
{
dafs::BlockInfo lockfile;
lockfile.path = Constant::LockName;
replication.Write
(
dafs::serialize<dafs::Proposal>
(
CreateProposal
(
dafs::ProposalType::WriteBlock,
dafs::serialize
(
CreateDelta(
"", // was empty
dafs::serialize(address)
)
),
lockfile,
0, // revision
0 // Write IFF was empty
)
)
);
return dafs::ReadBlock(rooted(lockfile)).contents == dafs::serialize(address);
}
bool
ReplicatedLock::IsLocked()
{
dafs::BlockInfo lockfile;
lockfile.path = Constant::LockName;
return dafs::ReadBlock(rooted(lockfile)).contents.size() > 0;
}
void
ReplicatedLock::Release()
{
dafs::BlockInfo lockfile;
lockfile.path = Constant::LockName;
replication.Write
(
dafs::serialize<dafs::Proposal>
(
CreateProposal
(
dafs::ProposalType::DeleteBlock,
"",
lockfile,
lockfile.revision,
std::hash<dafs::BlockInfo>{}(rooted(lockfile))
)
)
);
}
BlockInfo
ReplicatedLock::rooted(
BlockInfo info)
{
info.path = (boost::filesystem::path(root.directory) /
boost::filesystem::path(info.path)).string();
return info;
}
BlockAllocator::BlockAllocator(
std::function<dafs::BlockIndex(void)> get_index,
std::function<void(dafs::BlockInfo)> insert_index,
std::function<dafs::ReplicatedEndpoints(void)> get_endpoints)
: get_index(get_index),
insert_index(insert_index),
get_endpoints(get_endpoints)
{
}
dafs::BlockInfo
BlockAllocator::Allocate()
{
auto details = get_endpoints();
dafs::BlockInfo info
{
details.zero.identity.id,
details.zero.identity,
1
};
while (IsLogicallyOrdered(details.zero.identity,
info.identity,
details.plus.identity))
{
auto index = get_index().items;
if (std::any_of(index.cbegin(), index.cend(),
[=](const BlockInfo& b)
{
return b.identity==info.identity;
}))
{
info.identity += 1;
info.path = info.identity.id;
}
else
{
insert_index(info);
return info;
}
}
return dafs::BlockInfo{"", dafs::Identity(), 0};
}
}
| 26.451389 | 86 | 0.526822 | [
"vector"
] |
3c01d36af40256a94dea0136905cc413c15ad5f0 | 3,340 | cpp | C++ | ojcpp/leetcode/500/522_m_longest_uncommon_seq.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | 3 | 2019-05-04T03:26:02.000Z | 2019-08-29T01:20:44.000Z | ojcpp/leetcode/500/522_m_longest_uncommon_seq.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | ojcpp/leetcode/500/522_m_longest_uncommon_seq.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | //
// Created by rui.zhou on 3/17/2019.
//
/*
* Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
Example 1:
Input: "aba", "cdc", "eae"
Output: 3
Note:
All the given strings' lengths will not exceed 10.
The length of the given list will be in the range of [2, 50].
Basically this solution relies on two things:
1- If a substring of any string in the list is an uncommon subsequence,
then so is the string. So the longest uncommon substring, if there is one, has to be a whole string from the list.
2- A string can only be a subsequence of another string that is the same size (if it's the same string) or longer.
So, what we do is sort the strings by size (in decreasing order) and then, starting from the longest string,
check if there are any other strings of it's length or higher that it is a subsequence of. If there isn't then that is the max uncommon subsequence.
找出最长非公共子序列。公共子序列的定义是一个字符串可由另一个字符串删除某些字符得到。
如果在一组字符串中,某一个字符串不是任何另外的字符串的公共子序列,那么这就是它是全组的非公共子序列。找出最长的长度。
直接用暴力法
先排序,从大到小,然后一次看每一个str是否和数组里的有subseq关系
*/
#include <codech/codech_def.h>
using namespace std;
namespace {
class Solution {
public:
//检查是否subsequence的套路,通过删除字符
// aa is aaa subseq, abc is addbddc subseq
bool check_subsequence(string str1, string str2){
int i = 0; int j = 0;
while (i < str1.size() && j < str2.size()){
if (str1[i] == str2[j])
i++;
j++;
}
return (i == str1.size());
}
int findLUSlength(vector<string>& strs) {
std::sort(strs.begin(), strs.end(), [](string a, string b){return a.size() > b.size();});
for (int i = 0; i < strs.size(); i++){
bool is_subsequence = false;
for (int j = 0; j < strs.size() && (j < i || strs[i].size() == strs[j].size()); j++){
//只和大于等于自己长度的str比较,str[i].length <= str[j].length
//如果自己的长度大于对方,那就不存在subseq了!
if (i != j && check_subsequence(strs[i], strs[j])){
is_subsequence = true;
break;
}
}
if (!is_subsequence)
return strs[i].size();
}
return -1;
}
};
}
DEFINE_CODE_TEST(522_longest_uncommonseq2)
{
Solution obj;
{
vector<string> strs{"aaa","aaa","aa"};
VERIFY_CASE(obj.findLUSlength(strs),-1);
}
{
vector<string> strs{"abaa", "cdc", "eae"};
VERIFY_CASE(obj.findLUSlength(strs),4);
}
{
vector<string> strs{"aba", "cdc", "eae"};
VERIFY_CASE(obj.findLUSlength(strs),3);
}
} | 36.304348 | 257 | 0.617365 | [
"vector"
] |
3c04ade472adba56dec3de4ad04a1a9bd9aaebba | 4,529 | cpp | C++ | libnd4j/include/ops/declarable/generic/convo/conv3d_ops.cpp | rexwong/deeplearning4j | 96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38 | [
"Apache-2.0"
] | 97 | 2016-02-15T07:08:45.000Z | 2021-05-09T17:36:38.000Z | libnd4j/include/ops/declarable/generic/convo/conv3d_ops.cpp | rexwong/deeplearning4j | 96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38 | [
"Apache-2.0"
] | 331 | 2016-03-07T21:26:26.000Z | 2018-06-08T07:16:15.000Z | libnd4j/include/ops/declarable/generic/convo/conv3d_ops.cpp | rexwong/deeplearning4j | 96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38 | [
"Apache-2.0"
] | 108 | 2016-01-19T15:11:03.000Z | 2021-03-29T05:25:51.000Z | //
// @author raver119@gmail.com
//
#include <op_boilerplate.h>
#if NOT_EXCLUDED(OP_conv3d)
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/generic/helpers/convolutions.h>
namespace nd4j {
namespace ops {
CUSTOM_OP_IMPL(conv3d, 2, 1, false, 0, 7) {
// cubic convo
NDArray<T> *input = INPUT_VARIABLE(0);
NDArray<T> *weights = INPUT_VARIABLE(1);
NDArray<T> *bias = nullptr;
if (block.width() == 3)
bias = INPUT_VARIABLE(2);
if (input->rankOf() != 5)
return ND4J_STATUS_BAD_DIMENSIONS;
NDArray<T>* output = OUTPUT_VARIABLE(0);
bool biasUsed = INT_ARG(0) != 0 && bias != nullptr;
// TODO: change width/height order height/width
int dT = INT_ARG(1);
int dW = INT_ARG(2);
int dH = INT_ARG(3);
int pT = INT_ARG(4);
int pW = INT_ARG(5);
int pH = INT_ARG(6);
REQUIRE_TRUE(!(pT != 0 || pW != 0 || pH != 0), 0, "Padding isn't supported on CPU backend O_o");
std::unique_ptr<ResultSet<T>> batchIn(NDArrayFactory<T>::allExamples(input));
std::unique_ptr<ResultSet<T>> batchOut(NDArrayFactory<T>::allExamples(output));
// FIXME: helpers should be used here
for (int e = 0; e < batchIn->size(); e++) {
auto tadIn = batchIn->at(e);
auto tadOut = batchOut->at(e);
if (biasUsed) {
std::unique_ptr<ResultSet<T>> outputBlock(NDArrayFactory<T>::allExamples(tadOut));
for (int i = 0; i < bias->lengthOf(); i++) {
auto oB = outputBlock->at(i);
oB->assign(bias->getScalar(i));
}
} else
output->assign(0.0);
Nd4jStatus res = ConvolutionUtils<T>::conv3Dmv(tadOut, (T) 1.0f, (T) 1.0f, tadIn, weights, dT, dH, dW, "V", "X");
if (res != ND4J_STATUS_OK)
throw std::runtime_error("Failed to apply Conv3D");
}
STORE_RESULT(*output);
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(conv3d) {
// REQUIRE_TRUE(output->sizeAt(0) == input->sizeAt(0) && output->sizeAt(1) == nOutputPlane && output->sizeAt(2) == outputDepth && output->sizeAt(3) == outputHeight && output->sizeAt(4) == outputWidth, 0,
// "Expected output shape: [%i, %i, %i, %i, %i] but got [%i, %i, %i, %i, %i] instead", input->sizeAt(0), nOutputPlane, outputDepth, outputHeight, outputWidth, output->sizeAt(0), output->sizeAt(1), output->sizeAt(2), output->sizeAt(3), output->sizeAt(4));
auto inputShapeInfo = inputShape->at(0);
auto weightShapeInfo = inputShape->at(1);
int rank = inputShapeInfo[0]; // = 5
int bS = inputShapeInfo[1];
int inputDepth = inputShapeInfo[3];
int inputHeight = inputShapeInfo[4];
int inputWidth = inputShapeInfo[5];
int nOutputPlane = weightShapeInfo[1];
int kT = weightShapeInfo[3];
int kH = weightShapeInfo[4];
int kW = weightShapeInfo[5];
int dT = INT_ARG(1);
int dW = INT_ARG(2);
int dH = INT_ARG(3);
int outputDepth = (inputDepth - kT) / dT + 1;
int outputHeight = (inputHeight - kH) / dH + 1;
int outputWidth = (inputWidth - kW) / dW + 1;
int shapeInfoLength = rank*2 + 4;
char order = (char)(inputShapeInfo[shapeInfoLength-1]);
Nd4jLong *newShapeInfo = nullptr;
ALLOCATE(newShapeInfo, block.getWorkspace(), shapeInfoLength, Nd4jLong);
newShapeInfo[0] = rank;
newShapeInfo[1] = bS;
newShapeInfo[2] = nOutputPlane;
newShapeInfo[3] = outputDepth;
newShapeInfo[4] = outputHeight;
newShapeInfo[5] = outputWidth;
shape::updateStrides(newShapeInfo, order);
return SHAPELIST(newShapeInfo);
}
//////////////////////////////////////////////////////////////////////////
CONFIGURABLE_OP_IMPL(conv3d_bp, 3, 1, false, 0, 7) {
return ND4J_STATUS_OK;
}
}
}
#endif | 38.709402 | 266 | 0.50541 | [
"shape"
] |
3c0bd4adfa38c0bc93fc0704be5f902bfed1c301 | 1,233 | cpp | C++ | openmmapi/src/ANN_ForceImpl.cpp | weiHelloWorld/ANN_Force | 1fe5abe7fbc9b3b64b7ae135f6039dbca59bd1b8 | [
"MIT"
] | 5 | 2018-06-02T18:55:16.000Z | 2020-11-18T05:43:46.000Z | openmmapi/src/ANN_ForceImpl.cpp | weiHelloWorld/ANN_Force | 1fe5abe7fbc9b3b64b7ae135f6039dbca59bd1b8 | [
"MIT"
] | 1 | 2018-02-24T09:51:21.000Z | 2018-02-24T10:23:58.000Z | openmmapi/src/ANN_ForceImpl.cpp | weiHelloWorld/ANN_Force | 1fe5abe7fbc9b3b64b7ae135f6039dbca59bd1b8 | [
"MIT"
] | 2 | 2017-10-23T19:12:56.000Z | 2020-05-24T19:12:52.000Z | #include "openmm/internal/ContextImpl.h"
#include "openmm/Platform.h"
#include <set>
#include "openmm/internal/ANN_ForceImpl.h"
#include "openmm/ANN_Kernels.h"
#include "openmm/OpenMMException.h"
#include <cmath>
using namespace OpenMM;
using std::pair;
using std::vector;
using std::set;
ANN_ForceImpl::ANN_ForceImpl(const ANN_Force& owner) : owner(owner) {
}
ANN_ForceImpl::~ANN_ForceImpl() {
}
void ANN_ForceImpl::initialize(ContextImpl& context) {
kernel = context.getPlatform().createKernel(CalcANN_ForceKernel::Name(), context);
kernel.getAs<CalcANN_ForceKernel>().initialize(context.getSystem(), owner);
}
double ANN_ForceImpl::calcForcesAndEnergy(ContextImpl& context, bool includeForces, bool includeEnergy, int groups) {
if ((groups&(1<<owner.getForceGroup())) != 0)
return kernel.getAs<CalcANN_ForceKernel>().execute(context, includeForces, includeEnergy);
return 0.0;
}
std::vector<std::string> ANN_ForceImpl::getKernelNames() {
std::vector<std::string> names;
names.push_back(CalcANN_ForceKernel::Name());
return names;
}
void ANN_ForceImpl::updateParametersInContext(ContextImpl& context) {
kernel.getAs<CalcANN_ForceKernel>().copyParametersToContext(context, owner);
}
| 29.357143 | 117 | 0.752636 | [
"vector"
] |
3c12c013318823c6311c661527794ff3f742e58e | 4,460 | cpp | C++ | JsonBuilder.cpp | Aliw7979/Jason-Builder | 72e573ba74a7837ce24f36f2e208ad058152360a | [
"MIT"
] | null | null | null | JsonBuilder.cpp | Aliw7979/Jason-Builder | 72e573ba74a7837ce24f36f2e208ad058152360a | [
"MIT"
] | null | null | null | JsonBuilder.cpp | Aliw7979/Jason-Builder | 72e573ba74a7837ce24f36f2e208ad058152360a | [
"MIT"
] | null | null | null | #include"JsonBuilder.hpp"
#include"Object.hpp"
#include"StrData.hpp"
#include"IntData.hpp"
#include"Defines.hpp"
void JsonBuilder::print(int id)
{
std::vector<AllObjects*>temp_of_all_objects = all_objects;
if (id == MOTHER_OBJECT) {
for (int i = 0; i < temp_of_all_objects.size(); i++) {
temp_of_all_objects[i]->print(temp_of_all_objects);
}
}
else {
for (int i = 0; i < temp_of_all_objects.size(); i++) {
if (id == temp_of_all_objects[i]->get_id()) {
temp_of_all_objects[i]->print(temp_of_all_objects);
break;
}
}
}
}
int JsonBuilder::id_creator()
{
srand((unsigned)time(0));
int all_ids_temp = rand() % 99999;
all_ids.push_back(all_ids_temp);
return all_ids_temp;
}
int JsonBuilder::addContainerToArray(int parent_id, std::string type)
{
int temp_id;
int created_id;
if (parent_id == MOTHER_OBJECT) {
created_id = id_creator();
Object * new_object = new Object(created_id, type, DEFAULT_KEY);
all_objects.push_back(new_object);
}
else {
for (int i = 0; i < all_objects.size(); i++) {
if (all_objects[i]->get_id() == parent_id) {
created_id = id_creator();
temp_id = i;
Object * new_object = new Object(created_id, type, DEFAULT_KEY);
all_objects.push_back(new_object);
all_objects[temp_id]->nested_id_collector(created_id);
break;
}
}
}
return created_id;
}
void JsonBuilder::addStringToArray(int parent_id, std::string value)
{
int created_id;
int temp_id;
for (int i = 0; i < all_objects.size(); i++) {
if (all_objects[i]->get_id() == parent_id) {
temp_id = i;
created_id = id_creator();
StrData *new_str_data = new StrData(value, DEFAULT_KEY,created_id);
all_objects.push_back(new_str_data);
all_objects[temp_id]->nested_id_collector(created_id);
break;
}
}
}
void JsonBuilder::addIntegerToArray(int parent_id, int value)
{
int created_id;
int temp_id;
for (int i = 0; i < all_objects.size(); i++) {
if (all_objects[i]->get_id() == parent_id) {
temp_id = i;
created_id = id_creator();
IntData *new_str_data = new IntData(value, DEFAULT_KEY,created_id);
all_objects.push_back(new_str_data);
all_objects[temp_id]->nested_id_collector(created_id);
break;
}
}
}
void JsonBuilder::addStringToObject(int parent_id, std::string key, std::string value)
{
int created_id;
int counter;
int temp_id;
if (parent_id == MOTHER_OBJECT) {
created_id = id_creator();
StrData *new_str_data = new StrData(value, key,created_id);
all_objects.push_back(new_str_data);
}
else {
for (int i = 0; i < all_objects.size(); i++) {
if (all_objects[i]->get_id() == parent_id) {
temp_id = i;
created_id = id_creator();
StrData *new_str_data = new StrData(value, key,created_id);
all_objects.push_back(new_str_data);
all_objects[temp_id]->nested_id_collector(created_id);
counter = 1;
break;
}
}
if (counter != 1) {
created_id = id_creator();
StrData *new_str_data = new StrData(value, key,created_id);
all_objects.push_back(new_str_data);
}
}
}
void JsonBuilder::addIntegerToObject(int parent_id, std::string key, int value)
{
int created_id;
int temp_id;
if (parent_id == MOTHER_OBJECT) {
created_id = id_creator();
IntData *new_str_data = new IntData(value, key,created_id);
all_objects.push_back(new_str_data);
}
else {
for (int i = 0; i < all_objects.size(); i++) {
if (all_objects[i]->get_id() == parent_id) {
temp_id = i;
created_id = id_creator();
IntData *new_str_data = new IntData(value, key,created_id);
all_objects.push_back(new_str_data);
all_objects[temp_id]->nested_id_collector(created_id);
break;
}
else {
created_id = id_creator();
IntData *new_str_data = new IntData(value, key,created_id);
all_objects.push_back(new_str_data);
}
}
}
}
int JsonBuilder::addContainerToObject(int parent_id, std::string key, std::string type)
{
int temp_id;
int created_id;
if (parent_id == MOTHER_OBJECT) {
created_id = id_creator();
Object * new_object = new Object(created_id, type, key);
all_objects.push_back(new_object);
}
else {
for (int i = 0; i < all_objects.size(); i++) {
if (all_objects[i]->get_id() == parent_id) {
created_id = id_creator();
temp_id = i;
Object * new_object = new Object(created_id, type, key);
all_objects.push_back(new_object);
all_objects[temp_id]->nested_id_collector(all_objects.size() - 1);
break;
}
}
}
return created_id;
}
| 25.19774 | 87 | 0.684529 | [
"object",
"vector"
] |
3c1b34914c55d1d7aaaa2b0eb02a359cfe258579 | 4,813 | cpp | C++ | Physics3D_class5_solution/PhysVehicle3D.cpp | lucho1/GreedyCrash-Project | b870e582f8459978a9af5b21185479b587d3795e | [
"MIT"
] | null | null | null | Physics3D_class5_solution/PhysVehicle3D.cpp | lucho1/GreedyCrash-Project | b870e582f8459978a9af5b21185479b587d3795e | [
"MIT"
] | null | null | null | Physics3D_class5_solution/PhysVehicle3D.cpp | lucho1/GreedyCrash-Project | b870e582f8459978a9af5b21185479b587d3795e | [
"MIT"
] | null | null | null | #include "PhysVehicle3D.h"
#include "Primitive.h"
#include "Bullet/include/btBulletDynamicsCommon.h"
#include "ModuleInput.h"
#include "Application.h"
// ----------------------------------------------------------------------------
VehicleInfo::~VehicleInfo()
{
//if(wheels != NULL)
//delete wheels;
}
// ----------------------------------------------------------------------------
PhysVehicle3D::PhysVehicle3D(btRigidBody* body, btRaycastVehicle* vehicle, const VehicleInfo& info) : PhysBody3D(body), vehicle(vehicle), info(info)
{
}
// ----------------------------------------------------------------------------
PhysVehicle3D::~PhysVehicle3D()
{
delete vehicle;
}
// ----------------------------------------------------------------------------
void PhysVehicle3D::Render()
{
Cylinder wheel;
wheel.color = Green;
for(int i = 0; i < vehicle->getNumWheels(); ++i)
{
wheel.radius = info.wheels[0].radius;
wheel.height = info.wheels[0].width;
vehicle->updateWheelTransform(i);
vehicle->getWheelInfo(i).m_worldTransform.getOpenGLMatrix(&wheel.transform);
wheel.Render();
}
chassis = Cube(info.chassis_size.x, info.chassis_size.y, info.chassis_size.z);
vehicle->getChassisWorldTransform().getOpenGLMatrix(&chassis.transform);
btQuaternion q = vehicle->getChassisWorldTransform().getRotation();
btVector3 offset(info.chassis_offset.x, info.chassis_offset.y, info.chassis_offset.z);
offset = offset.rotate(q.getAxis(), q.getAngle());
chassis.transform.M[12] += offset.getX();
chassis.transform.M[13] += offset.getY();
chassis.transform.M[14] += offset.getZ();
chassis.color = info.color;
cabina = Cube(3, 1, 5);
vehicle->getChassisWorldTransform().getOpenGLMatrix(&cabina.transform);
btVector3 cabina_offset(0, 3, 0);
cabina_offset = cabina_offset.rotate(q.getAxis(), q.getAngle());
cabina.transform.M[12] += cabina_offset.getX();
cabina.transform.M[13] += cabina_offset.getY();
cabina.transform.M[14] += cabina_offset.getZ();
cabina.color.Set(0, 1, 1);
light1 = Cube(0.8, 0.5, 0.5);
vehicle->getChassisWorldTransform().getOpenGLMatrix(&light1.transform);
btVector3 light1_offset(1.5, 2.4, 4.1);
light1_offset = light1_offset.rotate(q.getAxis(), q.getAngle());
light1.transform.M[12] += light1_offset.getX();
light1.transform.M[13] += light1_offset.getY();
light1.transform.M[14] += light1_offset.getZ();
light2 = Cube(0.8, 0.5, 0.5);
vehicle->getChassisWorldTransform().getOpenGLMatrix(&light2.transform);
btVector3 light2_offset(-1.5, 2.4, 4.1);
light2_offset = light2_offset.rotate(q.getAxis(), q.getAngle());
light2.transform.M[12] += light2_offset.getX();
light2.transform.M[13] += light2_offset.getY();
light2.transform.M[14] += light2_offset.getZ();
light3 = Cube(0.8, 0.5, 0.5);
vehicle->getChassisWorldTransform().getOpenGLMatrix(&light3.transform);
btVector3 light3_offset(-1.5, 2.4, -4.1);
light3_offset = light3_offset.rotate(q.getAxis(), q.getAngle());
light3.transform.M[12] += light3_offset.getX();
light3.transform.M[13] += light3_offset.getY();
light3.transform.M[14] += light3_offset.getZ();
light4 = Cube(0.8, 0.5, 0.5);
vehicle->getChassisWorldTransform().getOpenGLMatrix(&light4.transform);
btVector3 light4_offset(1.5, 2.4, -4.1);
light4_offset = light4_offset.rotate(q.getAxis(), q.getAngle());
light4.transform.M[12] += light4_offset.getX();
light4.transform.M[13] += light4_offset.getY();
light4.transform.M[14] += light4_offset.getZ();
if (!forward){
light1.color.Set(0.5, 0.5, 0);
light2.color.Set(0.5, 0.5, 0);
light3.color.Set(1, 0, 0);
light4.color.Set(1, 0, 0);
}
if (forward) {
light1.color.Set(1, 1, 0);
light2.color.Set(1, 1, 0);
light3.color.Set(0.3, 0, 0);
light4.color.Set(0.3, 0, 0);
}
light3.Render();
light4.Render();
light2.Render();
light1.Render();
cabina.Render();
chassis.Render();
}
// ----------------------------------------------------------------------------
void PhysVehicle3D::ApplyEngineForce(float force)
{
for(int i = 0; i < vehicle->getNumWheels(); ++i)
{
if(info.wheels[i].drive == true)
{
vehicle->applyEngineForce(force, i);
}
}
}
// ----------------------------------------------------------------------------
void PhysVehicle3D::Brake(float force)
{
for(int i = 0; i < vehicle->getNumWheels(); ++i)
{
if(info.wheels[i].brake == true)
{
vehicle->setBrake(force, i);
}
}
}
// ----------------------------------------------------------------------------
void PhysVehicle3D::Turn(float degrees)
{
for(int i = 0; i < vehicle->getNumWheels(); ++i)
{
if(info.wheels[i].steering == true)
{
vehicle->setSteeringValue(degrees, i);
}
}
}
// ----------------------------------------------------------------------------
float PhysVehicle3D::GetKmh() const
{
return vehicle->getCurrentSpeedKmHour();
}
| 27.820809 | 148 | 0.603366 | [
"render",
"transform"
] |
3c1d1e6c5e768cd106ac1d3479d667422c8ffd79 | 18,131 | cc | C++ | tests/commands.cc | klaasjacobdevries/lothar | 38ad3e4e0552abaff253e77c4a6cf0657d920196 | [
"MIT"
] | 2 | 2016-07-23T13:05:10.000Z | 2021-01-25T01:10:33.000Z | tests/commands.cc | klaasjacobdevries/lothar | 38ad3e4e0552abaff253e77c4a6cf0657d920196 | [
"MIT"
] | null | null | null | tests/commands.cc | klaasjacobdevries/lothar | 38ad3e4e0552abaff253e77c4a6cf0657d920196 | [
"MIT"
] | 1 | 2019-06-26T19:39:28.000Z | 2019-06-26T19:39:28.000Z | #include <gtest/gtest.h>
#include <string>
#include "commands.hh"
#include "error_handling.hh"
#include "connectionmock.hh"
using namespace std;
using namespace lothar;
using namespace testing;
namespace
{
// the payload is as a std::string just for the convenience of being able to type string literals
// be carefull with '\0' characters
vector<uint8_t> create_request(char code, bool reply, string const &payload)
{
vector<uint8_t> result;
result.push_back(reply ? '\0' : '\x80');
result.push_back(code);
for(string::const_iterator i = payload.begin(); i != payload.end(); ++i)
result.push_back(*i);
return result;
}
vector<uint8_t> create_reply(char code, string payload, char status = '\0')
{
vector<uint8_t> result;
result.push_back('\x02');
result.push_back(code);
result.push_back(status);
for(string::const_iterator i = payload.begin(); i != payload.end(); ++i)
result.push_back(*i);
return result;
}
}
TEST(CommandsTest, StatusByte)
{
uint8_t buf[2];
vector<uint8_t> const request = create_request(11, true, "");
vector<uint8_t> const reply = create_reply(11, string(buf, buf + 2));
ConnectionMock mock;
mock.expect_write(request);
mock.expect_read(reply);
EXPECT_NO_THROW(getbatterylevel(mock));
}
TEST(CommandsTest, StatusByteInsancePacket)
{
uint8_t buf[2];
vector<uint8_t> const request = create_request(11, true, "");
vector<uint8_t> reply = create_reply(11, string(buf, buf + 2));
reply[2] = LOTHAR_ERROR_INSANE_PACKET;
ConnectionMock mock;
mock.expect_write(request);
mock.expect_read(reply);
EXPECT_THROW(getbatterylevel(mock), lothar::Error);
}
TEST(CommandsTest, StartProgram)
{
ConnectionMock mock;
string filename = "12345678901234.123";
vector<uint8_t> request = create_request(0, false, filename);
request.push_back('\0');
// happy path
mock.expect_write(request);
startprogram(mock, filename.c_str());
}
TEST(CommandsTest, StartProgramNullFilename)
{
ConnectionMock mock;
EXPECT_CALL(mock, write(_, _)).
Times(0);
EXPECT_THROW(startprogram(mock, NULL), lothar::Error);
}
TEST(CommandsTest, StartProgramFilenameTooLong)
{
ConnectionMock mock;
EXPECT_CALL(mock, write(_, _)).
Times(0);
EXPECT_THROW(startprogram(mock, "12345678901234.1234"), lothar::Error);
}
TEST(CommandsTest, StopProgram)
{
ConnectionMock mock;
// only happy path, this can only do one thing
vector<uint8_t> const request = create_request(1, false, "");
mock.expect_write(request);
stopprogram(mock);
}
TEST(CommandsTest, PlaySoundFile)
{
ConnectionMock mock;
string filename = "12345678901234.123";
vector<uint8_t> request = create_request(2, false, "\x01" + filename);
request.push_back('\0');
mock.expect_write(request);
playsoundfile(mock, true, filename.c_str());
}
TEST(CommandsTest, PlaySoundFileNull)
{
ConnectionMock mock;
EXPECT_CALL(mock, write(_, _)).
Times(0);
// filename is null
EXPECT_THROW(playsoundfile(mock, true, NULL), lothar::Error);
}
TEST(CommandsTest, PlaySoundFileNameTooLong)
{
ConnectionMock mock;
EXPECT_CALL(mock, write(_, _)).
Times(0);
// filename too long
EXPECT_THROW(playsoundfile(mock, false, "12345678901234.1234"), lothar::Error);
}
TEST(CommandsTest, PlayTone)
{
ConnectionMock mock;
uint16_t const frequency = 500;
uint16_t const duration = 40000;
uint8_t freq[3] = {0, 0, 0};
uint8_t dur[3] = {0, 0, 0};
htonxts(frequency, freq);
htonxts(duration, dur);
vector<uint8_t> const request = create_request(3, false, string(freq, freq + 2) + string(dur, dur + 2));
mock.expect_write(request);
// happy
playtone(mock, frequency, duration);
}
TEST(CommandsTest, PlayToneFequencyBelowRange)
{
ConnectionMock mock;
uint16_t const given_frequency = 199; // will be clamped to 200
uint16_t const frequency = 200;
uint16_t const duration = 40000;
uint8_t freq[3] = {0, 0, 0};
uint8_t dur[3] = {0, 0, 0};
htonxts(frequency, freq);
htonxts(duration, dur);
vector<uint8_t> const request = create_request(3, false, string(freq, freq + 2) + string(dur, dur + 2));
mock.expect_write(request);
// happy
playtone(mock, given_frequency, duration);
}
TEST(CommandsTest, PlayToneFequencyAboveRange)
{
ConnectionMock mock;
uint16_t const given_frequency = 14001; // will be clamped to 14000
uint16_t const frequency = 14000;
uint16_t const duration = 40000;
uint8_t freq[3] = {0, 0, 0};
uint8_t dur[3] = {0, 0, 0};
htonxts(frequency, freq);
htonxts(duration, dur);
vector<uint8_t> const request = create_request(3, false, string(freq, freq + 2) + string(dur, dur + 2));
mock.expect_write(request);
// happy
playtone(mock, given_frequency, duration);
}
TEST(CommandsTest, SetOutputState)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(4, false,
string("\x01") + // port
string("\x14") + // power
string("\x01") + // motor on
string("\x01") + // requlation mode speed
string("\x14") + // turn ratio
string("\x10") + // run state (rampup)
string("\x01\x01\x01\x01")); // tacho limit (16843009)
// happy
mock.expect_write(request);
setoutputstate(mock,
OUTPUT_B,
20,
MOTOR_MODE_MOTORON,
REGULATION_MODE_SPEED,
20,
RUNSTATE_RAMPUP,
16843009);
}
TEST(CommandsTest, SetOutputStatePowerClamp)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(4, false,
string("\x01") + // port
string("\x64") + // power
string("\x01") + // motor on
string("\x01") + // requlation mode speed
string("\x14") + // turn ratio
string("\x10") + // run state (rampup)
string("\x01\x01\x01\x01")); // tacho limit (16843009)
// happy
mock.expect_write(request);
setoutputstate(mock,
OUTPUT_B,
101,
MOTOR_MODE_MOTORON,
REGULATION_MODE_SPEED,
20,
RUNSTATE_RAMPUP,
16843009);
}
TEST(CommandsTest, SetOutputStateTurnRatioClamp)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(4, false,
string("\x01") + // port
string("\x14") + // power
string("\x01") + // motor on
string("\x01") + // requlation mode speed
string("\x64") + // turn ratio
string("\x10") + // run state (rampup)
string("\x01\x01\x01\x01")); // tacho limit (16843009)
// happy
mock.expect_write(request);
setoutputstate(mock,
OUTPUT_B,
20,
MOTOR_MODE_MOTORON,
REGULATION_MODE_SPEED,
101,
RUNSTATE_RAMPUP,
16843009);
}
TEST(CommandsTest, SetInputMode)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(5, false,
string("\x01") + // port
string("\x01") + // type (switch)
string("\x20")); // mode (boolean)
// happy
mock.expect_write(request);
setinputmode(mock, INPUT_2, SENSOR_SWITCH, SENSOR_MODE_BOOLEANMODE);
}
TEST(CommandsTest, GetOutputState)
{
ConnectionMock mock;
uint32_t val = (1 << 24) | (2 << 16) | (3 << 8) | 4;
uint8_t buf[4];
htonxtl(val, buf);
vector<uint8_t> const request = create_request(6, true, string("\x01"));// port (B)
vector<uint8_t> const reply = create_reply(6,
string("\x01") + // port (B)
string("\x14") + // power (20)
string("\x01") + // mode (motor on)
string("\x01") + // regulation (speed)
string("\x14") + // turn ratio (20)
string("\x10") + // run state (rampup)
string(buf, buf + 4) + // tacho limit
string(buf, buf + 4) + // tacho count
string(buf, buf + 4) + // block tacho limit
string(buf, buf + 4)); // block tacho count
mock.expect_write(request);
mock.expect_read(reply);
int8_t power;
output_motor_mode motormode;
output_regulation_mode regulationmode;
uint8_t turnratio;
output_runstate runstate;
uint32_t tacholimit;
int32_t tachocount;
int32_t blocktachocount;
int32_t rotationcount;
getoutputstate(mock, OUTPUT_B, &power, &motormode, ®ulationmode, &turnratio, &runstate, &tacholimit, &tachocount, &blocktachocount, &rotationcount);
EXPECT_EQ(20, power);
EXPECT_EQ(MOTOR_MODE_MOTORON, motormode);
EXPECT_EQ(REGULATION_MODE_SPEED, regulationmode);
EXPECT_EQ(20, turnratio);
EXPECT_EQ(RUNSTATE_RAMPUP, runstate);
EXPECT_EQ(val, tacholimit);
EXPECT_EQ(static_cast<int32_t>(val), tachocount);
EXPECT_EQ(static_cast<int32_t>(val), blocktachocount);
EXPECT_EQ(static_cast<int32_t>(val), rotationcount);
}
TEST(CommandsTest, GetInputValues)
{
ConnectionMock mock;
uint16_t val = (1 << 8) | 2;
uint8_t buf[2];
htonxts(val, buf);
vector<uint8_t> const request = create_request(7, true, string("\x01")); // INPUT_2
vector<uint8_t> const reply = create_reply(7,
string("\x01") + // port (2)
string("\x01") + // valid (true)
string("\x01") + // calibrated (true)
string("\x01") + // type (switch)
string("\x20") + // mode (boolean)
string(buf, buf + 2) + // raw
string(buf, buf + 2) + // normalized
string(buf, buf + 2) + // scaled
string(buf, buf + 2)); // calibrated
mock.expect_write(request);
mock.expect_read(reply);
bool valid = false;
bool calibrated = false;
sensor_type type = SENSOR_NO_SENSOR;
sensor_mode mode = SENSOR_MODE_RAWMODE;
uint16_t raw = 0;
uint16_t norm = 0;
int16_t scaled = 0;
int16_t cal = 0;
getinputvalues(mock, INPUT_2, &valid, &calibrated, &type, &mode, &raw, &norm, &scaled, &cal);
EXPECT_TRUE(valid);
EXPECT_TRUE(calibrated);
EXPECT_EQ(SENSOR_SWITCH, type);
EXPECT_EQ(SENSOR_MODE_BOOLEANMODE, mode);
EXPECT_EQ(val, raw);
EXPECT_EQ(val, norm);
EXPECT_EQ(val, scaled);
EXPECT_EQ(val, cal);
}
TEST(CommandsTest, ResetInputScaledValue)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(8, false, string("\x02")); // INPUT_3
mock.expect_write(request);
resetinputscaledvalue(mock, INPUT_3);
}
TEST(CommandsTest, MessageWrite)
{
ConnectionMock mock;
string const message = "1234567890";
vector<uint8_t> const request = create_request(9, false, string("\x05\x0A") + message);
mock.expect_write(request);
messagewrite(mock, 5, reinterpret_cast<uint8_t const *>(message.data()), message.size());
}
TEST(CommandsTest, MessageWriteEmpty)
{
ConnectionMock mock;
vector<uint8_t> request = create_request(9, false, string("\x05"));
request.push_back('\0');
mock.expect_write(request);
messagewrite(mock, 5, NULL, 0);
}
TEST(CommandsTest, MessageWriteMaximumSize)
{
ConnectionMock mock;
string const message = "12345678901234567890123456789012345678901234567890123456789";
vector<uint8_t> const request = create_request(9, false, string("\x05\x3B") + message);
mock.expect_write(request);
messagewrite(mock, 5, reinterpret_cast<uint8_t const *>(message.data()), message.size());
}
TEST(CommandsTest, MessageWriteMoreThanMaximumSize)
{
ConnectionMock mock;
string const message = "123456789012345678901234567890123456789012345678901234567890";
EXPECT_CALL(mock, write(_, _)).
Times(0);
EXPECT_THROW(
messagewrite(mock, 9, reinterpret_cast<uint8_t const *>(message.data()), message.size()),
lothar::Error);
}
TEST(CommandsTest, MessageWriteInvalidInbox)
{
ConnectionMock mock;
string const message = "1234567890";
vector<uint8_t> const request = create_request(9, false, string("\x05\x0A") + message);
EXPECT_CALL(mock, write(_, _)).
Times(0);
EXPECT_THROW(
messagewrite(mock, 11, reinterpret_cast<uint8_t const *>(message.data()), message.size()),
lothar::Error);
}
TEST(CommandsTest, ResetMotorPosition)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(10, false, string("\x02\x01"));
mock.expect_write(request);
resetmotorposition(mock, OUTPUT_C, true);
}
TEST(CommandsTest, GetBatteryLevel)
{
ConnectionMock mock;
uint16_t val = 8000;
uint8_t buf[2];
htonxts(val, buf);
vector<uint8_t> const request = create_request(11, true, "");
vector<uint8_t> const reply = create_reply(11, string(buf, buf + 2));
mock.expect_write(request);
mock.expect_read(reply);
uint16_t level = getbatterylevel(mock);
EXPECT_EQ(val, level);
}
TEST(CommandsTest, StopSoundPlayback)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(12, false, "");
mock.expect_write(request);
stopsoundplayback(mock);
}
TEST(CommandsTest, KeepAlive)
{
ConnectionMock mock;
uint32_t val = (1 << 24) | (2 << 16) | (3 << 8) | 4;
uint8_t buf[4];
htonxtl(val, buf);
vector<uint8_t> const request = create_request(13, true, "");
vector<uint8_t> const reply = create_reply(13, string(buf, buf + 4));
mock.expect_write(request);
mock.expect_read(reply);
uint32_t sleeptime = keepalive(mock);
EXPECT_EQ(val, sleeptime);
}
TEST(CommandsTest, LSGetStatus)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(14, true, "\x01");
vector<uint8_t> const reply = create_reply(14, "\x14");
mock.expect_write(request);
mock.expect_read(reply);
uint8_t ls = lsgetstatus(mock, INPUT_2);
EXPECT_EQ(20, ls);
}
TEST(CommandsTest, LSWrite)
{
ConnectionMock mock;
string const txdata = "1234567890123456";
vector<uint8_t> const request = create_request(15, false, string("\x01\x10\x10") + txdata);
mock.expect_write(request);
lswrite(mock, INPUT_2, reinterpret_cast<uint8_t const *>(txdata.data()), txdata.size(), 16);
}
TEST(CommandsTest, LSWriteDataTooBig)
{
ConnectionMock mock;
string const txdata = "12345678901234567";
EXPECT_THROW(
lswrite(mock, INPUT_2, reinterpret_cast<uint8_t const *>(txdata.data()), txdata.size(), 17),
lothar::Error);
}
TEST(CommandsTest, LSWriteEmpty)
{
ConnectionMock mock;
vector<uint8_t> request = create_request(15, false, string("\x01\x01\x10"));
request[3] = '\0';
mock.expect_write(request);
lswrite(mock, INPUT_2, NULL, 0, 16);
}
TEST(CommandsTest, LSRead)
{
ConnectionMock mock;
string const data = "1234567890123456";
vector<uint8_t> request = create_request(16, true, string("\x01"));
vector<uint8_t> reply = create_reply(16, string("\x10") + data);
mock.expect_write(request);
mock.expect_read(reply);
uint8_t rxdata[16];
uint8_t rxlen;
lsread(mock, INPUT_2, rxdata, sizeof(rxdata), &rxlen);
}
TEST(CommandsTest, LSReadOverflow)
{
ConnectionMock mock;
string const data = "1234567890123456";
vector<uint8_t> request = create_request(16, true, string("\x01"));
vector<uint8_t> reply = create_reply(16, string("\x10") + data);
mock.expect_write(request);
mock.expect_read(reply);
uint8_t rxdata[10];
uint8_t rxlen;
EXPECT_THROW(lsread(mock, INPUT_2, rxdata, sizeof(rxdata), &rxlen),
lothar::Error);
}
TEST(CommandsTest, GetCurrentProgramMame)
{
ConnectionMock mock;
string const filename = "12345678901234.123";
vector<uint8_t> request = create_request(17, true, "");
vector<uint8_t> reply = create_reply(17, filename);
reply.push_back('\0');
mock.expect_write(request);
mock.expect_read(reply);
char cfilename[19];
getcurrentprogramname(mock, cfilename);
EXPECT_STREQ(filename.c_str(), cfilename);
}
TEST(CommandsTest, MessageRead)
{
ConnectionMock mock;
vector<uint8_t> const request = create_request(19, true,
string("\x01") + // remote inbox (1)
string("\x02") + // local inbox (2)
string("\x01")); // remove (true)
string const message = "12345678901234567890123456789012345678901234567890123456789";
vector<uint8_t> const reply = create_reply(19, string("\x02\x3B") + message);
mock.expect_write(request);
mock.expect_read(reply);
uint8_t data[59];
uint8_t len = 0;
messageread(mock, 1, 2, true, data, &len);
EXPECT_EQ(message.size(), len);
EXPECT_EQ(message, string(data, data + len));
}
| 29.102729 | 153 | 0.599195 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.