hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | 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 260 | max_issues_repo_name stringlengths 5 109 | 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 260 | max_forks_repo_name stringlengths 5 109 | 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 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c435b80427e33659bf04672a165b0e478061080 | 1,535 | h | C | spoopy/tools/vole/source/olderfiles/illumestimators/fusion/average/averagefusion.h | rodrigobressan/PADify | 362db2b3a33793ac53f938e89f90a6ecdf778e89 | [
"MIT"
] | 12 | 2019-11-26T07:44:08.000Z | 2021-03-03T09:51:43.000Z | spoopy/tools/vole/source/illumestimators/fusion/average/averagefusion.h | rodrigobressan/PADify | 362db2b3a33793ac53f938e89f90a6ecdf778e89 | [
"MIT"
] | 13 | 2020-01-28T22:09:41.000Z | 2022-03-11T23:43:37.000Z | spoopy/tools/vole/source/illumestimators/fusion/average/averagefusion.h | rodrigobressan/PADify | 362db2b3a33793ac53f938e89f90a6ecdf778e89 | [
"MIT"
] | 5 | 2020-01-02T09:52:42.000Z | 2022-02-21T15:45:23.000Z | #ifndef ILLUMESTIMATORS_FUSION_AVERAGE_AVERAGEFUSION_H
#define ILLUMESTIMATORS_FUSION_AVERAGE_AVERAGEFUSION_H
#include "fusion/fusion.h"
namespace illumestimators {
class AverageFusion : public Fusion
{
public:
enum Method { AVERAGE, LEAVE_N_OUT };
public:
AverageFusion(const std::vector<IlluminantEstimator*>& estimators, Method method = AVERAGE, int n = 0);
~AverageFusion();
public:
std::string name() const;
std::string identifier() const;
public:
using IlluminantEstimator::estimateIlluminant;
Illum estimateIlluminant(const cv::Mat_<cv::Vec3d>& image, const cv::Mat_<unsigned char>& mask) const;
Illum estimateIlluminant(const cv::Mat_<cv::Vec3d>& image, const std::vector<cv::Point>& superpixel, const cv::Mat_<unsigned char>& mask) const;
Illum estimateIlluminant(const std::vector<cv::Vec3d>& estimates) const;
public:
bool train(const std::vector<std::string>& imageFiles, const std::vector<std::string>& colorspaces, const std::vector<cv::Vec3d>& illuminants, const std::vector<std::string>& maskFiles = std::vector<std::string>());
virtual void preprocessImage(const cv::Mat_<cv::Vec3d>& image, const cv::Mat_<unsigned char>& mask, cv::Mat_<cv::Vec3d> &outputImage, cv::Mat_<unsigned char> &outputMask) const;
public:
bool save(const std::string& filename) const;
bool load(const std::string& filename);
virtual int error(); // dummy implementation - returns always 0
private:
Method m_method;
int m_n;
};
} // namespace illumestimators
#endif // ILLUMESTIMATORS_FUSION_AVERAGE_AVERAGEFUSION_H
| 34.111111 | 216 | 0.762215 | [
"vector"
] |
1c49d0707e814c62bfad8a6e54d48943eebc03ac | 2,064 | h | C | src/RVConditionalPrior.h | Kamuish/kima | 158fbddf5867b433d7b97f9d4766aa67a22aafaf | [
"MIT"
] | null | null | null | src/RVConditionalPrior.h | Kamuish/kima | 158fbddf5867b433d7b97f9d4766aa67a22aafaf | [
"MIT"
] | null | null | null | src/RVConditionalPrior.h | Kamuish/kima | 158fbddf5867b433d7b97f9d4766aa67a22aafaf | [
"MIT"
] | null | null | null | // (c) 2019 João Faria
// This file is part of kima, which is licensed under the MIT license (see LICENSE for details)
#ifndef DNest4_RVConditionalPrior
#define DNest4_RVConditionalPrior
#include <memory>
#include "RNG.h"
#include "RJObject/ConditionalPriors/ConditionalPrior.h"
#include "DNest4.h"
/// whether the model includes hyper-priors for the orbital period and semi-amplitude
extern const bool hyperpriors;
class RVConditionalPrior:public DNest4::ConditionalPrior
{
private:
// Parameters of bi-exponential hyper-distribution for log-periods
double center, width;
// Mean of exponential hyper-distribution for semi-amplitudes
double muK;
double perturb_hyperparameters(DNest4::RNG& rng);
public:
RVConditionalPrior();
// priors for all planet parameters
/// Prior for the orbital periods.
std::shared_ptr<DNest4::ContinuousDistribution> Pprior;
/// Prior for the semi-amplitudes (in m/s).
std::shared_ptr<DNest4::ContinuousDistribution> Kprior;
/// Prior for the eccentricities.
std::shared_ptr<DNest4::ContinuousDistribution> eprior;
/// Prior for the phases.
std::shared_ptr<DNest4::ContinuousDistribution> phiprior;
/// Prior for the .
std::shared_ptr<DNest4::ContinuousDistribution> wprior;
// hyperpriors
/// Prior for the log of the median orbital period
std::shared_ptr<DNest4::ContinuousDistribution> log_muP_prior;
/// Prior for the diversity of orbital periods
std::shared_ptr<DNest4::ContinuousDistribution> wP_prior;
/// Prior for the log of the mean semi-amplitude
std::shared_ptr<DNest4::ContinuousDistribution> log_muK_prior;
/// Generate a point from the prior.
void from_prior(DNest4::RNG& rng);
double log_pdf(const std::vector<double>& vec) const;
/// Get parameter sample from a uniform sample (CDF)
void from_uniform(std::vector<double>& vec) const;
/// Get uniform sample from a parameter sample (inverse CDF)
void to_uniform(std::vector<double>& vec) const;
void print(std::ostream& out) const;
static const int weight_parameter = 1;
};
#endif
| 30.352941 | 95 | 0.752422 | [
"vector",
"model"
] |
1c526a7938a85fe155d84ac3e7325d1a4a6415d8 | 11,804 | h | C | PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctnQ3D.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctnQ3D.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctnQ3D.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | ///
/// \file AliFemtoCorrFctnQ3D.h
///
#pragma once
#ifndef ALIFEMTOCORRFCTNQ3D_H
#define ALIFEMTOCORRFCTNQ3D_H
#include "AliFemtoCorrFctn.h"
#include "AliFemtoPairCut.h"
#include <TH3F.h>
#include <TProfile3D.h>
#if __cplusplus >= 201103L
#include <tuple>
#define USE_TUPLE
#endif
/// \class AliFemtoCorrFctnQ3D
/// \brief A class to calculate 3D correlation functions for pairs
/// of identical particles vs. Bertsh-Pratt coordinates
///
/// It is recommended that you use one of the concrete classes which
/// bind this templated class to a frame-of-reference.
///
/// * AliFemtoCorrFctnQ3DLCMS
/// * AliFemtoCorrFctnQ3DBF
/// * AliFemtoCorrFctnQ3DPF
///
/// This is templated to enable custom calculation of the out, side,
/// long coordinates by writing a class (struct) with the static
/// methods `GetQ` and `FrameName` (look to the femtoQ3D namespace for
/// example implementation).
/// I would rather use std::tuple to return the three components,
/// (expanded with std::tie) but at this time we cannot support
/// c++11/ROOT6, so I use mutable references.
///
/// \author Andrew Kubera, Ohio State University <andrew.kubera@cern.ch>
///
template <typename Frame_t>
class AliFemtoCorrFctnQ3D : public AliFemtoCorrFctn {
public:
/// Build parameter object for easy & explicit construction
struct Build {
TString name;
UInt_t nbins;
Float_t qmax;
Bool_t use_simple_name;
Bool_t use_tprofile;
Bool_t single_qinv_hist;
#define IMPL(__name, __type, __param) \
Build __name(const __type p) const \
{ Build b(*this); b.__param = p; return b; }
IMPL(Name, TString, name);
IMPL(Title, TString, name);
IMPL(Bins, UInt_t, nbins);
IMPL(QMax, float, qmax);
IMPL(UseSimpleNaming, bool, use_simple_name);
IMPL(UseTProfile, bool, use_tprofile);
IMPL(SingleQinvHist, bool, single_qinv_hist);
#undef IMPL
Build()
: name("Q3D")
, nbins(59)
, qmax(.295)
, use_simple_name(true)
, use_tprofile(false)
, single_qinv_hist(true)
{ }
AliFemtoCorrFctnQ3D<Frame_t> into() const
{ return AliFemtoCorrFctnQ3D<Frame_t>(name, nbins, qmax, use_simple_name, single_qinv_hist, use_tprofile); }
AliFemtoCorrFctnQ3D<Frame_t>* into_ptr() const
{ return new AliFemtoCorrFctnQ3D<Frame_t>(name, nbins, qmax, use_simple_name, single_qinv_hist, use_tprofile); }
operator AliFemtoCorrFctnQ3D<Frame_t>() const
{ return into(); }
operator AliFemtoCorrFctnQ3D<Frame_t>*() const
{ return into_ptr(); }
};
/// Build the correlation function with parameters.
///
/// \param title The title with which to give the output
/// \param nbins The number of bins in each direction of q{out,side,long}
/// \param QHi The limit of each axis
/// \param simple_name - do not append title to the beginning of the name
///
AliFemtoCorrFctnQ3D(const char* title,
const int nbins,
const float QHi,
const bool simple_name=true,
const bool single_qinv_hist=true,
const bool use_tprofile=false);
/// Copy Constructor
AliFemtoCorrFctnQ3D(const AliFemtoCorrFctnQ3D<Frame_t>&);
/// Assignment - clone histograms
AliFemtoCorrFctnQ3D& operator=(const AliFemtoCorrFctnQ3D<Frame_t>&);
/// Deletes histograms
virtual ~AliFemtoCorrFctnQ3D();
virtual AliFemtoCorrFctn* Clone() const
{ return new AliFemtoCorrFctnQ3D<Frame_t>(*this); }
virtual AliFemtoString Report();
virtual void AddRealPair(AliFemtoPair* pair)
{ AddRealPair(const_cast<const AliFemtoPair&>(*pair)); }
virtual void AddMixedPair(AliFemtoPair *pair)
{ AddMixedPair(const_cast<const AliFemtoPair&>(*pair)); }
void AddRealPair(const AliFemtoPair &pair)
{ AddPair(pair, *fNumerator, *fNumeratorW); }
void AddMixedPair(const AliFemtoPair &pair)
{ AddPair(pair, *fDenominator, fDenominatorW ? *fDenominatorW : *fNumeratorW); }
/// Remove underflow-overflow contents to improve compressed file size
virtual void Finish()
{ // no-op
}
/// Return denominator
TH3& Numerator()
{ return *fNumerator; }
/// Return denominator
TH3& Denominator()
{ return *fDenominator; }
/// Return bins weighed by qinv (Numerator + Denominator)
/// -- NULL if using two histograms
TH3* QinvW()
{ return fDenominatorW == nullptr ? fNumeratorW : nullptr; }
/// Return numerator weighed by qinv -- NULL if using one histogram
TH3* NumeratorW()
{ return fDenominatorW == nullptr ? nullptr : fNumeratorW; }
/// Return denominator weighed by qinv -- NULL if using one histogram
TH3* DenominatorW()
{ return fDenominatorW; }
virtual TList* GetOutputList()
{
TList *list = new TList();
AddOutputObjectsTo(*list);
return list;
}
virtual void AddOutputObjectsTo(TCollection &dest)
{
dest.Add(fNumerator);
dest.Add(fDenominator);
dest.Add(fNumeratorW);
if (fDenominatorW) {
dest.Add(fDenominatorW);
}
}
/// Load 3D q-vector components into variables
static void GetQ(const AliFemtoPair &pair, double &out, double &side, double &lon);
#ifdef USE_TUPLE
/// Return 3D q-vector components
std::tuple<double, double, double> GetQ(const AliFemtoPair &pair) const
{
double x, y, z;
GetQ(pair, x, y, z);
return std::make_tuple(x, y, z);
}
#endif
protected:
void AddPair(const AliFemtoPair &pair, TH3& dest, TH3& qinv)
{
if (fPairCut && !fPairCut->Pass(&pair)) {
return;
}
// auto [qout, qside, qlong] = Frame_t::GetQ(pair); // maybe someday...
double qout, qside, qlong;
Frame_t::GetQ(pair, qout, qside, qlong);
Int_t bin = dest.FindBin(qout, qlong, qside);
if (!(dest.IsBinOverflow(bin) or dest.IsBinUnderflow(bin))) {
dest.Fill(qout, qside, qlong);
qinv.Fill(qout, qside, qlong, pair.QInv());
}
}
TH3F* fNumerator; ///<!< Numerator
TH3F* fDenominator; ///<!< Denominator
TH3* fNumeratorW; ///<!< Qinv-Weighted numerator
TH3* fDenominatorW; ///<!< Qinv-Weighted denominator
};
template <typename T>
AliFemtoCorrFctnQ3D<T>::AliFemtoCorrFctnQ3D(const char* title,
const int nbins,
const float QHi,
const bool simple_name,
const bool single_qinv_hist,
const bool use_tprofile)
: AliFemtoCorrFctn()
, fNumerator(nullptr)
, fDenominator(nullptr)
, fNumeratorW(nullptr)
, fDenominatorW(nullptr)
{
TString hist_title = TString::Format("%s (Frame=%s); q_{out} (GeV); q_{side} (GeV); q_{long} (GeV)", title, T::FrameName());
TString hist_name = simple_name ? "" : title;
auto new_3d_hist = [&] (const TString name, const TString htitle)
{
return new TH3F(simple_name ? name : name + " " + title,
htitle + hist_title,
nbins, -QHi, QHi,
nbins, -QHi, QHi,
nbins, -QHi, QHi);
};
fNumerator = new_3d_hist("Num", "Numerator");
fDenominator = new_3d_hist("Den", "Denominator");
auto qinv_member_builder = [&] (const TString name, const TString htitle) -> TH3*
{
if (!use_tprofile) {
return new_3d_hist(name, htitle);
}
return new TProfile3D(simple_name ? name : name + " " + title,
htitle + hist_title,
nbins, -QHi, QHi,
nbins, -QHi, QHi,
nbins, -QHi, QHi);
};
// note: non-weighted histograms do not need Sumw2 - save space and time by not enabling
if (single_qinv_hist) {
fNumeratorW = qinv_member_builder("QinvW", "Q_{inv} Weights (divide by Num + Den)");
fNumeratorW->Sumw2();
} else {
fNumeratorW = qinv_member_builder("NumQinvW", "Q_{inv} Weighted Numerator");
fDenominatorW = qinv_member_builder("DenQinvW", "Q_{inv} Weighted Denominator");
fNumeratorW->Sumw2();
fDenominatorW->Sumw2();
}
}
template <typename T>
AliFemtoCorrFctnQ3D<T>::AliFemtoCorrFctnQ3D(const AliFemtoCorrFctnQ3D<T>& orig)
: AliFemtoCorrFctn(orig)
, fNumerator(new TH3F(*orig.fNumerator))
, fDenominator(new TH3F(*orig.fDenominator))
, fNumeratorW(static_cast<TH3*>(orig.fNumeratorW->Clone()))
, fDenominatorW(static_cast<TH3*>(orig.fDenominatorW ? orig.fDenominatorW->Clone() : nullptr))
{
}
template <typename T>
AliFemtoCorrFctnQ3D<T>&
AliFemtoCorrFctnQ3D<T>::operator=(const AliFemtoCorrFctnQ3D<T> &rhs)
{
if (this != &rhs) {
AliFemtoCorrFctn::operator=(rhs);
*fNumerator = *rhs.fNumerator;
*fDenominator = *rhs.fDenominator;
delete fNumeratorW;
fNumeratorW = static_cast<TH3*>(rhs.fNumeratorW->Clone());
delete fDenominatorW;
fDenominatorW = rhs.fDenominatorW ? static_cast<TH3*>(rhs.fDenominatorW->Clone()) : nullptr;
}
return *this;
}
template <typename T>
AliFemtoCorrFctnQ3D<T>::~AliFemtoCorrFctnQ3D()
{
delete fNumerator;
delete fDenominator;
delete fNumeratorW;
delete fDenominatorW;
}
template <typename T>
AliFemtoString
AliFemtoCorrFctnQ3D<T>::Report()
{
// Construct the report
AliFemtoString report
= AliFemtoString("Bertsch-Pratt 3D Correlation Function")
+ Form(" (Frame = %s) Report:\n", T::FrameName())
+ Form("Number of entries in numerator:\t%E\n", fNumerator->GetEntries())
+ Form("Number of entries in denominator:\t%E\n", fDenominator->GetEntries());
if (fPairCut) {
report += "Here is the PairCut specific to this CorrFctn\n";
report += fPairCut->Report();
} else {
report += "No PairCut specific to this CorrFctn\n";
}
return report;
}
#undef SINGLE_WQINV
/*
#ifdef USE_TUPLE
template <typename T>
void
AliFemtoCorrFctnQ3D<T>::GetQ(const AliFemtoPair &pair, double &x, double &y, double &z)
{
std::tie(x, y, z) = static_cast<T*>(this)->GetQ(pair);
}
#endif
*/
struct AliFemtoCorrFctnQ3DLCMS : public AliFemtoCorrFctnQ3D<AliFemtoCorrFctnQ3DLCMS> {
typedef AliFemtoCorrFctnQ3D<AliFemtoCorrFctnQ3DLCMS> Super;
typedef Super::Build Build;
AliFemtoCorrFctnQ3DLCMS(const Super::Build &b)
: Super(b.into())
{ }
AliFemtoCorrFctnQ3DLCMS(const char *name, int x, float y, bool b=true)
: Super(name, x, y, b)
{ }
static void GetQ(const AliFemtoPair &pair, double &x, double &y, double &z)
{
x = pair.QOutCMS();
y = pair.QSideCMS();
z = pair.QLongCMS();
}
static const char* FrameName()
{ return "LCMS"; }
};
struct AliFemtoCorrFctnQ3DPF : public AliFemtoCorrFctnQ3D<AliFemtoCorrFctnQ3DPF> {
typedef AliFemtoCorrFctnQ3D<AliFemtoCorrFctnQ3DPF> Super;
typedef Super::Build Build;
AliFemtoCorrFctnQ3DPF(const Super::Build &b)
: Super(b.into())
{ }
AliFemtoCorrFctnQ3DPF(const char *name, int x, float y, bool b=true)
: Super(name, x, y, b)
{ }
static void GetQ(const AliFemtoPair &pair, double &x, double &y, double &z)
{
x = pair.QOutPf();
y = pair.QSidePf();
z = pair.QLongPf();
}
static const char* FrameName()
{ return "PF"; }
};
struct AliFemtoCorrFctnQ3DBF : public AliFemtoCorrFctnQ3D<AliFemtoCorrFctnQ3DBF> {
typedef AliFemtoCorrFctnQ3D<AliFemtoCorrFctnQ3DBF> Super;
typedef Super::Build Build;
AliFemtoCorrFctnQ3DBF(const Super::Build &b)
: Super(b.into())
{ }
AliFemtoCorrFctnQ3DBF(const char *name, int x, float y, bool b=true)
: Super(name, x, y, b)
{ }
static void GetQ(const AliFemtoPair &pair, double &x, double &y, double &z)
{
x = pair.QOutBf();
y = pair.QSideBf();
z = pair.QLongBf();
}
static const char* FrameName()
{ return "BF"; }
};
#undef USE_TUPLE
#endif
| 28.375 | 126 | 0.653677 | [
"object",
"vector",
"3d"
] |
1c59c0f5dcb5c23ee421518fffbd214672c1089d | 854 | h | C | bsp_for_art-badge/packages/persim-packages/include/api/js_pomtypes.h | Rbb666/SDK | cdf0bfeeb35b989ccf13c41b9625059de5fec87b | [
"Apache-2.0"
] | null | null | null | bsp_for_art-badge/packages/persim-packages/include/api/js_pomtypes.h | Rbb666/SDK | cdf0bfeeb35b989ccf13c41b9625059de5fec87b | [
"Apache-2.0"
] | null | null | null | bsp_for_art-badge/packages/persim-packages/include/api/js_pomtypes.h | Rbb666/SDK | cdf0bfeeb35b989ccf13c41b9625059de5fec87b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <pm_variant.h>
#include <pm_vector.h>
#include <jsvm/jsvm.h>
namespace pom
{
class VariantAdapter
{
public:
VariantAdapter();
virtual ~VariantAdapter();
virtual persim::Variant toVariant(const JsValue &value) const = 0;
virtual JsValue toJsValue(const persim::Variant &variant) const = 0;
};
class TypeAdapters
{
public:
TypeAdapters();
~TypeAdapters();
const VariantAdapter *adapter(persim::Variant::Type type) const;
template<typename T> void reg(VariantAdapter *adapter)
{
insert(persim::Variant::type<T>(), adapter);
}
private:
void insert(persim::Variant::Type type, VariantAdapter *adapter);
struct Node
{
persim::Variant::Type type;
VariantAdapter *adapter;
};
persim::Vector<Node> m_adapters;
class Private;
};
} // namespace pom
| 21.35 | 72 | 0.673302 | [
"vector"
] |
1c5b1202ac06882ec3351e20d85ee0544cb5019a | 1,283 | h | C | ROBOTIS/ROBOTIS-Math/robotis_math/include/robotis_math/bezier_curve.h | andy-Chien/timda_dual_arm | 94170d8889218ea0dc4e6031dcbbf59b7e37e70c | [
"MIT"
] | 227 | 2021-01-20T05:34:32.000Z | 2022-03-29T12:43:05.000Z | ROBOTIS/ROBOTIS-Math/robotis_math/include/robotis_math/bezier_curve.h | andy-Chien/timda_dual_arm | 94170d8889218ea0dc4e6031dcbbf59b7e37e70c | [
"MIT"
] | 12 | 2019-05-14T12:24:02.000Z | 2020-03-24T14:00:48.000Z | ROBOTIS/ROBOTIS-Math/robotis_math/include/robotis_math/bezier_curve.h | andy-Chien/timda_dual_arm | 94170d8889218ea0dc4e6031dcbbf59b7e37e70c | [
"MIT"
] | 239 | 2021-01-28T02:59:53.000Z | 2022-03-29T08:02:17.000Z | /*******************************************************************************
* Copyright 2018 ROBOTIS 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.
*******************************************************************************/
/*
* bezier_curve.h
*
* Created on: 2016. 8. 12.
* Author: Jay Song
*/
#ifndef ROBOTIS_MATH_BEZIER_CURVE_H_
#define ROBOTIS_MATH_BEZIER_CURVE_H_
#include <vector>
#include "robotis_math_base.h"
#include "robotis_linear_algebra.h"
namespace robotis_framework
{
class BezierCurve
{
public:
BezierCurve();
~BezierCurve();
void setBezierControlPoints(const std::vector<Point2D>& points);
Point2D getPoint(double t);
private:
std::vector<Point2D> control_points_;
};
}
#endif /* ROBOTIS_MATH_BEZIER_CURVE_H_ */
| 23.759259 | 80 | 0.650818 | [
"vector"
] |
1c5b767ba63ce8b1b058f42ad91471528ae0c21d | 2,162 | h | C | tests/achievements/gamekit_admin_achievements_exports_tests.h | aws/aws-gamekit | 7ea5a9067c53a70ed279e1870008cf3a6d8d3b2e | [
"Apache-2.0"
] | 16 | 2022-03-23T18:28:16.000Z | 2022-03-31T19:59:23.000Z | tests/achievements/gamekit_admin_achievements_exports_tests.h | aws/aws-gamekit | 7ea5a9067c53a70ed279e1870008cf3a6d8d3b2e | [
"Apache-2.0"
] | null | null | null | tests/achievements/gamekit_admin_achievements_exports_tests.h | aws/aws-gamekit | 7ea5a9067c53a70ed279e1870008cf3a6d8d3b2e | [
"Apache-2.0"
] | 1 | 2022-03-28T17:14:15.000Z | 2022-03-28T17:14:15.000Z | #pragma once
#include "../core/test_common.h"
#include "../core/mocks/fake_http_client.h"
#include "aws/gamekit/achievements/gamekit_admin_achievements.h"
#include "aws/gamekit/achievements/exports_admin.h"
#include "../core/test_stack.h"
#include "../core/test_log.h"
namespace GameKit
{
namespace Tests
{
namespace AdminAchievementsExports
{
class Dispatcher
{
public:
Dispatcher() = default;
DISPATCH_RECEIVER_HANDLE get()
{
return this;
}
std::string message;
void CallbackHandler(const char* message);
};
class GameKitAdminAchievementsExportsTestFixture : public ::testing::Test
{
public:
GameKitAdminAchievementsExportsTestFixture();
~GameKitAdminAchievementsExportsTestFixture();
virtual void SetUp() override;
virtual void TearDown() override;
protected:
static const std::string MOCK_ACCESS_ID;
static const std::string MOCK_ACCESS_SECRET;
static const std::string MOCK_SESSION_TOKEN;
void* createAchievementsInstance(bool setToken);
void setAchievementsMocks(void* instance);
void setAchievementsAdminCredentials(GameKit::Achievements::AdminAchievements* achievementsInstance);
std::shared_ptr<MockHttpClient> mockHttpClient;
AccountCredentials mockAccountCredentials;
AccountInfo mockAccountInfo;
Aws::STS::Model::Credentials mockSessionCredentials;
template <typename Result, typename Outcome>
Outcome SuccessOutcome()
{
Result result;
Outcome outcome(result);
return outcome;
}
TestStackInitializer testStackInitializer;
typedef TestLog<GameKitAdminAchievementsExportsTestFixture> TestLogger;
};
}
}
}
| 34.31746 | 117 | 0.577706 | [
"model"
] |
1c5ca11d005237261cf8efc262174f29468ead98 | 911 | h | C | Half Robot/Miniworld.h | marcus1337/HalfRobot | 1f1b66b3e8a999a103b027f72d94492f465f96be | [
"MIT"
] | null | null | null | Half Robot/Miniworld.h | marcus1337/HalfRobot | 1f1b66b3e8a999a103b027f72d94492f465f96be | [
"MIT"
] | null | null | null | Half Robot/Miniworld.h | marcus1337/HalfRobot | 1f1b66b3e8a999a103b027f72d94492f465f96be | [
"MIT"
] | null | null | null | #pragma once
#include "Kartbit.h"
#include <vector>
#include <iostream>
class Miniworld {
public:
void init(std::vector<Kartbit>* kartor, Kartbit* karta) {
_kartor = kartor;
_karta = karta;
kMap = _karta->getKarta();
grannar = _karta->getNeighbors(); // 0 = Up, 1 = Down, 2 = L, 3 = R
if (grannar[0] != -1) { //UP
}
if (grannar[1] != -1) { //DOWN
}
if (grannar[2] != -1) { // LEFT
}
if (grannar[3] != -1) { //RIGHT
int name = grannar[3];
granMap[3] = &kartor->at(name - 1);
}
else granMap[3] = nullptr;
}
char getValue(int x, int y) {
if (x < 0) {
return 1;
}
else if (x >= 20) {
if (granMap[3]) {
int x2 = x - 20;
return granMap[3]->getKarta()[x2 + y * 20];
}
return 1;
}
return _karta->getKarta()[x + y * 20];
}
private:
std::vector<Kartbit>* _kartor;
Kartbit* _karta;
char* kMap;
int* grannar;
Kartbit* granMap[4];
}; | 14.934426 | 69 | 0.548847 | [
"vector"
] |
1c73bee0603c6845dace9ab092cbd4a395405f40 | 708 | h | C | include/motionclassification.h | DuinoDu/MotionDetection | da9ba307948882fe66910f3936743309fda07fbc | [
"MIT"
] | 1 | 2017-07-12T09:01:40.000Z | 2017-07-12T09:01:40.000Z | include/motionclassification.h | DuinoDu/MotionDetection | da9ba307948882fe66910f3936743309fda07fbc | [
"MIT"
] | null | null | null | include/motionclassification.h | DuinoDu/MotionDetection | da9ba307948882fe66910f3936743309fda07fbc | [
"MIT"
] | null | null | null | #ifndef MOTIONCLASSIFICATION_H
#define MOTIONCLASSIFICATION_H
#include "common.h"
#include "objectdetection.h"
#include "objecttrack.h"
#include "actionrecognition.h"
class MotionClassification
{
public:
MotionClassification();
~MotionClassification();
void classify(Mat& frame, vector<vector<Point>>contours, vector<vector<int>> &result);
void setCaffemodelPath(string path);
bool showWindow = false;
private:
ObjectDetection *faceDetection;
ObjectTrack *faceTrack;
ActionRecognition *recognition;
vector<vector<int>> faceBoxes;
bool _isTrackingObject(const Rect2d& rect, const vector<Rect2d>& objects);
};
#endif // MOTIONCLASSIFICATION_H
| 25.285714 | 91 | 0.731638 | [
"vector"
] |
1c7b4622316d56592586b312f106178c2f6a187c | 2,244 | h | C | src/PointNeighborSearcher3.h | IceLanguage/CalfFluidEngine | 3b01805e76cb9f6c37a68900abb7f351708f2d67 | [
"MIT"
] | 2 | 2019-05-23T11:40:51.000Z | 2019-06-18T17:02:58.000Z | src/PointNeighborSearcher3.h | IceLanguage/CalfFluidEngine | 3b01805e76cb9f6c37a68900abb7f351708f2d67 | [
"MIT"
] | null | null | null | src/PointNeighborSearcher3.h | IceLanguage/CalfFluidEngine | 3b01805e76cb9f6c37a68900abb7f351708f2d67 | [
"MIT"
] | null | null | null | #ifndef _CalfFluidEngine_PointNeighborSearcher3_
#define _CalfFluidEngine_PointNeighborSearcher3_
#include <vector>
#include <Vector3.h>
#include <functional>
#include <algorithm>
namespace CalfFluidEngine {
class PointNeighborSearcher3
{
public:
PointNeighborSearcher3();
~PointNeighborSearcher3();
//**********************************************
//building the internal data structure
//**********************************************
virtual void Build(const std::vector<Vector3D>& points) = 0;
//**********************************************
//looking up the nearby points.
//**********************************************
virtual void ForEachNearbyPoint(
const Vector3D& origin,
double radius,
const std::function<void(size_t, const Vector3D&)>& callback) const = 0;
//**********************************************
//Returns true if there are any nearby points for given origin within radius
//**********************************************
virtual bool HasNearbyPoint(
const Vector3D& origin, double radius) const = 0;
};
class PointHashGridSearcher3 final : public PointNeighborSearcher3
{
public:
PointHashGridSearcher3(const Vector3<size_t>& resolution, double gridSpacing);
PointHashGridSearcher3(
size_t resolutionX,
size_t resolutionY,
size_t resolutionZ,
double gridSpacing);
virtual void Build(const std::vector<Vector3D>& points);
virtual void ForEachNearbyPoint(
const Vector3D& origin,
double radius,
const std::function<void(size_t, const Vector3D&)>& callback) const;
size_t GetHashKeyFromPosition(const Vector3D& position) const;
size_t GetHashKeyFromBucketIndex(const Vector3<size_t>& bucketIndex) const;
Vector3<size_t> GetBucketIndex(const Vector3D& position) const;
bool HasNearbyPoint(
const Vector3D& origin, double radius) const override;
void Add(const Vector3D& point);
const std::vector<std::vector<size_t>>& GetBuckets() const {
return _buckets;
}
private:
void getNearbyKeys(const Vector3D& position, size_t* nearbyKeys) const;
double _gridSpacing = 1.0;
std::vector<Vector3D> _points;
std::vector<std::vector<size_t>> _buckets;
Vector3<size_t> _resolution = Vector3<size_t>(1, 1, 1);
};
}
#endif
| 33.492537 | 80 | 0.657308 | [
"vector"
] |
1c873143fca14040dbe27b4282e96b17c7bc43ed | 3,458 | h | C | directfire_github/trunk/uilib/widgets/turnplatedialog.h | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | 1 | 2015-08-12T04:05:33.000Z | 2015-08-12T04:05:33.000Z | directfire_github/trunk/uilib/widgets/turnplatedialog.h | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | null | null | null | directfire_github/trunk/uilib/widgets/turnplatedialog.h | zhwsh00/DirectFire-android | 10c757e1be0b25dee951f9ba3a0e1f6d5c04a938 | [
"MIT"
] | null | null | null | #ifndef _turnplatedialog_h_
#define _turnplatedialog_h_
#include "uilib/uilib.h"
#include "cliententry/uimsgevent.h"
using namespace uilib;
#include <string>
#include <vector>
#include <sstream>
using namespace std;
#include "cocos2d.h"
using namespace std;
namespace uilib {
class TurnPlateDialog;
class TurnPlateNodeDelegate : public FSizeCCNodeDelegate
{
public:
TurnPlateNodeDelegate(TurnPlateDialog *owner,CCNode *node,const CCSize &size = CCSizeMake(0,0));
virtual ~TurnPlateNodeDelegate();
virtual void touchPressEvent(CCTouch *pTouch, CCEvent *pEvent);
virtual void touchReleaseEvent(CCTouch *pTouch, CCEvent *pEvent);
protected:
TurnPlateDialog *m_owner;
CCPoint m_pressEvent;
CCPoint m_releaseEvent;
};
class TurnPlateDialog : public BasShowDialog
{
public:
typedef struct TurnPlateBetInfo{
TurnPlateBetInfo(){
m_goldUsed = 0;
m_propNum = 0;
}
TurnPlateBetInfo(int use,const std::string &prop,int num){
m_goldUsed = use;
m_propName = prop;
m_propNum = num;
}
int m_goldUsed;
std::string m_propName;
int m_propNum;
}TurnPlateBetInfo;
TurnPlateDialog(CCNode *parent = 0,const ccColor4B &color = ccc4(0,0,0,0));
virtual ~TurnPlateDialog();
void exec();
void setPlateGridNum(int num) { m_plateGridNum = num;}
void setPlateInfo(const std::string &hand,const std::string &plate,const std::string &frame,const std::string &ind);
void setPropPayInfo(const std::vector<std::string> &props,const std::vector<int> &payrate);
void setForce(float force);
void setGlodInfo(const std::string &img,int num);
void setBetMinMax(int min,int max);
const std::vector<TurnPlateBetInfo> &getBetResults() { return m_betResults;}
void usePropReplyGot();
protected:
void finish();
void initPlateProps();
void initGoldInfo();
void initBetInfo();
protected:
void startIndicator();
void onFrameClicked();
void onPlateActionFinished(CCNode *node,void *data);
void onFrameActionFinished(CCNode *node,void *data);
void onFrameIndicatorFinished(CCNode *node,void *data);
void calculateResult();
void sendBetResult();
void showBetResult(const std::string &img,int num,int rate);
protected:
void onShowResultFinished(CCNode *node,void *data);
protected:
void onIncClicked(CCNode *node,void *data);
void onDecClicked(CCNode *node,void *data);
protected:
std::string m_handString,m_plateString,m_frameString,m_inString;
CCSprite *m_handSprite;
CCSprite *m_plateSprite;
CCSprite *m_frameSprite;
CCSprite *m_inSprite;
FSizeCCNodeDelegate *m_handDele;
FSizeCCNodeDelegate *m_plateDele;
FSizeCCNodeDelegate *m_frameDele;
FSizeCCNodeDelegate *m_inDele;
CCNode *m_wonShowSprite;
int m_plateGridNum;
protected:
std::vector<std::string> m_props;
std::vector<int> m_payRate;
protected:
CCActionEase* m_plateSpeed;
CCActionEase* m_frameSpeed;
bool m_plateFinished;
bool m_frameFinished;
bool m_usePropGot;
protected:
float m_force;
protected:
std::string m_goldImg;
int m_goldNum;
CCLabelBMFont *m_goldSprite;
protected:
CCLabelBMFont *m_betNumSprite;
BasButton *m_incButton;
BasButton *m_decButton;
int m_betMinNum;
int m_betMaxNum;
int m_betOnNum;
protected:
std::vector<TurnPlateBetInfo> m_betResults;
};
}
#endif
| 29.305085 | 120 | 0.712551 | [
"vector"
] |
1c8da20c158d459e0c4e069bb314296355e17f43 | 1,063 | c | C | tempsensor_v1/src/system/timer.c | sergioamr/vaccinemonitoring | 9ae91df587542a1565803053c65809e67a5747f1 | [
"Apache-2.0"
] | null | null | null | tempsensor_v1/src/system/timer.c | sergioamr/vaccinemonitoring | 9ae91df587542a1565803053c65809e67a5747f1 | [
"Apache-2.0"
] | null | null | null | tempsensor_v1/src/system/timer.c | sergioamr/vaccinemonitoring | 9ae91df587542a1565803053c65809e67a5747f1 | [
"Apache-2.0"
] | null | null | null | /*
* timer.c
*
* Created on: Feb 11, 2015
* Author: rajeevnx
*/
#include "config.h"
#include "timer.h"
volatile uint16_t iTick = 0;
volatile uint32_t delay_count = 0;
// Timer0_A0 interrupt service routine
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = TIMER0_A0_VECTOR
__interrupt void Timer0_A0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(TIMER0_A0_VECTOR))) Timer0_A0_ISR (void)
#else
#error Compiler not supported!
#endif
{
if (++iTick >= delay_count)
__bic_SR_register_on_exit(LPM0_bits); // Resume functionality.
}
void delay(uint32_t time) {
iTick = 0;
if (time > 180000 || time <= 10) {
_NOP();
time = 180000;
}
delay_count = time / 10;
TA0CCTL0 = CCIE; // TACCR0 interrupt enabled
TA0CCR0 = 10000; // 10ms (1 cnt = 1us @1MHz timer clk)
TA0CTL = TASSEL__SMCLK | MC__UP | ID__8; // SMCLK/8 (1MHz), UP mode
__bis_SR_register(LPM0_bits + GIE); // Disable CPU, keep functional master clock and slaves.
TA0CTL = MC__STOP;
iTick = 0;
}
| 23.622222 | 93 | 0.688617 | [
"vector"
] |
46a89ba6faba9db4b59c91fe684d83225df15cd4 | 627 | h | C | include/Dojo3D/common_header.h | Tomcc/dojo3D | 4b443899752f73daf0b5a6d4588930af63e1b9db | [
"MIT"
] | 3 | 2016-01-18T06:15:18.000Z | 2016-05-23T22:21:16.000Z | include/Dojo3D/common_header.h | Tomcc/dojo3D | 4b443899752f73daf0b5a6d4588930af63e1b9db | [
"MIT"
] | null | null | null | include/Dojo3D/common_header.h | Tomcc/dojo3D | 4b443899752f73daf0b5a6d4588930af63e1b9db | [
"MIT"
] | null | null | null | #pragma once
#include <dojo.h>
#include <unordered_set>
#include <mutex>
#include <future>
#pragma warning(push)
#pragma warning(disable: 4127) // possible loss of data
#include "btBulletDynamicsCommon.h"
#pragma warning(pop)
namespace Phys {
struct Group : public Dojo::PseudoEnumClass<uint16_t> {
template<typename T>
Group(T raw) : PseudoEnumClass(raw) {}
};
using Vector = Dojo::Vector;
using Quaternion = Dojo::Quaternion;
using Matrix = Dojo::Matrix;
using Radians = Dojo::Radians;
typedef std::lock_guard<std::mutex> ScopedLock;
template<typename T>
using optional_ref = Dojo::optional_ref<T>;
}
| 19 | 56 | 0.727273 | [
"vector"
] |
46aaf793dda1f78d509a513dcd7cb2974485b787 | 889 | h | C | 0102-Binary-Tree-Level-Order-Traversal/cpp_0102/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | 12 | 2020-03-18T14:36:23.000Z | 2021-12-19T02:24:33.000Z | 0102-Binary-Tree-Level-Order-Traversal/cpp_0102/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | 0102-Binary-Tree-Level-Order-Traversal/cpp_0102/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | //
// Created by ooooo on 2019/11/4.
//
#ifndef CPP_0102_SOLUTION1_H
#define CPP_0102_SOLUTION1_H
#include <iostream>
#include "TreeNode.h"
#include <queue>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> res;
if (!root) {
return res;
}
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
vector<int> vec;
for (int i = 0; i < size; ++i) {
TreeNode *node = q.front();
vec.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
q.pop();
}
res.push_back(vec);
}
return res;
}
};
#endif //CPP_0102_SOLUTION1_H
| 20.204545 | 53 | 0.502812 | [
"vector"
] |
46b1072471e5f0cb06df462c6ccc8abf1777a05f | 7,910 | h | C | Source/Plugins/TeBulletPhysics/TeBulletPhysics.h | fabsgc/TweedeFrameworkRedux | 2c61e6f31c43db36a20d3288e45047586a503725 | [
"Zlib"
] | 57 | 2019-09-02T01:10:37.000Z | 2022-01-11T06:28:10.000Z | Source/Plugins/TeBulletPhysics/TeBulletPhysics.h | fabsgc/TweedeFrameworkRedux | 2c61e6f31c43db36a20d3288e45047586a503725 | [
"Zlib"
] | null | null | null | Source/Plugins/TeBulletPhysics/TeBulletPhysics.h | fabsgc/TweedeFrameworkRedux | 2c61e6f31c43db36a20d3288e45047586a503725 | [
"Zlib"
] | 6 | 2020-02-29T17:19:30.000Z | 2021-10-30T04:29:22.000Z | #pragma once
#include "TeBulletPhysicsPrerequisites.h"
#include "Physics/TePhysics.h"
#include "Physics/TePhysicsCommon.h"
#include "Utility/TePoolAllocator.h"
namespace te
{
class BulletScene;
/** Bullet implementation of Physics. */
class BulletPhysics : public Physics
{
public:
/** Type of contacts reported by PhysX simulation. */
enum class ContactEventType
{
ContactBegin,
ContactStay,
ContactEnd
};
/** Event reported when two colliders interact. */
struct ContactEvent
{
Body* BodyA = nullptr; /** First body. */
Body* BodyB = nullptr; /** Second body. */
ContactEventType Type = ContactEventType::ContactBegin; /** Exact type of the event. */
// Note: Not too happy this is heap allocated, use static allocator?
Vector<ContactPoint> Points; /** Information about all contact points between the colliders. */
};
/** Event reported when a joint breaks. */
struct JointBreakEvent
{
Joint* JointElt; /** Broken joint. */
};
public:
BulletPhysics(const PHYSICS_INIT_DESC& input);
~BulletPhysics();
TE_MODULE_STATIC_HEADER_MEMBER(BulletPhysics)
/** @copydoc Physics::CreateMesh */
SPtr<PhysicsMesh> CreateMesh(const SPtr<MeshData>& meshData) override;
/** @copydoc Physics::CreateMesh */
SPtr<PhysicsHeightField> CreateHeightField(const SPtr<Texture>& texture) override;
/** @copydoc Physics::CreatePhysicsScene */
SPtr<PhysicsScene> CreatePhysicsScene() override;
/** @copydoc Physics::Update */
void Update() override;
/** @copydoc Physics::SetPaused */
void SetPaused(bool paused) override;
/** @copydoc Physics::SetPaused */
bool IsPaused() const override;
/** Enable or disable debug informations globally */
void SetDebug(bool debug) override;
/** @copydoc SetDebug */
bool IsDebug() override;
/** @copydoc Physics::DrawDebug */
void DrawDebug(const SPtr<Camera>& camera, const SPtr<RenderTarget>& renderTarget) override;
/** @copydoc Physics::SetGravity */
virtual void SetGravity(const Vector3& gravity) override;
/** Notifies the system that at physics scene is about to be destroyed. */
void NotifySceneDestroyed(BulletScene* scene);
private:
friend class BulletScene;
bool _paused; // is simulation paused
bool _debug; // is debug enabled
btBroadphaseInterface* _broadphase = nullptr;
btCollisionDispatcher* _collisionDispatcher = nullptr;
btSequentialImpulseConstraintSolver* _constraintSolver = nullptr;
btDefaultCollisionConfiguration* _collisionConfiguration = nullptr;
Vector<BulletScene*> _scenes;
INT32 _maxSubSteps = 1;
UINT32 _maxSolveIterations = 256;
float _internalFps = 60.0f;
float _deltaTimeSec = 1.0f;
UINT32 _debugMode = btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawContactPoints |
btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits | btIDebugDraw::DBG_DrawAabb;
};
typedef Pair<const btCollisionObject*, const btCollisionObject*> ContactEventKey;
struct ContactEventKeyHash
{
template <class T1, class T2>
std::size_t operator() (const Pair<T1, T2>& pair) const {
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
typedef UnorderedMap<ContactEventKey, BulletPhysics::ContactEvent*, ContactEventKeyHash> ContactEventsMap;
/** Contains information about a single Bullet scene. */
class BulletScene : public PhysicsScene
{
public:
BulletScene(BulletPhysics* physics, const PHYSICS_INIT_DESC& desc);
~BulletScene();
/** PhysicsScene::TriggerCollisions */
void TriggerCollisions() override;
/** PhysicsScene::TriggerCollisions */
void ReportCollisions() override;
/** @copydoc PhysicsScene::CreateRigidBody */
SPtr<RigidBody> CreateRigidBody(const HSceneObject& linkedSO) override;
/** @copydoc PhysicsScene::CreateSoftBody */
SPtr<SoftBody> CreateSoftBody(const HSceneObject& linkedSO) override;
/** @copydoc PhysicsScene::CreateConeTwistJoint */
SPtr<ConeTwistJoint> CreateConeTwistJoint() override;
/** @copydoc PhysicsScene::CreateHingeJoint */
SPtr<HingeJoint> CreateHingeJoint() override;
/** @copydoc PhysicsScene::CreateSphericalJoint */
SPtr<SphericalJoint> CreateSphericalJoint() override;
/** @copydoc PhysicsScene::CreateSliderJoint */
SPtr<SliderJoint> CreateSliderJoint() override;
/** @copydoc PhysicsScene::CreateD6Joint */
SPtr<D6Joint> CreateD6Joint() override;
/** @copydoc PhysicsScene::CreateBoxCollider */
SPtr<BoxCollider> CreateBoxCollider(const Vector3& extents, const Vector3& position,
const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreatePlaneCollider */
SPtr<PlaneCollider> CreatePlaneCollider(const Vector3& normal, const Vector3& position,
const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreateSphereCollider */
SPtr<SphereCollider> CreateSphereCollider(float radius, const Vector3& position,
const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreateCylinderCollider */
SPtr<CylinderCollider> CreateCylinderCollider(const Vector3& extents, const Vector3& position,
const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreateCapsuleCollider */
SPtr<CapsuleCollider> CreateCapsuleCollider(float radius, float height, const Vector3& position,
const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreateMeshCollider */
SPtr<MeshCollider> CreateMeshCollider(const Vector3& position, const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreateConeCollider */
SPtr<ConeCollider> CreateConeCollider(float radius, float height, const Vector3& position,
const Quaternion& rotation) override;
/** @copydoc PhysicsScene::CreateHeightFieldCollider */
SPtr<HeightFieldCollider> CreateHeightFieldCollider(const Vector3& position, const Quaternion& rotation) override;
/** Add RigidBody to current scene */
void AddRigidBody(btRigidBody* body);
/** Remove RigidBody from scene */
void RemoveRigidBody(btRigidBody* body);
/** Add Joint to the current scene */
void AddJoint(btTypedConstraint* joint, bool collisionWithLinkedBody = true) const;
/** Remove Joint from the current scene */
void RemoveJoint(btTypedConstraint* joint) const;
/** @copydoc Physics::RayCast */
bool RayCast(const Vector3& origin, const Vector3& unitDir, PhysicsQueryHit& hit,
float maxDist = FLT_MAX) const override;
/** @copydoc Physics::RayCast */
bool RayCast(const Vector3& origin, const Vector3& unitDir, Vector<PhysicsQueryHit>& hits,
float maxDist = FLT_MAX) const override;
private:
friend class BulletPhysics;
PHYSICS_INIT_DESC _initDesc;
BulletPhysics* _physics = nullptr;
btDiscreteDynamicsWorld* _world = nullptr;
btSoftBodyWorldInfo* _worldInfo = nullptr;
ContactEventsMap* _beginContactEvents = nullptr;
ContactEventsMap* _stayContactEvents = nullptr;
ContactEventsMap* _endContactEvents = nullptr;
};
BulletPhysics& gBulletPhysics();
IMPLEMENT_GLOBAL_POOL(BulletPhysics::ContactEvent, 64)
}
| 36.790698 | 122 | 0.666119 | [
"vector"
] |
46b6c1bdc9a139d0c819b4dc5bffc08eb8428d87 | 782 | h | C | TTable.h | CGLemon/Leela | ecac362274b15e51d71bc93dd14130bb7176b695 | [
"MIT"
] | 36 | 2020-12-02T22:09:05.000Z | 2022-02-15T09:24:43.000Z | TTable.h | CGLemon/Leela | ecac362274b15e51d71bc93dd14130bb7176b695 | [
"MIT"
] | 1 | 2020-12-27T11:51:42.000Z | 2020-12-29T21:37:09.000Z | TTable.h | CGLemon/Leela | ecac362274b15e51d71bc93dd14130bb7176b695 | [
"MIT"
] | 10 | 2020-12-09T11:53:14.000Z | 2022-03-28T04:03:59.000Z | #ifndef TTABLE_H_INCLUDED
#define TTABLE_H_INCLUDED
#include <vector>
#include "UCTNode.h"
#include "SMP.h"
class TTEntry {
public:
TTEntry()
: m_hash(0) {
};
uint64 m_hash;
// XXX: need RAVE data here?
double m_blackwins;
int m_visits;
double m_eval_sum;
int m_eval_count;
};
class TTable {
public:
/*
return the global TT
*/
static TTable* get_TT(void);
/*
update corresponding entry
*/
void update(uint64 hash, const float komi, const UCTNode * node);
/*
sync given node with TT
*/
void sync(uint64 hash, const float komi, UCTNode * node);
private:
TTable(int size = 500000);
SMP::Mutex m_mutex;
std::vector<TTEntry> m_buckets;
float m_komi;
};
#endif
| 15.64 | 69 | 0.61509 | [
"vector"
] |
46be3f802d920ef5811384a6c515b5ed2787bb5f | 363 | h | C | include/hub/storage/csvfilestorage.h | tfrec-kalcsits/SensorSystem-Hub | c74849cab6e7a58af318a8538a3931af60b406c5 | [
"MIT"
] | 2 | 2018-06-30T06:05:29.000Z | 2021-08-24T22:34:19.000Z | include/hub/storage/csvfilestorage.h | tfrec-kalcsits/SensorSystem-Hub | c74849cab6e7a58af318a8538a3931af60b406c5 | [
"MIT"
] | 13 | 2018-07-07T00:11:08.000Z | 2018-09-05T02:49:11.000Z | include/hub/storage/csvfilestorage.h | tfrec-kalcsits/SensorSystem-Hub | c74849cab6e7a58af318a8538a3931af60b406c5 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <hub/measurement.h>
#include "filestorage.h"
namespace sensorsystem
{
class CSVFileStorage : public FileStorage
{
public:
CSVFileStorage(std::string prefix_path);
bool recordMeasurementToFile(const Measurement& measurement) override;
private:
const std::string prefix_path;
};
} | 15.782609 | 74 | 0.738292 | [
"vector"
] |
46bf2ad060038291f125eb5a63823c9bdd494c04 | 3,208 | h | C | grante/MultichainGibbsInference.h | pantonante/grante-bazel | e3f22ec111463a7ae0686494422ab09f86b4d39a | [
"DOC"
] | null | null | null | grante/MultichainGibbsInference.h | pantonante/grante-bazel | e3f22ec111463a7ae0686494422ab09f86b4d39a | [
"DOC"
] | null | null | null | grante/MultichainGibbsInference.h | pantonante/grante-bazel | e3f22ec111463a7ae0686494422ab09f86b4d39a | [
"DOC"
] | null | null | null |
#ifndef GRANTE_MCHAINGIBBSINFERENCE_H
#define GRANTE_MCHAINGIBBSINFERENCE_H
#include "FactorGraph.h"
#include "InferenceMethod.h"
#include "GibbsSampler.h"
namespace Grante {
/* Gibbs sampling inference with multiple chains and convergence diagnostics.
*
* References
*
* [Brooks1998], Stephen P. Brooks, Andrew Gelman,
* "General Methods for Monitoring Convergence of Iterative Simulations",
* Journal of Computational and Graphical Statistics,
* Vol. 7, No. 4, pages 434--455, December 1998.
*
* [Gelman1992], Andrew Gelman, Donald B. Rubin,
* "Inference from Iterative Simulation using Multiple Sequences",
* Statistical Science,
* Vol. 7, pages 457--511, 1992.
*/
class MultichainGibbsInference : public InferenceMethod {
public:
explicit MultichainGibbsInference(const FactorGraph* fg);
virtual ~MultichainGibbsInference();
virtual InferenceMethod* Produce(const FactorGraph* fg) const;
// Set multi-chain Gibbs sampling parameters.
//
// number_of_chains: >=3, number of parallel chains used.
// accept_psrf: >1.0, potential scale reduction factor acceptance
// threshold; if max_i PSRF_c <= accept_psnr, then we assume the chains
// have converged.
// spacing_sweeps: number of sweeps to discard between samples.
// Default: 0.
// sample_count: number of samples used to estimate marginals after
// convergence has been determined. Default: 10000.
void SetSamplingParameters(unsigned int number_of_chains,
double accept_psrf, unsigned int spacing_sweeps, unsigned int sample_count);
// Perform Gibbs sampling to compute marginals.
virtual void PerformInference();
virtual void ClearInferenceResult();
// Approximate marginals
virtual const std::vector<double>& Marginal(unsigned int factor_id) const;
virtual const std::vector<std::vector<double> >& Marginals() const;
// Gibbs sampling does not support computation of the log-partition
// function.
// This method always returns the signaling_NaN value.
virtual double LogPartitionFunction() const;
// Produce approximate samples from the distribution
virtual void Sample(std::vector<std::vector<unsigned int> >& states,
unsigned int sample_count);
// NOT IMPLEMENTED
virtual double MinimizeEnergy(std::vector<unsigned int>& state);
private:
// Marginal distribution means and variances for M chains
typedef std::vector<std::vector<double> > marginals_t;
std::vector<marginals_t> chain_mean;
std::vector<marginals_t> chain_varm;
// Inference result: estimated marginal distributions for all factors
std::vector<std::vector<double> > marginals;
// Inference result: estimated log-partition function.
// XXX: Not available through Gibbs sampling
double log_z;
// Workhorse: the actual Gibbs sampler used
std::vector<GibbsSampler> chain_gibbs;
// Gibbs sampling parameters
unsigned int number_of_chains;
double accept_psrf;
unsigned int spacing_sweeps;
unsigned int sample_count;
void PerformBurninPhase();
// Setup chain_mean and chain_varm
void SetupChains(void);
void UpdateMeanVariance(const GibbsSampler& gibbs,
marginals_t& mean, marginals_t& varm, unsigned int n);
double ComputePSRF(unsigned int n) const;
};
}
#endif
| 31.762376 | 78 | 0.761534 | [
"vector"
] |
46cba132d7c5024e71d7e4943d152fb5bcd4c7e0 | 13,575 | h | C | clicks/spiisolator2/lib/include/spiisolator2.h | dMajoIT/mikrosdk_click_v2 | f425fd85054961b4f600d1708cf18ac952a6bdb8 | [
"MIT"
] | 31 | 2020-10-02T14:15:14.000Z | 2022-03-24T08:33:21.000Z | clicks/spiisolator2/lib/include/spiisolator2.h | dMajoIT/mikrosdk_click_v2 | f425fd85054961b4f600d1708cf18ac952a6bdb8 | [
"MIT"
] | 4 | 2020-10-27T14:05:00.000Z | 2022-03-10T09:38:57.000Z | clicks/spiisolator2/lib/include/spiisolator2.h | dMajoIT/mikrosdk_click_v2 | f425fd85054961b4f600d1708cf18ac952a6bdb8 | [
"MIT"
] | 32 | 2020-11-28T07:56:42.000Z | 2022-03-14T19:42:29.000Z | /****************************************************************************
** Copyright (C) 2020 MikroElektronika d.o.o.
** Contact: https://www.mikroe.com/contact
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
** OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
** DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
** OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
** USE OR OTHER DEALINGS IN THE SOFTWARE.
****************************************************************************/
/*!
* @file spiisolator2.h
* @brief This file contains API for SPI Isolator 2 Click Driver.
*/
#ifndef SPIISOLATOR2_H
#define SPIISOLATOR2_H
#ifdef __cplusplus
extern "C"{
#endif
#include "drv_digital_out.h"
#include "drv_digital_in.h"
#include "drv_spi_master.h"
/*!
* @addtogroup spiisolator2 SPI Isolator 2 Click Driver
* @brief API for configuring and manipulating SPI Isolator 2 Click driver.
* @{
*/
/**
* @defgroup spiisolator2_reg SPI Isolator 2 Registers List
* @brief List of registers of SPI Isolator 2 Click driver.
*/
/**
* @defgroup spiisolator2_set SPI Isolator 2 Registers Settings
* @brief Settings for registers of SPI Isolator 2 Click driver.
*/
/**
* @addtogroup spiisolator2_set
* @{
*/
/**
* @brief SPI Isolator 2 description setting.
* @details Specified setting for description of SPI Isolator 2 Click driver.
*/
#define SPIISOLATOR2_EEPROM5_CMD_WREN 0x06000000
#define SPIISOLATOR2_EEPROM5_CMD_WRDI 0x04000000
#define SPIISOLATOR2_EEPROM5_CMD_RDSR 0x05000000
#define SPIISOLATOR2_EEPROM5_CMD_WRSR 0x01000000
#define SPIISOLATOR2_EEPROM5_CMD_READ 0x03000000
#define SPIISOLATOR2_EEPROM5_CMD_WRITE 0x02000000
#define SPIISOLATOR2_EEPROM5_CMD_READ_ID 0x83000000
#define SPIISOLATOR2_EEPROM5_CMD_WRITE_ID 0x82000000
#define SPIISOLATOR2_EEPROM5_CMD_READ_LOCK_STATUS 0x83000000
#define SPIISOLATOR2_EEPROM5_CMD_LOCK_ID 0x82000000
#define SPIISOLATOR2_EEPROM5_CMD_WRITE_ENABLE 0x06
#define SPIISOLATOR2_OUT_DISABLE 0x00
#define SPIISOLATOR2_OUT_ENABLE 0x01
#define SPIISOLATOR2_DUMMY 0x00
/*! @} */ // spiisolator2_set
/**
* @defgroup spiisolator2_map SPI Isolator 2 MikroBUS Map
* @brief MikroBUS pin mapping of SPI Isolator 2 Click driver.
*/
/**
* @addtogroup spiisolator2_map
* @{
*/
/**
* @brief MikroBUS pin mapping.
* @details Mapping pins of SPI Isolator 2 Click to the selected MikroBUS.
*/
#define SPIISOLATOR2_MAP_MIKROBUS( cfg, mikrobus ) \
cfg.miso = MIKROBUS( mikrobus, MIKROBUS_MISO ); \
cfg.mosi = MIKROBUS( mikrobus, MIKROBUS_MOSI ); \
cfg.sck = MIKROBUS( mikrobus, MIKROBUS_SCK ); \
cfg.cs = MIKROBUS( mikrobus, MIKROBUS_CS ); \
cfg.en1 = MIKROBUS( mikrobus, MIKROBUS_RST ); \
/*! @} */ // spiisolator2_map
/*! @} */ // spiisolator2
/**
* @brief SPI Isolator 2 Click context object.
* @details Context object definition of SPI Isolator 2 Click driver.
*/
typedef struct
{
// Output pins
digital_out_t en1; /**< Description. */
// Modules
spi_master_t spi; /**< SPI driver object. */
pin_name_t chip_select; /**< Chip select pin descriptor (used for SPI driver). */
} spiisolator2_t;
/**
* @brief SPI Isolator 2 Click configuration object.
* @details Configuration object definition of SPI Isolator 2 Click driver.
*/
typedef struct
{
// Communication gpio pins
pin_name_t miso; /**< Master input - slave output pin descriptor for SPI driver. */
pin_name_t mosi; /**< Master output - slave input pin descriptor for SPI driver. */
pin_name_t sck; /**< Clock pin descriptor for SPI driver. */
pin_name_t cs; /**< Chip select pin descriptor for SPI driver. */
// Additional gpio pins
pin_name_t en1; /**< Description. */
// static variable
uint32_t spi_speed; /**< SPI serial speed. */
spi_master_mode_t spi_mode; /**< SPI master mode. */
spi_master_chip_select_polarity_t cs_polarity; /**< Chip select pin polarity. */
} spiisolator2_cfg_t;
/**
* @brief SPI Isolator 2 Click return value data.
* @details Predefined enum values for driver return values.
*/
typedef enum
{
SPIISOLATOR2_OK = 0,
SPIISOLATOR2_ERROR = -1
} spiisolator2_return_value_t;
/*!
* @addtogroup spiisolator2 SPI Isolator 2 Click Driver
* @brief API for configuring and manipulating SPI Isolator 2 Click driver.
* @{
*/
/**
* @brief SPI Isolator 2 configuration object setup function.
* @details This function initializes click configuration structure to initial
* values.
* @param[out] cfg : Click configuration structure.
* See #spiisolator2_cfg_t object definition for detailed explanation.
* @return Nothing.
* @note The all used pins will be set to unconnected state.
*/
void spiisolator2_cfg_setup ( spiisolator2_cfg_t *cfg );
/**
* @brief SPI Isolator 2 initialization function.
* @details This function initializes all necessary pins and peripherals used
* for this click board.
* @param[out] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] cfg : Click configuration structure.
* See #spiisolator2_cfg_t object definition for detailed explanation.
* @return @li @c 0 - Success,
* @li @c -1 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t spiisolator2_init ( spiisolator2_t *ctx, spiisolator2_cfg_t *cfg );
/**
* @brief SPI Isolator 2 data writing function.
* @details This function writes a desired number of data bytes starting from
* the selected register by using SPI serial interface.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] reg : Start register address.
* @param[in] data_in : Data to be written.
* @param[in] len : Number of bytes to be written.
* @return @li @c 0 - Success,
* @li @c -1 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t spiisolator2_generic_write ( spiisolator2_t *ctx, uint8_t reg, uint8_t *data_in, uint8_t len );
/**
* @brief SPI Isolator 2 data reading function.
* @details This function reads a desired number of data bytes starting from
* the selected register by using SPI serial interface.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] reg : Start register address.
* @param[out] data_out : Output read data.
* @param[in] len : Number of bytes to be read.
* @return @li @c 0 - Success,
* @li @c -1 - Error.
*
* See #err_t definition for detailed explanation.
* @note None.
*/
err_t spiisolator2_generic_read ( spiisolator2_t *ctx, uint8_t reg, uint8_t *data_out, uint8_t len );
/**
* @brief SPI Isolator 2 output enable function.
* @details The function enable or disable output ( isolation ) of the ISO7741DWR High-Speed,
* Robust-EMC Reinforced and Basic Quad-Channel Digital Isolators on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] en_out : Enable/disable pin.
* @return Nothing.
* @note None.
*/
void spiisolator2_output_enable( spiisolator2_t *ctx, uint8_t en_out );
/**
* @brief SPI Isolator 2 send command function.
* @details The function sends the desired command to the ISO7741DWR High-Speed, Robust-EMC Reinforced
* and Basic Quad-Channel Digital Isolators on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] cmd : 8-bit commands instruction.
* @return Nothing.
* @note None.
*/
void spiisolator2_set_cmd ( spiisolator2_t *ctx, uint8_t cmd );
/**
* @brief SPI Isolator 2 write the byte of data function.
* @details The function writes the byte of data to the targeted 8-bit
* register address of the ISO7741DWR High-Speed, Robust-EMC Reinforced
* and Basic Quad-Channel Digital Isolators on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] reg : 8-bit register address.
* @param[in] tx_data : 8-bit data to be written.
* @return Nothing.
* @note None.
*/
void spiisolator2_write_byte ( spiisolator2_t *ctx, uint8_t reg, uint8_t tx_data );
/**
* @brief SPI Isolator 2 read the byte of data function.
* @details The function read a the byte of data from the targeted 8-bit
* register address of the ISO7741DWR High-Speed, Robust-EMC Reinforced
* and Basic Quad-Channel Digital Isolators on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] reg : 8-bit register address.
* @return 8-bit read data.
* @note None.
*/
uint8_t spiisolator2_read_byte ( spiisolator2_t *ctx, uint8_t reg );
/**
* @brief SPI Isolator 2 burst write function.
* @details The function writes sequential data starting to the targeted 8-bit register address
* of the ISO7741DWR High-Speed, Robust-EMC Reinforced and Basic Quad-Channel Digital Isolators
* on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] reg : 8-bit register address.
* @param[in] p_tx_data : 8-bit data to be written.
* @param[in] n_bytes : number of bytes to be written.
* @return Nothing.
* @note None.
*/
void spiisolator2_burst_write ( spiisolator2_t *ctx, uint8_t reg, uint8_t *p_tx_data, uint8_t n_bytes );
/**
* @brief SPI Isolator 2 burst read function.
* @details The function read sequential data starting from the targeted 8-bit register address
* of the ISO7741DWR High-Speed, Robust-EMC Reinforced and Basic Quad-Channel Digital Isolators
* on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] reg : 8-bit register address.
* @param[in] p_rx_data : 8-bit data to be written.
* @param[in] n_bytes : number of bytes to be written.
* @return Nothing.
* @note None.
*/
void spiisolator2_burst_read ( spiisolator2_t *ctx, uint8_t reg, uint8_t *p_rx_data, uint8_t n_bytes );
/**
* @brief SPI Isolator 2 multi write function.
* @details The function writes sequential data starting of the targeted (selected) 8-bit, 16-bit,
* 24-bit, or 32-bit register address of the ISO7741DWR High-Speed, Robust-EMC Reinforced
* and Basic Quad-Channel Digital Isolators on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] addr : 8-bit register address.
* @param[in] addr_n_bytes : The number of bytes of the registry address.
* @param[in] p_tx_data : 8-bit data to be written.
* @param[in] tx_data_n_bytes : Pointer to the data to be written.
* @return Nothing.
* @note None.
*/
void spiisolator2_multi_write ( spiisolator2_t *ctx, uint32_t addr, uint8_t addr_n_bytes, uint8_t *p_tx_data, uint8_t tx_data_n_bytes );
/**
* @brief SPI Isolator 2 multi read function.
* @details The function read sequential data starting from the targeted (selected) 8-bit, 16-bit,
* 24-bit, or 32-bit register address of the ISO7741DWR High-Speed, Robust-EMC Reinforced
* and Basic Quad-Channel Digital Isolators on SPI Isolator 2 click board.
* @param[in] ctx : Click context object.
* See #spiisolator2_t object definition for detailed explanation.
* @param[in] addr : 8-bit register address.
* @param[in] addr_n_bytes : The number of bytes of the registry address.
* @param[in] p_rx_data : Pointer to the memory location where data be stored.
* @param[in] tx_data_n_bytes : Number of bytes to be read.
* @return Nothing.
* @note None.
*/
void spiisolator2_multi_read ( spiisolator2_t *ctx, uint32_t addr, uint8_t addr_n_bytes, uint8_t *p_rx_data, uint8_t tx_data_n_bytes );
#ifdef __cplusplus
}
#endif
#endif // SPIISOLATOR2_H
/*! @} */ // spiisolator2
// ------------------------------------------------------------------------ END
| 38.896848 | 136 | 0.685157 | [
"object"
] |
46eaf8c8b5de9f92b947f8639ba448e4774bd0d0 | 1,636 | h | C | es-app/src/FileData.h | wakegrady/EmulationStation | 7635f11f92d77b28b9d9123e240db2f4a18b5637 | [
"Apache-2.0",
"MIT"
] | 2 | 2016-02-07T20:59:02.000Z | 2016-08-17T10:57:56.000Z | es-app/src/FileData.h | wakegrady/EmulationStation | 7635f11f92d77b28b9d9123e240db2f4a18b5637 | [
"Apache-2.0",
"MIT"
] | 1 | 2016-02-07T21:23:37.000Z | 2016-07-02T15:55:21.000Z | es-app/src/FileData.h | wakegrady/EmulationStation | 7635f11f92d77b28b9d9123e240db2f4a18b5637 | [
"Apache-2.0",
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <boost/filesystem.hpp>
#include "MetaData.h"
class SystemData;
struct FileSort;
enum FileType
{
GAME = 1,
FOLDER = 2
};
// Used for loading/saving gamelist.xml.
const char* fileTypeToString(FileType type);
FileType stringToFileType(const char* str);
// Remove (.*) and [.*] from str
std::string removeParenthesis(const std::string& str);
std::string getCleanGameName(const std::string& str, const SystemData* system);
class FileData
{
public:
FileData();
FileData(const std::string& fileID, SystemData* system, FileType type, const std::string& nameCache = "");
FileData(const std::string& fileID, const std::string& systemID, FileType type);
inline bool operator==(const FileData& rhs) const { return (mFileID == rhs.mFileID && mSystem == rhs.mSystem); }
inline bool operator!=(const FileData& rhs) const { return !(*this == rhs); }
MetaDataMap get_metadata() const;
void set_metadata(const MetaDataMap& metadata);
const std::string& getName() const;
FileType getType() const;
boost::filesystem::path getPath() const;
inline const std::string& getFileID() const { return mFileID; }
const std::string& getSystemID() const;
SystemData* getSystem() const { return mSystem; }
std::vector<FileData> getChildren(const FileSort* sortType = NULL) const;
std::vector<FileData> getChildrenRecursive(bool includeFolders, const FileSort* sortType = NULL) const;
inline std::string getCleanName() const { return getCleanGameName(mFileID, mSystem); }
private:
std::string mFileID;
SystemData* mSystem;
FileType mType;
mutable std::string mNameCache;
};
| 27.266667 | 113 | 0.735941 | [
"vector"
] |
46f028a3f73899365ab8a05a5ee91dd37df64ed4 | 6,709 | h | C | Classes/Foundation/Coding/AJRXMLCoder.h | araftis/AJRFoundation | 5b849caa1d24b1638927c49ee22a1466bd50acfb | [
"BSD-3-Clause"
] | null | null | null | Classes/Foundation/Coding/AJRXMLCoder.h | araftis/AJRFoundation | 5b849caa1d24b1638927c49ee22a1466bd50acfb | [
"BSD-3-Clause"
] | null | null | null | Classes/Foundation/Coding/AJRXMLCoder.h | araftis/AJRFoundation | 5b849caa1d24b1638927c49ee22a1466bd50acfb | [
"BSD-3-Clause"
] | null | null | null | /*
AJRXMLCoder.h
AJRFoundation
Copyright © 2021, AJ Raftis and AJRFoundation authors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of AJRFoundation nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AJ RAFTIS 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.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
extern NSString * const AJRXMLCodingException;
extern NSString * const AJRXMLCodingErrorDomain;
extern NSString * const AJRXMLCodingLogDomain;
typedef void (^AJRXMLUnarchiverFinalizer)(void);
typedef BOOL (^AJRXMLUnarchiverGenericSetter)(id _Nullable rawValue, NSError * _Nullable * _Nullable error);
@interface NSObject (AJRXMLCoding)
@property (nonatomic,class,readonly) NSString *ajr_nameForXMLArchiving;
@property (nonatomic,readonly) NSString *ajr_nameForXMLArchiving;
@property (nonatomic,class,readonly) Class ajr_classForXMLArchiving;
@property (nonatomic,readonly) Class ajr_classForXMLArchiving;
@end
@interface AJRXMLCoder : NSObject
- (id)initWithStream:(NSStream *)stream;
@property (nonatomic,readonly) NSStream *stream;
- (void)encodeRootObject:(id)object forKey:(nullable NSString *)key;
- (void)encodeObject:(id)object;
- (void)encodeObject:(nullable id)object forKey:(NSString *)key;
- (void)encodeObjectReference:(id)object;
- (void)encodeObjectReference:(nullable id)object forKey:(NSString *)key;
- (void)encodeBool:(BOOL)number forKey:(NSString *)key;
- (void)encodeInteger:(NSInteger)number forKey:(NSString *)key;
- (void)encodeInt:(int)number forKey:(NSString *)key;
- (void)encodeInt32:(int32_t)number forKey:(NSString *)key;
- (void)encodeInt64:(int64_t)number forKey:(NSString *)key;
- (void)encodeUInteger:(NSUInteger)number forKey:(NSString *)key;
- (void)encodeUInt:(unsigned int)number forKey:(NSString *)key;
- (void)encodeUInt32:(uint32_t)number forKey:(NSString *)key;
- (void)encodeUInt64:(uint64_t)number forKey:(NSString *)key;
- (void)encodeFloat:(float)number forKey:(NSString *)key;
- (void)encodeDouble:(double)number forKey:(NSString *)key;
- (void)encodeBytes:(const uint8_t *)bytes length:(NSUInteger)length;
- (void)encodeBytes:(const uint8_t *)bytes length:(NSUInteger)length forKey:(NSString *)key;
- (void)encodeRange:(NSRange)range forKey:(NSString *)key;
// Additional conveniences that produce slightly nicer results than the default implementations
- (void)encodeObjectIfNotNil:(nullable id)object forKey:(NSString *)key;
- (void)encodeGroupForKey:(NSString *)key usingBlock:(void (^)(void))block;
- (void)encodeString:(NSString *)value forKey:(NSString *)key;
- (void)encodeCString:(const char *)value forKey:(NSString *)key;
- (void)encodeKey:(NSString *)key withCStringFormat:(const char *)format arguments:(va_list)args;
- (void)encodeKey:(NSString *)key withCStringFormat:(const char *)format, ...;
- (void)encodeText:(NSString *)text;
- (void)encodeText:(NSString *)text forKey:(NSString *)key;
- (void)encodeComment:(NSString *)text;
- (void)encodeURL:(NSURL *)url forKey:(NSString *)key;
- (void)encodeURLBookmark:(NSURL *)url forKey:(NSString *)key;
- (void)finalizeDecodeWithBlock:(AJRXMLUnarchiverFinalizer)finalizer;
- (void)decodeObjectForKey:(NSString *)key setter:(nullable void (^)(id _Nullable object))setter;
- (void)decodeObjectUsingSetter:(nullable void (^)(id object))setter;
- (void)decodeStringForKey:(NSString *)key setter:(nullable void (^)(NSString *string))setter;
- (void)decodeCStringForKey:(NSString *)key setter:(nullable void (^)(const char *string))setter;
- (void)decodeBoolForKey:(NSString *)key setter:(nullable void (^)(BOOL value))setter;
- (void)decodeIntegerForKey:(NSString *)key setter:(nullable void (^)(NSInteger value))setter;
- (void)decodeIntForKey:(NSString *)key setter:(nullable void (^)(int value))setter;
- (void)decodeInt32ForKey:(NSString *)key setter:(nullable void (^)(int32_t value))setter;
- (void)decodeInt64ForKey:(NSString *)key setter:(nullable void (^)(int64_t value))setter;
- (void)decodeUIntegerForKey:(NSString *)key setter:(nullable void (^)(NSUInteger value))setter;
- (void)decodeUIntForKey:(NSString *)key setter:(nullable void (^)(unsigned int value))setter;
- (void)decodeUInt32ForKey:(NSString *)key setter:(nullable void (^)(uint32_t value))setter;
- (void)decodeUInt64ForKey:(NSString *)key setter:(nullable void (^)(uint64_t value))setter;
- (void)decodeFloatForKey:(NSString *)key setter:(nullable void (^)(float value))setter;
- (void)decodeDoubleForKey:(NSString *)key setter:(nullable void (^)(double value))setter;
- (void)decodeBytesForKey:(NSString *)key setter:(nullable void (^)(uint8_t *, NSUInteger length))setter;
- (void)decodeBytesUsingSetter:(nullable void (^)(uint8_t *, NSUInteger length))setter;
- (void)decodeRangeForKey:(NSString *)key setter:(void (^)(NSRange range))setter;
// Additional conveniences that produce slightly nicer results than the default implementations
- (void)decodeGroupForKey:(NSString *)key usingBlock:(void (^)(void))block setter:(nullable void (^)(void))setter;
- (void)decodeTextUsingSetter:(void (^)(NSString *))setter;
- (void)decodeURLForKey:(NSString *)key setter:(nullable void (^)(NSURL *url))setter;
- (void)decodeURLBookmarkForKey:(NSString *)key setter:(nullable void (^)(NSURL *url))setter;
@end
extern NSNumberFormatter *AJRXMLCoderGetDoubleFormatter(void); // Formatter with 10 places after decimal.
extern NSNumberFormatter *AJRXMLCoderGetFloatFormatter(void); // Formatter with 5 places after decimal.
NS_ASSUME_NONNULL_END
| 54.991803 | 114 | 0.775525 | [
"object"
] |
46f23595f75ed85b71b9492f4f97e750c9e02bd5 | 82,647 | c | C | source/3rd/cpl-7.1.4/cplcore/tests/cpl_image_basic-test.c | ray820328/Funra | 99c89a7a40798fb41dd401195fcc4711bec2520b | [
"MIT"
] | null | null | null | source/3rd/cpl-7.1.4/cplcore/tests/cpl_image_basic-test.c | ray820328/Funra | 99c89a7a40798fb41dd401195fcc4711bec2520b | [
"MIT"
] | null | null | null | source/3rd/cpl-7.1.4/cplcore/tests/cpl_image_basic-test.c | ray820328/Funra | 99c89a7a40798fb41dd401195fcc4711bec2520b | [
"MIT"
] | null | null | null | /*
* This file is part of the ESO Common Pipeline Library
* Copyright (C) 2001-2017 European Southern Observatory
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*-----------------------------------------------------------------------------
Includes
-----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <complex.h>
#include "cpl_image_basic.h"
#include "cpl_image_stats.h"
#include "cpl_image_filter.h"
#include "cpl_image_gen.h"
#include "cpl_image_bpm.h"
#include "cpl_image_io.h"
#include "cpl_stats.h"
#include "cpl_vector.h"
#include "cpl_memory.h"
#include "cpl_test.h"
#include "cpl_math_const.h"
#include "cpl_tools.h"
/*-----------------------------------------------------------------------------
Defines
-----------------------------------------------------------------------------*/
#ifndef IMAGESZ
#define IMAGESZ 512
#endif
#define MAGIC_PIXEL 42
#define POLY_SIZE 24
/*-----------------------------------------------------------------------------
Private function prototypes
-----------------------------------------------------------------------------*/
static void cpl_image_flip_turn_test(const cpl_image *);
static void cpl_image_turn_flip_test(void);
static void cpl_image_copy_test(void);
static void cpl_image_collapse_median_test(void);
static void cpl_image_complex_mult(size_t o1, size_t o2, size_t n);
static void cpl_image_complex_mult_d(size_t o1, size_t o2, size_t n);
static void cpl_image_get_fwhm_test(void);
static void cpl_image_divide_test_one(void);
static void cpl_image_power_test(void);
static void cpl_image_hypot_test(void);
static void cpl_image_bitwise_test(cpl_size, cpl_size);
static void cpl_image_divide_create_test(void);
/*-----------------------------------------------------------------------------
Main
-----------------------------------------------------------------------------*/
int main(void)
{
cpl_image * imf1;
cpl_image * imf2;
cpl_image * imd1;
cpl_image * imd2;
cpl_image * imi1;
cpl_image * imi2;
cpl_image * imf;
cpl_image * imd;
cpl_image * imi;
cpl_image * imtmp;
cpl_image * imfc1;
cpl_image * imfc2;
cpl_image * imfc3;
float complex * dataf1;
float complex * dataf2;
float complex * dataf3;
cpl_image * imdc1;
cpl_image * imdc2;
cpl_image * imdc3;
double complex * data1;
double complex * data2;
double complex * data3;
cpl_vector * taylor;
double * ddata;
int nb_cut;
const cpl_size new_pos[9] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
double err;
double value;
int is_rejected;
cpl_mask * mask;
int is_bad;
int i, j, k;
cpl_error_code error;
cpl_boolean do_bench;
/*
* FIXME: Ideally, we should simply use the macro I
* (ISO/IEC 9899:1999(E) - Section 7.3.1 - Paragraph 4)
* for arithmetics involving the imaginary unit.
*
* However, the usage of this macro I makes gcc issue the following
*
* warning: imaginary constants are a GCC extension
*
* when the flag --pedantic is on.
*
* This is a bug in gcc (seems to be related to Bugzilla #7263) and, as a
* workaround in order to avoid that warning, we compute ourselves the
* value of the macro.
*/
double complex cpl_i = csqrt(-1.0);
cpl_test_init(PACKAGE_BUGREPORT, CPL_MSG_WARNING);
do_bench = cpl_msg_get_level() <= CPL_MSG_INFO ? CPL_TRUE : CPL_FALSE;
/* Insert tests below */
cpl_image_bitwise_test(IMAGESZ, IMAGESZ);
cpl_image_bitwise_test(1, 1);
cpl_image_bitwise_test(17, 15);
cpl_image_bitwise_test(3, 32);
if (do_bench) {
double secs = cpl_test_get_walltime();
for (i = 0; i < 2; i++) {
cpl_image_bitwise_test(IMAGESZ/2, IMAGESZ/2);
cpl_image_bitwise_test(IMAGESZ, IMAGESZ);
cpl_image_bitwise_test(IMAGESZ*2, IMAGESZ*2);
cpl_image_bitwise_test(IMAGESZ*4, IMAGESZ*4);
}
secs = cpl_test_get_walltime() - secs;
cpl_msg_info(cpl_func, "Time to test bit-wise calls [s]: %g", secs);
}
cpl_image_hypot_test();
cpl_image_power_test();
cpl_image_divide_test_one();
cpl_image_get_fwhm_test();
cpl_image_collapse_median_test();
cpl_image_copy_test();
cpl_image_turn_flip_test();
cpl_image_divide_create_test();
/* Tests of cpl_image_collapse_window_create() */
/* Tests of cpl_image_collapse_create() */
imtmp = cpl_image_collapse_create(NULL, 1);
cpl_test_error( CPL_ERROR_NULL_INPUT );
cpl_test_null( imtmp );
imtmp = cpl_image_collapse_window_create(NULL, 1, 1, 1, 1, 1);
cpl_test_error( CPL_ERROR_NULL_INPUT );
cpl_test_null( imtmp );
imd = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
imtmp = cpl_image_collapse_create(imd, -1);
cpl_test_error( CPL_ERROR_ILLEGAL_INPUT );
cpl_test_null( imtmp );
/* Set two pixels in the last columns to 1 */
cpl_test_zero(cpl_image_set(imd, IMAGESZ-1, IMAGESZ, 1.0));
cpl_test_zero(cpl_image_set(imd, IMAGESZ, IMAGESZ, 1.0));
/* No BPM */
/* Collapse the x-direction to an image with 1 row */
imtmp = cpl_image_collapse_create(imd, 1);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 1);
cpl_test_eq( cpl_image_get_size_y(imtmp), IMAGESZ);
cpl_test_zero( cpl_image_get(imtmp, 1, IMAGESZ-1, &is_bad));
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 1, IMAGESZ, &is_bad), 2);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
imtmp = cpl_image_collapse_window_create(imd, IMAGESZ-1, IMAGESZ-1,
IMAGESZ, IMAGESZ, 1);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 1);
cpl_test_eq( cpl_image_get_size_y(imtmp), 2);
cpl_test_zero( cpl_image_get(imtmp, 1, 1, &is_bad));
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 1, 2, &is_bad), 2);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
/* Collapse the y-direction to an image with 1 column */
imtmp = cpl_image_collapse_create(imd, 0);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), IMAGESZ);
cpl_test_eq( cpl_image_get_size_y(imtmp), 1);
cpl_test_eq( cpl_image_get(imtmp, IMAGESZ - 1, 1, &is_bad), 1);
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, IMAGESZ, 1, &is_bad), 1);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
imtmp = cpl_image_collapse_window_create(imd, IMAGESZ-1, IMAGESZ-1,
IMAGESZ, IMAGESZ, 0);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 2);
cpl_test_eq( cpl_image_get_size_y(imtmp), 1);
cpl_test_eq( cpl_image_get(imtmp, 1, 1, &is_bad), 1);
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 2, 1, &is_bad), 1);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
/* Force creation of BPM */
mask = cpl_image_get_bpm(imd);
/* Collapse the x-direction to an image with 1 row */
imtmp = cpl_image_collapse_window_create(imd, IMAGESZ-1, IMAGESZ-1,
IMAGESZ, IMAGESZ, 1);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 1);
cpl_test_eq( cpl_image_get_size_y(imtmp), 2);
cpl_test_zero( cpl_image_get(imtmp, 1, 1, &is_bad));
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 1, 2, &is_bad), 2);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
/* Collapse the y-direction to an image with 1 column */
imtmp = cpl_image_collapse_window_create(imd, IMAGESZ-1, IMAGESZ-1,
IMAGESZ, IMAGESZ, 0);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 2);
cpl_test_eq( cpl_image_get_size_y(imtmp), 1);
cpl_test_eq( cpl_image_get(imtmp, 1, 1, &is_bad), 1);
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 2, 1, &is_bad), 1);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
/* Flag the two zero pixels in the last row as bad */
cpl_test_zero( cpl_mask_set(mask, IMAGESZ-1, IMAGESZ-1, CPL_BINARY_1));
cpl_test_zero( cpl_mask_set(mask, IMAGESZ, IMAGESZ-1, CPL_BINARY_1));
/* Collapse the x-direction to an image with 1 row */
imtmp = cpl_image_collapse_window_create(imd, IMAGESZ-1, IMAGESZ-1,
IMAGESZ, IMAGESZ, 1);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 1);
cpl_test_eq( cpl_image_get_size_y(imtmp), 2);
value = cpl_image_get(imtmp, 1, 1, &is_bad);
cpl_test( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 1, 2, &is_bad), 2);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
/* Collapse the y-direction to an image with 1 column */
imtmp = cpl_image_collapse_window_create(imd, IMAGESZ-1, IMAGESZ-1,
IMAGESZ, IMAGESZ, 0);
cpl_test_eq( cpl_image_get_type(imtmp), cpl_image_get_type(imd));
cpl_test_eq( cpl_image_get_size_x(imtmp), 2);
cpl_test_eq( cpl_image_get_size_y(imtmp), 1);
cpl_test_eq( cpl_image_get(imtmp, 1, 1, &is_bad), 2);
cpl_test_zero( is_bad );
cpl_test_eq( cpl_image_get(imtmp, 2, 1, &is_bad), 2);
cpl_test_zero( is_bad );
cpl_image_delete(imtmp);
/* Finished testing cpl_image_collapse_window_create() */
/* Finished testing cpl_image_collapse_create() */
cpl_image_delete(imd);
/* Test for DFS 1724 */
imd1 = cpl_image_new(2, 2, CPL_TYPE_DOUBLE);
imd2 = cpl_image_new(2, 2, CPL_TYPE_DOUBLE);
imi1 = cpl_image_new(2, 2, CPL_TYPE_INT);
imi2 = cpl_image_new(2, 2, CPL_TYPE_INT);
/* Fill images with values 0, 1, 2, 3 */
value = 0.0;
for (i=1; i <= 2; i++) {
for (j=1; j <= 2; j++) {
cpl_test_zero( cpl_image_set(imd1, i, j, value));
cpl_test_zero( cpl_image_set(imd2, i, j, value));
cpl_test_zero( cpl_image_set(imi1, i, j, value));
cpl_test_zero( cpl_image_set(imi2, i, j, value));
value++;
}
}
/* Test cpl_image_divide_create() on integer and double */
imd = cpl_image_divide_create(imd1, imd2);
cpl_test_nonnull( imd);
imi = cpl_image_divide_create(imi1, imi2);
cpl_test_nonnull( imi);
value = 0.0;
for (i=1; i <= 2; i++) {
for (j=1; j <= 2; j++, value++) {
const double vald = cpl_image_get(imd, i, j, &is_bad);
const double vali = cpl_image_get(imi, i, j, &is_bad);
if (value != 0.0) cpl_test_abs(vald, 1.0, 0.0);
if (value != 0.0) cpl_test_abs(vali, 1.0, 0.0);
}
}
/* Test with lo_cut equal to hi_cut */
error = cpl_image_threshold(imd1, (double)MAGIC_PIXEL, (double)MAGIC_PIXEL,
(double)MAGIC_PIXEL, (double)MAGIC_PIXEL);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_test_leq( cpl_image_get_max(imd1), (double)MAGIC_PIXEL);
cpl_test_leq( (double)MAGIC_PIXEL, cpl_image_get_min(imd1));
cpl_image_delete(imd1);
cpl_image_delete(imd2);
cpl_image_delete(imd);
cpl_image_delete(imi1);
cpl_image_delete(imi2);
cpl_image_delete(imi);
/* Test for DFS02782 */
imi = cpl_image_new(1, 1, CPL_TYPE_INT);
imd = cpl_image_new(1, 1, CPL_TYPE_DOUBLE);
cpl_image_set(imi, 1, 1, 10);
cpl_image_set(imd, 1, 1, 0.5);
imi1 = cpl_image_divide_create(imi, imd);
cpl_image_delete(imi);
cpl_image_delete(imd);
value = cpl_image_get(imi1, 1, 1, &is_bad);
cpl_test_abs(value, 20.0, 0.0);
cpl_image_delete(imi1);
imd = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
/* Fill the image with a sinus */
ddata = cpl_image_get_data(imd);
cpl_test_nonnull( ddata );
for (i=0; i < IMAGESZ; i++) {
for (j=0; j < IMAGESZ; j++) {
value = sin(i*CPL_MATH_2PI/IMAGESZ) * sin(j*CPL_MATH_2PI/IMAGESZ);
if (cpl_image_set(imd, i+1, j+1, value)) break;
if ( ddata[i + j * IMAGESZ] != value ) break;
if (cpl_image_get(imd, i+1, j+1, &is_rejected) != value) break;
if (is_rejected) break; /* Not really useful */
}
cpl_test_eq( j, IMAGESZ);
}
imd1 = cpl_image_duplicate(imd);
cpl_test_nonnull( imd1 );
cpl_test_zero( cpl_image_fft(imd1, NULL, CPL_FFT_DEFAULT) );
cpl_test_zero( cpl_image_abs(imd1) );
/* 4 FFT-components are non-zero */
value = IMAGESZ*IMAGESZ/4;
err = fabs(cpl_image_get(imd1, 2, 2, &is_rejected) - value);
cpl_test_zero( cpl_image_set(imd1, 2, 2, err) );
err = fabs(cpl_image_get(imd1, 2, IMAGESZ, &is_rejected) - value);
cpl_test_zero( cpl_image_set(imd1, 2, IMAGESZ, err) );
err = fabs(cpl_image_get(imd1, IMAGESZ, 2, &is_rejected) - value);
cpl_test_zero( cpl_image_set(imd1, IMAGESZ, 2, err) );
err = fabs(cpl_image_get(imd1, IMAGESZ, IMAGESZ, &is_rejected) - value);
cpl_test_zero( cpl_image_set(imd1, IMAGESZ, IMAGESZ, err) );
err = cpl_image_get_max(imd1);
cpl_msg_info("", "FFT(%g) round-off [DBL_EPSILON]: %g < %d", value,
err/DBL_EPSILON, IMAGESZ*IMAGESZ);
cpl_test_leq( fabs(err), IMAGESZ*IMAGESZ * DBL_EPSILON);
cpl_image_delete(imd1);
/* Create a Taylor-expansion of exp() */
cpl_test_nonnull( taylor = cpl_vector_new(POLY_SIZE) );
i = 0;
cpl_vector_set(taylor, i, 1);
for (i=1; i<POLY_SIZE; i++)
cpl_vector_set(taylor, i, cpl_vector_get(taylor, i-1)/i);
/* Evaluate exp() using Horners scheme on the Taylor expansion */
imd2 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
cpl_test_nonnull( imd2 );
cpl_test_zero( cpl_image_add_scalar(imd2, cpl_vector_get(taylor,
POLY_SIZE-1)) );
for (k=POLY_SIZE-1; k > 0; k--) {
cpl_test_zero( cpl_image_multiply(imd2, imd) );
if (k&1) {
cpl_test_zero( cpl_image_add_scalar(imd2,
cpl_vector_get(taylor, k-1)) );
} else {
cpl_test_zero( cpl_image_subtract_scalar(imd2,
-cpl_vector_get(taylor, k-1)) );
}
}
/* Verify the result (against cpl_image_exponential() ) */
imd1 = cpl_image_duplicate(imd);
cpl_test_nonnull( imd1 );
cpl_test_zero( cpl_image_exponential(imd1, CPL_MATH_E) );
cpl_test_zero( cpl_image_subtract(imd2, imd1) );
cpl_test_zero( cpl_image_divide(imd2, imd1) );
cpl_test_zero( cpl_image_divide_scalar(imd2, DBL_EPSILON) );
cpl_test_leq( fabs(cpl_image_get_max(imd2)), 2.64494 );
cpl_test_leq( fabs(cpl_image_get_min(imd2)), 2.03626 );
cpl_image_delete(imd2);
/* Evaluate exp() using cpl_image_pow() on the Taylor expansion */
imd2 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
cpl_test_nonnull( imd2 );
cpl_test_zero( cpl_image_add_scalar(imd2, cpl_vector_get(taylor, 0)) );
/* POLY_SIZE > 10 on alphaev56:
Program received signal SIGFPE, Arithmetic exception.
0x200000a3ff0 in cpl_vector_multiply_scalar ()
*/
for (k=1; k < POLY_SIZE; k++) {
imtmp = cpl_image_duplicate(imd);
cpl_test_zero( cpl_image_power(imtmp, k) );
cpl_test_zero( cpl_image_multiply_scalar(imtmp, cpl_vector_get(taylor, k)) );
cpl_test_zero( cpl_image_add(imd2, imtmp) );
cpl_image_delete(imtmp);
}
cpl_vector_delete(taylor);
/* Much less precise than Horner ... */
cpl_test_image_abs(imd2, imd1, 16 * DBL_EPSILON);
/* Verify cpl_image_logarithm() ) */
cpl_test_zero( cpl_image_logarithm(imd1, 10) );
cpl_test_zero( cpl_image_multiply_scalar(imd1, CPL_MATH_LN10) );
cpl_test_image_abs(imd, imd1, 3 * DBL_EPSILON);
cpl_test_zero( cpl_image_exponential(imd, CPL_MATH_E) );
cpl_test_zero( cpl_image_copy(imd1, imd,1,1) );
cpl_test_zero( cpl_image_fft(imd1, NULL, CPL_FFT_DEFAULT) );
cpl_image_delete(imd2);
imd2 = cpl_image_duplicate(imd1);
cpl_test_nonnull( imd2 );
imtmp = cpl_image_duplicate(imd1);
cpl_test_nonnull( imtmp );
cpl_test_zero( cpl_image_copy(imd1, imd2, 1, 1) );
cpl_test_zero( cpl_image_add(imd1, imd2) );
cpl_test_zero( cpl_image_add(imd1, imd2) );
cpl_test_zero( cpl_image_add(imd1, imd2) );
cpl_test_zero( cpl_image_subtract(imd1, imd2) );
cpl_test_zero( cpl_image_multiply_scalar(imtmp, 3) );
cpl_test_eq(cpl_image_count_rejected(imtmp), 0);
cpl_test_zero( cpl_image_divide(imtmp, imd1) );
cpl_test_zero( cpl_image_abs(imtmp) );
cpl_test_abs( modf(IMAGESZ*IMAGESZ - cpl_image_get_flux(imtmp),
&err), 0.0, DBL_EPSILON);
cpl_test_eq(cpl_image_count_rejected(imtmp), err);
cpl_test_zero( cpl_image_fft(imd1, NULL, CPL_FFT_INVERSE) );
cpl_test_zero( cpl_image_divide_scalar(imd1, 3) );
cpl_test_image_abs(imd, imd1, 32 * DBL_EPSILON);
cpl_test_zero( cpl_image_copy(imd1, imd, 1, 1) );
cpl_test_zero( cpl_image_fft(imd1, NULL, CPL_FFT_INVERSE) );
cpl_test_zero( cpl_image_fft(imd1, NULL, CPL_FFT_DEFAULT) );
cpl_test_image_abs(imd, imd1, 32 * DBL_EPSILON);
cpl_image_delete(imd);
cpl_image_delete(imd1);
cpl_image_delete(imd2);
cpl_image_delete(imtmp);
/* Create test images */
imd1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
cpl_image_fill_noise_uniform(imd1, 1, 100);
imf1 = cpl_image_cast(imd1, CPL_TYPE_FLOAT);
imi1 = cpl_image_cast(imd1, CPL_TYPE_INT);
cpl_image_flip_turn_test(imd1);
cpl_image_flip_turn_test(imf1);
cpl_image_flip_turn_test(imi1);
imd2 = cpl_image_fill_test_create(IMAGESZ, IMAGESZ);
cpl_image_save(imd2, "test.fits", CPL_TYPE_FLOAT, NULL,
CPL_IO_CREATE);
remove("test.fits");
imf2 = cpl_image_cast(imd2, CPL_TYPE_FLOAT);
imi2 = cpl_image_cast(imd2, CPL_TYPE_INT);
cpl_test_nonnull( imd1 );
cpl_test_nonnull( imd2 );
cpl_test_nonnull( imf1 );
cpl_test_nonnull( imf2 );
cpl_test_nonnull( imi1 );
cpl_test_nonnull( imi2 );
/* COMPUTE imi =(imi1-imi2)*imi1/(imi1+imi2) with local functions */
cpl_msg_info("","Compute imi = (imi1-imi2)*imi1/(imi1+imi2) in INTEGER");
imi = cpl_image_duplicate(imi1);
cpl_test_zero( cpl_image_subtract(imi, imi2) );
cpl_test_zero( cpl_image_multiply(imi, imi1) );
imtmp = cpl_image_duplicate(imi1);
cpl_test_zero( cpl_image_add(imtmp, imi2) );
cpl_test_zero( cpl_image_divide(imi, imtmp) );
cpl_image_delete(imtmp);
/* Delete imi1 and imi2 */
cpl_image_delete(imi1);
cpl_image_delete(imi2);
/* COMPUTE imf =(imf1-imf2)*imf1/(imf1+imf2) with local functions */
cpl_msg_info("","Compute imf = (imf1-imf2)*imf1/(imf1+imf2) in FLOAT");
imf = cpl_image_duplicate(imf1);
cpl_test_zero( cpl_image_subtract(imf, imf2) );
cpl_test_zero( cpl_image_multiply(imf, imf1) );
imtmp = cpl_image_duplicate(imf1);
cpl_test_zero( cpl_image_add(imtmp, imf2) );
cpl_test_zero( cpl_image_divide(imf, imtmp) );
cpl_image_delete(imtmp);
/* Delete imf1 and imf2 */
cpl_image_delete(imf1);
cpl_image_delete(imf2);
/* COMPUTE imd =(imd1-imd2)*imd1/(imd1+imd2) with local functions */
cpl_msg_info("","Compute imd = (imd1-imd2)*imd1/(imd1+imd2) in DOUBLE");
imd = cpl_image_duplicate(imd1);
cpl_test_zero( cpl_image_subtract(imd, imd2) );
cpl_test_zero( cpl_image_multiply(imd, imd1) );
imtmp = cpl_image_duplicate(imd1);
cpl_test_zero( cpl_image_add(imtmp, imd2) );
cpl_test_zero( cpl_image_divide(imd, imtmp) );
cpl_image_delete(imtmp);
/* Delete imd1 and imd2 */
cpl_image_delete(imd1);
cpl_image_delete(imd2);
/* At this point imi, imf and imd are int, resp float and double type */
/* images with the same values - apart from differences in rounding. */
/* Test cpl_image_average_create() */
cpl_image_delete( cpl_image_average_create(imf, imd) );
/* Test collapse functions */
/* Set all pixels as bad */
mask = cpl_mask_new(IMAGESZ, IMAGESZ);
cpl_mask_not(mask);
cpl_image_reject_from_mask(imd, mask);
cpl_mask_delete(mask);
/* Collapse with bad pixels */
imtmp = cpl_image_collapse_create(imd, 0);
cpl_test_eq( cpl_mask_count(cpl_image_get_bpm(imtmp)), IMAGESZ);
cpl_image_delete(imtmp);
/* Reset the bad pixlels in imd */
cpl_image_accept_all(imd);
/* Collapse */
imtmp = cpl_image_collapse_create(imd, 0);
cpl_test_zero( cpl_mask_count(cpl_image_get_bpm(imtmp)));
cpl_image_delete(imtmp);
/* Median collapse */
imtmp = cpl_image_collapse_median_create(imf, 0, 10, 10);
cpl_image_delete(imtmp);
/* imf=((((imf+MAGIC_PIXEL)*MAGIC_PIXEL)-MAGIC_PIXEL)/-MAGIC_PIXEL)*/
/* with non local functions */
cpl_msg_info("","Compute imf = ((((imf+42)*42)-42)/-42)");
cpl_test_zero( cpl_image_add_scalar(imf, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_multiply_scalar(imf, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_subtract_scalar(imf, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_divide_scalar(imf, -(double)MAGIC_PIXEL) );
/* imd=((((imd+MAGIC_PIXEL)*MAGIC_PIXEL)-MAGIC_PIXEL)/-MAGIC_PIXEL)*/
/* with local functions */
cpl_msg_info("","Compute imd = ((((imd+42)*42)-42)/-42)");
cpl_test_zero( cpl_image_add_scalar(imd, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_multiply_scalar(imd, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_subtract_scalar(imd, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_divide_scalar(imd, -(double)MAGIC_PIXEL) );
/* imi=((((imi+MAGIC_PIXEL)*MAGIC_PIXEL)-MAGIC_PIXEL)/-MAGIC_PIXEL)*/
/* with local functions */
cpl_msg_info("","Compute imi = ((((imi+42)*42)-42)/-42)");
cpl_test_zero( cpl_image_add_scalar(imi, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_multiply_scalar(imi, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_subtract_scalar(imi, (double)MAGIC_PIXEL) );
cpl_test_zero( cpl_image_divide_scalar(imi, -(double)MAGIC_PIXEL) );
/* Compute imi = |imi|, imf = |imf| and imd = |imd| */
cpl_msg_info("","Take the absolute value of imi, imf and imd");
imtmp = cpl_image_abs_create(imi);
cpl_image_delete(imi);
imi = imtmp;
imtmp = NULL;
imtmp = cpl_image_abs_create(imf);
cpl_image_delete(imf);
imf = imtmp;
imtmp = NULL;
imtmp = cpl_image_abs_create(imd);
cpl_image_delete(imd);
imd = imtmp;
imtmp = NULL;
/* Test cpl_image_move() */
cpl_msg_info("","Test the pixels moving function on imd");
imd1 = cpl_image_extract(imd, 11, 11, 13, 16);
nb_cut = 3;
error = cpl_image_move(imd1, nb_cut, new_pos);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_image_delete(imd1);
/* Test extraction w. a bad pixel */
cpl_test_zero(cpl_image_reject(imd, 12, 14));
cpl_test_eq(cpl_image_count_rejected(imd), 1);
imd1 = cpl_image_extract(imd, 11, 11, 13, 16);
cpl_test_eq(cpl_image_get_size_x(imd1), 3);
cpl_test_eq(cpl_image_get_size_y(imd1), 6);
cpl_test(cpl_image_is_rejected(imd1, 2, 4));
cpl_image_delete(imd1);
/* Threshold imi, imf and imd */
cpl_msg_info("","Threshold imi, imf and imd");
cpl_image_threshold(imi, -DBL_MAX, (double)MAGIC_PIXEL,
0.0, (double)MAGIC_PIXEL);
cpl_image_threshold(imf, -DBL_MAX, (double)MAGIC_PIXEL,
0.0, (double)MAGIC_PIXEL);
cpl_image_threshold(imd, -DBL_MAX, (double)MAGIC_PIXEL,
0.0, (double)MAGIC_PIXEL);
/* Subtract the min of the image from the image -> imi, imf and imd */
cpl_msg_info("","Subtract the minimum for imi, imf and imd");
cpl_test_zero( cpl_image_subtract_scalar(imi, cpl_image_get_min(imi)) );
cpl_test_zero( cpl_image_subtract_scalar(imf, cpl_image_get_min(imf)) );
cpl_test_zero( cpl_image_subtract_scalar(imd, cpl_image_get_min(imd)) );
/* Extract sub windows from imf and imd */
cpl_msg_info("","Extract the central part of imi, imf and imd");
imtmp = cpl_image_extract(imi, IMAGESZ/4, IMAGESZ/4, IMAGESZ/2, IMAGESZ/2);
cpl_test_nonnull( imtmp );
cpl_image_delete(imi);
imi = imtmp;
imtmp = NULL;
imtmp = cpl_image_extract(imf, IMAGESZ/4, IMAGESZ/4, IMAGESZ/2, IMAGESZ/2);
cpl_test_nonnull( imtmp );
cpl_image_delete(imf);
imf = imtmp;
imtmp = NULL;
imtmp = cpl_image_extract(imd, IMAGESZ/4, IMAGESZ/4, IMAGESZ/2, IMAGESZ/2);
cpl_test_nonnull( imtmp );
cpl_image_delete(imd);
imd = imtmp;
imtmp = NULL;
/* Test exp operation */
cpl_msg_info("","Compute exp(imi), exp(imf) and exp(imd)");
cpl_test_zero( cpl_image_exponential(imi, CPL_MATH_E) );
cpl_test_zero( cpl_image_exponential(imf, CPL_MATH_E) );
cpl_test_zero( cpl_image_exponential(imd, CPL_MATH_E) );
/* Test log operation */
cpl_msg_info("","Compute log(imi), log(imf) and log(imd)");
cpl_test_zero( cpl_image_logarithm(imi, CPL_MATH_E) );
cpl_test_zero( cpl_image_logarithm(imf, CPL_MATH_E) );
cpl_test_zero( cpl_image_logarithm(imd, CPL_MATH_E) );
/* Test ^ operation */
cpl_msg_info("","Compute imi^2, imf^2 and imd^2");
cpl_test_zero( cpl_image_power(imi, 2.0) );
cpl_test_zero( cpl_image_power(imf, 2.0) );
cpl_test_zero( cpl_image_power(imd, 2.0) );
/* Test sqrt operation */
cpl_msg_info("","Compute imf^0.5 and imd^0.5");
cpl_test_zero( cpl_image_power(imf, 0.5) );
cpl_test_zero( cpl_image_power(imd, 0.5) );
/* TEST CROSS-TYPES OPERATIONS */
cpl_msg_info("","Test cross types operations");
imtmp = cpl_image_add_create(imf, imd);
cpl_msg_info("","Get mean of imf + imd : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_add_create(imd, imf);
cpl_msg_info("","Get mean of imd + imf : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_subtract_create(imf, imd);
cpl_msg_info("","Get mean of imf - imd : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_subtract_create(imd, imf);
cpl_msg_info("","Get mean of imd - imf : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_multiply_create(imf, imd);
cpl_msg_info("","Get mean of imf * imd : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_multiply_create(imd, imf);
cpl_msg_info("","Get mean of imd * imf : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_divide_create(imf, imd);
cpl_msg_info("","Get mean of imf / imd : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
imtmp = cpl_image_divide_create(imd, imf);
cpl_msg_info("","Get mean of imd / imf : %g", cpl_image_get_mean(imtmp));
cpl_image_delete(imtmp);
/* Normalize imf and imd */
cpl_msg_info("","Normalize imf and imd");
imtmp = cpl_image_normalise_create(imf, CPL_NORM_MEAN);
cpl_test_nonnull( imtmp );
cpl_image_delete(imf);
imf = imtmp;
imtmp = NULL;
imtmp = cpl_image_normalise_create(imd, CPL_NORM_MEAN);
cpl_test_nonnull( imtmp );
cpl_image_delete(imd);
imd = imtmp;
imtmp = NULL;
/* Test the insertion function */
cpl_msg_info("","Insert an image in an other one");
imtmp = cpl_image_duplicate(imd);
cpl_image_reject(imtmp, 1, 1);
cpl_test_zero( cpl_image_copy(imd, imtmp, 100, 100) );
cpl_test(cpl_image_is_rejected(imd, 100, 100));
cpl_image_delete(imtmp);
/* Test the shift function */
cpl_msg_info("","Compute various shifts on imi, imf and imda");
cpl_test_zero( cpl_image_shift(imd, 1, 1) );
cpl_test_zero( cpl_image_shift(imf, 1, 1) );
cpl_test_zero( cpl_image_shift(imi, 1, 1) );
cpl_image_delete(imi);
cpl_image_delete(imf);
cpl_image_delete(imd);
/* Test for DFS02049 : Handle the division by ZERO */
/* Divide 3 | 4 by 2 | 0 --> 1.5 | X */
/* - - - - - - */
/* 2 | 3 2 | 0 1 | X */
imtmp = cpl_image_new(2, 2, CPL_TYPE_DOUBLE);
imd = cpl_image_new(2, 2, CPL_TYPE_DOUBLE);
imf = cpl_image_new(2, 2, CPL_TYPE_FLOAT);
imi = cpl_image_new(2, 2, CPL_TYPE_INT);
for (i=0; i<2; i++) {
for (j=0; j<2; j++) {
if (i==0) cpl_image_set(imtmp, i+1, j+1, 2.0);
cpl_image_set(imi, i+1, j+1, (double)(i+j+2));
cpl_image_set(imf, i+1, j+1, (double)(i+j+2));
cpl_image_set(imd, i+1, j+1, (double)(i+j+2));
}
}
imd1 = cpl_image_divide_create(imd, imtmp);
imf1 = cpl_image_divide_create(imf, imtmp);
imi1 = cpl_image_divide_create(imi, imtmp);
cpl_test_nonnull( imd1 );
cpl_test_nonnull( imf1 );
cpl_test_nonnull( imi1 );
cpl_test_abs( cpl_image_get_flux(imd1), 2.5, 0.0 );
cpl_test_abs( cpl_image_get_flux(imf1), 2.5, 0.0 );
cpl_test_abs( cpl_image_get_flux(imi1), 2.0, 0.0 );
cpl_image_delete(imd1);
cpl_image_delete(imf1);
cpl_image_delete(imi1);
cpl_test_zero( cpl_image_divide(imd, imtmp) );
cpl_test_zero( cpl_image_divide(imf, imtmp) );
cpl_test_zero( cpl_image_divide(imi, imtmp) );
cpl_test_abs( cpl_image_get_flux(imd), 2.5, 0.0 );
cpl_test_abs( cpl_image_get_flux(imf), 2.5, 0.0 );
cpl_test_abs( cpl_image_get_flux(imi), 2.0, 0.0 );
cpl_image_delete(imtmp);
cpl_image_delete(imd);
cpl_image_delete(imf);
cpl_image_delete(imi);
/* Test 0^0 operation */
imf = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_FLOAT);
imd = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
imf1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_FLOAT);
imd1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
cpl_msg_info("","Compute imf(0.0)^0.0");
cpl_test_zero( cpl_image_power(imf, 0.0) );
cpl_test_zero( cpl_image_power(imd, 0.0) );
cpl_test_zero( cpl_image_subtract_scalar(imf, 1.0) );
cpl_test_zero( cpl_image_subtract_scalar(imd, 1.0) );
cpl_test_image_abs(imf, imf1, 0.0);
cpl_test_image_abs(imd, imd1, 0.0);
cpl_image_delete(imf);
cpl_image_delete(imd);
cpl_image_delete(imf1);
cpl_image_delete(imd1);
/* New tests for complex images */
/* DOUBLE */
imdc1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE_COMPLEX);
imdc2 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE_COMPLEX);
data1 = cpl_image_get_data_double_complex(imdc1);
data2 = cpl_image_get_data_double_complex(imdc2);
for (i = 0; i < IMAGESZ * IMAGESZ; i++) {
data1[i] = i + i * cpl_i;
data2[i] = 2 * i + 2 * i * cpl_i;
}
imdc3 = cpl_image_add_create(imdc1, imdc2);
data3 = cpl_image_get_data_double_complex(imdc3);
for (i = 0; i < IMAGESZ * IMAGESZ; i++) {
cpl_test_abs( data3[i], 3 * i + 3 * i * cpl_i, 0.0 );
}
cpl_image_delete(imdc1);
cpl_image_delete(imdc2);
cpl_image_delete(imdc3);
/* FLOAT */
imfc1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_FLOAT_COMPLEX);
imfc2 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_FLOAT_COMPLEX);
dataf1 = cpl_image_get_data_float_complex(imfc1);
dataf2 = cpl_image_get_data_float_complex(imfc2);
for (i = 0; i < IMAGESZ * IMAGESZ; i++) {
dataf1[i] = i + i * cpl_i;
dataf2[i] = 2 * i + 2 * i * cpl_i;
}
imfc3 = cpl_image_add_create(imfc1, imfc2);
dataf3 = cpl_image_get_data_float_complex(imfc3);
for (i = 0; i < IMAGESZ * IMAGESZ; i++) {
cpl_test_abs( dataf3[i], 3 * i + 3 * i * cpl_i, 0.0 );
}
cpl_image_delete(imfc1);
cpl_image_delete(imfc2);
cpl_image_delete(imfc3);
/* test complex multiplication with several alignments and sizes */
cpl_image_complex_mult(0, 0, 64);
cpl_image_complex_mult(1, 1, 64);
cpl_image_complex_mult(1, 0, 64);
cpl_image_complex_mult(0, 0, 63);
cpl_image_complex_mult(1, 1, 63);
cpl_image_complex_mult(1, 0, 63);
/* test complex multiplication with several alignments and sizes */
cpl_image_complex_mult_d(0, 0, 64);
cpl_image_complex_mult_d(1, 1, 64);
cpl_image_complex_mult_d(1, 0, 64);
cpl_image_complex_mult_d(0, 0, 63);
cpl_image_complex_mult_d(1, 1, 63);
cpl_image_complex_mult_d(1, 0, 63);
/* End of tests */
return cpl_test_end(0);
}
/**@}*/
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test cpl_image_complex multiplication
@param o1 image 1 offset
@param o2 image 2 offset
@param n npixels
@return void
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_complex_mult(size_t o1, size_t o2, size_t n)
{
/* test multiplication, compares vector version with scalar version */
const size_t nl = n + 2;
const float complex cpl_i = csqrtf(-1.0);
float complex * dataf1_ = cpl_malloc(nl * nl * sizeof(float complex));
float complex * dataf2_ = cpl_malloc(nl * nl * sizeof(float complex));
float complex * dataf3;
float complex * dataf4 = cpl_malloc(n * n * sizeof(float complex));
float complex * dataf1 = dataf1_;
float complex * dataf2 = dataf2_;
size_t do1 = ((intptr_t)dataf1) % 16;
size_t do2 = ((intptr_t)dataf2) % 16;
cpl_image * imfc1;
cpl_image * imfc2;
cpl_msg_info(cpl_func, "Float complex vector multiply, "
"size: %zu, offsets: %zu %zu", n * n, o1, o2);
do1 = (do1 ? (16u - do1) / sizeof(float complex) : 0u) + o1;
do2 = (do2 ? (16u - do2) / sizeof(float complex) : 0u) + o2;
dataf1 = dataf1 + do1;
dataf2 = dataf2 + do2;
for (size_t i = 0; i < n * n; i++) {
dataf1[i] = i + 12.2e-1 * i * cpl_i;
dataf2[i] = 3.23 * i + 2. * i * cpl_i;
}
/* add multiplication overflows, ignored in -ffast-math mode */
dataf1[0] = 1e30;
dataf2[0] = 1e30;
dataf1[1] = -1e30;
dataf2[1] = -1e30;
/* only one of the vector bad */
dataf2[2] = NAN + 1e30 * cpl_i;
dataf2[3] = -34.231e-5 + 4.111e+9 * cpl_i;
dataf2[4] = NAN + INFINITY * cpl_i;
dataf1[5] = 35.126e14 - INFINITY * cpl_i;
dataf2[5] = 35.126e14 - INFINITY * cpl_i;
/* subnormals */
dataf1[6] = 0.0000032e-37f - 0.0000001e-36f * cpl_i;
dataf2[6] = 0.16f - INFINITY * cpl_i;
dataf1[7] = 0.0000032e-37f - 0.0000001e-36f * cpl_i;
dataf2[7] = 1.16f - 0.0000001e-36f * cpl_i;
for (size_t i = 0; i < n * n; i++)
dataf4[i] = dataf1[i] * dataf2[i];
imfc1 = cpl_image_wrap(n, n, CPL_TYPE_FLOAT_COMPLEX, dataf1);
imfc2 = cpl_image_wrap(n, n, CPL_TYPE_FLOAT_COMPLEX, dataf2);
dataf3 = cpl_image_get_data_float_complex(imfc1);
/* multiply several times to get get multiplications
* involving special float values */
for (int j = 0; j < 3; j++) {
cpl_msg_info(cpl_func, "iteration: %d", j);
cpl_image_multiply(imfc1, imfc2);
for (size_t i = 0; i < n * n; i++) {
float r1 = creal(dataf3[i]);
float r2 = creal(dataf4[i]);
float i1 = cimag(dataf3[i]);
float i2 = cimag(dataf4[i]);
if (isnan(r1) || isnan(r2))
cpl_test_eq(isnan(r1), isnan(r2));
else if (isnan(i1) || isnan(i2))
cpl_test_eq(isnan(i1), isnan(i2));
else if (!isfinite(r1) || !isfinite(r2))
cpl_test_eq(isinf(r1), isinf(r2));
else if (!isfinite(i1) || !isfinite(i2))
cpl_test_eq(isinf(i1), isinf(i2));
else {
/* this test will fail if SSE is enabled but mfpmath=387, as
* the comparison numbers are then generated with different
* precision, the relative difference stays below ~ 1e-6,
* also set mfpmath=sse for consistent results */
cpl_test_abs(i1, i2, FLT_EPSILON);
cpl_test_abs(r1, r2, FLT_EPSILON);
}
dataf4[i] *= dataf2[i];
}
}
cpl_image_unwrap(imfc1);
cpl_image_unwrap(imfc2);
cpl_free(dataf1_);
cpl_free(dataf2_);
cpl_free(dataf4);
}
static void cpl_image_complex_mult_d(size_t o1, size_t o2, size_t n)
{
/* test multiplication, compares vector version with scalar version */
const size_t nl = n + 2;
const double complex cpl_i = csqrt(-1.0);
double complex * dataf1_ = cpl_malloc(nl * nl * sizeof(double complex));
double complex * dataf2_ = cpl_malloc(nl * nl * sizeof(double complex));
double complex * dataf3;
double complex * dataf4 = cpl_malloc(n * n * sizeof(double complex));
double complex * dataf1 = dataf1_;
double complex * dataf2 = dataf2_;
size_t do1 = ((intptr_t)dataf1) % 16;
size_t do2 = ((intptr_t)dataf2) % 16;
cpl_image * imfc1;
cpl_image * imfc2;
cpl_msg_info(cpl_func, "Double complex vector multiply, "
"size: %zu, offsets: %zu %zu", n * n, o1, o2);
/* i386 aligns complex double 8 bytes */
do1 = (do1 ? (16u - do1) / sizeof(double) : 0u) + o1;
do2 = (do2 ? (16u - do2) / sizeof(double) : 0u) + o2;
dataf1 = (double complex *)((double *)dataf1 + do1);
dataf2 = (double complex *)((double *)dataf2 + do2);
for (size_t i = 0; i < n * n; i++) {
dataf1[i] = i + 12.2e-1 * i * cpl_i;
dataf2[i] = 3.23 * i + 2. * i * cpl_i;
}
/* add multiplication overflows, ignored in -ffast-math mode */
dataf1[0] = 1e30;
dataf2[0] = 1e30;
dataf1[1] = -1e30;
dataf2[1] = -1e30;
/* only one of the vector bad */
dataf2[2] = NAN + 1e30 * cpl_i;
dataf2[3] = -34.231e-5 + 4.111e+9 * cpl_i;
dataf2[4] = NAN + INFINITY * cpl_i;
dataf1[5] = 35.126e14 - INFINITY * cpl_i;
dataf2[5] = 35.126e14 - INFINITY * cpl_i;
/* subnormals */
dataf1[6] = 0.00000000032e-307 - 0.0000000001e-306 * cpl_i;
dataf2[6] = 0.16 - INFINITY * cpl_i;
dataf1[7] = 0.0000000032e-307 - 443.1 * cpl_i;
dataf2[7] = 1.16 - 0.00000000001e-306 * cpl_i;
for (size_t i = 0; i < n * n; i++)
dataf4[i] = dataf1[i] * dataf2[i];
imfc1 = cpl_image_wrap(n, n, CPL_TYPE_DOUBLE_COMPLEX, dataf1);
imfc2 = cpl_image_wrap(n, n, CPL_TYPE_DOUBLE_COMPLEX, dataf2);
dataf3 = cpl_image_get_data_double_complex(imfc1);
/* multiply several times to get get multiplications
* involving special double values */
for (int j = 0; j < 3; j++) {
cpl_msg_info(cpl_func, "iteration: %d", j);
cpl_image_multiply(imfc1, imfc2);
for (size_t i = 0; i < n * n; i++) {
double r1 = creal(dataf3[i]);
double r2 = creal(dataf4[i]);
double i1 = cimag(dataf3[i]);
double i2 = cimag(dataf4[i]);
if (isnan(r1) || isnan(r2))
cpl_test_eq(isnan(r1), isnan(r2));
else if (isnan(i1) || isnan(i2))
cpl_test_eq(isnan(i1), isnan(i2));
else if (!isfinite(r1) || !isfinite(r2))
cpl_test_eq(isinf(r1), isinf(r2));
else if (!isfinite(i1) || !isfinite(i2))
cpl_test_eq(isinf(i1), isinf(i2));
else {
/* this test will fail if SSE is enabled but mfpmath=387, as
* the comparison numbers are then generated with different
* precision, the relative difference stays below ~ 1e-15,
* also set mfpmath=sse for consistent results */
cpl_test_abs(i1, i2, DBL_EPSILON);
cpl_test_abs(r1, r2, DBL_EPSILON);
}
dataf4[i] *= dataf2[i];
}
}
cpl_image_unwrap(imfc1);
cpl_image_unwrap(imfc2);
cpl_free(dataf1_);
cpl_free(dataf2_);
cpl_free(dataf4);
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test cpl_image_copy
@return void
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_copy_test(void)
{
cpl_image * im1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
cpl_image * im2 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_INT);
cpl_error_code error;
error = cpl_image_copy(NULL, im1, 1, 1);
cpl_test_eq_error(error, CPL_ERROR_NULL_INPUT);
error = cpl_image_copy(im1, NULL, 1, 1);
cpl_test_eq_error(error, CPL_ERROR_NULL_INPUT);
error = cpl_image_copy(im1, im2, 1, 1);
cpl_test_eq_error(error, CPL_ERROR_TYPE_MISMATCH);
cpl_image_delete(im1);
im1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_INT);
error = cpl_image_copy(im1, im2, 0, 1);
cpl_test_eq_error(error, CPL_ERROR_ACCESS_OUT_OF_RANGE);
error = cpl_image_copy(im1, im2, 1, 0);
cpl_test_eq_error(error, CPL_ERROR_ACCESS_OUT_OF_RANGE);
error = cpl_image_copy(im1, im2, IMAGESZ+1, 1);
cpl_test_eq_error(error, CPL_ERROR_ACCESS_OUT_OF_RANGE);
error = cpl_image_copy(im1, im2, 1, IMAGESZ+1);
cpl_test_eq_error(error, CPL_ERROR_ACCESS_OUT_OF_RANGE);
/* Test copy of whole image */
cpl_test_zero(cpl_image_add_scalar(im1, 1.0));
cpl_test_zero(cpl_image_copy(im1, im2, 1, 1));
cpl_test_zero(cpl_image_get_max(im1));
/* Test copy of whole number of columns (all but two) */
cpl_test_zero(cpl_image_add_scalar(im1, 1.0));
cpl_test_zero(cpl_image_copy(im1, im2, 3, 1));
cpl_test_abs(cpl_image_get_flux(im1), 2.0 * IMAGESZ, 0.0);
cpl_test_abs(cpl_image_get_flux_window(im1, 1, 1, 1, IMAGESZ), IMAGESZ, 0.0);
cpl_test_abs(cpl_image_get_flux_window(im1, 2, 1, 2, IMAGESZ), IMAGESZ, 0.0);
cpl_test_abs(cpl_image_get_flux_window(im1, 3, 1, IMAGESZ, IMAGESZ), 0.0, 0.0);
/* Test copy of whole number of rows (all but two) */
cpl_test_zero(cpl_image_copy(im1, im2, 1, 1));
cpl_test_zero(cpl_image_add_scalar(im1, 1.0));
cpl_test_zero(cpl_image_copy(im1, im2, 1, 3));
cpl_test_abs(cpl_image_get_flux(im1), 2.0 * IMAGESZ, 0.0);
cpl_test_abs(cpl_image_get_flux_window(im1, 1, 1, IMAGESZ, 1), IMAGESZ, 0.0);
cpl_test_abs(cpl_image_get_flux_window(im1, 1, 2, IMAGESZ, 2), IMAGESZ, 0.0);
cpl_test_abs(cpl_image_get_flux_window(im1, 1, 3, IMAGESZ, IMAGESZ), 0.0, 0.0);
cpl_image_delete(im1);
cpl_image_delete(im2);
return;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test cpl_image_turn() and cpl_image_flip()
@return void
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_turn_flip_test(void)
{
const cpl_type ttype[] = {CPL_TYPE_INT, CPL_TYPE_FLOAT, CPL_TYPE_DOUBLE};
size_t itype;
const int npix[] = {1, 2, 3, 5, 10, 11};
const int buf9[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
/* Rotate this 90 degrees clockwise to get buf9 */
const int rot9[] = {7, 4, 1, 8, 5, 2, 9, 6, 3};
/* This image is not modified while wrapping around this buffer */
cpl_image * ref = cpl_image_new(3, 3, CPL_TYPE_INT);
cpl_image * raw = cpl_image_new(3, 3, CPL_TYPE_INT);
cpl_error_code error;
cpl_test_eq_ptr(memcpy(cpl_image_get_data_int(ref), buf9, 9*sizeof(int)),
cpl_image_get_data_int_const(ref));
/* Test 1: Verify direction of 90 degree rotation */
cpl_test_eq_ptr(memcpy(cpl_image_get_data_int(raw), rot9, 9*sizeof(int)),
cpl_image_get_data_int_const(raw));
error = cpl_image_turn(raw, 1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_test_image_abs(raw, ref, 0.0);
cpl_image_delete(raw);
/* Test 1a: Verify flip around x=y and x=-y */
cpl_image_flip_turn_test(ref);
cpl_image_delete(ref);
/* Test 2: Check error handling */
error = cpl_image_turn(NULL, 1);
cpl_test_eq_error(error, CPL_ERROR_NULL_INPUT);
/* Test 3: Verify consistency of rotations across types */
for (itype = 0; itype < sizeof(ttype)/sizeof(ttype[0]); itype++) {
const cpl_type imtype = ttype[itype];
size_t ipix;
for (ipix = 0; ipix < sizeof(npix)/sizeof(npix[0]); ipix++) {
const int nx = npix[ipix];
size_t jpix;
for (jpix = 0; jpix < sizeof(npix)/sizeof(npix[0]); jpix++) {
const int ny = npix[jpix];
cpl_mask * bpm;
raw = cpl_image_new(nx, ny, imtype);
error = cpl_image_fill_noise_uniform(raw, (double)-ny,
(double)nx);
cpl_test_eq_error(error, CPL_ERROR_NONE);
/* About 1/4 of the pixels are flagged */
bpm = cpl_mask_threshold_image_create(raw, -0.25*ny, 0.25*nx);
if (cpl_mask_count(bpm) < nx * ny) {
/* Will not test with no good pixels */
error = cpl_image_reject_from_mask(raw, bpm);
cpl_test_eq_error(error, CPL_ERROR_NONE);
}
cpl_mask_delete(bpm);
ref = cpl_image_duplicate(raw);
/* Turn the image all the way around */
error = cpl_image_turn(raw, 1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw, 2);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw, 3);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw, 4);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw,-1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw,-2);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw,-3);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_turn(raw, 0);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_test_image_abs(raw, ref, 0.0);
/* Flip the image all the way around */
error = cpl_image_flip(raw, 0);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 2);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 3);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 0);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 2);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(raw, 3);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_test_image_abs(raw, ref, 0.0);
cpl_image_delete(ref);
cpl_image_delete(raw);
}
}
}
return;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test cpl_image_collapse_median_create()
@return void
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_collapse_median_test(void)
{
const int mx = IMAGESZ | 1;
const int my = IMAGESZ/2 | 1;
const cpl_type types[] = {CPL_TYPE_DOUBLE_COMPLEX,
CPL_TYPE_FLOAT_COMPLEX};
const cpl_type imtypes[] = {CPL_TYPE_DOUBLE, CPL_TYPE_FLOAT,
CPL_TYPE_INT};
cpl_image * null;
int ityp;
null = cpl_image_collapse_median_create(NULL, 0, 0, 0);
cpl_test_error(CPL_ERROR_NULL_INPUT);
cpl_test_null(null);
/* Iterate through all non-supported pixel types */
for (ityp = 0; ityp < (int)(sizeof(types)/sizeof(types[0])); ityp++) {
const cpl_type imtype = types[ityp];
cpl_image * img = cpl_image_new(mx, my, imtype);
cpl_test_nonnull(img);
null = cpl_image_collapse_median_create(img, 0, 0, 0);
cpl_test_error(CPL_ERROR_INVALID_TYPE);
cpl_test_null(null);
cpl_image_delete(img);
}
/* Iterate through all supported pixel types */
for (ityp = 0; ityp < (int)(sizeof(imtypes)/sizeof(imtypes[0])); ityp++) {
const cpl_type imtype = imtypes[ityp];
cpl_image * img = cpl_image_new(mx, my, imtype);
int idrop;
cpl_test_nonnull(img);
cpl_image_fill_noise_uniform(img, 0.0, IMAGESZ);
null = cpl_image_collapse_median_create(img, 0, my, 0);
cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
cpl_test_null(null);
null = cpl_image_collapse_median_create(img, 0, 0, my);
cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
cpl_test_null(null);
null = cpl_image_collapse_median_create(img, 1, 0, mx);
cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
cpl_test_null(null);
null = cpl_image_collapse_median_create(img, 1, mx, 0);
cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
cpl_test_null(null);
null = cpl_image_collapse_median_create(img, 2, 0, 0);
cpl_test_error(CPL_ERROR_ILLEGAL_INPUT);
cpl_test_null(null);
/* Iterate through various drop combinations for dir == 0 */
for (idrop = 0; idrop * 2 < 5; idrop ++) {
cpl_image * filt = cpl_image_new(mx, 1 + 2 * idrop, imtype);
cpl_mask * mask = cpl_mask_new(1, my - 2 * idrop);
int jdrop;
cpl_error_code error;
cpl_mask_not(mask);
error = cpl_image_filter_mask(filt, img, mask,
CPL_FILTER_MEDIAN, CPL_BORDER_CROP);
cpl_test_eq_error(error, CPL_ERROR_NONE);
for (jdrop = 0; jdrop <= 2 * idrop; jdrop++) {
cpl_image * med
= cpl_image_collapse_median_create(img, 0, jdrop,
2 * idrop - jdrop);
cpl_image * img1d = cpl_image_extract(filt, 1, 1 + jdrop, mx,
1 + jdrop);
int k, is_bad, is_bad2;
cpl_test_nonnull(med);
cpl_test_nonnull(img1d);
cpl_test_eq(cpl_image_get_type(med), imtype);
cpl_test_eq(cpl_image_get_size_x(med), mx);
cpl_test_eq(cpl_image_get_size_y(med), 1);
cpl_test_image_abs(med, img1d, 0.0);
cpl_image_delete(med);
/* Fail on all bad pixels */
cpl_mask_not(cpl_image_get_bpm(img));
cpl_test_eq(cpl_image_count_rejected(img), mx * my);
null = cpl_image_collapse_median_create(img, 0, jdrop,
2 * idrop - jdrop);
cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
cpl_test_null(null);
/* Accept all pixels in one column */
for (k = 1; k <= my; k++) {
cpl_image_accept(img, mx/2, k);
}
cpl_test_eq(cpl_image_count_rejected(img), mx * my - my);
med = cpl_image_collapse_median_create(img, 0, jdrop,
2 * idrop - jdrop);
cpl_test_nonnull(med);
cpl_test_eq(cpl_image_count_rejected(med), mx - 1);
cpl_test_abs(cpl_image_get(med, mx/2, 1, &is_bad),
cpl_image_get(img1d, mx/2, 1, &is_bad2), 0.0);
cpl_test_zero(is_bad);
cpl_test_zero(is_bad2);
cpl_test_abs(cpl_image_get(med, 1, 1, &is_bad), 0.0, 0.0);
cpl_test(is_bad);
cpl_image_delete(med);
cpl_image_delete(img1d);
cpl_image_accept_all(img);
/* Accept all pixels in one row */
cpl_mask_not(cpl_image_get_bpm(img));
for (k = 1; k <= mx; k++) {
cpl_image_accept(img, k, my/2);
}
med = cpl_image_collapse_median_create(img, 0, jdrop,
2 * idrop - jdrop);
cpl_test_nonnull(med);
cpl_test_zero(cpl_image_count_rejected(med));
img1d = cpl_image_extract(img, 1, my/2, mx, my/2);
cpl_test_image_abs(med, img1d, 0.0);
cpl_image_delete(img1d);
cpl_image_delete(med);
cpl_image_accept_all(img);
}
cpl_image_delete(filt);
cpl_mask_delete(mask);
}
/* Iterate through various drop combinations for dir == 1 */
for (idrop = 0; idrop * 2 < 5; idrop ++) {
cpl_image * filt = cpl_image_new(1 + 2 * idrop, my, imtype);
cpl_mask * mask = cpl_mask_new(mx - 2 * idrop, 1);
int jdrop;
cpl_error_code error;
cpl_mask_not(mask);
error = cpl_image_filter_mask(filt, img, mask,
CPL_FILTER_MEDIAN, CPL_BORDER_CROP);
cpl_test_eq_error(error, CPL_ERROR_NONE);
for (jdrop = 0; jdrop <= 2 * idrop; jdrop++) {
cpl_image * med
= cpl_image_collapse_median_create(img, 1, jdrop,
2 * idrop - jdrop);
cpl_image * img1d = cpl_image_extract(filt, 1 + jdrop, 1,
1 + jdrop, my);
int k, is_bad, is_bad2;
cpl_test_nonnull(med);
cpl_test_nonnull(img1d);
cpl_test_eq(cpl_image_get_type(med), imtype);
cpl_test_eq(cpl_image_get_size_x(med), 1);
cpl_test_eq(cpl_image_get_size_y(med), my);
cpl_test_image_abs(med, img1d, 0.0);
cpl_image_delete(med);
/* Fail on all bad pixels */
cpl_mask_not(cpl_image_get_bpm(img));
cpl_test_eq(cpl_image_count_rejected(img), mx * my);
null = cpl_image_collapse_median_create(img, 1, jdrop,
2 * idrop - jdrop);
cpl_test_error(CPL_ERROR_DATA_NOT_FOUND);
cpl_test_null(null);
/* Accept all pixels in one row */
for (k = 1; k <= mx; k++) {
cpl_image_accept(img, k, my/2);
}
cpl_test_eq(cpl_image_count_rejected(img), mx * my - mx);
med = cpl_image_collapse_median_create(img, 1, jdrop,
2 * idrop - jdrop);
cpl_test_nonnull(med);
cpl_test_eq(cpl_image_count_rejected(med), my - 1);
cpl_test_abs(cpl_image_get(med, 1, my/2, &is_bad),
cpl_image_get(img1d, 1, my/2, &is_bad2), 0.0);
cpl_test_zero(is_bad);
cpl_test_zero(is_bad2);
cpl_test_abs(cpl_image_get(med, 1, 1, &is_bad), 0.0, 0.0);
cpl_test(is_bad);
cpl_image_delete(med);
cpl_image_accept_all(img);
cpl_image_delete(img1d);
/* Accept all pixels in one column */
cpl_mask_not(cpl_image_get_bpm(img));
for (k = 1; k <= my; k++) {
cpl_image_accept(img, mx/2, k);
}
med = cpl_image_collapse_median_create(img, 1, jdrop,
2 * idrop - jdrop);
cpl_test_nonnull(med);
cpl_test_zero(cpl_image_count_rejected(med));
img1d = cpl_image_extract(img, mx/2, 1, mx/2, my);
cpl_test_image_abs(med, img1d, 0.0);
cpl_image_delete(img1d);
cpl_image_delete(med);
cpl_image_accept_all(img);
}
cpl_image_delete(filt);
cpl_mask_delete(mask);
}
cpl_image_delete(img);
}
return;
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test cpl_image_flip(), cpl_image_turn()
@param self The image to test
@return void
@see cpl_mask_flip_turn_test()
A:
Rotate 90 counterclock-wise, then
flip around the vertical axis, then
flip around x=y, and
it should be back to its original.
B:
Rotate 90 counterclock-wise, then
flip around the horizontal axis, then
flip around x=-y, and
it should be back to its original.
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_flip_turn_test(const cpl_image * self)
{
cpl_error_code error;
cpl_image * tmp = cpl_image_duplicate(self);
error = cpl_image_turn(tmp, -1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(tmp, 2);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(tmp, 1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_test_image_abs(self, tmp, 0.0);
error = cpl_image_turn(tmp, -1);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(tmp, 0);
cpl_test_eq_error(error, CPL_ERROR_NONE);
error = cpl_image_flip(tmp, 3);
cpl_test_eq_error(error, CPL_ERROR_NONE);
cpl_test_image_abs(self, tmp, 0.0);
cpl_image_delete(tmp);
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test the CPL function
@return void
@see cpl_image_get_fwhm()
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_get_fwhm_test(void)
{
/* Test case for DFS12346 */
const double x[] = {
-13.9055,
-2.24811,
-4.60207,
12.0745,
-9.29113,
19.4861,
17.6999,
32.2417,
68.0725,
120.824,
172.361,
242.671,
302.048,
355.937,
348.458,
309.819,
240.489,
179.107,
117.223,
66.3061,
32.7849,
22.9367,
};
const cpl_size sz = (cpl_size)(sizeof(x)/sizeof(x[0]));
/* x will _not_ be modified */
cpl_image * im1d = cpl_image_wrap_double(sz, 1, (double*)x);
cpl_size xmaxpos, ymaxpos;
double xfwhm, yfwhm, xref;
cpl_error_code code;
cpl_msg_info(cpl_func, "Testing cpl_image_get_fwhm() with %u elements",
(unsigned)sz);
code = cpl_image_get_maxpos(im1d, &xmaxpos, &ymaxpos);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_eq(xmaxpos, 14);
cpl_test_eq(ymaxpos, 1);
/* Test some error input */
code = cpl_image_get_fwhm(NULL, xmaxpos, ymaxpos, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = cpl_image_get_fwhm(im1d, xmaxpos, ymaxpos, NULL, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = cpl_image_get_fwhm(im1d, xmaxpos, ymaxpos, &xfwhm, NULL);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = cpl_image_get_fwhm(im1d, 0, ymaxpos, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_ACCESS_OUT_OF_RANGE);
code = cpl_image_get_fwhm(im1d, xmaxpos, 0, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_ACCESS_OUT_OF_RANGE);
code = cpl_image_get_fwhm(im1d, 0, ymaxpos, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_ACCESS_OUT_OF_RANGE);
code = cpl_image_get_fwhm(im1d, sz+1, ymaxpos, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_ACCESS_OUT_OF_RANGE);
code = cpl_image_get_fwhm(im1d, xmaxpos, 2, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_ACCESS_OUT_OF_RANGE);
code = cpl_image_get_fwhm(im1d, ymaxpos, ymaxpos, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_DATA_NOT_FOUND);
/* Test with valid input */
code = cpl_image_get_fwhm(im1d, xmaxpos, ymaxpos, &xfwhm, &yfwhm);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_abs(xfwhm, 6.7434, 1e-4);
cpl_test_abs(yfwhm, -1.0, 0.0);
/* Rotate the image 90 degrees (this does not modfy the pixel buffer) */
code = cpl_image_turn(im1d, -1);
cpl_test_eq_error(code, CPL_ERROR_NONE);
/* Call again, with x/y variables swapped */
xref = xfwhm;
code = cpl_image_get_fwhm(im1d, ymaxpos, xmaxpos, &yfwhm, &xfwhm);
cpl_test_eq_error(code, CPL_ERROR_NONE);
/* Expect exactly same result */
cpl_test_abs(xfwhm, xref, 0.0);
cpl_test_abs(yfwhm, -1.0, 0.0);
cpl_test_eq_ptr((const void*)x, cpl_image_unwrap(im1d));
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test the CPL function
@return void
@see cpl_image_divide()
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_divide_test_one(void) {
cpl_image * img1 = cpl_image_new(1, 2, CPL_TYPE_DOUBLE);
cpl_image * img2 = cpl_image_new(1, 2, CPL_TYPE_DOUBLE);
cpl_error_code code;
code = cpl_image_add_scalar(img1, 5.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_add_scalar(img2, 1.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_abs(cpl_image_get_flux(img1), 10.0, DBL_EPSILON);
cpl_test_zero(cpl_image_count_rejected(img1));
cpl_test_zero(cpl_image_count_rejected(img2));
code = cpl_image_reject(img1, 1, 1);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_eq(cpl_image_count_rejected(img1), 1);
cpl_test_abs(cpl_image_get_flux(img1), 5.0, DBL_EPSILON);
code = cpl_image_divide(img1, img2);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_abs(cpl_image_get_flux(img1), 5.0, DBL_EPSILON);
cpl_test_eq(cpl_image_count_rejected(img1), 1);
cpl_image_delete(img1);
cpl_image_delete(img2);
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test the CPL function
@return void
@see cpl_image_power()
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_hypot_test(void) {
const cpl_type htype[2] = {CPL_TYPE_FLOAT, CPL_TYPE_DOUBLE};
for (int i1type = 0; i1type < 2; i1type++) {
for (int i2type = 0; i2type < 2; i2type++) {
for (int i3type = 0; i3type < 2; i3type++) {
const double tol =
htype[i1type] == CPL_TYPE_FLOAT ||
htype[i2type] == CPL_TYPE_FLOAT ||
htype[i3type] == CPL_TYPE_FLOAT
? 40.0 * FLT_EPSILON
: 40.0 * DBL_EPSILON;
cpl_image * img1 = cpl_image_new(IMAGESZ, IMAGESZ, htype[i1type]);
cpl_image * img2 = cpl_image_new(IMAGESZ, IMAGESZ, htype[i2type]);
cpl_image * img3 = cpl_image_new(IMAGESZ, IMAGESZ, htype[i3type]);
cpl_image * img1copy;
cpl_image * img2copy;
cpl_error_code code;
code = cpl_image_fill_noise_uniform(img1, 1.0, MAGIC_PIXEL);
cpl_test_eq_error(code, CPL_ERROR_NONE);
img1copy = cpl_image_duplicate(img1);
code = cpl_image_fill_noise_uniform(img2, 1.0, MAGIC_PIXEL);
cpl_test_eq_error(code, CPL_ERROR_NONE);
img2copy = cpl_image_duplicate(img2);
code = cpl_image_hypot(img3, img1, img2);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_power(img1, 2.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_power(img2, 2.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_add(img1, img2);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_power(img1, 0.5);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(img1, img3, tol);
code = cpl_image_hypot(img1copy, NULL, img2copy);
cpl_test_eq_error(code, CPL_ERROR_NONE);
/* The in-place is not as accurate (w. all float data) ... */
cpl_test_image_abs(img1copy, img3, 1.5 * tol);
cpl_image_delete(img1);
cpl_image_delete(img2);
cpl_image_delete(img3);
/* Verify handling of incompatible size */
img3 = cpl_image_new(IMAGESZ+1, IMAGESZ, htype[i1type]);
code = cpl_image_hypot(img3, img1copy, img2copy);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = cpl_image_hypot(img1copy, img3, img2copy);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = cpl_image_hypot(img1copy, img2copy, img3);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = cpl_image_hypot(img3, NULL, img2copy);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = cpl_image_hypot(img2copy, NULL, img3);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
cpl_image_delete(img3);
/* Verify handling of unsupported type */
img3 = cpl_image_new(IMAGESZ+1, IMAGESZ, htype[i1type]
| CPL_TYPE_COMPLEX);
code = cpl_image_hypot(img3, img1copy, img2copy);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = cpl_image_hypot(img1copy, img3, img2copy);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = cpl_image_hypot(img1copy, img2copy, img3);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = cpl_image_hypot(img3, NULL, img2copy);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = cpl_image_hypot(img2copy, NULL, img3);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
cpl_image_delete(img3);
/* Verify handling of NULL pointers */
code = cpl_image_hypot(img1copy, img2copy, NULL);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = cpl_image_hypot(NULL, img1copy, img2copy);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
cpl_image_delete(img1copy);
cpl_image_delete(img2copy);
}
}
}
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test the CPL function
@return void
@see cpl_image_power()
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_power_test(void) {
cpl_image * img1 = cpl_image_new(IMAGESZ, IMAGESZ, CPL_TYPE_DOUBLE);
cpl_image * img2;
cpl_error_code code;
/* Avoid division by zero for now */
code = cpl_image_fill_noise_uniform(img1, 1.0, MAGIC_PIXEL);
cpl_test_eq_error(code, CPL_ERROR_NONE);
img2 = cpl_image_power_create(img1, 1.0);
cpl_test_error(CPL_ERROR_NONE);
cpl_test_nonnull(img2);
code = cpl_image_power(img1, -2.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_power(img1, -0.5);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(img1, img2, 40.0 * DBL_EPSILON);
cpl_image_delete(img2);
img2 = cpl_image_power_create(img1, 1.0);
cpl_test_error(CPL_ERROR_NONE);
cpl_test_nonnull(img2);
code = cpl_image_power(img1, -3.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_power(img1, -1.0/3.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(img1, img2, 100.0 * DBL_EPSILON);
cpl_image_delete(img1);
cpl_image_delete(img2);
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test the CPL function
@return void
@see cpl_image_and(), cpl_image_or(), cpl_image_xor()
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_bitwise_test(cpl_size nx, cpl_size ny)
{
cpl_error_code (*fimage[3])(cpl_image *, const cpl_image *,
const cpl_image *)
= {cpl_image_and, cpl_image_or, cpl_image_xor};
cpl_error_code (*fscalar[3])(cpl_image *, const cpl_image *,
cpl_bitmask)
= {cpl_image_and_scalar, cpl_image_or_scalar, cpl_image_xor_scalar};
const size_t nfunc = sizeof(fimage)/sizeof(*fimage);
cpl_image * imf = cpl_image_new(nx, ny, CPL_TYPE_FLOAT);
cpl_image * im01 = cpl_image_new(nx, ny + 1, CPL_TYPE_INT);
cpl_image * im10 = cpl_image_new(nx + 1, ny, CPL_TYPE_INT);
cpl_image * im0 = cpl_image_new(nx, ny, CPL_TYPE_INT);
cpl_image * im1 = cpl_image_new(nx, ny, CPL_TYPE_INT);
cpl_image * im2 = cpl_image_new(nx, ny, CPL_TYPE_INT);
cpl_mask * mask0 = cpl_mask_new(nx, ny);
cpl_error_code code;
cpl_test_eq( sizeof(fimage), sizeof(fscalar));
/* Test the handling of the 3 possible error types for all 7 functions */
for (size_t i = 0; i < nfunc; i++) {
const cpl_image * im3 = im1;
for (size_t i2 = 0; i2 < 2; i2++, im3 = NULL) {
code = fimage[i](NULL, im3, im2);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = fimage[i](im1, im3, NULL);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = fscalar[i](NULL, im3, 0);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = fimage[i](im01, im3, im2);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fimage[i](im10, im3, im2);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fimage[i](im1, im3, im01);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fimage[i](im1, im3, im10);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fimage[i](imf, im3, im2);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = fimage[i](im1, im3, imf);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = fscalar[i](imf, im3, 0);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
if (i == 0) {
code = cpl_image_not(NULL, im3);
cpl_test_eq_error(code, CPL_ERROR_NULL_INPUT);
code = cpl_image_not(imf, im3);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
}
}
code = fimage[i](im1, im01, im2);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fimage[i](im1, im10, im2);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fscalar[i](im1, im01, 0);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fscalar[i](im1, im10, 0);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fscalar[i](im01, im1, 0);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fscalar[i](im10, im1, 0);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = fimage[i](im1, imf, im2);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
code = fscalar[i](im1, imf, 0);
cpl_test_eq_error(code, CPL_ERROR_INVALID_TYPE);
}
code = cpl_image_not(im1, im01);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = cpl_image_not(im1, im10);
cpl_test_eq_error(code, CPL_ERROR_INCOMPATIBLE_INPUT);
code = cpl_image_fill_noise_uniform(im1,
-cpl_tools_ipow(2.0, 31),
cpl_tools_ipow(2.0, 31) - 1.0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_not(im2, im1);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_or(im0, im1, im2);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -1.5, -0.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
code = cpl_image_xor(im0, im1, im2);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -1.5, -0.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
code = cpl_image_and(im0, im1, im2);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -0.5, 0.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
code = cpl_image_and_scalar(im0, im1, 15);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -0.5, 15.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
if (cpl_mask_count(mask0)) {
int idummy;
cpl_test_eq(cpl_image_get(im0, 1, 1, &idummy), 15);
}
code = cpl_image_and_scalar(im0, im1, 0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -0.5, 0.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
code = cpl_image_and_scalar(im0, im1, 15);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -0.5, 15.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
code = cpl_image_and_scalar(im0, im1, (cpl_bitmask)-1);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(im0, im1, 0.0);
code = cpl_image_or_scalar(im0, im1, 0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(im0, im1, 0.0);
code = cpl_image_xor_scalar(im0, im1, 0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(im0, im1, 0.0);
code = cpl_image_or_scalar(im0, im1, (cpl_bitmask)-1);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_mask_threshold_image(mask0, im0, -1.5, -0.5, CPL_BINARY_0);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_zero(cpl_mask_count(mask0));
code = cpl_image_xor_scalar(im0, im1, (cpl_bitmask)-1);
cpl_test_eq_error(code, CPL_ERROR_NONE);
code = cpl_image_not(im0, NULL);
cpl_test_eq_error(code, CPL_ERROR_NONE);
cpl_test_image_abs(im0, im1, 0.0);
cpl_image_delete(imf);
cpl_image_delete(im01);
cpl_image_delete(im10);
cpl_image_delete(im0);
cpl_image_delete(im1);
cpl_image_delete(im2);
cpl_mask_delete(mask0);
}
/*----------------------------------------------------------------------------*/
/**
@internal
@brief Test the cpl_image_divide_create function
@return void
This test checks the behaviour of the cpl_image_divide_create function for
various cases of division by zeros and bad pixel masks.
*/
/*----------------------------------------------------------------------------*/
static void cpl_image_divide_create_test(void)
{
cpl_image * a = cpl_image_new(3, 3, CPL_TYPE_FLOAT);
cpl_image * b = cpl_image_new(3, 3, CPL_TYPE_FLOAT);
cpl_image * c = NULL;
const cpl_mask * m = NULL;
float * data_a = cpl_image_get_data_float(a);
float * data_b = cpl_image_get_data_float(b);
int i;
/* Make sure the reference images are initialised. Otherwise stop here. */
cpl_test_nonnull(a);
cpl_test_nonnull(b);
cpl_test_nonnull(data_a);
cpl_test_nonnull(data_b);
if (a == NULL || b == NULL || data_a == NULL || data_b == NULL) return;
/* [ 6 -7 8]
* Set image A to [-3 4 -5]
* [ 0 -1 2]
*/
for (i = 0; i < 9; ++i) data_a[i] = (float)i * (i % 2 == 0 ? 1.0 : -1.0);
/* Image B should be all zeros from the function call cpl_image_new. */
for (i = 0; i < 9; ++i) cpl_test(data_b[i] == 0.0);
/* Check that dividing by image B with all zeros produces a CPL divide by
* zero error code. */
c = cpl_image_divide_create(a, b);
cpl_test_null(c);
cpl_test_error(CPL_ERROR_DIVISION_BY_ZERO);
/* Check that the following holds A/B = C, where
* [ 6 -7 8] 1 [6 0 0] [ 1 0 0]
* A = [-3 4 -5] B = -- * [0 4 5] C = 10 * [ 0 1 -1]
* [ 0 -1 2] 10 [0 1 0] [ 0 -1 0]
* The bad pixel masks should be the following (X indicates bad, '.' good):
* [. X X]
* C_bpm = [X . .]
* [X . X]
*/
data_b[6] = 0.6; data_b[7] = 0.0; data_b[8] = 0.0;
data_b[3] = 0.0; data_b[4] = 0.4; data_b[5] = 0.5;
data_b[0] = 0.0; data_b[1] = 0.1; data_b[2] = 0.0;
c = cpl_image_divide_create(a, b);
cpl_test_nonnull(c);
cpl_test_error(CPL_ERROR_NONE);
cpl_test_abs(cpl_image_get_data_float_const(c)[0], 0.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[1], -10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[2], 0.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[3], 0.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[4], 10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[5], -10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[6], 10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[7], 0.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[8], 0.0, FLT_EPSILON);
/* Check the bad pixels. */
m = cpl_image_get_bpm_const(c);
cpl_test_nonnull(m);
cpl_test(cpl_mask_get_data_const(m)[0] == CPL_BINARY_1);
cpl_test(cpl_mask_get_data_const(m)[1] == CPL_BINARY_0);
cpl_test(cpl_mask_get_data_const(m)[2] == CPL_BINARY_1);
cpl_test(cpl_mask_get_data_const(m)[3] == CPL_BINARY_1);
cpl_test(cpl_mask_get_data_const(m)[4] == CPL_BINARY_0);
cpl_test(cpl_mask_get_data_const(m)[5] == CPL_BINARY_0);
cpl_test(cpl_mask_get_data_const(m)[6] == CPL_BINARY_0);
cpl_test(cpl_mask_get_data_const(m)[7] == CPL_BINARY_1);
cpl_test(cpl_mask_get_data_const(m)[8] == CPL_BINARY_1);
cpl_image_delete(c);
/* Check that the following holds A/B = C, where
* [ 6 -7 8] 1 [6 7 8] [ 1 -1 1]
* A = [-3 4 -5] B = -- * [3 4 5] C = 10 * [-1 1 -1]
* [ 0 -1 2] 10 [9 1 2] [ 0 -1 1]
* The resultant bad pixel masks should be (X indicates bad, '.' good):
* [. . .]
* C_bpm = [. . .]
* [. . .]
*/
data_b[6] = 0.6; data_b[7] = 0.7; data_b[8] = 0.8;
data_b[3] = 0.3; data_b[4] = 0.4; data_b[5] = 0.5;
data_b[0] = 0.9; data_b[1] = 0.1; data_b[2] = 0.2;
c = cpl_image_divide_create(a, b);
cpl_test_nonnull(c);
cpl_test_error(CPL_ERROR_NONE);
cpl_test_abs(cpl_image_get_data_float_const(c)[0], 0.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[1], -10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[2], 10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[3], -10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[4], 10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[5], -10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[6], 10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[7], -10.0, FLT_EPSILON);
cpl_test_abs(cpl_image_get_data_float_const(c)[8], 10.0, FLT_EPSILON);
/* Check that there are no bad pixels. Note, we check this using a slightly
* different method from above to test also cpl_image_is_rejected. */
m = cpl_image_get_bpm_const(c);
cpl_test_null(m);
cpl_test_zero(cpl_image_is_rejected(c, 1, 1));
cpl_test_zero(cpl_image_is_rejected(c, 2, 1));
cpl_test_zero(cpl_image_is_rejected(c, 3, 1));
cpl_test_zero(cpl_image_is_rejected(c, 1, 2));
cpl_test_zero(cpl_image_is_rejected(c, 2, 2));
cpl_test_zero(cpl_image_is_rejected(c, 3, 2));
cpl_test_zero(cpl_image_is_rejected(c, 1, 3));
cpl_test_zero(cpl_image_is_rejected(c, 2, 3));
cpl_test_zero(cpl_image_is_rejected(c, 3, 3));
cpl_image_delete(c);
cpl_image_delete(a);
cpl_image_delete(b);
}
| 35.949108 | 85 | 0.603906 | [
"vector"
] |
46f8622bfb07d3eb75164f88a82db398628b953b | 5,835 | h | C | LDSketch3/ldsketch.h | Paper-commits/MCSketch | 787e233b5b6cf09fc03a2bc98f33586a427ca34f | [
"Apache-2.0"
] | null | null | null | LDSketch3/ldsketch.h | Paper-commits/MCSketch | 787e233b5b6cf09fc03a2bc98f33586a427ca34f | [
"Apache-2.0"
] | null | null | null | LDSketch3/ldsketch.h | Paper-commits/MCSketch | 787e233b5b6cf09fc03a2bc98f33586a427ca34f | [
"Apache-2.0"
] | null | null | null | #ifndef _LDSKETCH_H
#define _LDSKETCH_H
#include "../common/param.h"
#include "../common/BOBHash32.h"
using namespace std;
class BUCKET{
public:
uint32_t sum = 0;
uint32_t error = 0;
uint32_t length = 0;
map<uint32_t,uint32_t> array;
uint32_t BucketUpdate(uint32_t cur_key, uint32_t cur_nbucket);
uint32_t BucketEstimate(uint32_t cur_key);
};
class LDSketch{
private:
// BUCKET *bucket;
int row;
int width;
int key_len = 4;
int cur_nbucket = 0;
BOBHash32 *hash[ROW_NUM];
vector<BUCKET> bucket;
public:
static uint32_t max_nbucket;
static uint32_t max_length;
static uint32_t T;
LDSketch(int total_memory, int threshold, float ratio);
void Insert(uint32_t key);
void Print_basic_info();
uint32_t Estimate(uint32_t cur_key);
map<uint32_t,int> Query_threshold(int threshold);
};
uint32_t LDSketch::max_nbucket = 0;
uint32_t LDSketch::max_length = 0;
uint32_t LDSketch::T = 0;
//uint32_t BUCKET::BucketUpdate
uint32_t BUCKET::BucketUpdate(uint32_t cur_key, uint32_t cur_nbucket){
sum +=1;
// new packet is stored in array
if(array.find(cur_key)!= array.end()){
array[cur_key] += 1;
}
// array size is smaller than length
else if(array.size() < length){
array.insert(pair<uint32_t,uint32_t>(cur_key,1));
} else{
uint32_t k = sum / LDSketch::T;
if(((k+1)*(k+2)-1)<= length) {
// get error
uint32_t tmp_min = 0;
for(auto iter = array.begin();iter!= array.end();iter++){
if(iter == array.begin()) tmp_min = iter->second;
else{
if(iter->second < tmp_min){
tmp_min = iter->second;
}
}
}
if( 1< tmp_min) tmp_min =1;
error += tmp_min;
//delete array which value is 1
for(auto iter = array.begin();iter!=array.end();){
iter-> second -= tmp_min;
if(iter->second == 0){
auto tmp_iter = next(iter);
array.erase(iter);
iter = tmp_iter;
}else{
iter++;
}
}
if(1 > tmp_min){
array.insert(pair<uint32_t,uint32_t>(cur_key,1-tmp_min));
}
}
else if(cur_nbucket < LDSketch::max_nbucket){
uint32_t prev_length = length;
length = (k+1)*(k+2) -1;
if(length >LDSketch::max_length){
length = LDSketch::max_length;
}
uint32_t delta_length = length - prev_length;
if(delta_length > LDSketch::max_nbucket - cur_nbucket){
length = prev_length + LDSketch::max_nbucket - cur_nbucket;
delta_length = LDSketch::max_nbucket - cur_nbucket;
}
array.insert(pair<uint32_t,uint32_t>(cur_key,1));
return delta_length;
}
}
return 0;
}
uint32_t BUCKET::BucketEstimate(uint32_t cur_key){
uint32_t result = 0;
if(array.size()> 0){
if(array.find(cur_key) != array.end()){
result = array[cur_key];
}
}
result += error;
return result;
}
LDSketch::LDSketch(int total_memory, int threshold, float ratio){
row = ROW_NUM;
uint32_t bucket_size = 4+4+4;//<sum,error,length>
uint32_t bucket_num = total_memory * ratio /bucket_size;
width = floor(bucket_num/row);
LDSketch::max_nbucket = total_memory*(1-ratio)/8;// <key,value> size is 8 byte;
LDSketch::max_length = 10;
LDSketch::T = threshold;
cur_nbucket = 0;
bucket.resize(width*row,BUCKET());
for(int i =0;i<row;i++)
hash[i] = new BOBHash32(i+750);
}
void LDSketch::Insert(uint32_t key){
int index;
int pos;
for (int i =0;i<row;i++){
index = (hash[i]->run((const char*)&key,key_len))%width;
pos = i*width + index;
// BUCKET* tmpbkt = &bucket[pos];
uint32_t delta = bucket[pos].BucketUpdate(key,cur_nbucket);
cur_nbucket += delta;
}
}
void LDSketch::Print_basic_info(){
cout<<"LDSketch"<<endl<<"\t bucket number: "<<width*row<<"\t width: "<<width<<endl;
cout<<"\t total cell number: "<<max_nbucket<<endl;
}
uint32_t LDSketch::Estimate(uint32_t cur_key){
uint32_t result = 0;
int index;
int pos;
for (int i = 0;i<ROW_NUM;i++){
index = (hash[i]->run((const char*)&cur_key,key_len))%width;
pos = i*width + index;
uint32_t tmp_res = bucket[pos].BucketEstimate(cur_key);
if(i==0||tmp_res<result)
result = tmp_res;
}
}
map<uint32_t,int> LDSketch::Query_threshold(int threshold){
map<uint32_t,int> result;
set<uint32_t> res;
for(int i =0;i<width*row;i++){
for(auto iter = bucket[i].array.begin();iter!=bucket[i].array.end();iter++){
if(iter->second > (uint32_t)threshold) res.insert(iter->first);
// j =0;j<bucket[i].array.size();j++){
// cout<<"test"<<endl;
// if(bucket[i].array[j])
}
}
for(auto iter = res.begin();iter!=res.end();iter++){
uint32_t value = Estimate(*iter);
if(value > (uint32_t)threshold){
result.insert(make_pair(*iter,value));
}
}
return result;
}
#endif
| 32.780899 | 88 | 0.521337 | [
"vector"
] |
46fc2263c3a6b192411d23b8d002c816fb9793ec | 7,175 | c | C | daemon/chat.c | facadepapergirl/shadowgate | 2b811671c5c85952ed93767753d72fc0d12819d8 | [
"MIT"
] | null | null | null | daemon/chat.c | facadepapergirl/shadowgate | 2b811671c5c85952ed93767753d72fc0d12819d8 | [
"MIT"
] | null | null | null | daemon/chat.c | facadepapergirl/shadowgate | 2b811671c5c85952ed93767753d72fc0d12819d8 | [
"MIT"
] | null | null | null | #include <udp.h>
#include <daemons.h>
#include <objects.h>
#include <std.h>
#define MAGENTA "%^MAGENTA%^"
#define RESET "%^RESET%^"
static private mapping channels;
int list_channel(string str);
object *arches(object *objs);
void do_amsg(object tp, object *list, string verb, string str, int emote);
/**
* @file
* @brief Channels related functions
*/
void create()
{
string *chans;
object *who;
int i, j;
seteuid(getuid());
channels = ([]);
i = sizeof(who = users());
while(i--)
{
j = sizeof(chans = (string *)who[i]->query_channels());
while(j--)
{
if(!channels[chans[j]]) channels[chans[j]] = ({});
channels[chans[j]] = distinct_array(channels[chans[j]]+({who[i]}));
}
}
}
/**
* This function formats messages
*
* @param chan Channel for the message
* @param name Name of the player
* @param position Special position character to display whether player is an imm or not
* @param message The message itself
* @param emote Whether it is an emote (ACTION)
*
* @return Formatted string
*
*/
string format_chat(string chan,string name,string position,string message,int emote)
{
string chanprefix;
//It HAS TO BE either
// '[channel] <.Name> message'
//or
// '[channel] * Name action'
// if you wish continued support of IPC chats.
//Coloration is irrelevant.
chanprefix = "%^RESET%^%^BLUE%^[%^BOLD%^%^CYAN%^" + chan +"%^RESET%^%^BLUE%^] " ;
if(emote)
return chanprefix+"%^RESET%^%^BOLD%^%^MAGENTA%^* %^RESET%^%^WHITE%^"+name+" "+message+"%^RESET%^";
else
return chanprefix+"%^GREEN%^<%^RESET%^%^ORANGE%^"+position+"%^BOLD%^%^GREEN%^"+name+"%^RESET%^%^GREEN%^>%^RESET%^ "+message+"%^RESET%^";
}
/**
* This function adds user to channels
*
* @param *chans Pointer to channels array
* @param who Whom to add
*
*/
varargs void add_user(string *chans, object who)
{
object ob;
int i;
if(objectp(who) && userp(who)) ob = who;
else if(base_name(ob = previous_object()) != OB_USER) return;
i = sizeof(chans);
while(i--)
{
if(!channels[chans[i]]) channels[chans[i]] = ({});
channels[chans[i]] = distinct_array(channels[chans[i]]+({ob}));
}
}
/**
* This function removes user from channels.
*
* @param *chans Pointer to channels array
*
*/
void remove_user(string *chans)
{
object ob;
int i;
if(base_name(ob = previous_object()) != OB_USER) return;
i = sizeof(chans);
while(i--)
{
if(!channels[chans[i]]) continue;
else channels[chans[i]] -= ({ ob });
if(!sizeof(channels[chans[i]])) map_delete(channels, chans[i]);
}
}
/**
* Sends message to everyone on related channel
*
* @param verb A verb user used to invoke this function. Could be a
* channel name or channel name+emote to indicate emotes and
* actions
* @param str Message user is sending
*
* @return 1 on success, 0 on failure.
*
*/
int do_chat(string verb, string str)
{
string msg;
int emote;
object *archlist, *pllist;
string tpname,tppos;
if(!channels[verb])
{
if(sscanf(verb, "%semote", verb)) emote = 1;
else return 0;
if(!channels[verb]) return 0;
}
if(member_array(TP, channels[verb]) == -1) return 0;
if(!str)
{
TP->set_blocked(verb);
return 1;
}
if((int)TP->query_blocked(verb))
{
if((int)TP->query_blocked("all"))
{
message(verb, "%^BOLD%^%^RED%^You cannot chat while totally blocked.%^RESET%^", TP);
return 1;
}
TP->set_blocked(verb);
}
str += RESET ;
pllist = channels[verb];
//pllist -= ({TP});
tpname=capitalize(TPQN);
if(wizardp(TP))
tppos="@";
else if (avatarp(TP))
tppos="%";
else
tppos=" ";
msg=format_chat(verb,tpname,tppos,str,emote);
message(verb,msg,pllist,ignored_list(TP));
//BUS_D->sendbus("CHAT",strip(msg));
return 1;
}
/**
* This function prints list of everyone on a channel
*
* @param str A channel to use
*
* @return 1 on succes, 0 on failure
*/
int list_channel(string str)
{
string list;
int i;
if(!channels[str]) return 0;
if(!avatarp(TP)) return 0;
if(member_array(TP, channels[str]) == -1) return 0;
list = "";
list = "%^BOLD%^Users with the "+str+" channel on %^RESET%^(are true_invis):";
i =sizeof(channels[str]);
while(i--)
{
if(!channels[str][i]) continue;
if (channels[str][i]->query_quietness() && wizardp(channels[str][i]) && !wizardp(TP)) continue;
if((int)channels[str][i]->query_blocked(str)) continue;
if(channels[str][i]->query_true_invis() && channels[str][i]->query_level() > TP->query_level() && TP != channels[str][i]) continue;
if(channels[str][i]->query_true_invis())
{
list += " ("+capitalize(channels[str][i]->query_name()+")");
}
else if(channels[str][i]->query_disguised())
{
list += " "+capitalize(channels[str][i]->query_vis_name());
}
else
{
list += " "+capitalize(channels[str][i]->query_name());
}
//list += " "+channels[str][i]->query_cap_name();
}
message("info", list, TP);
return 1;
}
object *arches(object *objs)
{
int i;
object *these;
these = ({});
for(i=0;i<sizeof(objs);i++)
{
if(!objectp(objs[i])) continue;
if(wizardp(objs[i]) && !objs[i]->query_property("seesomeone"))
{
these += ({objs[i]});
}
}
return these;
}
/**
* Send a message to everyone on the channel
*
* @param tp object that sends a message.
* @param *list pointer to array of people to send message to
* @param chan channel to send messages to.
* @param msg message to send
* @param emote Whether message is action/emote
*/
void do_amsg(object tp, object *list, string chan, string msg, int emote)
{
int i;
string tpname, tppos;
if(wizardp(TP))
tppos="@";
else if (archp(TP))
tppos="%";
else
tppos=" ";
tpname = capitalize((string)tp->query_name());
for(i=0;i<sizeof(list);i++)
message(chan,format_chat(chan,tpname,tppos,msg,emote),list[i],ignored_list(TP));
}
int clear_channels()
{
channels = ([ ]);
return 1;
}
void force_chat(object tp, string verb, string str, int emote)
{
object * list;
if(!channels[verb]) return;
list = channels[verb];
list -= ({ 0 }) ;
return do_amsg(tp, list, verb, str, emote);
}
object *ignored_list(object obj)
{
object *ppl,*ignoring=({});
string name, *ignored;
int i;
if(!objectp(obj)) { return ({}); }
if(avatarp(obj)) { return ({}); }
name = obj->query_true_name();
ppl = users();
for(i=0;sizeof(ppl),i<sizeof(ppl);i++)
{
if(!objectp(ppl[i])) { continue; }
ignored = ppl[i]->query_ignored();
if(!sizeof(ignored)) { continue; }
if(member_array(name,ignored) == -1) { continue; }
ignoring += ({ ppl[i] });
}
return ignoring;
}
| 24.077181 | 144 | 0.57324 | [
"object"
] |
200fb5a7f917bfce896b86b17a9444ecc8bc2145 | 2,350 | h | C | Classes/GameObject.h | otakuidoru/Reflection | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | [
"MIT"
] | null | null | null | Classes/GameObject.h | otakuidoru/Reflection | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | [
"MIT"
] | null | null | null | Classes/GameObject.h | otakuidoru/Reflection | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | [
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __GAME_OBJECT_H__
#define __GAME_OBJECT_H__
#include <map>
#include <string>
#include <vector>
#include "cocos2d.h"
#include "ColorType.h"
#include "Direction.h"
class GameObject : public cocos2d::Sprite {
protected:
const int id;
const unsigned int numPlanes;
const ColorType colorType;
Direction direction;
std::map<int, bool> planeReflective;
GameObject(int id, ColorType colorType, unsigned int numPlanes);
public:
virtual ~GameObject();
virtual bool initWithFile(const std::string& filename) override;
inline int getId() const { return this->id; }
inline ColorType getColorType() const { return this->colorType; }
inline Direction getDirection() const { return this->direction; }
void setDirection(Direction direction);
inline unsigned int getNumPlanes() const { return this->numPlanes; }
virtual cocos2d::Plane getPlane(unsigned int index) = 0;
std::vector<cocos2d::Plane> getPlanes();
bool isPlaneReflective(unsigned int index);
void setPlaneReflective(unsigned int index, bool reflective);
};
#endif // __GAME_OBJECT_H__
| 35.074627 | 78 | 0.722128 | [
"vector"
] |
2011fed9bb611e2ad53890c01aacc281a5e43f70 | 8,895 | c | C | src/render.c | den-mentiei/b4re | 7e25cf01631ec576daa956bd6e51c0bcfdeb8819 | [
"MIT"
] | null | null | null | src/render.c | den-mentiei/b4re | 7e25cf01631ec576daa956bd6e51c0bcfdeb8819 | [
"MIT"
] | null | null | null | src/render.c | den-mentiei/b4re | 7e25cf01631ec576daa956bd6e51c0bcfdeb8819 | [
"MIT"
] | null | null | null | #include "render.h"
#include <assert.h>
#include <string.h> // memcpy
#include <math.h> // floor
#include <stb_image.h>
#include <bgfx/bgfx.h>
#include "utils.h"
#include "shaders/tex_color_vs.h"
#include "shaders/tex_color_fs.h"
// TODO: ?
#define MAX_TEXTURES 1024
#define MAX_SPRITES 1024
typedef struct sprite_t {
render_texture_t tex;
float w, h;
float u0, v0;
float u1, v1;
} sprite_t;
static struct {
bgfx_vertex_decl_t vdecl;
bgfx_program_handle_t program;
bgfx_uniform_handle_t u_texture;
const bgfx_memory_t* pending_memory;
struct {
size_t count;
struct {
bgfx_texture_handle_t handle;
float w, h;
} data[MAX_TEXTURES];
} textures;
struct {
size_t count;
sprite_t data[MAX_SPRITES];
} sprites;
} s_ctx = {0};
const uint64_t DEFAULT_STATE_2D =
(0
| BGFX_STATE_RGB_WRITE
| BGFX_STATE_BLEND_ALPHA
| BGFX_STATE_ALPHA_WRITE
| BGFX_STATE_CULL_CCW
);
void render_init() {
bgfx_vertex_decl_begin(&s_ctx.vdecl, BGFX_RENDERER_TYPE_NOOP);
bgfx_vertex_decl_add(&s_ctx.vdecl, BGFX_ATTRIB_POSITION, 3, BGFX_ATTRIB_TYPE_FLOAT, false, false);
bgfx_vertex_decl_add(&s_ctx.vdecl, BGFX_ATTRIB_TEXCOORD0, 2, BGFX_ATTRIB_TYPE_FLOAT, false, false);
bgfx_vertex_decl_add(&s_ctx.vdecl, BGFX_ATTRIB_COLOR0, 4, BGFX_ATTRIB_TYPE_UINT8, true, false);
bgfx_vertex_decl_end(&s_ctx.vdecl);
bgfx_shader_handle_t vs = bgfx_create_shader(bgfx_make_ref(tex_color_vs, sizeof(tex_color_vs)));
bgfx_set_shader_name(vs, "tex_color_vs");
bgfx_shader_handle_t fs = bgfx_create_shader(bgfx_make_ref(tex_color_fs, sizeof(tex_color_fs)));
bgfx_set_shader_name(fs, "tex_color_fs");
s_ctx.program = bgfx_create_program(vs, fs, true);
s_ctx.u_texture = bgfx_create_uniform("s_texture", BGFX_UNIFORM_TYPE_INT1, 1);
static uint32_t white = 0xFFFFFFFF;
bgfx_texture_handle_t white_texture = bgfx_create_texture_2d(1, 1, false, 0, BGFX_TEXTURE_FORMAT_RGBA8, BGFX_TEXTURE_U_MIRROR | BGFX_TEXTURE_W_MIRROR | BGFX_TEXTURE_MAG_POINT | BGFX_TEXTURE_MIN_POINT, bgfx_make_ref(&white, sizeof(white)));
bgfx_set_texture_name(white_texture, "dummy white texture");
render_texture_t white_id = s_ctx.textures.count++;
s_ctx.textures.data[white_id].handle = white_texture;
s_ctx.textures.data[white_id].w = 1;
s_ctx.textures.data[white_id].h = 1;
}
void render_shutdown() {
for (size_t i = 0; i < s_ctx.textures.count; ++i) {
bgfx_destroy_texture(s_ctx.textures.data[i].handle);
}
bgfx_destroy_uniform(s_ctx.u_texture);
bgfx_destroy_program(s_ctx.program);
}
render_texture_t render_load_texture(const char* path) {
assert(s_ctx.textures.count < MAX_TEXTURES);
render_texture_t id = s_ctx.textures.count++;
const uint32_t flags = BGFX_TEXTURE_NONE
| BGFX_TEXTURE_U_CLAMP | BGFX_TEXTURE_V_CLAMP
| BGFX_TEXTURE_MAG_POINT | BGFX_TEXTURE_MIN_POINT;
int w = 0, h = 0, comp = 0;
stbi_uc* bytes = stbi_load(path, &w, &h, &comp, 4);
if (bytes) {
// TODO: do we really need a copy here?
bgfx_texture_handle_t handle = bgfx_create_texture_2d(w, h, false, 1, BGFX_TEXTURE_FORMAT_RGBA8, flags, bgfx_copy(bytes, w * h * 4));
s_ctx.textures.data[id].handle = handle;
s_ctx.textures.data[id].w = w;
s_ctx.textures.data[id].h = h;
bgfx_set_texture_name(handle, path);
stbi_image_free(bytes);
} else {
id = 0;
}
return id;
}
const sprite_t* render_create_sprite(render_texture_t t, float u0, float v0, float u1, float v1) {
assert(s_ctx.sprites.count < MAX_SPRITES);
assert(t < s_ctx.textures.count);
sprite_t* s = &s_ctx.sprites.data[s_ctx.sprites.count++];
const float w = s_ctx.textures.data[t].w;
const float h = s_ctx.textures.data[t].h;
s->tex = t;
s->w = w;
s->h = h;
s->u0 = u0;
s->v0 = v0;
s->u1 = u1;
s->v1 = v1;
return s;
}
static render_vertex_t s_vertices[] = {
{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0xFFFFFFFF },
{ 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0xFFFFFFFF },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0xFFFFFFFF },
{ 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0xFFFFFFFF },
};
// 0 1
// 3 2
static uint16_t s_indices[] = {
0, 1, 2,
2, 3, 0
};
void render_sprite(const sprite_t* s, float x, float y) {
render_sprite_colored(s, x, y, 0xFFFFFFFF);
}
void render_sprite_colored(const sprite_t* s, float x, float y, color_t color) {
const float w = s->w;
const float h = s->h;
#define VERT(i, _x, _y) s_vertices[i].x = _x; s_vertices[i].y = _y; s_vertices[i].color = color;
VERT(0, x, y);
VERT(1, x + w, y);
VERT(2, x + w, y + h);
VERT(3, x, y + h);
#undef VERT
const size_t NUM_INDICES = ARRAY_SIZE(s_indices);
const size_t NUM_VERTICES = ARRAY_SIZE(s_vertices);
bgfx_transient_vertex_buffer_t tvb;
bgfx_transient_index_buffer_t tib;
bgfx_alloc_transient_buffers(&tvb, &s_ctx.vdecl, NUM_VERTICES, &tib, NUM_INDICES);
memcpy(tvb.data, s_vertices, tvb.size);
memcpy(tib.data, s_indices, tib.size);
bgfx_texture_handle_t tex = s_ctx.textures.data[s->tex].handle;
bgfx_set_transient_vertex_buffer(0, &tvb, 0, NUM_VERTICES);
bgfx_set_transient_index_buffer(&tib, 0, NUM_INDICES);
bgfx_set_texture(0, s_ctx.u_texture, tex, UINT32_MAX);
bgfx_set_state(DEFAULT_STATE_2D, 0);
bgfx_submit(0, s_ctx.program, 0, false);
}
render_tex_t render_create_texture_rgba8(uint32_t width, uint32_t height) {
render_tex_t result;
bgfx_texture_handle_t tex = bgfx_create_texture_2d(width, height, false, 1, BGFX_TEXTURE_FORMAT_RGBA8, BGFX_TEXTURE_NONE, NULL);
memcpy(&result, &tex, sizeof(tex));
return result;
}
void render_destroy_texture(render_tex_t tex) {
bgfx_texture_handle_t th;
memcpy(&th, &tex, sizeof(th));
bgfx_destroy_texture(th);
}
uint8_t* render_update_texture_begin(size_t size) {
assert(!s_ctx.pending_memory);
const bgfx_memory_t* mem = bgfx_alloc(size);
s_ctx.pending_memory = mem;
return mem->data;
}
void render_update_texture_end(render_tex_t tex, uint32_t x, uint32_t y, uint32_t w, uint32_t h) {
assert(s_ctx.pending_memory);
bgfx_texture_handle_t th;
memcpy(&th, &tex, sizeof(th));
bgfx_update_texture_2d(th, 0, 0, x, y, w, h, s_ctx.pending_memory, -1);
s_ctx.pending_memory = NULL;
}
void render_transient(const render_vertex_t* vertices, size_t num_vertices, const uint16_t* indices, size_t num_indices, render_tex_t tex) {
assert(vertices && num_vertices > 0);
assert(indices && num_indices > 0);
bgfx_transient_vertex_buffer_t tvb;
bgfx_transient_index_buffer_t tib;
bgfx_alloc_transient_buffers(&tvb, &s_ctx.vdecl, num_vertices, &tib, num_indices);
memcpy(tvb.data, vertices, tvb.size);
memcpy(tib.data, indices, tib.size);
bgfx_texture_handle_t th;
memcpy(&th, &tex, sizeof(th));
bgfx_set_transient_vertex_buffer(0, &tvb, 0, num_vertices);
bgfx_set_transient_index_buffer(&tib, 0, num_indices);
bgfx_set_texture(0, s_ctx.u_texture, th, UINT32_MAX);
bgfx_set_state(DEFAULT_STATE_2D, 0);
bgfx_submit(0, s_ctx.program, 0, false);
}
static render_vertex_t s_tile_vertices[] = {
{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0xFFFFFFFF },
{ 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0xFFFFFFFF },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0xFFFFFFFF },
{ 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0xFFFFFFFF },
};
void render_tile(const struct sprite_t* tilemap, float x, float y, const render_tile_t* params) {
assert(tilemap);
assert(params);
assert(params->tile_w > 0);
assert(params->tile_h > 0);
const float w = params->tile_w;
const float h = params->tile_h;
const size_t NUM_TILES_X = floor(tilemap->w / params->tile_w);
const size_t NUM_TILES_Y = floor(tilemap->h / params->tile_h);
// TODO: Hard-coded for non-atlassed sprites, assumes 0..1 uvs.
const float du = 1.0f / NUM_TILES_X;
const float dv = 1.0f / NUM_TILES_Y;
const float u0 = params->tile_x * du;
const float v0 = params->tile_y * dv;
const float u1 = u0 + du;
const float v1 = v0 + dv;
assert(params->tile_x < NUM_TILES_X);
assert(params->tile_y < NUM_TILES_Y);
#define VERT(i, _x, _y, _u, _v) \
s_tile_vertices[i].x = _x; \
s_tile_vertices[i].y = _y; \
s_tile_vertices[i].u = _u; \
s_tile_vertices[i].v = _v; \
s_tile_vertices[i].color = 0xFFFFFFFF;
VERT(0, x, y, u0, v0);
VERT(1, x + w, y, u1, v0);
VERT(2, x + w, y + h, u1, v1);
VERT(3, x, y + h, u0, v1);
#undef VERT
const size_t NUM_INDICES = ARRAY_SIZE(s_indices);
const size_t NUM_VERTICES = ARRAY_SIZE(s_vertices);
bgfx_transient_vertex_buffer_t tvb;
bgfx_transient_index_buffer_t tib;
bgfx_alloc_transient_buffers(&tvb, &s_ctx.vdecl, NUM_VERTICES, &tib, NUM_INDICES);
memcpy(tvb.data, s_tile_vertices, tvb.size);
memcpy(tib.data, s_indices, tib.size);
bgfx_texture_handle_t tex = s_ctx.textures.data[tilemap->tex].handle;
bgfx_set_transient_vertex_buffer(0, &tvb, 0, NUM_VERTICES);
bgfx_set_transient_index_buffer(&tib, 0, NUM_INDICES);
bgfx_set_texture(0, s_ctx.u_texture, tex, UINT32_MAX);
bgfx_set_state(DEFAULT_STATE_2D, 0);
bgfx_submit(0, s_ctx.program, 0, false);
}
| 29.65 | 240 | 0.718494 | [
"render"
] |
2014d6554c3501870fbccefaa1b58c78c2637e12 | 9,760 | h | C | module/src/API/JavaResource_API.h | robertnisipeanu/altv-java-module | 53be7482cd3b7bef78c7b84c9dbe12a6fdc3a235 | [
"MIT"
] | 1 | 2020-02-10T21:00:50.000Z | 2020-02-10T21:00:50.000Z | module/src/API/JavaResource_API.h | robertnisipeanu/altv-java-module | 53be7482cd3b7bef78c7b84c9dbe12a6fdc3a235 | [
"MIT"
] | null | null | null | module/src/API/JavaResource_API.h | robertnisipeanu/altv-java-module | 53be7482cd3b7bef78c7b84c9dbe12a6fdc3a235 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <altv-cpp-api/SDK.h>
#include "../JavaResource.h"
#ifndef EXPORT
#define EXPORT _declspec(dllexport)
#endif // !EXPORT
// Need to use extern "C" else the name of the functions gets mangled and JAVA won't be able to find them anymore
#ifdef __cplusplus
extern "C" {
#endif
/*
Model: static `RETURNING_TYPE` (*CallbackName) (`ARGUMENTS_TYPE`)
Usually first argument will be the pointer to the resource, if there will be any other arg or first argument has different purpose then that'll be added as a comment with `// arg{number}: description`
*/
extern void (*JavaResource_OnTick_Callback)(uintptr_t);
extern bool (*JavaResource_Start_Callback)(uintptr_t);
extern bool (*JavaResource_Stop_Callback)(uintptr_t);
extern void (*JavaResource_CreateBaseObject_Callback)(uintptr_t, uintptr_t); // arg2: pointer to alt::IBaseObject*
extern void (*JavaResource_RemoveBaseObject_Callback)(uintptr_t, uintptr_t);
#pragma region Events callback
extern bool (*JavaResource_OnEvent_Callback)(uintptr_t, uintptr_t); // arg2: pointer to the CEvent object
extern bool (*JavaResource_PlayerConnectEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_PlayerDisconnectEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_ServerScriptEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_ClientScriptEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_MetaChangeEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_SyncedMetaChangeEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_PlayerDamageEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_PlayerDeathEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_CheckpointEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_ColshapeEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_PlayerEnterVehicleEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_PlayerLeaveVehicleEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_PlayerChangeVehicleSeatEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_RemoveEntityEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_DataNodeReceivedEvent_Callback)(uintptr_t, uintptr_t);
extern bool (*JavaResource_ConsoleCommandEvent_Callback)(uintptr_t, uintptr_t);
#pragma endregion
/*
Those will be called from Java, first argument being the pointer to the resource it wants to register the event and the second argument being the pointer to the (java) method that will be called("the callback")
*/
EXPORT void alt_JavaResource_OnTick_Callback_Register(void (*cb)(uintptr_t));
EXPORT void alt_JavaResource_Start_Callback_Register(bool (*cb)(uintptr_t));
EXPORT void alt_JavaResource_Stop_Callback_Register(bool (*cb)(uintptr_t));
EXPORT void alt_JavaResource_OnCreateBaseObject_Callback_Register(void (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_OnRemoveBaseObject_Callback_Register(void (*cb)(uintptr_t, uintptr_t));
#pragma region Events callback register
EXPORT void alt_JavaResource_OnEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerConnectEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerDisconnectEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_ServerScriptEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_ClientScriptEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_MetaChangeEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_SyncedMetaChangeEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerDamageEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerDeathEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_CheckpointEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_ColshapeEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerEnterVehicleEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerLeaveVehicleEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_PlayerChangeVehicleSeatEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_RemoveEntityEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_DataNodeReceivedEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
EXPORT void alt_JavaResource_ConsoleCommandEvent_Callback_Register(bool (*cb)(uintptr_t, uintptr_t));
#pragma endregion
/*
Methods that the Java API will be able to call
*/
#pragma region Resource information
EXPORT const char* alt_JavaResource_GetName(uintptr_t resourcePointer);
EXPORT const char* alt_JavaResource_CreationInfo_GetName(uintptr_t creationInfoPointer);
EXPORT const char* alt_JavaResource_GetPath(uintptr_t resourcePointer);
EXPORT const char* alt_JavaResource_CreationInfo_GetPath(uintptr_t creationInfoPointer);
EXPORT const char* alt_JavaResource_GetMain(uintptr_t resourcePointer);
EXPORT const char* alt_JavaResource_CreationInfo_GetMain(uintptr_t creationInfoPointer);
EXPORT int32_t alt_JavaResource_CEvent_GetType(uintptr_t ceventPointer);
#pragma endregion
#pragma region Events info
#pragma region PlayerConnectEvent
EXPORT const char* alt_JavaResource_PlayerConnectEvent_GetReason(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerConnectEvent_GetTarget(uintptr_t eventPointer);
#pragma endregion
#pragma region PlayerDisconnectEvent
EXPORT const char* alt_JavaResource_PlayerDisconnectEvent_GetReason(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerDisconnectEvent_GetTarget(uintptr_t eventPointer);
#pragma endregion
// TODO: ServerScriptEvent->GetArgs()
#pragma region ServerScriptEvent
EXPORT const char* alt_JavaResource_ServerScriptEvent_GetName(uintptr_t eventPointer);
#pragma endregion
// TODO: ClientScriptEvent->GetArgs()
#pragma region ClientScriptEvent
EXPORT const char* alt_JavaResource_ClientScriptEvent_GetName(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_ClientScriptEvent_GetTarget(uintptr_t eventPointer);
#pragma endregion
// TODO
#pragma region MetaChangeEvent
#pragma endregion
// TODO
#pragma region SyncedMetaChangeEvent
#pragma endregion
#pragma region PlayerDamageEvent
EXPORT uintptr_t alt_JavaResource_PlayerDamageEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerDamageEvent_GetAttacker(uintptr_t eventPointer);
EXPORT uint16_t alt_JavaResource_PlayerDamageEvent_GetDamage(uintptr_t eventPointer);
EXPORT uint32_t alt_JavaResource_PlayerDamageEvent_GetWeapon(uintptr_t eventPointer);
#pragma endregion
#pragma region PlayerDeathEvent
EXPORT uintptr_t alt_JavaResource_PlayerDeathEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerDeathEvent_GetKiller(uintptr_t eventPointer);
EXPORT uint32_t alt_JavaResource_PlayerDeathEvent_GetWeapon(uintptr_t eventPointer);
#pragma endregion
#pragma region CheckpointEvent
EXPORT uintptr_t alt_JavaResource_CheckpointEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_CheckpointEvent_GetEntity(uintptr_t eventPointer);
EXPORT bool alt_JavaResource_CheckpointEvent_GetState(uintptr_t eventPointer);
#pragma endregion
#pragma region ColshapeEvent
EXPORT uintptr_t alt_JavaResource_ColshapeEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_ColshapeEvent_GetEntity(uintptr_t eventPointer);
EXPORT bool alt_JavaResource_ColshapeEvent_GetState(uintptr_t eventPointer);
#pragma endregion
#pragma region PlayerEnterVehicleEvent
EXPORT uintptr_t alt_JavaResource_PlayerEnterVehicleEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerEnterVehicleEvent_GetPlayer(uintptr_t eventPointer);
EXPORT uint8_t alt_JavaResource_PlayerEnterVehicleEvent_GetSeat(uintptr_t eventPointer);
#pragma endregion
#pragma region PlayerLeaveVehicleEvent
EXPORT uintptr_t alt_JavaResource_PlayerLeaveVehicleEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerLeaveVehicleEvent_GetPlayer(uintptr_t eventPointer);
EXPORT uint8_t alt_JavaResource_PlayerLeaveVehicleEvent_GetSeat(uintptr_t eventPointer);
#pragma endregion
#pragma region PlayerChangeVehicleSeatEvent
EXPORT uintptr_t alt_JavaResource_PlayerChangeVehicleSeatEvent_GetTarget(uintptr_t eventPointer);
EXPORT uintptr_t alt_JavaResource_PlayerChangeVehicleSeatEvent_GetPlayer(uintptr_t eventPointer);
EXPORT uint8_t alt_JavaResource_PlayerChangeVehicleSeatEvent_GetOldSeat(uintptr_t eventPointer);
EXPORT uint8_t alt_JavaResource_PlayerChangeVehicleSeatEvent_GetNewSeat(uintptr_t eventPointer);
#pragma endregion
#pragma region RemoveEntityEvent
uintptr_t alt_JavaResource_RemoveEntityEvent_GetEntity(uintptr_t eventPointer);
#pragma endregion
#pragma region DataNodeReceivedEvent
EXPORT const char* alt_JavaResource_DataNodeReceivedEvent_GetName(uintptr_t eventPointer);
EXPORT const char* alt_JavaResource_DataNodeReceivedEvent_GetJson(uintptr_t eventPointer);
#pragma endregion
#pragma region ConsoleCommandEvent
EXPORT const char* alt_JavaResource_ConsoleCommandEvent_GetName(uintptr_t eventPointer);
#pragma endregion
#pragma endregion Events info
#pragma region MValue
EXPORT uint8_t alt_MValue_GetType(uintptr_t mvaluePointer);
#pragma endregion
#ifdef __cplusplus
}
#endif | 53.333333 | 212 | 0.852561 | [
"object",
"model"
] |
201d2d9cd1a01ce55382b63257704984c9c87e85 | 334 | h | C | include/archlab/ArchLab.h | xzrunner/cgaview | 559899f0f9bcb1186e41b4108388ee2c69008966 | [
"MIT"
] | null | null | null | include/archlab/ArchLab.h | xzrunner/cgaview | 559899f0f9bcb1186e41b4108388ee2c69008966 | [
"MIT"
] | null | null | null | include/archlab/ArchLab.h | xzrunner/cgaview | 559899f0f9bcb1186e41b4108388ee2c69008966 | [
"MIT"
] | null | null | null | #pragma once
#include <blueprint/typedef.h>
#include <cu/cu_macro.h>
#include <vector>
#include <memory>
namespace archlab
{
class ArchLab
{
public:
auto& GetAllNodes() { return m_nodes; }
private:
void InitNodes();
private:
std::vector<bp::NodePtr> m_nodes;
CU_SINGLETON_DECLARATION(ArchLab)
}; // ArchLab
} | 11.928571 | 43 | 0.688623 | [
"vector"
] |
20248bed0b3b99cb53dc0de06748247273118c1d | 2,626 | h | C | src/include/event_impl.h | kyper999/clDNN_neuset | 85148cef898dbf1b314ef742092824c447474f2d | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | 1 | 2018-06-07T09:21:08.000Z | 2018-06-07T09:21:08.000Z | src/include/event_impl.h | kyper999/clDNN_neuset | 85148cef898dbf1b314ef742092824c447474f2d | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | src/include/event_impl.h | kyper999/clDNN_neuset | 85148cef898dbf1b314ef742092824c447474f2d | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 2016 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "api_impl.h"
#include "refcounted_obj.h"
#include "gpu/ocl_toolkit.h"
namespace cldnn
{
struct event_impl: public refcounted_obj<event_impl>
{
public:
event_impl(const cl::Event& event) : _event(event)
{}
void wait() const { _event.wait(); }
virtual void set() { throw std::logic_error("cannot set OCL event"); }
void add_event_handler(cldnn_event_handler handler, void* data)
{
std::lock_guard<std::mutex> lock(_handlers_mutex);
if (_event.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE)
{
handler(data);
}
else
{
if (_handlers.size() == 0)
{
_event.setCallback(CL_COMPLETE, callBack, this);
}
_handlers.push_back({ handler, data });
}
}
cl::Event get() const { return _event; }
const std::vector<cldnn_profiling_interval>& get_profiling_info();
protected:
//TODO prevent long handler execution problem
static void CL_CALLBACK callBack(cl_event, cl_int, void* me)
{
reinterpret_cast<event_impl*>(me)->callHandlers();
}
void callHandlers()
{
std::lock_guard<std::mutex> lock(_handlers_mutex);
for (auto& pair : _handlers)
{
try
{
pair.first(pair.second);
}
catch (...) {}
}
_handlers.clear();
}
std::mutex _handlers_mutex;
cl::Event _event;
std::vector<std::pair<cldnn_event_handler, void*>> _handlers;
std::vector<cldnn_profiling_interval> _profiling_info;
};
class user_event_gpu : public event_impl
{
public:
user_event_gpu(const cl::UserEvent& event) : event_impl(event), _user_event(event) {}
void set() override { _user_event.setStatus(CL_COMPLETE); }
private:
cl::UserEvent _user_event;
};
}
API_CAST(::cldnn_event, cldnn::event_impl)
| 29.177778 | 99 | 0.621097 | [
"vector"
] |
20275312640fa1bbd19399c8027c56b99b10cef6 | 9,851 | h | C | HipsHookTest/HipsHookTest.h | smalltong02/Bruce-Ma | 2ee9455635af9f0300f53781382de88d3ef99003 | [
"MIT"
] | 1 | 2021-06-22T04:41:41.000Z | 2021-06-22T04:41:41.000Z | HipsHookTest/HipsHookTest.h | smalltong02/Bruce-Ma | 2ee9455635af9f0300f53781382de88d3ef99003 | [
"MIT"
] | 1 | 2021-02-23T17:45:30.000Z | 2021-02-23T17:45:30.000Z | HipsHookTest/HipsHookTest.h | smalltong02/Bruce-Ma | 2ee9455635af9f0300f53781382de88d3ef99003 | [
"MIT"
] | null | null | null | #pragma once
#include <stdio.h>
#include <windows.h>
#include <string>
#include <vector>
#include <regex>
#include <unordered_set>
#include <thread>
#include <chrono>
#include "gtest\gtest.h"
#include "resource.h"
#include "HipsCfgObject.h"
#include "HookImplementObject.h"
#include "utils.h"
#include "commutils.h"
#include "R3LogObject.h"
#include "PassSupport.h"
#ifdef USING_PIPE_MESSAGE
#include "PipeJSONServer.h"
#endif
using namespace std::chrono_literals;
class CServerObject
{
public:
CServerObject() {
m_tempfp = tmpfile();
#ifdef USING_PIPE_MESSAGE
std::function<void(const std::unique_ptr<RapidDocument>)> callback(std::bind(&CServerObject::LogCallBack, this, std::placeholders::_1));
m_pipe_mess_object = std::make_shared<PipeJSONServer>(L"\\\\.\\pipe\\hips_hook");
if (m_pipe_mess_object)
{
m_pipe_mess_object->Start(callback);
}
#else
std::function<void(const std::unique_ptr<CRapidJsonWrapper>)> callback(std::bind(&CServerObject::LogCallBack, this, std::placeholders::_1));
m_pipe_object = std::make_unique<CLpcPipeObject>();
if (m_pipe_object)
{
m_pipe_object->Listen(std::move(callback));
}
#endif
}
~CServerObject() {
#ifdef USING_PIPE_MESSAGE
if (m_pipe_mess_object)
m_pipe_mess_object->Stop();
#else
if (m_pipe_object)
m_pipe_object->StopListen();
#endif
if (m_tempfp)
fclose(m_tempfp);
}
void ClearLogsCount() {
#ifdef USING_PIPE_MESSAGE
return;
#else
return m_pipe_object->ClearLogsCount();
#endif
}
int GetTotalLogs() const {
#ifdef USING_PIPE_MESSAGE
return 0;
#else
return m_pipe_object->GetTotalLogs();
#endif
}
std::unordered_map<std::string, int> GetLogCountMap() {
std::lock_guard lock(m_log_count_mutex);
return m_log_count_map;
}
void ClearLogMap() {
std::lock_guard lock(m_log_count_mutex);
m_log_count_map.clear();
}
void EnableDebugPid() { m_enable_debugpid = true; }
void DisableDebugPid() { m_enable_debugpid = false; }
void AddLogCountMap(const std::vector<std::string>& action_list) {
ClearLogMap();
std::lock_guard lock(m_log_count_mutex);
for (auto& elem : action_list) {
if (elem.length() && m_log_count_map.find(elem) == m_log_count_map.end()) {
m_log_count_map[elem] = 0;
}
}
return;
}
BOOL WaitLogCountMap(const std::vector<int>& count_list, DWORD dwMaxseconds)
{
if (!count_list.size())
return FALSE;
{
std::lock_guard lock(m_log_count_mutex);
if (count_list.size() != m_log_count_map.size())
return FALSE;
}
BOOL bmatch = TRUE;
std::chrono::milliseconds total_times = {};
while (true) {
bmatch = TRUE;
{
int count = 0;
std::lock_guard lock(m_log_count_mutex);
for (auto& elem : m_log_count_map) {
if (count_list[count] > elem.second)
{
bmatch = FALSE;
break;
}
count++;
}
}
if (bmatch) break;
std::this_thread::sleep_for(100ms);
total_times += 100ms;
if (total_times.count() >= dwMaxseconds*1000)
break;
}
return bmatch;
}
bool AddDebugPid(DWORD_PTR pid)
{
std::lock_guard lock(m_debugpid_mutex);
auto& it = m_debugpid_list.find(pid);
if (it != m_debugpid_list.end()) return false;
m_debugpid_list[pid] = 0;
return true;
}
void DelDebugPid(DWORD_PTR pid)
{
std::lock_guard lock(m_debugpid_mutex);
auto& it = m_debugpid_list.find(pid);
if (it == m_debugpid_list.end()) return;
m_debugpid_list.erase(pid);
return;
}
int GetCountForDebugPid(DWORD_PTR pid)
{
std::lock_guard lock(m_debugpid_mutex);
auto& it = m_debugpid_list.find(pid);
if (it == m_debugpid_list.end()) return 0;
return it->second;
}
private:
bool CheckVerifier(const CRapidJsonWrapper& rapid_log) const
{
if (auto anyvalue(rapid_log.GetMember("verifier_result"));
anyvalue.has_value() && anyvalue.type() == typeid(std::string_view))
{
std::string verifier_result(std::any_cast<std::string_view>(anyvalue));
if (!verifier_result.compare("false")) {
return false;
}
}
return true;
}
void CheckLogCountMap(const CRapidJsonWrapper& rapid_log) {
std::lock_guard lock(m_log_count_mutex);
if (!m_log_count_map.size()) return;
if (auto anyvalue(rapid_log.GetMember("Action"));
anyvalue.has_value() && anyvalue.type() == typeid(std::string_view))
{
for (auto& elem : m_log_count_map) {
std::string action_str(std::any_cast<std::string_view>(anyvalue));
if (action_str.compare(elem.first) == 0) {
elem.second++;
}
}
}
return;
}
void CheckDebugPid(const CRapidJsonWrapper& rapid_log)
{
if (m_enable_debugpid)
{
if (auto anyvalue(rapid_log.GetMember("Pid"));
anyvalue.has_value() && anyvalue.type() == typeid(std::string_view))
{
std::string pid_str(std::any_cast<std::string_view>(anyvalue));
if(pid_str.length())
{
char* end;
DWORD_PTR pid = (DWORD_PTR)strtol(pid_str.c_str(), &end, 10);
std::lock_guard lock(m_debugpid_mutex);
auto& it = m_debugpid_list.find(pid);
if (it != m_debugpid_list.end())
{
it->second++;
}
}
}
}
return;
}
#ifdef USING_PIPE_MESSAGE
std::string JSONToString(std::unique_ptr<RapidDocument> json) {
if (json == nullptr) return "";
rapidjson::StringBuffer string_buffer;
string_buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(string_buffer);
json->Accept(writer);
if (!string_buffer.GetSize()) return "";
return string_buffer.GetString();
}
void LogCallBack(std::unique_ptr<RapidDocument> json_log) {
if (!json_log)
return;
std::string rapid_string = JSONToString(std::move(json_log));
ASSERT_TRUE(!rapid_string.empty());
std::unique_ptr<CRapidJsonWrapper> rapid_log = std::make_unique<CRapidJsonWrapper>(rapid_string);
ASSERT_TRUE(rapid_log);
if (!rapid_log) return;
if (!rapid_log->IsValid()) return;
ASSERT_TRUE(CheckVerifier(*rapid_log));
CheckLogCountMap(*rapid_log);
CheckDebugPid(*rapid_log);
m_logs_total_count++;
{
auto optstring = rapid_log->Serialize();
if (!optstring) return;
std::lock_guard lock(m_log_mutex);
if (m_tempfp)
{
fputs(optstring.value().c_str(), m_tempfp);
}
else
std::cout << optstring.value() << std::endl;
}
return;
}
#else
void LogCallBack(const std::unique_ptr<CRapidJsonWrapper> rapid_log) {
//ASSERT_TRUE(rapid_log);
if (!rapid_log)
return;
if (!rapid_log->IsValid()) return;
ASSERT_TRUE(CheckVerifier(*rapid_log));
CheckLogCountMap(*rapid_log);
CheckDebugPid(*rapid_log);
m_logs_total_count++;
{
auto optstring = rapid_log->Serialize();
if (!optstring) return;
std::lock_guard lock(m_log_mutex);
if (m_tempfp)
{
fputs(optstring.value().c_str(), m_tempfp);
}
else
std::cout << optstring.value() << std::endl;
}
return;
}
#endif
std::atomic_int m_logs_total_count = 0;
std::mutex m_log_mutex;
FILE* m_tempfp = nullptr;
#ifdef USING_PIPE_MESSAGE
std::shared_ptr<PipeJSONServer> m_pipe_mess_object;
#else
std::unique_ptr<CLpcPipeObject> m_pipe_object;
#endif
std::recursive_mutex m_log_count_mutex;
std::unordered_map<std::string, int> m_log_count_map;
std::atomic_bool m_enable_debugpid = false;
std::mutex m_debugpid_mutex;
std::map<DWORD_PTR, int> m_debugpid_list;
};
class HipsHookTest
{
public:
HipsHookTest() : m_valid(false), m_hipsCfgObject(nullptr), m_hookImplObject(nullptr) {}
~HipsHookTest() {
m_hookImplObject->DisableAllApis();
}
bool Initialize() {
m_hookImplObject = g_impl_object;
m_hipsCfgObject = InitializeConfig();
if (!m_hookImplObject) return false;
if (!m_hipsCfgObject) return false;
g_log_object->DisableDupFlt();
if (!m_hookImplObject->Initialize(std::move(m_hipsCfgObject)))
return false;
if (!m_hookImplObject->Running())
return false;
m_valid = true;
return m_valid;
}
bool EnableAllApis() { return m_hookImplObject->EnableAllApis(); }
bool DisableAllApis() { return m_hookImplObject->DisableAllApis(); }
private:
bool m_valid;
std::shared_ptr<cchips::CHipsCfgObject> m_hipsCfgObject;
std::shared_ptr<cchips::CHookImplementObject> m_hookImplObject;
};
extern std::unique_ptr<HipsHookTest> g_hook_test_object;
extern std::unique_ptr<CServerObject> g_server_object;
| 31.174051 | 148 | 0.584002 | [
"vector"
] |
202ba4cf8028479dd8e67e8429c05e02f9f067e2 | 2,049 | h | C | src/runtime_src/core/common/api/context_mgr.h | subeeshm-xilinx/XRT | f2f551a815dcd135132f974205401ca0982f9a3b | [
"Apache-2.0"
] | 359 | 2018-10-05T03:05:08.000Z | 2022-03-31T06:28:16.000Z | src/runtime_src/core/common/api/context_mgr.h | kbhardwa-xilinx/XRT | 9cadec73f5211577c7d5c408a4a7fee0eed23b70 | [
"Apache-2.0"
] | 5,832 | 2018-10-02T22:43:29.000Z | 2022-03-31T22:28:05.000Z | src/runtime_src/core/common/api/context_mgr.h | kbhardwa-xilinx/XRT | 9cadec73f5211577c7d5c408a4a7fee0eed23b70 | [
"Apache-2.0"
] | 442 | 2018-10-02T23:06:29.000Z | 2022-03-21T08:34:44.000Z | /*
* SPDX-License-Identifier: Apache-2.0
* Copyright (C) 2021 Xilinx, Inc. All rights reserved.
*/
#include "core/include/xrt/xrt_uuid.h"
#include "core/common/cuidx_type.h"
#include <memory>
// This file defines APIs for compute unit (ip) context management
// It is used by xrt::kernel and xrt::ip implementation.
namespace xrt_core {
class device;
// Context management is somewhat complex in multi-threaded host
// applications where same device object is shared between threads.
//
// A call to xclOpenContext must be protected against a race where
// one thread is in the process of call xclCloseContext.
namespace context_mgr {
class device_context_mgr;
// Create a context manager for a specific device The manager is
// shared and cached so that it is constructed only if necessary. In
// other words, multi threads using same device can share the same
// context manager.
std::shared_ptr<device_context_mgr>
create(const xrt_core::device* device);
// Open a device context a specified compute unit (ip)
//
// @device: device to open context on
// @uuid: xclbin uuid with the CU
// @cuidx: index of CU
// @shared: open in shared (true) or exclusive mode (false)
//
// The function blocks until the context can be acquired. If
// timeout, then the function throws.
//
// Note that the context manager is not intended to support two or
// more threads opening a context on the same compute unit. This
// situation must be guarded by the client (xrt::kernel) of the
// manager.
//
// The function is simply a synchronization between two threads
// simultanous use of open_context and close_context.
void
open_context(xrt_core::device* device, const xrt::uuid& uuid, cuidx_type cuidx, bool shared);
// Close a previously opened device context
//
// @device: device to close context on
// @uuid: xclbin uuid with the CU
// @cuidx: index of CU
//
// The function throws if no context is open on specified CU.
void
close_context(xrt_core::device* device, const xrt::uuid& uuid, cuidx_type cuidx);
}} // context_mgr, xrt_core
| 32.015625 | 93 | 0.744754 | [
"object"
] |
20334e5c069234ada48f3acd5aaf470f4672d089 | 1,905 | h | C | Coin3D/src/Inventor/Xt/viewers/SoXtPlaneViewerP.h | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/Inventor/Xt/viewers/SoXtPlaneViewerP.h | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/Inventor/Xt/viewers/SoXtPlaneViewerP.h | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#ifndef SOXTPLANEVIEWERP_H
#define SOXTPLANEVIEWERP_H
#include <Inventor/Xt/viewers/SoGuiPlaneViewerP.h>
// ************************************************************************
// This class contains private data and methods used within the
// SoXtPlaneViewer class.
class SoXtPlaneViewerP : public SoGuiPlaneViewerP
{
public:
SoXtPlaneViewerP(SoXtPlaneViewer * publ);
~SoXtPlaneViewerP();
void constructor(SbBool build);
static struct SoXtViewerButton SoXtPlaneViewerButtons[];
struct SoXtViewerButton * buttons;
int findButton(Widget button) const;
static void buttonCB(Widget, XtPointer, XtPointer);
struct {
Pixmap ortho, ortho_ins;
Pixmap perspective, perspective_ins;
} pixmaps;
};
// ************************************************************************
#endif // ! SOXTPLANEVIEWERP_H
| 33.421053 | 76 | 0.627822 | [
"3d"
] |
203e898a478af6399d278c7a0feaa1b9daf8adfa | 1,022 | h | C | Engine/Renderer/Vulkan/include/VKIndirectBuffer.h | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | 3 | 2018-12-08T16:32:05.000Z | 2020-06-02T11:07:15.000Z | Engine/Renderer/Vulkan/include/VKIndirectBuffer.h | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | null | null | null | Engine/Renderer/Vulkan/include/VKIndirectBuffer.h | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | 1 | 2019-09-12T00:26:05.000Z | 2019-09-12T00:26:05.000Z | #pragma once
#include "VKRenderer.h"
class CVKIndirectBuffer : public CGfxIndirectBuffer
{
public:
CVKIndirectBuffer(CVKDevice* pDevice, int numDrawCommands);
virtual ~CVKIndirectBuffer(void);
virtual void Release(void);
public:
VkBuffer GetBuffer(void) const;
public:
uint32_t GetDrawCommandCount(void) const;
uint32_t GetDrawCommandOffset(int indexDraw) const;
uint32_t GetSize(void) const;
uint32_t GetStride(void) const;
public:
bool BufferData(int indexDraw, int firstIndex, int baseVertex, int baseInstance, int indexCount, int instanceCount);
private:
eastl::vector<DrawCommand> m_draws;
private:
CVKBuffer* m_pBuffer;
private:
CVKDevice* m_pDevice;
};
class CVKMultiIndirectBuffer : public CGfxMultiIndirectBuffer
{
public:
CVKMultiIndirectBuffer(CVKDevice* pDevice, int numDrawCommands, int count);
virtual ~CVKMultiIndirectBuffer(void);
virtual void Release(void);
public:
CGfxIndirectBuffer* GetBuffer(int index) const;
private:
eastl::vector<CVKIndirectBuffer*> m_pBuffers;
};
| 19.653846 | 117 | 0.792564 | [
"vector"
] |
5aa1af3df29898caa2fafb86ec008d6c6ba772bd | 1,715 | h | C | component/gui/gui_page.h | wele2010/eBox_Framework | 8de6e2ee8d0f1e5a3f0c2cf97435da317150b489 | [
"MIT"
] | 1 | 2019-11-24T14:58:54.000Z | 2019-11-24T14:58:54.000Z | component/gui/gui_page.h | wele2010/eBox_Framework | 8de6e2ee8d0f1e5a3f0c2cf97435da317150b489 | [
"MIT"
] | null | null | null | component/gui/gui_page.h | wele2010/eBox_Framework | 8de6e2ee8d0f1e5a3f0c2cf97435da317150b489 | [
"MIT"
] | 1 | 2020-12-13T15:19:06.000Z | 2020-12-13T15:19:06.000Z | #ifndef __GUI_PAGE_H
#define __GUI_PAGE_H
#include "graphic.h"
#include "gui_base.h"
#include "list.h"
class GuiPage :public Component
{
public :
GuiPage(String name)
{
this->x = 0;
this->y = 0;
this->len = 256;
this->hight = 64;
this->name = name;
last_index = index = 0;
type = GuiType::Page;
outline = GuiOutlineMode::None;
};
GuiPage(int16_t x,int16_t y,int16_t len,int16_t hight,
String name)
{
this->x = x;
this->y = y;
this->len = len;
this->hight = hight;
this->name = name;
last_index = index = 0;
type = GuiType::Page;
outline = GuiOutlineMode::Surround;
};
GuiPage *father;
virtual void create();
virtual void cancel();
virtual void event(Object *sender,GuiMessage *msg) = 0;
virtual void show();
virtual void hide();
virtual void loop();
virtual void Register(ActivityComponent *object);
virtual void Register(Component *object);
virtual ActivityComponent *get_selected_object();
int16_t index_get();
void index_set(int16_t value);
bool index_next();
bool index_previous();
public:
List activityList;
List componentList;
int index;
int last_index;
void update_index();
private:
int16_t x;
int16_t y;
int16_t len;
int16_t hight;
GuiOutlineMode outline;
};
#endif
| 23.493151 | 63 | 0.504956 | [
"object"
] |
5aa708e7f8c0b0ab8ef9235312973415b9c2baf1 | 7,356 | c | C | string-diff/diff.c | Ralph-Zitz/ldmud-extensions | ae9d30bebbcc27d2b2e982ba75dda49145393882 | [
"BSD-2-Clause"
] | 2 | 2015-08-11T08:28:47.000Z | 2016-07-09T07:03:44.000Z | string-diff/diff.c | Ralph-Zitz/ldmud-extensions | ae9d30bebbcc27d2b2e982ba75dda49145393882 | [
"BSD-2-Clause"
] | null | null | null | string-diff/diff.c | Ralph-Zitz/ldmud-extensions | ae9d30bebbcc27d2b2e982ba75dda49145393882 | [
"BSD-2-Clause"
] | 6 | 2015-05-28T00:33:58.000Z | 2021-09-05T14:12:44.000Z | /*
* diff -- computes the difference between two strings
* (the minimal number of changes needed to make one equal the other where
* a change is one of the following:
* - replacing a character by another one
* - inserting a character
* - deleting a character
* - swapping two consecutive characters)
*
* by Alfe for TubMud 99-Mar-10
* original idea and a first LPC implementation by Ugh
*
* Notes about the implementation:
* The algorithm conducts an exhaustive search of a tree, which nodes
* consists of the tuple (pos in string a, pos in string b, difference
* computed while advancing the positions so far). Every node has one
* to four children:
* If the characters at the positions match: a new tuple (a+1, b+1, diff).
* If the characters at the positions don't match:
* 1. Always: new tuple (a+1, b+1, diff+1)
* 2. Characters at the position and the next are swapped,
* new tuple (a+2, b+2, diff+1)
* 3. Always: Possible insertion in a, new tuple (a+1, b, diff+1)
* 4. Always: Possible insertion in b, new tuple (a, b+1, diff+1)
*
* The implementation exploits that only the 'diff' is required for the
* result, which allows to keep all tuples in a single list instead
* of explicitely constructing a tree. The list is sorted by the 'diff'
* value of the tuples in increasing order. Since the construction of
* the tree always creates the children for the currently first tuple
* in the list (which is removed by this), the effect for the tree building
* is that always the currently most promising branch of all is searched
* first - it is impossible to get stuck in a local optimum.
*
* The disadvantage is the possible high memory usage: for two strings
* with pairwise swapped characters (e.g. 'abcdef' and 'badcfe') I
* guesstimate O(3**N) created nodes (N being the length of the strings)
* and computation costs of O(2**N). I better dig out the functions
* I wrote in a former life for this problem...
*/
#define DEBUG
#ifdef DEBUG
# define _D_ printf("%s %d\n",__FILE__,__LINE__)
# define _D(x) printf x
int global_debug_counter = 0;
#else
# define _D_
# define _D(x)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int diff(char *,char *,int);
void cleanup_diff_pool();
void main(int argc,char *argv[]) {
if (argc != 4) {
printf("usage: %s <arg1> <arg2> <max>\n",argv[0]);
exit(1);
}
printf("%d\n",diff(argv[1],argv[2],atoi(argv[3])));
/*
* cleanup_diff_pool should be called from time to time when memory
* is needed. to call it here is just one solution (especially in
* combination with debug output to check that all entries are freed
* again)
*/
cleanup_diff_pool();
}
/*
* an entry in the list of found positions
* a -- position in first string
* b -- position in second string
* d -- difference at that point
*/
typedef struct entry {
struct entry *next;
int a,b,d;
} entry;
/*
* this is a pool of disposed entries which are reused to reduce memory
* management overhead.
*/
entry *diff_pool = NULL;
/*
* make a new entry, fill it with the given values, return it.
* this function could well use a pool of old disposed entries instead
* of calling malloc() to create a new entry.
*/
entry *make_entry(int a,int b,int d) {
entry *e;
#define USE_DISPOSED_POOL
#ifndef USE_DISPOSED_POOL
e = malloc(sizeof(entry));
_D(("mem %p %5d %4d %4d %3d malloc\n",e,global_debug_counter++,a,b,d));
#else
if (diff_pool) {
e = diff_pool;
diff_pool = diff_pool->next;
_D(("mem %p %5d %4d %4d %3d reuse\n",e,global_debug_counter++,a,b,d));
}
else {
e = malloc(sizeof(entry));
_D(("mem %p %5d %4d %4d %3d malloc\n",e,global_debug_counter++,a,b,d));
}
#endif
e->a = a;
e->b = b;
e->d = d;
return e;
}
/*
* dispose the given entry (e.g. free it); this function could well put
* the entry into a pool of disposed entries to reduce memory management
* overhead.
*/
void dispose_entry(entry **ep) {
#ifndef USE_DISPOSED_POOL
_D(("mem %p %5d %4d %4d %3d free\n",(*ep),global_debug_counter++,
(*ep)->a,(*ep)->b,(*ep)->d));
free(*ep);
#else
_D(("mem %p %5d %4d %4d %3d dispose\n",(*ep),global_debug_counter++,
(*ep)->a,(*ep)->b,(*ep)->d));
(*ep)->next = diff_pool;
diff_pool = (*ep);
#endif
(*ep) = NULL;
}
/*
* this should cleanup the memory, i.e. free the pool of old disposed entries
* if any exists. it should be called from time to time in a running system,
* but not too often to reduce memory management overhead.
*/
void cleanup_diff_pool() {
int counter;
entry *walker,*e;
walker = diff_pool;
for (counter=0; walker; counter++) {
e = walker;
walker = walker->next;
_D(("mem %p %5d %4d %4d %3d free\n",e,global_debug_counter++,
e->a,e->b,e->d));
free(e);
}
diff_pool = NULL;
_D(("info %d\n",counter));
}
/*
* insert the given entry into the given list at the appropriate place.
*/
void insert_entry(entry *e,entry **startp) {
entry *walker;
if (!(*startp) || // list empty?
e->d < (*startp)->d) { // less than the start entry?
e->next = (*startp);
(*startp) = e;
return;
}
walker = (*startp);
while (walker->next && e->d >= walker->next->d) {
if (walker->a == e->a &&
walker->b == e->b) { // a shorter way to this pos already in list?
dispose_entry(&e);
return;
}
walker = walker->next;
}
// normal case: found place to insert entry
e->next = walker->next;
walker->next = e;
}
/*
* use the first entry of the given queue and produce children of it; add
* them to the list of entries at the appropriate places.
*/
void add_new_entries(char *a,char *b,entry **startp) {
entry *old;
int ap,bp,d;
ap = (*startp)->a;
bp = (*startp)->b;
d = (*startp)->d;
// remove first from list (we will process it now)
old = (*startp);
(*startp) = (*startp)->next;
dispose_entry(&old);
if (a[ap] && b[bp]) { // both strings not at their end?
// create usual child (both strings one further)
if (a[ap] == b[bp]) { // chars equal?
insert_entry(make_entry(ap+1,bp+1,d),startp);
return;
}
else { // not equal, counts as one difference
insert_entry(make_entry(ap+1,bp+1,d+1),startp);
// check for swapped letters: one diff
if (a[ap+1] && b[bp+1]) // both strings still have one more char?
if (a[ap] == b[bp+1] &&
b[bp] == a[ap+1])
insert_entry(make_entry(ap+2,bp+2,d+1),startp);
}
}
if (a[ap]) { // first not at its end?
// create difference child (assume missing letter in second: one diff)
insert_entry(make_entry(ap+1,bp,d+1),startp);
}
if (b[bp]) { // second not at its end?
// create difference child (assume missing letter in first: one diff)
insert_entry(make_entry(ap,bp+1,d+1),startp);
}
}
int diff(char *a,char *b,int max) {
char *s;
int al,bl,h;
entry *e,*start;
al = strlen(a);
bl = strlen(b);
start = make_entry(0,0,0); // start value: at pos (0,0) difference 0
while (start->a < al ||
start->b < bl) {
if (max > 0 && start->d >= max) // maximum reached?
break;
add_new_entries(a,b,&start);
}
h = start->d;
while (start) {
e = start;
start = start->next;
dispose_entry(&e);
}
return h;
}
| 30.271605 | 78 | 0.632953 | [
"3d"
] |
5aa9646614afaf0d94f659ba896d5d94ecb6c60d | 14,852 | h | C | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/internal/utility/TypedProperties.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/internal/utility/TypedProperties.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/internal/utility/TypedProperties.h | 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.
//=========================================================================
#ifndef __ELASTOS_DROID_INTERNAL_UTILITY_TYPEDPROPERTIES_H__
#define __ELASTOS_DROID_INTERNAL_UTILITY_TYPEDPROPERTIES_H__
#include "elastos/droid/ext/frameworkext.h"
#include "Elastos.Droid.Internal.h"
#include <elastos/core/Object.h>
#include <elastos/utility/HashMap.h>
using Elastos::Core::IString;
using Elastos::IO::IReader;
using Elastos::IO::IStreamTokenizer;
using Elastos::Utility::HashMap;
namespace Elastos {
namespace Droid {
namespace Internal {
namespace Utility {
class TypedProperties
: public HashMap
, public ITypedProperties
{
public:
CAR_INTERFACE_DECL()
/**
* Creates an empty TypedProperties instance.
*/
CARAPI constructor();
/**
* Loads zero or more properties from the specified Reader.
* Properties that have already been loaded are preserved unless
* the new Reader overrides or unsets earlier values for the
* same properties.
* <p>
* File syntax:
* <blockquote>
* <tt>
* <type> <property-name> = <value> ;
* <br />
* unset ( <property-name> ) ;
* </tt>
* <p>
* "//" comments everything until the end of the line.
* "/a;" comments everything until the next appearance of "a;/".
* <p>
* Blank lines are ignored.
* <p>
* The only required whitespace is between the type and
* the property name.
* <p>
* <type> is one of {boolean, byte, short, Int32, long,
* float, double, String}, and is case-sensitive.
* <p>
* <property-name> is a valid fully-qualified class name
* (one or more valid identifiers separated by dot characters).
* <p>
* <value> depends on the type:
* <ul>
* <li> boolean: one of {TRUE, false} (case-sensitive)
* <li> byte, short, Int32, long: a valid Java integer constant
* (including non-base-10 constants like 0xabc and 074)
* whose value does not overflow the type. NOTE: these are
* interpreted as Java integer values, so they are all signed.
* <li> float, double: a valid Java floating-point constant.
* If the type is float, the value must fit in 32 bits.
* <li> String: a double-quoted string value, or the word {@code NULL}.
* NOTE: the contents of the string must be 7-bit clean ASCII;
* C-style octal escapes are recognized, but Unicode escapes are not.
* </ul>
* <p>
* Passing a property-name to {@code unset()} will unset the property,
* removing its value and type information, as if it had never been
* defined.
* </blockquote>
*
* @param r The Reader to load properties from
* @throws IOException if an error occurs when reading the data
* @throws IllegalArgumentException if the data is malformed
*/
CARAPI Load(
/* [in] */ IReader* r);
// @Override
CARAPI Get(
/* [in] */ IInterface* key,
/* [out] */ IInterface** value);
/*
* Getters with explicit defaults
*/
/**
* Returns the value of a boolean property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a boolean
*/
CARAPI GetBoolean(
/* [in] */ const String& property,
/* [in] */ Boolean def,
/* [out] */ Boolean* value);
/**
* Returns the value of a byte property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a byte
*/
CARAPI GetByte(
/* [in] */ const String& property,
/* [in] */ Byte def,
/* [out] */ Byte* value);
/**
* Returns the value of a short property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a short
*/
CARAPI GetInt16(
/* [in] */ const String& property,
/* [in] */ Int16 def,
/* [out] */ Int16* value);
/**
* Returns the value of an integer property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not an integer
*/
CARAPI GetInt32(
/* [in] */ const String& property,
/* [in] */ Int32 def,
/* [out] */ Int32* value);
/**
* Returns the value of a long property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a long
*/
CARAPI GetInt64(
/* [in] */ const String& property,
/* [in] */ Int64 def,
/* [out] */ Int64* value);
/**
* Returns the value of a float property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a float
*/
CARAPI GetFloat(
/* [in] */ const String& property,
/* [in] */ Float def,
/* [out] */ Float* value);
/**
* Returns the value of a double property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a double
*/
CARAPI GetDouble(
/* [in] */ const String& property,
/* [in] */ Double def,
/* [out] */ Double* value);
/**
* Returns the value of a string property, or the default if the property
* has not been defined.
*
* @param property The name of the property to return
* @param def The default value to return if the property is not set
* @return the value of the property
* @throws TypeException if the property is set and is not a string
*/
CARAPI GetString(
/* [in] */ const String& property,
/* [in] */ const String& def,
/* [out] */ String* value);
/*
* Getters with implicit defaults
*/
/**
* Returns the value of a boolean property, or false
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a boolean
*/
CARAPI GetBoolean(
/* [in] */ const String& property,
/* [out] */ Boolean* value);
/**
* Returns the value of a byte property, or 0
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a byte
*/
CARAPI GetByte(
/* [in] */ const String& property,
/* [out] */ Byte* value);
/**
* Returns the value of a short property, or 0
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a short
*/
CARAPI GetInt16(
/* [in] */ const String& property,
/* [out] */ Int16* value);
/**
* Returns the value of an integer property, or 0
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not an integer
*/
CARAPI GetInt32(
/* [in] */ const String& property,
/* [out] */ Int32* value);
/**
* Returns the value of a long property, or 0
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a long
*/
CARAPI GetInt64(
/* [in] */ const String& property,
/* [out] */ Int64* value);
/**
* Returns the value of a float property, or 0.0
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a float
*/
CARAPI GetFloat(
/* [in] */ const String& property,
/* [out] */ Float* value);
/**
* Returns the value of a double property, or 0.0
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a double
*/
CARAPI GetDouble(
/* [in] */ const String& property,
/* [out] */ Double* value);
/**
* Returns the value of a String property, or ""
* if the property has not been defined.
*
* @param property The name of the property to return
* @return the value of the property
* @throws TypeException if the property is set and is not a string
*/
CARAPI GetString(
/* [in] */ const String& property,
/* [out] */ String* value);
/**
* Provides string type information about a property.
*
* @param property the property to check
* @return STRING_SET if the property is a string and is non-NULL.
* STRING_NULL if the property is a string and is NULL.
* STRING_NOT_SET if the property is not set (no type or value).
* STRING_TYPE_MISMATCH if the property is set but is not a string.
*/
CARAPI GetStringInfo(
/* [in] */ const String& property,
/* [out] */ Int32* info);
CARAPI Clone(
/* [out] */ IInterface** object);
public:
/**
* Instantiates a {@link java.io.StreamTokenizer} and sets its syntax tables
* appropriately for the {@code TypedProperties} file format.
*
* @param r The {@code Reader} that the {@code StreamTokenizer} will read from
* @return a newly-created and initialized {@code StreamTokenizer}
*/
static CARAPI_(AutoPtr<IStreamTokenizer>) InitTokenizer(
/* [in] */ IReader* r);
static CARAPI ThrowParseException(
/* [in] */ IStreamTokenizer* st,
/* [in] */ const String& expected);
/**
* Converts a string to an internal type constant.
*
* @param typeName the type name to convert
* @return the type constant that corresponds to {@code typeName},
* or {@code TYPE_ERROR} if the type is unknown
*/
static CARAPI_(Int32) InterpretType(
/* [in] */ const String& typeName);
/**
* Parses the data in the reader.
*
* @param r The {@code Reader} containing input data to parse
* @param map The {@code Map} to insert parameter values into
* @throws ParseException if the input data is malformed
* @throws IOException if there is a problem reading from the {@code Reader}
*/
static CARAPI Parse(
/* [in] */ IReader* r,
/* [in] */ IMap* map);
/**
* Parses the next token in the StreamTokenizer as the specified type.
*
* @param st The token source
* @param type The type to interpret next token as
* @return a Boolean, Number subclass, or String representing the value.
* Null strings are represented by the String instance NULL_STRING
* @throws IOException if there is a problem reading from the {@code StreamTokenizer}
*/
static CARAPI ParseValue(
/* [in] */ IStreamTokenizer* st,
/* [in] */ Int32 type,
/* [out] */ IObject** object);
/**
* An unchecked exception that is thrown if a {@code get<TYPE>()} method
* is used to retrieve a parameter whose type does not match the method name.
*/
static CARAPI ThrowTypeException(
/* [in] */ const String& property,
/* [in] */ IInterface* value,
/* [in] */ const String& requestedType);
protected:
CARAPI CloneImpl(
/* [in] */ ITypedProperties* object);
public:
// A sentinel instance used to indicate a NULL string.
static const AutoPtr<IString> NULL_STRING;
// Constants used to represent the supported types.
static const Int32 TYPE_UNSET;
static const Int32 TYPE_BOOLEAN;
static const Int32 TYPE_BYTE;
// TYPE_CHAR: character literal syntax not supported; use short.
static const Int32 TYPE_SHORT;
static const Int32 TYPE_INT;
static const Int32 TYPE_LONG;
static const Int32 TYPE_FLOAT;
static const Int32 TYPE_DOUBLE;
static const Int32 TYPE_STRING;
static const Int32 TYPE_ERROR;
};
} // namespace Utility
} // namespace Internal
} // namespace Droid
} // namespace Elastos
#endif //__ELASTOS_DROID_INTERNAL_UTILITY_TYPEDPROPERTIES_H__
| 34.86385 | 89 | 0.610692 | [
"object"
] |
5aa9a663bd401854aed1cabe6d6c4ab773ee5ddf | 19,039 | c | C | aaFat.c | Mr-Bossman/aaFat | a67d287dfcbb383d0ef923146220c992c19f61c6 | [
"MIT"
] | 1 | 2021-10-08T23:34:26.000Z | 2021-10-08T23:34:26.000Z | aaFat.c | Mr-Bossman/aaFat | a67d287dfcbb383d0ef923146220c992c19f61c6 | [
"MIT"
] | null | null | null | aaFat.c | Mr-Bossman/aaFat | a67d287dfcbb383d0ef923146220c992c19f61c6 | [
"MIT"
] | null | null | null |
#include "aaFat.h"
#ifdef EXAMPLE_
//#define BACKTRACE_ERR
#define BT_SZ 100
#define TABLE_LEN 50
#define BLOCK_SIZE 1024
unsigned char *store;
int read_blk(size_t offset, unsigned char *mem)
{
if (offset >= TABLE_LEN)
return -1;
memcpy(mem, store + (offset * BLOCK_SIZE), BLOCK_SIZE);
return ERR_OK;
}
int write_blk(size_t offset, unsigned char *mem)
{
if (offset >= TABLE_LEN)
return -1;
memcpy(store + (offset * BLOCK_SIZE), mem, BLOCK_SIZE);
return ERR_OK;
}
#endif
#ifdef BACKTRACE_ERR
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#endif
/* TODO: double check error checks */
/* Curent error number. */
static ERR err = -ERR_OK;
#define chk_err() \
do { \
if (err) \
return; \
} while(0)
#define chk_err_e() \
do { \
if (err) \
return err; \
} while(0)
#define fatal_check() \
do { \
if (err) \
if (validate_FAT()) \
return err; \
} while(0)
#define min(a,b) (((a)>(b))?(b):(a))
#define max(a,b) (((a)<(b))?(b):(a))
int read_blk(size_t offset, unsigned char *mem);
int write_blk(size_t offset, unsigned char *mem);
/* Clears and returns current error number. */
ERR FAT_ERRpop()
{
ERR tmp = err;
err = -ERR_OK;
return tmp;
}
/* Names of ERR numbers. */
static char *ERR_NAME[] =
{ENUMS(ERR_OK), ENUMS(READ_BLK_ERR), ENUMS(WRITE_BLK_ERR), ENUMS(BLK_OOB),
ENUMS(BLK_NSP), ENUMS(BLK_EOF), ENUMS(FS_LOOP), ENUMS(FS_FNF), ENUMS(FS_BNAME),
ENUMS(FS_OOB), ENUMS(FS_INVALID)};
/* Prints current error number and name. */
int print_ERR()
{
ERR tmp = FAT_ERRpop();
int ret = printf("ERR: %s\n", ERR_NAME[-tmp]);
if (tmp != ERR_OK)
{
#ifdef BACKTRACE_ERR
void *buffer[BT_SZ];
int nptrs = backtrace(buffer, BT_SZ);
printf("backtrace() returned %d addresses\n", nptrs);
backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO);
#endif
}
return ret;
}
static uint32_t get_nextblock(uint32_t block_index);
static uint32_t get_block_itter(uint32_t start, uint32_t i);
static uint32_t get_block_len(uint32_t start);
static uint32_t get_freeblock();
static uint32_t extend_blocks(uint32_t index);
static uint32_t add_block();
static int del_block(uint32_t index);
static int new_file_size(const char *name, size_t size, uint8_t shrink);
static int check_block_loop(uint32_t index);
static int end_block(uint32_t index);
/* Writes FAT to block, over writes. */
/* Returns error num. */
int write_FAT()
{
#ifdef EXAMPLE_
store = malloc(BLOCK_SIZE*TABLE_LEN);
if(!store)
{
printf("Can't alloc.\n");
}
#endif
if (BLOCK_SIZE < TABLE_LEN * sizeof(uint32_t))
{
printf("Invalid conf.\n");
err = FS_INVALID;
return err;
}
unsigned char fat[BLOCK_SIZE];
memset(fat, 0xFF, BLOCK_SIZE);
((uint32_t *)fat)[0] = 1;
((uint32_t *)fat)[1] = 0;
if (write_blk(0, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
memset(fat, 0, BLOCK_SIZE);
if (write_blk(1, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
err = ERR_OK;
return err;
}
/* Returns the integrity of file system. */
/* Returns error num. */
int validate_FAT()
{
err = ERR_OK;
unsigned char fat[BLOCK_SIZE];
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
if (((uint32_t *)fat)[0] != 1)
{
err = -FS_INVALID;
return err;
}
if (((uint32_t *)fat)[1] != 0)
{
err = -FS_INVALID;
return err;
}
check_block_loop(1);
chk_err_e();
size_t b = file_count();
chk_err_e();
name_file file;
while (b--)
{
get_file_index(&file,b);
chk_err_e();
if (strnlen(file.name, 16) == 16)
{
err = -FS_BNAME;
return err;
}
check_block_loop(file.index);
chk_err_e();
}
return ERR_OK;
}
/* Gets Next block in linked list. */
/* Returns error num or block. */
static uint32_t get_nextblock(uint32_t block_index)
{
unsigned char fat[BLOCK_SIZE] = {0};
if (block_index > TABLE_LEN)
{
err = -BLK_OOB;
return err;
}
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
uint32_t tmp = ((uint32_t *)fat)[block_index];
if (tmp == UINT32_MAX)
{
err = -FS_INVALID;
return err;
}
return tmp;
}
/* Get 'i'th block from start. */
/* Returns error num or block. */
static uint32_t get_block_itter(uint32_t start, uint32_t i)
{
if (!i)
return start;
uint32_t blocks = start;
while (((blocks = get_nextblock(blocks))))
{
chk_err_e();
i--;
if (!i)
return blocks;
}
err = -BLK_EOF;
return err;
}
/* Get total block lenth of linked list staring at start. */
/* Returns error num or number of blocks. */
static uint32_t get_block_len(uint32_t start)
{
uint32_t i = 0;
uint32_t blocks = start;
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
i++;
}
return i;
}
/* Checks for loops in file system linked list. */
/* Returns error num. */
static int check_block_loop(uint32_t index)
{
unsigned char fat[BLOCK_SIZE] = {0};
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
if (!index)
{
err = -BLK_OOB;
return err;
}
/*if(index >= TABLE_LEN)
{
err = -FS_INVALID;
return err;
}
uint32_t tortoise = index;
uint32_t hare = ((uint32_t *)fat)[index];
while (hare && hare >= TABLE_LEN && ((uint32_t *)fat)[hare] && ((uint32_t *)fat)[hare] >= TABLE_LEN)
{
if (tortoise == hare)
{
err = -FS_LOOP;
return err;
}
tortoise = ((uint32_t *)fat)[tortoise];
if(tortoise >= TABLE_LEN)
{
err = -FS_INVALID;
return err;
}
if(tortoise == UINT32_MAX)
tortoise = 0;
uint32_t tmp = ((uint32_t *)fat)[hare];
if(tmp >= TABLE_LEN)
{
err = -FS_INVALID;
return err;
}
if(tmp == UINT32_MAX)
hare = 0;
else
hare = ((uint32_t *)fat)[tmp];
if(hare >= TABLE_LEN)
{
err = -FS_INVALID;
return err;
}
if(hare == UINT32_MAX)
hare = 0;
}*/
return ERR_OK;
}
/* Gets next free block. */
/* Returns error num or block. */
static uint32_t get_freeblock()
{
unsigned char fat[BLOCK_SIZE] = {0};
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
for (size_t i = 0; i < TABLE_LEN; i++)
if (((uint32_t *)fat)[i] == UINT32_MAX)
return i;
err = -BLK_NSP;
return err;
}
/* Adds free block to end of link list. */
/* Returns error num. */
static uint32_t extend_blocks(uint32_t index)
{
unsigned char fat[BLOCK_SIZE] = {0};
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
check_block_loop(index);
chk_err_e();
uint32_t last;
while (index)
{
last = index;
index = ((uint32_t *)fat)[index];
}
uint32_t tmp = get_freeblock();
chk_err_e();
((uint32_t *)fat)[last] = tmp;
((uint32_t *)fat)[tmp] = 0;
if (write_blk(0, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
memset(fat, 0, BLOCK_SIZE);
if (write_blk(tmp, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
return tmp;
}
/* Ends a block after deleting. */
/* Returns error num. */
static int end_block(uint32_t index)
{
unsigned char fat[BLOCK_SIZE] = {0};
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
((uint32_t *)fat)[index] = 0;
if (write_blk(0, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
return ERR_OK;
}
/* Add new linked list to FAT. */
/* Returns error num or block. */
static uint32_t add_block()
{
unsigned char fat[BLOCK_SIZE] = {0};
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
uint32_t tmp = get_freeblock();
chk_err_e();
((uint32_t *)fat)[tmp] = 0;
if (write_blk(0, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
memset(fat, 0, BLOCK_SIZE);
if (write_blk(tmp, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
return tmp;
}
/* Deletes all blocks in linked list after index. */
/* Returns error num. */
static int del_block(uint32_t index)
{
if (index == 0 || index > TABLE_LEN)
{
err = -BLK_OOB;
return err;
}
unsigned char fat[BLOCK_SIZE] = {0};
if (read_blk(0, fat))
{
err = -READ_BLK_ERR;
return err;
}
check_block_loop(index);
chk_err_e();
uint32_t last;
while (index)
{
last = index;
index = ((uint32_t *)fat)[index];
((uint32_t *)fat)[last] = -1;
}
if (write_blk(0, fat))
{
err = -WRITE_BLK_ERR;
return err;
}
return ERR_OK;
}
/* Gets the total number of files. */
/* Returns error num or number of files. */
size_t file_count()
{
fatal_check();
size_t n = 0;
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
size_t i = 0;
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
while (1)
{
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
if (((name_file *)name_table)[i].index == 0)
break;
if (((name_file *)name_table)[i].index == 1)
n--;
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
n += i;
}
return n;
}
/* Gets the file struct at index. */
/* Returns error num. */
int get_file_index(name_file *ret, size_t index)
{
fatal_check();
uint32_t blocks = 0;
size_t n = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
if (((name_file *)name_table)[i].index == 1)
index++;
if (i+n == index)
{
*ret = ((name_file *)name_table)[i];
return ERR_OK;
}
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
n += i;
}
err = -FS_FNF;
return err;
}
/* Gets the index of index. */
/* Returns error num. */
uint32_t get_index_file(const char *name)
{
fatal_check();
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
uint32_t blocks = 0;
size_t n = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
size_t b = strnlen(((name_file *)name_table)[i].name, 16);
if (b == strnlen(name, 16))
if (!strncmp(name, ((name_file *)name_table)[i].name, 16))
return n+i;
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
n += i;
}
err = -FS_FNF;
return err;
}
/* Gets first block of file. */
/* Returns error num or block. */
uint32_t get_file_block(const char *name)
{
fatal_check();
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
size_t b = strnlen(((name_file *)name_table)[i].name, 16);
if (b == strnlen(name, 16))
if (!strncmp(name, ((name_file *)name_table)[i].name, 16))
return ((name_file *)name_table)[i].index;
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
err = -FS_FNF;
return err;
}
/* Gets if file exists */
/* Returns error. */
int get_file_exists(const char *name)
{
fatal_check();
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
size_t b = strnlen(((name_file *)name_table)[i].name, 16);
if (b == strnlen(name, 16))
if (!strncmp(name, ((name_file *)name_table)[i].name, 16))
return ERR_OK;
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
err = -FS_FNF;
return err;
}
/* Gets file size. */
/* Returns error num or size of file. */
size_t get_file_size(const char *name)
{
fatal_check();
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
size_t b = strnlen(((name_file *)name_table)[i].name, 16);
if (b == strnlen(name, 16))
if (!strncmp(name, ((name_file *)name_table)[i].name, 16))
return ((name_file *)name_table)[i].size_b;
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
err = -FS_FNF;
return err;
}
/* Updates size not block */
/* Returns error num. */
static int new_file_size(const char *name, size_t size, uint8_t shrink)
{
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
size_t b = strnlen(((name_file *)name_table)[i].name, 16);
if (b == strnlen(name, 16))
if (!strncmp(name, ((name_file *)name_table)[i].name, 16))
{
size_t tmp = ((name_file *)name_table)[i].size_b;
if(!shrink)
size = max(size,tmp);
((name_file *)name_table)[i].size_b = size;
if (write_blk(blocks, name_table))
{
err = -WRITE_BLK_ERR;
return err;
}
return ERR_OK;
}
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
err = -FS_FNF;
return err;
}
int set_file_size(const char * name,size_t size){
fatal_check();
uint32_t blk = get_file_block(name);
chk_err_e();
size_t block_num = (size/BLOCK_SIZE);
uint32_t total = get_block_len(blk);
chk_err_e();
if(block_num < total && block_num) {
uint32_t last = get_block_itter(blk,block_num);
chk_err_e();
uint32_t del = get_nextblock(last);
chk_err_e();
del_block(del);
chk_err_e();
end_block(last);
chk_err_e();
} else if( block_num > total) {
uint32_t last = get_block_itter(blk,total);
chk_err_e();
for(uint32_t i =total; i < block_num;i++){
extend_blocks(last);
chk_err_e();
}
}
total = get_block_len(blk);
chk_err_e();
new_file_size(name, size, 1);
chk_err_e();
return ERR_OK;
}
/* Adds new file. */
/* Returns error num. */
int new_file(const char *name)
{
fatal_check();
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
get_file_exists(name);
if (err == -ERR_OK)
{
err = -FS_BNAME;
return err;
}
else if (err != -FS_FNF)
{
chk_err_e();
}
else
err = -ERR_OK;
char name_padded[16] = {0};
memcpy(name_padded, name, b);
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while (1)
{
uint32_t tmp = get_nextblock(blocks);
chk_err_e();
if (!tmp)
extend_blocks(blocks);
chk_err_e();
blocks = tmp;
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
if (((name_file *)name_table)[i].index == 0 || ((name_file *)name_table)[i].index == 1)
{
name_file tmp;
memcpy(tmp.name, name_padded, 16);
tmp.index = add_block();
tmp.size_b = 0;
chk_err_e();
((name_file *)name_table)[i] = tmp;
if (write_blk(blocks, name_table))
{
err = -WRITE_BLK_ERR;
return err;
}
return ERR_OK;
}
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
}
/* Deletes file. */
/* Returns error num. */
int del_file(const char *name)
{
fatal_check();
size_t b = strnlen(name, 16);
if (b == 16)
{
err = -FS_BNAME;
return err;
}
ERR ret = -FS_FNF;
char name_padded[16] = {0};
memcpy(name_padded, name, b);
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
chk_err_e();
if (read_blk(blocks, name_table))
{
err = -READ_BLK_ERR;
return err;
}
size_t i = 0;
while (1)
{
size_t b = strnlen(((name_file *)name_table)[i].name, 16);
if (b == strnlen(name, 16))
if (!strncmp(name, ((name_file *)name_table)[i].name, 16))
{
ret = -ERR_OK;
del_block(((name_file *)name_table)[i].index);
chk_err_e();
name_file tmp;
memset(tmp.name, 0, 16);
tmp.index = 1;
((name_file *)name_table)[i] = tmp;
if (write_blk(blocks, name_table))
{
err = -WRITE_BLK_ERR;
return err;
}
break;
}
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
return ret;
}
/* Reads from file. */
/* Returns error num. */
int read_file(const char *file_name, void *buffer, size_t count, size_t offset)
{
fatal_check();
char *buf = buffer;
if (count + offset > get_file_size(file_name))
{
err = -FS_OOB;
return err;
}
chk_err_e();
uint32_t blk = get_file_block(file_name);
chk_err_e();
unsigned char BLOCKS[BLOCK_SIZE] = {0};
while (blk)
{
chk_err_e();
if (offset >= BLOCK_SIZE)
{
offset -= BLOCK_SIZE;
blk = get_nextblock(blk);
continue;
}
if (read_blk(blk, BLOCKS))
{
err = -READ_BLK_ERR;
return err;
}
size_t cpy_len = min(count + offset, BLOCK_SIZE);
cpy_len -= offset;
count -= cpy_len;
memcpy(buf, BLOCKS + offset, cpy_len);
buf += cpy_len;
offset = 0;
if (!count)
break;
blk = get_nextblock(blk);
}
return ERR_OK;
}
/* Write to file. */
/* Returns error num*/
int write_file(const char *file_name, void *buffer, size_t count, size_t offset)
{
fatal_check();
char *buf = buffer;
uint32_t blk = get_file_block(file_name);
chk_err_e();
unsigned char BLOCKS[BLOCK_SIZE] = {0};
size_t sz = offset + count;
while (1)
{
uint32_t tmp;
if (offset >= BLOCK_SIZE)
{
offset -= BLOCK_SIZE;
goto end;
}
if (read_blk(blk, BLOCKS))
{
err = -READ_BLK_ERR;
return err;
}
size_t cpy_len = min(count + offset, BLOCK_SIZE);
cpy_len -= offset;
count -= cpy_len;
memcpy(BLOCKS + offset, buf, cpy_len);
buf += cpy_len;
if (write_blk(blk, BLOCKS))
{
err = -WRITE_BLK_ERR;
return err;
}
offset = 0;
if(!count)
break;
end:
do
{
tmp = get_nextblock(blk);
chk_err_e();
if (!tmp)
extend_blocks(blk);
chk_err_e();
} while (!tmp);
blk = tmp;
}
new_file_size(file_name, sz, 0);
chk_err_e();
return ERR_OK;
}
/* No error checking. */
void print_fat()
{
puts("FAT, linked list:");
unsigned char fat[BLOCK_SIZE] = {0};
read_blk(0, fat);
printf("%3d", ((uint32_t *)fat)[0]);
for (size_t i = 1; i < TABLE_LEN; i++)
printf(",%3d", ((uint32_t *)fat)[i]);
puts("");
printf(" 0");
for (size_t i = 1; i < TABLE_LEN; i++)
printf(",%3lu", i);
puts("");
}
/* No error checking. */
void print_file_table()
{
uint32_t blocks = 0;
unsigned char name_table[BLOCK_SIZE] = {0};
while ((blocks = get_nextblock(blocks)))
{
read_blk(blocks, name_table);
size_t i = 0;
while (1)
{
if (((name_file *)name_table)[i].index == 0)
break;
if (((name_file *)name_table)[i].index == 1)
{
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
continue;
}
printf("%s, BLKS: %u", ((name_file *)name_table)[i].name, ((name_file *)name_table)[i].index);
{
uint32_t blk = ((name_file *)name_table)[i].index;
while ((blk = get_nextblock(blk)))
printf(",%u", blk);
puts("");
}
i++;
if (i * sizeof(name_file) >= BLOCK_SIZE)
break;
}
}
}
| 19.173212 | 103 | 0.619045 | [
"3d"
] |
5aaa74a6dc87194c89e4d14a4f7f975b176eb8fb | 1,038 | c | C | src/vector/vector_push_back.c | StarNuik/libft2 | 93fe782c00471981623e2bf749f3e68405115c8b | [
"MIT"
] | null | null | null | src/vector/vector_push_back.c | StarNuik/libft2 | 93fe782c00471981623e2bf749f3e68405115c8b | [
"MIT"
] | null | null | null | src/vector/vector_push_back.c | StarNuik/libft2 | 93fe782c00471981623e2bf749f3e68405115c8b | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* vector_push_back.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sbosmer <sbosmer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/01 14:11:10 by sbosmer #+# #+# */
/* Updated: 2021/03/08 17:20:50 by sbosmer ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft2/vector.h"
t_bool vector_push_back(t_vector *vector, void *object)
{
return (vector_insert(vector, object, vector->length));
}
| 54.631579 | 80 | 0.207129 | [
"object",
"vector"
] |
5aabc284fed9f74b7859ea526be11a83515fc4e5 | 2,330 | c | C | kubernetes/unit-test/test_apps_v1beta1_deployment_strategy.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 69 | 2020-03-17T13:47:05.000Z | 2022-03-30T08:25:05.000Z | kubernetes/unit-test/test_apps_v1beta1_deployment_strategy.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 115 | 2020-03-17T14:53:19.000Z | 2022-03-31T11:31:30.000Z | kubernetes/unit-test/test_apps_v1beta1_deployment_strategy.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 28 | 2020-03-17T13:42:21.000Z | 2022-03-19T23:37:16.000Z | #ifndef apps_v1beta1_deployment_strategy_TEST
#define apps_v1beta1_deployment_strategy_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define apps_v1beta1_deployment_strategy_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/apps_v1beta1_deployment_strategy.h"
apps_v1beta1_deployment_strategy_t* instantiate_apps_v1beta1_deployment_strategy(int include_optional);
#include "test_apps_v1beta1_rolling_update_deployment.c"
apps_v1beta1_deployment_strategy_t* instantiate_apps_v1beta1_deployment_strategy(int include_optional) {
apps_v1beta1_deployment_strategy_t* apps_v1beta1_deployment_strategy = NULL;
if (include_optional) {
apps_v1beta1_deployment_strategy = apps_v1beta1_deployment_strategy_create(
// false, not to have infinite recursion
instantiate_apps_v1beta1_rolling_update_deployment(0),
"0"
);
} else {
apps_v1beta1_deployment_strategy = apps_v1beta1_deployment_strategy_create(
NULL,
"0"
);
}
return apps_v1beta1_deployment_strategy;
}
#ifdef apps_v1beta1_deployment_strategy_MAIN
void test_apps_v1beta1_deployment_strategy(int include_optional) {
apps_v1beta1_deployment_strategy_t* apps_v1beta1_deployment_strategy_1 = instantiate_apps_v1beta1_deployment_strategy(include_optional);
cJSON* jsonapps_v1beta1_deployment_strategy_1 = apps_v1beta1_deployment_strategy_convertToJSON(apps_v1beta1_deployment_strategy_1);
printf("apps_v1beta1_deployment_strategy :\n%s\n", cJSON_Print(jsonapps_v1beta1_deployment_strategy_1));
apps_v1beta1_deployment_strategy_t* apps_v1beta1_deployment_strategy_2 = apps_v1beta1_deployment_strategy_parseFromJSON(jsonapps_v1beta1_deployment_strategy_1);
cJSON* jsonapps_v1beta1_deployment_strategy_2 = apps_v1beta1_deployment_strategy_convertToJSON(apps_v1beta1_deployment_strategy_2);
printf("repeating apps_v1beta1_deployment_strategy:\n%s\n", cJSON_Print(jsonapps_v1beta1_deployment_strategy_2));
}
int main() {
test_apps_v1beta1_deployment_strategy(1);
test_apps_v1beta1_deployment_strategy(0);
printf("Hello world \n");
return 0;
}
#endif // apps_v1beta1_deployment_strategy_MAIN
#endif // apps_v1beta1_deployment_strategy_TEST
| 36.984127 | 161 | 0.840773 | [
"model"
] |
5ab2eb3cdbce90b91f381db35eed040aa203e590 | 1,214 | h | C | Grafos/GrafoM.h | monotera/Estructuras | 9d186839500bd51e0cb351da8a8c0124f8623a79 | [
"MIT"
] | 3 | 2020-02-19T03:53:29.000Z | 2020-08-28T02:31:09.000Z | Grafos/GrafoM.h | monotera/Estructuras | 9d186839500bd51e0cb351da8a8c0124f8623a79 | [
"MIT"
] | 3 | 2020-03-12T19:29:13.000Z | 2020-05-28T17:39:21.000Z | Grafos/GrafoM.h | monotera/Estructuras | 9d186839500bd51e0cb351da8a8c0124f8623a79 | [
"MIT"
] | 2 | 2020-02-20T00:57:48.000Z | 2021-03-13T23:25:21.000Z | #ifndef __GRAFOM__H__
#define __GRAFOM__H__
#include <vector>
#include <utility>
#include <stack>
using namespace std;
typedef long long unsigned ll;
template <class T, class C>
class GrafoM
{
protected:
vector <vector<C>> matAristas;
vector<T> vertices;
ll numVertices = 0;
public:
int cantiVertices();
int cantiAristas();
void insertarVertice(T Vertice);
void insertarArista(T origen, T destino, C peso);
ll buscarVertice(T vertice);
T obtenerVertice(ll indice);
bool buscarArista(ll origen, ll destino);
void eliminarVertice(T vertice);
void eliminarArista(T origen, T destino);
void recorridoPlano();
void imprimirGrafo();
void recorridoDFS(T inicio);
void recorridoDFS(ll inicio, bool *visitados);
void recorridoBFS(T inicio);
void prim(T inicio,vector<T> &camino,vector<T> &predecesor ,vector<C> &pesos);
void menorPeso(vector<pair<int,int>> &vistos);
void dijkstra(T inicio, vector<T> &s, vector<T> &pred, vector<C> &dist);
vector<C**> floydWarshall();
vector<T> caminoFloyd(vector<C**> floyd, T ori,T destino);
vector<vector<vector<T>>> caminosFloyd(vector<C**> floyd);
};
#include "GrafoM.hxx"
#endif | 28.232558 | 82 | 0.689456 | [
"vector"
] |
5ab7d101807118a959613f9806d413f1ae38b022 | 2,082 | h | C | codegen/cpp/cerata/src/cerata/vhdl/template.h | fnonnenmacher/fletcher | fc2098db0b84e5b3d30ad96f1bb9ae6655861811 | [
"Apache-2.0"
] | 3 | 2020-04-20T10:48:28.000Z | 2022-02-08T00:31:08.000Z | codegen/cpp/cerata/src/cerata/vhdl/template.h | fnonnenmacher/fletcher | fc2098db0b84e5b3d30ad96f1bb9ae6655861811 | [
"Apache-2.0"
] | 2 | 2020-03-30T10:46:22.000Z | 2020-07-27T12:34:50.000Z | codegen/cpp/cerata/src/cerata/vhdl/template.h | fnonnenmacher/fletcher | fc2098db0b84e5b3d30ad96f1bb9ae6655861811 | [
"Apache-2.0"
] | 1 | 2022-02-08T00:31:25.000Z | 2022-02-08T00:31:25.000Z | // Copyright 2018-2019 Delft University of Technology
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <regex>
#include <map>
namespace cerata::vhdl {
/// Structure to hold a template replacement string location
struct trloc {
/// @brief Template replacement location constructor.
trloc(size_t line, size_t start) : line(line), start(start) {}
/// The line.
size_t line;
/// The starting character index on the line.
size_t start;
};
/// @brief Class to hold and modify a VHDL template file.
class Template {
public:
/// @brief Construct a Template from an input stream.
explicit Template(std::istream *str);
/// @brief Construct a Template from an input string.
static Template FromString(const std::string& str);
/// @brief Construct a Template from a file.
static Template FromFile(const std::string &filename);
/// @brief Mark the locations of all replaceable template strings.
void Analyze();
/// @brief Replace a template replacement string with some number.
void Replace(const std::string &str, int with);
/// @brief Replace a template replacement string with some other string.
void Replace(const std::string &str, const std::string &with);
/// @brief Return the file as a string.
std::string ToString();
private:
/// Map from a template replacement string to a vector of line numbers.
std::map<std::string, std::vector<trloc>> replace_list_;
/// Lines of the file.
std::vector<std::string> lines_;
};
} // namespace cerata::vhdl
| 34.131148 | 75 | 0.722863 | [
"vector"
] |
5abcee5231995165b74885d928e445587ff23845 | 895 | h | C | src/rcpp_get_wecoma.h | Nowosad/comat | 1ee49911e46dca3549080361b655c58f8af01978 | [
"MIT"
] | 5 | 2019-07-17T09:00:06.000Z | 2022-03-21T04:22:28.000Z | src/rcpp_get_wecoma.h | Nowosad/comat | 1ee49911e46dca3549080361b655c58f8af01978 | [
"MIT"
] | 13 | 2019-08-23T09:42:26.000Z | 2020-03-30T16:07:26.000Z | src/rcpp_get_wecoma.h | Nowosad/comat | 1ee49911e46dca3549080361b655c58f8af01978 | [
"MIT"
] | null | null | null | #ifndef RCPP_GET_WECOMA_H
#define RCPP_GET_WECOMA_H
#include <RcppArmadillo.h>
using namespace Rcpp;
//[[Rcpp::interfaces(r, cpp)]]
Rcpp::NumericMatrix rcpp_get_wecoma(const Rcpp::IntegerMatrix& x,
const Rcpp::NumericMatrix& w,
const arma::imat& directions,
const std::string fun = "mean",
const std::string na_action = "replace") ;
Rcpp::NumericMatrix rcpp_get_wecoma_internal(const Rcpp::IntegerMatrix& x,
const Rcpp::NumericMatrix& w,
const arma::imat& directions,
std::vector<int> classes,
const std::string fun = "mean",
const std::string na_action = "replace") ;
#endif // RCPP_GET_WECOMA_H
| 40.681818 | 78 | 0.510615 | [
"vector"
] |
5abf27e35a57996842c0810f9ed351f7f7236f60 | 74,104 | h | C | src/lib/fasync/include/lib/fasync/internal/future.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/lib/fasync/include/lib/fasync/internal/future.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | src/lib/fasync/include/lib/fasync/internal/future.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_LIB_FASYNC_INCLUDE_LIB_FASYNC_INTERNAL_FUTURE_H_
#define SRC_LIB_FASYNC_INCLUDE_LIB_FASYNC_INTERNAL_FUTURE_H_
#include <lib/fasync/internal/compiler.h>
LIB_FASYNC_CPP_VERSION_COMPAT_BEGIN
// fit::function is still C++14-compliant, but when we compile in C++17 mode these warnings still
// fire.
LIB_FASYNC_IGNORE_CPP14_COMPAT_BEGIN
#include <lib/fit/function.h>
LIB_FASYNC_IGNORE_CPP14_COMPAT_END
#include <lib/fasync/internal/type_traits.h>
#include <lib/fasync/poll.h>
#include <lib/fasync/type_traits.h>
#include <lib/fitx/result.h>
#include <lib/stdcompat/functional.h>
#include <lib/stdcompat/optional.h>
#include <lib/stdcompat/span.h>
#include <lib/stdcompat/tuple.h>
#include <lib/stdcompat/type_traits.h>
#include <lib/stdcompat/variant.h>
#include <algorithm>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace fasync {
class context;
namespace internal {
using ::fitx::internal::requires_conditions;
using ::fitx::internal::is_match;
using ::fitx::internal::is_match_v;
using ::fitx::internal::is_error;
using ::fitx::internal::is_error_v;
using ::fitx::internal::is_success;
using ::fitx::internal::is_success_v;
using ::fitx::internal::is_result;
using ::fitx::internal::is_result_v;
template <typename T, requires_conditions<cpp17::negation<std::is_move_assignable<T>>> = true>
constexpr void move_construct_optional(cpp17::optional<T>& to, T&& from) {
to.emplace(std::move(from));
}
template <typename T, requires_conditions<std::is_move_assignable<T>> = true>
constexpr void move_construct_optional(cpp17::optional<T>& to, T&& from) {
to = std::move(from);
}
////// BEGIN CONCEPTS EQUIVALENTS /////////
template <typename H, typename... Args>
struct is_invocable_with_applicable : std::false_type {};
template <typename H, typename T>
struct is_invocable_with_applicable<H, T> : is_applicable_to<H, T>::type {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_with_applicable_v =
is_invocable_with_applicable<H, Args...>::value;
template <typename T>
struct is_context_arg : cpp17::conjunction<std::is_lvalue_reference<T>,
std::is_base_of<context, cpp20::remove_cvref_t<T>>> {};
template <typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_context_arg_v = is_context_arg<Args...>::value;
template <typename... Args>
struct has_context_arg : is_context_arg<first_t<Args...>>::type {};
template <>
struct has_context_arg<> : std::false_type {};
template <typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool has_context_arg_v = has_context_arg<Args...>::value;
template <typename H, typename... Args>
constexpr auto args_as_list_impl(std::nullptr_t)
-> decltype(std::declval<H>()({std::declval<Args>()...}), std::true_type());
template <typename H, typename... Args>
constexpr std::false_type args_as_list_impl(...);
template <typename H, typename... Args>
struct is_invocable_with_args_as_list : decltype(args_as_list_impl<H, Args...>(nullptr)) {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_with_args_as_list_v =
is_invocable_with_args_as_list<H, Args...>::value;
////// END CONCEPTS EQUIVALENTS /////////
} // namespace internal
namespace internal {
template <typename...>
struct delay_compile_error : std::false_type {};
template <typename H, typename... Args>
constexpr void invoke_compile_error(H&& handler, Args&&... args) {
static_assert(delay_compile_error<H, Args...>::value,
"Your handler does not meet the requirements in order to be valid.\n"
"See the documentation of |fasync::future| for more information\n");
}
template <typename H, typename T, typename = bool>
struct apply_result {};
template <typename H, typename T>
struct apply_result<H, T, requires_conditions<is_applicable_to<H, T>>> {
using type = decltype(cpp17::apply(std::declval<H>(), std::declval<T>()));
};
template <typename H, typename T>
using apply_result_t = typename apply_result<H, T>::type;
template <typename StoredF, typename... BoundArgs>
class ref_binder {
public:
template <typename F, typename... Args>
explicit constexpr ref_binder(F&& f, Args&&... args)
: stored_f_(std::forward<F>(f)), bound_args_(std::forward<Args>(args)...) {}
// TODO(schottm): do other ref-qualifier overloads, might have to go back to the old
// std::index_sequence way to make it work
template <typename... CallArgs,
requires_conditions<cpp17::is_invocable<StoredF, BoundArgs..., CallArgs...>> = true>
constexpr decltype(auto) operator()(CallArgs&&... call_args) {
return cpp17::apply(
[this](auto&&... all_args) -> decltype(auto) {
return cpp20::invoke(stored_f_, std::forward<decltype(all_args)>(all_args)...);
},
std::tuple_cat(std::move(bound_args_),
std::forward_as_tuple(std::forward<CallArgs>(call_args)...)));
}
private:
StoredF stored_f_;
LIB_FASYNC_NO_UNIQUE_ADDRESS std::tuple<BoundArgs...> bound_args_;
};
// cpp20::bind_front is not sufficient since it can't store references or unwrap
// std::reference_wrapper
template <typename F, typename... BoundArgs>
auto bind_refs(F&& f, BoundArgs&&... bound_args) {
// Note: the way forwarding works, this binder is designed to store lvalue references directly.
return ref_binder<F, BoundArgs...>(std::forward<F>(f), std::forward<BoundArgs>(bound_args)...);
}
template <typename H, typename... Args,
requires_conditions<cpp17::bool_constant<(sizeof...(Args) == 1)>,
is_applicable<first_t<Args...>>> = true>
constexpr decltype(auto) invoke_with_applicable_as_list(H&& handler, Args&&... args) {
return cpp17::apply(
[&](auto&&... list) -> decltype(auto) {
return std::forward<H>(handler)({std::forward<decltype(list)>(list)...});
},
std::forward<Args>(args)...);
}
} // namespace internal
namespace internal {
////// BEGIN CONCEPTS EQUIVALENTS /////////
template <typename H, typename... Args>
constexpr auto applicable_as_list_impl(std::nullptr_t)
-> decltype(std::declval<H>()({}),
invoke_with_applicable_as_list(std::declval<H>(), std::declval<Args>()...),
std::true_type());
template <typename H, typename... Args>
constexpr std::false_type applicable_as_list_impl(...);
template <typename H, typename... Args>
struct is_invocable_with_applicable_as_list
: decltype(applicable_as_list_impl<H, Args...>(nullptr)) {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_with_applicable_as_list_v =
is_invocable_with_applicable_as_list<H, Args...>::value;
template <typename H, typename... Args>
struct is_invocable_handler_internal
: cpp17::conjunction<
cpp17::negation<has_context_arg<Args...>>,
cpp17::disjunction<
is_invocable_with_applicable<H, Args...>, cpp17::is_invocable<H, Args...>,
is_invocable_with_args_as_list<H, Args...>,
is_invocable_with_applicable_as_list<H, Args...>, cpp17::is_invocable<H>>>::type {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_handler_internal_v =
is_invocable_handler_internal<H, Args...>::value;
////// END CONCEPTS EQUIVALENTS /////////
template <typename H, typename T, requires_conditions<is_invocable_with_applicable<H, T>> = true>
constexpr apply_result_t<H, T> invoke_handler_internal(priority_tag<4>, H&& handler,
T&& applicable) {
return cpp17::apply(std::forward<H>(handler), std::forward<T>(applicable));
}
template <typename H, typename... Args,
requires_conditions<cpp17::negation<is_invocable_with_applicable<H, Args...>>,
cpp17::is_invocable<H, Args...>> = true>
constexpr cpp17::invoke_result_t<H, Args...> invoke_handler_internal(priority_tag<3>, H&& handler,
Args&&... args) {
return cpp20::invoke(std::forward<H>(handler), std::forward<Args>(args)...);
}
template <typename H, typename... Args,
requires_conditions<is_invocable_with_args_as_list<H, Args...>> = true>
constexpr auto invoke_handler_internal(priority_tag<2>, H&& handler, Args&&... args)
-> decltype(std::forward<H>(handler)({std::forward<Args>(args)...})) {
return std::forward<H>(handler)({std::forward<Args>(args)...});
}
template <typename H, typename T,
requires_conditions<is_invocable_with_applicable_as_list<H, T>> = true>
constexpr auto invoke_handler_internal(priority_tag<1>, H&& handler, T&& applicable)
-> decltype(invoke_with_applicable_as_list(std::forward<H>(handler),
std::forward<T>(applicable))) {
return invoke_with_applicable_as_list(std::forward<H>(handler), std::forward<T>(applicable));
}
template <typename H, typename... Args>
constexpr decltype(auto) invoke_handler_internal(priority_tag<0>, H&& handler, Args&&... args) {
// H wants to ignore all args
return cpp20::invoke(std::forward<H>(handler));
}
template <typename H, typename... Args,
requires_conditions<is_invocable_handler_internal<H, Args...>> = true>
constexpr decltype(auto) invoke_handler_internal(H&& handler, Args&&... args) {
return invoke_handler_internal(priority_tag<4>(), std::forward<H>(handler),
std::forward<Args>(args)...);
}
template <typename H, typename... Args,
requires_conditions<is_invocable_handler_internal<H, Args...>> = true>
constexpr decltype(auto) invoke_without_context(H&& handler, ::fasync::context&, Args&&... args) {
return invoke_handler_internal(std::forward<H>(handler), std::forward<Args>(args)...);
}
template <typename H, typename... Args,
requires_conditions<
cpp17::negation<first_param_is_generic_t<H, Args...>>,
is_invocable_handler_internal<decltype(bind_refs(std::declval<H>(),
std::declval<::fasync::context&>())),
Args...>> = true>
constexpr decltype(auto) invoke_with_context(H&& handler, ::fasync::context& context,
Args&&... args) {
return invoke_handler_internal(bind_refs(std::forward<H>(handler), context),
std::forward<Args>(args)...);
}
template <typename H, typename... Args,
requires_conditions<
cpp17::negation<first_param_is_generic_t<H, Args...>>,
is_invocable_handler_internal<decltype(bind_refs(std::declval<H>(),
std::declval<::fasync::context&>())),
Args...>> = true>
constexpr decltype(auto) invoke_with_context(H&& handler, const ::fasync::context& context,
Args&&... args) {
return invoke_handler_internal(bind_refs(std::forward<H>(handler), context),
std::forward<Args>(args)...);
}
} // namespace internal
namespace internal {
////// BEGIN CONCEPTS EQUIVALENTS /////////
template <typename H, typename... Args>
constexpr auto without_context_impl(std::nullptr_t)
-> decltype(invoke_without_context(std::declval<H>(), std::declval<Args>()...),
std::true_type());
template <typename H, typename... Args>
constexpr std::false_type without_context_impl(...);
template <typename H, typename... Args>
struct is_invocable_handler_internal_without_context
: decltype(without_context_impl<H, Args...>(nullptr)) {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_handler_internal_without_context_v =
is_invocable_handler_internal_without_context<H, Args...>::value;
template <typename H, typename... Args>
constexpr auto with_context_impl(std::nullptr_t)
-> decltype(invoke_with_context(std::declval<H>(), std::declval<Args>()...), std::true_type());
template <typename H, typename... Args>
constexpr std::false_type with_context_impl(...);
template <typename H, typename... Args>
struct is_invocable_handler_internal_with_context
: decltype(with_context_impl<H, Args...>(nullptr)) {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_handler_internal_with_context_v =
is_invocable_handler_internal_with_context<H, Args...>::value;
// TODO(schottm): it might not be useful to define it like this with the context shoved in; what if
// your Args already has a context?
template <typename H, typename... Args>
struct is_invocable_handler
: cpp17::disjunction<
is_invocable_handler_internal_without_context<H, ::fasync::context&, Args...>,
is_invocable_handler_internal_with_context<H, ::fasync::context&, Args...>>::type {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_invocable_handler_v =
is_invocable_handler<H, Args...>::value;
////// END CONCEPTS EQUIVALENTS /////////
template <typename H, typename... Args,
requires_conditions<is_invocable_handler_internal_without_context<H, Args...>> = true>
constexpr decltype(auto) invoke_handler_tag(priority_tag<2>, H&& handler, Args&&... args) {
return invoke_without_context(std::forward<H>(handler), std::forward<Args>(args)...);
}
template <
typename H, typename... Args,
requires_conditions<cpp17::negation<is_invocable_handler_internal_without_context<H, Args...>>,
is_invocable_handler_internal_with_context<H, Args...>> = true>
constexpr decltype(auto) invoke_handler_tag(priority_tag<1>, H&& handler, Args&&... args) {
return invoke_with_context(std::forward<H>(handler), std::forward<Args>(args)...);
}
template <typename H, typename... Args>
constexpr decltype(auto) invoke_handler_tag(priority_tag<0>, H&& handler, Args&&... args) {
return invoke_compile_error(std::forward<H>(handler), std::forward<Args>(args)...);
}
template <typename H, typename... Args>
constexpr decltype(auto) invoke_handler(H&& handler, Args&&... args) {
return invoke_handler_tag(priority_tag<2>(), std::forward<H>(handler),
std::forward<Args>(args)...);
}
template <typename H, typename... Args,
requires_conditions<is_invocable_handler<H, Args...>> = true>
constexpr auto invoke_handler_type_impl()
-> decltype(invoke_handler(std::declval<H>(), std::declval<::fasync::context&>(),
std::declval<Args>()...));
template <typename Enable, typename H, typename... Args>
struct invoke_handler_type {};
template <typename H, typename... Args>
struct invoke_handler_type<cpp17::void_t<decltype(invoke_handler_type_impl<H, Args...>())>, H,
Args...>
: cpp20::type_identity<decltype(invoke_handler_type_impl<H, Args...>())> {};
template <typename H, typename... Args>
using invoke_handler_t = typename invoke_handler_type<void, H, Args...>::type;
template <typename Enable, typename H, typename... Args>
struct handler_returns_void_for_impl : std::false_type {};
template <typename H, typename... Args>
struct handler_returns_void_for_impl<cpp17::void_t<invoke_handler_t<H, Args...>>, H, Args...>
: std::is_void<invoke_handler_t<H, Args...>>::type {};
// Metafunction for determining whether a callable returns void given the provided argument types.
template <typename H, typename... Args>
struct handler_returns_void_for : handler_returns_void_for_impl<void, H, Args...>::type {};
template <typename H, typename... Args>
LIB_FASYNC_INLINE_CONSTANT constexpr bool handler_returns_void_for_v =
handler_returns_void_for<H, Args...>::value;
template <typename F>
class poller;
template <typename T>
struct promote_return_type {
using type = T;
};
template <typename... Ts>
struct promote_return_type<::fitx::success<Ts...>> {
using type = ::fitx::result<fitx::failed, Ts...>;
};
template <typename E>
struct promote_return_type<::fitx::error<E>> {
using type = ::fitx::result<E>;
};
template <>
struct promote_return_type<::fitx::failed> {
using type = ::fitx::result<::fitx::failed>;
};
template <typename... Ts>
struct promote_return_type<::fasync::ready<::fitx::success<Ts...>>> {
using type = ::fasync::try_poll<fitx::failed, Ts...>;
};
template <typename E>
struct promote_return_type<::fasync::ready<::fitx::error<E>>> {
using type = ::fasync::try_poll<E>;
};
template <>
struct promote_return_type<::fasync::ready<::fitx::failed>> {
using type = ::fasync::try_poll<::fitx::failed>;
};
template <typename T>
using promote_return_type_t = typename promote_return_type<cpp20::remove_cvref_t<T>>::type;
template <typename R, typename T>
struct merge_ok_result {};
// TODO(schottm): necessary for returning futures?
template <typename E, typename... Ts, typename U>
struct merge_ok_result<::fitx::result<E, Ts...>, U> {
using type = ::fitx::result<E, U>;
};
template <typename E, typename... Ts>
struct merge_ok_result<::fitx::result<E, Ts...>, ::fitx::failed> {
using type = ::fitx::result<::fitx::failed, Ts...>;
};
template <typename E, typename... Ts, typename F>
struct merge_ok_result<::fitx::result<E, Ts...>, ::fitx::error<F>> {
using type = ::fitx::result<F, Ts...>;
};
template <typename E, typename... Ts, typename... Us>
struct merge_ok_result<::fitx::result<E, Ts...>, ::fitx::success<Us...>> {
using type = ::fitx::result<E, Us...>;
};
// TODO(schottm): is this really what we want?
// Probably not; make one merge_result and ditch the ok/error distinction?
template <typename E, typename... Ts, typename F, typename... Us>
struct merge_ok_result<::fitx::result<E, Ts...>, ::fitx::result<F, Us...>> {
using type = ::fitx::result<E, Us...>;
};
template <typename E, typename... Ts>
struct merge_ok_result<::fitx::result<E, Ts...>, void> {
using type = ::fitx::result<E>;
};
template <typename R, typename T>
using merge_ok_result_t =
typename merge_ok_result<cpp20::remove_cvref_t<R>, cpp20::remove_cvref_t<T>>::type;
template <typename R, typename E>
struct merge_error_result {};
template <typename E, typename... Ts, typename F>
struct merge_error_result<::fitx::result<E, Ts...>, F> {
using type = ::fitx::result<F, Ts...>;
};
template <typename E, typename... Ts>
struct merge_error_result<::fitx::result<E, Ts...>, ::fitx::failed> {
using type = ::fitx::result<::fitx::failed, Ts...>;
};
template <typename E, typename... Ts, typename F>
struct merge_error_result<::fitx::result<E, Ts...>, ::fitx::error<F>> {
using type = ::fitx::result<F, Ts...>;
};
template <typename E, typename... Ts, typename... Us>
struct merge_error_result<::fitx::result<E, Ts...>, ::fitx::success<Us...>> {
using type = ::fitx::result<E, Us...>;
};
template <typename E, typename... Ts, typename F, typename... Us>
struct merge_error_result<::fitx::result<E, Ts...>, ::fitx::result<F, Us...>> {
using type = ::fitx::result<F, Ts...>;
};
template <typename E, typename... Ts>
struct merge_error_result<::fitx::result<E, Ts...>, void> {
using type = ::fitx::result<E>;
};
template <typename R, typename E>
using merge_error_result_t =
typename merge_error_result<cpp20::remove_cvref_t<R>, cpp20::remove_cvref_t<E>>::type;
// Arbitrary types are neither success nor error.
template <typename R, typename T>
struct merge_result {
using type = T;
};
template <typename R>
struct merge_result<R, ::fitx::failed> {
using type = merge_error_result_t<R, ::fitx::failed>;
};
template <typename R, typename E>
struct merge_result<R, ::fitx::error<E>> {
using type = merge_error_result_t<R, ::fitx::error<E>>;
};
template <typename R, typename... Ts>
struct merge_result<R, ::fitx::success<Ts...>> {
using type = merge_ok_result_t<R, ::fitx::success<Ts...>>;
};
template <typename R, typename T>
using merge_result_t = typename merge_result<R, T>::type;
////////// FORWARD_TO_*
// These |forward_to_*_result()| functions take incomplete result types like |fitx::success| and
// |fitx::error| and return a result appropriately derived from the given result type.
template <typename R, typename T, requires_conditions<is_future<T>> = true>
constexpr merge_ok_result_t<R, T> forward_to_ok_result(T&& value) {
return merge_ok_result_t<R, T>(::fitx::ok(std::forward<T>(value)));
}
template <typename R>
constexpr merge_ok_result_t<R, ::fitx::failed> forward_to_ok_result(::fitx::failed) {
return merge_ok_result_t<R, ::fitx::failed>(::fitx::failed());
}
template <typename R, typename E>
constexpr merge_ok_result_t<R, ::fitx::error<E>> forward_to_ok_result(::fitx::error<E>&& error) {
return merge_ok_result_t<R, ::fitx::error<E>>(std::forward<::fitx::error<E>>(error));
}
template <typename R, typename... Ts>
constexpr merge_ok_result_t<R, ::fitx::success<Ts...>> forward_to_ok_result(
::fitx::success<Ts...>&& success) {
return merge_ok_result_t<R, ::fitx::success<Ts...>>(
std::forward<::fitx::success<Ts...>>(success));
}
template <typename R, typename E, typename... Ts>
constexpr merge_ok_result_t<R, ::fitx::result<E, Ts...>> forward_to_ok_result(
::fitx::result<E, Ts...>&& result) {
return merge_ok_result_t<R, ::fitx::result<E, Ts...>>(
std::forward<::fitx::result<E, Ts...>>(result));
}
template <typename R, typename T, requires_conditions<is_future<T>> = true>
constexpr merge_error_result_t<R, T> forward_to_error_result(T&& value) {
return merge_error_result_t<R, T>(::fitx::error<T>(std::forward<T>(value)));
}
template <typename R>
constexpr merge_error_result_t<R, ::fitx::failed> forward_to_error_result(::fitx::failed) {
return merge_error_result_t<R, ::fitx::failed>(::fitx::failed());
}
template <typename R, typename E>
constexpr merge_error_result_t<R, ::fitx::error<E>> forward_to_error_result(
::fitx::error<E>&& error) {
return merge_error_result_t<R, ::fitx::error<E>>(std::forward<::fitx::error<E>>(error));
}
template <typename R, typename... Ts>
constexpr merge_error_result_t<R, ::fitx::success<Ts...>> forward_to_error_result(
::fitx::success<Ts...>&& success) {
return merge_error_result_t<R, ::fitx::success<Ts...>>(
std::forward<::fitx::success<Ts...>>(success));
}
template <typename R, typename E, typename... Ts>
constexpr decltype(auto) forward_to_error_result(::fitx::result<E, Ts...>&& result) {
return std::forward<::fitx::result<E, Ts...>>(result);
}
template <typename R, typename T>
constexpr merge_result_t<R, T> forward_to_result(T&& value) {
return merge_result_t<R, T>(std::forward<T>(value));
}
////////// FORWARD_TO_*
/////////// HANDLE_RESULT //////////////
template <typename H, typename R, requires_conditions<is_result<R>> = true>
using handle_result_t = merge_result_t<R, invoke_handler_t<H, R>>;
template <typename H, typename R,
requires_conditions<cpp17::negation<handler_returns_void_for<H, R>>> = true>
constexpr handle_result_t<H, R> handle_result(H&& handler, ::fasync::context& context, R&& result) {
return forward_to_result<R>(
invoke_handler(std::forward<H>(handler), context, std::forward<R>(result)));
}
template <typename H, typename R, requires_conditions<handler_returns_void_for<H, R>> = true>
constexpr handle_result_t<H, R> handle_result(H&& handler, ::fasync::context& context, R&& result) {
invoke_handler(std::forward<H>(handler), context, std::forward<R>(result));
return forward_to_result<R>(::fitx::ok());
}
/////////// HANDLE_RESULT //////////////
////////// HANDLE_OUTPUT //////////////
template <typename H, typename... Ts>
struct handle_output_type {
using type = promote_return_type_t<invoke_handler_t<H, Ts...>>;
};
// TODO(schottm): is_result and matching on result have different semantics
template <typename H, typename E, typename... Ts>
struct handle_output_type<H, ::fitx::result<E, Ts...>> {
using type = handle_result_t<H, ::fitx::result<E, Ts...>>;
};
template <typename H, typename... Ts>
using handle_output_t = typename handle_output_type<H, Ts...>::type;
template <typename H>
constexpr handle_output_t<H> handle_output(H&& handler, ::fasync::context& context) {
return invoke_handler(std::forward<H>(handler), context);
}
template <typename H, typename T, requires_conditions<cpp17::negation<is_result<T>>> = true>
constexpr handle_output_t<H, T> handle_output(H&& handler, ::fasync::context& context, T&& value) {
return invoke_handler(std::forward<H>(handler), context, std::forward<T>(value));
}
template <typename H, typename R, requires_conditions<is_result<R>> = true>
constexpr handle_output_t<H, R> handle_output(H&& handler, ::fasync::context& context, R&& result) {
return handle_result(std::forward<H>(handler), context, std::forward<R>(result));
}
////////// HANDLE_OUTPUT //////////////
////////// HANDLE_VALUE //////////////
template <typename H, typename R, requires_conditions<is_result<R>> = true>
using handle_ok_result_t = merge_ok_result_t<R, invoke_handler_t<H, R>>;
template <typename H, typename R,
requires_conditions<is_result<R>, cpp17::negation<handler_returns_void_for<H, R>>> = true>
constexpr handle_ok_result_t<H, R> handle_ok_result(H&& handler, ::fasync::context& context,
R&& result) {
return forward_to_ok_result<R>(
invoke_handler(std::forward<H>(handler), context, std::forward<R>(result)));
}
template <typename H, typename R,
requires_conditions<is_result<R>, handler_returns_void_for<H, R>> = true>
constexpr handle_ok_result_t<H, R> handle_ok_result(H&& handler, ::fasync::context& context,
R&& result) {
invoke_handler(std::forward<H>(handler), context, std::forward<R>(result));
return forward_to_ok_result<R>(::fitx::ok());
}
template <typename H, typename... Ts>
struct handle_value_type {
using type = invoke_handler_t<H, Ts...>;
};
template <typename H, typename E, typename... Ts>
struct handle_value_type<H, ::fitx::result<E, Ts...>> {
using type = handle_ok_result_t<H, ::fitx::result<E, Ts...>>;
};
template <typename H, typename... Ts>
using handle_value_t = typename handle_value_type<H, Ts...>::type;
template <typename H>
constexpr invoke_handler_t<H> handle_value(H&& handler, ::fasync::context& context) {
return invoke_handler(std::forward<H>(handler), context);
}
template <typename H, typename T, requires_conditions<cpp17::negation<is_result<T>>> = true>
constexpr handle_value_t<H, T> handle_value(H&& handler, ::fasync::context& context, T&& value) {
return invoke_handler(std::forward<H>(handler), context, std::forward<T>(value));
}
template <typename H, typename R, requires_conditions<is_result<R>> = true>
constexpr handle_value_t<H, R> handle_value(H&& handler, ::fasync::context& context, R&& result) {
return handle_ok_result(std::forward<H>(handler), context, std::forward<R>(result));
}
////////// HANDLE_VALUE //////////////
////////// HANDLE_ERROR //////////////
template <typename H, typename R, requires_conditions<is_result<R>> = true>
using handle_error_result_t = merge_error_result_t<R, invoke_handler_t<H, R>>;
template <typename H, typename... Ts>
struct handle_error_type {
using type = invoke_handler_t<H, Ts...>;
};
template <typename H, typename E, typename... Ts>
struct handle_error_type<H, ::fitx::result<E, Ts...>> {
using type = handle_error_result_t<H, ::fitx::result<E, Ts...>>;
};
template <typename H, typename... Ts>
using handle_error_t = typename handle_error_type<H, Ts...>::type;
template <typename H, typename R,
requires_conditions<cpp17::negation<handler_returns_void_for<H, R>>> = true>
constexpr handle_error_result_t<H, R> handle_error_result(H&& handler, ::fasync::context& context,
R&& result) {
return forward_to_error_result<R>(
invoke_handler(std::forward<H>(handler), context, std::forward<R>(result)));
}
// TODO(schottm): should this be ok instead? or not allowed? or just forward the previous result?
template <typename H, typename R, requires_conditions<handler_returns_void_for<H, R>> = true>
constexpr handle_error_result_t<H, R> handle_error_result(H&& handler, ::fasync::context& context,
R&& result) {
invoke_handler(std::forward<H>(handler), context, std::forward<R>(result));
return forward_to_error_result<R>(::fitx::ok());
}
template <typename H, typename T, requires_conditions<cpp17::negation<is_result<T>>> = true>
constexpr handle_error_t<H, T> handle_error(H&& handler, ::fasync::context& context, T&& value) {
return invoke_handler(std::forward<H>(handler), context, std::forward<T>(value));
}
template <typename H, typename R, requires_conditions<is_result<R>> = true>
constexpr handle_error_t<H, R> handle_error(H&& handler, ::fasync::context& context, R&& result) {
return handle_error_result(std::forward<H>(handler), context, std::forward<R>(result));
}
////////// HANDLE_ERROR //////////////
// Note: this bypasses the reason we have a separate fasync::ready in the first place and should
// never be used outside these specific internal functions.
inline constexpr ::fasync::poll<> to_poll(::fasync::pending pending) { return pending; }
template <typename... Ts>
constexpr ::fasync::poll<Ts...> to_poll(::fasync::ready<Ts...>&& ready) {
return std::forward<::fasync::ready<Ts...>>(ready);
}
template <typename... Ts>
constexpr ::fasync::poll<Ts...> to_poll(::fasync::poll<Ts...>&& poll) {
return std::forward<::fasync::poll<Ts...>>(poll);
}
// TODO: is this necessary? if not, is this entire overload set necessary?
template <typename T>
constexpr ::fasync::poll<T> to_poll(T&& value) {
return ::fasync::done(std::forward<T>(value));
}
//////////// HANDLE_MAP ///////////////
template <typename H, typename F,
requires_conditions<is_void_future<F>, handler_returns_void_for<H>> = true>
constexpr ::fasync::poll<> handle_map(H&& handler, ::fasync::context& context, poller<F>& poller) {
handle_output(std::forward<H>(handler), context);
return ::fasync::done();
}
template <
typename H, typename F,
requires_conditions<is_void_future<F>, cpp17::negation<handler_returns_void_for<H>>> = true>
constexpr auto handle_map(H&& handler, ::fasync::context& context, poller<F>& poller) {
return to_poll(handle_output(std::forward<H>(handler), context));
}
template <typename H, typename F,
requires_conditions<cpp17::negation<is_void_future<F>>,
handler_returns_void_for<H, future_output_t<F>&>> = true>
constexpr ::fasync::poll<> handle_map(H&& handler, ::fasync::context& context, poller<F>& poller) {
invoke_handler(std::forward<H>(handler), context, poller.output());
return ::fasync::done();
}
template <
typename H, typename F,
requires_conditions<cpp17::negation<is_void_future<F>>,
cpp17::negation<handler_returns_void_for<H, future_output_t<F>&>>> = true>
constexpr auto handle_map(H&& handler, ::fasync::context& context, poller<F>& poller) {
return to_poll(handle_output(std::forward<H>(handler), context, poller.output()));
}
template <typename H, typename F>
using handle_map_t = decltype(handle_map(std::declval<H>(), std::declval<::fasync::context&>(),
std::declval<poller<F>&>()));
//////////// HANDLE_MAP ///////////////
//////////// HANDLE_MAP_OK ///////////////
template <typename H, typename F,
requires_conditions<cpp17::negation<is_value_try_future<F>>,
handler_returns_void_for<H>> = true>
constexpr ::fasync::future_poll_t<F> handle_map_ok(priority_tag<9>, H&& handler,
::fasync::context& context, poller<F>& poller) {
invoke_handler(std::forward<H>(handler), context);
return ::fasync::done(::fitx::ok());
}
template <typename H, typename F,
requires_conditions<cpp17::negation<is_value_try_future<F>>,
cpp17::negation<handler_returns_void_for<H>>> = true>
constexpr auto handle_map_ok(priority_tag<8>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return to_poll(::fasync::done(forward_to_ok_result<::fasync::future_result_t<F>>(
handle_value(std::forward<H>(handler), context))));
}
template <typename H, typename F,
requires_conditions<cpp17::negation<is_value_try_future<F>>,
is_poll<invoke_handler_t<H, ::fasync::future_value_t<F>&>>> = true>
constexpr auto handle_map_ok(priority_tag<7>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return handle_value(std::forward<H>(handler), context);
}
template <typename H, typename F,
requires_conditions<cpp17::negation<is_value_try_future<F>>,
is_ready<invoke_handler_t<H, ::fasync::future_value_t<F>&>>> = true>
constexpr auto handle_map_ok(priority_tag<6>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return to_poll(handle_value(std::forward<H>(handler), context));
}
template <typename H, typename F,
requires_conditions<cpp17::negation<is_value_try_future<F>>,
is_pending<invoke_handler_t<H, ::fasync::future_value_t<F>&>>> = true>
constexpr auto handle_map_ok(priority_tag<5>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return ::fasync::future_poll_t<F>(invoke_handler(std::forward<H>(handler), context));
}
template <typename H, typename F,
requires_conditions<is_value_try_future<F>,
handler_returns_void_for<H, ::fasync::future_value_t<F>&>> = true>
constexpr auto handle_map_ok(priority_tag<4>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
invoke_handler(std::forward<H>(handler), context, poller.output().value());
return ::fasync::try_poll<::fasync::future_error_t<F>>(::fasync::done(::fitx::ok()));
}
template <typename H, typename F,
requires_conditions<is_value_try_future<F>,
is_poll<invoke_handler_t<H, ::fasync::future_value_t<F>&>>> = true>
constexpr auto handle_map_ok(priority_tag<3>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return handle_value(std::forward<H>(handler), context, poller.output().value());
}
template <typename H, typename F,
requires_conditions<is_value_try_future<F>,
is_ready<invoke_handler_t<H, ::fasync::future_value_t<F>&>>> = true>
constexpr auto handle_map_ok(priority_tag<2>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return to_poll(handle_value(std::forward<H>(handler), context, poller.output().value()));
}
template <typename H, typename F,
requires_conditions<is_value_try_future<F>,
is_pending<invoke_handler_t<H, ::fasync::future_value_t<F>&>>> = true>
constexpr auto handle_map_ok(priority_tag<1>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return ::fasync::future_poll_t<F>(
invoke_handler(std::forward<H>(handler), context, poller.output().value()));
}
template <typename H, typename F, typename R = invoke_handler_t<H, ::fasync::future_value_t<F>&>,
requires_conditions<is_value_try_future<F>, cpp17::negation<std::is_void<R>>,
cpp17::negation<is_poll<R>>> = true>
constexpr auto handle_map_ok(priority_tag<0>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return to_poll(::fasync::done(forward_to_ok_result<::fasync::future_result_t<F>>(
handle_value(std::forward<H>(handler), context, poller.output().value()))));
}
template <typename H, typename F>
constexpr auto handle_map_ok(H&& handler, ::fasync::context& context, poller<F>& poller) {
return handle_map_ok(priority_tag<9>(), std::forward<H>(handler), context, poller);
}
template <typename H, typename F>
using handle_map_ok_t = decltype(handle_map_ok(
std::declval<H>(), std::declval<::fasync::context&>(), std::declval<poller<F>&>()));
//////////// HANDLE_MAP_OK ///////////////
//////////// HANDLE_MAP_ERROR ///////////////
template <typename H, typename F,
requires_conditions<handler_returns_void_for<H, ::fasync::future_error_t<F>&>> = true>
constexpr auto handle_map_error(priority_tag<4>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
static_assert(!is_value_try_future_v<F>,
"Returning void from an error handler is only supported when the previous result "
"had no |value_type|.");
invoke_handler(std::forward<H>(handler), context, poller.output().error_value());
return ::fasync::future_poll_t<F>(::fasync::done(::fitx::ok()));
}
template <typename H, typename F,
requires_conditions<is_poll<invoke_handler_t<H, ::fasync::future_error_t<F>&>>> = true>
constexpr auto handle_map_error(priority_tag<3>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return handle_error(std::forward<H>(handler), context, poller.output().error_value());
}
template <typename H, typename F,
requires_conditions<is_ready<invoke_handler_t<H, ::fasync::future_error_t<F>&>>> = true>
constexpr auto handle_map_error(priority_tag<2>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return to_poll(handle_error(std::forward<H>(handler), context, poller.output().error_value()));
}
template <typename H, typename F,
requires_conditions<is_pending<invoke_handler_t<H, ::fasync::future_error_t<F>&>>> = true>
constexpr auto handle_map_error(priority_tag<1>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return ::fasync::future_poll_t<F>(
invoke_handler(std::forward<H>(handler), context, poller.output().error_value()));
}
template <typename H, typename F>
constexpr auto handle_map_error(priority_tag<0>, H&& handler, ::fasync::context& context,
poller<F>& poller) {
return to_poll(::fasync::done(forward_to_error_result<::fasync::future_result_t<F>>(
handle_error(std::forward<H>(handler), context, poller.output().error_value()))));
}
template <typename H, typename F>
constexpr auto handle_map_error(H&& handler, ::fasync::context& context, poller<F>& poller) {
return handle_map_error(priority_tag<4>(), std::forward<H>(handler), context, poller);
}
template <typename H, typename F>
using handle_map_error_t = decltype(handle_map_error(
std::declval<H>(), std::declval<::fasync::context&>(), std::declval<poller<F>&>()));
//////////// HANDLE_MAP_ERROR ///////////////
template <typename H, typename F, typename = bool>
struct handler_output {
using type = decltype(::fasync::internal::invoke_handler(
std::declval<H>(), std::declval<::fasync::context&>(),
std::declval<::fasync::future_output_t<F>&>()));
};
template <typename H, typename F>
struct handler_output<H, F, requires_conditions<is_void_future<F>>> {
using type = decltype(::fasync::internal::invoke_handler(std::declval<H>(),
std::declval<::fasync::context&>()));
};
// Determines the output of a handler type H chained onto a future type F.
template <typename H, typename F, requires_conditions<is_future<F>> = true>
using handler_output_t = typename handler_output<H, F>::type;
template <typename H, typename F, requires_conditions<is_try_future<F>> = true>
using value_handler_result_t =
::fitx::result<future_error_t<F>, decltype(::fasync::internal::invoke_handler(
std::declval<H>(), std::declval<::fasync::context&>(),
std::declval<::fasync::future_value_t<F>>()))>;
template <typename H, typename F, requires_conditions<is_try_future<F>> = true>
using error_handler_result_t =
::fitx::result<decltype(::fasync::internal::invoke_handler(
std::declval<H>(), std::declval<::fasync::context&>(),
std::declval<::fasync::future_error_t<F>>())),
::fasync::future_value_t<F>>;
// |pending_future|
//
// A future that always returns pending. The template parameters are used for
// the returned |fasync::poll<Ts...>| type.
template <typename...>
class pending_future;
template <>
class LIB_FASYNC_NODISCARD pending_future<> final {
public:
// Same rules as for value_future even though we don't have an actual value
constexpr pending_future() = default;
constexpr pending_future(const pending_future&) = default;
constexpr pending_future& operator=(const pending_future&) = default;
constexpr pending_future(pending_future&&) = default;
constexpr pending_future& operator=(pending_future&&) = default;
constexpr ::fasync::poll<> operator()(::fasync::context&) const { return ::fasync::pending(); }
};
template <typename T>
class LIB_FASYNC_NODISCARD pending_future<T> final {
public:
// Same rules as for value_future even though we don't have an actual value
constexpr pending_future() = default;
constexpr pending_future(pending_future<>) {}
template <typename U, requires_conditions<std::is_constructible<T, U>> = true>
constexpr pending_future(pending_future<U>) {}
constexpr pending_future(const pending_future&) = default;
constexpr pending_future& operator=(const pending_future&) = default;
constexpr pending_future(pending_future&&) = default;
constexpr pending_future& operator=(pending_future&&) = default;
constexpr ::fasync::poll<T> operator()(::fasync::context&) const { return ::fasync::pending(); }
};
#if LIB_FASYNC_HAS_CPP_FEATURE(deduction_guides)
pending_future()->pending_future<>;
template <typename T>
pending_future(pending_future<T>&&) -> pending_future<T>;
#endif
// A |pending_future| for |fitx::result<E, Ts...>|.
template <typename E, typename... Ts>
using pending_try_future = pending_future<::fitx::result<E, Ts...>>;
// |value_future| is a future that always resolves with a single value.
template <typename T>
class LIB_FASYNC_NODISCARD LIB_FASYNC_OWNER_OF(T) value_future final {
using value_type = std::decay_t<T>;
public:
template <typename... Args,
requires_conditions<std::is_constructible<value_type, Args...>> = true>
explicit constexpr value_future(Args&&... args) : value_(std::forward<Args>(args)...) {}
template <typename U, requires_conditions<std::is_constructible<value_type, U>> = true>
constexpr value_future(value_future<U>&& other) : value_(std::forward<U>(other.value_)) {}
constexpr value_future(const value_future&) = default;
constexpr value_future& operator=(const value_future&) = default;
constexpr value_future(value_future&&) = default;
constexpr value_future& operator=(value_future&&) = default;
constexpr ::fasync::poll<value_type> operator()(::fasync::context&) {
return ::fasync::done(std::move(value_));
}
private:
value_type value_;
};
#if LIB_FASYNC_HAS_CPP_FEATURE(deduction_guides)
template <typename T>
value_future(T&&) -> value_future<T>;
template <typename T>
value_future(value_future<T>&&) -> value_future<T>;
#endif
// These next futures are variants of |value_future| for |fitx::result| and related types.
template <typename E, typename... Ts>
using result_future = value_future<::fitx::result<std::decay_t<E>, std::decay_t<Ts>...>>;
template <typename... Ts>
using ok_future = result_future<::fitx::failed, std::decay_t<Ts>...>;
template <typename E>
using error_future = result_future<std::decay_t<E>>;
using failed_future = result_future<::fitx::failed>;
// Describes the status of a poller.
enum class poller_state : uint8_t {
// The poller holds a future that may eventually produce an output but
// it currently doesn't have an output. The poller's future must be
// invoked in order to make progress from this state.
pending,
// The poller has an output ready.
ready,
};
// |fasync::poller|
//
// Holds onto a future until it has completed, then provides access to its
// output.
//
// SYNOPSIS
//
// |F| is the type of future the poller acts upon.
// Can be accessed via |typename poller<F>::future_type| or |poller_future_t<P>|.
//
// |typename poller<F>::output_type| is the type of output produced by the future (and thus poller).
// Can also be accessed via |poller_output_t<P>|.
//
// THEORY OF OPERATION
//
// A poller has a single owner who is responsible for setting its future
// or output and driving its execution. Unlike |fasync::future|, a poller retains
// the output produced by completion of its asynchronous task. Output retention
// eases the implementation of combined tasks that need to await the results
// of other tasks before proceeding.
//
// A poller can be in one of two states, depending on whether it holds...
// - an output: |poller_state::ready|
// - a future that may eventually produce a result: |poller_state::pending|
//
// On its own, a poller is "inert"; it only makes progress in response to
// actions taken by its owner. The state of the poller never changes
// spontaneously or concurrently.
//
// When the poller's state is |poller_state::pending|, its owner is
// responsible for calling the poller's |operator()| to invoke the future.
// If the future completes and returns a result, the poller will transition
// to the ready state. The future itself will
// then be destroyed since it has fulfilled its purpose.
//
// When the poller's state is |poller_state::ready|, its owner is responsible
// for consuming the stored value using |output()| or |take_output()|.
//
// See also |fasync::future| for more information about promises and their
// execution.
template <typename F>
class LIB_FASYNC_NODISCARD LIB_FASYNC_OWNER poller final {
static_assert(is_future_v<F>, "");
public:
// The type of future held by the poller.
using future_type = std::decay_t<F>;
// The future's output type.
using output_type = std::decay_t<::fasync::future_output_t<F>>;
// Creates a poller and assigns a future to compute its output.
// The poller enters the pending state.
template <typename G, requires_conditions<std::is_constructible<future_type, G>> = true>
explicit constexpr poller(G&& future)
: state_(cpp17::in_place_index<0>, std::forward<G>(future)) {}
// Creates a poller and assigns its output.
// The poller enters the ready state.
template <typename T = output_type,
requires_conditions<std::is_constructible<output_type, T>> = true>
explicit constexpr poller(T&& output)
: state_(cpp17::in_place_index<1>, std::forward<T>(output)) {}
constexpr poller(const poller&) = delete;
constexpr poller& operator=(const poller&) = delete;
constexpr poller(poller&& other) = default;
constexpr poller& operator=(poller&&) = default;
// Destroys the poller, releasing its future and output (if any).
~poller() = default;
// Returns the state of the poller: pending or ready.
constexpr poller_state state() const {
switch (state_.index()) {
case 0:
return poller_state::pending;
case 1:
return poller_state::ready;
}
__builtin_unreachable();
}
// Returns true if the poller's state is |fasync::poller_state::pending|:
// it does not hold an output yet but it does hold a future that can be invoked
// to make progress towards obtaining an output.
constexpr bool is_pending() const { return state() == poller_state::pending; }
// Returns true if the poller's state is |fasync::poller_state::ready|.
constexpr bool is_ready() const { return state() == poller_state::ready; }
// Evaluates the poller and returns true if its output is ready.
//
// If the future completes and returns an output, the poller will transition
// to the ready state. The future itself will
// then be destroyed since it has fulfilled its purpose.
constexpr bool operator()(fasync::context& context) {
switch (state_.index()) {
case 0: {
::fasync::future_poll_t<future_type> poll = cpp20::invoke(cpp17::get<0>(state_), context);
if (poll.is_pending()) {
return false;
}
emplace_output(std::move(poll));
return true;
}
case 1:
return true;
}
__builtin_unreachable();
}
// Gets a reference to the poller's future.
// Asserts that the poller's state is |fasync::poller_state::pending|.
constexpr future_type& future() {
return const_cast<future_type&>(cpp17::as_const(*this).future());
}
// TODO(schottm): do other ref qualifiers
constexpr const future_type& future() const {
assert(is_pending());
return cpp17::get<0>(state_);
}
// Takes the poller's future, leaving it in an empty state.
// Asserts that the poller's state is |fasync::poller_state::pending|.
constexpr future_type take_future() {
assert(is_pending());
return std::move(cpp17::get<0>(state_));
}
// Gets a reference to the poller's output.
// Asserts that the poller's state is |fasync::poller_state::ready|.
template <typename T = output_type, requires_conditions<cpp17::negation<std::is_void<T>>> = true>
constexpr std::add_lvalue_reference_t<output_type> output() {
return const_cast<std::add_lvalue_reference_t<output_type>>(cpp17::as_const(*this).output());
}
template <typename T = output_type, requires_conditions<cpp17::negation<std::is_void<T>>> = true>
constexpr std::add_lvalue_reference_t<const output_type> output() const {
assert(is_ready());
return cpp17::get<1>(state_);
}
// Takes the poller's output, leaving it in an empty state.
// Asserts that the poller's state is |fasync::poller_state::ready|.
constexpr output_type take_output() {
assert(is_ready());
return std::move(cpp17::get<1>(state_));
}
// Assigns a future to compute the poller's output.
// The poller enters the pending state.
constexpr poller& operator=(future_type&& future) {
state_.emplace<0>(std::move(future));
return *this;
}
// Assigns the poller's output.
// The poller enters the ready state.
//
// NOTE: the substitution failure for void&& is sufficient to guard against that usage.
template <typename T = output_type>
constexpr poller& operator=(T&& output) {
state_.emplace<1>(std::move(output));
return *this;
}
// Swaps the pollers' contents.
constexpr void swap(poller& other) {
using std::swap;
swap(state_, other.state_);
}
private:
template <typename P, requires_conditions<is_void_poll<P>> = true>
void emplace_output(P&& poll) {
state_.template emplace<1>(cpp17::monostate());
}
template <typename P, requires_conditions<cpp17::negation<is_void_poll<P>>> = true>
void emplace_output(P&& poll) {
state_.template emplace<1>(std::forward<P>(poll).output());
}
template <typename T>
using real_or_monostate = std::conditional_t<cpp17::is_void_v<T>, cpp17::monostate, T>;
cpp17::variant<future_type, real_or_monostate<output_type>> state_;
};
template <typename F>
using poller_future_t = typename poller<F>::future_type;
template <typename F>
using poller_output_t = typename poller<F>::output_type;
// The continuation produced by |fasync::map()|.
template <typename F, typename H>
class LIB_FASYNC_OWNER map_future final {
static_assert(is_future_v<F>, "");
public:
template <typename G, typename I, requires_conditions<std::is_constructible<poller<F>, G>> = true>
constexpr map_future(G&& future, I&& handler)
: poller_(std::forward<G>(future)), handler_(std::forward<I>(handler)) {}
constexpr handle_map_t<H, F> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
return handle_map(handler_, context, poller_);
}
private:
poller<F> poller_;
H handler_;
};
template <typename F, typename H>
using map_future_t = map_future<std::decay_t<F>, std::decay_t<H>>;
// The continuation produced by |fasync::map_ok|.
template <typename F, typename H>
class LIB_FASYNC_OWNER map_ok_future final {
static_assert(is_try_future_v<F>, "");
public:
template <typename G, typename I, requires_conditions<std::is_constructible<poller<F>, G>> = true>
constexpr map_ok_future(G&& future, I&& handler)
: poller_(std::forward<G>(future)), handler_(std::forward<I>(handler)) {}
constexpr handle_map_ok_t<H, F> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
if (poller_.output().is_error()) {
return ::fasync::done(::fitx::as_error(poller_.output().error_value()));
}
return handle_map_ok(handler_, context, poller_);
}
private:
poller<F> poller_;
H handler_;
};
template <typename F, typename H>
using map_ok_future_t = map_ok_future<std::decay_t<F>, std::decay_t<H>>;
// The continuation produced by |fasync::map_error|.
template <typename F, typename H>
class map_error_future final {
static_assert(is_try_future_v<F>, "");
public:
template <typename G, typename I, requires_conditions<std::is_constructible<poller<F>, G>> = true>
constexpr map_error_future(G&& future, I&& handler)
: poller_(std::forward<G>(future)), handler_(std::forward<I>(handler)) {}
template <typename G = F, requires_conditions<is_value_try_future<G>> = true>
constexpr handle_map_error_t<H, F> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
if (poller_.output().is_error()) {
return handle_map_error(handler_, context, poller_);
}
return ::fasync::done(::fitx::ok(std::move(poller_.output()).value()));
}
template <typename G = F, requires_conditions<cpp17::negation<is_value_try_future<G>>> = true>
constexpr handle_map_error_t<H, F> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
if (poller_.output().is_error()) {
return handle_map_error(handler_, context, poller_);
}
return ::fasync::done(::fitx::ok());
}
private:
poller<F> poller_;
H handler_;
};
template <typename F, typename H>
using map_error_future_t = map_error_future<std::decay_t<F>, std::decay_t<H>>;
// The continuation produced by |fasync::flatten|.
template <typename F>
class flatten_future final {
static_assert(is_future_v<F> && is_future_v<future_output_t<F>>, "");
public:
template <typename G, requires_conditions<std::is_constructible<poller<F>, G>> = true>
constexpr flatten_future(G&& future) : poller_(std::forward<G>(future)) {}
constexpr ::fasync::future_poll_t<::fasync::future_output_t<F>> operator()(
::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
return cpp20::invoke(poller_.output(), context);
}
private:
poller<F> poller_;
};
template <typename F>
using flatten_future_t = flatten_future<std::decay_t<F>>;
// A continuation used to flatten futures producing a |fitx::result| where the value type is a
// future. Used by |fasync::and_then|.
template <typename F>
class try_flatten_future final {
static_assert(is_try_future_v<F>, "");
using value_future = ::fasync::future_value_t<F>;
template <typename G, typename = bool>
struct poll_type {
using type = ::fasync::try_poll<::fasync::future_error_t<G>>;
};
template <typename G>
struct poll_type<G, requires_conditions<is_value_try_future<G>>> {
using type = ::fasync::try_poll<::fasync::future_error_t<F>, ::fasync::future_value_t<G>>;
};
template <typename G, requires_conditions<is_try_future<G>> = true>
using poll_t = typename poll_type<G>::type;
public:
template <typename G, requires_conditions<std::is_constructible<poller<F>, G>> = true>
constexpr try_flatten_future(G&& future) : poller_(std::forward<G>(future)) {}
constexpr poll_t<value_future> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
if (poller_.output().is_error()) {
return ::fasync::done(::fitx::as_error(poller_.output().error_value()));
}
return poller_.output().value()(context);
}
private:
poller<F> poller_;
};
template <typename F>
using try_flatten_future_t = try_flatten_future<std::decay_t<F>>;
// A continuation used to flatten futures producing a |fitx::result| where the error type is a
// future. Used by |fasync::or_else|.
template <typename F>
class try_flatten_error_future final {
static_assert(is_try_future_v<F>, "");
using error_future = ::fasync::future_error_t<F>;
template <typename G, typename = bool>
struct poll_type {
using type = ::fasync::try_poll<::fasync::future_error_t<error_future>>;
};
template <typename G>
struct poll_type<G, requires_conditions<is_value_try_future<G>>> {
using type =
::fasync::try_poll<::fasync::future_error_t<error_future>, ::fasync::future_value_t<G>>;
};
template <typename G, requires_conditions<is_try_future<G>> = true>
using poll_t = typename poll_type<G>::type;
public:
template <typename G, requires_conditions<std::is_constructible<poller<F>, G>> = true>
constexpr try_flatten_error_future(G&& future) : poller_(std::forward<G>(future)) {}
template <typename G = F, requires_conditions<is_value_try_future<G>> = true>
constexpr poll_t<F> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
if (poller_.output().is_error()) {
return cpp20::invoke(poller_.output().error_value(), context);
}
return ::fasync::done(::fitx::ok(std::move(poller_.output()).value()));
}
template <typename G = F, requires_conditions<cpp17::negation<is_value_try_future<G>>> = true>
constexpr poll_t<F> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
if (poller_.output().is_error()) {
return cpp20::invoke(poller_.output().error_value(), context);
}
return ::fasync::done(::fitx::ok());
}
private:
poller<F> poller_;
};
template <typename F>
using try_flatten_error_future_t = try_flatten_error_future<std::decay_t<F>>;
template <typename F, typename H, requires_conditions<is_future<F>> = true>
class inspect_future final {
static_assert(!is_void_future_v<F> && handler_returns_void_for_v<H, const future_output_t<F>&>,
"");
public:
template <
typename G, typename I,
requires_conditions<std::is_constructible<poller<F>, G>, std::is_constructible<H, I>> = true>
explicit constexpr inspect_future(G&& future, I&& handler)
: poller_(std::forward<G>(future)), handler_(std::forward<I>(handler)) {}
constexpr future_poll_t<F> operator()(context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
invoke_handler(handler_, context, cpp17::as_const(poller_.output()));
return ::fasync::done(std::move(poller_.output()));
}
private:
poller<F> poller_;
H handler_;
};
template <typename F, typename H>
using inspect_future_t = inspect_future<std::decay_t<F>, std::decay_t<H>>;
template <typename F, typename H, requires_conditions<is_try_future<F>> = true>
class inspect_ok_future final {
static_assert(handler_returns_void_for_v<H, const future_value_t<F>&>, "");
public:
template <
typename G, typename I,
requires_conditions<std::is_constructible<poller<F>, G>, std::is_constructible<H, I>> = true>
explicit constexpr inspect_ok_future(G&& future, I&& handler)
: poller_(std::forward<G>(future)), handler_(std::forward<I>(handler)) {}
constexpr future_poll_t<F> operator()(context& context) {
if (!poller_(context)) {
return ::fasync::pending();
} else if (poller_.output().is_ok()) {
invoke_handler(handler_, context, cpp17::as_const(poller_.output().value()));
}
return ::fasync::done(std::move(poller_.output()));
}
private:
poller<F> poller_;
H handler_;
};
template <typename F, typename H>
using inspect_ok_future_t = inspect_ok_future<std::decay_t<F>, std::decay_t<H>>;
template <typename F, typename H, requires_conditions<is_try_future<F>> = true>
class inspect_error_future final {
static_assert(handler_returns_void_for_v<H, const future_error_t<F>&>, "");
public:
template <
typename G, typename I,
requires_conditions<std::is_constructible<poller<F>, G>, std::is_constructible<H, I>> = true>
explicit constexpr inspect_error_future(G&& future, I&& handler)
: poller_(std::forward<G>(future)), handler_(std::forward<I>(handler)) {}
constexpr future_poll_t<F> operator()(context& context) {
if (!poller_(context)) {
return ::fasync::pending();
} else if (poller_.output().is_error()) {
invoke_handler(handler_, context, cpp17::as_const(poller_.output().error_value()));
}
return ::fasync::done(std::move(poller_.output()));
}
private:
poller<F> poller_;
H handler_;
};
template <typename F, typename H>
using inspect_error_future_t = inspect_error_future<std::decay_t<F>, std::decay_t<H>>;
template <typename F, requires_conditions<is_future<F>> = true>
class discard_future final {
public:
template <typename G, requires_conditions<std::is_constructible<poller<F>, G>> = true>
explicit constexpr discard_future(G&& future) : poller_(std::forward<G>(future)) {}
constexpr ::fasync::poll<> operator()(::fasync::context& context) {
if (!poller_(context)) {
return ::fasync::pending();
}
return ::fasync::done();
}
private:
poller<F> poller_;
};
template <typename F>
using discard_future_t = discard_future<std::decay_t<F>>;
template <typename... Rest>
constexpr bool and_all(bool first, Rest&&... rest) {
return first && and_all(std::forward<Rest>(rest)...);
}
template <>
constexpr bool and_all(bool arg) {
return arg;
}
template <typename... Fs>
class join_future final {
static_assert(cpp17::conjunction_v<is_future<Fs>...>, "");
using output_type = std::tuple<future_output_t<Fs>...>;
using in_progress_type = std::tuple<::fasync::internal::poller<Fs>...>;
public:
template <
typename... Gs,
requires_conditions<std::is_constructible<::fasync::internal::poller<Fs>, Gs>...> = true>
explicit constexpr join_future(Gs&&... futures) : in_progress_(std::forward<Gs>(futures)...) {}
constexpr ::fasync::poll<output_type> operator()(::fasync::context& context) {
return evaluate_join(context, std::index_sequence_for<Fs...>());
}
private:
template <size_t... Is>
constexpr ::fasync::poll<output_type> evaluate_join(::fasync::context& context,
std::index_sequence<Is...>) {
bool all_ready = and_all(std::get<Is>(in_progress_)(context)...);
if (all_ready) {
return done(cpp17::apply(
[](auto&&... pollers) { return output_type(std::move(pollers.output())...); },
in_progress_));
} else {
return ::fasync::pending();
}
}
in_progress_type in_progress_;
};
template <typename... Fs>
using join_future_t = join_future<std::decay_t<Fs>...>;
template <template <typename, typename> class C, typename F,
template <typename> class Allocator = std::allocator>
class join_container_future final {
static_assert(is_future_v<F>, "");
using output_type = C<future_output_t<F>, Allocator<future_output_t<F>>>;
using in_progress_type = C<poller<F>, Allocator<poller<F>>>;
public:
template <template <typename, typename> class D, typename G,
template <typename> class OtherAllocator = std::allocator,
requires_conditions<std::is_constructible<poller<F>, G>> = true>
explicit constexpr join_container_future(D<G, OtherAllocator<G>>&& futures)
: in_progress_(std::make_move_iterator(std::begin(futures)),
std::make_move_iterator(std::end(futures))) {}
constexpr ::fasync::poll<output_type> operator()(::fasync::context& context) {
bool all_ready = true;
for (auto& i : in_progress_) {
all_ready &= i(context);
}
if (!all_ready) {
return ::fasync::pending();
}
output_type output;
std::transform(std::begin(in_progress_), std::end(in_progress_), std::back_inserter(output),
[](auto&& poller) { return std::move(poller.output()); });
return ::fasync::done(std::move(output));
}
private:
in_progress_type in_progress_;
};
template <template <typename, size_t> class View, typename F, size_t N>
class join_view_future final {
static_assert(is_future_v<F>, "");
using output_type = std::array<future_output_t<F>, N>;
using in_progress_type = std::array<cpp17::optional<future_output_t<F>>, N>;
public:
template <template <typename, size_t> class OtherView, typename G, size_t O,
requires_conditions<cpp17::bool_constant<N != cpp20::dynamic_extent>,
std::is_constructible<View<F, N>, OtherView<G, O>>> = true>
explicit constexpr join_view_future(OtherView<G, O> other) : view_(std::move(other)) {}
constexpr ::fasync::poll<output_type> operator()(::fasync::context& context) {
bool all_ready = true;
auto i = std::begin(view_);
auto j = std::begin(in_progress_);
for (; i != std::end(view_) && j != std::end(in_progress_);
i = std::next(i), j = std::next(j)) {
if (j->has_value()) {
continue;
}
future_poll_t<F> p = cpp20::invoke(*i, context);
all_ready &= p.is_ready();
if (p.is_ready()) {
*j = std::move(p).output();
}
}
if (!all_ready) {
return ::fasync::pending();
}
return ::fasync::done(cpp17::apply(
[](auto&&... opts) { return output_type{std::move(*opts)...}; }, std::move(in_progress_)));
}
private:
View<F, N> view_;
in_progress_type in_progress_;
};
template <typename F>
class join_span_future final {
static_assert(is_future_v<F>, "");
using output_type = std::vector<future_output_t<F>>;
using in_progress_type = std::vector<poller<F>>;
public:
template <typename G, requires_conditions<std::is_constructible<poller<F>, G>> = true>
explicit constexpr join_span_future(cpp20::span<G> span)
: in_progress_(std::make_move_iterator(std::begin(span)),
std::make_move_iterator(std::end(span))) {}
constexpr ::fasync::poll<output_type> operator()(::fasync::context& context) {
bool all_ready = true;
for (auto& i : in_progress_) {
all_ready &= i(context);
}
if (!all_ready) {
return ::fasync::pending();
}
output_type output;
std::transform(std::begin(in_progress_), std::end(in_progress_), std::back_inserter(output),
[](auto&& poller) { return std::move(poller.output()); });
return ::fasync::done(std::move(output));
}
private:
in_progress_type in_progress_;
};
// An adaptor for callables returning |fasync::pending| for |fasync::make_future|.
template <typename StoredH>
class pending_adaptor final {
using return_type = invoke_handler_t<StoredH>;
static_assert(is_pending_v<return_type>, "");
public:
template <typename H, requires_conditions<std::is_constructible<StoredH, H>> = true>
constexpr pending_adaptor(H&& handler) : handler_(std::forward<H>(handler)) {}
constexpr ::fasync::poll<> operator()(::fasync::context& context) {
return invoke_handler(handler_, context);
}
private:
StoredH handler_;
};
template <typename H>
using pending_adaptor_t = pending_adaptor<std::decay_t<H>>;
// An adaptor for callables returning |fasync::ready| for |fasync::make_future|.
template <typename StoredH>
class ready_adaptor final {
using return_type = invoke_handler_t<StoredH>;
static_assert(is_ready_v<return_type>, "");
using output_type = ready_output_t<return_type>;
using poll_type = std::conditional_t<cpp17::is_void_v<output_type>, ::fasync::poll<>,
::fasync::poll<output_type>>;
public:
template <typename H, requires_conditions<std::is_constructible<StoredH, H>> = true>
constexpr ready_adaptor(H&& handler) : handler_(std::forward<H>(handler)) {}
constexpr poll_type operator()(::fasync::context& context) {
return invoke_handler(handler_, context);
}
private:
StoredH handler_;
};
template <typename H>
using ready_adaptor_t = ready_adaptor<std::decay_t<H>>;
// An adaptor for callables returning another future for |fasync::make_future|.
template <typename StoredH>
class future_adaptor final {
using future_type = invoke_handler_t<StoredH>;
static_assert(is_future_v<future_type>, "");
public:
template <typename H,
requires_conditions<std::is_constructible<StoredH, H>,
std::is_constructible<future_type, invoke_handler_t<H>>> = true>
constexpr future_adaptor(H&& handler) : handler_(std::forward<H>(handler)) {}
constexpr ::fasync::future_poll_t<future_type> operator()(::fasync::context& context) {
if (!future_.has_value()) {
move_construct_optional(future_, invoke_handler(std::move(handler_), context));
}
return cpp20::invoke(*future_, context);
}
private:
StoredH handler_;
cpp17::optional<future_type> future_;
};
template <typename H>
using future_adaptor_t = future_adaptor<std::decay_t<H>>;
// An adaptor for arbitrary handlers for |fasync::make_future|.
template <typename StoredH>
class handler_adaptor final {
public:
template <typename H, requires_conditions<std::is_constructible<StoredH, H>> = true>
constexpr handler_adaptor(H&& handler) : handler_(std::forward<H>(handler)) {}
constexpr auto operator()(::fasync::context& context) { return invoke(handler_, context); }
private:
template <typename H, requires_conditions<handler_returns_void_for<H>> = true>
constexpr ::fasync::poll<> invoke(priority_tag<1>, H&& handler, ::fasync::context& context) {
invoke_handler(std::forward<H>(handler), context);
return ::fasync::done();
}
template <typename H, requires_conditions<cpp17::negation<handler_returns_void_for<H>>> = true>
constexpr auto invoke(priority_tag<0>, H&& handler, ::fasync::context& context) {
return to_poll(handle_output(std::forward<H>(handler), context));
}
template <typename H>
constexpr auto invoke(H&& handler, ::fasync::context& context) {
return invoke(priority_tag<1>(), std::forward<H>(handler), context);
}
StoredH handler_;
};
template <typename H>
using handler_adaptor_t = handler_adaptor<std::decay_t<H>>;
template <typename H, typename return_type = invoke_handler_t<std::decay_t<H>>>
using make_future_adaptor_t = std::conditional_t<
is_pending_v<return_type>, pending_adaptor_t<H>,
std::conditional_t<
is_ready_v<return_type>, ready_adaptor_t<H>,
std::conditional_t<is_future_v<return_type>, future_adaptor_t<H>, handler_adaptor_t<H>>>>;
// A perfect forwarding call wrapper ([func.require] § 4) for composing two callables, with the same
// call pattern as calling |F| on its own. This is useful for composing the right side of a pipeline
// ahead of time and then invoking it with a future on the left.
template <typename F, typename G>
class compose_wrapper {
public:
template <typename H, typename I,
requires_conditions<std::is_constructible<F, H>, std::is_constructible<G, I>> = true>
explicit constexpr compose_wrapper(H&& h, I&& i)
: f_(std::forward<H>(h)), g_(std::forward<I>(i)) {}
constexpr compose_wrapper(const compose_wrapper&) = default;
constexpr compose_wrapper& operator=(const compose_wrapper&) = default;
constexpr compose_wrapper(compose_wrapper&&) = default;
constexpr compose_wrapper& operator=(compose_wrapper&&) = default;
// TODO(schottm): noexcept and decltype for this
template <typename... Args>
constexpr decltype(auto) operator()(Args&&... args) & {
return cpp20::invoke(f_, cpp20::invoke(g_, std::forward<Args>(args)...));
}
template <typename... Args>
constexpr decltype(auto) operator()(Args&&... args) const& {
return cpp20::invoke(f_, cpp20::invoke(g_, std::forward<Args>(args)...));
}
template <typename... Args>
constexpr decltype(auto) operator()(Args&&... args) && {
return cpp20::invoke(std::move(f_), cpp20::invoke(std::move(g_), std::forward<Args>(args)...));
}
// TODO(schottm): invocable requirements
template <typename... Args>
constexpr decltype(auto) operator()(Args&&... args) const&& {
return cpp20::invoke(std::move(f_),
cpp20::invoke(std::move > (g_), std::forward<Args>(args)...));
}
private:
F f_;
G g_;
};
template <typename F, typename G>
using compose_wrapper_t = compose_wrapper<std::decay_t<F>, std::decay_t<G>>;
template <typename Closure>
struct future_adaptor_closure;
template <typename T>
struct is_future_adaptor_closure : std::is_base_of<future_adaptor_closure<cpp20::remove_cvref_t<T>>,
cpp20::remove_cvref_t<T>>::type {};
template <typename T>
LIB_FASYNC_INLINE_CONSTANT constexpr bool is_future_adaptor_closure_v =
is_future_adaptor_closure<T>::value;
template <typename F>
struct future_adaptor_closure_t : F, future_adaptor_closure<future_adaptor_closure_t<F>> {
explicit constexpr future_adaptor_closure_t(F&& f) : F(std::forward<F>(f)) {}
};
} // namespace internal
} // namespace fasync
LIB_FASYNC_CPP_VERSION_COMPAT_END
#endif // SRC_LIB_FASYNC_INCLUDE_LIB_FASYNC_INTERNAL_FUTURE_H_
| 38.02155 | 100 | 0.682419 | [
"vector",
"transform"
] |
5ac8855652318657c30b11f691be1ba8bc4b48de | 2,485 | c | C | 3rd_party/nek5000_parRSB/src/genmap-vector.c | RonRahaman/nekRS | ffc02bca33ece6ba3330c4ee24565b1c6b5f7242 | [
"BSD-3-Clause"
] | 2 | 2021-09-07T03:00:53.000Z | 2021-12-06T18:08:27.000Z | 3rd_party/nek5000_parRSB/src/genmap-vector.c | neams-th-coe/nekRS | 5d2c8ab3d14b3fb16db35682336a1f96000698bb | [
"BSD-3-Clause"
] | 2 | 2021-06-27T02:07:27.000Z | 2021-08-24T04:47:42.000Z | 3rd_party/nek5000_parRSB/src/genmap-vector.c | neams-th-coe/nekRS | 5d2c8ab3d14b3fb16db35682336a1f96000698bb | [
"BSD-3-Clause"
] | 1 | 2019-09-10T20:12:48.000Z | 2019-09-10T20:12:48.000Z | #include <genmap-impl.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
int genmap_vector_create(genmap_vector *x, GenmapInt size) {
/* Asserts:
- size > 0
*/
assert(size > 0);
GenmapMalloc(1, x);
if (*x == NULL) {
return 1;
}
(*x)->size = size;
(*x)->data = NULL;
GenmapMalloc((size_t)size, &(*x)->data);
if ((*x)->data == NULL) {
return 1;
}
return 0;
}
int GenmapDestroyVector(genmap_vector x) {
if (x->data) {
GenmapFree(x->data);
}
if (x) {
GenmapFree(x);
}
return 0;
}
int genmap_vector_copy(genmap_vector y, genmap_vector x) {
/* Asserts:
- size y = size x
*/
assert(y->size >= x->size);
GenmapInt n = x->size;
GenmapInt i;
for (i = 0; i < n; i++) {
y->data[i] = x->data[i];
}
return 0;
}
int genmap_vector_scale(genmap_vector y, genmap_vector x, GenmapScalar alpha) {
/* asserts:
- size x = size y
*/
assert(x->size == y->size);
GenmapInt n = x->size;
GenmapInt i;
for (i = 0; i < n; i++) {
y->data[i] = alpha * x->data[i];
}
return 0;
}
int GenmapCreateOnesVector(genmap_vector *x, GenmapInt size) {
genmap_vector_create(x, size);
GenmapInt i;
for (i = 0; i < size; i++) {
(*x)->data[i] = 1.;
}
return 0;
}
int genmap_vector_create_zeros(genmap_vector *x, GenmapInt size) {
genmap_vector_create(x, size);
GenmapInt i;
for (i = 0; i < size; i++) {
(*x)->data[i] = 0.;
}
return 0;
}
GenmapScalar genmap_vector_dot(genmap_vector y, genmap_vector x) {
/* asserts:
- size x = size y
*/
assert(x->size == y->size);
GenmapScalar result = 0.0;
GenmapInt i;
for (i = 0; i < x->size; i++) {
result += x->data[i] * y->data[i];
}
return result;
}
int genmap_vector_axpby(genmap_vector z, genmap_vector x, GenmapScalar alpha,
genmap_vector y, GenmapScalar beta) {
assert(z->size == x->size);
assert(z->size == y->size);
GenmapInt n = z->size;
GenmapInt i;
for (i = 0; i < n; i++) {
z->data[i] = alpha * x->data[i] + beta * y->data[i];
}
return 0;
}
/* Orthogonalize by 1-vector (vector of all 1's) */
int genmap_vector_ortho_one(struct comm *c, genmap_vector q1, GenmapULong n) {
GenmapInt i;
GenmapScalar sum = 0.0, buf;
for (i = 0; i < q1->size; i++)
sum += q1->data[i];
comm_allreduce(c, gs_double, gs_add, &sum, 1, &buf);
sum /= n;
for (i = 0; i < q1->size; i++)
q1->data[i] -= sum;
return 0;
}
| 18.007246 | 79 | 0.571429 | [
"vector"
] |
5ace1ea557ba80cb174cb22730d9b644c957c2e1 | 2,360 | h | C | Libs/MRML/DisplayableManager/vtkMRMLRubberBandWidgetRepresentation.h | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Libs/MRML/DisplayableManager/vtkMRMLRubberBandWidgetRepresentation.h | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Libs/MRML/DisplayableManager/vtkMRMLRubberBandWidgetRepresentation.h | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
==============================================================================*/
/**
* @class vtkMRMLRubberBandWidgetRepresentation
* @brief represent intersections of other slice views in the current slice view
*
* @sa
* vtkSliceIntersectionWidget vtkWidgetRepresentation vtkAbstractWidget
*/
#ifndef vtkMRMLRubberBandWidgetRepresentation_h
#define vtkMRMLRubberBandWidgetRepresentation_h
#include "vtkMRMLDisplayableManagerExport.h" // For export macro
#include "vtkMRMLAbstractWidgetRepresentation.h"
class VTK_MRML_DISPLAYABLEMANAGER_EXPORT vtkMRMLRubberBandWidgetRepresentation : public vtkMRMLAbstractWidgetRepresentation
{
public:
/**
* Instantiate this class.
*/
static vtkMRMLRubberBandWidgetRepresentation *New();
//@{
/**
* Standard methods for instances of this class.
*/
vtkTypeMacro(vtkMRMLRubberBandWidgetRepresentation, vtkMRMLAbstractWidgetRepresentation);
void PrintSelf(ostream& os, vtkIndent indent) override;
//@}
/// Top-left point position in display coordinates
vtkGetVector2Macro(CornerPoint1, int);
vtkSetVector2Macro(CornerPoint1, int);
vtkGetVector2Macro(CornerPoint2, int);
vtkSetVector2Macro(CornerPoint2, int);
//@{
/**
* Methods to make this class behave as a vtkProp.
*/
void GetActors2D(vtkPropCollection *) override;
void ReleaseGraphicsResources(vtkWindow *) override;
int RenderOverlay(vtkViewport *viewport) override;
//@}
protected:
vtkMRMLRubberBandWidgetRepresentation();
~vtkMRMLRubberBandWidgetRepresentation() override;
class vtkInternal;
vtkInternal * Internal;
int CornerPoint1[2];
int CornerPoint2[2];
private:
vtkMRMLRubberBandWidgetRepresentation(const vtkMRMLRubberBandWidgetRepresentation&) = delete;
void operator=(const vtkMRMLRubberBandWidgetRepresentation&) = delete;
};
#endif
| 29.873418 | 123 | 0.729237 | [
"3d"
] |
5ad250ecbeadde0ce00a27897ecca49845972939 | 18,145 | h | C | Source/HoudiniEngineRuntime/Private/HoudiniPDGAssetLink.h | eliiik/HoudiniEngineForUnreal-v2 | 6cfc93a8f7f4929e13823a1611532bfd102bc190 | [
"BSD-3-Clause"
] | null | null | null | Source/HoudiniEngineRuntime/Private/HoudiniPDGAssetLink.h | eliiik/HoudiniEngineForUnreal-v2 | 6cfc93a8f7f4929e13823a1611532bfd102bc190 | [
"BSD-3-Clause"
] | null | null | null | Source/HoudiniEngineRuntime/Private/HoudiniPDGAssetLink.h | eliiik/HoudiniEngineForUnreal-v2 | 6cfc93a8f7f4929e13823a1611532bfd102bc190 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) <2021> Side Effects Software Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. The name of Side Effects Software may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "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 SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
//#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "HoudiniAsset.h"
#include "HoudiniAssetComponent.h"
#include "HoudiniPDGAssetLink.generated.h"
struct FHoudiniPackageParams;
UENUM()
enum class EPDGLinkState : uint8
{
Inactive,
Linking,
Linked,
Error_Not_Linked
};
UENUM()
enum class EPDGNodeState : uint8
{
None,
Dirtied,
Dirtying,
Cooking,
Cook_Complete,
Cook_Failed
};
UENUM()
enum class EPDGWorkResultState : uint8
{
None,
ToLoad,
Loading,
Loaded,
ToDelete,
Deleting,
Deleted,
NotLoaded
};
#if WITH_EDITORONLY_DATA
UENUM()
enum class EPDGBakeSelectionOption : uint8
{
All,
SelectedNetwork,
SelectedNode
};
#endif
#if WITH_EDITORONLY_DATA
UENUM()
enum class EPDGBakePackageReplaceModeOption : uint8
{
CreateNewAssets,
ReplaceExistingAssets
};
#endif
USTRUCT()
struct HOUDINIENGINERUNTIME_API FOutputActorOwner
{
GENERATED_BODY();
public:
FOutputActorOwner()
: OutputActor(nullptr) {};
virtual ~FOutputActorOwner() {};
// Create OutputActor, an actor to hold work result output
virtual bool CreateOutputActor(UWorld* InWorld, UHoudiniPDGAssetLink* InAssetLink, AActor *InParentActor, const FName& InName);
// Return OutputActor
virtual AActor* GetOutputActor() const { return OutputActor; }
// Setter for OutputActor
virtual void SetOutputActor(AActor* InActor) { OutputActor = InActor; }
// Destroy OutputActor if it is valid.
virtual bool DestroyOutputActor();
private:
UPROPERTY(NonTransactional)
AActor* OutputActor;
};
USTRUCT()
struct HOUDINIENGINERUNTIME_API FTOPWorkResultObject
{
GENERATED_USTRUCT_BODY()
public:
// Constructor
FTOPWorkResultObject();
// Call DestroyResultObjects in the destructor
virtual ~FTOPWorkResultObject();
// Set ResultObjects to a copy of InUpdatedOutputs
void SetResultOutputs(const TArray<UHoudiniOutput*>& InUpdatedOutputs) { ResultOutputs = InUpdatedOutputs; }
// Getter for ResultOutputs
TArray<UHoudiniOutput*>& GetResultOutputs() { return ResultOutputs; }
// Getter for ResultOutputs
const TArray<UHoudiniOutput*>& GetResultOutputs() const { return ResultOutputs; }
// Destroy ResultOutputs
void DestroyResultOutputs();
// Get the OutputActor owner struct
FOutputActorOwner& GetOutputActorOwner() { return OutputActorOwner; }
// Get the OutputActor owner struct
const FOutputActorOwner& GetOutputActorOwner() const { return OutputActorOwner; }
public:
UPROPERTY(NonTransactional)
FString Name;
UPROPERTY(NonTransactional)
FString FilePath;
UPROPERTY(NonTransactional)
EPDGWorkResultState State;
protected:
// UPROPERTY()
// TArray<UObject*> ResultObjects;
UPROPERTY(NonTransactional)
TArray<UHoudiniOutput*> ResultOutputs;
private:
// List of objects to delete, internal use only (DestroyResultOutputs)
UPROPERTY(NonTransactional)
TArray<UObject*> OutputObjectsToDelete;
UPROPERTY(NonTransactional)
FOutputActorOwner OutputActorOwner;
};
USTRUCT()
struct HOUDINIENGINERUNTIME_API FTOPWorkResult
{
GENERATED_USTRUCT_BODY()
public:
// Constructor
FTOPWorkResult();
// Comparison operator, used by hashing containers and arrays.
bool operator==(const FTOPWorkResult& OtherWorkResult) const;
public:
UPROPERTY(NonTransactional)
int32 WorkItemIndex;
UPROPERTY(Transient)
int32 WorkItemID;
UPROPERTY(NonTransactional)
TArray<FTOPWorkResultObject> ResultObjects;
/*
UPROPERTY()
TArray<UObject*> ResultObjects;
UPROPERTY()
TArray<FString> ResultNames;
UPROPERTY()
TArray<FString> ResultFilePaths;
UPROPERTY()
TArray<EPDGWorkResultState> ResultStates;
*/
};
USTRUCT()
struct HOUDINIENGINERUNTIME_API FWorkItemTally
{
GENERATED_USTRUCT_BODY()
public:
// Constructor
FWorkItemTally();
void ZeroAll();
bool AreAllWorkItemsComplete() const;
bool AnyWorkItemsFailed() const;
bool AnyWorkItemsPending() const;
FString ProgressRatio() const;
public:
UPROPERTY()
int32 TotalWorkItems;
UPROPERTY()
int32 WaitingWorkItems;
UPROPERTY()
int32 ScheduledWorkItems;
UPROPERTY()
int32 CookingWorkItems;
UPROPERTY()
int32 CookedWorkItems;
UPROPERTY()
int32 ErroredWorkItems;
};
// Container for baked outputs of a PDG work result object.
USTRUCT()
struct HOUDINIENGINERUNTIME_API FHoudiniPDGWorkResultObjectBakedOutput
{
GENERATED_BODY()
public:
// Array of baked output per output index of the work result object's outputs.
UPROPERTY()
TArray<FHoudiniBakedOutput> BakedOutputs;
};
UCLASS()
class HOUDINIENGINERUNTIME_API UTOPNode : public UObject
{
GENERATED_BODY()
public:
// Constructor
UTOPNode();
// Comparison operator, used by hashing containers and arrays.
bool operator==(const UTOPNode& Other) const;
void Reset();
bool AreAllWorkItemsComplete() const { return WorkItemTally.AreAllWorkItemsComplete(); };
bool AnyWorkItemsFailed() const { return WorkItemTally.AnyWorkItemsFailed(); };
bool AnyWorkItemsPending() const { return WorkItemTally.AnyWorkItemsPending(); };
bool IsVisibleInLevel() const { return bShow; }
void SetVisibleInLevel(bool bInVisible);
void UpdateOutputVisibilityInLevel();
// Sets all WorkResultObjects that are in the NotLoaded state to ToLoad.
void SetNotLoadedWorkResultsToLoad(bool bInAlsoSetDeletedToLoad=false);
// Sets all WorkResultObjects that are in the Loaded state to ToDelete (will delete output objects and output
// actors).
void SetLoadedWorkResultsToDelete();
// Immediately delete Loaded work result output objects (keeps the work items and result arrays but deletes the output
// objects and actors and sets the state to Deleted.
void DeleteWorkResultOutputObjects();
// Get the OutputActor owner struct
FOutputActorOwner& GetOutputActorOwner() { return OutputActorOwner; }
// Get the OutputActor owner struct
const FOutputActorOwner& GetOutputActorOwner() const { return OutputActorOwner; }
// Get the baked outputs from the last bake. The map keys are [work_result_index]_[work_result_object_index]
TMap<FString, FHoudiniPDGWorkResultObjectBakedOutput>& GetBakedWorkResultObjectsOutputs() { return BakedWorkResultObjectOutputs; }
const TMap<FString, FHoudiniPDGWorkResultObjectBakedOutput>& GetBakedWorkResultObjectsOutputs() const { return BakedWorkResultObjectOutputs; }
bool GetBakedWorkResultObjectOutputsKey(int32 InWorkResultIndex, int32 InWorkResultObjectIndex, FString& OutKey) const;
static FString GetBakedWorkResultObjectOutputsKey(int32 InWorkResultIndex, int32 InWorkResultObjectIndex);
bool GetBakedWorkResultObjectOutputs(int32 InWorkResultIndex, int32 InWorkResultObjectIndex, FHoudiniPDGWorkResultObjectBakedOutput*& OutBakedOutput);
bool GetBakedWorkResultObjectOutputs(int32 InWorkResultIndex, int32 InWorkResultObjectIndex, FHoudiniPDGWorkResultObjectBakedOutput const*& OutBakedOutput) const;
#if WITH_EDITOR
void PostEditChangeChainProperty(FPropertyChangedChainEvent& PropertyChangedEvent) override;
#endif
#if WITH_EDITOR
void PostTransacted(const FTransactionObjectEvent& TransactionEvent) override;
#endif
public:
UPROPERTY(Transient, NonTransactional)
int32 NodeId;
UPROPERTY(NonTransactional)
FString NodeName;
UPROPERTY(NonTransactional)
FString NodePath;
UPROPERTY(NonTransactional)
FString ParentName;
UPROPERTY()
UObject* WorkResultParent;
UPROPERTY(NonTransactional)
TArray<FTOPWorkResult> WorkResult;
// Hidden in the nodes combobox
UPROPERTY()
bool bHidden;
UPROPERTY()
bool bAutoLoad;
UPROPERTY(Transient, NonTransactional)
EPDGNodeState NodeState;
UPROPERTY(Transient, NonTransactional)
FWorkItemTally WorkItemTally;
// This is set when the TOP node's work items are processed by
// FHoudiniPDGManager based on if any NotLoaded work result objects are found
UPROPERTY(NonTransactional)
bool bCachedHaveNotLoadedWorkResults;
// This is set when the TOP node's work items are processed by
// FHoudiniPDGManager based on if any Loaded work result objects are found
UPROPERTY(NonTransactional)
bool bCachedHaveLoadedWorkResults;
// True if this node has child nodes
UPROPERTY(NonTransactional)
bool bHasChildNodes;
protected:
// Visible in the level
UPROPERTY()
bool bShow;
// Map of [work_result_index]_[work_result_object_index] to the work result object's baked outputs.
UPROPERTY()
TMap<FString, FHoudiniPDGWorkResultObjectBakedOutput> BakedWorkResultObjectOutputs;
private:
UPROPERTY()
FOutputActorOwner OutputActorOwner;
};
UCLASS()
class HOUDINIENGINERUNTIME_API UTOPNetwork : public UObject
{
GENERATED_BODY()
public:
// Constructor
UTOPNetwork();
// Comparison operator, used by hashing containers and arrays.
bool operator==(const UTOPNetwork& Other) const;
// Sets all WorkResultObjects that are in the Loaded state to ToDelete (will delete output objects and output
// actors).
void SetLoadedWorkResultsToDelete();
// Immediately delete Loaded work result output objects (keeps the work items and result arrays but deletes the output
// objects and actors and sets the state to Deleted.
void DeleteWorkResultOutputObjects();
// Returns true if any node in this TOP net has pending (waiting, scheduled, cooking) work items.
bool AnyWorkItemsPending() const;
public:
UPROPERTY(Transient, NonTransactional)
int32 NodeId;
UPROPERTY(NonTransactional)
FString NodeName;
// HAPI path to this node (relative to the HDA)
UPROPERTY(NonTransactional)
FString NodePath;
UPROPERTY()
TArray<UTOPNode*> AllTOPNodes;
// TODO: Should be using SelectedNodeName instead?
// Index is not consistent after updating filter
UPROPERTY()
int32 SelectedTOPIndex;
UPROPERTY(NonTransactional)
FString ParentName;
UPROPERTY()
bool bShowResults;
UPROPERTY()
bool bAutoLoadResults;
};
class UHoudiniPDGAssetLink;
DECLARE_MULTICAST_DELEGATE_FourParams(FHoudiniPDGAssetLinkWorkResultObjectLoaded, UHoudiniPDGAssetLink*, UTOPNode*, int32 /*WorkItemId*/, const FString& /*WorkResultObjectName*/);
UCLASS()
class HOUDINIENGINERUNTIME_API UHoudiniPDGAssetLink : public UObject
{
GENERATED_UCLASS_BODY()
public:
friend class UHoudiniAssetComponent;
static FString GetAssetLinkStatus(const EPDGLinkState& InLinkState);
static FString GetTOPNodeStatus(const UTOPNode* InTOPNode);
static FLinearColor GetTOPNodeStatusColor(const UTOPNode* InTOPNode);
void UpdateTOPNodeWithChildrenWorkItemTallyAndState(UTOPNode* InNode, UTOPNetwork* InNetwork);
void UpdateWorkItemTally();
static void ResetTOPNetworkWorkItemTally(UTOPNetwork* TOPNetwork);
// Set the TOP network at the given index as currently selected TOP network
void SelectTOPNetwork(const int32& AtIndex);
// Set the TOP node at the given index in the given TOP network as currently selected TOP node
void SelectTOPNode(UTOPNetwork* InTOPNetwork, const int32& AtIndex);
UTOPNode* GetSelectedTOPNode();
UTOPNetwork* GetSelectedTOPNetwork();
FString GetSelectedTOPNodeName();
FString GetSelectedTOPNetworkName();
UTOPNode* GetTOPNode(const int32& InNodeID);
UTOPNetwork* GetTOPNetwork(const int32& AtIndex);
// Find the node with relative path 'InNodePath' from its topnet.
static UTOPNode* GetTOPNodeByNodePath(const FString& InNodePath, const TArray<UTOPNode*>& InTOPNodes, int32& OutIndex);
// Find the network with relative path 'InNetPath' from the HDA
static UTOPNetwork* GetTOPNetworkByNodePath(const FString& InNodePath, const TArray<UTOPNetwork*>& InTOPNetworks, int32& OutIndex);
// Get the parent TOP node of the specified node. This is resolved
UTOPNode* GetParentTOPNode(const UTOPNode* InNode);
static void ClearTOPNodeWorkItemResults(UTOPNode* TOPNode);
static void ClearTOPNetworkWorkItemResults(UTOPNetwork* TOPNetwork);
// Clear the result objects of a work item (FTOPWorkResult.ResultObjects), but don't delete the work item from
// TOPNode.WorkResults (for example, the work item was dirtied but not removed from PDG)
static void ClearWorkItemResultByID(const int32& InWorkItemID, UTOPNode* InTOPNode);
// Calls ClearWorkItemResultByID and then deletes the FTOPWorkResult from InTOPNode.Result as well. For example:
// the work item was removed in PDG.
static void DestroyWorkItemByID(const int32& InWorkItemID, UTOPNode* InTOPNode);
static FTOPWorkResult* GetWorkResultByID(const int32& InWorkItemID, UTOPNode* InTOPNode);
// This should be called after the owner and this PDG asset link is duplicated. Set all output parent actors to
// null in all TOP networks/nodes. Since the TOP Networks/TOP nodes are all structs, we cannot set
// DuplicateTransient property on their OutputActor properties.
void UpdatePostDuplicate();
// Load the geometry generated as results of the given work item, of the given TOP node.
// The load will be done asynchronously.
// Results must be tagged with 'file', and must have a file path, otherwise will not be loaded.
//void LoadResults(FTOPNode TOPNode, HAPI_PDG_WorkitemInfo workItemInfo, HAPI_PDG_WorkitemResultInfo[] resultInfos, HAPI_PDG_WorkitemId workItemID)
// Gets the temporary cook folder. If the parent of this asset link is a HoudiniAssetComponent use that, otherwise
// use the default static mesh temporary cook folder.
FDirectoryPath GetTemporaryCookFolder() const;
// Get the actor that owns this PDG asset link. If the asset link is owned by a component,
// then the component's owning actor is returned. Can return null if this is now owned by
// an actor or component.
AActor* GetOwnerActor() const;
// Checks if the asset link has any temporary outputs and returns true if it has
bool HasTemporaryOutputs() const;
// Filter TOP nodes and outputs (hidden/visible) by TOPNodeFilter and TOPOutputFilter.
void FilterTOPNodesAndOutputs();
// On all FTOPNodes: Load not loaded items if bAutoload is true, and update the level visibility of work items
// result. Used when FTOPNode.bShow and/or FTOPNode.bAutoload changed.
void UpdateTOPNodeAutoloadAndVisibility();
#if WITH_EDITORONLY_DATA
void PostEditChangeChainProperty(FPropertyChangedChainEvent& PropertyChangedEvent) override;
#endif
#if WITH_EDITORONLY_DATA
void PostTransacted(const FTransactionObjectEvent& TransactionEvent) override;
#endif
private:
void ClearAllTOPData();
static void DestroyWorkItemResultData(FTOPWorkResult& Result, UTOPNode* InTOPNode);
static void DestoryWorkResultObjectData(FTOPWorkResultObject& ResultObject);
public:
//UPROPERTY()
//UHoudiniAsset* HoudiniAsset;
//UPROPERTY()
//UHoudiniAssetComponent* ParentHAC;
UPROPERTY(DuplicateTransient, NonTransactional)
FString AssetName;
// The full path to the HDA in HAPI
UPROPERTY(DuplicateTransient, NonTransactional)
FString AssetNodePath;
UPROPERTY(DuplicateTransient, NonTransactional)
int32 AssetID;
UPROPERTY()
TArray<UTOPNetwork*> AllTOPNetworks;
UPROPERTY()
int32 SelectedTOPNetworkIndex;
UPROPERTY(Transient, NonTransactional)
EPDGLinkState LinkState;
UPROPERTY()
bool bAutoCook;
UPROPERTY()
bool bUseTOPNodeFilter;
UPROPERTY()
bool bUseTOPOutputFilter;
UPROPERTY()
FString TOPNodeFilter;
UPROPERTY()
FString TOPOutputFilter;
UPROPERTY(NonTransactional)
int32 NumWorkitems;
UPROPERTY(Transient, NonTransactional)
FWorkItemTally WorkItemTally;
UPROPERTY()
FString OutputCachePath;
UPROPERTY(Transient)
bool bNeedsUIRefresh;
// A parent actor to serve as the parent of any output actors
// that are created.
// If null, then output actors are created under a folder
UPROPERTY(EditAnywhere, Category="Output")
AActor* OutputParentActor;
// Folder used for baking PDG outputs
UPROPERTY()
FDirectoryPath BakeFolder;
//
// Notifications
//
// Delegate that is broadcast when a work result object has been loaded
FHoudiniPDGAssetLinkWorkResultObjectLoaded OnWorkResultObjectLoaded;
//
// End: Notifications
//
#if WITH_EDITORONLY_DATA
UPROPERTY()
bool bBakeMenuExpanded;
// What kind of output to bake, for example, bake actors, bake to blueprint
UPROPERTY()
EHoudiniEngineBakeOption HoudiniEngineBakeOption;
// Which outputs to bake, for example, all, selected network, selected node
UPROPERTY()
EPDGBakeSelectionOption PDGBakeSelectionOption;
// This determines if the baked assets should replace existing assets with the same name,
// or always generate new assets (with numerical suffixes if needed to create unique names)
UPROPERTY()
EPDGBakePackageReplaceModeOption PDGBakePackageReplaceMode;
// If true, recenter baked actors to their bounding box center after bake
UPROPERTY()
bool bRecenterBakedActors;
// Auto-bake: if this is true, it indicates that a work result object should be baked after it is loaded.
UPROPERTY()
bool bBakeAfterWorkResultObjectLoaded;
// The delegate handle of the auto bake helper function bound to OnWorkResultObjectLoaded.
FDelegateHandle AutoBakeDelegateHandle;
#endif
};
| 29.219002 | 179 | 0.786939 | [
"mesh",
"geometry",
"object"
] |
5ad3886e5cc92469a18b60e1de817495700e8e0e | 1,195 | h | C | Sudoku/Main.h | strah19/Sudoku | f1ab40916b9c6bc4dc59f7171fb5ce9c088c7e68 | [
"MIT"
] | null | null | null | Sudoku/Main.h | strah19/Sudoku | f1ab40916b9c6bc4dc59f7171fb5ce9c088c7e68 | [
"MIT"
] | null | null | null | Sudoku/Main.h | strah19/Sudoku | f1ab40916b9c6bc4dc59f7171fb5ce9c088c7e68 | [
"MIT"
] | null | null | null | #pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <utility>
#include <string>
#include <sstream>
#include <random>
namespace Keys
{
enum listOfKeys {ONE = SDL_SCANCODE_1
,TWO = SDL_SCANCODE_2
, THREE = SDL_SCANCODE_3
, FOUR = SDL_SCANCODE_4
, FIVE = SDL_SCANCODE_5
, SIX = SDL_SCANCODE_6
, SEVEN = SDL_SCANCODE_7
, EIGHT = SDL_SCANCODE_8
, NINE = SDL_SCANCODE_9
};
}
struct MouseInputs
{
bool leftClick;
bool rightClick;
bool UpScroll;
bool DownScroll;
};
class gamePlay
{
private:
SDL_Window* mainWin;
bool Running;
bool successfulInit;
int RenWidth, RenHeight;
int state = 0;
int fps;
public:
bool init(const char* title, int width, int height, int full);
void cleanUp(gamePlay*);
bool initSudoku();
bool gameLoop();
void render();
void update();
static SDL_Renderer* mainRen;
static SDL_Event mainEvent;
SDL_Color mainTextColor = { 0, 0, 0, 0 };
SDL_Color changer = { 100, 100, 100, 255 };
SDL_Color wrong = { 255, 0, 0, 255 };
inline void getFPS(int f) { fps = f; }
inline bool getDone() const { return Running; }
};
| 18.384615 | 63 | 0.699582 | [
"render"
] |
5ad6340ffd9c3ba40ba9c5f65211c0d5d27b5e6f | 5,547 | h | C | src/ViennaRNA/landscape/move.h | visigoth/ViennaRNA | 0b8ca4c6604e7a8bea366af62d82f8f40cea49bf | [
"Python-2.0"
] | 157 | 2016-10-12T22:11:56.000Z | 2022-03-20T05:45:15.000Z | src/ViennaRNA/landscape/move.h | visigoth/ViennaRNA | 0b8ca4c6604e7a8bea366af62d82f8f40cea49bf | [
"Python-2.0"
] | 136 | 2016-11-07T19:06:30.000Z | 2022-03-10T23:50:55.000Z | src/ViennaRNA/landscape/move.h | visigoth/ViennaRNA | 0b8ca4c6604e7a8bea366af62d82f8f40cea49bf | [
"Python-2.0"
] | 59 | 2016-11-17T20:23:55.000Z | 2022-01-27T15:23:17.000Z | #ifndef VIENNA_RNA_PACKAGE_MOVE_H
#define VIENNA_RNA_PACKAGE_MOVE_H
/**
* @file ViennaRNA/landscape/move.h
* @ingroup neighbors
* @brief Methods to operate with structural neighbors of RNA secondary structures.
*/
/**
* @addtogroup neighbors
* @{
*/
/**
* @brief A single move that transforms a secondary structure into one of its neighbors
*/
typedef struct vrna_move_s vrna_move_t;
/**
* @brief Option flag indicating insertion move
* @see vrna_neighbors(), vrna_neighbors_successive, vrna_path()
*/
#define VRNA_MOVESET_INSERTION 4
/**
* @brief Option flag indicating deletion move
* @see vrna_neighbors(), vrna_neighbors_successive, vrna_path()
*/
#define VRNA_MOVESET_DELETION 8
/**
* @brief Option flag indicating shift move
* @see vrna_neighbors(), vrna_neighbors_successive, vrna_path()
*/
#define VRNA_MOVESET_SHIFT 16
/**
* @brief Option flag indicating moves without lonely base pairs
* @see vrna_neighbors(), vrna_neighbors_successive, vrna_path()
*/
#define VRNA_MOVESET_NO_LP 32
/**
* @brief Option flag indicating default move set, i.e. insertions/deletion of a base pair
* @see vrna_neighbors(), vrna_neighbors_successive, vrna_path()
*/
#define VRNA_MOVESET_DEFAULT (VRNA_MOVESET_INSERTION | VRNA_MOVESET_DELETION)
/**
* @brief An atomic representation of the transition / move from one structure to its neighbor
*
* An atomic transition / move may be one of the following:
* - a <strong>base pair insertion</strong>,
* - a <strong>base pair removal</strong>, or
* - a <strong>base pair shift</strong> where an existing base pair changes one of its
* pairing partner.
*
* These moves are encoded by two integer values that represent the affected 5' and 3'
* nucleotide positions. Furthermore, we use the following convention on the signedness
* of these encodings:
* - both values are positive for <em>insertion moves</em>
* - both values are negative for <em>base pair removals</em>
* - both values have different signedness for <em>shift moves</em>, where the positive
* value indicates the nucleotide that stays constant, and the others absolute value
* is the new pairing partner
*
* @note A value of 0 in either field is used as list-end indicator and doesn't represent
* any valid move.
*/
struct vrna_move_s {
int pos_5; /**< @brief The (absolute value of the) 5' position of a base pair, or any position of a shifted pair */
int pos_3; /**< @brief The (absolute value of the) 3' position of a base pair, or any position of a shifted pair */
vrna_move_t *next; /**< @brief The next base pair (if an elementary move changes more than one base pair), or @p NULL
* Has to be terminated with move 0,0
*/
};
/**
* @brief Create an atomic move
*
* @see #vrna_move_s
*
* @param pos_5 The 5' position of the move (positive for insertions, negative for removal, any value for shift moves)
* @param pos_3 The 3' position of the move (positive for insertions, negative for removal, any value for shift moves)
* @return An atomic move as specified by @p pos_5 and @p pos_3
*/
vrna_move_t
vrna_move_init(int pos_5,
int pos_3);
/**
* delete all moves in a zero terminated list.
*/
void
vrna_move_list_free(vrna_move_t *moves);
/**
* @brief Apply a particular move / transition to a secondary structure, i.e. transform a structure
*
* @param[in,out] pt The pair table representation of the secondary structure
* @param[in] m The move to apply
*/
void
vrna_move_apply(short *pt,
const vrna_move_t *m);
void
vrna_move_apply_db(char *structure,
const short *pt,
const vrna_move_t *m);
/**
* @brief Test whether a move is a base pair removal
*
* @param m The move to test against
* @return Non-zero if the move is a base pair removal, 0 otherwise
*/
int
vrna_move_is_removal(const vrna_move_t *m);
/**
* @brief Test whether a move is a base pair insertion
*
* @param m The move to test against
* @return Non-zero if the move is a base pair insertion, 0 otherwise
*/
int
vrna_move_is_insertion(const vrna_move_t *m);
/**
* @brief Test whether a move is a base pair shift
*
* @param m The move to test against
* @return Non-zero if the move is a base pair shift, 0 otherwise
*/
int
vrna_move_is_shift(const vrna_move_t *m);
/**
* @brief Compare two moves
*
* The function compares two moves @p a and @p b and returns
* whether move @p a is lexicographically smaller (-1), larger (1)
* or equal to move @p b.
*
* If any of the moves @p a or @p b is a shift move, this
* comparison only makes sense in a structure context. Thus,
* the third argument with the current structure must be provided.
*
* @note This function returns 0 (equality) upon any error, e.g. missing input
*
* @warning Currently, shift moves are not supported!
*
* @param a The first move of the comparison
* @param b The second move of the comparison
* @param pt The pair table of the current structure that is compatible with both moves (maybe NULL if moves are guaranteed to be no shifts)
* @return -1 if @p a < @p b, 1 if @p a > @p b, 0 otherwise
*/
int
vrna_move_compare(const vrna_move_t *a,
const vrna_move_t *b,
const short *pt);
/**
* @}
*/
#endif
| 30.646409 | 145 | 0.674238 | [
"transform"
] |
5ae473539e6514b0204cc62f63d5572960777799 | 4,309 | c | C | src/libdamiao/MT19937-64.c | ismaeldamiao/CLMC | f255859b996dc328ca8269e2bdb170a484598cc2 | [
"MIT"
] | null | null | null | src/libdamiao/MT19937-64.c | ismaeldamiao/CLMC | f255859b996dc328ca8269e2bdb170a484598cc2 | [
"MIT"
] | null | null | null | src/libdamiao/MT19937-64.c | ismaeldamiao/CLMC | f255859b996dc328ca8269e2bdb170a484598cc2 | [
"MIT"
] | null | null | null | /* *****************************************************************************
A C- program for MT19937: Real number version
genrand() generates pseudorandom real number (double)
which is uniformly distributed on [0, 1] interval, for each
call.
***
This vesion use words with 64bit. In the first
call genrand(seed) set initial values to the working area of 312 words.
(seed is any 64-bit integer except for 0)
The function genrand(*y) return the pseudorandom real and
set y to the pseudorandom integer.
***
The original code has write by Takuji Nishimura and the values for
64bit words has obtained in wikipedia.
*****************************************************************************
E-mail: ismaellxd@gmail.com
Site: https://ismaeldamiao.github.io/
*****************************************************************************
Copyright (c) 2021 I.F.F. dos SANTOS (Ismael Damiao)
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 <stdio.h>
#include <stdint.h> /* Use C99 or latter */
/* Period parameters */
#define WORD_SIZE 64
#define N 312
#define M 156
#define MATRIX_A UINT64_C(0xb5026f5aa96619e9) /* constant vector a */
#define UPPER_MASK (UINT64_C(0x80000000)) /* most significant w-r bits */
#define LOWER_MASK (UINT64_C(0x7fffffff)) /* least significant r bits */
/* Tempering parameters */
#define TEMPERING_MASK_D UINT64_C(0x5555555555555555)
#define TEMPERING_MASK_B UINT64_C(0x71d67fffeda60000)
#define TEMPERING_MASK_C UINT64_C(0xfff7eee000000000)
#define TEMPERING_SHIFT_U(y) (y >> 29)
#define TEMPERING_SHIFT_S(y) (y << 17)
#define TEMPERING_SHIFT_T(y) (y << 37)
#define TEMPERING_SHIFT_L(y) (y >> 43)
double mt19937(uint64_t *y)
{
static uint64_t mt[N]; /* the array for the state vector */
static int mti = N+1; /* mti==N+1 means mt[N] is not initialized */
static uint64_t mag01[2] = {UINT64_C(0x0), MATRIX_A};
if(mti >= N){ /* generate N words at one time */
int kk;
if(mti == N+1){ /* initializing the array with NONZERO seed */
if(*y == UINT64_C(0)) *y = UINT64_C(4357); /* a default seed is used */
/* setting the initial seeds to mt[N] using the generator Line 25 of
table 1 in [KNUTH 1981, The Art of Computer Programming Vol. 2
(2nd Ed.), pp102 */
mt[0] = *y & UINT64_C(0xffffffffffffffff);
for(mti = 1; mti < N; ++mti)
mt[mti] = (69069 * mt[mti-1]) & UINT64_C(0xffffffffffffffff);
}
for(kk = 0; kk < N-M; ++kk){
*y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+M] ^ (*y >> 1) ^ mag01[*y & 0x1];
}
for(; kk < N-1; ++kk){
*y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk + (M-N)] ^ (*y >> 1) ^ mag01[*y & 0x1];
}
*y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N-1] = mt[M-1] ^ (*y >> 1) ^ mag01[*y & 0x1];
mti = 0;
}
*y = mt[++mti];
*y ^= TEMPERING_SHIFT_U(*y) & TEMPERING_MASK_D;
*y ^= TEMPERING_SHIFT_S(*y) & TEMPERING_MASK_B;
*y ^= TEMPERING_SHIFT_T(*y) & TEMPERING_MASK_C;
*y ^= TEMPERING_SHIFT_L(*y);
return ((double)(*y) / (double)UINT64_MAX);
}
| 45.840426 | 80 | 0.616152 | [
"vector"
] |
5ae8606ced9186f96b8905bb8053abae37110e93 | 3,712 | h | C | src/main/cpp/utils/utils.h | DeathByKorea/nova-renderer | 3becf4216d798d7fc615b7990b266559f52db0af | [
"MIT"
] | null | null | null | src/main/cpp/utils/utils.h | DeathByKorea/nova-renderer | 3becf4216d798d7fc615b7990b266559f52db0af | [
"MIT"
] | null | null | null | src/main/cpp/utils/utils.h | DeathByKorea/nova-renderer | 3becf4216d798d7fc615b7990b266559f52db0af | [
"MIT"
] | null | null | null | /*!
* \brief Contains a bunch of utility functions which may or may not be actually used anywhere
*
* \author David
* \date 18-May-16.
*/
#ifndef RENDERER_UTILS_H
#define RENDERER_UTILS_H
#include <vector>
#include <string>
#include <algorithm>
#include <exception>
#include <json.hpp>
#include <fstream>
#include <easylogging++.h>
#include <glm/glm.hpp>
/*!
* \brief Initializes the logging system
*/
void initialize_logging();
namespace nova {
/*!
* \brief Calls the fucntion once for every element in the provided container
*
* \param container The container to perform an action for each element in
* \param thingToDo The action to perform for each element in the collection
*/
template <typename Cont, typename Func>
void foreach(Cont container, Func thingToDo) {
std::for_each(std::cbegin(container), std::cend(container), thingToDo);
};
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim);
/*!
* \brief Simple exception to represent that a resouce can not be found
*/
class resource_not_found : public std::exception {
public:
resource_not_found(const std::string& msg);
virtual const char * what() const noexcept;
private:
std::string message;
};
/*!
* \brief Loads a json data structure from the provided stream
*
* A couple assumptions are made here:
* - The stream is already open
* - The stream will return a valid JSON string
*
* If one or both of these is not true, this method will throw an exception
*
* Also worth noting: this function will close the stream. Do not try to
* use it after calling this function of you'll have a bad time
*/
nlohmann::json load_json_from_stream(std::istream& stream);
/*!
* \brief Stream insertion for glm::ivec3
*
* \param out The stream to write to
* \param vec The vector to write
* \return The written to stream
*/
el::base::Writer &operator<<(el::base::Writer &out, const glm::ivec3 &vec);
/*!
* \brief Stream insertion for glm::vec2
*
* \param out The stream to write to
* \param vec The vector to write
* \return The written to stream
*/
el::base::Writer &operator<<(el::base::Writer &out, const glm::vec2 &vec);
/*!
* \brief Stream insertion for glm::vec3
*
* \param out The stream to write to
* \param vec The vector to write
* \return The written to stream
*/
el::base::Writer &operator<<(el::base::Writer &out, const glm::vec3 &vec);
/*!
* \brief Stream insertion for glm::vec4
*
* \param out The stream to write to
* \param vec The vector to write
* \return The written to stream
*/
el::base::Writer &operator<<(el::base::Writer &out, const glm::vec4 &vec);
/*!
* \brief Stream insertion for glm::vec4
*
* \param out The stream to write to
* \param vec The vector to write
* \return The written to stream
*/
template <typename T>
el::base::Writer &operator<<(el::base::Writer &out, const std::vector<T> &vec) {
out << "(";
for(auto& val : vec) {
out << val << ", ";
}
out << ")";
return out;
}
std::string print_color(unsigned int color);
std::string print_array(int data[], int num_elements);
}
#endif //RENDERER_UTILS_H
| 27.294118 | 94 | 0.613416 | [
"vector"
] |
5ae9cb50443ab5d0116d7a1cd8b7e6920c27ccc1 | 3,832 | h | C | Dependencies/mysqlpp/wnp_connection.h | sosan/NoahGameFrame | 38c54014c5c4620b784b2c1d2cab256f42bae186 | [
"Apache-2.0"
] | 61 | 2016-10-13T09:24:31.000Z | 2022-03-26T09:59:34.000Z | Dependencies/mysqlpp/wnp_connection.h | sosan/NoahGameFrame | 38c54014c5c4620b784b2c1d2cab256f42bae186 | [
"Apache-2.0"
] | 3 | 2018-05-15T10:42:22.000Z | 2021-07-02T01:38:08.000Z | Dependencies/mysqlpp/wnp_connection.h | sosan/NoahGameFrame | 38c54014c5c4620b784b2c1d2cab256f42bae186 | [
"Apache-2.0"
] | 36 | 2016-12-28T04:54:41.000Z | 2021-12-15T06:02:56.000Z | /// \file wnp_connection.h
/// \brief Declares the WindowsNamedPipeConnection class.
/***********************************************************************
Copyright (c) 2007-2008 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the
CREDITS.txt file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#if !defined(MYSQLPP_WNP_CONNECTION_H)
#define MYSQLPP_WNP_CONNECTION_H
#include "connection.h"
namespace mysqlpp {
/// \brief Specialization of \c Connection for Windows named pipes
///
/// This class just simplifies the connection creation interface of
/// \c Connection. It does not add new functionality.
class MYSQLPP_EXPORT WindowsNamedPipeConnection : public Connection
{
public:
/// \brief Create object without connecting it to the MySQL server.
WindowsNamedPipeConnection() :
Connection()
{
}
/// \brief Create object and connect to database server over Windows
/// named pipes in one step.
///
/// \param db name of database to use
/// \param user user name to log in under, or 0 to use the user
/// name the program is running under
/// \param password password to use when logging in
WindowsNamedPipeConnection(const char* db, const char* user = 0,
const char* password = 0) :
Connection()
{
connect(db, user, password);
}
/// \brief Establish a new connection using the same parameters as
/// an existing connection.
///
/// \param other pre-existing connection to clone
WindowsNamedPipeConnection(const WindowsNamedPipeConnection& other) :
Connection(other)
{
}
/// \brief Destroy object
~WindowsNamedPipeConnection() { }
/// \brief Connect to database after object is created.
///
/// It's better to use the connect-on-create constructor if you can.
/// See its documentation for the meaning of these parameters.
///
/// If you call this method on an object that is already connected
/// to a database server, the previous connection is dropped and a
/// new connection is established.
bool connect(const char* db = 0, const char* user = 0,
const char* password = 0);
/// \brief Check that given string denotes a Windows named pipe
/// connection to MySQL
///
/// \param server the server address
///
/// \return false if server address does not denote a Windows
/// named pipe connection, or we are not running on Windows
static bool is_wnp(const char* server);
private:
/// \brief Provide uncallable versions of the parent class ctors we
/// don't want to provide so we don't get warnings about hidden
/// overloads with some compilers
WindowsNamedPipeConnection(bool) { }
WindowsNamedPipeConnection(const char*, const char*, const char*,
const char*, unsigned int) { }
/// \brief Explicitly override parent class version so we don't get
/// complaints about hidden overloads with some compilers
bool connect(const char*, const char*, const char*, const char*,
unsigned int) { return false; }
};
} // end namespace mysqlpp
#endif // !defined(MYSQLPP_WNP_CONNECTION_H)
| 33.911504 | 72 | 0.711378 | [
"object"
] |
5ae9fa2dbe17500dd89bf5aa61b654d9b2ce932f | 1,138 | h | C | vkoo/include/vkoo/st/hittables/Ray.h | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 129 | 2021-09-07T17:15:18.000Z | 2022-02-28T08:59:02.000Z | vkoo/include/vkoo/st/hittables/Ray.h | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 2 | 2021-10-03T07:30:20.000Z | 2022-01-06T16:05:41.000Z | vkoo/include/vkoo/st/hittables/Ray.h | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 11 | 2021-09-08T11:29:09.000Z | 2022-03-17T08:39:50.000Z | #pragma once
#include "vkoo/common.h"
namespace vkoo {
namespace st {
struct HitRecord {
HitRecord() { time = std::numeric_limits<float>::max(); }
float time;
glm::vec3 normal;
};
class Ray {
public:
Ray(const glm::vec3& origin, const glm::vec3& direction)
: origin_(origin), direction_(direction) {}
const glm::vec3& GetOrigin() const { return origin_; }
const glm::vec3& GetDirection() const { return direction_; }
void SetDirection(const glm::vec3& direction) { direction_ = direction; }
glm::vec3 At(float t) const { return origin_ + t * direction_; }
void ApplyTransform(const glm::mat4& transform) {
glm::vec3 ref = At(1.0f);
glm::vec4 new_origin = transform * glm::vec4(origin_, 1.0f);
origin_ = glm::vec3(new_origin / new_origin.w);
glm::vec4 new_ref = transform * glm::vec4(ref, 1.0f);
ref = glm::vec3(new_ref / new_ref.w);
direction_ = ref - origin_;
// Note: do not normalize direction_ here since we want
// ref to always be At(1.0) before/after transform.
}
private:
glm::vec3 origin_;
glm::vec3 direction_;
};
} // namespace st
} // namespace vkoo | 25.863636 | 75 | 0.662566 | [
"transform"
] |
5af9e17dc4e9dad8294357a6730ca8ac127607bd | 2,152 | c | C | kernel/src/interrupts/impl/exceptions.c | Gon-Namprasertkul/OmegaOS | 6c27a43758d966264c0dae68404cb5411466c62f | [
"Apache-2.0"
] | null | null | null | kernel/src/interrupts/impl/exceptions.c | Gon-Namprasertkul/OmegaOS | 6c27a43758d966264c0dae68404cb5411466c62f | [
"Apache-2.0"
] | null | null | null | kernel/src/interrupts/impl/exceptions.c | Gon-Namprasertkul/OmegaOS | 6c27a43758d966264c0dae68404cb5411466c62f | [
"Apache-2.0"
] | null | null | null | #include "../exceptions.h"
static void crapout(int_frame_t* frame, uint16_t vector) {
kwrite("\n\033[41;1;37mFATAL CPU EXCEPTION: ");
kwrite((char*)hex2str(vector));
kwrite("\n*** KERNEL PANIC ***\n\n");
kwrite("<==== INTERRUPT FRAME DUMP ====>\n\n");
kwrite("RIP: ");
kwrite((char*)hex2str(frame->rip));
kwrite("\nCS: ");
kwrite((char*)hex2str(frame->cs));
kwrite("\nRFLAGS: ");
kwrite((char*)hex2str(frame->rflags));
kwrite("\nRSP: ");
kwrite((char*)hex2str(frame->rsp));
kwrite("\nSS: ");
kwrite((char*)hex2str(frame->ss));
kwrite("\n\n*** SYSTEM HALTED ***\n");
__asm__ __volatile__("hlt");
}
__attribute__((interrupt)) void div0_handler(int_frame_t* frame) {
crapout(frame, 0x0);
}
__attribute__((interrupt)) void debug_excp_handler(int_frame_t* frame) {
crapout(frame, 0x1);
}
__attribute__((interrupt)) void breakpoint_handler(int_frame_t* frame) {
crapout(frame, 0x3);
}
__attribute__((interrupt)) void overflow_handler(int_frame_t* frame) {
crapout(frame, 0x4);
}
__attribute__((interrupt)) void bre_handler(int_frame_t* frame) {
crapout(frame, 0x5);
}
__attribute__((interrupt)) void invld_opcode_handler(int_frame_t* frame) {
crapout(frame, 0x6);
}
__attribute__((interrupt)) void device_not_avail_handler(int_frame_t* frame) {
crapout(frame, 0x7);
}
__attribute__((interrupt)) void double_fault_handler(int_frame_t* frame) {
crapout(frame, 0x8);
}
__attribute__((interrupt)) void cso_handler(int_frame_t* frame) {
crapout(frame, 0x9);
}
__attribute__((interrupt)) void invalid_tss_handler(int_frame_t* frame) {
crapout(frame, 0xA);
}
__attribute__((interrupt)) void snp_handler(int_frame_t* frame) {
crapout(frame, 0xB);
}
__attribute__((interrupt)) void ssf_handler(int_frame_t* frame) {
crapout(frame, 0xC);
}
__attribute__((interrupt)) void gpf_handler(int_frame_t* frame) {
crapout(frame, 0xD);
}
__attribute__((interrupt)) void page_fault_handler(int_frame_t* frame) {
crapout(frame, 0xE);
}
__attribute__((interrupt)) void fpe_handler(int_frame_t* frame) {
crapout(frame, 0xF);
}
| 22.652632 | 78 | 0.684015 | [
"vector"
] |
8501a100ebb5bfab29155a07b49696d116d3e8e0 | 2,394 | h | C | source/seqsolo/cntProLSClass.h | kuolinhsu/SOLO | af7804a523dd4ab79371d9e1c78e23946926c0be | [
"BSD-3-Clause"
] | 1 | 2021-01-17T20:53:39.000Z | 2021-01-17T20:53:39.000Z | source/seqsolo/cntProLSClass.h | kuolinhsu/SOLO | af7804a523dd4ab79371d9e1c78e23946926c0be | [
"BSD-3-Clause"
] | null | null | null | source/seqsolo/cntProLSClass.h | kuolinhsu/SOLO | af7804a523dd4ab79371d9e1c78e23946926c0be | [
"BSD-3-Clause"
] | 1 | 2021-05-04T17:55:08.000Z | 2021-05-04T17:55:08.000Z | // *********************************************
// CLASS HEAD FILE: CounterPropagation LEAST SQUARE Networks
// Kuo-lin Hsu
// Feb. 5, 1998
// *********************************************
# ifndef _CNTPROLSCLASS_H_
# define _CNTPROLSCLASS_H_
# include <iostream>
# include <cstdlib>
# include <cmath>
# include "MATRIX.h"
class cntProLSClass {
//protected:
public:
int sofmNode, nVars;
int indexX, indexY;
int cntFreq;
float ***wIn, ***wOut;
float *data1;
float ***eValue, ****eVector;
float *yPc;
float noObsData;
//public:
// COUNSTRUCTOR:
cntProLSClass(){};
// INITIAL NETWORK STRUCTURE:
void cnt_init(int node, int vars, int cntFreq1,
float *** wI, float ***wO, float *da1, float ***eValue, float ****eVector, float noDataFlag);
// PUT INPUT:
void putInputData(float *da1) {data1 = da1;}
// PUT INPUT-HIDDEN AND HIDDEN-OUTPUT WEIGHTS:
void putWinWoutWeights(float ***wI, float ***wO) {wIn = wI; wOut = wO;}
// MODIFY EIGEN VECTORS AND VALUES:
void modifyEigenValues
(int indx, int indy, float *eValue2, float **eVector2);
// FIND HIDDEN-OUTPUT AND MINIMUM DISTANCE NODE:
void findMinDisHiddenOutput();
// FIND SIMULATION HIDDEN-OUTPUT AND MINIMUM DISTANCE NODE:
void findMinDisHiddenOutput(long **freqTab);
// PRODUCE OUTPUT FROM HIDDEN-OUTPUTS:
void produceOutput(float *z);
// PRODUCE OUTPUT FROM HIDDEN-OUTPUTS:
void produceOutput(int idx, int idy, float *z);
// GENERATE SIGNLE OUTPUT:
void produceOutputFromSingleInput(float *z1);
// GENERATE SIGNLE OUTPUT:
void produceOutputFromSingleInput(long **freqTab, float *z1);
// PRODUCE RMSE FROM OBSERVATION AND MODEL OUTPUT:
void produceRMSE(long nda, float **data, float *zobs, float *rmse);
// PRODUCE RMSE FROM OBSERVATION AND MODEL OUTPUT:
void produceRMSE(int idx, int idy, long nda, float **data, float *zobs, float *rmse);
// PRODUCE RMSE FROM OBSERVATION AND MODEL OUTPUT:
void produceRMSE(long **freqTab, long nda, float **data, float *zobs, float *rmse);
// REAL TIME TRAINING PROCESS:
void realTimeTraining(float learningRate, long **freqTab, float *daX1, float *z1obs);
// PASS Win and Wout:
void passWinWout(float ***wI, float ***wO) {wI = wIn; wO = wOut;}
// MODIFY HIDDEN-OUTPUT WEIGHTS:
void modifyTriggeredHidOutWeights(int idx, int Idy, float *para);
//DESTRUCTOR:
~cntProLSClass(){};
};
# endif
| 27.204545 | 94 | 0.668338 | [
"model"
] |
c1c320e1c406a5e044ee08fe45b0002289730c28 | 2,856 | h | C | mysql-dst/mysql-cluster/client/dump/abstract_mysql_chain_element_extension.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/client/dump/abstract_mysql_chain_element_extension.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/client/dump/abstract_mysql_chain_element_extension.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /*
Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ABSTRACT_MYSQL_CHAIN_ELEMENT_EXTENSION_INCLUDED
#define ABSTRACT_MYSQL_CHAIN_ELEMENT_EXTENSION_INCLUDED
#include "i_chain_element.h"
#include "i_connection_provider.h"
#include "base/message_data.h"
#include "nullable.h"
#include "i_callable.h"
#include "mysql_chain_element_options.h"
#include "abstract_data_object.h"
#define MYSQL_UNIVERSAL_CLIENT_CHARSET "utf8"
#define MAX_NAME_LEN (64 * 3)
namespace Mysql{
namespace Tools{
namespace Dump{
class Abstract_mysql_chain_element_extension : public virtual I_chain_element
{
protected:
Abstract_mysql_chain_element_extension(
I_connection_provider* connection_provider,
Mysql::I_callable<bool, const Mysql::Tools::Base::Message_data&>*
message_handler, const Mysql_chain_element_options* options);
Mysql::Tools::Base::Mysql_query_runner* get_runner() const;
I_connection_provider* get_connection_provider() const;
uint64 get_server_version();
std::string get_server_version_string();
int compare_no_case_latin_with_db_string(
const std::string& latin_name, const std::string& db_name);
/**
Gets CREATE statement for specified object. If object type is database,
then object_name should be empty.
*/
Mysql::Nullable<std::string> get_create_statement(
Mysql::Tools::Base::Mysql_query_runner* runner,
const std::string& database_name, const std::string& object_name,
const std::string& object_type, uint field_id= 1);
/**
Quotes char string, taking into account compatible mode.
*/
std::string quote_name(const std::string& name);
std::string get_quoted_object_full_name(const Abstract_data_object* object);
std::string get_quoted_object_full_name(
const std::string& database_name, const std::string& object_name);
const Mysql_chain_element_options* get_mysql_chain_element_options() const;
CHARSET_INFO* get_charset() const;
private:
I_connection_provider* m_connection_provider;
Mysql::I_callable<bool, const Mysql::Tools::Base::Message_data&>*
m_message_handler;
const Mysql_chain_element_options* m_options;
CHARSET_INFO* m_charset;
};
}
}
}
#endif
| 31.043478 | 78 | 0.77556 | [
"object"
] |
c1c71a766175cd527212aea4de2a6e865febad9e | 2,542 | h | C | Labyrint/labyball/Classes/Native/mscorlib_System_Collections_ArrayList_ReadOnlyArra2159356062MethodDeclarations.h | mimietti/Labyball | c4b03f5b5d5ec1a1cae5831d22391bc2a171230f | [
"MIT"
] | null | null | null | Labyrint/labyball/Classes/Native/mscorlib_System_Collections_ArrayList_ReadOnlyArra2159356062MethodDeclarations.h | mimietti/Labyball | c4b03f5b5d5ec1a1cae5831d22391bc2a171230f | [
"MIT"
] | 23 | 2016-07-21T13:03:02.000Z | 2016-10-03T12:43:01.000Z | Labyrint/labyrinti1/Classes/Native/mscorlib_System_Collections_ArrayList_ReadOnlyArra2159356062MethodDeclarations.h | mimietti/Labyball | c4b03f5b5d5ec1a1cae5831d22391bc2a171230f | [
"MIT"
] | 1 | 2019-09-08T17:32:17.000Z | 2019-09-08T17:32:17.000Z | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Collections.ArrayList/ReadOnlyArrayListWrapper
struct ReadOnlyArrayListWrapper_t2159356062;
// System.Collections.ArrayList
struct ArrayList_t2121638921;
// System.String
struct String_t;
// System.Object
struct Il2CppObject;
// System.Collections.IComparer
struct IComparer_t2207526184;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Collections_ArrayList2121638921.h"
#include "mscorlib_System_Object837106420.h"
// System.Void System.Collections.ArrayList/ReadOnlyArrayListWrapper::.ctor(System.Collections.ArrayList)
extern "C" void ReadOnlyArrayListWrapper__ctor_m471776423 (ReadOnlyArrayListWrapper_t2159356062 * __this, ArrayList_t2121638921 * ___innerArrayList0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.String System.Collections.ArrayList/ReadOnlyArrayListWrapper::get_ErrorMessage()
extern "C" String_t* ReadOnlyArrayListWrapper_get_ErrorMessage_m1411886211 (ReadOnlyArrayListWrapper_t2159356062 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.Collections.ArrayList/ReadOnlyArrayListWrapper::get_IsReadOnly()
extern "C" bool ReadOnlyArrayListWrapper_get_IsReadOnly_m2940664529 (ReadOnlyArrayListWrapper_t2159356062 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Object System.Collections.ArrayList/ReadOnlyArrayListWrapper::get_Item(System.Int32)
extern "C" Il2CppObject * ReadOnlyArrayListWrapper_get_Item_m1660065334 (ReadOnlyArrayListWrapper_t2159356062 * __this, int32_t ___index0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Collections.ArrayList/ReadOnlyArrayListWrapper::set_Item(System.Int32,System.Object)
extern "C" void ReadOnlyArrayListWrapper_set_Item_m1186907789 (ReadOnlyArrayListWrapper_t2159356062 * __this, int32_t ___index0, Il2CppObject * ___value1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Collections.ArrayList/ReadOnlyArrayListWrapper::Sort()
extern "C" void ReadOnlyArrayListWrapper_Sort_m749027708 (ReadOnlyArrayListWrapper_t2159356062 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Collections.ArrayList/ReadOnlyArrayListWrapper::Sort(System.Collections.IComparer)
extern "C" void ReadOnlyArrayListWrapper_Sort_m480650942 (ReadOnlyArrayListWrapper_t2159356062 * __this, Il2CppObject * ___comparer0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| 57.772727 | 201 | 0.849331 | [
"object"
] |
c1d0b1b0bcc5140a1e7dfd1531e2edc6dad7ec40 | 2,720 | h | C | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT362Listener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT362Listener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT362Listener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null |
#include "repository/ISwiftMtParser.h"
#include "SwiftMtMessage.pb.h"
#include <vector>
#include <string>
#include "BaseErrorListener.h"
#include "SwiftMtParser_MT362Lexer.h"
// Generated from C:/programming/message-converter-c/message/generation/swift-mt-generation/repository/SR2018/grammars/SwiftMtParser_MT362.g4 by ANTLR 4.7.2
#pragma once
#include "antlr4-runtime.h"
#include "SwiftMtParser_MT362Parser.h"
namespace message::definition::swift::mt::parsers::sr2018 {
/**
* This interface defines an abstract listener for a parse tree produced by SwiftMtParser_MT362Parser.
*/
class SwiftMtParser_MT362Listener : public antlr4::tree::ParseTreeListener {
public:
virtual void enterMessage(SwiftMtParser_MT362Parser::MessageContext *ctx) = 0;
virtual void exitMessage(SwiftMtParser_MT362Parser::MessageContext *ctx) = 0;
virtual void enterBh(SwiftMtParser_MT362Parser::BhContext *ctx) = 0;
virtual void exitBh(SwiftMtParser_MT362Parser::BhContext *ctx) = 0;
virtual void enterBh_content(SwiftMtParser_MT362Parser::Bh_contentContext *ctx) = 0;
virtual void exitBh_content(SwiftMtParser_MT362Parser::Bh_contentContext *ctx) = 0;
virtual void enterAh(SwiftMtParser_MT362Parser::AhContext *ctx) = 0;
virtual void exitAh(SwiftMtParser_MT362Parser::AhContext *ctx) = 0;
virtual void enterAh_content(SwiftMtParser_MT362Parser::Ah_contentContext *ctx) = 0;
virtual void exitAh_content(SwiftMtParser_MT362Parser::Ah_contentContext *ctx) = 0;
virtual void enterUh(SwiftMtParser_MT362Parser::UhContext *ctx) = 0;
virtual void exitUh(SwiftMtParser_MT362Parser::UhContext *ctx) = 0;
virtual void enterTr(SwiftMtParser_MT362Parser::TrContext *ctx) = 0;
virtual void exitTr(SwiftMtParser_MT362Parser::TrContext *ctx) = 0;
virtual void enterSys_block(SwiftMtParser_MT362Parser::Sys_blockContext *ctx) = 0;
virtual void exitSys_block(SwiftMtParser_MT362Parser::Sys_blockContext *ctx) = 0;
virtual void enterSys_element(SwiftMtParser_MT362Parser::Sys_elementContext *ctx) = 0;
virtual void exitSys_element(SwiftMtParser_MT362Parser::Sys_elementContext *ctx) = 0;
virtual void enterSys_element_key(SwiftMtParser_MT362Parser::Sys_element_keyContext *ctx) = 0;
virtual void exitSys_element_key(SwiftMtParser_MT362Parser::Sys_element_keyContext *ctx) = 0;
virtual void enterSys_element_content(SwiftMtParser_MT362Parser::Sys_element_contentContext *ctx) = 0;
virtual void exitSys_element_content(SwiftMtParser_MT362Parser::Sys_element_contentContext *ctx) = 0;
virtual void enterMt(SwiftMtParser_MT362Parser::MtContext *ctx) = 0;
virtual void exitMt(SwiftMtParser_MT362Parser::MtContext *ctx) = 0;
};
} // namespace message::definition::swift::mt::parsers::sr2018
| 40.597015 | 156 | 0.802574 | [
"vector"
] |
c1ddc0f8ec39b837808d5f7915c09abd5795a862 | 5,484 | h | C | s32v234_sdk/demos/isp/max9286_96705_4channel_uyvy/inc/FinalScene.h | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/demos/isp/max9286_96705_4channel_uyvy/inc/FinalScene.h | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/demos/isp/max9286_96705_4channel_uyvy/inc/FinalScene.h | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | 2 | 2021-01-21T02:06:16.000Z | 2021-01-28T10:47:37.000Z | #ifndef _FINAL_SCENE_H__
#define _FINAL_SCENE_H__
#include <memory>
#include "nanovg.h"
#include "const_value.h"
#include "GLES2/gl2.h"
#include "opencv2/core.hpp"
#include "DrawScene.h"
#include "OGLWin.h"
//代表最终展示的界面类,初始展示时调用onStart,结束展示时调用onStop,并可以根据用户的输入执行不同的控制代码
//使用renderToSreen渲染界面
#include "LUT.h"
#include "utils.hpp"
#include "RadarView.hpp"
#include "DistanceLine.hpp"
#include "TransBot.h"
#include "BirdEyeView.hpp"
#include "PlaneExpandView.hpp"
#include "BoxExpandView.hpp"
#include "imgproc/smooth.hpp"
#include <thread>
#include <mutex>
enum class SceneMode
{
Scene2D,
Scene3D,
SceneSingle,
Scene2DWith3D,
Scene2DWithSingle,
Scene2DWithZoomFront,
Scene2DWithZoomRear,
Scene2DWithZoomLeft,
Scene2DWithZoomRight,
Scene2DWithZoomLeftRight
};
class CFinalScene
{
public:
CFinalScene();
~CFinalScene(void);
public:
void changeView();
void onStart();
void onStop();
void renderToSreen(); //渲染界面
void onMessage(int message); //响应消息
void onButtonUp(int times);
void onButtonDown(int times);
void onButtonLeft(int times);
void onButtonRight(int times);
void onButtonOK();
void endPreviousMode(int mode);
void beginCurrentMode(int mode);
void switchMode();
void onButtonZoomIn(int times);
void onButtonZoomOut(int times);
void onButtonMoveLeft(int times);
void onButtonMoveRight(int times);
void onButtonMoveUp(int times);
void onButtonMoveDown(int times);
void onButtonTurnLeft(int times)
{
steeringAngle = clamp(steeringAngle - steeringStep, minAngle, maxAngle);
}
void onButtonTurnRight(int times)
{
steeringAngle = clamp(steeringAngle + steeringStep, minAngle, maxAngle);
}
void onButtonSwitchMode(SceneMode mode);
inline void setBirdEyeViewport(int x, int y, int width, int height)
{
birdEyeViewX = x;
birdEyeViewY = y;
birdEyeViewWidth = width;
birdEyeViewHeight = height;
setBirdEyeViewParams(*lut);
}
inline void setSingleViewport(int x, int y, int width, int height)
{
singleViewX = x;
singleViewY = y;
singleViewWidth = width;
singleViewHeight = height;
//setSingleViewParams(singleViewWidth, singleViewHeight);
setSingleViewParams(1110, 810);
}
inline void set3DViewport(int x, int y, int width, int height)
{
threeDViewX = x;
threeDViewY = y;
threeDViewWidth = width;
threeDViewHeight = height;
}
void render2DView(int x, int y, int width, int height,void* data, GLuint fbo = 0);
void render2DViewCrop(int x, int y, int width, int height, void* data, const glm::mat4& transform = glm::mat4(1.0), GLuint fbo = 0);
void render2DViewCropViewport(int cropWidth, int cropHeight, int viewX, int viewY, int viewWidth, int viewHeight, void* data, const glm::mat4& transform = glm::mat4(1.0), GLuint fbo = 0);
void render3DView(int x, int y, int width, int height, void* data, GLuint fbo = 0);
void renderSingleView(int camID,int x, int y, int width, int height, const glm::mat4& transform = glm::mat4(1.0));
void renderImage(const char* path, int x, int y, int width, int height, const glm::mat4& transform = glm::mat4(1.0));
void renderTrail(int x, int y, int width, int height, bool applyTransform = false, GLuint fbo = 0);
void renderTexView(GLint textureID, int x, int y, int width, int height, glm::mat4 transMatrix = glm::mat4(1.0));
void copyFBOTexture(GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
/**
* 渲染文本框
*
* @param text 要渲染的文字,编码必须为 UTF-8
* @param x 文本框左上角位置 (坐标原点在屏幕左上角)
* @param y
* @param rowWidth 行宽,文本超过行宽会换行。(默认为当前屏幕宽度)
* @param fontSize 字体大小
* @param textColor 字体颜色 (RGBA) (默认不透明白色)
* @param boxColor 文本框的填充色 (RGBA) (默认全透明色)
*/
void renderTextBox(const char* text, int x, int y, int fontSize,
int rowWidth = getScreenWidth(),
const NVGcolor& textColor = nvgRGBAf(1, 1, 1, 1),
const NVGcolor& boxColor = nvgRGBAf(1, 1, 1, 0));
void setRegionHighlight(int regionId);
void unsetRegionHighlight(int regionId);
// 透明车底
// 2. 里程计数据
Encoder encoderData;
// 3. 透明车底类
bool reset;
private:
int m_endView;
int m_curView;
float m_phei[4];
float m_theta[4];
GLuint m_imageTextureID[const_value::CAMERANUM];
GLvoid *m_dataBuffer[const_value::CAMERANUM];
static const int ADJUST_TIMES = 8;
GLuint fbo, rbo, dstTex;
static const int lumEqualRate = 15;
std::shared_ptr<CalibLUT> lut;
RadarView radar;
float radarSignals[16] = {0};
std::mutex radarSignalMutex;
DistanceLineView disLine;
std::shared_ptr<NVGcontext> vgCtx;
//SceneMode mode = SceneMode::Scene2DWith3D;
SceneMode mode = SceneMode::Scene2DWithSingle;
const float steeringStep = M_PI / 180.0;
const float minAngle = steeringStep * -31.0;
const float maxAngle = steeringStep * 31.0;
float steeringAngle = minAngle;
bool isRegionHighlighted[const_value::REGION_NUM];
static float highlightColor[4]; // RGBA
static float blankColor[4];
int dynamicLineFlag = 31;
GLuint Calib_BirdView_TextureID[1];
int birdEyeViewX, birdEyeViewY, birdEyeViewWidth, birdEyeViewHeight;
int singleViewX, singleViewY, singleViewWidth, singleViewHeight;
int threeDViewX, threeDViewY, threeDViewWidth, threeDViewHeight;
BirdEyeView bev;
PlaneExpandView pevs[const_value::CAMERANUM];
BoxExpandView boxViews[2];
ExposureCompensation exposureComp;
int vgFontId;
std::map<std::string, int> images;
// 透明车底
// 1. 前一帧的帧缓存
GLuint fboPre, dstTexPre;
// 2. 里程计数据
//Encoder encoderData;
// 3. 透明车底类
TransBot *transBotC;
//bool reset;
};
#endif
| 26.114286 | 188 | 0.729577 | [
"transform"
] |
c1f0839d3ae1f4578d1d331a4f746c54d1b45798 | 3,766 | h | C | src/GraphicsEngine3D/OpenGLEngine/GLEController.h | StefanMermans/GraphicsEngine | 4310c9ace8f4daaedb6ab62a90aea85bc8f695aa | [
"MIT"
] | 1 | 2018-02-06T15:28:32.000Z | 2018-02-06T15:28:32.000Z | src/GraphicsEngine3D/OpenGLEngine/GLEController.h | StefanMermans/GraphicsEngine | 4310c9ace8f4daaedb6ab62a90aea85bc8f695aa | [
"MIT"
] | null | null | null | src/GraphicsEngine3D/OpenGLEngine/GLEController.h | StefanMermans/GraphicsEngine | 4310c9ace8f4daaedb6ab62a90aea85bc8f695aa | [
"MIT"
] | null | null | null | #ifndef GLE_CONTROLLER_H
#define GLE_CONTROLLER_H
#include <vector>
#include "GLEModel.h"
#include "../Core/Vertex.h"
#include "GLEKey.h"
#include "../OpenGLEngine/Controller/GLEMouse.h"
#include "../OpenGLEngine/Controller/GLECamera.h"
#define GLE_MOUSE_BUTTON_NONE -1
#define GLE_KEY_COUNT sizeof(unsigned char) * 255
static const std::vector<Core::Vertex> CUBE_VERTS = {
{ { -0.5f, -0.5f, -0.5f },{ 1, 0, 0,1 },{ 0.0f, 0.0f },{ 0.0f, 0.0f, -1.0f } },
{ { 0.5f, -0.5f, -0.5f },{ 0, 1, 0,1 },{ 1.0f, 0.0f },{ 0.0f, 0.0f, -1.0f } },
{ { 0.5f, 0.5f, -0.5f },{ 0, 0, 1,1 },{ 1.0f, 1.0f },{ 0.0f, 0.0f, -1.0f } },
{ { 0.5f, 0.5f, -0.5f },{ 0, 0, 1,1 },{ 1.0f, 1.0f },{ 0.0f, 0.0f, -1.0f } },
{ { -0.5f, 0.5f, -0.5f },{ 0, 1, 0,1 },{ 0.0f, 1.0f },{ 0.0f, 0.0f, -1.0f } },
{ { -0.5f, -0.5f, -0.5f },{ 1, 0, 0,1 },{ 0.0f, 0.0f },{ 0.0f, 0.0f, -1.0f } },
{ { -0.5f, -0.5f, 0.5f },{ 1, 0, 0,1 },{ 0.0f, 0.0f },{ 0.0f, 0.0f, 1.0f } },
{ { 0.5f, -0.5f, 0.5f },{ 0, 1, 0,1 },{ 1.0f, 0.0f },{ 0.0f, 0.0f, 1.0f } },
{ { 0.5f, 0.5f, 0.5f },{ 0, 0, 1,1 },{ 1.0f, 1.0f },{ 0.0f, 0.0f, 1.0f } },
{ { 0.5f, 0.5f, 0.5f },{ 0, 0, 1,1 },{ 1.0f, 1.0f },{ 0.0f, 0.0f, 1.0f } },
{ { -0.5f, 0.5f, 0.5f },{ 0, 1, 0,1 },{ 0.0f, 1.0f },{ 0.0f, 0.0f, 1.0f } },
{ { -0.5f, -0.5f, 0.5f },{ 1, 0, 0,1 },{ 0.0f, 0.0f },{ 0.0f, 0.0f, 1.0f } },
{ { -0.5f, 0.5f, 0.5f },{ 1, 0, 0,1 },{ 1.0f, 0.0f },{ -1.0f, 0.0f, 0.0f } },
{ { -0.5f, 0.5f, -0.5f },{ 0, 1, 0,1 },{ 1.0f, 1.0f },{ -1.0f, 0.0f, 0.0f } },
{ { -0.5f, -0.5f, -0.5f },{ 0, 0, 1,1 },{ 0.0f, 1.0f },{ -1.0f, 0.0f, 0.0f } },
{ { -0.5f, -0.5f, -0.5f },{ 0, 0, 1,1 },{ 0.0f, 1.0f },{ -1.0f, 0.0f, 0.0f } },
{ { -0.5f, -0.5f, 0.5f },{ 0, 1, 0,1 },{ 0.0f, 0.0f },{ -1.0f, 0.0f, 0.0f } },
{ { -0.5f, 0.5f, 0.5f },{ 1, 0, 0,1 },{ 1.0f, 0.0f },{ -1.0f, 0.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.5f },{ 1, 0, 0,1 },{ 1.0f, 0.0f },{ 1.0f, 0.0f, 0.0f } },
{ { 0.5f, 0.5f, -0.5f },{ 0, 1, 0,1 },{ 1.0f, 1.0f },{ 1.0f, 0.0f, 0.0f } },
{ { 0.5f, -0.5f, -0.5f },{ 0, 0, 1,1 },{ 0.0f, 1.0f },{ 1.0f, 0.0f, 0.0f } },
{ { 0.5f, -0.5f, -0.5f },{ 0, 0, 1,1 },{ 0.0f, 1.0f },{ 1.0f, 0.0f, 0.0f } },
{ { 0.5f, -0.5f, 0.5f },{ 0, 1, 0,1 },{ 0.0f, 0.0f },{ 1.0f, 0.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.5f },{ 1, 0, 0,1 },{ 1.0f, 0.0f },{ 1.0f, 0.0f, 0.0f } },
{ { -0.5f, -0.5f, -0.5f },{ 1, 0, 0,1 },{ 0.0f, 1.0f },{ 0.0f, -1.0f, 0.0f } },
{ { 0.5f, -0.5f, -0.5f },{ 0, 1, 0,1 },{ 1.0f, 1.0f },{ 0.0f, -1.0f, 0.0f } },
{ { 0.5f, -0.5f, 0.5f },{ 0, 0, 1,1 },{ 1.0f, 0.0f },{ 0.0f, -1.0f, 0.0f } },
{ { 0.5f, -0.5f, 0.5f },{ 0, 0, 1,1 },{ 1.0f, 0.0f },{ 0.0f, -1.0f, 0.0f } },
{ { -0.5f, -0.5f, 0.5f },{ 0, 1, 0,1 },{ 0.0f, 0.0f },{ 0.0f, -1.0f, 0.0f } },
{ { -0.5f, -0.5f, -0.5f },{ 1, 0, 0,1 },{ 0.0f, 1.0f },{ 0.0f, -1.0f, 0.0f } },
{ { -0.5f, 0.5f, -0.5f },{ 1, 0, 0,1 },{ 0.0f, 1.0f },{ 0.0f, 1.0f, 0.0f } },
{ { 0.5f, 0.5f, -0.5f },{ 0, 1, 0,1 },{ 1.0f, 1.0f },{ 0.0f, 1.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.5f },{ 0, 0, 1,1 },{ 1.0f, 0.0f },{ 0.0f, 1.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.5f },{ 0, 0, 1,1 },{ 1.0f, 0.0f },{ 0.0f, 1.0f, 0.0f } },
{ { -0.5f, 0.5f, 0.5f },{ 0, 1, 0,1 },{ 0.0f, 0.0f },{ 0.0f, 1.0f, 0.0f } },
{ { -0.5f, 0.5f, -0.5f },{ 1, 0, 0,1 },{ 0.0f, 1.0f },{ 0.0f, 1.0f, 0.0f } }
};
class GLEController {
public:
GLEController();
~GLEController() = default;
void init();
void update(float deltaTime, Input * input);
void render(glm::mat4 view);
void reloadShaders();
std::vector<GLEModel*> models;
private:
GLECamera _camera;
const std::vector<Core::Vertex> _triangleVertices = {
{ { -1, -1, 0 },{ 1, 0, 0, 1 }},
{ { 1, -1, 0 },{ 0, 1, 0, 1 }},
{ { -1, 1, 0 },{ 0, 0, 1, 1}}
};
};
#endif // !GLE_CONTROLLER_H
| 47.075 | 82 | 0.415295 | [
"render",
"vector"
] |
c1f2511a95f3e13e7fe97a48d21425c7f655b805 | 6,786 | h | C | src/ray/raylet/local_scheduler_client.h | tashachin/ray | 43df405d07516ba4be8d1a7686c090fde2184b0b | [
"Apache-2.0"
] | 1 | 2021-05-16T06:37:59.000Z | 2021-05-16T06:37:59.000Z | src/ray/raylet/local_scheduler_client.h | tashachin/ray | 43df405d07516ba4be8d1a7686c090fde2184b0b | [
"Apache-2.0"
] | 1 | 2018-11-08T02:04:35.000Z | 2018-11-08T21:54:45.000Z | src/ray/raylet/local_scheduler_client.h | tashachin/ray | 43df405d07516ba4be8d1a7686c090fde2184b0b | [
"Apache-2.0"
] | null | null | null | #ifndef LOCAL_SCHEDULER_CLIENT_H
#define LOCAL_SCHEDULER_CLIENT_H
#include <mutex>
#include "ray/raylet/task_spec.h"
using ray::ObjectID;
using ray::JobID;
using ray::TaskID;
using ray::ActorID;
using ray::UniqueID;
struct LocalSchedulerConnection {
/** File descriptor of the Unix domain socket that connects to local
* scheduler. */
int conn;
/** The IDs of the GPUs that this client can use. NOTE(rkn): This is only used
* by legacy Ray and will be deprecated. */
std::vector<int> gpu_ids;
/// A map from resource name to the resource IDs that are currently reserved
/// for this worker. Each pair consists of the resource ID and the fraction
/// of that resource allocated for this worker.
std::unordered_map<std::string, std::vector<std::pair<int64_t, double>>> resource_ids_;
/// A mutex to protect stateful operations of the local scheduler client.
std::mutex mutex;
/// A mutext to protect write operations of the local scheduler client.
std::mutex write_mutex;
};
/**
* Connect to the local scheduler.
*
* @param local_scheduler_socket The name of the socket to use to connect to the
* local scheduler.
* @param worker_id A unique ID to represent the worker.
* @param is_worker Whether this client is a worker. If it is a worker, an
* additional message will be sent to register as one.
* @param driver_id The ID of the driver. This is non-nil if the client is a
* driver.
* @return The connection information.
*/
LocalSchedulerConnection *LocalSchedulerConnection_init(
const char *local_scheduler_socket, const UniqueID &worker_id, bool is_worker,
const JobID &driver_id, const Language &language);
/**
* Disconnect from the local scheduler.
*
* @param conn Local scheduler connection information returned by
* LocalSchedulerConnection_init.
* @return Void.
*/
void LocalSchedulerConnection_free(LocalSchedulerConnection *conn);
/// Submit a task using the raylet code path.
///
/// \param The connection information.
/// \param The execution dependencies.
/// \param The task specification.
/// \return Void.
void local_scheduler_submit_raylet(LocalSchedulerConnection *conn,
const std::vector<ObjectID> &execution_dependencies,
const ray::raylet::TaskSpecification &task_spec);
/**
* Notify the local scheduler that this client is disconnecting gracefully. This
* is used by actors to exit gracefully so that the local scheduler doesn't
* propagate an error message to the driver.
*
* @param conn The connection information.
* @return Void.
*/
void local_scheduler_disconnect_client(LocalSchedulerConnection *conn);
/// Get next task for this client. This will block until the scheduler assigns
/// a task to this worker. The caller takes ownership of the returned task
/// specification and must free it.
///
/// \param conn The connection information.
/// \return The assigned task.
ray::raylet::TaskSpecification *local_scheduler_get_task_raylet(
LocalSchedulerConnection *conn);
/**
* Tell the local scheduler that the client has finished executing a task.
*
* @param conn The connection information.
* @return Void.
*/
void local_scheduler_task_done(LocalSchedulerConnection *conn);
/**
* Tell the local scheduler to reconstruct or fetch objects.
*
* @param conn The connection information.
* @param object_ids The IDs of the objects to reconstruct.
* @param fetch_only Only fetch objects, do not reconstruct them.
* @return Void.
*/
void local_scheduler_reconstruct_objects(LocalSchedulerConnection *conn,
const std::vector<ObjectID> &object_ids,
bool fetch_only = false);
/**
* Notify the local scheduler that this client (worker) is no longer blocked.
*
* @param conn The connection information.
* @return Void.
*/
void local_scheduler_notify_unblocked(LocalSchedulerConnection *conn);
// /**
// * Get an actor's current task frontier.
// *
// * @param conn The connection information.
// * @param actor_id The ID of the actor whose frontier is returned.
// * @return A byte vector that can be traversed as an ActorFrontier flatbuffer.
// */
// const std::vector<uint8_t> local_scheduler_get_actor_frontier(
// LocalSchedulerConnection *conn,
// ActorID actor_id);
// /**
// * Set an actor's current task frontier.
// *
// * @param conn The connection information.
// * @param frontier An ActorFrontier flatbuffer to set the frontier to.
// * @return Void.
// */
// void local_scheduler_set_actor_frontier(LocalSchedulerConnection *conn,
// const std::vector<uint8_t> &frontier);
/// Wait for the given objects until timeout expires or num_return objects are
/// found.
///
/// \param conn The connection information.
/// \param object_ids The objects to wait for.
/// \param num_returns The number of objects to wait for.
/// \param timeout_milliseconds Duration, in milliseconds, to wait before
/// returning.
/// \param wait_local Whether to wait for objects to appear on this node.
/// \return A pair with the first element containing the object ids that were
/// found, and the second element the objects that were not found.
std::pair<std::vector<ObjectID>, std::vector<ObjectID>> local_scheduler_wait(
LocalSchedulerConnection *conn, const std::vector<ObjectID> &object_ids,
int num_returns, int64_t timeout_milliseconds, bool wait_local);
/// Push an error to the relevant driver.
///
/// \param conn The connection information.
/// \param The ID of the job that the error is for.
/// \param The type of the error.
/// \param The error message.
/// \param The timestamp of the error.
/// \return Void.
void local_scheduler_push_error(LocalSchedulerConnection *conn, const JobID &job_id,
const std::string &type, const std::string &error_message,
double timestamp);
/// Store some profile events in the GCS.
///
/// \param conn The connection information.
/// \param profile_events A batch of profiling event information.
/// \return Void.
void local_scheduler_push_profile_events(LocalSchedulerConnection *conn,
const ProfileTableDataT &profile_events);
/// Free a list of objects from object stores.
///
/// \param conn The connection information.
/// \param object_ids A list of ObjectsIDs to be deleted.
/// \param local_only Whether keep this request with local object store
/// or send it to all the object stores.
/// \return Void.
void local_scheduler_free_objects_in_object_store(
LocalSchedulerConnection *conn, const std::vector<ray::ObjectID> &object_ids,
bool local_only);
#endif
| 37.491713 | 90 | 0.712791 | [
"object",
"vector"
] |
c1f446240486d0dcb4a8446339611afb546f7fd7 | 3,578 | h | C | src/projectAPI/Robot.h | urbanoanderson/mazerobot | fc207abc859b9fa14b2ce3f71917099688c23df2 | [
"MIT"
] | 4 | 2018-09-21T23:09:14.000Z | 2018-09-22T11:33:07.000Z | src/projectAPI/Robot.h | urbanoanderson/maze-rpi-robot | fc207abc859b9fa14b2ce3f71917099688c23df2 | [
"MIT"
] | null | null | null | src/projectAPI/Robot.h | urbanoanderson/maze-rpi-robot | fc207abc859b9fa14b2ce3f71917099688c23df2 | [
"MIT"
] | 1 | 2018-09-21T23:09:48.000Z | 2018-09-21T23:09:48.000Z | #ifndef ROBOT_H_INCLUDED
#define ROBOT_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <math.h>
#include <string>
#include <unistd.h>
#include "RobotAPI.h"
#include "EnvMap.h"
#include "Utils.h"
#include "ObjectDetector.h"
class Robot
{
private:
//Mapa do ambiente
EnvMap envmap;
//Detector de Objetos
ObjectDetector objectDetector;
//Caminho do robô
std::vector< std::vector<float> > path; //Vetor de objetivos do robô
float goal[3]; //Objetivo atual
int current_goal; //Índice do objetivo atual no path
bool reached_goal; //Se chegou ao objetivo atual
bool loop_path; //Se é pra repetir o caminho quando terminar
bool finishedTask; //Se cumpriu todos os objetivos
int num_voltas; //Quantidade de voltas que o robô deu no percurso
//Posição do robô
Matrix realpos; //posição verdadeira de referencia da API do VREP
Matrix pos; //posição estimada pelo robô
//Leituras dos sonares
enum SONAR_ID { LEFT = 0, FRONT = 1, RIGHT = 2 };
float sonarReading[3]; //Vetor que contem a leitura dos sonares
float sensorLeftPos[3]; //Posicionamento do sensor esquerdo em relação ao robô
float sensorFrontPos[3]; //Posicionamento do sensor frontal em relação ao robô
float sensorRightPos[3]; //Posicionamento do sensor direito em relação ao robô
float SENSOR_DEVIATION; //Desvio padrão da medida de distancia fornecida pelo sonar
float SENSOR_OPENING_ANGLE; //Abertura em radianos do cone do sonar (metade da abertura)
//Constantes do controle de movimento
float MOTION_CONTROL_K_RHO;
float MOTION_CONTROL_K_ALPHA;
float MOTION_CONTROL_K_BETA;
float MOTION_CONTROL_MIN_V;
float MOTION_CONTROL_MAX_V;
float MOTION_CONTROL_DISTXY_THRESHOLD;
float MOTION_CONTROL_DISTTHETA_THRESHOLD;
//Variáveis da odometria
float ODOMETRY_KL;
float ODOMETRY_KR;
float ACUMULATED_DISTANCE_THRESHOLD;
float acumulatedDistance;
//Variáveis do Filtro de Kalman
Matrix sigmapos; //Matriz de covariância da posição estimada (modelo de incerteza)
Matrix R; //Matriz de covariância do sensor
float posdeviation[3]; //Desvio padrão da posição do robô
float DEVIATION_THRESHOLD_X; //Limiar em X para chamar atualização de percepção
float DEVIATION_THRESHOLD_Y; //Limiar em Y para chamar atualização de percepção
float DEVIATION_THRESHOLD_THETA; //Limiar em THETA para chamar atualização de percepção
float PERCETION_UPDATE_STEP_X;
float PERCETION_UPDATE_STEP_Y;
float PERCETION_UPDATE_STEP_THETA;
float PERCETION_UPDATE_STEP_SONAR;
//Funções auxiliares
void UpdateSonarReadings(); //Atualiza a leitura dos sonares do robô e armazena em sonarReading[]
void ManageObjectives(); //Gerencia os objetivos do robô
void MotionControl(); //Faz o robô andar em direção ao objetivo atual
void ActionUpdate(); //Atualiza pos e sigmapos após movimento do robô usando a odometria
bool PerceptionUpdateCondition(); //Decide quando fazer atualização de percepção
void PerceptionUpdate(); //Melhora a estimativa de posição do robô com os sensores e o mapa
Matrix EstimateXz(); //Faz uma estimativa da posição do robô com base nos sensores
float RobotToSensorPointDist(float x, float y, float theta, float Sx, float Sy, float Stheta, float sensorDist);
public:
//Funções principais de interface do robô
Robot(const char* INIT_FILENAME);
void Init(const char* INIT_FILENAME);
bool LoadPath(const char* PATH_FILENAME);
bool FinishedWork();
void Log();
void Update();
};
#endif
| 37.663158 | 114 | 0.74986 | [
"vector"
] |
c1f5f1dc9ffaae25acb707799c7f99835c729723 | 723 | h | C | moveitCpp/ros/MoveitPublisher.h | awied1404/COPING | 0fe36c1835928db15fb36f752ca83f8d2c2e33d4 | [
"MIT"
] | null | null | null | moveitCpp/ros/MoveitPublisher.h | awied1404/COPING | 0fe36c1835928db15fb36f752ca83f8d2c2e33d4 | [
"MIT"
] | null | null | null | moveitCpp/ros/MoveitPublisher.h | awied1404/COPING | 0fe36c1835928db15fb36f752ca83f8d2c2e33d4 | [
"MIT"
] | null | null | null | //
// Created by andreas on 19.11.20.
//
#ifndef MOVEIT_MOVEITPUBLISHER_H
#define MOVEIT_MOVEITPUBLISHER_H
#include "../config.h"
#ifdef USE_MOVEIT_PUB
#include "ros/ros.h"
#include <trajectory_msgs/JointTrajectoryPoint.h>
#include "own_msg/youBotJoints.h"
class MoveitPublisher
{
public:
MoveitPublisher(ros::NodeHandle &nodeHandle);
void publishMotion(bool lastMotion);
void addMotion(std::vector<trajectory_msgs::JointTrajectoryPoint> &);
void addGripperJointValues(std::vector<double> &);
private:
ros::Publisher publisher;
std::vector<double> gripperJointValues;
std::vector<trajectory_msgs::JointTrajectoryPoint> motion;
};
#endif /*USE_MOVEIT_PUB*/
#endif //MOVEIT_MOVEITPUBLISHER_H
| 24.1 | 73 | 0.763485 | [
"vector"
] |
de03dd4fc6f228054d9d4b4c7cb445855a823d98 | 5,416 | c | C | Reference/qpc/examples/workstation/dpp-comp/comp/philo.c | Harveyhubbell/Paid-RTOS | e56a1346cce026428c2bfef05b6a4e6bb2ee7f4e | [
"MIT"
] | null | null | null | Reference/qpc/examples/workstation/dpp-comp/comp/philo.c | Harveyhubbell/Paid-RTOS | e56a1346cce026428c2bfef05b6a4e6bb2ee7f4e | [
"MIT"
] | null | null | null | Reference/qpc/examples/workstation/dpp-comp/comp/philo.c | Harveyhubbell/Paid-RTOS | e56a1346cce026428c2bfef05b6a4e6bb2ee7f4e | [
"MIT"
] | null | null | null | /*.$file${Comp::.::philo.c} vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/
/*
* Model: dpp.qm
* File: ${Comp::.::philo.c}
*
* This code has been generated by QM 5.1.0 <www.state-machine.com/qm/>.
* DO NOT EDIT THIS FILE MANUALLY. All your changes will be lost.
*
* This program is open source 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.
*
* 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.
*/
/*.$endhead${Comp::.::philo.c} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
#include "qpc.h"
#include "dpp.h"
#include "bsp.h"
//Q_DEFINE_THIS_FILE
/* helper macros to provide a randomized think time for Philos */
#define THINK_TIME \
(QTimeEvtCtr)((BSP_random() % BSP_TICKS_PER_SEC) + (BSP_TICKS_PER_SEC/2U))
#define EAT_TIME \
(QTimeEvtCtr)((BSP_random() % BSP_TICKS_PER_SEC) + BSP_TICKS_PER_SEC)
/* Philo definition --------------------------------------------------------*/
/*.$skip${QP_VERSION} vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/
/*. Check for the minimum required QP version */
#if (QP_VERSION < 680U) || (QP_VERSION != ((QP_RELEASE^4294967295U) % 0x3E8U))
#error qpc version 6.8.0 or higher required
#endif
/*.$endskip${QP_VERSION} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
/*.$define${Comp::Philo} vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/
/*.${Comp::Philo} ..........................................................*/
/*.${Comp::Philo::ctor} ....................................................*/
void Philo_ctor(Philo * const me) {
QHsm_ctor(&me->super, Q_STATE_CAST(&Philo_initial));
CompTimeEvt_ctor(&me->timeEvt, AO_Table, &me->super, TIMEOUT_SIG, 0U);
}
/*.${Comp::Philo::SM} ......................................................*/
QState Philo_initial(Philo * const me, void const * const par) {
/*.${Comp::Philo::SM::initial} */
static uint8_t registered = (uint8_t)0; /* starts off with 0, per C-standard */
(void)e; /* suppress the compiler warning about unused parameter */
if (registered == (uint8_t)0) {
registered = (uint8_t)1;
QS_FUN_DICTIONARY(&Philo_initial);
QS_FUN_DICTIONARY(&Philo_thinking);
QS_FUN_DICTIONARY(&Philo_hungry);
QS_FUN_DICTIONARY(&Philo_eating);
}
return Q_TRAN(&Philo_thinking);
}
/*.${Comp::Philo::SM::thinking} ............................................*/
QState Philo_thinking(Philo * const me, QEvt const * const e) {
QState status_;
switch (e->sig) {
/*.${Comp::Philo::SM::thinking} */
case Q_ENTRY_SIG: {
QTimeEvt_armX(&me->timeEvt.super, THINK_TIME, 0U);
status_ = Q_HANDLED();
break;
}
/*.${Comp::Philo::SM::thinking} */
case Q_EXIT_SIG: {
QTimeEvt_disarm(&me->timeEvt.super);
status_ = Q_HANDLED();
break;
}
/*.${Comp::Philo::SM::thinking::TIMEOUT} */
case TIMEOUT_SIG: {
status_ = Q_TRAN(&Philo_hungry);
break;
}
/*.${Comp::Philo::SM::thinking::TEST} */
case TEST_SIG: {
status_ = Q_HANDLED();
break;
}
default: {
status_ = Q_SUPER(&QHsm_top);
break;
}
}
return status_;
}
/*.${Comp::Philo::SM::hungry} ..............................................*/
QState Philo_hungry(Philo * const me, QEvt const * const e) {
QState status_;
switch (e->sig) {
/*.${Comp::Philo::SM::hungry} */
case Q_ENTRY_SIG: {
/* asynchronously post event to the Container */
TableEvt *pe = Q_NEW(TableEvt, HUNGRY_SIG);
pe->philo = me;
QACTIVE_POST_LIFO(AO_Table, &pe->super);
status_ = Q_HANDLED();
break;
}
/*.${Comp::Philo::SM::hungry::EAT} */
case EAT_SIG: {
status_ = Q_TRAN(&Philo_eating);
break;
}
default: {
status_ = Q_SUPER(&QHsm_top);
break;
}
}
return status_;
}
/*.${Comp::Philo::SM::eating} ..............................................*/
QState Philo_eating(Philo * const me, QEvt const * const e) {
QState status_;
switch (e->sig) {
/*.${Comp::Philo::SM::eating} */
case Q_ENTRY_SIG: {
QTimeEvt_armX(&me->timeEvt.super, EAT_TIME, 0U);
status_ = Q_HANDLED();
break;
}
/*.${Comp::Philo::SM::eating} */
case Q_EXIT_SIG: {
QTimeEvt_disarm(&me->timeEvt.super);
/* asynchronously post event to the Container */
TableEvt *pe = Q_NEW(TableEvt, DONE_SIG);
pe->philo = me;
QACTIVE_POST_LIFO(AO_Table, &pe->super);
status_ = Q_HANDLED();
break;
}
/*.${Comp::Philo::SM::eating::TIMEOUT} */
case TIMEOUT_SIG: {
status_ = Q_TRAN(&Philo_thinking);
break;
}
default: {
status_ = Q_SUPER(&QHsm_top);
break;
}
}
return status_;
}
/*.$enddef${Comp::Philo} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
| 35.631579 | 83 | 0.531388 | [
"model"
] |
de091aa366b542d69b75d6fb0785c178f8b6ce3f | 421 | h | C | include/items/vPwmOut.h | ecrandz/IoTManager | 5d0eb71cfccccf9020b28be8c9fa5837988fb6ba | [
"MIT"
] | 37 | 2020-08-17T10:39:06.000Z | 2022-02-17T16:18:47.000Z | include/items/vPwmOut.h | ecrandz/IoTManager | 5d0eb71cfccccf9020b28be8c9fa5837988fb6ba | [
"MIT"
] | 11 | 2020-10-20T14:48:07.000Z | 2022-02-04T07:05:05.000Z | include/items/vPwmOut.h | ecrandz/IoTManager | 5d0eb71cfccccf9020b28be8c9fa5837988fb6ba | [
"MIT"
] | 43 | 2020-06-19T22:40:14.000Z | 2022-03-05T05:29:07.000Z | #ifdef EnablePwmOut
#pragma once
#include <Arduino.h>
#include "Consts.h"
#include "Global.h"
class PwmOut;
typedef std::vector<PwmOut> MyPwmOutVector;
class PwmOut {
public:
PwmOut(unsigned int pin, String key);
~PwmOut();
void execute(String state);
private:
unsigned int _pin;
String _key;
};
extern MyPwmOutVector* myPwmOut;
extern void pwmOut();
extern void pwmOutExecute();
#endif
| 14.517241 | 43 | 0.700713 | [
"vector"
] |
de0c52a55c9033949c2d1b5493fbf3b4ee51daca | 3,921 | h | C | src/fastertransformer/models/swin_int8/SwinINT8.h | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | src/fastertransformer/models/swin_int8/SwinINT8.h | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | src/fastertransformer/models/swin_int8/SwinINT8.h | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "src/fastertransformer/kernels/activation_kernels.h"
#include "src/fastertransformer/models/swin_int8/SwinBasicLayerINT8.h"
#include "src/fastertransformer/utils/allocator.h"
#include "src/fastertransformer/utils/conv2d.h"
#include "src/fastertransformer/utils/memory_utils.h"
namespace fastertransformer {
template<typename T>
class SwinTransformerINT8 {
private:
int int8_mode = 0;
int max_batch_ = 1;
int img_size_ = 224;
int patch_size_ = 4;
int in_chans_ = 3;
int embed_dim_ = 96;
int window_size_ = 7;
int* depths_;
int* num_heads_;
bool ape_ = false;
bool patch_norm_ = true;
float mlp_ratio_ = 4.0f;
bool qkv_bias_ = true;
int patches_resolution_ = 56;
int layer_num_ = 4;
int qk_scale_ = 1.0f;
size_t max_buf_size_ = 0;
size_t max_basic_layer_buf_size_ = 0;
size_t max_block_buf_size_ = 0;
size_t max_window_attention_buf_size_ = 0;
IAllocator* allocator_ = nullptr;
cudnnHandle_t cudnn_handle_;
cudaStream_t stream_;
cublasMMWrapper* cublas_wrapper_;
bool is_free_buffer_after_forward_;
bool is_allocate_buffer_ = false;
T* buf_ = nullptr;
T* x_patch_embed_ = nullptr;
T* basic_layer_output_ = nullptr;
// for avgPool_ones
T* avg_pool_ones_ = nullptr;
T* buffer_COL32 = nullptr;
SwinTransformerINT8BasicLayer<T>* basic_layer_ = nullptr;
static size_t getBufSize(const int batch, const int patches_resolution, const int layer_num, const int embed_dim);
void allocateBuffer();
void freeBuffer();
// input is [B, C_in, H, W]
// output is [B, H, W, C_out]
void patchEmbed(T* output,
const T* input,
const T* kernel,
const T* bias,
const T* gamma,
const T* beta,
const int batch,
const int img_size,
const int patch_size,
const int patches_resolution,
const int in_chans,
const int embed_dim,
const bool patch_norm);
public:
SwinTransformerINT8(int int8_mode,
int max_batch,
int img_size,
int patch_size,
int in_chans,
int embed_dim,
int window_size,
int* depths,
int* num_heads,
bool ape,
bool patch_norm,
int layer_num,
float mlp_ratio,
cudnnHandle_t cudnn_handle,
cudaStream_t stream,
cublasMMWrapper* cublas_wrapper,
IAllocator* allocator,
bool is_free_buffer_after_forward,
bool qkv_bias = true,
float qk_scale = 1.0f);
~SwinTransformerINT8();
void forward(std::vector<Tensor>* output_tensors,
const std::vector<Tensor>* input_tensors,
SwinTransformerINT8Weight<T>& swin_weights);
}; // class SwinTransformerINT8
} // namespace fastertransformer
| 33.512821 | 118 | 0.598572 | [
"vector"
] |
de0f5037285caab1fbfe0d423f6691a1e34a8173 | 885 | h | C | Post/source/ShapeWorksView2/MeshWorker.h | amylenz/ShapeWorks | 78c2ee067a23e31f5b83d0121e60addb1b0bf462 | [
"MIT"
] | null | null | null | Post/source/ShapeWorksView2/MeshWorker.h | amylenz/ShapeWorks | 78c2ee067a23e31f5b83d0121e60addb1b0bf462 | [
"MIT"
] | 1 | 2020-08-04T22:39:02.000Z | 2020-08-05T21:02:47.000Z | Post/source/ShapeWorksView2/MeshWorker.h | amylenz/ShapeWorks | 78c2ee067a23e31f5b83d0121e60addb1b0bf462 | [
"MIT"
] | null | null | null | /*
* Shapeworks license
*/
/**
* @file MeshWorker.h
* @brief Worker class for parallel mesh reconstruction
*
* The MeshWorker implements each threads mesh construction management
*/
#ifndef MESH_WORKER_H
#define MESH_WORKER_H
#include <QObject>
#include <QWaitCondition>
#include <MeshWorkQueue.h>
#include <MeshCache.h>
#include <MeshGenerator.h>
class MeshWorker : public QObject
{
Q_OBJECT
public:
void setWorkQueue( MeshWorkQueue* queue );
void setWorkingQueue( MeshWorkQueue* queue );
void setWorkDoneCondition( QWaitCondition* condition );
void setMeshCache( MeshCache* cache );
MeshGenerator* getMeshGenerator();
public Q_SLOTS:
void threadBegin();
private:
MeshGenerator meshGenerator;
MeshWorkQueue* workQueue;
MeshWorkQueue* workingQueue;
MeshCache* meshCache;
QWaitCondition* workDoneCondition;
};
#endif // ifndef MESH_WORKER_H
| 18.061224 | 70 | 0.755932 | [
"mesh"
] |
de105523279ab6e052ae62419d38095f771c3473 | 15,539 | h | C | include/sparse.h | nmakimoto/nmlib | dd518a7a61c9b1e41fd393659dc91691272c0565 | [
"MIT"
] | null | null | null | include/sparse.h | nmakimoto/nmlib | dd518a7a61c9b1e41fd393659dc91691272c0565 | [
"MIT"
] | null | null | null | include/sparse.h | nmakimoto/nmlib | dd518a7a61c9b1e41fd393659dc91691272c0565 | [
"MIT"
] | null | null | null | // Sparse matrix and solvers (CG/BiCG/PBCG)
#ifndef SPARSE_H
#define SPARSE_H
#include <vector>
#include <map>
#include <cmath>
#include <iostream>
#include <stdexcept>
#include "matrix.h"
namespace nmlib{
/******** Class I/F ********/
// Sparse matrices
class Sparse{
public:
explicit Sparse(size_t r=0, size_t c=0);
size_t nrow(void) const; // number of rows
size_t ncol(void) const; // number of columns
double operator()(size_t i, size_t j) const; // get s=A(i,j)
double& operator()(size_t i, size_t j); // set A(i,j)=s
const std::map<size_t,double>& columns(size_t i) const{ return val[i]; } // i-th row (map j=>Aij)
std::map<size_t,double>& columns(size_t i) { return val[i]; } // i-th row (non-const version)
private:
size_t row, col; // dimentions
std::vector<std::map<size_t,double> > val; // componets val[i][j] CRS(Condensed Row Storage)
};
// Configurations for sparse solvers
class SparseConf{
public:
SparseConf(void): tol(1.e-8), loop(100), x0(), lu(), verb(false) {}
Sparse& init_ilu0(const Sparse& a); // initialize preconditioner(ILU0)
double tol; // tolerance |Ax-b|/|b|
int loop; // max iteration
Matrix x0; // initial value
Sparse lu; // preconditioner
bool verb; // verbosity (show progress to std::cerr)
};
// Configuration for sparse eigensolver
struct SparseEigenConf{
SparseEigenConf(void): x0(), mu0(0), tol(1.e-8), loop(100), warmup(0), pbcg(false), verb(false) {}
Matrix x0; // initial guess of an eigenvector
double mu0; // initial guess of an eigenvalue
double tol; // tolerance for convergence check
int loop; // max iteration
int warmup;// number of iteration to magnify eigens near mu0
bool pbcg; // use PBCG with ILU(0) preconditioner
bool verb; // verbosity
};
/******** Utility I/F ********/
// Incremental operations
Sparse& operator+=(Sparse& a, double s); // A=A+sI
Sparse& operator-=(Sparse& a, double s); // A=A-sI
Sparse& operator*=(Sparse& a, double s); // A=A*s
Sparse& operator/=(Sparse& a, double s); // A=A/s
Sparse& operator+=(Sparse& a, const Sparse& b); // A=A+B
Sparse& operator-=(Sparse& a, const Sparse& b); // A=A-B
//Sparse& operator*=(Sparse& a, const Sparse& b);
//Sparse& operator/=(Sparse& a, const Sparse& b);
// Scalar operations
Sparse operator-(const Sparse& a); // -A (unary)
Sparse operator+(const Sparse& a, double s); // A+sI
Sparse operator-(const Sparse& a, double s); // A-sI
Sparse operator*(const Sparse& a, double s); // A*s
Sparse operator/(const Sparse& a, double s); // A/s
Sparse operator+(double s, const Sparse& a); // sI+A
Sparse operator-(double s, const Sparse& a); // sI-A
Sparse operator*(double s, const Sparse& a); // s*A
//Sparse operator/(double s, const Sparse& a); // s*inv(A)
// Sparse-Sparse operations
Sparse operator+(const Sparse& a, const Sparse& b); // A+B
Sparse operator-(const Sparse& a, const Sparse& b); // A-B
Sparse operator*(const Sparse& a, const Sparse& b); // A*B
Matrix operator*(const Sparse& a, const Matrix& b); // A*b (dense Matrix version)
// Utilities
double norm (const Sparse& a); // |A|
Sparse tp (const Sparse& a); // A^T
Matrix dense(const Sparse& a); // conversion to dens matrix - use with care
Matrix tpab (const Sparse& a, const Matrix& b); // A^T * b
// I/O
std::istream& operator>>(std::istream& s, Sparse& a); // text I/O
std::ostream& operator<<(std::ostream& s, const Sparse& a); // text I/O
std::istream& read (std::istream& s, Sparse& a); // binary I/O
std::ostream& write (std::ostream& s, const Sparse& a); // binary I/O
// Sparse solvers
Matrix solve_cg (const Sparse& a, const Matrix& b, const SparseConf& cf=SparseConf()); // CG (for symmetric positive definit A)
Matrix solve_bcg (const Sparse& a, const Matrix& b, const SparseConf& cf=SparseConf()); // BiCG
Matrix solve_pbcg(const Sparse& a, const Matrix& b, const SparseConf& cf=SparseConf()); // Preconditioned BiCG
// Preconditioners
Sparse& ilu0(Sparse& a); // incomplete LU decomposition ILU(0) (overwrites A)
Matrix lux (const Sparse& lu, const Matrix& x); // LUx
Matrix sluxb (const Sparse& lu, const Matrix& b); // (LU)^-1 b (solve LUx=b)
Matrix slutxb(const Sparse& lu, const Matrix& b); // (LU)^-T b (solve LU^T x=b)
// Sparse eigensolver
Matrix eigenvec(const Sparse& a0, const SparseEigenConf& cf1=SparseEigenConf(), const SparseConf& cf20=SparseConf());
/******** Implementation ********/
// Class methods
inline Sparse::Sparse(size_t r, size_t c): row(r),col(c),val(r) {}
inline size_t Sparse::nrow(void) const{ return row; }
inline size_t Sparse::ncol(void) const{ return col; }
inline double& Sparse::operator()(size_t i, size_t j){
if( !(i<nrow() && j<ncol()) ) throw std::domain_error("Sparse::operator(): out of range");
return val[i][j];
}
inline double Sparse::operator()(size_t i, size_t j) const {
if( !(i<nrow() && j<ncol()) ) throw std::domain_error("Sparse::operator() const: out of range");
const auto& c=val[i].find(j);
return (c==val[i].end() ? 0 : c->second);
}
inline Sparse& SparseConf::init_ilu0(const Sparse& a){ lu=a; return ilu0(lu); }
// Incremental operations
inline Sparse& operator+=(Sparse& a, double s){
for(size_t k=0; k<a.ncol(); k++) a(k,k)+=s;
return a;
}
inline Sparse& operator-=(Sparse& a, double s){
a+=-s;
return a;
}
inline Sparse& operator*=(Sparse& a, double s){
for(size_t i=0; i<a.nrow(); i++)
for(auto& c: a.columns(i))
c.second*=s;
return a;
}
inline Sparse& operator/=(Sparse& a, double s){
a*=1/s;
return a;
}
inline Sparse& operator+=(Sparse& a, const Sparse& b){
if( !(a.nrow()==b.nrow() && a.ncol()==b.ncol()) )
throw std::domain_error("operator +=(Sparse,Sparse): invalid dimensions");
for(size_t i=0; i<b.nrow(); i++)
for(const auto& c: b.columns(i))
a(i,c.first)+=c.second;
return a;
}
inline Sparse& operator-=(Sparse& a, const Sparse& b){
if( !(a.nrow()==b.nrow() && a.ncol()==b.ncol()) )
throw std::domain_error("operator -=(Sparse,Sparse): invalid dimensions");
for(size_t i=0; i<b.nrow(); i++)
for(const auto& c: b.columns(i))
a(i,c.first)-=c.second;
return a;
}
// Basic operations
inline Sparse operator-(const Sparse& a) { Sparse b(a); b*=-1.0; return b; }
inline Sparse operator+(const Sparse& a, double s){ Sparse b(a); b+=s; return b; }
inline Sparse operator-(const Sparse& a, double s){ Sparse b(a); b-=s; return b; }
inline Sparse operator*(const Sparse& a, double s){ Sparse b(a); b*=s; return b; }
inline Sparse operator/(const Sparse& a, double s){ Sparse b(a); b/=s; return b; }
inline Sparse operator+(double s, const Sparse& a){ Sparse b(a); b+=s; return b; }
inline Sparse operator-(double s, const Sparse& a){ Sparse b(a); b*=-1.0; b+=s; return b; }
inline Sparse operator*(double s, const Sparse& a){ Sparse b(a); return (b*=s); }
//inline Sparse operator/(double s, const Sparse& a);
inline Sparse operator+(const Sparse& a, const Sparse& b){ Sparse c(a); c+=b; return c; }
inline Sparse operator-(const Sparse& a, const Sparse& b){ Sparse c(a); c-=b; return c; }
inline Sparse operator*(const Sparse& a, const Sparse& b){
if( a.ncol()!=b.nrow() )
throw std::domain_error("operator *(Sparse,Sparse): invalid dimensions");
Sparse ret(a.nrow(),b.ncol());
for(size_t j=0; j<ret.ncol(); j++)
for(size_t i=0; i<a.nrow(); i++)
for(const auto& c: a.columns(i))
ret(i,j)+=c.second*b(c.first,j);
return ret;
}
inline Matrix operator*(const Sparse& a, const Matrix& b){
if( a.ncol()!=b.nrow() )
throw std::domain_error("operator *(Sparse,Matrix): invalid dimensions");
Matrix ret(a.nrow(),b.ncol());
for(size_t j=0; j<ret.ncol(); j++)
for(size_t i=0; i<a.nrow(); i++)
for(const auto& c: a.columns(i))
ret(i,j)+=c.second*b(c.first,j);
return ret;
}
// Utilities
inline double norm (const Sparse& a){
double s=0;
for(size_t i=0; i<a.nrow(); i++){
for(const auto& c: a.columns(i)){
double t=c.second;
s+=t*t;
}
}
return sqrt(s);
}
inline Sparse tp (const Sparse& a){
Sparse b(a.ncol(),a.nrow());
for(size_t i=0; i<a.nrow(); i++)
for(const auto& c: a.columns(i))
b(c.first,i)=c.second;
return b;
}
inline Matrix dense(const Sparse& a){
Matrix b(a.nrow(),a.ncol());
for(size_t i=0; i<a.nrow(); i++)
for(const auto& c: a.columns(i))
b(i,c.first)=c.second;
return b;
}
inline Matrix tpab (const Sparse& a, const Matrix& b){
if( a.nrow()!=b.nrow() )
throw std::domain_error("tpab(Sparse,Matrix): invalid dimensions");
Matrix ret(b.nrow(),b.ncol());
for(size_t j=0; j<ret.ncol(); j++)
for(size_t i=0; i<a.nrow(); i++)
for(const auto& c: a.columns(i))
ret(c.first,j)+=c.second*b(i,j);
return ret;
}
// Solve Ax=b (CG - Conjugate Gradient for symmetric positive definite A)
inline Matrix solve_cg(const Sparse& a, const Matrix& b, const SparseConf& cf){
if( !(a.nrow()==a.ncol() && a.ncol()==b.nrow() && b.ncol()==1) )
throw std::domain_error("solve_cg(Sparse,Matrix): invalid dimensions");
Matrix x,r,p,q;
double t,rr;
x=(cf.x0.dim()>0 ? cf.x0 : Matrix(a.ncol()));
p=r=b-a*x;
for(int j=0; j<cf.loop; j++){
if(cf.verb) std::cerr<<"CG["<<j<<"]\t"<<norm(r)/norm(b)<<"\t"<<norm(a*x-b)<<"\n";
if(norm(r)<=norm(b)*cf.tol) break; // convergence
rr=inner(r,r);
q=a*p;
t=rr/inner(p,q);
x+=t*p;
r-=t*q; // r=b-Ax
t=inner(r,r)/rr;
p=r+t*p;
}
return x;
}
// Solve Ax=b (BiCG - Bi-Conjugate Gradient)
inline Matrix solve_bcg(const Sparse& a, const Matrix& b, const SparseConf& cf){
if( !(a.nrow()==a.ncol() && a.ncol()==b.nrow() && b.ncol()==1) )
throw std::domain_error("solve_bcg(Sparse,Matrix): invalid dimensions");
Matrix x,r1,r2,p1,p2,q1,q2;
double t,rr;
x=Matrix(a.ncol()); if(cf.x0.dim()>0) x=cf.x0;
p1=r1=b-a*x;
p2=r2=r1;
for(int j=0; j<cf.loop; j++){
if(cf.verb) std::cerr<<"BCG["<<j<<"]\t"<<norm(r1)/norm(b)<<"\t"<<norm(a*x-b)<<"\n";
if(norm(r1)<=norm(b)*cf.tol) break;
rr=inner(r1,r2);
q1=a*p1;
q2=tpab(a,p2); // A^T*p2
t =rr/inner(q1,p2);
x +=t*p1;
r1-=t*q1; // r1=b-Ax
r2-=t*q2;
t =inner(r1,r2)/rr;
p1=r1+t*p1;
p2=r2+t*p2;
}
return x;
}
// Solve Ax=b (PBCG - Preconditioned BiCG)
inline Matrix solve_pbcg(const Sparse& a, const Matrix& b, const SparseConf& cf){
if( !(a.nrow()==a.ncol() && a.ncol()==b.nrow() && b.ncol()==1) )
throw std::domain_error("solve_pbcg(Sparse,Matrix): invalid dimensions");
Matrix x,r1,r2,p1,p2,q1,q2;
double t,rr;
Sparse lu0; if(cf.lu.nrow()==0){ lu0=a; ilu0(lu0); }
const Sparse& lu=(cf.lu.nrow()>0 ? cf.lu : lu0);
x=Matrix(a.ncol()); if(cf.x0.dim()>0) x=cf.x0;
p1=r1=sluxb(lu,b-a*x); //lu.prod_inv (b-a*x);
p2=r2=slutxb(lu,b-a*x); //lu.prod_tpinv(b-a*x);
for(int j=0; j<cf.loop; j++){
if(cf.verb) std::cerr<<"PBCG["<<j<<"]\t"<<norm(a*x-b)/norm(b)<<"\t"<<norm(a*x-b)<<"\t"<<"\n";
if(norm(a*x-b)<=norm(b)*cf.tol) break;
rr=inner(r1,r2);
q1=sluxb(lu,a*p1); //lu.prod_inv(a*p1); // (C^-1 A) * p1
q2=tpab(a,slutxb(lu,p2)); //tpab(a,lu.prod_tpinv(p2)); // (C^-1 A)^T * p2
t =rr/inner(q1,p2);
x +=t*p1;
r1-=t*q1; // r1=C^-1 (b-Ax)
r2-=t*q2;
t =inner(r1,r2)/rr;
p1=r1+t*p1;
p2=r2+t*p2;
}
return x;
}
// ILU(0) - incomplete LU decomposition
// - A typical preconditioner without fill-in
// - Decomposition is complete when A is a band matrix
inline Sparse& ilu0(Sparse& a){
if( a.nrow()!=a.ncol() ) throw std::domain_error("ilu0(Sparse): invalid dimensions");
for(size_t i=0; i<a.nrow(); i++){
std::map<size_t,double>& ai=a.columns(i);
auto aii=ai.find(i); // Uii
if( aii==ai.end() ) throw std::runtime_error("ilu0(Sparse): division by Aii=0");
for(auto aik=ai.begin(); aik!=aii; aik++){
size_t k=aik->first;
auto& ak=a.columns(k);
aik->second /= a(k,k); // Lik
auto aij=aik;
for(aij++; aij!=ai.end(); aij++){
size_t j=aij->first;
auto akj=ak.find(j);
if( akj!=ak.end() ) aij->second -= aik->second * akj->second; // Uij
}
}
}
return a;
}
// b=LUx
inline Matrix lux(const Sparse& lu, const Matrix& x){
if( !(lu.nrow()==lu.ncol() && lu.ncol()==x.nrow() && x.ncol()==1) )
throw std::domain_error("lux(Sparse,Matrix): invalid dimensions");
// y=Ux
Matrix y(x.nrow());
for(size_t i=0; i<lu.nrow(); i++)
for(auto c1=lu.columns(i).find(i),c2=lu.columns(i).end(); c1!=c2; c1++)
y(i) += c1->second * x(c1->first);
// z=Ly=LUx
Matrix z(y); // Lii=1
for(size_t i=0; i<lu.nrow(); i++)
for(auto c1=lu.columns(i).begin(),c2=lu.columns(i).find(i); c1!=c2; c1++)
z(i) += c1->second * y(c1->first);
return z;
}
// (LU)^-1 b (solve LUx=b)
inline Matrix sluxb(const Sparse& lu, const Matrix& b){
if( !(lu.nrow()==lu.ncol() && lu.ncol()==b.nrow() && b.ncol()==1) )
throw std::domain_error("sluxb(Sparse,Matrix): invalid dimensions");
Matrix x(b);
// x --> L^-1 x
for(size_t i=0; i<lu.nrow(); i++){
auto c1=lu.columns(i).begin(), c2=lu.columns(i).find(i);
for(; c1!=c2; c1++) x(i) -= c1->second * x(c1->first);
//x(i)/=1;
}
// x --> U^-1 x
for(size_t i=lu.nrow()-1; /*i>=0*/; i--){
auto c1=lu.columns(i).find(i), c2=lu.columns(i).end();
for(c1++; c1!=c2; c1++) x(i) -= c1->second * x(c1->first);
x(i)/=lu(i,i); // = (bi - \sum_{j>i} Uij xj) / Uii
if(i==0) break;
}
return x;
}
// (LU)^-T b (solve LU^T x=b)
inline Matrix slutxb(const Sparse& lu, const Matrix& b){
if( !(lu.nrow()==lu.ncol() && lu.ncol()==b.nrow() && b.ncol()==1) )
throw std::domain_error("slutxb(Sparse,Matrix): invalid dimensions");
Matrix x(b);
// x --> U^-T x
for(size_t i=0; i<lu.ncol(); i++){
auto c1=lu.columns(i).find(i), c2=lu.columns(i).end();
x(i) /= c1->second; ; // xi /= Uii
for(c1++; c1!=c2; c1++) x(c1->first) -= c1->second * x(i); // xj -= Uji*xi
}
// x --> L^-T x
for(size_t i=lu.ncol()-1; /*i>=0*/; i--){
auto c1=lu.columns(i).begin(), c2=lu.columns(i).find(i);
//x(i)/=1; // xi /== Lii
for( ; c1!=c2; c1++) x(c1->first) -= c1->second * x(i); // xj -= Lji*xi
if(i==0) break;
}
return x;
}
// Sparse eigensolver by shifted inverse iteration
inline Matrix eigenvec(const Sparse& a0, const SparseEigenConf& cf1, const SparseConf& cf20){
Sparse amu=a0;
SparseConf cf2=cf20;
Matrix x, x_old;
double mu=cf1.mu0, err=0, err_old;
x=(cf1.x0.dim() ? cf1.x0 : cf2.x0.dim() ? cf2.x0 : Matrix(a0.nrow()).fill(1));
x/=norm(x);
for(int i=0; i<cf1.loop; i++){
x_old=x;
err_old=norm(a0*x-mu*x);
for(size_t i=0; i<a0.nrow(); i++) amu(i,i)=a0(i,i)-mu;
cf2.x0=x;
bool use_pbcg=(cf1.pbcg && std::isfinite(norm(cf2.init_ilu0(amu))));
if( cf1.verb && cf1.pbcg && !use_pbcg ) std::cerr<<"EIGEN["<<i<<"]: broken preconditioner (not used)\n";
if( use_pbcg ) x=solve_pbcg(amu,x,cf2);
else x=solve_cg (amu,x,cf2);
x/=norm(x);
if( cf1.warmup<=i ) mu=inner(a0*x,x); // use mu0 at an early stage to magnify eigens near mu0
err=norm(a0*x-mu*x);
if( cf1.warmup<i && err_old<cf1.tol && !(err<err_old) ) return x_old;
if( cf1.verb ) std::cerr<<"EIGEN["<<i<<"]\terr="<<err<<"\tmu="<<mu<<"\tcos="<<inner(x,x_old)<<"\n";
if( !std::isfinite(err) ) break;
}
if( cf1.verb ) std::cerr<<"EIGEN: perhaps poor convergence.\n";
return (std::isfinite(err) ? x : x_old);
}
} //namespace nmlib
#endif //SPARSE_H
| 32.7827 | 129 | 0.600553 | [
"vector"
] |
de141aecfa381dc25a39cea108c94b12fe794d3f | 15,097 | c | C | src/main/c/Jep/python/jep_object.c | git9am/jep | d1c7f1479ae46893fdab45c34088e1d788609b09 | [
"Zlib"
] | null | null | null | src/main/c/Jep/python/jep_object.c | git9am/jep | d1c7f1479ae46893fdab45c34088e1d788609b09 | [
"Zlib"
] | null | null | null | src/main/c/Jep/python/jep_object.c | git9am/jep | d1c7f1479ae46893fdab45c34088e1d788609b09 | [
"Zlib"
] | null | null | null | /*
jep - Java Embedded Python
Copyright (c) 2004-2018 JEP AUTHORS.
This file is licensed under the the zlib/libpng License.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Jep.h"
#include "jep_python_PyObject.h"
/*
* Class: jep_python_PyObject
* Method: decref
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_decref
(JNIEnv *env, jobject jobj, jlong tstate, jlong ptr)
{
PyObject *o = (PyObject *) ptr;
JepThread* jepThread = (JepThread *) tstate;
if (ptr == 0) {
THROW_JEP(env, "jep_object: Invalid object");
} else {
PyEval_AcquireThread(jepThread->tstate);
Py_DECREF(o);
process_py_exception(env);
PyEval_ReleaseThread(jepThread->tstate);
}
}
/*
* Class: jep_python_PyObject
* Method: incref
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_incref
(JNIEnv *env, jobject jobj, jlong tstate, jlong ptr)
{
PyObject *o = (PyObject *) ptr;
JepThread* jepThread = (JepThread *) tstate;
if (ptr == 0) {
THROW_JEP(env, "jep_object: Invalid object");
} else {
PyEval_AcquireThread(jepThread->tstate);
Py_INCREF(o);
PyEval_ReleaseThread(jepThread->tstate);
}
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL
Java_jep_python_PyObject_set__JJLjava_lang_String_2Ljava_lang_Object_2
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jobject jval)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_object(env, (intptr_t) tstate, (intptr_t) module, name,
jval);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL
Java_jep_python_PyObject_set__JJLjava_lang_String_2Ljava_lang_String_2
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jstring jval)
{
const char *name, *value;
name = jstring2char(env, jname);
value = jstring2char(env, jval);
pyembed_setparameter_string(env, (intptr_t) tstate, (intptr_t) module, name,
value);
release_utf_char(env, jname, name);
release_utf_char(env, jval, value);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2I
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jint jval)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_int(env, (intptr_t) tstate, (intptr_t) module, name,
(int) jval);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;J)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2J
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jlong jval)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_long(env, (intptr_t) tstate, (intptr_t) module, name,
(PY_LONG_LONG) jval);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;D)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2D
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jdouble jval)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_double(env, (intptr_t) tstate, (intptr_t) module, name,
(double) jval);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;F)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2F
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jfloat jval)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_float(env, (intptr_t) tstate, (intptr_t) module, name,
(float) jval);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[Z)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3Z
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jbooleanArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[I)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3I
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jintArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[S)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3S
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jshortArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[B)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3B
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jbyteArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[J)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3J
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jlongArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[D)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3D
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jdoubleArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: set
* Signature: (JJLjava/lang/String;[F)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_set__JJLjava_lang_String_2_3F
(JNIEnv *env, jobject obj, jlong tstate, jlong module,
jstring jname, jfloatArray jarr)
{
const char *name;
name = jstring2char(env, jname);
pyembed_setparameter_array(env, (intptr_t) tstate, (intptr_t) module, name,
(jobjectArray) jarr);
release_utf_char(env, jname, name);
}
/*
* Class: jep_python_PyObject
* Method: getAttr
* Signature: (JJLjava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_jep_python_PyObject_getAttr
(JNIEnv *env, jobject obj, jlong tstate, jlong pyobj, jstring str, jclass clazz)
{
JepThread *jepThread;
PyObject *pyObject;
const char *attrName;
PyObject *attr;
jobject ret = NULL;
jepThread = (JepThread *) tstate;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return ret;
}
if (str == NULL) {
THROW_JEP(env, "Attribute name cannot be null.");
return ret;
}
pyObject = (PyObject*) pyobj;
attrName = jstring2char(env, str);
PyEval_AcquireThread(jepThread->tstate);
attr = PyObject_GetAttrString(pyObject, attrName);
if (process_py_exception(env)) {
goto EXIT;
}
ret = PyObject_As_jobject(env, attr, clazz);
process_py_exception(env);
EXIT:
Py_XDECREF(attr);
PyEval_ReleaseThread(jepThread->tstate);
release_utf_char(env, str, attrName);
return ret;
}
/*
* Class: jep_python_PyObject
* Method: setAttr
* Signature: (JJLjava/lang/String;Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_setAttr
(JNIEnv *env, jobject obj, jlong tstate, jlong pyobj, jstring str,
jobject jAttr)
{
JepThread *jepThread;
PyObject *pyObject;
const char *attrName;
PyObject *pyAttr;
int ret;
jepThread = (JepThread *) tstate;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return;
}
if (str == NULL) {
THROW_JEP(env, "Attribute name cannot be null.");
return;
}
pyObject = (PyObject*) pyobj;
attrName = jstring2char(env, str);
PyEval_AcquireThread(jepThread->tstate);
pyAttr = jobject_As_PyObject(env, jAttr);
if (process_py_exception(env)) {
goto EXIT;
}
ret = PyObject_SetAttrString(pyObject, attrName, pyAttr);
if (ret == -1) {
process_py_exception(env);
}
EXIT:
PyEval_ReleaseThread(jepThread->tstate);
release_utf_char(env, str, attrName);
}
/*
* Class: jep_python_PyObject
* Method: delAttr
* Signature: (JJLjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_jep_python_PyObject_delAttr
(JNIEnv *env, jobject obj, jlong tstate, jlong pyobj, jstring str)
{
JepThread *jepThread;
PyObject *pyObject;
const char *attrName;
int ret;
jepThread = (JepThread *) tstate;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return;
}
if (str == NULL) {
THROW_JEP(env, "Attribute name cannot be null.");
return;
}
pyObject = (PyObject*) pyobj;
attrName = jstring2char(env, str);
PyEval_AcquireThread(jepThread->tstate);
ret = PyObject_DelAttrString(pyObject, attrName);
if (ret == -1) {
process_py_exception(env);
}
PyEval_ReleaseThread(jepThread->tstate);
release_utf_char(env, str, attrName);
}
/*
* Class: jep_python_PyObject
* Method: createModule
* Signature: (JJLjava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_jep_python_PyObject_createModule
(JNIEnv *env, jobject obj, jlong tstate, jlong module, jstring jstr)
{
const char *str;
jlong ret;
str = jstring2char(env, jstr);
ret = pyembed_create_module_on(env, (intptr_t) tstate, (intptr_t) module,
(char *) str);
release_utf_char(env, jstr, str);
return ret;
}
/*
* Class: jep_python_PyObject
* Method: getValue
* Signature: (JJLjava/lang/String;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_jep_python_PyObject_getValue
(JNIEnv *env, jobject obj, jlong tstate, jlong onModule, jstring jstr)
{
const char *str;
jobject ret;
str = jstring2char(env, jstr);
ret = pyembed_getvalue_on(env, (intptr_t) tstate, (intptr_t) onModule,
(char *) str);
release_utf_char(env, jstr, str);
return ret;
}
/*
* Class: jep_python_PyObject
* Method: equals
* Signature: (JJLjava/lang/Object;)Z
*/
JNIEXPORT jboolean JNICALL Java_jep_python_PyObject_equals
(JNIEnv *env, jobject obj, jlong tstate, jlong pyObj, jobject otherObj)
{
JepThread *jepThread;
PyObject *pyObject;
PyObject *otherPyObject;
int result = 0;
jboolean ret = JNI_FALSE;
jepThread = (JepThread *) tstate;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return ret;
}
pyObject = (PyObject*) pyObj;
PyEval_AcquireThread(jepThread->tstate);
otherPyObject = jobject_As_PyObject(env, otherObj);
if (process_py_exception(env)) {
goto EXIT;
}
result = PyObject_RichCompareBool(pyObject, otherPyObject, Py_EQ);
if (result == -1) {
process_py_exception(env);
} else if (result == 1) {
ret = JNI_TRUE;
}
EXIT:
Py_XDECREF(otherPyObject);
PyEval_ReleaseThread(jepThread->tstate);
return ret;
}
/*
* Class: jep_python_PyObject
* Method: toString
* Signature: (JJ)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_jep_python_PyObject_toString
(JNIEnv *env, jobject obj, jlong tstate, jlong pyobj)
{
JepThread *jepThread;
PyObject *pyObject;
jstring ret = NULL;
jepThread = (JepThread *) tstate;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return ret;
}
pyObject = (PyObject*) pyobj;
PyEval_AcquireThread(jepThread->tstate);
ret = PyObject_As_jstring(env, pyObject);
process_py_exception(env);
PyEval_ReleaseThread(jepThread->tstate);
return ret;
}
/*
* Class: jep_python_PyObject
* Method: hashCode
* Signature: (JJ)J
*/
JNIEXPORT jlong JNICALL Java_jep_python_PyObject_hashCode
(JNIEnv *env, jobject obj, jlong tstate, jlong pyobj)
{
JepThread *jepThread;
PyObject *pyObject;
Py_hash_t hash = -1;
jepThread = (JepThread *) tstate;
if (!jepThread) {
THROW_JEP(env, "Couldn't get thread objects.");
return (jlong) hash;
}
pyObject = (PyObject*) pyobj;
PyEval_AcquireThread(jepThread->tstate);
hash = PyObject_Hash(pyObject);
process_py_exception(env);
PyEval_ReleaseThread(jepThread->tstate);
return (jlong) hash;
}
| 26.485965 | 80 | 0.669736 | [
"object"
] |
de1aff545ea616f6428ec192c4608d62928d714a | 14,864 | h | C | include/dpmmSubclusters/reduction_array2.h | jstraub/dpMM | 538c432d5f98c040d5c1adb072e545e38f97fc69 | [
"MIT-feh"
] | 11 | 2015-04-27T15:14:01.000Z | 2021-11-18T00:19:18.000Z | include/dpmmSubclusters/reduction_array2.h | jstraub/dpMM | 538c432d5f98c040d5c1adb072e545e38f97fc69 | [
"MIT-feh"
] | null | null | null | include/dpmmSubclusters/reduction_array2.h | jstraub/dpMM | 538c432d5f98c040d5c1adb072e545e38f97fc69 | [
"MIT-feh"
] | 6 | 2015-07-02T12:46:20.000Z | 2022-03-30T04:39:30.000Z | // =============================================================================
// == reduction_array2.h
// == --------------------------------------------------------------------------
// == A reduction array class that can be used with OpenMP. Current OpenMP
// == software only allows the reduction of an array into a scalar. This class
// == allows one to reduce an array into an array. Also, since the code here
// == implements a reduction similar to OpenMP without actually using OpenMP's
// == reduction clause, the reduction_array2 class allows users to define their
// == own reduction functions and reductions on user-specified classes.
// ==
// == An array of size numThreads x D is created. Reduction is performed so
// == that each thread only has write accesses a unique spot in the array.
// ==
// == Notation is as follows:
// == numThreads - The number of OpenMP threads that will be running
// == D - The dimension of the array to reduce to (if scalar, should be 1)
// ==
// == General usage:
// == (1) Before the parallel environment, initialize the reduction array:
// == >> reduction_array2<double> my_arr(numThreads,D,initial_value);
// ==
// == (2) Inside the parallel for loop, you can reduce with data x with:
// == >> my_arr.reduce_XXX(omp_get_thread_num(), bin, x);
// == "XXX" can be the predefined "add", "multiply", "max", or "min"
// == or you can specify a function pointer to your own function with
// == >> my_arr.reduce_function(omp_get_thread_num(), bin, x, func_ptr);
// ==
// == (3) After the parallel environment, reduce on the separate threads:
// == >> double* output = my_arr.final_reduce_XXX();
// == Again, "XXX" can be any of the predefined functions, or you can use
// == >> double* output = my_arr.final_reduce_function(func_ptr);
// ==
// == (4) output now is an array of length D with the reduced values.
// == Do *NOT* attempt to deallocate output or my_arr as they have their
// == own destructors.
// ==
// == Notes:
// == (1) Because of possible "false sharing", the array size here is actually
// == numThreads x D x cache_line. We pad the array so that different
// == threads will not access the same cache_line. If the cache line is
// == not large enough, please increase ie manually.
// == --------------------------------------------------------------------------
// == Written by Jason Chang 04-14-2013 - jchang7@csail.mit.edu
// =============================================================================
#ifndef _REDUCTION_ARRAY2
#define _REDUCTION_ARRAY2
#include <string.h>
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include "dpmmSubclusters/reduction_array.h"
//#include "array.h"
//#include "helperMEX.h"
#ifndef cache_line
#define cache_line 4
#endif
template <typename T>
class reduction_array2
{
private:
arr(T) data;
int numThreads;
int K;
int D;
long offt; // offsets for the threads
long offk; // offsets for the dimensions
public:
// --------------------------------------------------------------------------
// -- reduction_array2
// -- constructors; initializes the reduction array with a number of
// -- threads, each with a KxD dimensional vector. The third parameter can be
// -- specified to give the initializing value.
// --------------------------------------------------------------------------
reduction_array2();
reduction_array2(int thenumThreads, int theK, int theD);
reduction_array2(int thenumThreads, int theK, int theD, T value);
virtual ~reduction_array2();
// --------------------------------------------------------------------------
// -- init_values
// -- Initializes all values in the reduciton array to "value"
// --
// -- parameters:
// -- - value : the value to set all elements to
// --------------------------------------------------------------------------
void init_values(T value);
// --------------------------------------------------------------------------
// -- reduce_XXX
// -- Performs the reduction "XXX" on the d^th dimension with value
// --------------------------------------------------------------------------
void reduce_inc(int t, int k);
void reduce_add(int t, int k, arr(T) value);
template <typename T2>
void reduce_add(int t, int k, long d, T2 value);
template <typename T2>
void reduce_add(int t, int k, long* ds, T2* values, int nnz);
void reduce_add_outerprod(int t, int k, arr(T) value);
void reduce_multiply(int t, int k, arr(T) value);
void reduce_min(int t, int k, arr(T) value);
void reduce_max(int t, int k, arr(T) value);
// --------------------------------------------------------------------------
// -- reduce_function
// -- Performs the reduction specified by the function pointer
// --------------------------------------------------------------------------
void reduce_function(int t, int k, arr(T) value, T (*func)(T,T));
// --------------------------------------------------------------------------
// -- final_reduce_XXX
// -- Performs the reduction "XXX" on the threads and returns result
// --------------------------------------------------------------------------
arr(T) final_reduce_add();
arr(T) final_reduce_multiply();
arr(T) final_reduce_min();
arr(T) final_reduce_max();
// --------------------------------------------------------------------------
// -- final_reduce_function
// -- The function pointer version of above
// --------------------------------------------------------------------------
arr(T) final_reduce_function(T (*func)(T,T));
// --------------------------------------------------------------------------
// -- final_reduce_ext_XXX
// -- Performs the reduction "XXX" on the threads into the external array.
// -- Assumes that ext is already allocated to the correct size.
// --------------------------------------------------------------------------
void final_reduce_ext_add(arr(T) ext);
void final_reduce_ext_multiply(arr(T) ext);
// --------------------------------------------------------------------------
// -- collapse_cache_line
// -- collapses the cache line for the final return
// --------------------------------------------------------------------------
void collapse_cache_line();
};
// --------------------------------------------------------------------------
// -- reduction_array2
// -- constructors; initializes the reduction array with a number of
// -- threads, each with a KxD dimensional vector. The third parameter can be
// -- specified to give the initializing value.
// --------------------------------------------------------------------------
template <typename T>
reduction_array2<T>::reduction_array2() :
numThreads(0), K(0), D(0), data(NULL)
{
}
template <typename T>
reduction_array2<T>::reduction_array2(int thenumThreads, int theK, int theD) :
numThreads(thenumThreads), K(theK), D(theD)
{
offk = D + cache_line;
offt = offk*K;
data = allocate_memory<T>(numThreads*offt);
}
template <typename T>
reduction_array2<T>::reduction_array2(int thenumThreads, int theK, int theD, T value) :
numThreads(thenumThreads), K(theK), D(theD)
{
offk = D + cache_line;
offt = offk*K;
data = allocate_memory<T>(numThreads*offt);
set_memory<T>(data, value, sizeof(T)*numThreads*offt);
}
template <typename T>
reduction_array2<T>::~reduction_array2()
{
if (data!=NULL)
deallocate_memory(data);;
}
// --------------------------------------------------------------------------
// -- init_values
// -- Initializes all values in the reduciton array to "value"
// --
// -- parameters:
// -- - value : the value to set all elements to
// --------------------------------------------------------------------------
template <typename T>
void reduction_array2<T>::init_values(T value)
{
set_memory<T>(data, value, sizeof(T)*numThreads*offt);
}
// --------------------------------------------------------------------------
// -- reduce_XXX
// -- Performs the reduction "XXX" on the d^th dimension with value
// --------------------------------------------------------------------------
template <typename T>
inline void reduction_array2<T>::reduce_inc(int t, int k)
{
long offset = t*offt + k*offk;
for (int d=0; d<D; d++)
++data[offset+d];
}
template <typename T>
inline void reduction_array2<T>::reduce_add(int t, int k, arr(T) value)
{
long offset = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset+d] += value[d];
}
template <typename T>
template <typename T2>
inline void reduction_array2<T>::reduce_add(int t, int k, long d, T2 value)
{
long offset = t*offt + k*offk;
data[offset+d] += value;
}
template <typename T>
template <typename T2>
inline void reduction_array2<T>::reduce_add(int t, int k, long* ds, T2* values, int nnz)
{
long offset = t*offt + k*offk;
for (int di=0; di<nnz; di++)
data[offset+ds[di]] += values[di];
}
template <typename T>
inline void reduction_array2<T>::reduce_add_outerprod(int t, int k, arr(T) value)
{
long offset = t*offt + k*offk;
long sqrtD = sqrt(D);
for (int d=0; d<D; d++)
data[offset+d] += value[d/sqrtD]*value[d%sqrtD];
}
template <typename T>
inline void reduction_array2<T>::reduce_multiply(int t, int k, arr(T) value)
{
long offset = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset+d] *= value[d];
}
template <typename T>
inline void reduction_array2<T>::reduce_min(int t, int k, arr(T) value)
{
long offset = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset+d] = mymin(data[offset+d], value[d]);
}
template <typename T>
inline void reduction_array2<T>::reduce_max(int t, int k, arr(T) value)
{
long offset = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset+d] = mymax(data[offset+d], value[d]);
}
// --------------------------------------------------------------------------
// -- reduce_function
// -- Performs the reduction specified by the function pointer
// --------------------------------------------------------------------------
template <typename T>
inline void reduction_array2<T>::reduce_function(int t, int k, arr(T) value, T (*func)(T,T))
{
long offset = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset+d] = func(data[offset+d], value[d]);
}
// --------------------------------------------------------------------------
// -- final_reduce_XXX
// -- Performs the reduction "XXX" on the threads and returns result
// --------------------------------------------------------------------------
template <typename T>
inline arr(T) reduction_array2<T>::final_reduce_add()
{
for (int k=0; k<K; k++)
for (int t=1; t<numThreads; t++)
{
long offset0 = k*offk;
long offset1 = t*offt + k*offk;
#pragma omp parallel for
for (int d=0; d<D; d++)
data[offset0+d] += data[offset1+d];
}
collapse_cache_line();
return data;
}
template <typename T>
inline arr(T) reduction_array2<T>::final_reduce_multiply()
{
for (int t=1; t<numThreads; t++)
for (int k=0; k<K; k++)
{
long offset0 = k*offk;
long offset1 = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset0+d] *= data[offset1+d];
}
collapse_cache_line();
return data;
}
template <typename T>
inline arr(T) reduction_array2<T>::final_reduce_min()
{
for (int t=1; t<numThreads; t++)
for (int k=0; k<K; k++)
{
long offset0 = k*offk;
long offset1 = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset0+d] = mymin(data[offset0+d],data[offset1+d]);
}
collapse_cache_line();
return data;
}
template <typename T>
inline arr(T) reduction_array2<T>::final_reduce_max()
{
for (int t=1; t<numThreads; t++)
for (int k=0; k<K; k++)
{
long offset0 = k*offk;
long offset1 = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset0+d] = mymax(data[offset0+d],data[offset1+d]);
}
collapse_cache_line();
return data;
}
// --------------------------------------------------------------------------
// -- final_reduce_function
// -- The function pointer version of above
// --------------------------------------------------------------------------
template <typename T>
inline arr(T) reduction_array2<T>::final_reduce_function(T (*func)(T,T))
{
for (int t=1; t<numThreads; t++)
for (int k=0; k<K; k++)
{
long offset0 = k*offk;
long offset1 = t*offt + k*offk;
for (int d=0; d<D; d++)
data[offset0+d] = func(data[offset0+d],data[offset1+d]);
}
collapse_cache_line();
return data;
}
// --------------------------------------------------------------------------
// -- collapse_cache_line
// -- collapses the cache line for the final return
// --------------------------------------------------------------------------
template <typename T>
inline void reduction_array2<T>::collapse_cache_line()
{
// doesn't need to do anything since cache_line = 1;
for (int k=1; k<K; k++)
{
long offsetOld = k*offk;
long offsetNew = k*D;
for (int d=0; d<D; d++)
data[offsetNew+d] = data[offsetOld+d];
}
}
// --------------------------------------------------------------------------
// -- final_reduce_ext_XXX
// -- Performs the reduction "XXX" on the threads into the external array.
// -- Assumes that ext is already allocated to the correct size.
// --------------------------------------------------------------------------
template <typename T>
inline void reduction_array2<T>::final_reduce_ext_add(arr(T) ext)
{
set_memory<T>(ext, 0, sizeof(T)*K*D);
for (int t=0; t<numThreads; t++)
for (int k=0; k<K; k++)
{
long offset0 = k*D;
long offset1 = t*offt + k*offk;
for (int d=0; d<D; d++)
ext[offset0+d] += data[offset1+d];
}
}
template <typename T>
inline void reduction_array2<T>::final_reduce_ext_multiply(arr(T) ext)
{
set_memory<T>(ext, 1, sizeof(T)*K*D);
for (int t=0; t<numThreads; t++)
for (int k=0; k<K; k++)
{
long offset0 = k*D;
long offset1 = t*offt + k*offk;
for (int d=0; d<D; d++)
ext[offset0+d] *= data[offset1+d];
}
}
#endif
| 36.431373 | 93 | 0.498991 | [
"vector"
] |
de1ffb37d6af2570d4a6728bb5e85eb6a16ecef9 | 3,103 | h | C | Eudoxus/include/primesense/XnEE/XnVDepthMatrix.h | roadnarrows-robotics/rnr-sdk | aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29 | [
"MIT"
] | null | null | null | Eudoxus/include/primesense/XnEE/XnVDepthMatrix.h | roadnarrows-robotics/rnr-sdk | aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29 | [
"MIT"
] | null | null | null | Eudoxus/include/primesense/XnEE/XnVDepthMatrix.h | roadnarrows-robotics/rnr-sdk | aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29 | [
"MIT"
] | null | null | null | /****************************************************************************
* *
* PrimeSense Sensor 5.x Alpha *
* Copyright (C) 2011 PrimeSense Ltd. *
* *
* This file is part of PrimeSense Sensor. *
* *
* PrimeSense Sensor 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 3 of the License, or *
* (at your option) any later version. *
* *
* PrimeSense Sensor 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 PrimeSense Sensor. If not, see <http://www.gnu.org/licenses/>.*
* *
****************************************************************************/
#ifndef _XNV_DEPTH_MATRIX_H_
#define _XNV_DEPTH_MATRIX_H_
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnVMatrix.h"
/**
* This object is a specific XnVMatrix, which holds XnDepthPixel, and should be used
* for holding depths.
* It is used by XnVDepthMap.
*/
//---------------------------------------------------------------------------
// Types
//---------------------------------------------------------------------------
class XN_EE_CORE_API XnVDepthMatrix : public XnVMatrix
{
public:
XnVDepthMatrix(XnDepthPixel* pBuffer, XnUInt16 nXRes, XnUInt16 nYRes) :
XnVMatrix(pBuffer, nXRes, nYRes, sizeof(XnDepthPixel))
{}
XnVDepthMatrix(XnUInt16 nXRes, XnUInt16 nYRes) :
XnVMatrix(nXRes, nYRes, sizeof(XnDepthPixel))
{}
operator XnDepthPixel*()
{
return (XnDepthPixel*)Data();
}
operator const XnDepthPixel*() const
{
return (const XnDepthPixel*)Data();
}
inline const XnDepthPixel& operator[](XnInt32 nIndex) const
{
return ((XnDepthPixel*)Data())[nIndex];
}
inline XnDepthPixel& operator[](XnInt32 nIndex)
{
return ((XnDepthPixel*)Data())[nIndex];
}
inline const XnDepthPixel& operator()(XnInt32 nX, XnInt32 nY) const
{
return (*this)[nY*m_nXRes+nX];
}
inline XnDepthPixel& operator()(XnInt32 nX, XnInt32 nY)
{
return (*this)[nY*m_nXRes+nX];
}
};
#endif //_XNV_DEPTH_MATRIX_H_
| 37.385542 | 84 | 0.460522 | [
"object"
] |
de2ea707c4820b7ca23f3b34a600be8449502557 | 1,176 | h | C | script/decision/filter/decision_filter.h | Andrettin/Metternich | 513a7d3cddacad5d5efd2fa5faeed03bc55a190c | [
"MIT"
] | 12 | 2019-08-03T05:58:12.000Z | 2022-01-20T20:46:41.000Z | script/decision/filter/decision_filter.h | Andrettin/Metternich | 513a7d3cddacad5d5efd2fa5faeed03bc55a190c | [
"MIT"
] | 6 | 2019-08-03T11:46:49.000Z | 2022-01-22T10:20:32.000Z | script/decision/filter/decision_filter.h | Andrettin/Metternich | 513a7d3cddacad5d5efd2fa5faeed03bc55a190c | [
"MIT"
] | null | null | null | #pragma once
#include "database/identifiable_type.h"
namespace metternich {
class character;
class holding;
struct context;
template <typename T>
class scoped_decision;
class decision_filter_base
{
public:
decision_filter_base(const std::string &identifier) : identifier(identifier)
{
}
const std::string &get_identifier() const
{
return this->identifier;
}
private:
std::string identifier;
};
template <typename T>
class decision_filter : public decision_filter_base, public identifiable_type<decision_filter<T>>
{
public:
static constexpr const char *class_identifier = "event_trigger";
decision_filter(const std::string &identifier) : decision_filter_base(identifier)
{
}
void add_decision(const scoped_decision<T> *decision)
{
this->decisions.push_back(decision);
}
void do_ai_decisions(const std::vector<T *> &scopes, character *source_character) const;
private:
std::vector<const scoped_decision<T> *> decisions;
};
extern template class decision_filter<holding>;
class holding_decision_filter final : public decision_filter<holding>
{
public:
static inline const decision_filter<holding> *owned = decision_filter::add("owned");
};
}
| 19.6 | 97 | 0.772109 | [
"vector"
] |
de3151cbd6136b9068acfaa4f07e295c380956cc | 2,489 | h | C | src/engine/components/RenderComponent.h | Polldo/dolp | a33e56d66b40a47af0af568d476fef44ca278364 | [
"MIT"
] | 3 | 2022-03-16T13:32:35.000Z | 2022-03-16T16:03:19.000Z | src/engine/components/RenderComponent.h | polldo/dolp | a33e56d66b40a47af0af568d476fef44ca278364 | [
"MIT"
] | null | null | null | src/engine/components/RenderComponent.h | polldo/dolp | a33e56d66b40a47af0af568d476fef44ca278364 | [
"MIT"
] | null | null | null | #ifndef RENDER_COMPONENT_H
#define RENDER_COMPONENT_H
#ifndef RENDER_COMPONENTS_PER_WORLD
#define RENDER_COMPONENTS_PER_WORLD (200)
#endif
#include "Common.h"
#include "engine/Pool.h"
#include "BodyComponent.h"
#include "drivers/Timer.h"
class Entity;
//typedef uint16_t* ImageColor;
//typedef uint8_t* ImageMonochrome;
// Alternative for animation
//#ifdef ANIMATION_FRAME_ALTERNATIVE
//struct AnimationFrame {
//const uint8_t* image;
//const uint32_t duration;
//};
//#endif
// Example of the alternative:
// const uint8_t numberFrames = 2;
// const AnimationFrame monsterFrames[numberFrames] = { AnimationFrame(monsterImageOne, 100), AnimationFrame(monsterImageTwo, 200) };
// const Animation monsterAnimation(monsterFrames, numberFrames);
struct Animation {
//const AnimationFrame* frames;
const uint8_t** imagesMonochrome;
const uint16_t** imagesColor;
const uint32_t* times;
uint8_t length;
Animation() : imagesMonochrome(NULL), imagesColor(NULL), times(NULL), length(0) {}
Animation(const uint8_t** img, const uint32_t* tms, uint8_t len) : imagesMonochrome(img), imagesColor(NULL), times(tms), length(len) {}
Animation(const uint16_t** img, const uint32_t* tms, uint8_t len) : imagesMonochrome(NULL), imagesColor(img), times(tms), length(len) {}
};
class RenderComponent : public Poolable {
public:
RenderComponent();
virtual ~RenderComponent();
void render();
//void update();
void setImage(const uint8_t* image);
void setImage(const uint16_t* image);
void setAnimation(const Animation& animation);
void removeAnimation();
protected:
friend class Entity;
void init(Entity* entity);
void init(Entity* entity, BodyComponent* bodyComponent);
void deinit();
private:
Entity* _entity;
BodyComponent* _bodyComponent;
const uint8_t* _imageMonochrome;
const uint16_t* _imageColor;
const Animation* _animation;
TimeoutId _animationTimeout;
uint8_t _animationCounter;
};
class RenderComponentPool : public Pool<RenderComponent, RENDER_COMPONENTS_PER_WORLD> {
public:
void render()
{
#if defined (POOL_DOUBLE_LINK)
auto component = getItems();
while (component) {
component->render();
component = static_cast<RenderComponent*>(component->getNext());
}
#else
for (int i = 0; i < RENDER_COMPONENTS_PER_WORLD; i++) {
if (_pool[i].isAllocated()) {
_pool[i].render();
}
}
#endif
}
};
#endif
| 26.763441 | 138 | 0.708718 | [
"render"
] |
de3a237a0ae1358788d2159496b3cb8ff5527e43 | 9,194 | h | C | Code/Components/Services/cpdataservices/client-cpp/current/tests/calibrationclient/IceMapperTest.h | steve-ord/askapsoft | 21b9df1b393b973ec312591efad7ee2b8c974811 | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 1 | 2020-06-18T08:37:43.000Z | 2020-06-18T08:37:43.000Z | Code/Components/Services/cpdataservices/client-cpp/current/tests/calibrationclient/IceMapperTest.h | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Services/cpdataservices/client-cpp/current/tests/calibrationclient/IceMapperTest.h | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | /// @file IceMapperTest.h
///
/// @copyright (c) 2011 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Ben Humphreys <ben.humphreys@csiro.au>
// CPPUnit includes
#include <cppunit/extensions/HelperMacros.h>
// Support classes
#include "casacore/casa/aipstype.h"
#include "casacore/casa/BasicSL/Complex.h"
#include "CalibrationDataService.h" // Ice generated interface
#include "calibaccess/JonesJTerm.h"
#include "calibaccess/JonesIndex.h"
#include "calibrationclient/GenericSolution.h"
// Classes to test
#include "calibrationclient/IceMapper.h"
namespace askap {
namespace cp {
namespace caldataservice {
class IceMapperTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(IceMapperTest);
CPPUNIT_TEST(testGainToIce);
CPPUNIT_TEST(testLeakageToIce);
CPPUNIT_TEST(testBandpassToIce);
CPPUNIT_TEST(testGainFromIce);
CPPUNIT_TEST(testLeakageFromIce);
CPPUNIT_TEST(testBandpassFromIce);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
};
void tearDown()
{
}
void testGainToIce()
{
// Build the source object
askap::cp::caldataservice::GainSolution sol(theirTimestamp);
casa::Float val = 1.0;
for (casa::Short antenna = 1; antenna <= theirNAntenna; ++antenna) {
for (casa::Short beam = 1; beam <= theirNBeam; ++beam) {
JonesJTerm jterm(casa::Complex(val, val), true,
casa::Complex(0.0, 0.0), false);
sol.map()[JonesIndex(antenna, beam)] = jterm;
val += 0.1;
}
}
// Convert
const askap::interfaces::calparams::TimeTaggedGainSolution ice_sol = IceMapper::toIce(sol);
// Compare source with the target copy
CPPUNIT_ASSERT_EQUAL(static_cast<long>(theirTimestamp), static_cast<long>(ice_sol.timestamp));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(theirNAntenna * theirNBeam), ice_sol.solutionMap.size());
val = 1.0;
for (casa::Short antenna = 1; antenna <= theirNAntenna; ++antenna) {
for (casa::Short beam = 1; beam <= theirNBeam; ++beam) {
askap::interfaces::calparams::JonesIndex jindex;
jindex.antennaID = antenna;
jindex.beamID = beam;
askap::interfaces::calparams::JonesJTerm actual = ice_sol.solutionMap.find(jindex)->second;
CPPUNIT_ASSERT_EQUAL(true, actual.g1Valid);
CPPUNIT_ASSERT_EQUAL(false, actual.g2Valid);
askap::interfaces::FloatComplex expected;
expected.real = val;
expected.imag = val;
compare(expected, actual.g1);
val += 0.1;
}
}
}
void testLeakageToIce()
{
// Build the source object
askap::cp::caldataservice::LeakageSolution sol(theirTimestamp);
// Convert
const askap::interfaces::calparams::TimeTaggedLeakageSolution ice_sol = IceMapper::toIce(sol);
// Compare source with the target copy
CPPUNIT_ASSERT_EQUAL(static_cast<long>(theirTimestamp), static_cast<long>(ice_sol.timestamp));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), ice_sol.solutionMap.size());
}
void testBandpassToIce()
{
// Build the source object
askap::cp::caldataservice::BandpassSolution sol(theirTimestamp);
// Convert
const askap::interfaces::calparams::TimeTaggedBandpassSolution ice_sol = IceMapper::toIce(sol);
// Compare source with the target copy
CPPUNIT_ASSERT_EQUAL(static_cast<long>(theirTimestamp), static_cast<long>(ice_sol.timestamp));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), ice_sol.solutionMap.size());
}
void testGainFromIce()
{
// Build the source object
askap::interfaces::calparams::TimeTaggedGainSolution ice_sol;
ice_sol.timestamp = theirTimestamp;
casa::Float val = 1.0;
for (casa::Short antenna = 1; antenna <= theirNAntenna; ++antenna) {
for (casa::Short beam = 1; beam <= theirNBeam; ++beam) {
askap::interfaces::calparams::JonesJTerm jterm;
askap::interfaces::FloatComplex g1;
g1.real = val;
g1.imag = val;
jterm.g1 = g1;
jterm.g1Valid = true;
askap::interfaces::FloatComplex g2;
g2.real = 0.0;
g2.imag = 0.0;
jterm.g2 = g2;
jterm.g2Valid = false;
askap::interfaces::calparams::JonesIndex jindex;
jindex.antennaID = antenna;
jindex.beamID = beam;
ice_sol.solutionMap[jindex] = jterm;
val += 0.1;
}
}
// Convert
const askap::cp::caldataservice::GainSolution sol = IceMapper::fromIce(ice_sol);
// Compare source with the target copy
CPPUNIT_ASSERT_EQUAL(theirTimestamp, sol.timestamp());
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(theirNAntenna * theirNBeam), sol.map().size());
val = 1.0;
for (casa::Short antenna = 1; antenna <= theirNAntenna; ++antenna) {
for (casa::Short beam = 1; beam <= theirNBeam; ++beam) {
JonesJTerm actual = sol.map().find(JonesIndex(antenna, beam))->second;
CPPUNIT_ASSERT_EQUAL(true, actual.g1IsValid());
CPPUNIT_ASSERT_EQUAL(false, actual.g2IsValid());
compare(casa::Complex(val, val), actual.g1());
val += 0.1;
}
}
}
void testLeakageFromIce()
{
// Build the source object
askap::interfaces::calparams::TimeTaggedLeakageSolution ice_sol;
ice_sol.timestamp = theirTimestamp;
// Convert
const askap::cp::caldataservice::LeakageSolution sol = IceMapper::fromIce(ice_sol);
// Compare source with the target copy
CPPUNIT_ASSERT_EQUAL(theirTimestamp, sol.timestamp());
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), sol.map().size());
}
void testBandpassFromIce()
{
// Build the source object
askap::interfaces::calparams::TimeTaggedBandpassSolution ice_sol;
ice_sol.timestamp = theirTimestamp;
// Convert
const askap::cp::caldataservice::BandpassSolution sol = IceMapper::fromIce(ice_sol);
// Compare source with the target copy
CPPUNIT_ASSERT_EQUAL(theirTimestamp, sol.timestamp());
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), sol.map().size());
}
private:
void compare(const casa::Complex& expected, const casa::Complex& actual)
{
const double tolerance = 0.000001;
CPPUNIT_ASSERT_DOUBLES_EQUAL(expected.real(), actual.real(), tolerance);
CPPUNIT_ASSERT_DOUBLES_EQUAL(expected.imag(), actual.imag(), tolerance);
}
void compare(const askap::interfaces::FloatComplex& expected,
const askap::interfaces::FloatComplex& actual)
{
const double tolerance = 0.000001;
CPPUNIT_ASSERT_DOUBLES_EQUAL(expected.real, actual.real, tolerance);
CPPUNIT_ASSERT_DOUBLES_EQUAL(expected.imag, actual.imag, tolerance);
}
static const casa::Long theirTimestamp;
static const casa::Short theirNAntenna;
static const casa::Short theirNBeam;
};
const casa::Long IceMapperTest::theirTimestamp = 1234567890;
const casa::Short IceMapperTest::theirNAntenna = 36;
const casa::Short IceMapperTest::theirNBeam = 32;
} // End namespace caldataservice
} // End namespace cp
} // End namespace askap
| 38.793249 | 111 | 0.598978 | [
"object"
] |
de525ecefd4fe79523c987073d7d57050df77fea | 2,596 | h | C | ios/versioned-react-native/ABI30_0_0/React/Base/Surface/SurfaceHostingView/ABI30_0_0RCTSurfaceHostingView.h | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 2 | 2019-05-23T20:39:18.000Z | 2019-05-24T14:00:32.000Z | ios/versioned-react-native/ABI30_0_0/React/Base/Surface/SurfaceHostingView/ABI30_0_0RCTSurfaceHostingView.h | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 2 | 2022-02-14T18:22:55.000Z | 2022-02-26T02:17:58.000Z | ios/versioned-react-native/ABI30_0_0/React/Base/Surface/SurfaceHostingView/ABI30_0_0RCTSurfaceHostingView.h | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 1 | 2020-03-01T01:28:59.000Z | 2020-03-01T01:28:59.000Z | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <ReactABI30_0_0/ABI30_0_0RCTSurfaceDelegate.h>
#import <ReactABI30_0_0/ABI30_0_0RCTSurfaceSizeMeasureMode.h>
#import <ReactABI30_0_0/ABI30_0_0RCTSurfaceStage.h>
@class ABI30_0_0RCTBridge;
@class ABI30_0_0RCTSurface;
typedef UIView *(^ABI30_0_0RCTSurfaceHostingViewActivityIndicatorViewFactory)();
NS_ASSUME_NONNULL_BEGIN
/**
* UIView subclass which providers interoperability between UIKit and
* Surface regarding layout and life-cycle.
* This class can be used as easy-to-use general purpose integration point
* of ReactABI30_0_0Native-powered experiences in UIKit based apps.
*/
@interface ABI30_0_0RCTSurfaceHostingView : UIView <ABI30_0_0RCTSurfaceDelegate>
/**
* Designated initializer.
* Instanciates a view with given Surface object.
* Note: The view retains the surface object.
*/
- (instancetype)initWithSurface:(ABI30_0_0RCTSurface *)surface NS_DESIGNATED_INITIALIZER;
/**
* Convenience initializer.
* Instanciates a Surface object with given `bridge`, `moduleName`, and
* `initialProperties`, and then use it to instanciate a view.
*/
- (instancetype)initWithBridge:(ABI30_0_0RCTBridge *)bridge
moduleName:(NSString *)moduleName
initialProperties:(NSDictionary *)initialProperties;
/**
* Create an instance of ABI30_0_0RCTSurface to be hosted.
*/
- (ABI30_0_0RCTSurface *)createSurfaceWithBridge:(ABI30_0_0RCTBridge *)bridge
moduleName:(NSString *)moduleName
initialProperties:(NSDictionary *)initialProperties;
/**
* Surface object which is currently using to power the view.
* Read-only.
*/
@property (nonatomic, strong, readonly) ABI30_0_0RCTSurface *surface;
/**
* Size measure mode which are defining relationship between UIKit and ReactABI30_0_0Native
* layout approaches.
* Defaults to `ABI30_0_0RCTSurfaceSizeMeasureModeWidthAtMost | ABI30_0_0RCTSurfaceSizeMeasureModeHeightAtMost`.
*/
@property (nonatomic, assign) ABI30_0_0RCTSurfaceSizeMeasureMode sizeMeasureMode;
/**
* Activity indicator factory.
* A hosting view may use this block to instantiate and display custom activity
* (loading) indicator (aka "spinner") when it needed.
* Defaults to `nil` (no activity indicator).
*/
@property (nonatomic, copy, nullable) ABI30_0_0RCTSurfaceHostingViewActivityIndicatorViewFactory activityIndicatorViewFactory;
@end
NS_ASSUME_NONNULL_END
| 34.157895 | 126 | 0.769646 | [
"object"
] |
de544a4ec1e9aee919d2d9fcb08492f621ac1006 | 21,946 | h | C | zircon/system/ulib/zbitl/include/lib/zbitl/view.h | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 10 | 2020-12-28T17:04:44.000Z | 2022-03-12T03:20:43.000Z | zircon/system/ulib/zbitl/include/lib/zbitl/view.h | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | zircon/system/ulib/zbitl/include/lib/zbitl/view.h | dahliaOS/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIB_ZBITL_VIEW_H_
#define LIB_ZBITL_VIEW_H_
#include <lib/cksum.h>
#include <lib/fitx/result.h>
#include <zircon/assert.h>
#include <zircon/boot/image.h>
#include <functional>
#include <optional>
#include <type_traits>
#include <variant>
#include "checking.h"
#include "storage_traits.h"
namespace zbitl {
/// The zbitl::View template class provides an error-checking container view of
/// a ZBI. It satisfies the C++20 std::forward_range concept; it satisfies the
/// std::view concept if the Storage and Storage::error_type types support
/// constant-time copy/move/assignment.
///
/// The "error-checking view" pattern means that the container/range/view API
/// of begin() and end() iterators is supported, but when begin() or
/// iterator::operator++() encounters an error, it simply returns end() so that
/// loops terminate normally. Thereafter, take_error() must be called to check
/// whether the loop terminated because it iterated past the last item or
/// because it encountered an error. Once begin() has been called,
/// take_error() must be called before the View is destroyed, so no error goes
/// undetected. Since all use of iterators updates the error state, use of any
/// zbitl::View object must be serialized and after begin() or operator++()
/// yields end(), take_error() must be checked before using begin() again.
///
/// Each time begin() is called the underlying storage is examined afresh, so
/// it's safe to reuse a zbitl::View object after changing the data. Reducing
/// the size of the underlying storage invalidates any iterators that pointed
/// past the new end of the image. It's simplest just to assume that changing
/// the underlying storage always invalidates all iterators.
///
/// The Storage type is some type that can be abstractly considered to have
/// non-owning "view" semantics: it doesn't hold the storage of the ZBI, it
/// just refers to it somehow. The zbitl::View:Error type describes errors
/// encountered while iterating. It uses the Storage::error_type type to
/// propagate errors caused by access to the underlying storage.
///
/// Usually Storage and Storage:error_type types are small and can be copied.
/// zbitl::View is move-only if Storage is move-only or if Storage::error_type
/// is move-only. Note that copying zbitl::View copies its error-checking
/// state exactly, so if the original View needed to be checked for errors
/// before destruction then both the original and the copy need to be checked
/// before their respective destructions. A moved-from zbitl::View can always
/// be destroyed without checking.
template <typename Storage, Checking Check = Checking::kStrict>
class View {
public:
using storage_type = Storage;
View() = default;
View(const View&) = default;
View& operator=(const View&) = default;
// This is almost the same as the default move behavior. But it also
// explicitly resets the moved-from error state to kUnused so that the
// moved-from View can be destroyed without checking it.
View(View&& other)
: error_(std::move(other.error_)), storage_(std::move(other.storage_)), limit_(other.limit_) {
other.error_ = Unused{};
other.limit_ = 0;
}
View& operator=(View&& other) {
error_ = std::move(other.error_);
other.error_ = Unused{};
storage_ = std::move(other.storage_);
limit_ = other.limit_;
other.limit_ = 0;
return *this;
}
explicit View(storage_type storage) : storage_(std::move(storage)) {}
~View() {
ZX_ASSERT_MSG(!std::holds_alternative<Error>(error_),
"zbitl::View destroyed after error without check");
ZX_ASSERT_MSG(!std::holds_alternative<NoError>(error_),
"zbtil::View destroyed after successful iteration without check");
}
/// The API details of what Storage means are delegated to the StorageTraits
/// template; see <lib/zbitl/storage_traits.h>.
using Traits = StorageTraits<Storage>;
static_assert(std::is_default_constructible_v<typename Traits::error_type>);
static_assert(std::is_copy_constructible_v<typename Traits::error_type>);
static_assert(std::is_copy_assignable_v<typename Traits::error_type>);
static_assert(std::is_default_constructible_v<typename Traits::payload_type>);
static_assert(std::is_copy_constructible_v<typename Traits::payload_type>);
static_assert(std::is_copy_assignable_v<typename Traits::payload_type>);
/// The header is represented by an opaque type that can be dereferenced as
/// if it were `const zbi_header_t*`, i.e. `*header` or `header->member`.
/// Either it stores the `zbi_header_t` directly or it holds a pointer into
/// someplace owned or viewed by the Storage object. In the latter case,
/// i.e. when Storage represents something already in memory, `header_type`
/// should be no larger than a plain pointer.
class header_type {
public:
header_type() = default;
header_type(const header_type&) = default;
header_type(header_type&&) = default;
header_type& operator=(const header_type&) = default;
header_type& operator=(header_type&&) = default;
/// `*header` always copies, so lifetime of `this` doesn't matter.
zbi_header_t operator*() const {
if constexpr (kCopy) {
return stored_;
} else {
return *stored_;
}
}
/// `header->member` refers to the header in place, so never do
/// `&header->member` but always dereference a member directly.
const zbi_header_t* operator->() const {
if constexpr (kCopy) {
return &stored_;
} else {
return stored_;
}
}
private:
using TraitsHeader = decltype(Traits::Header(std::declval<View>().storage(), 0));
static constexpr bool kCopy =
std::is_same_v<TraitsHeader, fitx::result<typename Traits::error_type, zbi_header_t>>;
static constexpr bool kReference =
std::is_same_v<TraitsHeader, fitx::result<typename Traits::error_type,
std::reference_wrapper<const zbi_header_t>>>;
static_assert(kCopy || kReference,
"zbitl::StorageTraits specialization's Header function returns wrong type");
friend View;
using HeaderStorage = std::conditional_t<kCopy, zbi_header_t, const zbi_header_t*>;
HeaderStorage stored_;
// This can only be used by begin(), below.
template <typename T>
explicit header_type(const T& header)
: stored_([&header]() {
if constexpr (kCopy) {
static_assert(std::is_same_v<zbi_header_t, T>);
return header;
} else {
static_assert(std::is_same_v<std::reference_wrapper<const zbi_header_t>, T>);
return &(header.get());
}
}()) {}
};
/// The payload type is provided by the StorageTraits specialization. It's
/// opaque to View, but must be default-constructible, copy-constructible,
/// and copy-assignable. It's expected to have "view"-style semantics,
/// i.e. be small and not own any storage itself but only refer to storage
/// owned by the Storage object.
using payload_type = typename Traits::payload_type;
/// The element type is a trivial struct morally equivalent to
/// std::pair<header_type, payload_type>. Both member types are
/// default-constructible, copy-constructible, and copy-assignable, so
/// value_type as a whole is as well.
struct value_type {
header_type header;
payload_type payload;
};
/// The Error type is returned by take_error() after begin() or an iterator
/// operator encountered an error. There is always a string description of
/// the error. Errors arising from Storage access also provide an error
/// value defined via StorageTraits; see <lib/zbitl/storage_traits.h>.
struct Error {
/// A string constant describing the error.
std::string_view zbi_error{};
/// This is the offset into the ZBI of the item (header) at fault. This is
/// zero for problems with the overall container, which begin() detects.
/// In iterator operations, it refers to the offset into the image where
/// the item was (or should have been).
uint32_t item_offset = 0;
/// This reflects the underlying error from accessing the Storage object,
/// if any. If storage_error.has_value() is false, then the error is in
/// the format of the contents of the ZBI, not in accessing the contents.
std::optional<typename Traits::error_type> storage_error{};
};
/// Check the container for errors after using iterators. When begin() or
/// iterator::operator++() encounters an error, it simply returns end() so
/// that loops terminate normally. Thereafter, take_error() must be called
/// to check whether the loop terminated because it iterated past the last
/// item or because it encountered an error. Once begin() has been called,
/// take_error() must be called before the View is destroyed, so no error
/// goes undetected. After take_error() is called the error state is
/// consumed and take_error() cannot be called again until another begin() or
/// iterator::operator++() call has been made.
[[nodiscard]] fitx::result<Error> take_error() {
ErrorState result = std::move(error_);
error_ = Taken{};
if (std::holds_alternative<Error>(result)) {
return fitx::error{std::move(std::get<Error>(result))};
}
ZX_ASSERT_MSG(!std::holds_alternative<Taken>(result),
"zbitl::View::take_error() was already called");
return fitx::ok();
}
/// If you explicitly don't care about any error that might have terminated
/// the last loop early, then call ignore_error() instead of take_error().
void ignore_error() { static_cast<void>(take_error()); }
/// Trivial accessor for the underlying Storage (view) object.
storage_type& storage() { return storage_; }
class iterator {
public:
/// The default-constructed iterator is invalid for all uses except
/// equality comparison.
iterator() = default;
iterator& operator=(const iterator&) = default;
bool operator==(const iterator& other) const {
return other.view_ == view_ && other.offset_ == offset_;
}
bool operator!=(const iterator& other) const { return !(*this == other); }
iterator& operator++() { // prefix
Assert(__func__);
view_->StartIteration();
ZX_DEBUG_ASSERT(offset_ >= sizeof(zbi_header_t));
ZX_DEBUG_ASSERT(offset_ <= view_->limit_);
ZX_DEBUG_ASSERT(offset_ % ZBI_ALIGNMENT == 0);
if (view_->limit_ - offset_ < sizeof(zbi_header_t)) {
// Reached the end of the container.
if constexpr (Check != Checking::kPermissive) {
if (offset_ != view_->limit_) {
Fail("container too short for next item header");
}
}
*this = view_->end();
} else if (auto header = Traits::Header(view_->storage(), offset_); header.is_error()) {
// Failed to read the next header.
Fail("cannot read item header", std::move(header.error_value()));
} else if (auto header_error = CheckHeader<Check>(header.value(), view_->limit_ - offset_);
header_error.is_error()) {
Fail(header_error.error_value());
} else {
header_ = header_type(header.value());
offset_ += static_cast<uint32_t>(sizeof(zbi_header_t));
if (auto payload = Traits::Payload(view_->storage(), offset_, header_->length);
payload.is_error()) {
Fail("cannot extract payload view", std::move(payload.error_value()));
} else {
offset_ += ZBI_ALIGN(header_->length);
payload_ = std::move(payload.value());
if constexpr (Check == Checking::kCrc) {
if (header_->flags & ZBI_FLAG_CRC32) {
uint32_t item_crc32 = 0;
auto compute_crc32 = [&item_crc32](ByteView chunk) -> fitx::result<fitx::failed> {
item_crc32 =
crc32(item_crc32, reinterpret_cast<const uint8_t*>(chunk.data()), chunk.size());
return fitx::ok();
};
// An item's CRC32 is computed as the hash of its header with its
// crc32 field set to 0, combined with the hash of its payload.
zbi_header_t header_without_crc32 = *header_;
header_without_crc32.crc32 = 0;
static_cast<void>(compute_crc32({reinterpret_cast<std::byte*>(&header_without_crc32),
sizeof(header_without_crc32)}));
if (auto result =
Traits::Read(view_->storage(), payload_, header_->length, compute_crc32);
result.is_error()) {
Fail("cannot compute item CRC32", std::move(result.error_value()));
} else {
ZX_DEBUG_ASSERT(result.value().is_ok());
if (item_crc32 != header_->crc32) {
Fail("item CRC32 mismatch");
}
}
}
}
}
}
return *this;
}
iterator operator++(int) { // postfix
iterator old = *this;
++*this;
return old;
}
value_type operator*() const {
Assert(__func__);
return {header_, payload_};
}
uint32_t item_offset() const {
return payload_offset() - static_cast<uint32_t>(sizeof(zbi_header_t));
}
uint32_t payload_offset() const {
Assert(__func__);
return offset_ - ZBI_ALIGN(header_->length);
}
private:
// The default-constructed state is almost the same as the end() state:
// nothing but operator==() should ever be called if view_ is nullptr.
View* view_ = nullptr;
// The offset into the ZBI of the next item's header. This is 0 in
// default-constructed iterators and kEnd_ in end() iterators, where
// operator*() can never be called. A valid non-end() iterator holds the
// header and payload (references) of the "current" item for operator*() to
// return, and its offset_ always looks past to the horizon. If offset_ as
// at the end of the container, then operator++() will yield end().
uint32_t offset_ = 0;
// end() uses a different offset_ value to distinguish a true end iterator
// from a particular view from a default-constructed iterator from nowhere.
static constexpr uint32_t kEnd_ = std::numeric_limits<uint32_t>::max();
// These are left uninitialized until a successful increment sets them.
// They are only examined by a dereference, which is invalid without
// a successful increment.
header_type header_{};
payload_type payload_;
// This is called only by begin() and end().
friend class View;
iterator(View* view, bool is_end)
: view_(view), offset_(is_end ? kEnd_ : sizeof(zbi_header_t)) {
ZX_DEBUG_ASSERT(view_);
if (!is_end) {
// The initial offset_ points past the container header, to the first
// item. The first increment reaches end() or makes the iterator valid.
++*this;
}
}
void Fail(std::string_view sv,
std::optional<typename Traits::error_type> storage_error = std::nullopt) {
view_->Fail({sv, offset_, std::move(storage_error)});
*this = view_->end();
}
void Assert(const char* func) const {
ZX_ASSERT_MSG(view_, "%s on default-constructed zbitl::View::iterator", func);
ZX_ASSERT_MSG(offset_ != kEnd_, "%s on zbitl::View::end() iterator", func);
}
};
// This returns its own error state and does not affect the `take_error()`
// state of the View.
fitx::result<Error, zbi_header_t> container_header() {
auto capacity_error = Traits::Capacity(storage());
if (capacity_error.is_error()) {
return fitx::error{
Error{"cannot determine storage capacity", 0, std::move(capacity_error.error_value())}};
}
uint32_t capacity = capacity_error.value();
// Minimal bounds check before trying to read.
if (capacity < sizeof(zbi_header_t)) {
return fitx::error(
Error{"storage capacity too small for ZBI container header", capacity, {}});
}
// Read and validate the container header.
auto header_error = Traits::Header(storage(), 0);
if (header_error.is_error()) {
// Failed to read the container header.
return fitx::error{
Error{"cannot read container header", 0, std::move(header_error.error_value())}};
}
const header_type header(std::move(header_error.value()));
auto check_error = CheckHeader<Check>(*header, capacity);
if (check_error.is_error()) {
return fitx::error(Error{check_error.error_value(), 0, {}});
}
if constexpr (Check != Checking::kPermissive) {
if (header->flags & ZBI_FLAG_CRC32) {
return fitx::error(Error{"container header has CRC32 flag", 0, {}});
}
}
if (header->length % ZBI_ALIGNMENT != 0) {
return fitx::error(Error{"container header has misaligned length", 0, {}});
}
return fitx::ok(*header);
}
/// After calling begin(), it's mandatory to call take_error() before
/// destroying the View object. An iteration that encounters an error will
/// simply end early, i.e. begin() or operator++() will yield an iterator
/// that equals end(). At the end of a loop, call take_error() to check for
/// errors. It's also acceptable to call take_error() during an iteration
/// that hasn't reached end() yet, but it cannot be called again before the
/// next begin() or operator++() call.
iterator begin() {
StartIteration();
auto header = container_header();
if (header.is_error()) {
Fail(header.error_value());
limit_ = 0; // Reset from past uses.
return end();
}
// The container's "payload" is all the items. Don't scan past it.
limit_ = static_cast<uint32_t>(sizeof(zbi_header_t) + header->length);
return {this, false};
}
iterator end() { return {this, true}; }
size_t size_bytes() {
if (std::holds_alternative<Unused>(error_)) {
ZX_ASSERT(limit_ == 0);
// Taking the size before doing begin() takes extra work.
auto capacity_error = Traits::Capacity(storage());
if (capacity_error.is_ok()) {
uint32_t capacity = capacity_error.value();
if (capacity >= sizeof(zbi_header_t)) {
auto header_error = Traits::Header(storage(), 0);
if (header_error.is_ok()) {
const header_type header(header_error.value());
if (header->length <= capacity - sizeof(zbi_header_t)) {
return sizeof(zbi_header_t) + header->length;
}
}
}
}
}
return limit_;
}
// Replace an item's header with a new one, using an iterator into this
// view.. This never changes the existing item's length (nor its payload),
// and always writes a header that passes Checking::kStrict. So the header
// can be `{.type = XYZ}` alone or whatever fields and flags matter. Note
// this returns only the storage error type, not an Error since no ZBI
// format errors are possible here, only a storage failure to update.
//
// This method is not available if zbitl::StorageTraits<storage_type>
// doesn't support mutation.
template < // SFINAE check for Traits::Write method.
typename T = Traits,
typename = std::void_t<decltype(
T::Write(std::declval<std::reference_wrapper<storage_type>>().get(), 0, ByteView{}))>>
fitx::result<typename Traits::error_type> EditHeader(const iterator& item, zbi_header_t header) {
item.Assert(__func__);
header = SanitizeHeader(header);
header.length = item.header_->length;
return Traits::Write(storage(), item.item_offset(), AsBytes(header));
}
// When the iterator is mutable and not a temporary, make the next
// operator*() consistent with the new header if it worked. For kReference
// storage types, the change is reflected intrinsically.
template < // SFINAE check for Traits::Write method.
typename T = Traits,
typename = std::void_t<decltype(
T::Write(std::declval<std::reference_wrapper<storage_type>>().get(), 0, ByteView{}))>>
fitx::result<typename Traits::error_type> EditHeader(iterator& item, zbi_header_t header) {
auto result = EditHeader(const_cast<const iterator&>(item), header);
if constexpr (header_type::kCopy) {
if (result.is_ok()) {
item.header_.stored_ = header;
}
}
return result;
}
private:
struct Unused {};
struct NoError {};
struct Taken {};
using ErrorState = std::variant<Unused, NoError, Error, Taken>;
void StartIteration() {
ZX_ASSERT_MSG(!std::holds_alternative<Error>(error_),
"zbitl:View iterators used without taking prior error");
error_ = NoError{};
}
void Fail(Error error) {
ZX_DEBUG_ASSERT_MSG(!std::holds_alternative<Error>(error_),
"Fail in error state: missing zbitl::View::StartIteration() call?");
ZX_DEBUG_ASSERT_MSG(!std::holds_alternative<Unused>(error_),
"Fail in Unused: missing zbitl::View::StartIteration() call?");
error_ = std::move(error);
}
storage_type storage_;
ErrorState error_;
uint32_t limit_ = 0;
};
// Deduction guide: View v(T{}) instantiates View<T>.
template <typename Storage>
explicit View(Storage) -> View<Storage>;
// A shorthand for permissive checking.
template <typename Storage>
using PermissiveView = View<Storage, Checking::kPermissive>;
// A shorthand for CRC checking.
template <typename Storage>
using CrcCheckingView = View<Storage, Checking::kCrc>;
} // namespace zbitl
#endif // LIB_ZBITL_VIEW_H_
| 40.94403 | 100 | 0.662034 | [
"object"
] |
59e638c73d6e353d62769d033cd6b6d1e6f21f18 | 21,154 | h | C | GL_SDL_hybrid_IK/Lights.h | akiipli/Allan | 9cc89bb219c04225a4139ad8b5e3edea251a2820 | [
"MIT"
] | null | null | null | GL_SDL_hybrid_IK/Lights.h | akiipli/Allan | 9cc89bb219c04225a4139ad8b5e3edea251a2820 | [
"MIT"
] | 1 | 2019-01-23T15:36:17.000Z | 2019-02-02T13:43:45.000Z | GL_SDL_hybrid_IK/Lights.h | akiipli/Allan | 9cc89bb219c04225a4139ad8b5e3edea251a2820 | [
"MIT"
] | null | null | null | /*
In this file i attempt uniform block bindings
for fog and light.
Maybe these features grow more complicated in
the future and Light and fog get more members
in them. Right now i use light position to create
normalized reversed light vector.
*/
/*look OFFSETCOMMENT*/
int Themes = 12;
char Hint[STRLEN];
void init_Hint()
{
sprintf(Hint, "Light theme:%d Alt+U\nNight:%d Alt+N Shadows:%d Alt+S\n\nELEMENT ARRAYS: %d",
currentTheme, NIGHT, SHADOWS, ELEMENT_ARRAYS);
}
GLuint lightHandle, fogHandle, materialSHandle3;
typedef struct
{
float Ka[3]; // Ambient reflectivity
float Kd[3]; // Diffuse reflectivity
float Ks[3]; // Specular reflectivity
float Shininess; // Specular shininess
}
MaterialS;
MaterialS materialS;
typedef struct
{
float Position[3];
float Ambient[3];
}
Light;
Light light;
Light Light_Themes[12];
void init_MATERIALS()
{
glGenBuffers(1, &materialSHandle3);
float color[3] = {0.7, 0.5, 0.3};
memcpy(&materialS.Ka, (float[3]){0.07, 0.05, 0.03}, sizeof(color));
memcpy(&materialS.Kd, color, sizeof(color));
memcpy(&materialS.Ks, (float[3]){0.9,0.9,0.9}, sizeof(color));
materialS.Shininess = 1;
}
void init_LIGHT_THEME()
{
glGenBuffers(1, &lightHandle);
memcpy(&Light_Themes[0], (void*){(float[6]){10, 10, 10, 1.0, 0.0, 0.0}}, sizeof(Light));
memcpy(&Light_Themes[1], (void*){(float[6]){-10, 10, -10, 0.1, 0.1, 1.0}}, sizeof(Light));
memcpy(&Light_Themes[2], (void*){(float[6]){-10, -10, -10, 0.1, 0.1, 1.0}}, sizeof(Light));
memcpy(&Light_Themes[3], (void*){(float[6]){10, -10, -10, 0.1, 1.0, 0.1}}, sizeof(Light));
memcpy(&Light_Themes[4], (void*){(float[6]){-10, 10, 10, 1.0, 0.0, 1.0}}, sizeof(Light));
memcpy(&Light_Themes[5], (void*){(float[6]){-10, -10, -10, 1.0, 0.1, 0.1}}, sizeof(Light));
memcpy(&Light_Themes[6], (void*){(float[6]){-10, -10, 10, -1.0, 0.1, 0.1}}, sizeof(Light));
memcpy(&Light_Themes[7], (void*){(float[6]){-10, 10, 10, -0.1, 1.1, -1.0}}, sizeof(Light));
memcpy(&Light_Themes[8], (void*){(float[6]){-10, -10, 10, -0.1, -0.1, -1.0}}, sizeof(Light));
memcpy(&Light_Themes[9], (void*){(float[6]){10, -10, -10, 1.0, -1.0, -0.1}}, sizeof(Light));
memcpy(&Light_Themes[10], (void*){(float[6]){-10, 10, 10, 1.0, 0.0, -1.0}}, sizeof(Light));
memcpy(&Light_Themes[11], (void*){(float[6]){10, 10, 10, -1.0, -0.1, -1.0}}, sizeof(Light));
}
typedef struct
{
float Color[4];
float Distance;
float min_Distance;
}
Fog;
Fog fog;
void init_materialS()
{
GLint blockSize;
glGetActiveUniformBlockiv(T_program[4], uniform_mat4, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);
GLubyte * blockBuffer;
blockBuffer = (GLubyte*)malloc(blockSize);
GLint offset[4];
offset[0] = 0;
offset[1] = 4 * sizeof(GLfloat); /*OFFSETCOMMENT*/
offset[2] = offset[1] + 4 * sizeof(GLfloat);
offset[3] = offset[2] + 4 * sizeof(GLfloat);
memcpy(blockBuffer + offset[0], materialS.Ka, 3 * sizeof(GLfloat));
memcpy(blockBuffer + offset[1], materialS.Kd, 3 * sizeof(GLfloat));
memcpy(blockBuffer + offset[2], materialS.Ks, 3 * sizeof(GLfloat));
memcpy(blockBuffer + offset[3], &materialS.Shininess, sizeof(GLfloat));
glBindBuffer(GL_UNIFORM_BUFFER, materialSHandle3);
glBufferData(GL_UNIFORM_BUFFER, blockSize, blockBuffer, GL_DYNAMIC_DRAW);
free(blockBuffer);
}
GLuint shadowFBO, pass1Index, pass2Index;
float shadowMapWidth = 512 * 2;
float shadowMapHeight = 512 * 2;
void init_shadows()
{
pass1Index = glGetSubroutineIndex(T_program[4], GL_FRAGMENT_SHADER, "recordDepth");
pass2Index = glGetSubroutineIndex(T_program[4], GL_FRAGMENT_SHADER, "shadeWithShadow");
}
void init_lights()
{
GLint blockSize;
glGetActiveUniformBlockiv(T_program[2], uniform_light2, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);
// CheckGLError();
GLubyte * blockBuffer;
// printf("%d\n", blockSize);
blockBuffer = (GLubyte*)malloc(blockSize);
// const GLchar * names[] = {"Position", "Ambient"};
// GLuint indices[2];
// glGetUniformIndices(T_program[2], 2, names, indices);
//
GLint offset[2];
offset[0] = 0;
offset[1] = 4 * sizeof(GLfloat); /*OFFSETCOMMENT*/
// glGetActiveUniformsiv(T_program[2], 2, indices, GL_UNIFORM_OFFSET, offset);
//
memcpy(blockBuffer + offset[0], light.Position, 3 * sizeof(GLfloat));
memcpy(blockBuffer + offset[1], light.Ambient, 3 * sizeof(GLfloat));
glBindBuffer(GL_UNIFORM_BUFFER, lightHandle);
glBufferData(GL_UNIFORM_BUFFER, blockSize, blockBuffer, GL_DYNAMIC_DRAW);
free(blockBuffer);
}
float shadowBias[16];
float shadowMatrix[16];
void setMatrices()
{
memcpy(shadowBias, (float[16]){
0.5f,0.0f,0.0f,0.0f,
0.0f,0.5f,0.0f,0.0f,
0.0f,0.0f,0.5f,0.0f,
0.5f,0.5f,0.5f,1.0f}, sizeof(shadowBias)
);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(45, 1, 1, 60);
gluLookAt(light.Position[0], light.Position[1], light.Position[2], 0, 0, 0, 0, 1, 0);
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix);
rotate_matrix_I_4x4((void *)shadowMatrix, (void *)shadowBias, (void *)projectionMatrix);
// shadowMatrix = shadowBias * projectionMatrix;
}
void update_Light(Light L)
{
//float len = sqrt(L.Position[0] * L.Position[0] + L.Position[1] * L.Position[1] + L.Position[2] * L.Position[2]);
memcpy(light.Position, (float[3]){L.Position[0], L.Position[1], L.Position[2]}, sizeof(light.Position));
memcpy(light.Ambient, (float[3]){L.Ambient[0], L.Ambient[1], L.Ambient[2]}, sizeof(light.Ambient));
setMatrices();
}
void update_fog()
{
GLint blockSize;
glGetActiveUniformBlockiv(T_program[2], uniform_fog2, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);
GLubyte * blockBuffer;
blockBuffer = (GLubyte*)malloc(blockSize);
//
GLint offset[3];
offset[0] = 0;
offset[1] = 4 * sizeof(GLfloat); /*OFFSETCOMMENT*/
offset[2] = offset[1] + sizeof(GLfloat);
// glGetActiveUniformsiv(T_program[2], 2, indices, GL_UNIFORM_OFFSET, offset);
//
memcpy(blockBuffer + offset[0], fog.Color, 4 * sizeof(GLfloat));
memcpy(blockBuffer + offset[1], &fog.Distance, sizeof(GLfloat));
memcpy(blockBuffer + offset[2], &fog.min_Distance, sizeof(GLfloat));
glBindBuffer(GL_UNIFORM_BUFFER, fogHandle);
glBufferData(GL_UNIFORM_BUFFER, blockSize, blockBuffer, GL_DYNAMIC_DRAW);
free(blockBuffer);
}
void init_fog()
{
GLfloat color[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, color);
memcpy(fog.Color, color, sizeof(fog.Color));
fog.Distance = 100;
fog.min_Distance = 10;
GLint blockSize;
glGetActiveUniformBlockiv(T_program[2], uniform_fog2, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);
CheckGLError();
GLubyte * blockBuffer;
printf("%d\n", blockSize);
blockBuffer = (GLubyte*)malloc(blockSize);
const GLchar * names[] = {"Color", "Distance"};
GLuint indices[2];
glGetUniformIndices(T_program[2], 2, names, indices);
//
GLint offset[3];
offset[0] = 0;
offset[1] = 4 * sizeof(GLfloat); /*OFFSETCOMMENT*/
offset[2] = offset[1] + sizeof(GLfloat);
// glGetActiveUniformsiv(T_program[2], 2, indices, GL_UNIFORM_OFFSET, offset);
//
memcpy(blockBuffer + offset[0], fog.Color, 4 * sizeof(GLfloat));
memcpy(blockBuffer + offset[1], &fog.Distance, sizeof(GLfloat));
memcpy(blockBuffer + offset[2], &fog.min_Distance, sizeof(GLfloat));
glGenBuffers(1, &fogHandle);
glBindBuffer(GL_UNIFORM_BUFFER, fogHandle);
glBufferData(GL_UNIFORM_BUFFER, blockSize, blockBuffer, GL_DYNAMIC_DRAW);
}
void render_polys_OnScreen_Shadows(camera * C, int currentObject, int mode, int Selection_Mode, int update_colors, int update_uv, int elem);
void render_quads_OnScreen_Shadows(camera * C, int l, int currentObject, int mode, int Selection_Mode, int update_colors, int update_uv, int elem);
void SceneShadowMap_render(camera * C, int width, int height, int subdLevel, int elem)
{
glUseProgram(T_program[4]);
// Pass 1 (shadow map generation)
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(45, 1, 1, 60);
gluLookAt(light.Position[0], light.Position[1], light.Position[2], 0, 0, 0, 0, 1, 0);
glBindFramebuffer(GL_FRAMEBUFFER, shadowFBO);
GLint params[4];
glGetIntegerv(GL_SCISSOR_BOX, params);
glScissor(0, 0, shadowMapWidth,shadowMapHeight);
glClear(GL_DEPTH_BUFFER_BIT);
glViewport(0,0,shadowMapWidth,shadowMapHeight);
glUniformSubroutinesuiv(GL_FRAGMENT_SHADER, 1, &pass1Index);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(2.5f,10.0f);
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix);
//glEnable(GL_ALPHA_TEST);
//glAlphaFunc(GL_GREATER, 0);
//glEnable(GL_STENCIL_TEST);
//glStencilFunc(GL_GEQUAL, 1, 0xFF);
//glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
//glStencilMask(0x00);
//glDepthMask(GL_TRUE);
if (subdLevel == -1)
render_polys_OnScreen_Shadows(C, 0, 0, 0, 0, 0, elem);
else
render_quads_OnScreen_Shadows(C, subdLevel, 0, 0, 0, 0, 0, elem);
//glDisable(GL_STENCIL_TEST);
//glDisable(GL_ALPHA_TEST);
glCullFace(GL_BACK);
//glFlush();
glPopMatrix();
// Pass 2 (render)
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glScissor(params[0], params[1], params[2], params[3]);
glUseProgram(0);
}
GLuint depthFBO;
GLuint depthTex, drag_texture;
#define D_plane 3000
float drag_depth_Width;
float drag_depth_Height;
//float Drag_Plane[4][3] = {{-D_plane, D_plane, 1}, {-D_plane, -D_plane, 1}, {D_plane, -D_plane, 1}, {D_plane, D_plane, 1}};
GLfloat winX, winY, winZ;
struct
{
float A[3], A_[3];
float B[3], B_[3];
float C[3], C_[3];
float D[3], D_[3];
}
Drag_Plane;
void init_Drag_Plane(float width, float height)
{
memcpy(Drag_Plane.A_, (float[3]){-D_plane, D_plane, 1}, sizeof(float[3]));
memcpy(Drag_Plane.B_, (float[3]){-D_plane, -D_plane, 1}, sizeof(float[3]));
memcpy(Drag_Plane.C_, (float[3]){D_plane, -D_plane, 1}, sizeof(float[3]));
memcpy(Drag_Plane.D_, (float[3]){D_plane, D_plane, 1}, sizeof(float[3]));
drag_depth_Width = width;
drag_depth_Height = height;
}
void render_Depth_Drag_Plane();
void rotate_Drag_Plane(camera * C)
{
direction D1;
rotate_Vertex_I(C->T->rotVec_, Drag_Plane.A_[0], Drag_Plane.A_[1], Drag_Plane.A_[2], &D1);
memcpy(Drag_Plane.A, &D1, sizeof(float[3]));
rotate_Vertex_I(C->T->rotVec_, Drag_Plane.B_[0], Drag_Plane.B_[1], Drag_Plane.B_[2], &D1);
memcpy(Drag_Plane.B, &D1, sizeof(float[3]));
rotate_Vertex_I(C->T->rotVec_, Drag_Plane.C_[0], Drag_Plane.C_[1], Drag_Plane.C_[2], &D1);
memcpy(Drag_Plane.C, &D1, sizeof(float[3]));
rotate_Vertex_I(C->T->rotVec_, Drag_Plane.D_[0], Drag_Plane.D_[1], Drag_Plane.D_[2], &D1);
memcpy(Drag_Plane.D, &D1, sizeof(float[3]));
}
void translate_Drag_Plane(camera * C)
{
Drag_Plane.A[0] += C->T->pos[0];
Drag_Plane.A[1] += C->T->pos[1];
Drag_Plane.A[2] += C->T->pos[2];
Drag_Plane.B[0] += C->T->pos[0];
Drag_Plane.B[1] += C->T->pos[1];
Drag_Plane.B[2] += C->T->pos[2];
Drag_Plane.C[0] += C->T->pos[0];
Drag_Plane.C[1] += C->T->pos[1];
Drag_Plane.C[2] += C->T->pos[2];
Drag_Plane.D[0] += C->T->pos[0];
Drag_Plane.D[1] += C->T->pos[1];
Drag_Plane.D[2] += C->T->pos[2];
}
void Drag_Plane_render_action()
{
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix);
render_Depth_Drag_Plane();
glCullFace(GL_BACK);
}
void Drag_Plane_transforms(float ObjDist, camera * C)
{
Drag_Plane.A_[2] = ObjDist;
Drag_Plane.B_[2] = ObjDist;
Drag_Plane.C_[2] = ObjDist;
Drag_Plane.D_[2] = ObjDist;
rotate_Drag_Plane(C);
translate_Drag_Plane(C);
}
/*
void Drag_Plane_render(float ObjDist, camera * C)
{
Drag_Plane.A_[2] = ObjDist;
Drag_Plane.B_[2] = ObjDist;
Drag_Plane.C_[2] = ObjDist;
Drag_Plane.D_[2] = ObjDist;
rotate_Drag_Plane(C);
translate_Drag_Plane(C);
GLint params[4];
glGetIntegerv(GL_SCISSOR_BOX, params);
glScissor(SIDEBAR, BOTTOM_LINE, drag_depth_Width, drag_depth_Height);
glClear(GL_DEPTH_BUFFER_BIT);
glViewport(SIDEBAR, BOTTOM_LINE, drag_depth_Width, drag_depth_Height);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix);
render_Depth_Drag_Plane();
glCullFace(GL_BACK);
glScissor(params[0], params[1], params[2], params[3]);
}
*/
GLfloat * Windepth = NULL;
int resize_Depth_Buffer(float width, float height)
{
int r = 0;
drag_depth_Width = width;
drag_depth_Height = height;
Windepth = realloc(Windepth, drag_depth_Width * drag_depth_Height * sizeof(GLfloat));
if (!Windepth)
return 0;
glDeleteTextures(1, &drag_texture);
glGenTextures(1, &drag_texture);
glBindTexture(GL_TEXTURE_2D, drag_texture);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT24, drag_depth_Width, drag_depth_Height);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, drag_texture);
glBindFramebuffer(GL_FRAMEBUFFER, depthFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, drag_texture, 0);
GLenum drawBuffers[] = {GL_NONE};
glDrawBuffers(1, drawBuffers);
GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if( result == GL_FRAMEBUFFER_COMPLETE)
{
printf("Depth Framebuffer is complete.\n");
r = 1;
}
else
{
printf("Depth Framebuffer is not complete.\n");
r = 0;
}
glBindFramebuffer(GL_FRAMEBUFFER,0);
return r;
}
int setup_Depth_Buffer()
{
int r = 0;
Windepth = malloc(drag_depth_Width * drag_depth_Height * sizeof(GLfloat));
if (!Windepth)
return 0;
glGenTextures(1, &drag_texture);
glBindTexture(GL_TEXTURE_2D, drag_texture);
//glTexImage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT24, drag_depth_Width, drag_depth_Height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT24, drag_depth_Width, drag_depth_Height);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, drag_texture);
glGenFramebuffers(1, &depthFBO);
glBindFramebuffer(GL_FRAMEBUFFER, depthFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, drag_texture, 0);
GLenum drawBuffers[] = {GL_NONE};
glDrawBuffers(1, drawBuffers);
GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if( result == GL_FRAMEBUFFER_COMPLETE)
{
printf("Depth Framebuffer is complete.\n");
r = 1;
}
else
{
printf("Depth Framebuffer is not complete.\n");
r = 0;
}
glBindFramebuffer(GL_FRAMEBUFFER,0);
return r;
}
int setupFBO()
{
int r = 0;
GLfloat border[] = {1.0f, 0.0f,0.0f,0.0f };
// The depth buffer texture
glGenTextures(1, &depthTex);
glBindTexture(GL_TEXTURE_2D, depthTex);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT24, shadowMapWidth, shadowMapHeight);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
// Assign the depth buffer texture to texture channel 0
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, depthTex);
// Create and set up the FBO
glGenFramebuffers(1, &shadowFBO);
glBindFramebuffer(GL_FRAMEBUFFER, shadowFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, depthTex, 0);
GLenum drawBuffers[] = {GL_NONE};
glDrawBuffers(1, drawBuffers);
GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if( result == GL_FRAMEBUFFER_COMPLETE)
{
printf("Framebuffer is complete.\n");
r = 1;
}
else
{
printf("Framebuffer is not complete.\n");
r = 0;
}
glBindFramebuffer(GL_FRAMEBUFFER,0);
return r;
}
void render_polys_OnScreen(camera * C, int wireframe, int edgedraw, int vertdraw, int currentObject, int rendermode, int Selection_Mode, int update_colors, int update_uv, int elem);
void render_quads_OnScreen(camera * C, int wireframe, int edgedraw, int vertdraw, int l, int currentObject, int mode, int Selection_Mode, int update_colors, int update_uv, int elem);
void load_m_colors_object(object * O);
void Materials_Thumbnail_render(camera * C, int width, int height, int subdLevel, int elem)
{
/*
if (SHADERS && SHADOWS)
{
if (Fan_Arrays_Shader || subdLevel > -1)
{
SceneShadowMap_render(C, width, height, subdLevel, ELEMENT_ARRAYS);
}
}
*/
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(C->v_view * (180.0 / pi), 1.0, persp_Near, persp_Far);
gluLookAt(0.0, 0.0, 1.5, 0.0, 0.0, 0.0, C->T->rotVec_[1][0], C->T->rotVec_[1][1], C->T->rotVec_[1][2]);
glGetFloatv(GL_PROJECTION_MATRIX, projectionMatrix);
glBindFramebuffer(GL_FRAMEBUFFER, materialTexFBO);
glDrawBuffer(GL_COLOR_ATTACHMENT1);
glScissor(0, 0, width, height);
glViewport(0, 0, width, height);
glClearColor(0.8, 0.5, 0.3, 0.0);
int s;
object * O = objects[C->objects[0]];
//glActiveTexture(GL_TEXTURE0);
GLuint Texture;
int r;
//for (s = 0; s < Materials_count; s ++)
for (s = Materials_count - 1; s >= 0; s --)
{
Texture = Material_Textures[s];
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
GL_TEXTURE_2D, Texture, 0);
GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if( result == GL_FRAMEBUFFER_COMPLETE)
{
//printf("Framebuffer is complete.\n");
r = 1;
}
else
{
//printf("Framebuffer is not complete.\n");
r = 0;
}
if (r)
{
O->surface = s;
load_m_colors_object(O);
if (subdLevel == -1)
render_polys_OnScreen(C, 0, 0, 0, 0, POLY_RENDER, 0, 1, 0, elem);
else
render_quads_OnScreen(C, subdLevel, 0, 0, 1, 0, POLY_RENDER, 0, 1, 0, elem);
SDL_Surface * surface = Material_Thumbnail_Surfaces[s];
glBindTexture(GL_TEXTURE_2D, Material_Textures[s]);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, surface->pixels);
// SDL_LockSurface(surface);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);
// SDL_UnlockSurface(surface);
}
}
O->surface = 0;
glPopMatrix();
// Pass 2 (render)
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
| 31.858434 | 183 | 0.648908 | [
"render",
"object",
"vector"
] |
59e9eeaaeecc6e25b7b19f3e752696b4012d1289 | 950 | c | C | src/objects/vectors/vector_float_ext.c | TravisWheelerLab/MMOREseqs | 492eda6efa4fd95ac0a787405a40db5a860bf3dc | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | src/objects/vectors/vector_float_ext.c | TravisWheelerLab/MMOREseqs | 492eda6efa4fd95ac0a787405a40db5a860bf3dc | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | src/objects/vectors/vector_float_ext.c | TravisWheelerLab/MMOREseqs | 492eda6efa4fd95ac0a787405a40db5a860bf3dc | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* - FILE: vector_float_ext.c
* - DESC: VECTOR_FLT Object (Extended) Functions.
* Float type-specific vector operations.
*******************************************************************************/
/* imports */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
/* local imports */
#include "../../objects/structs.h"
#include "../../utilities/_utilities.h"
#include "../../objects/_objects.h"
/* header */
#include "_vectors.h"
#include "vector_float.h"
/*! FUNCTION: VECTOR_FLT_Logf()
* SYNOPSIS: Perform logrithmic function on <vec>
*/
STATUS_FLAG
VECTOR_FLT_Logf(VECTOR_FLT* vec) {
int L = VECTOR_FLT_GetSize(vec);
for (int i = 0; i < L; i++) {
if (VEC_X(vec, i) > 0.0) {
VEC_X(vec, i) = logf(VEC_X(vec, i));
} else {
VEC_X(vec, i) = -INF;
}
}
return STATUS_SUCCESS;
}
| 25.675676 | 81 | 0.512632 | [
"object",
"vector"
] |
59ea84b3cb96d38d5980b75744cbe92ac039dbe8 | 32,374 | c | C | ni/vcompiler.c | tonysimpson/Ni | e1fd80852538d7d4b918aa929e48eba8bf503b5b | [
"MIT"
] | 1 | 2020-04-21T21:40:41.000Z | 2020-04-21T21:40:41.000Z | ni/vcompiler.c | tonysimpson/Ni | e1fd80852538d7d4b918aa929e48eba8bf503b5b | [
"MIT"
] | null | null | null | ni/vcompiler.c | tonysimpson/Ni | e1fd80852538d7d4b918aa929e48eba8bf503b5b | [
"MIT"
] | null | null | null | #include "vcompiler.h"
#include "Python/pycompiler.h"
#include "codemanager.h"
#include "dispatcher.h"
#include "mergepoints.h"
#include "pycodegen.h"
#include "v_mem_mov.h"
#include <idispatcher.h>
DEFINEVAR const long psyco_zero = 0;
DEFINEVAR source_virtual_t psyco_vsource_not_important;
/*****************************************************************/
BLOCKALLOC_IMPLEMENTATION(vinfo, vinfo_t, 8192)
BLOCKALLOC_IMPLEMENTATION(sk, source_known_t, 4096)
/*****************************************************************/
DEFINEFN
vinfo_array_t *array_grow1(vinfo_array_t *array, int ncount) {
int i = array->count;
extra_assert(ncount > i);
if (i == 0)
array = PyMem_MALLOC(offsetof(vinfo_array_t, items) +
ncount * sizeof(vinfo_t *));
else
array = PyMem_REALLOC(array, offsetof(vinfo_array_t, items) +
ncount * sizeof(vinfo_t *));
if (array == NULL)
OUT_OF_MEMORY();
array->count = ncount;
while (i < ncount)
array->items[i++] = NULL;
return array;
}
DEFINEFN
void vinfo_array_shrink(PsycoObject *po, vinfo_t *vi, int ncount) {
vinfo_array_t *array = vi->array;
int i = array->count;
if (i <= ncount)
return;
while (i > ncount) {
vinfo_t *v1 = array->items[--i];
if (v1 != NULL) {
array->items[i] = NULL;
vinfo_decref(v1, po);
}
}
if (ncount == 0)
array = NullArray;
else {
array = PyMem_REALLOC(array, offsetof(vinfo_array_t, items) +
ncount * sizeof(vinfo_t *));
if (array == NULL)
OUT_OF_MEMORY();
array->count = ncount;
}
vi->array = array;
}
/*****************************************************************/
DEFINEFN
void sk_release(source_known_t *sk) {
#if 0
XXX --- XXX --- XXX --- XXX --- XXX --- XXX --- XXX --- XXX --- XXX
The Python objects who get once in a source_known_t are never
freed. This is so because we might have references to them left
in the code buffers. This is tricky because the references can
be indirect (to a sub-objects, to a field in the object structure,
etc...)
So not freeing them at all is the easy way out. It is expected
that not too many objects will get lost this way. This must be
carefully worked out when implementing releasing of code
buffers. It will probably require careful checks for all
instructions that might emit an immediate value in the code,
and for where this immediate value (indirectly or not) comes from.
XXX --- XXX --- XXX --- XXX --- XXX --- XXX --- XXX --- XXX --- XXX
if ((sk->refcount1_flags & SkFlagPyObj) != 0) {
Py_XDECREF((PyObject*)(sk->value));
}
#endif
sk_delete(sk);
}
DEFINEFN
vinfo_t *vinfo_copy(vinfo_t *vi) {
vinfo_t *result = vinfo_new_skref(vi->source);
result->array = vi->array;
if (result->array->count > 0) {
result->array = array_new(result->array->count);
duplicate_array(result->array, vi->array);
}
return result;
}
DEFINEFN
void vinfo_release(vinfo_t *vi, PsycoObject *po) {
switch (gettime(vi->source)) {
case RunTime:
if (po != NULL) {
if (has_rtref(vi->source)) {
/* write Py_DECREF() when releasing the last reference to
a run-time vinfo_t holding a reference to a Python object */
psyco_decref_rt(po, vi);
}
RTVINFO_RELEASE(vi->source);
}
break;
case CompileTime:
sk_decref(CompileTime_Get(vi->source));
break;
#if HAVE_CCREG
case VirtualTime:
if (po != NULL) {
int i;
for (i = 0; i < HAVE_CCREG; i++)
if (vi == po->ccregs[i])
po->ccregs[i] = NULL;
}
break;
#endif
}
/* must be after the switch because psyco_decref_rt() did use the
array to extract any available type information to speed up Py_DECREF(). */
if (vi->array != NullArray)
array_delete(vi->array, po);
#if HAVE_CCREG && ALL_CHECKS
/* only virtual-time vinfos are allowed in po->ccreg */
if (po != NULL) {
int i;
for (i = 0; i < HAVE_CCREG; i++)
extra_assert(vi != po->ccregs[i]);
}
#endif
psyco_llfree_vinfo(vi);
}
DEFINEFN
void vinfo_move(PsycoObject *po, vinfo_t *vtarget, vinfo_t *vsource) {
Source src = vsource->source;
#if ALL_CHECKS
extra_assert(!is_virtualtime(src));
if (is_compiletime(src)) {
/* a compile-time vinfo may only hold compile-time subitems */
int j;
for (j = 0; j < vtarget->array->count; j++)
extra_assert(vtarget->array->items[j] == NULL ||
is_compiletime(vtarget->array->items[j]->source));
}
#endif
extra_assert(vsource->array == NullArray);
vtarget->source = src;
if (is_runtime(src))
RTVINFO_MOVE(src, vtarget);
extra_assert(vsource->refcount == 1);
psyco_llfree_vinfo(vsource);
clear_tmp_marks(vtarget->array);
psyco_simplify_array(vtarget->array, po);
}
DEFINEFN
bool vinfo_would_be_recursive(vinfo_t *vi, vinfo_t *newitem) {
vinfo_array_t *array;
int i;
if (newitem == vi)
return true;
array = newitem->array;
i = array->count;
while (i--)
if (array->items[i] != NULL)
if (vinfo_would_be_recursive(vi, array->items[i]))
return true;
return false;
}
DEFINEFN
void clear_tmp_marks(vinfo_array_t *array) {
/* clear all 'tmp' fields in the array, recursively */
int i = array->count;
while (i--)
if (array->items[i] != NULL) {
array->items[i]->tmp = NULL;
if (array->items[i]->array != NullArray)
clear_tmp_marks(array->items[i]->array);
}
}
#if ALL_CHECKS
DEFINEFN
void assert_cleared_tmp_marks(vinfo_array_t *array) {
/* assert that all 'tmp' fields are NULL */
int i = array->count;
while (i--)
if (array->items[i] != NULL) {
extra_assert(array->items[i]->tmp == NULL);
if (array->items[i]->array != NullArray)
assert_cleared_tmp_marks(array->items[i]->array);
}
}
static bool array_contains(vinfo_array_t *array, vinfo_t *vi) {
bool result = false;
int i = array->count;
while (i--)
if (array->items[i] != NULL) {
if (array->items[i] == vi)
result = true;
if (array->items[i]->array != NullArray) {
if (is_compiletime(array->items[i]->source))
extra_assert(!array_contains(array->items[i]->array, vi));
else if (array_contains(array->items[i]->array, vi))
result = true;
}
}
return result;
}
DEFINEFN
void assert_array_contains_nonct(vinfo_array_t *array, vinfo_t *vi) {
/* check that 'vi' appears at least once in 'array', and
never appears as subitem of a compile-time vinfo_t */
extra_assert(array_contains(array, vi));
}
static void coherent_array(vinfo_array_t *source, PsycoObject *po, int found[],
bool allow_any) {
int i = source->count;
while (i--)
if (source->items[i] != NULL) {
Source src = source->items[i]->source;
extra_assert(allow_any || is_compiletime(src));
switch (gettime(src)) {
case RunTime:
/* test that we don't have an unreasonably high value
although it might still be correct in limit cases */
extra_assert(getstack(src) < RunTime_StackMax / 2);
RTVINFO_CHECK(po, source->items[i], found);
break;
case CompileTime:
case VirtualTime:
break;
default:
psyco_fatal_msg("gettime() corrupted");
}
#if HAVE_CCREG
if (psyco_vsource_cc(src) != CC_ALWAYS_FALSE) {
int index = INDEX_CC(psyco_vsource_cc(src));
extra_assert(po->ccregs[index] == source->items[i]);
found[REG_TOTAL + index] = 1;
}
#endif
if (source->items[i]->array != NullArray)
coherent_array(source->items[i]->array, po, found,
!is_compiletime(src));
}
}
static void hack_refcounts(vinfo_array_t *source, int delta, int mvalue) {
int i = source->count;
while (i--)
if (source->items[i] != NULL) {
long rc = source->items[i]->refcount;
rc = ((rc + delta) & 0xFFFF) + (rc & 0x10000);
source->items[i]->refcount = rc;
if ((rc & 0x10000) == mvalue) {
source->items[i]->refcount ^= 0x10000;
if (source->items[i]->array != NullArray)
hack_refcounts(source->items[i]->array, delta, mvalue);
}
}
}
static vinfo_t *nonnull_refcount(vinfo_array_t *source) {
int i = source->count;
while (i--)
if (source->items[i] != NULL) {
if (source->items[i]->refcount != 0x10000) {
fprintf(stderr, "nonnull_refcount: item %d\n", i);
return source->items[i];
}
if (source->items[i]->array != NullArray) {
vinfo_t *result = nonnull_refcount(source->items[i]->array);
if (result != NULL) {
fprintf(stderr, "nonnull_refcount: in array item %d\n", i);
return result;
}
}
}
return NULL;
}
DEFINEFN
void psyco_assert_coherent1(PsycoObject *po, bool full) {
vinfo_array_t debug_extra_refs;
int found[REG_TOTAL + HAVE_CCREG];
int i;
vinfo_t *err;
for (i = 0; i < REG_TOTAL + HAVE_CCREG; i++)
found[i] = 0;
debug_extra_refs.count = 2;
debug_extra_refs.items[0] = po->pr.exc; /* normally private to pycompiler.c,*/
debug_extra_refs.items[1] = po->pr.val; /* but this is for debugging only */
coherent_array(&po->vlocals, po, found, true);
coherent_array(&debug_extra_refs, po, found, true);
if (full) {
RTVINFO_CHECKED(po, found);
#if HAVE_CCREG
for (i = 0; i < HAVE_CCREG; i++)
if (!found[REG_TOTAL + i])
extra_assert(po->ccregs[i] == NULL);
#endif
hack_refcounts(&po->vlocals, -1, 0);
hack_refcounts(&debug_extra_refs, -1, 0);
err = nonnull_refcount(&po->vlocals);
hack_refcounts(&debug_extra_refs, +1, 0x10000);
hack_refcounts(&po->vlocals, +1, 0x10000);
extra_assert(!err); /* see nonnull_refcounts() */
}
}
#endif /* ALL_CHECKS */
DEFINEFN
void duplicate_array(vinfo_array_t *target, vinfo_array_t *source) {
/* make a depth copy of an array.
Same requirements as psyco_duplicate().
Do not use for arrays of length 0. */
int i;
for (i = 0; i < source->count; i++) {
vinfo_t *sourcevi = source->items[i];
if (sourcevi == NULL)
target->items[i] = NULL;
else if (sourcevi->tmp != NULL) {
target->items[i] = sourcevi->tmp;
target->items[i]->refcount++;
} else {
vinfo_t *targetvi = vinfo_copy(sourcevi);
targetvi->tmp = NULL;
target->items[i] = sourcevi->tmp = targetvi;
}
}
target->count = source->count;
/*return true;
fail:
while (i--)
if (items[i] != NULL)
{
items[i]->tmp = NULL;
target->items[i]->decref(NULL);
}
return false;*/
}
DEFINEFN
PsycoObject *psyco_duplicate(PsycoObject *po) {
/* Requires that all 'tmp' marks in 'po' are cleared.
In the new copy all 'tmp' marks will be cleared. */
PsycoObject *result = PsycoObject_New(po->vlocals.count);
psyco_assert_coherent(po);
assert_cleared_tmp_marks(&po->vlocals);
duplicate_array(&result->vlocals, &po->vlocals);
/* set the register pointers of 'result' to the new vinfo_t's */
DUPLICATE_PROCESSOR(result, po);
/* the rest of the data is copied with no change */
result->respawn_cnt = po->respawn_cnt;
result->respawn_proxy = po->respawn_proxy;
result->code = po->code;
result->codelimit = po->codelimit;
pyc_data_duplicate(&result->pr, &po->pr);
assert_cleared_tmp_marks(&result->vlocals);
psyco_assert_coherent(result);
return result;
}
DEFINEFN void PsycoObject_Delete(PsycoObject *po) {
pyc_data_release(&po->pr);
deallocate_array(&po->vlocals, NULL);
PyMem_FREE(po);
}
DEFINEFN
bool psyco_limit_nested_weight(PsycoObject *po, vinfo_array_t *array,
int nw_index, signed char nw_end) {
signed char nw;
int i;
for (i = array->count; i--;) {
vinfo_t *vi = array->items[i];
if (vi != NULL) {
nw = nw_end;
if (is_virtualtime(vi->source)) {
source_virtual_t *sv = VirtualTime_Get(vi->source);
nw -= sv->nested_weight[nw_index];
if (nw <= 0) {
/* maximum reached, force out of virtual-time */
if (!sv->compute_fn(po, vi))
return false;
/* vi->array may be modified by compute_fn() */
continue;
}
}
if (vi->array != NullArray)
if (!psyco_limit_nested_weight(po, vi->array, nw_index, nw))
return false;
}
}
return true;
}
DEFINEFN
long direct_read_vinfo(vinfo_t *vi, char *data) {
int sindex;
if (vi == NULL) {
PyErr_SetString(PyExc_PsycoError, "undefined value");
return -1;
}
switch (gettime(vi->source)) {
case RunTime:
sindex = getstack(vi->source);
return *(long *)(data + sindex);
case CompileTime:
return CompileTime_Get(vi->source)->value;
default:
Py_FatalError("Psyco: virtual-time direct_read_vinfo");
return 0;
}
}
DEFINEFN
PyObject *direct_xobj_vinfo(vinfo_t *vi, char *data) {
int sindex;
PyObject *o = NULL;
if (vi != NULL) {
switch (gettime(vi->source)) {
case RunTime:
sindex = getstack(vi->source);
o = *(PyObject **)(data + sindex);
break;
case CompileTime:
o = (PyObject *)CompileTime_Get(vi->source)->value;
break;
case VirtualTime:
if (VirtualTime_Get(vi->source)->direct_compute_fn == NULL)
Py_FatalError("Psyco: value not directly computable");
return VirtualTime_Get(vi->source)->direct_compute_fn(vi, data);
}
Py_XINCREF(o);
}
return o;
}
/*****************************************************************/
PSY_INLINE vinfo_t *field_read(PsycoObject *po, vinfo_t *vi, long offset,
vinfo_t *vindex, defield_t df, bool newref) {
vinfo_t *result = v_mem_mov(po, NULL, vi, vindex, offset, FIELD_SIZE2(df),
((long)df & FIELD_UNSIGNED) == 0);
if ((long)df & FIELD_NONNEG) {
assert_nonneg(result);
}
if (newref && FIELD_HAS_REF(df)) {
/* the container 'vi' could be freed while the
field 'result' is still in use */
need_reference(po, result);
}
return result;
}
DEFINEFN
vinfo_t *psyco_internal_getfld(PsycoObject *po, int findex, defield_t df,
vinfo_t *vi, long offset) {
bool newref = !((long)df & FIELD_INTL_NOREF);
vinfo_t *vf;
if (is_virtualtime(vi->source)) {
vf = vinfo_getitem(vi, findex);
if (vf != NULL)
goto done;
if (!compute_vinfo(vi, po))
return NULL;
}
if ((long)df & FIELD_MUTABLE) {
extra_assert(newref);
return field_read(po, vi, offset, NULL, df, newref);
}
vf = vinfo_getitem(vi, findex);
if (vf != NULL)
goto done;
if (is_runtime(vi->source)) {
vf = field_read(po, vi, offset, NULL, df, newref);
} else {
long result;
long sk_flag = 0;
char *ptr = (char *)(CompileTime_Get(vi->source)->value);
ptr += offset;
switch (FIELD_SIZE2(df)) {
case 0:
if ((long)df & FIELD_UNSIGNED)
result = *((unsigned char *)ptr);
else
result = *((signed char *)ptr);
break;
case 1:
if ((long)df & FIELD_UNSIGNED)
result = *((unsigned short *)ptr);
else
result = *((signed short *)ptr);
break;
default:
result = *((long *)ptr);
if ((long)df & FIELD_PYOBJ_REF) {
extra_assert(result);
extra_assert(newref);
Py_INCREF((PyObject *)result);
sk_flag = SkFlagPyObj;
}
break;
}
vf = vinfo_new(CompileTime_NewSk(sk_new(result, sk_flag)));
}
if (((long)df & FIELD_ARRAY) && newref)
return vf;
CHECK_FIELD_INDEX(findex);
vinfo_setitem(po, vi, findex, vf);
done:
if (newref)
vinfo_incref(vf);
return vf;
}
DEFINEFN
vinfo_t *psyco_get_field_array(PsycoObject *po, vinfo_t *vi, defield_t df,
vinfo_t *vindex) {
long offset = FIELD_C_OFFSET(df);
if (!compute_vinfo(vindex, po))
return NULL;
extra_assert((long)df & FIELD_ARRAY);
if (is_compiletime(vindex->source)) {
return psyco_get_nth_field(po, vi, df,
CompileTime_Get(vindex->source)->value);
} else {
if (!compute_vinfo(vi, po))
return NULL;
return field_read(po, vi, offset, vindex, df, true);
}
}
DEFINEFN
bool psyco_internal_putfld(PsycoObject *po, int findex, defield_t df,
vinfo_t *vi, long offset, vinfo_t *value) {
if (is_virtualtime(vi->source)) {
vinfo_t *vf = vinfo_getitem(vi, findex);
if (vf != NULL) {
/* can only set field virtually if a value was
previously found */
vinfo_incref(value);
vinfo_setitem(po, vi, findex, value);
return true;
}
if (!compute_vinfo(vi, po))
return false;
}
extra_assert((long)df & FIELD_MUTABLE);
if (v_mem_mov(po, value, vi, NULL, offset, FIELD_SIZE2(df),
((long)df & FIELD_UNSIGNED) == 0) == NULL) {
return false;
}
if (FIELD_HAS_REF(df)) {
/* 'value' is a PyObject* that wants to hold a reference */
if (vinfo_getitem(vi, findex) == value) {
/* special case: writing a value that is already
virtually there. This is common when promoting
objects out of virtual-time. In this case, we try
to transfer the reference to the new memory
location. If this succeeds, the original 'value'
must be removed from 'vi', because it no longer
holds the reference and might become invalid if
its new no-longer-virtual container object is
deleted too early.
This causes the 'value' to be reloaded from the
memory location the next time it is used, but in a
lot of cases it avoids a Py_INCREF()/Py_DECREF()
pair, which costs more. */
if (decref_create_new_lastref(po, value)) {
vinfo_setitem(po, vi, findex, NULL);
}
} else {
/* common case */
decref_create_new_ref(po, value);
}
}
return true;
}
DEFINEFN
bool psyco_put_field_array(PsycoObject *po, vinfo_t *vi, defield_t df,
vinfo_t *vindex, vinfo_t *value) {
long offset = FIELD_C_OFFSET(df);
if (!compute_vinfo(vindex, po))
return false;
extra_assert((long)df & FIELD_ARRAY);
if (is_compiletime(vindex->source)) {
return psyco_put_nth_field(po, vi, df,
CompileTime_Get(vindex->source)->value, value);
} else {
if (!compute_vinfo(vi, po))
return false;
if (v_mem_mov(po, value, vi, vindex, offset, FIELD_SIZE2(df),
((long)df & FIELD_UNSIGNED)) == NULL) {
return false;
}
if (FIELD_HAS_REF(df)) {
/* 'value' is a PyObject* that wants to
hold a reference */
decref_create_new_ref(po, value);
}
return true;
}
}
DEFINEFN
void psyco_assert_field(PsycoObject *po, vinfo_t *vi, defield_t df,
long value) {
long sk_flag = 0;
extra_assert(!((long)df & FIELD_MUTABLE));
if (is_compiletime(vi->source)) {
#if ALL_CHECKS
/* check assertion at compile-time */
vinfo_t *vf = psyco_get_field(po, vi, df);
extra_assert(CompileTime_Get(vf->source)->value == value);
vinfo_decref(vf, po);
#endif
} else {
if (FIELD_HAS_REF(df)) {
Py_INCREF((PyObject *)value);
sk_flag = SkFlagPyObj;
}
CHECK_FIELD_INDEX(df);
vinfo_setitem(po, vi, FIELD_INDEX(df),
vinfo_new(CompileTime_NewSk(sk_new(value, sk_flag))));
}
}
/*****************************************************************/
typedef struct {
CodeBufferObject *self;
PsycoObject *po;
resume_fn_t resume_fn;
void *jump_to_fix;
} coding_pause_t;
static code_t *do_resume_coding(coding_pause_t *cp) {
/* called when entering a coding_pause (described by 'cp') */
code_t *target =
(cp->resume_fn)(cp->po, cp + 1); /* resume compilation work */
/* then fix the jump to point to 'target' */
change_cond_jump_target(cp->jump_to_fix, target);
/* cannot Py_DECREF(cp->self) because the current function is returning into
that code now, but any time later is fine: use the trash of codemanager.c
*/
psyco_trash_object((PyObject *)cp->self);
return target;
}
/* Prepare a 'coding pause', i.e. a short amount of code (proxy) that will be
called only if the execution actually reaches it to go on with compilation.
'po' is the PsycoObject corresponding to the proxy.
'jmpcondition' should not be CC_ALWAYS_FALSE.
The (possibly conditional) jump to the proxy is encoded in 'calling_code'.
When the execution reaches the proxy, 'resume_fn' is called and the proxy
destroys itself and replaces the original jump to it by a jump to the newly
compiled code. */
DEFINEFN
void psyco_coding_pause(PsycoObject *po, condition_code_t jmpcondition,
resume_fn_t resume_fn, void *extra, size_t extrasize) {
coding_pause_t *cp;
code_t *calling_code;
code_t *calling_limit;
code_t *limit;
CodeBufferObject *codebuf = psyco_new_code_buffer(NULL, NULL, &limit);
/* the proxy contains only a jump to do_resume_coding,
followed by a coding_pause_t structure, itself followed by the
'extra' data. */
calling_code = po->code;
calling_limit = po->codelimit;
po->code = insn_code_label(codebuf->codestart);
po->codelimit = limit;
cp = (coding_pause_t *)psyco_call_code_builder(
po, &do_resume_coding, true, SOURCE_DUMMY,
sizeof(coding_pause_t) + extrasize);
SHRINK_CODE_BUFFER(codebuf, po->code, "coding_pause");
/* fill in the coding_pause_t structure and the following 'extra' data */
psyco_resolved_cc(po, jmpcondition); /* jmpcondition is true if we follow
the branch */
cp->self = codebuf;
cp->po = po;
cp->resume_fn = resume_fn;
memcpy(cp + 1, extra, extrasize);
/* write the jump to the proxy */
po->code = calling_code;
po->codelimit = calling_limit;
cp->jump_to_fix =
conditional_jump_to(po, (code_t *)codebuf->codestart, jmpcondition);
}
/* for psyco_coding_pause(): a resume function that simply resumes compilation.
*/
static code_t *psyco_resume_compile(PsycoObject *po, void *extra) {
mergepoint_t *mp =
psyco_exact_merge_point(po->pr.merge_points, po->pr.next_instr);
/* check that we are not compiling recursively, or at least not too deeply */
extra_assert(psyco_locked_buffers() < WARN_TOO_MANY_BUFFERS - 1);
return (code_t *)psyco_compile_code(po, mp)->codestart;
/* XXX don't know what to do with the reference returned by
XXX psyco_compile_code() */
}
/* Main compiling function. Emit machine code corresponding to the state
'po'. The compiler produces its code into 'code' and the return value is
the end of the written code. 'po' is freed. */
DEFINEFN
code_t *psyco_compile(PsycoObject *po, mergepoint_t *mp,
bool continue_compilation) {
vcompatible_t *cmp = mp == NULL ? NULL : psyco_compatible(po, &mp->entries);
/*psyco_assert_cleared_tmp_marks(&po->vlocals); -- not needed -- */
if (cmp != NULL && cmp->diff == NullArray) /* exact match, jump there */
{
CodeBufferObject *oldcodebuf;
code_t *code2 = psyco_unify(po, cmp, &oldcodebuf);
/* XXX store reference to oldcodebuf somewhere */
return code2;
} else {
if (po->codelimit - po->code <= BUFFER_MARGIN && cmp == NULL) {
/* Running out of space in this buffer. */
/* Instead of going on we stop now and make ready to
start the new buffer later, when the execution actually
reaches this point. This forces the emission of code to
pause at predicible intervals. Among other advantages it
prevents long or infinite loops from exploding the memory
while the user sees no progression in the execution of
her program.
*/
psyco_coding_pause(po, CC_ALWAYS_TRUE, &psyco_resume_compile, NULL, 0);
return po->code;
}
/* Enough space left, continue in the same buffer. */
{
CodeBufferObject *codebuf =
psyco_proxy_code_buffer(po, mp != NULL ? &mp->entries : NULL);
/*Py_DECREF(codebuf); XXX cannot loose reference if mp == NULL*/
po->code = insn_code_label(codebuf->codestart);
}
if (cmp != NULL) /* partial match */
{
/* cmp->diff points to an array of vinfo_ts: make them run-time */
int i;
for (i = cmp->diff->count; i--;)
psyco_unfix(po, cmp->diff->items[i]);
psyco_stabilize(cmp);
/* start over (maybe we have already seen this new state) */
return psyco_compile(po, mp, continue_compilation);
}
if (continue_compilation)
return NULL; /* I won't actually compile myself, let the caller know */
/* call the entry point function which performs the actual compilation */
return GLOBAL_ENTRY_POINT(po);
}
}
DEFINEFN
void psyco_compile_cond(PsycoObject *po, mergepoint_t *mp,
condition_code_t condition) {
PsycoObject *po2 = PsycoObject_Duplicate(po);
vcompatible_t *cmp;
psyco_resolved_cc(po2, condition);
psyco_resolved_cc(po, INVERT_CC(condition));
cmp = mp == NULL ? NULL : psyco_compatible(po2, &mp->entries);
extra_assert((int)condition < CC_TOTAL);
if (cmp != NULL && cmp->diff == NullArray) /* exact match */
{
/* try to emit:
JNcond Label
<unification-and-jump>
Label:
if <unification-and-jump> is only a JMP, recode the whole as a single
Jcond <unification-jump-target>
*/
CodeBufferObject *oldcodebuf;
code_t *codeend;
void *extra = setup_conditional_code_bounds(po, po2, condition);
codeend = psyco_unify(po2, cmp, &oldcodebuf);
make_code_conditional(po, codeend, condition, extra);
/* XXX store reference to oldcodebuf somewhere */
} else {
/* Use the conditional-compiling abilities of
coding_pause(); it will write a Jcond to a proxy
which will perform the actual compilation later.
*/
if (cmp != NULL)
psyco_stabilize(cmp);
psyco_coding_pause(po2, condition, &psyco_resume_compile, NULL, 0);
po->code = po2->code;
}
}
/* Simplified interface to compile() without using a previously
existing code buffer. Return a new code buffer. */
DEFINEFN
CodeBufferObject *psyco_compile_code(PsycoObject *po, mergepoint_t *mp) {
code_t *code1;
CodeBufferObject *codebuf;
bool compile_now;
vcompatible_t *cmp = mp == NULL ? NULL : psyco_compatible(po, &mp->entries);
/*psyco_assert_cleared_tmp_marks(&po->vlocals); -- not needed -- */
if (cmp != NULL && cmp->diff == NullArray) /* exact match */
return psyco_unify_code(po, cmp);
/* We compile the new code right now if we have a full mismatch and if
there are not too many locked big buffers in codemanager.c */
compile_now =
cmp == NULL && psyco_locked_buffers() < WARN_TOO_MANY_BUFFERS - 1;
if (cmp == NULL && !compile_now)
mp = NULL; /* we are about to write a coding pause,
don't register it in mp->entries */
/* Normal case. Start a new buffer */
codebuf = psyco_new_code_buffer(po, mp == NULL ? NULL : &mp->entries,
&po->codelimit);
po->code = insn_code_label(codebuf->codestart);
if (compile_now) {
/* call the entry point function which performs the actual compilation
(this is the usual case) */
code1 = GLOBAL_ENTRY_POINT(po);
} else if (cmp != NULL) /* partial match */
{
int i;
for (i = cmp->diff->count; i--;)
psyco_unfix(po, cmp->diff->items[i]);
psyco_stabilize(cmp);
/* start over (maybe we have already seen this new state) */
code1 = psyco_compile(po, mp, false);
} else {
/* detected too many locked buffers. This occurs when compiling a
function that calls a function that needs compiling, recursively.
Delay compilation until run-time, when psyco_locked_buffers() will
be much smaller. */
psyco_coding_pause(po, CC_ALWAYS_TRUE, &psyco_resume_compile, NULL, 0);
code1 = po->code;
}
/* we have written some code into a new codebuf, now shrink it to
its actual size */
psyco_shrink_code_buffer(codebuf, code1);
return codebuf;
}
/*****************************************************************/
static bool computed_do_not_use(PsycoObject *po, vinfo_t *vi) {
fprintf(stderr, "psyco: internal error (computed_do_not_use)\n");
extra_assert(0); /* stop if debugging */
vi->source = SOURCE_DUMMY;
return true;
}
static PyObject *direct_computed_do_not_use(vinfo_t *vi, char *data) {
PyErr_SetString(PyExc_PsycoError,
"internal error (direct_computed_do_not_use)");
extra_assert(0); /* stop if debugging */
return NULL;
}
INITIALIZATIONFN
void psyco_compiler_init(void) {
INIT_SVIRTUAL(psyco_vsource_not_important, computed_do_not_use,
direct_computed_do_not_use, 0, 0, 0);
}
DEFINEFN
mergepoint_t *PsycoObject_Ready(PsycoObject *po) {
mergepoint_t *mp;
psyco_assert_coherent(po);
mp = psyco_first_merge_point(po->pr.merge_points);
psyco_delete_unused_vars(po, &mp->entries);
return mp;
}
DEFINEFN
PsycoObject *PsycoObject_FromCode(PyCodeObject *co, PyObject *globals,
PyObject *merge_points, int recursion) {
int i, argc, ncells, nfrees, extras;
PsycoObject *po;
Source rsrc;
source_known_t *sk;
vinfo_t *v;
ncells = PyTuple_GET_SIZE(co->co_cellvars);
nfrees = PyTuple_GET_SIZE(co->co_freevars);
extras = co->co_stacksize + co->co_nlocals + ncells + nfrees;
po = PsycoObject_New(INDEX_LOC_LOCALS_PLUS + extras);
po->stack_depth = INITIAL_STACK_DEPTH;
po->vlocals.count = INDEX_LOC_LOCALS_PLUS + extras;
INIT_PROCESSOR_PSYCOOBJECT(po);
po->pr.auto_recursion = AUTO_RECURSION(recursion);
/* initialize po->vlocals */
Py_INCREF(globals);
sk = sk_new((long)globals, SkFlagPyObj);
LOC_GLOBALS = vinfo_new(CompileTime_NewSk(sk));
argc = co->co_argcount;
if (co->co_flags & CO_VARARGS)
argc++;
if (co->co_flags & CO_VARKEYWORDS)
argc++;
/* initialize the free and cell vars */
i = co->co_nlocals + ncells + nfrees;
if (ncells || nfrees) {
while (i > co->co_nlocals) {
po->stack_depth += sizeof(long);
/* borrowed references from the frame object */
rsrc = RunTime_NewStack(po->stack_depth, false, false);
v = vinfo_new(rsrc);
LOC_LOCALS_PLUS[--i] = v;
}
/* skip the unbound local variables */
po->stack_depth += sizeof(long) * (i - argc);
}
/* initialize the local variables to zero (unbound) */
while (i > argc) {
v = psyco_vi_Zero();
LOC_LOCALS_PLUS[--i] = v;
}
/* initialize the keyword arguments dict */
if (co->co_flags & CO_VARKEYWORDS) {
po->stack_depth += sizeof(long);
rsrc = RunTime_NewStack(po->stack_depth, false, false);
v = vinfo_new(rsrc);
/* known to be a dict */
/*Psyco_AssertType(NULL, v, &PyDict_Type);*/
rsrc = CompileTime_New((long)&PyDict_Type);
v->array = array_new(FIELDS_TOTAL(OB_type));
v->array->items[iOB_TYPE] = vinfo_new(rsrc);
LOC_LOCALS_PLUS[--i] = v;
}
/* initialize the extra arguments tuple */
if (co->co_flags & CO_VARARGS) {
po->stack_depth += sizeof(long);
rsrc = RunTime_NewStack(po->stack_depth, false, false);
v = vinfo_new(rsrc);
/* known to be a tuple */
rsrc = CompileTime_New((long)&PyTuple_Type);
v->array = array_new(iOB_TYPE + 1);
v->array->items[iOB_TYPE] = vinfo_new(rsrc);
LOC_LOCALS_PLUS[--i] = v;
}
/* initialize the regular arguments */
while (i > 0) {
/* XXX do something more intelligent for cell and
free vars */
po->stack_depth += sizeof(long);
/* arguments get borrowed references */
rsrc = RunTime_NewStack(po->stack_depth, false, false);
v = vinfo_new(rsrc);
LOC_LOCALS_PLUS[--i] = v;
}
/* the rest of the stack in LOC_LOCALS_PLUS is
initialized to NULL by PsycoObject_New() */
/* store the code object */
po->pr.co = co;
Py_INCREF(co); /* XXX never freed */
pyc_data_build(po, merge_points);
/* set up the CALL return address */
po->stack_depth += sizeof(long);
rsrc = RunTime_NewStack(po->stack_depth, false, false);
LOC_CONTINUATION = vinfo_new(rsrc);
return po;
}
| 31.492218 | 80 | 0.630413 | [
"object"
] |
59f10e427eb9771ad78c2dc55d72952178b94d7d | 8,041 | c | C | main/c_list_jrn_objs/rtvjrnobj.c | SteversJE/OSSILE | 43858871c0c2149a9d98a9be304a40c8a46ebff1 | [
"MIT"
] | 66 | 2016-10-10T12:52:11.000Z | 2022-02-20T22:18:03.000Z | main/c_list_jrn_objs/rtvjrnobj.c | SteversJE/OSSILE | 43858871c0c2149a9d98a9be304a40c8a46ebff1 | [
"MIT"
] | 52 | 2016-10-10T09:48:44.000Z | 2021-09-25T19:22:17.000Z | main/c_list_jrn_objs/rtvjrnobj.c | SteversJE/OSSILE | 43858871c0c2149a9d98a9be304a40c8a46ebff1 | [
"MIT"
] | 54 | 2016-10-10T08:05:03.000Z | 2022-03-09T03:28:03.000Z | #include <stdio.h> // standard I/O */
#include <stdlib.h> // standard I/O */
#include <string.h> // memory and string*/
#include <qusec.h> // Error Code Structs */
#include <qmhsndm.h> // Send message */
#include <qmhsndpm.h> // Send Pgm Message */
#include <qjournal.h> // Journal functions */
#include <errno.h> // error no */
// structure typedefs
typedef _Packed struct Jrn_Req_Inf_x {
long int Length;
long int Key;
long int Data_Length;
char Obj[10];
} Jrn_Req_Inf_t;
typedef _Packed struct Jrn_Req_Str_x {
long int Num_Keys;
Jrn_Req_Inf_t Req_Info;
} Jrn_Req_Str_t;
typedef _Packed struct EC_x {
Qus_EC_t EC;
char Exception_Data[48];
} EC_t;
// definitions
#define _ERR_REC sizeof(struct EC_x);
#define _DFT_MSGQ "*REQUESTER*LIBL "
#define _DFT_MSGF "QCPFMSG *LIBL "
#define _CPYRGHT "Copyright (c) Chris Hird 2016 Made available under the terms of the license of the containing project"
#pragma comment(copyright,_CPYRGHT)
/*
* function snd_error_msg()
* Purpose: Forward an Error Message to the message queue.
* @parms
* Error Code Structure
* returns void
*/
void snd_error_msg(EC_t Error_Code) {
int data_len = 0; // data length
char Msg_Type[10] = "*INFO "; // msg type
char Msg_File[20] = "QCPFMSG *LIBL "; // Message file to use
char Msg_Key[4] = {' '}; // msg key
char QRpy_Q[20] = {' '}; // reply queue
EC_t E_Code = {0}; // error code struct
Error_Code.EC.Bytes_Provided = _ERR_REC;
if(Error_Code.EC.Bytes_Available < 16)
data_len = 16;
else
data_len = Error_Code.EC.Bytes_Available - 16; // BA + BP +msgid +rsvd
QMHSNDPM(Error_Code.EC.Exception_Id,
Msg_File,
Error_Code.Exception_Data,
data_len,
"*DIAG ",
"* ",
0,
Msg_Key,
&E_Code);
if(E_Code.EC.Bytes_Available > 0) {
snd_error_msg(E_Code);
}
QMHSNDM(Error_Code.EC.Exception_Id,
Msg_File,
Error_Code.Exception_Data,
data_len,
Msg_Type,
_DFT_MSGQ,
1,
QRpy_Q,
Msg_Key,
&E_Code);
if(E_Code.EC.Bytes_Available > 0) {
snd_error_msg(E_Code);
}
return;
}
/*
* function snd_msg()
* Purpose: Place a message in the message queue.
* @parms
* string MsgID
* string Msg_Data
* int Msg_Dta_Len
* returns void
*/
void snd_msg(char * MsgID,char * Msg_Data,int Msg_Dta_Len) {
char Msg_Type[10] = "*INFO "; // msg type
char Call_Stack[10] = {"*EXT "}; // call stack entry
char QRpy_Q[20] = {' '}; // reply queue
char Msg_Key[4] = {' '}; // msg key
EC_t Error_Code = {0}; // error code struct
Error_Code.EC.Bytes_Provided = _ERR_REC;
QMHSNDM(MsgID,
_DFT_MSGF,
Msg_Data,
Msg_Dta_Len,
Msg_Type,
_DFT_MSGQ,
1,
QRpy_Q,
Msg_Key,
&Error_Code);
if(Error_Code.EC.Bytes_Available > 0) {
snd_error_msg(Error_Code);
}
QMHSNDPM(MsgID,
_DFT_MSGF,
Msg_Data,
Msg_Dta_Len,
"*DIAG ",
"* ",
0,
Msg_Key,
&Error_Code);
if(Error_Code.EC.Bytes_Available > 0) {
snd_error_msg(Error_Code);
}
return;
}
int main(int argc, char ** argv) {
long len = -1; // length
int i = 0; // counter
int total = 0; // number of objects
char buf[8]; // temp buf
char Path[5002]; // returned path
char *buf_ptr; // buffer pointer
char *tmp; // temp ptr
Jrn_Req_Str_t Req_Inf; // request info
Qjo_RJRN0100_t *Jrn_Dets; // journal info struct
Qjo_JN_Repeating_Key_Fields_t *hdr; // keys header
Qjo_JN_Key_2_Output_Section_t *key_hdr; // key header
Qjo_JN_Repeating_Key_2_Output_t *key_data; // key data
EC_t Error_Code; // error code struct
Error_Code.EC.Bytes_Provided = _ERR_REC;
Req_Inf.Num_Keys = 1;
Req_Inf.Req_Info.Key = 2;
Req_Inf.Req_Info.Data_Length = 10;
Req_Inf.Req_Info.Length = sizeof(_Packed struct Jrn_Req_Str_x);
memcpy(Req_Inf.Req_Info.Obj,argv[2],10);
QjoRetrieveJournalInformation(buf,
&len,
argv[1],
"RJRN0100",
&Req_Inf,
&Error_Code);
if(Error_Code.EC.Bytes_Available > 0) {
snd_error_msg(Error_Code);
exit(-1);
}
// get the number of entries that will be made available
Jrn_Dets = (Qjo_RJRN0100_t *)buf;
len = Jrn_Dets->Bytes_Available;
printf("len = %d\n",len);
buf_ptr = _C_TS_malloc(len);
QjoRetrieveJournalInformation(buf_ptr,
&len,
argv[1],
"RJRN0100",
&Req_Inf,
&Error_Code);
if(Error_Code.EC.Bytes_Available > 0) {
snd_error_msg(Error_Code);
exit(-1);
}
Jrn_Dets = (Qjo_RJRN0100_t *)buf_ptr;
// print out the data
printf("Journalled object limit = %c\n",Jrn_Dets->Jrn_Object_Limit_Opt);
printf("Number of objects = %d\n",Jrn_Dets->Tot_Num_Jrn_All_Objs);
printf("Number of Files = %d\n",Jrn_Dets->Tot_Num_Jrn_Files);
printf("Number of Mbrs = %d\n",Jrn_Dets->Tot_Num_Jrn_Mbrs);
printf("Number of Dataara's = %d\n",Jrn_Dets->Tot_Num_Jrn_DtaAs);
printf("Number of DataQ's = %d\n",Jrn_Dets->Tot_Num_Jrn_DtaQs);
printf("Number of IFS = %d\n",Jrn_Dets->Tot_Num_Jrn_IFS);
printf("Number of Libs = %d\n",Jrn_Dets->Tot_Num_Jrn_Libs);
printf("Number of Access Paths = %d\n",Jrn_Dets->Tot_Num_Jrn_APs);
printf("Number of Commit Defs = %d\n",Jrn_Dets->Tot_Num_Jrn_Cmt_Defs);
printf("Jrn Recovery Count = %d\n",Jrn_Dets->Jrn_Recovery_Cnt);
printf("Bytes available = %d\n",Jrn_Dets->Bytes_Available);
// loop through the objects to get the details
tmp = buf_ptr;
key_hdr = (Qjo_JN_Key_2_Output_Section_t *)tmp;
printf("Offset to Key Info %d\n",Jrn_Dets->Off_Key_Info);
tmp += Jrn_Dets->Off_Key_Info;
// skip over number of keys field
tmp += 4;
hdr = (Qjo_JN_Repeating_Key_Fields_t *)tmp;
tmp += hdr->Off_Strt_Key_Info;
key_hdr = (Qjo_JN_Key_2_Output_Section_t *)tmp;
tmp += sizeof(_Packed struct Qjo_JN_Key_2_Output_Section);
key_data = (Qjo_JN_Repeating_Key_2_Output_t *)tmp;
total += key_hdr->Tot_Num_Jrn_Files;
total += key_hdr->Tot_Num_Jrn_DtaAs;
total += key_hdr->Tot_Num_Jrn_DtaQs;
total += key_hdr->Tot_Num_Jrn_IFS;
total += key_hdr->Tot_Num_Jrn_Libs;
for(i = 0; i < total; i++) {
// if its IFS object need to get path from file ID
if(memcmp(key_data->Object_Type,"*IFS",4) == 0) {
// convert Object File ID
if(Qp0lGetPathFromFileID(Path,sizeof(Path),key_data->Object_File_ID) == NULL) {
printf("Qp0lGetPathFromFileID error %s\n",strerror(errno));
}
else {
printf("Object %.10s Path %s \n",key_data->Object_Type,Path);
}
}
else {
printf("Object %.10s Lib %.10s Type %.10s File type %.1s\n",key_data->Object_Name,key_data->Object_Lib_Name,
key_data->Object_Type,key_data->Reserved);
}
key_data++;
}
_C_TS_free(buf_ptr);
return 1;
}
| 35.579646 | 121 | 0.553538 | [
"object"
] |
59f329959141eec1f8ca5f57e0a0b3afd6964d60 | 1,789 | h | C | include/SceneNode.h | tuanphuc/FlappyBirdLab | 2f8617aedd1a60e25721dedeca2048e0afd15b4a | [
"MIT"
] | 1 | 2019-06-26T13:05:47.000Z | 2019-06-26T13:05:47.000Z | include/SceneNode.h | tuanphuc/FlappyBirdLab | 2f8617aedd1a60e25721dedeca2048e0afd15b4a | [
"MIT"
] | null | null | null | include/SceneNode.h | tuanphuc/FlappyBirdLab | 2f8617aedd1a60e25721dedeca2048e0afd15b4a | [
"MIT"
] | null | null | null | #ifndef SCENENODE_H
#define SCENENODE_H
#include "Category.h"
#include "SFML/Graphics/Drawable.hpp"
#include "SFML/Graphics/Transformable.hpp"
#include "SFML/System/NonCopyable.hpp"
#include "SFML/System/Time.hpp"
#include <memory>
#include <set>
#include <vector>
struct Command;
class SceneNode : public sf::Transformable,
public sf::Drawable,
private sf::NonCopyable {
public:
static unsigned int nSceneNode;
typedef std::unique_ptr<SceneNode> Ptr;
typedef std::pair<SceneNode *, SceneNode *> Pair;
public:
SceneNode();
void attachChild(Ptr child);
Ptr detachChild();
int getNumerOfChild() const;
virtual unsigned int getId();
virtual void update(sf::Time dt);
sf::Vector2f getWorldPosition() const;
sf::Transform getWorldTransform() const;
std::vector<sf::Vector2f> getWorldPositionChildren();
void onCommand(const Command &command);
virtual unsigned int getCategory() const;
virtual sf::FloatRect getBoundingRect() const;
virtual bool isMarkedForRemoval() const;
virtual bool isDestroyed() const;
std::vector<unsigned int> getDyingNode(unsigned int category);
// Check node in different layers
void checkCollisionWith(SceneNode *node, std::set<Pair> &collisionPairs);
void removeWrecks();
private:
virtual void updateCurrent(sf::Time dt);
void updateChildren(sf::Time dt);
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
virtual void drawCurrent(sf::RenderTarget &target,
sf::RenderStates states) const;
void drawChildren(sf::RenderTarget &target, sf::RenderStates states) const;
private:
std::vector<Ptr> mChildren;
SceneNode *mParent;
};
bool collision(const SceneNode &lhs, const SceneNode &rhs);
#endif // SCENENODE_H
| 27.106061 | 77 | 0.725545 | [
"vector",
"transform"
] |
9404556d57925f785f6fb41ae9a71ea5f2e8132f | 2,473 | c | C | LIB/CDE/C/Rename_Timer.c | edwardcrichton/BToolkit | 1b927def38d143c1295edf0e0c98ad162d605e4a | [
"BSD-2-Clause"
] | 30 | 2015-04-28T13:12:25.000Z | 2022-03-29T17:05:04.000Z | LIB/CDE/C/Rename_Timer.c | edwardcrichton/BToolkit | 1b927def38d143c1295edf0e0c98ad162d605e4a | [
"BSD-2-Clause"
] | null | null | null | LIB/CDE/C/Rename_Timer.c | edwardcrichton/BToolkit | 1b927def38d143c1295edf0e0c98ad162d605e4a | [
"BSD-2-Clause"
] | 5 | 2016-08-28T20:58:01.000Z | 2021-09-27T18:10:57.000Z | /*Copyright (c) 1985-2012, B-Core (UK) Ltd
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "Rename_Timer.h"
#include "Bool_TYPE.h"
#include "Scalar_TYPE.h"
#define __inc_month \
{ \
_dd = 1; \
_mm++; \
if ( _mm == 13 ) { _mm = 1; _yy++; } \
}
void
Rename_IncYearMonthDay( int * _inc_ymd, int _ymd, int _days )
{
int _loop_n = _days;
int _dd = _ymd-100*(_ymd/100);
int _mm = (_ymd/100)-100*(_ymd/10000);
int _yy = _ymd/10000;
while ( _loop_n ) {
switch ( _dd ) {
case 31:
__inc_month;
break;
case 30:
switch ( _mm ) {
case 9:
case 4:
case 6:
case 11:
__inc_month;
break;
default :
_dd++;
break;
}
break;
case 29:
switch ( _mm ) {
case 2:
__inc_month;
break;
default :
_dd++;
break;
}
break;
case 28:
switch ( _mm ) {
case 2:
if ( _yy == _yy-4*(_yy/4) ) _dd++;
else __inc_month;
break;
default :
_dd++;
break;
}
break;
default:
_dd++;
break;
}
_loop_n--;
}
* _inc_ymd = (_yy*10000)+(_mm*100)+_dd;
}
| 27.175824 | 75 | 0.639304 | [
"object"
] |
9407212d9ea52e1358fad49489640d9ffe9d4b1b | 1,180 | h | C | ProjectAugustusPieterCoenen/src/MainScene.h | PieterCoenen/gba-sprite-engine | 1b9a9372733aa23423c5cf65c4c94f0d5436f4d5 | [
"MIT"
] | null | null | null | ProjectAugustusPieterCoenen/src/MainScene.h | PieterCoenen/gba-sprite-engine | 1b9a9372733aa23423c5cf65c4c94f0d5436f4d5 | [
"MIT"
] | null | null | null | ProjectAugustusPieterCoenen/src/MainScene.h | PieterCoenen/gba-sprite-engine | 1b9a9372733aa23423c5cf65c4c94f0d5436f4d5 | [
"MIT"
] | null | null | null | //
// Created by Pieter Coenen on 3/07/2021.
//
#ifndef GBA_SPRITE_ENGINE_PROJECT_MAINSCENE_H
#define GBA_SPRITE_ENGINE_PROJECT_MAINSCENE_H
#include <libgba-sprite-engine/gba_engine.h>
#include <libgba-sprite-engine/scene.h>
#include <vector>
#include "InventoryItem.h"
class MainScene : public Scene {
private:
std::unique_ptr<Sprite> avatar;
std::unique_ptr<Sprite> house;
std::unique_ptr<Sprite> plantArea;
std::unique_ptr<Background> bg;
public:
std::vector<Sprite *> sprites() override;
std::vector<Background *> backgrounds() override;
int scrollX, scrollY;
MainScene(const std::shared_ptr<GBAEngine> &engine, std::vector<InventoryItem> inventoryList) : Scene(engine) {
this->inventoryList = inventoryList;
};
std::vector<InventoryItem> inventoryList;
bool planted = false;
bool isAvailable = true;
void load() override;
void tick(u16 keys) override;
void addToInventory(InventoryItem item);
bool isInInventory(std::string name);
void plantCrop(std::string name);
InventoryItem makeInventoryItem(std::string name, int number);
};
#endif //GBA_SPRITE_ENGINE_PROJECT_MAINSCENE_H
| 23.137255 | 115 | 0.723729 | [
"vector"
] |
942663095ea39984c98392b6e23bac09464aae57 | 4,620 | h | C | Code/Legacy/CrySystem/Huffman.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-08-08T19:54:51.000Z | 2021-08-08T19:54:51.000Z | Code/Legacy/CrySystem/Huffman.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Code/Legacy/CrySystem/Huffman.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#ifndef CRYINCLUDE_CRYSYSTEM_HUFFMAN_H
#define CRYINCLUDE_CRYSYSTEM_HUFFMAN_H
#pragma once
class HuffmanCoder
{
private:
struct HuffmanTreeNode
{
uint32 count;
uint32 savedCount;
int child0;
int child1;
};
struct HuffmanSymbolCode
{
uint32 value;
uint32 numBits;
};
struct BitStreamBuilder
{
enum EModes
{
eM_WRITE,
eM_READ
};
union buf_ptr
{
uint8* ptr;
const uint8* const_ptr;
};
EModes m_mode;
uint8 m_mask;
buf_ptr m_pBufferStart;
buf_ptr m_pBufferCursor;
buf_ptr m_pBufferEnd; //Pointer to the last byte in the buffer
BitStreamBuilder(uint8* pBufferStart, uint8* pBufferEnd)
: m_mode(eM_WRITE)
, m_mask(0x80)
{
m_pBufferStart.ptr = pBufferStart;
m_pBufferCursor.ptr = pBufferStart;
m_pBufferEnd.ptr = pBufferEnd;
}
BitStreamBuilder(const uint8* pBufferStart, const uint8* pBufferEnd)
: m_mode(eM_READ)
, m_mask(0x80)
{
m_pBufferStart.const_ptr = pBufferStart;
m_pBufferCursor.const_ptr = pBufferStart;
m_pBufferEnd.const_ptr = pBufferEnd;
}
void AddBits(uint32 value, uint32 numBits);
void AddBits(uint8 value, uint32 numBits);
//Returns 1 or 0 for valid values. Returns 2 if the buffer has run out or is the wrong type of builder.
uint8 GetBit();
};
const static int MAX_SYMBOL_VALUE = (255);
const static int MAX_NUM_SYMBOLS = (MAX_SYMBOL_VALUE + 1);
const static int END_OF_STREAM = (MAX_NUM_SYMBOLS);
const static int MAX_NUM_CODES = (MAX_NUM_SYMBOLS + 1);
const static int MAX_NUM_NODES = (MAX_NUM_CODES * 2);
const static int MAX_NODE = (MAX_NUM_NODES - 1);
enum EHuffmanCoderState
{
eHCS_NEW, //Has been created, Init not called
eHCS_OPEN, //Init has been called, tree not yet constructed. Can accept new data.
eHCS_FINAL //Finalize has been called. Can no longer accept data, but can encode/decode.
};
HuffmanTreeNode* m_TreeNodes;
HuffmanSymbolCode* m_Codes;
uint32* m_Counts;
int m_RootNode;
uint32 m_RefCount;
EHuffmanCoderState m_State;
public:
HuffmanCoder()
: m_TreeNodes(NULL)
, m_Codes(NULL)
, m_Counts(NULL)
, m_State(eHCS_NEW)
, m_RootNode(0)
, m_RefCount(0) {}
~HuffmanCoder()
{
SAFE_DELETE_ARRAY(m_TreeNodes);
SAFE_DELETE_ARRAY(m_Codes);
SAFE_DELETE_ARRAY(m_Counts);
}
//A bit like an MD5 generator, has three phases.
//Clears the existing data
void Init();
//Adds the values of an array of chars to the counts
void Update(const uint8* const pSource, const size_t numBytes);
//Construct the coding tree using the counts
void Finalize();
//We typically create a Huffman Coder per localized string table loaded. Since we can and do unload strings at runtime, it's useful to keep a ref count of each coder.
inline void AddRef() { m_RefCount++; }
inline void DecRef() { m_RefCount = m_RefCount > 0 ? m_RefCount - 1 : 0; }
inline uint32 RefCount() { return m_RefCount; }
void CompressInput(const uint8* const pInput, const size_t numBytes, uint8* const pOutput, size_t* const outputSize);
size_t UncompressInput(const uint8* const pInput, const size_t numBytes, uint8* const pOutput, const size_t maxOutputSize);
void GetMemoryUsage(ICrySizer* pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
if (m_Counts != NULL)
{
pSizer->AddObject(m_Counts, sizeof(uint32), MAX_NUM_SYMBOLS);
}
if (m_TreeNodes != NULL)
{
pSizer->AddObject(m_TreeNodes, sizeof(HuffmanTreeNode), MAX_NUM_NODES);
}
if (m_Codes != NULL)
{
pSizer->AddObject(m_Codes, sizeof(HuffmanSymbolCode), MAX_NUM_CODES);
}
}
private:
void ScaleCountsAndUpdateNodes();
int BuildTree();
void ConvertTreeToCode(const HuffmanTreeNode* const pNodes, HuffmanSymbolCode* const pCodes, const unsigned int value, const unsigned int numBits, const int node);
};
#endif // CRYINCLUDE_CRYSYSTEM_HUFFMAN_H
| 30.8 | 170 | 0.638745 | [
"3d"
] |
942c040103b363cc31f037b877b9118e5feeffb8 | 66,221 | h | C | ds/ds/src/ntdsa/dblayer/dbintrnl.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/ds/src/ntdsa/dblayer/dbintrnl.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/ds/src/ntdsa/dblayer/dbintrnl.h | 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, 1996 - 1999
//
// File: dbintrnl.h
//
//--------------------------------------------------------------------------
/*
==========================================================================
**
** DB layer definitions required only within the DB layer, not to be
** exported to outside of the DB Layer.
**
==========================================================================
*/
#ifndef _dbintrnl_h_
#define _dbintrnl_h_
/* external variables */
extern DBPOS *pDBhidden;
extern char szUser[];
extern char szPassword[];
extern char szJetFilePath[];
extern char szJetDirectoryPath[];
extern int lastattr;
extern JET_COLUMNID insttypeid;
extern JET_COLUMNID objclassid;
extern JET_COLUMNID ntdefsecdescid;
extern JET_COLUMNID ntsecdescid;
extern JET_COLUMNID dntid;
extern JET_COLUMNID pdntid;
extern JET_COLUMNID ancestorsid;
extern JET_COLUMNID ncdntid;
extern JET_COLUMNID objid;
extern JET_COLUMNID rdnid;
extern JET_COLUMNID rdntypid;
extern JET_COLUMNID dscorepropinfoid;
extern JET_COLUMNID abcntid;
extern JET_COLUMNID cntid;
extern JET_COLUMNID deltimeid;
extern JET_COLUMNID usnid;
extern JET_COLUMNID usnchangedid;
extern JET_COLUMNID dsaid;
extern JET_COLUMNID isdeletedid;
extern JET_COLUMNID IsVisibleInABid;
extern JET_COLUMNID iscriticalid;
extern JET_COLUMNID cleanid;
// Link table
extern JET_COLUMNID linkdntid;
extern JET_COLUMNID backlinkdntid;
extern JET_COLUMNID linkbaseid;
extern JET_COLUMNID linkdataid;
extern JET_COLUMNID linkndescid;
// Link value replication
extern JET_COLUMNID linkdeltimeid;
extern JET_COLUMNID linkusnchangedid;
extern JET_COLUMNID linkncdntid;
extern JET_COLUMNID linkmetadataid;
// SD propagator
extern JET_COLUMNID orderid;
extern JET_COLUMNID begindntid;
extern JET_COLUMNID trimmableid;
extern JET_COLUMNID clientidid;
extern JET_COLUMNID sdpropflagsid;
extern JET_COLUMNID sdpropcheckpointid;
extern JET_INSTANCE jetInstance;
extern JET_COLUMNID guidid;
extern JET_COLUMNID distnameid;
extern JET_COLUMNID sidid;
extern JET_COLUMNID ShowInid;
extern JET_COLUMNID mapidnid;
// SD table
extern JET_COLUMNID sdidid;
extern JET_COLUMNID sdhashid;
extern JET_COLUMNID sdvalueid;
extern JET_COLUMNID sdrefcountid;
// Hidden table columns
extern JET_COLUMNID dsstateid;
extern JET_COLUMNID dsflagsid;
extern JET_COLUMNID jcidBackupUSN;
extern JET_COLUMNID jcidBackupExpiration;
// Quota table
//
extern JET_COLUMNID g_columnidQuotaNcdnt;
extern JET_COLUMNID g_columnidQuotaSid;
extern JET_COLUMNID g_columnidQuotaTombstoned;
extern JET_COLUMNID g_columnidQuotaTotal;
// Quota Rebuild Progress table
//
extern JET_COLUMNID g_columnidQuotaRebuildDNTLast;
extern JET_COLUMNID g_columnidQuotaRebuildDNTMax;
extern JET_COLUMNID g_columnidQuotaRebuildDone;
// Quota Audit table
//
extern JET_COLUMNID g_columnidQuotaAuditNcdnt;
extern JET_COLUMNID g_columnidQuotaAuditSid;
extern JET_COLUMNID g_columnidQuotaAuditDnt;
extern JET_COLUMNID g_columnidQuotaAuditOperation;
// indexes
extern JET_INDEXID idxPdnt;
extern JET_INDEXID idxRdn;
extern JET_INDEXID idxNcAccTypeName;
extern JET_INDEXID idxNcAccTypeSid;
extern JET_INDEXID idxAncestors;
extern JET_INDEXID idxDnt;
extern JET_INDEXID idxDel;
extern JET_INDEXID idxGuid;
extern JET_INDEXID idxSid;
extern JET_INDEXID idxProxy;
extern JET_INDEXID idxMapiDN;
extern JET_INDEXID idxDraUsn;
extern JET_INDEXID idxDraUsnCritical;
extern JET_INDEXID idxDsaUsn;
extern JET_INDEXID idxPhantom;
extern JET_INDEXID idxIsDel;
extern JET_INDEXID idxClean;
extern JET_INDEXID idxInvocationId;
// Link value replication
extern JET_INDEXID idxLink;
extern JET_INDEXID idxBackLink;
extern JET_INDEXID idxBackLinkAll;
extern JET_INDEXID idxLinkDel;
extern JET_INDEXID idxLinkDraUsn;
extern JET_INDEXID idxLinkLegacy;
extern JET_INDEXID idxLinkAttrUsn;
// Link value replication
// SD table
extern JET_INDEXID idxSDId;
extern JET_INDEXID idxSDHash;
// Lingering Object Removal
extern JET_INDEXID idxNcGuid;
// bit to use for JetPrepareUpdate(replace)
#define DS_JET_PREPARE_FOR_REPLACE JET_prepReplaceNoLock
/* string constants for JET */
// Link table
#define SZLINKTABLE "link_table" /* table for links and backlinks */
#define SZLINKDNT "link_DNT" /* DNT of link */
#define SZBACKLINKDNT "backlink_DNT" /* DNT of backlink */
#define SZLINKBASE "link_base" /* unique ID of link/backlink pair */
#define SZLINKDATA "link_data" /* more data for link/backlink */
#define SZLINKNDESC "link_ndesc" /* # of descriptors in more data */
// Link Value Replication
#define SZLINKDELTIME "link_deltime" // Deletion time
#define SZLINKUSNCHANGED "link_usnchanged" // Link USN changed
#define SZLINKNCDNT "link_ncdnt" // Link NC DNT
#define SZLINKMETADATA "link_metadata" // Link metadata
// Link Value Replication
// Lingering Object Removall
#define SZNCGUIDINDEX "nc_guid_Index" /* nc + guid index */
// SD table
#define SZSDTABLE "sd_table" /* table for SDs */
#define SZSDID "sd_id" /* SD hash value */
#define SZSDHASH "sd_hash" /* SD hash value */
#define SZSDREFCOUNT "sd_refcount" /* SD refcount */
#define SZSDVALUE "sd_value" /* actual SD data */
// Quota table
//
#define g_szQuotaTable "quota_table" // table for object owner quotas
#define g_szQuotaColumnNcdnt "quota_NCDNT" // NCDNT of owning object
#define g_szQuotaColumnSid "quota_SID" // SID of owning object
#define g_szQuotaColumnTombstoned "quota_tombstoned" // count of tombstoned objects owned
#define g_szQuotaColumnTotal "quota_total" // count of total objects owned
// Quota Rebuild Progress table
//
#define g_szQuotaRebuildProgressTable "quota_rebuild_progress_table" // temporary table to track progress of quota rebuild
#define g_szQuotaRebuildColumnDNTLast "quota_rebuild_DNT_Last" // last DNT successfully processed
#define g_szQuotaRebuildColumnDNTMax "quota_rebuild_DNT_Max" // max DNT to process
#define g_szQuotaRebuildColumnDone "quota_rebuild_fDone" // set to TRUE when Quota table completely rebuilt
// Quota Audit table
//
#define g_szQuotaAuditTable "quota_audit_table" // table for auditing of quota operations
#define g_szQuotaAuditColumnNcdnt "quota_audit_NCDNT" // NCDNT of target object of the operation
#define g_szQuotaAuditColumnSid "quota_audit_SID" // SID of target object of the operation
#define g_szQuotaAuditColumnDnt "quota_audit_DNT" // DNT of target object of the operation
#define g_szQuotaAuditColumnOperation "quota_audit_operation" // quota operation performed for target object
#define SZDATATABLE "datatable" /* name of JET data table */
#define SZPROPTABLE "sdproptable" /* Security Descriptor propagations */
#define SZANCESTORS "Ancestors_col" /* name of ancestors blob column */
#define SZDNT "DNT_col" /* name of DNT column */
#define SZPDNT "PDNT_col" /* name of PDNT column */
#define SZDISPTYPE "DispTYpeT_col" /* name of DispType column */
#define SZOBJ "OBJ_col" /* name of OBJ column */
#define SZRDNTYP "RDNtyp_col" /* name of RDN type column */
#define SZCACHE "cache_col" /* name of cache header column */
#define SZCNT "cnt_col" /* name of cache header column */
#define SZABCNT "ab_cnt_col" /* name of cache header column */
#define SZDELTIME "time_col" /* name of delete time column */
#define SZNCDNT "NCDNT_col" /* name of NCDNT column */
#define SZCLEAN "clean_col" /*name of clean column */
#define SZMAPIDN "ATTe590479" /* name of legacy mapi dn att */
#define SZ_NC_ACCTYPE_NAME_INDEX "NC_Acc_Type_Name"
#define SZ_NC_ACCTYPE_SID_INDEX "NC_Acc_Type_Sid"
#define SZANCESTORSINDEX "Ancestors_index"
#define SZDNTINDEX "DNT_index" /* name of DNT index */
#define SZPDNTINDEX "PDNT_index" /* name of PDNT index */
#define SZRDNINDEX "INDEX_00090001" /* name of RDN index */
#define SZDELINDEX "del_index" /* OBSOLETE name of time index */
#define SZDELTIMEINDEX "deltime_index" /* name of time index */
#define SZOBJCLASS "ATTc0" /* name of Object Class col */
#define SZCOMMONNAME "ATTm3" /* name of ATT_COMMON_NAME col */
#define SZDISPNAME "ATTm131085" /* name of Display Name col */
#define SZDRAUSNNAME "ATTq131192" /* name of DRAUSN att */
#define SZDRATIMENAME "ATTl131075" /* name of when changed att */
#define SZMETADATA "ATTk589827" /* name of meta data att */
#define SZOBJECTVERSION "ATTj131148" /* name of object version att */
#define SZDSASIGNAME "ATTk131146" /* name of DSA signature att */
#define SZSRCUSNNAME "ATTq131446" /* name of source usn att */
#define SZINVOCIDNAME "ATTk131187" /* name of invocation id att */
#define SZINVOCIDINDEX "INDEX_00020073" /* name of invocation id index */
#define SZPROXY "ATTe131282" /* name of Proxy-Address att */
#define SZPROXYINDEX "INDEX_000200D2" /* name of Proxy-Address index */
#define SZINSTTYPE "ATTj131073" /* name of Instance-Type att */
#define SZNTSECDESC "ATTp131353" /* name NT-Security-Descriptor att */
#define SZDEFNTSECDESC "ATTk590048" /* name NT-Security-Descriptor att */
#define SZSHOWINCONT "ATTb590468" /* name of the SHOW-IN att */
#define SZISDELETED "ATTi131120" /* name of Is-Deleted att */
#define SZLINKID "ATTj131122" /* name of ATT_LINK_ID column */
#define SZDMDLOCATION "ATTb131108" /* name of DMD-Location att */
#define SZHIDDENTABLE "hiddentable" /* name of JET hidden table */
#define SZDSA "dsa_col" /* name of DSA name column */
#define SZUSN "usn_col" /* name of USN column */
#define SZBACKUPUSN "backupusn_col" /* name of backup USN column */
#define SZBACKUPEXPIRATION "backupexpiration_col" /* name of backup expires column (used for tombstone) */
#define SZDSSTATE "state_col" /* Contains the state of the DS = UnInstalled Installed Running Backedup*/
#define SZDSFLAGS "flags_col" /* Contains additional Flags used for keeping track of state */
#define SZDRAUSNINDEX "DRA_USN_index" /* index for DRA USN */
#define SZDSAUSNINDEX "INDEX_0002004A" /* index for DSA USN */
#define SZISVISIBLEINAB "IsVisibleInAB" /* For restricting via index */
// Link indexes
// New programmatic names with ALL are given to the old non-conditional
// indexes. They have must retain their old Jet names. link_index is the
// primary index and cannot be changed.
// The default indexes, with program names SZLINKINDEX and SZBACKLINKINDEX,
// are redefined to point to the new conditional indexes.
#define SZLINKALLINDEX "link_index" /* name of link index */
#define SZLINKINDEX "link_present_index" /* name of link present index */
#define SZBACKLINKALLINDEX "backlink_index" /* name of backlink index */
#define SZBACKLINKINDEX "backlink_present_index" /* name of backlink index */
// Link Value Replication
#define SZLINKDELINDEX "link_del_index" /* name of link del time index */
#define SZLINKDRAUSNINDEX "link_DRA_USN_index" /* index for DRA USN */
#define SZLINKLEGACYINDEX "link_legacy_index" /* name of link legacy index */
#define SZLINKATTRUSNINDEX "link_attr_USN_index" /* index for attr USN */
// SD table indexes
#define SZSDIDINDEX "sd_id_index" /* index on SD id values */
#define SZSDHASHINDEX "sd_hash_index" /* index on SD hash values */
// Quota table indexes
//
#define g_szQuotaIndexNcdntSid "quota_NCDNT_SID_index" // index on NCDNT+SID (primary index)
#define SZGUID "ATTk589826" /* name of GUID att */
#define SZGUIDINDEX "INDEX_00090002" /* name of GUID index */
#define SZRDNATT "ATTm589825" /* name of RDN att */
#define SZSID "ATTr589970" /* name of SID att */
#define SZSIDINDEX "INDEX_00090092" /* name of SID index */
#define SZACCTYPE "ATTj590126" /* name of account type att */
#define SZACCNAME "ATTm590045" /* name of account name att */
#define SZDISTNAME "ATTb49"
#define SZORDER "order_col" /* Order column in SD prop table */
#define SZBEGINDNT "begindnt_col" /* Begin DNT column in SD prop table */
#define SZTRIMMABLE "trimmable_col" /* Trimmable column in SD prop table */
#define SZCLIENTID "clientid_col" /* Client id column in SD prop table */
#define SZSDPROPFLAGS "flags_col" /* flags column in SD prop table */
#define SZSDPROPCHECKPOINT "checkpoint_col" /* checkpoint column in SD prop table */
#define SZORDERINDEX "order_index" /* Order index in SD prop table */
#define SZTRIMINDEX "trim_index" /* Trimmable index, SD prop table */
#define SZCLIENTIDINDEX "clientid_index" /* Client ID index, SD prop table */
#define SZPROXIEDINDEX "INDEX_000904E1" /* ATT_PROXIED_OBJECT_NAME index */
#define SZSAMACCTINDEX "INDEX_000900DD" /* ATT_SAM_ACCOUNT_NAME index */
#define SZDISPLAYINDEX "INDEX_0002000D" /* ATT_DISPLAY_NAME index */
#define SZALTSECIDINDEX "INDEX_00090363" /* ATT_ALT_SECURITY_IDENTITIES index */
#define SZUPNINDEX "INDEX_00090290" /* ATT_USER_PRINCIPAL_NAME index */
#define SZSPNINDEX "INDEX_00090303" /* ATT_SERVICE_PRINCIPAL_NAME index */
#define SZMAPIDNINDEX "INDEX_0009028F" // ATT_LEGACY_EXCHANGE_DN
#define SZSIDHISTINDEX "INDEX_00090261" /* ATT_SID_HISTORY index */
#define SZPRIMARYGROUPIDINDEX "INDEX_00090062" /* ATT_PRIMARY_GROUP_ID index */
#define SZDSCOREPROPINFO "ATTl591181" /* ATT_DS_CORE_PROPAGATION_INFO */
#define SZPHANTOMINDEX "PhantomIndex" // Index to find ref phantoms
#define SZDNTDELINDEX "DNT_IsDeleted_Index" // OBSOLETE name of the DNT+IsDeleted index
#define SZISDELINDEX "INDEX_00020030" // name of the IsDeleted index
#define SZDNTCLEANINDEX "DNT_clean_Index" // OBSOLETE name of the DNT+clean index
#define SZCLEANINDEX "clean_index" // name of the clean index
#define SZTUPLEINDEXPREFIX "INDEX_T_"
#define SZLCLINDEXPREFIX "LCL_"
/* These indices are localized in dbinit.c. They MUST begin with
* the prefix defined in SZLCLINDEXPREFIX, so that we can reclaim
* unnecessary localized indices.
*/
/* name of ABView index */
#define SZABVIEWINDEX "LCL_ABVIEW_index"
// SZDRAUSNINDEX above
#define SZDRAUSNCRITICALINDEX "DRA_USN_CRITICAL_index"
// SZNCDNT above
#define SZUSNCHANGED "ATTq131192"
#define SZUSNCREATED "ATTq131091"
#define SZISCRITICAL "ATTi590692"
/* configuration parameters */
#define DISPNAMEINDXDENSITY 80 /* density of Display Name index */
#define GENERIC_INDEX_DENSITY 90
#define DB_INITIAL_BUF_SIZE 4096
// Attribute search state
#define ATTRSEARCHSTATEUNDEFINED 0
#define ATTRSEARCHSTATELINKS 1
#define ATTRSEARCHSTATEBACKLINKS 2
// values for ulIndexType
#define IndexTypeNone 0 /* index can not be defined on this field */
#define IndexTypeSingleColumn 1 /* index to be defined on this column alone */
/* structure to map DSA syntax types to JET column types and sizes.
A colsize of zero indicates a fixed length column (size is inherent).
*/
typedef struct
{
UCHAR syntax;
JET_COLTYP coltype;
USHORT colsize;
USHORT cp;
ULONG ulIndexType;
} SYNTAX_JET;
extern SYNTAX_JET syntax_jet[];
#define ENDSYNTAX 0xff /* end of table indicactor */
extern NT4SID *pgdbBuiltinDomain;
// Maximum number of Jet sessions
extern ULONG gcMaxJetSessions;
// Array of uncommitted usns
extern USN * UncUsn;
// Critical section to guard uncommitted usn array
extern CRITICAL_SECTION csUncUsn;
// The following is used by DNRead to do a JetRetrieveColumns call. However,
// dbinit.c needs to touch this object to stuff in column IDs.
extern JET_RETRIEVECOLUMN dnreadColumnInfoTemplate[];
// The following are used by dbAddSDPropTime, but dbinit.c needs to touch them
// to stuff in column IDs.
extern JET_RETRIEVECOLUMN dbAddSDPropTimeReadTemplate[];
extern JET_SETCOLUMN dbAddSDPropTimeWriteTemplate[];
// This is a macro to encapsulate when we should track value metadata
// fLinkedValueReplication is a thread-wide (machine-wide) state that controls
// whether we are recording link metadata. fScopeLegacyLinks is only
// significant when fLVR is true. It is needed when we have promoted to fLVR
// mode, but are applying a legacy value change that was originated in the old
// mode. fScopeLegacyLinks is only DBPOS-wide because on a replicated
// write, it is necessary for the incoming values to be applied with legacy
// semantics, but "cascaded originating writes" (ie those triggered locally
// during the application of the replicated write) in separate DBPOS must be
// applied with LVR semantics. Whew!
#define TRACKING_VALUE_METADATA( pDB ) \
( (pDB->pTHS->fLinkedValueReplication) && (!(pDB->fScopeLegacyLinks)) )
#define LEGACY_UPDATE_IN_LVR_MODE( pDB ) \
( (pDB->pTHS->fLinkedValueReplication) && (pDB->fScopeLegacyLinks) )
// Typedef for struct for an array of functions to translate to and from
// internal format and to do comparisons
typedef struct {
// Internal-to-External format translation function
// Internal is the DB format (i.e. DNs are represented as DNTs)
// External is the code/user format (i.e. DNs are represented as DSNAME structs)
//
// extTableOp can be either DBSYN_INQ (inquire) or DBSYN_REM (remove value):
// DBSYN_INQ does the actual translation.
//
// DBSYN_REM is called so that extra work can be done for attributes that
// reference other data (such as DNs and SDs) and you need to
// decrement the refcount.
//
// NOTE: DBSYN_REM is not used anywhere (except for one place in dbsetup.c)
// A similar functionality is usually achieved by invoking
// dbAdjustRefCountByAttVal. So, if you implement a refcounted value
// (such as SD or DN), you have to provide the functionality in both
// places. One exception with dbAdjustRefCountByAttVal is that it is
// not expected to create new rows. This is always achieved by
// a ExtIntXXXX(DBSYN_ADD) call.
//
// ulUpdateDnt is a hack for backlinks. The replicator needs to be able to
// remove backlinks from objects directly, but the ref count for link pairs
// goes from teh link to the backlink, not the other way around. This means
// that the ref count needs to be adjusted on an object other than the object
// being referenced (specifically, the object which the value is being removed
// from). It only has meaning on DSNAME syntaxes, and then is only used for
// backlinks.
//
// jTbl parameter seems to be unused...
//
// flags might have some meaning only for certain syntaxes.
int (*IntExt) (DBPOS FAR *pDB,
USHORT extTableOp,
ULONG intLen,
UCHAR *pIntVal,
ULONG *pExtLen,
UCHAR **pExtVal,
ULONG ulUpdateDnt,
JET_TABLEID jTbl,
ULONG flags);
// External-to-Internal format translation function
//
// extTableOp can be either DBSYN_INQ (inquire) or DBSYN_ADD (add value):
// DBSYN_INQ does the actual translation. If the value is refcounted, then
// it is also expected to check if the internal value exists in
// the table. If not, the function should return DIRERR_OBJ_NOT_FOUND
// (this is used in DBReplaceAtt_AC).
//
// DBSYN_ADD is called so that extra work can be done for attributes that
// reference other data (such as DNs and SDs) and you need to
// increment the refcount or create a new row.
int (*ExtInt) (DBPOS FAR *pDB,
USHORT extTableOp,
ULONG extLen,
UCHAR *pExtVal,
ULONG *pIntLen,
UCHAR **pIntVal,
ULONG ulUpdateDnt,
JET_TABLEID jTbl,
ULONG flags);
// value comparison function
// the comparison is always done on values in internal format
// Oper can be one of FI_CHOICE_* (see filtypes.h)
// NOTE: we always compare the second value against the first.
// so if you are doing a comparison for FI_CHOICE_LESS
// and you are looking for A < B
// you should pass A as the second argument and B as the first
int (*Eval) (DBPOS FAR *pDB,
UCHAR Oper,
ULONG IntLen1,
UCHAR *pIntVal1,
ULONG IntLen2,
UCHAR *pIntVal2);
} DBSyntaxStruct;
// TableOps for gDBSyntax[] conversions.
#define DBSYN_INQ 0
#define DBSYN_ADD 1
#define DBSYN_REM 2
// flags for ExtInt calls
#define EXTINT_NEW_OBJ_NAME 0x1
#define EXTINT_SECRETDATA 0x2
#define EXTINT_UPDATE_PHANTOM 0x4
#define EXTINT_REJECT_TOMBSTONES 0x8
// flags for IntExt calls
// The first 4 bits are reserved for security descriptor flags.
#define INTEXT_BACKLINK 0x10
#define INTEXT_SHORTNAME 0x20
#define INTEXT_MAPINAME 0x40
#define INTEXT_SECRETDATA 0x80
#define INTEXT_WELLKNOWNOBJ 0x100
#define INTEXT_VALID_FLAGS 0x1FF
extern const DBSyntaxStruct gDBSyntax[];
VOID
dbTrackModifiedDNTsForTransaction (
PDBPOS pDB,
DWORD NCDNT,
ULONG cAncestors,
DWORD *pdwAncestors,
BOOL fNotifyWaiters,
DWORD fChangeType
);
extern TRIBOOL
dbEvalInt (
DBPOS FAR *pDB,
BOOL fUseObjTbl,
UCHAR Operation,
ATTRTYP type,
ULONG valLenFilter,
UCHAR *pValFilter,
BOOL *pbSkip
);
extern DWORD
dbInitRec(
DBPOS FAR *pDB
);
extern VOID
dbInitIndicesToKeep(void);
extern DWORD
dbInitpDB (
DBPOS FAR *pDB
);
ULONG dbGetHiddenFlags(CHAR *pFlags, DWORD flagslen);
ULONG dbSetHiddenFlags(CHAR *pFlags, DWORD flagslen);
DWORD
dbUnMarshallRestart (
DBPOS FAR *pDB,
PRESTART pArgRestart,
BYTE *pDBKeyBMCurrent,
DWORD SearchFlags,
DWORD *cbDBKeyCurrent,
DWORD *cbDBBMCurrent,
DWORD *StartDNT
);
extern void
dbCheckJet (
JET_SESID sesid
);
DWORD
dbGetNthNextLinkVal(
DBPOS * pDB,
ULONG sequence,
ATTCACHE **ppAC,
DWORD Flags,
ULONG InBuffSize,
PUCHAR *ppVal,
ULONG *pul
);
extern DB_ERR
dbCloseTempTables (DBPOS *pDB);
extern void
dbFreeKeyIndex(
THSTATE *pTHS,
KEY_INDEX *pIndex
);
extern DB_ERR
dbGetSingleValueInternal (
DBPOS *pDB,
JET_COLUMNID colId,
void * pvData,
DWORD cbData,
DWORD *pSizeRead,
DWORD grbit
);
extern DWORD
dbGetMultipleColumns (
DBPOS *pDB,
JET_RETRIEVECOLUMN **ppOutputCols,
ULONG *pcOutputCols,
JET_RETRIEVECOLUMN *pInputCols,
ULONG cInputCols,
BOOL fGetValues,
BOOL fOriginal
);
extern BOOL
dbGetFilePath (
UCHAR *pFilePath,
DWORD dwSize
);
extern BOOL
dbEvalFilterSecurity (
DBPOS FAR *pDB,
CLASSCACHE *pCC,
PSECURITY_DESCRIPTOR pSD,
PDSNAME pDN
);
extern void
dbFlushUncUsns (
void
);
extern void
dbUnlockDNs (
DBPOS *pDB
);
void
dbReleaseGlobalDNReadCache (
THSTATE *pTHS
);
void
dbFlushDNReadCache (
IN DBPOS *pDB,
IN DWORD DNT
);
void
dbResetGlobalDNReadCache (
THSTATE *pTHS
);
VOID
dbResetLocalDNReadCache (
THSTATE *pTHS,
BOOL fForceClear
);
VOID
dbAdjustRefCountByAttVal(
DBPOS *pDB,
ATTCACHE *pAC,
PUCHAR pVal,
ULONG valLen,
int adjust);
DWORD
dbGetNextAtt (
DBPOS *pDB,
ATTCACHE **ppAC,
ULONG *pSearchState
);
BOOL
dbFindIntLinkVal(
DBPOS FAR *pDB,
ATTCACHE *pAC,
ULONG intLen,
void *pIntVal,
OUT BOOL *pfPresent
);
void
dbGetLinkTableData (
PDBPOS pDB,
BOOL bIsBackLink,
BOOL bWarnings,
DWORD *pulObjectDnt,
DWORD *pulValueDnt,
DWORD *pulRecLinkBase
);
DWORD APIENTRY
dbGetLinkVal(
DBPOS * pDB,
ULONG sequence,
ATTCACHE **ppAC,
DWORD Flags,
ULONG InBuffSize,
PUCHAR *ppVal,
ULONG *pul);
DWORD
dbAddIntLinkVal (
DBPOS FAR *pDB,
ATTCACHE *pAC,
ULONG intLen,
void *pIntVal,
IN VALUE_META_DATA *pMetaDataRemote OPTIONAL
);
void
dbSetLinkValuePresent(
IN DBPOS *pDB,
IN DWORD dwEventCode,
IN ATTCACHE *pAC,
IN BOOL fResetDelTime,
IN VALUE_META_DATA *pMetaDataRemote OPTIONAL
);
void
dbSetLinkValueAbsent(
IN DBPOS *pDB,
IN DWORD dwEventCode,
IN ATTCACHE *pAC,
IN PUCHAR pVal,
IN VALUE_META_DATA *pMetaDataRemote OPTIONAL
);
DWORD
dbRemIntLinkVal (
DBPOS FAR *pDB,
ATTCACHE *pAC,
ULONG intLen,
void *pIntVal,
IN VALUE_META_DATA *pMetaDataRemote OPTIONAL
);
VOID
dbDecodeInternalDistnameSyntax(
IN ATTCACHE *pAC,
IN VOID *pIntVal,
IN DWORD intLen,
OUT DWORD *pulBacklinkDnt,
OUT DWORD *pulLinkBase,
OUT PVOID *ppvData,
OUT DWORD *pcbData
);
UCHAR *
dbGetExtDnForLinkVal(
IN DBPOS * pDB
);
#define dbAlloc(size) THAllocOrgEx(pTHS, size)
#define dbReAlloc(ptr, size) THReAllocOrgEx(pTHS, ptr, size)
#define dbFree(ptr) THFreeOrg(pTHS, ptr)
// Subject Table routines.
extern BOOL
dbFIsAnAncestor (
DBPOS FAR *pDB,
ULONG ulAncestor
);
#define SBTGETTAG_fMakeCurrent (1)
#define SBTGETTAG_fUseObjTbl (2)
#define SBTGETTAG_fSearchByGuidOnly (4)
#define SBTGETTAG_fAnyRDNType (8)
extern DWORD
sbTableGetTagFromDSName(
DBPOS FAR *pDB,
DSNAME *pName,
ULONG ulFlags,
ULONG *pTag,
struct _d_memname **ppname
);
extern DWORD
sbTableGetDSName(
DBPOS FAR *pDB,
ULONG tag,
DSNAME **ppName,
DWORD fFlag
);
extern DWORD
sbTableAddRef (
DBPOS FAR *pDB,
DWORD dwFlags,
DSNAME *pName,
ULONG *pTag
);
void
InPlaceSwapSid(PSID pSid);
// Debug only routines
#if DBG
extern void
dbAddDBPOS (
DBPOS *pDB,
JET_SESID sesid
);
extern void
dbEndDBPOS (
DBPOS *pDB
);
#endif
// Replication meta data routines.
void
dbCacheMetaDataVector(
IN DBPOS * pDB
);
void
dbFlushMetaDataVector(
IN DBPOS * pDB,
IN USN usn,
IN PROPERTY_META_DATA_VECTOR * pMetaDataVecRemote OPTIONAL,
IN DWORD dwMetaDataFlags
);
void
dbFreeMetaDataVector(
IN DBPOS * pDB
);
void
dbSetLinkValueMetaData(
IN DBPOS *pDB,
IN DWORD dwEventCode,
IN ATTCACHE *pAC,
IN VALUE_META_DATA *pMetaDataLocal,
IN VALUE_META_DATA *pMetaDataRemote OPTIONAL,
IN DSTIME *ptimeCurrent OPTIONAL
);
void
dbTouchLinkMetaData(
IN DBPOS *pDB,
IN VALUE_META_DATA * pMetaData
);
BOOL
dbHasAttributeMetaData(
IN DBPOS * pDB,
IN ATTCACHE * pAC
);
//
// Wrapper routines that call Jet APIs and raise exceptions on all unexpected
// errors
//
// function prototypes
//
JET_ERR
JetInitException (
JET_INSTANCE *pinstance,
USHORT usFileNo,
int nLine
);
JET_ERR
JetTermException (
JET_INSTANCE instance,
USHORT usFileNo,
int nLine
);
JET_ERR
JetSetSystemParameterException (
JET_INSTANCE *pinstance,
JET_SESID sesid,
unsigned long paramid,
unsigned long lParam,
const char *sz,
USHORT usFileNo,
int nLine
);
JET_ERR
JetBeginSessionException (
JET_INSTANCE instance,
JET_SESID *psesid,
const char *szUserName,
const char *szPassword,
USHORT usFileNo,
int nLine
);
JET_ERR
JetDupSessionException (
JET_SESID sesid,
JET_SESID *psesid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetEndSessionException (
JET_SESID sesid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR JetEndSessionWithErr_(
JET_SESID sesid,
JET_ERR err,
const BOOL fHandleException,
const USHORT usFile,
const INT lLine );
JET_ERR
JetCreateDatabaseException (
JET_SESID sesid,
const char *szFilename,
const char *szConnect,
JET_DBID *pdbid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR
JetAttachDatabaseException (
JET_SESID sesid,
const char *szFilename,
JET_GRBIT grbit ,
USHORT usFileNo,
int nLine
);
JET_ERR
JetDetachDatabaseException (
JET_SESID sesid,
const char *szFilename,
USHORT usFileNo,
int nLine
);
JET_ERR
JetCreateTableException (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long lPages,
unsigned long lDensity,
JET_TABLEID *ptableid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetCreateTableException (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
unsigned long lPages,
unsigned long lDensity,
JET_TABLEID *ptableid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetGetTableColumnInfoException (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumnName,
void *pvResult,
unsigned long cbMax,
unsigned long InfoLevel,
USHORT usFileNo,
int nLine
);
JET_ERR
JetGetColumnInfoException (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
const char *szColumnName,
void *pvResult,
unsigned long cbMax,
unsigned long InfoLevel,
USHORT usFileNo,
int nLine
);
JET_ERR
JetAddColumnException (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumn,
const JET_COLUMNDEF *pcolumndef,
const void *pvDefault,
unsigned long cbDefault,
JET_COLUMNID *pcolumnid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetDeleteColumnException (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szColumn,
USHORT usFileNo,
int nLine
);
JET_ERR
JetGetTableIndexInfoException (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
void *pvResult,
unsigned long cbResult,
unsigned long InfoLevel,
DWORD dsid
);
JET_ERR
JetCreateIndexException (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_GRBIT grbit,
const char *szKey,
unsigned long cbKey,
unsigned long lDensity,
USHORT usFileNo,
int nLine
);
JET_ERR
JetDeleteIndexException (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
DWORD dsid
);
JET_ERR
JetBeginTransactionException (
JET_SESID sesid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetCommitTransactionException (
JET_SESID sesid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR
JetRollbackException (
JET_SESID sesid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR
JetCloseDatabaseException (
JET_SESID sesid,
JET_DBID dbid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR JetCloseDatabaseWithErr_(
JET_SESID sesid,
JET_DBID dbid,
JET_ERR err,
const BOOL fHandleException,
const USHORT usFile,
const INT lLine );
JET_ERR
JetCloseTableException (
JET_SESID sesid,
JET_TABLEID tableid,
USHORT usFileNo,
int nLine
);
JET_ERR JetCloseTableWithErr_(
JET_SESID sesid,
JET_TABLEID tableid,
JET_ERR err,
const BOOL fHandleException,
const USHORT usFile,
const INT lLine );
JET_ERR
JetOpenDatabaseException (
JET_SESID sesid,
const char *szFilename,
const char *szConnect,
JET_DBID *pdbid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR
JetOpenTableException (
JET_SESID sesid,
JET_DBID dbid,
const char *szTableName,
const void *pvParameters,
unsigned long cbParameters,
JET_GRBIT grbit,
JET_TABLEID *ptableid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetSetTableSequentialException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR
JetResetTableSequentialException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_GRBIT grbit,
USHORT usFileNo,
int nLine
);
JET_ERR
JetDeleteException (
JET_SESID sesid,
JET_TABLEID tableid,
USHORT usFileNo,
int nLine
);
JET_ERR
JetUpdateException (
JET_SESID sesid,
JET_TABLEID tableid,
void *pvBookmark,
unsigned long cbBookmark,
unsigned long *pcbActual,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetEscrowUpdateException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_COLUMNID columnid,
void *pvDelta,
unsigned long cbDeltaMax,
void *pvOld,
unsigned long cbOldMax,
unsigned long *pcbOldActual,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetRetrieveColumnException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_COLUMNID columnid,
void *pvData,
unsigned long cbData,
unsigned long *pcbActual,
JET_GRBIT grbit,
JET_RETINFO *pretinfo,
BOOL fExceptOnWarning,
DWORD dsid
);
JET_ERR
JetRetrieveColumnsException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_RETRIEVECOLUMN *pretrievecolumn,
unsigned long cretrievecolumn,
BOOL fExceptOnWarning ,
DWORD dsid
);
JET_ERR
JetEnumerateColumnsException(
JET_SESID sesid,
JET_TABLEID tableid,
ULONG cEnumColumnId,
JET_ENUMCOLUMNID* rgEnumColumnId,
ULONG* pcEnumColumn,
JET_ENUMCOLUMN** prgEnumColumn,
JET_PFNREALLOC pfnRealloc,
void* pvReallocContext,
ULONG cbDataMost,
JET_GRBIT grbit,
DWORD dsid );
JET_ERR
JetSetColumnException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_COLUMNID columnid,
const void *pvData,
unsigned long cbData,
JET_GRBIT grbit,
JET_SETINFO *psetinfo,
BOOL fExceptOnWarning,
DWORD dsid
);
JET_ERR
JetSetColumnsException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_SETCOLUMN *psetcolumn,
unsigned long csetcolumn ,
DWORD dsid
);
JET_ERR
JetPrepareUpdateException (
JET_SESID sesid,
JET_TABLEID tableid,
unsigned long prep,
DWORD dsid
);
JET_ERR
JetGetRecordPositionException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_RECPOS *precpos,
unsigned long cbRecpos,
DWORD dsid
);
JET_ERR
JetGotoPositionException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_RECPOS *precpos ,
DWORD dsid
);
JET_ERR
JetDupCursorException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_TABLEID *ptableid,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetGetCurrentIndexException (
JET_SESID sesid,
JET_TABLEID tableid,
char *szIndexName,
unsigned long cchIndexName,
DWORD dsid
);
JET_ERR
JetSetCurrentIndex2Exception (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
JET_GRBIT grbit,
BOOL fReturnErrors,
DWORD dsid
);
JET_ERR
JetSetCurrentIndex4Exception (
JET_SESID sesid,
JET_TABLEID tableid,
const char *szIndexName,
struct tagJET_INDEXID *pidx,
JET_GRBIT grbit,
BOOL fReturnErrors,
DWORD dsid
);
JET_ERR
JetMoveException (
JET_SESID sesid,
JET_TABLEID tableid,
long cRow,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetMakeKeyException (
JET_SESID sesid,
JET_TABLEID tableid,
const void *pvData,
unsigned long cbData,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetSeekException (
JET_SESID sesid,
JET_TABLEID tableid,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetGetBookmarkException (
JET_SESID sesid,
JET_TABLEID tableid,
void *pvBookmark,
unsigned long cbMax,
unsigned long *pcbActual,
DWORD dsid
);
JET_ERR
JetGotoBookmarkException (
JET_SESID sesid,
JET_TABLEID tableid,
void *pvBookmark,
unsigned long cbBookmark,
DWORD dsid
);
JET_ERR JetGetSecondaryIndexBookmarkException(
JET_SESID sesid,
JET_TABLEID tableid,
VOID * pvSecondaryKey,
const ULONG cbSecondaryKeyMax,
ULONG * pcbSecondaryKeyActual,
VOID * pvPrimaryBookmark,
const ULONG cbPrimaryBookmarkMax,
ULONG * pcbPrimaryBookmarkActual,
const DWORD dsid );
JET_ERR JetGotoSecondaryIndexBookmarkException(
JET_SESID sesid,
JET_TABLEID tableid,
VOID * pvSecondaryKey,
const ULONG cbSecondaryKey,
VOID * pvPrimaryBookmark,
const ULONG cbPrimaryBookmark,
const JET_GRBIT grbit,
const DWORD dsid );
JET_ERR
JetComputeStatsException (
JET_SESID sesid,
JET_TABLEID tableid,
DWORD dsid
);
JET_ERR
JetOpenTempTableException (
JET_SESID sesid,
const JET_COLUMNDEF *prgcolumndef,
unsigned long ccolumn,
JET_GRBIT grbit,
JET_TABLEID *ptableid,
JET_COLUMNID *prgcolumnid,
DWORD dsid
);
JET_ERR
JetIntersectIndexesException(
JET_SESID sesid,
JET_INDEXRANGE * rgindexrange,
unsigned long cindexrange,
JET_RECORDLIST * precordlist,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetSetIndexRangeException (
JET_SESID sesid,
JET_TABLEID tableidSrc,
JET_GRBIT grbit,
DWORD dsid
);
JET_ERR
JetIndexRecordCountException (
JET_SESID sesid,
JET_TABLEID tableid,
unsigned long *pcrec,
unsigned long crecMax ,
DWORD dsid
);
JET_ERR
JetRetrieveKeyException (
JET_SESID sesid,
JET_TABLEID tableid,
void *pvData,
unsigned long cbMax,
unsigned long *pcbActual,
JET_GRBIT grbit ,
BOOL fExceptOnWarning,
DWORD dsid
);
JET_ERR
JetGetLockException(
JET_SESID sesid,
JET_TABLEID tableid,
JET_GRBIT grbit,
DWORD dsid
);
//
// Macros to drop the line number into the Jet wrappers above.
//
#define JetInitEx(pinstance) JetInitException(pinstance, FILENO, __LINE__)
#define JetTermEx(instance) JetTermException(instance, FILENO, __LINE__)
#define JetSetSystemParameterEx(pinstance, sesid, paramid, lParam, sz) \
JetSetSystemParameterException(pinstance, sesid, paramid, lParam, sz, \
FILENO, __LINE__)
#define JetBeginSessionEx(instance, psesid, szUserName, szPassword) \
JetBeginSessionException(instance, psesid, szUserName, szPassword, \
FILENO, __LINE__)
#define JetDupSessionEx(sesid, psesid) \
JetDupSessionException(sesid, psesid, FILENO, __LINE__)
#define JetEndSessionEx(sesid, grbit) \
JetEndSessionException(sesid, grbit, FILENO, __LINE__)
#define JetEndSessionWithErr( sesid, err ) \
JetEndSessionWithErr_( sesid, err, TRUE, FILENO, __LINE__ )
#define JetEndSessionWithErrUnhandled( sesid, err ) \
JetEndSessionWithErr_( sesid, err, FALSE, FILENO, __LINE__ )
#define JetGetVersionEx(sesid, pwVersion) \
JetGetVersionException(sesid, pwVersion, FILENO, __LINE__)
#define JetCreateDatabaseEx(sesid, szFilename, szConnect, pdbid, grbit) \
JetCreateDatabaseException(sesid, szFilename, szConnect, pdbid, grbit, \
FILENO, __LINE__)
#define JetAttachDatabaseEx(sesid, szFilename, grbit ) \
JetAttachDatabaseException(sesid, szFilename, grbit , FILENO, __LINE__)
#define JetDetachDatabaseEx(sesid, szFilename) \
JetDetachDatabaseException(sesid, szFilename, FILENO, __LINE__)
#define JetCreateTableEx(sesid, dbid, szTableName, lPages, lDensity, ptableid) \
JetCreateTableException(sesid, dbid, szTableName, lPages, lDensity, \
ptableid, FILENO, __LINE__)
#define JetCreateTableEx(sesid, dbid, szTableName, lPages, lDensity,ptableid) \
JetCreateTableException(sesid, dbid, szTableName, lPages, lDensity, \
ptableid, FILENO, __LINE__)
#define JetGetTableColumnInfoEx(sesid, tableid, szColumnName, pvResult, cbMax, \
InfoLevel) \
JetGetTableColumnInfoException(sesid, tableid, szColumnName, pvResult, \
cbMax, InfoLevel, FILENO, __LINE__)
#define JetGetColumnInfoEx(sesid, dbid, szTableName, szColumnName, pvResult, \
cbMax, InfoLevel) \
JetGetColumnInfoException(sesid, dbid, szTableName, szColumnName, \
pvResult, cbMax, InfoLevel, FILENO, __LINE__)
#define JetAddColumnEx(sesid, tableid, szColumn, pcolumndef, pvDefault, \
cbDefault, pcolumnid) \
JetAddColumnException(sesid, tableid, szColumn, pcolumndef, pvDefault, \
cbDefault, pcolumnid, FILENO, __LINE__)
#define JetDeleteColumnEx(sesid, tableid, szColumn) \
JetDeleteColumnException(sesid, tableid, szColumn, FILENO, __LINE__)
#define JetGetTableIndexInfoEx(sesid, tableid, szIndexName, pvResult, \
cbResult, InfoLevel) \
JetGetTableIndexInfoException(sesid, tableid, szIndexName, pvResult, \
cbResult, InfoLevel, DSID(FILENO, __LINE__))
#define JetCreateIndexEx(sesid, tableid, szIndexName, grbit, szKey, cbKey, \
lDensity) \
JetCreateIndexException(sesid, tableid, szIndexName, grbit, szKey, \
cbKey, lDensity, FILENO, __LINE__)
#define JetDeleteIndexEx(sesid, tableid, szIndexName) \
JetDeleteIndexException(sesid, tableid, szIndexName, DSID(FILENO, __LINE__))
#define JetBeginTransactionEx(sesid) \
JetBeginTransactionException(sesid, FILENO, __LINE__)
#define JetCommitTransactionEx(sesid, grbit) \
JetCommitTransactionException(sesid, grbit, FILENO, __LINE__)
#define JetRollbackEx(sesid, grbit) \
JetRollbackException(sesid, grbit, FILENO, __LINE__)
#define JetCloseDatabaseEx(sesid, dbid, grbit) \
JetCloseDatabaseException(sesid, dbid, grbit, FILENO, __LINE__)
#define JetCloseDatabaseWithErr( sesid, dbid, err ) \
JetCloseDatabaseWithErr_(sesid, dbid, err, TRUE, FILENO, __LINE__ )
#define JetCloseDatabaseWithErrUnhandled( sesid, dbid, err ) \
JetCloseDatabaseWithErr_(sesid, dbid, err, FALSE, FILENO, __LINE__ )
#define JetCloseTableEx(sesid, tableid) \
JetCloseTableException(sesid, tableid, FILENO, __LINE__)
#define JetCloseTableWithErr( sesid, tableid, err ) \
JetCloseTableWithErr_(sesid, tableid, err, TRUE, FILENO, __LINE__ )
#define JetCloseTableWithErrUnhandled( sesid, tableid, err ) \
JetCloseTableWithErr_(sesid, tableid, err, FALSE, FILENO, __LINE__ )
#define JetOpenDatabaseEx(sesid, szFilename, szConnect, pdbid, grbit) \
JetOpenDatabaseException(sesid, szFilename, szConnect, pdbid, grbit, \
FILENO, __LINE__)
#define JetOpenTableEx(sesid, dbid, szTableName, pvParameters, cbParameters, \
grbit, ptableid) \
JetOpenTableException(sesid, dbid, szTableName, pvParameters, \
cbParameters, grbit, ptableid, FILENO, __LINE__)
#define JetSetTableSequentialEx(sesid, tableid, grbit) \
JetSetTableSequentialException(sesid, tableid, grbit, FILENO, __LINE__)
#define JetResetTableSequentialEx(sesid, tableid, grbit) \
JetResetTableSequentialException(sesid, tableid, grbit, FILENO, __LINE__)
#define JetDeleteEx(sesid, tableid) \
JetDeleteException(sesid, tableid, FILENO, __LINE__)
#define JetUpdateEx(sesid, tableid, pvBookmark, cbBookmark, pcbActual) \
JetUpdateException(sesid, tableid, pvBookmark, cbBookmark, pcbActual, \
NO_GRBIT, DSID(FILENO, __LINE__))
#define JetUpdate2Ex(sesid, tableid, pvBookmark, cbBookmark, pcbActual, grbit) \
JetUpdateException(sesid, tableid, pvBookmark, cbBookmark, pcbActual, \
grbit, DSID(FILENO, __LINE__))
#define JetEscrowUpdateEx(sesid, tableid, columnid, pvDelta, cbDeltaMax, \
pvOld, cbOldMax, pcbOldActual, grbit) \
JetEscrowUpdateException(sesid, tableid, columnid, pvDelta,cbDeltaMax,\
pvOld, cbOldMax, pcbOldActual, grbit, \
DSID(FILENO, __LINE__))
#define JetSetColumnEx(sesid,tableid,columnid,pvData, cbData, grbit, psetinfo)\
JetSetColumnException(sesid, tableid, columnid, pvData, cbData, grbit,\
psetinfo, FALSE, DSID(FILENO, __LINE__))
#define JetSetColumnsEx(sesid, tableid, psetcolumn, csetcolumn ) \
JetSetColumnsException(sesid, tableid, psetcolumn, csetcolumn, \
DSID(FILENO,__LINE__))
#define JetPrepareUpdateEx(sesid, tableid, prep) \
JetPrepareUpdateException(sesid, tableid, prep, DSID(FILENO, __LINE__))
#define JetGetRecordPositionEx(sesid, tableid, precpos, cbRecpos) \
JetGetRecordPositionException(sesid, tableid, precpos, cbRecpos, \
DSID(FILENO, __LINE__))
#define JetGotoPositionEx(sesid, tableid, precpos ) \
JetGotoPositionException(sesid, tableid, precpos, \
DSID(FILENO, __LINE__))
#define JetDupCursorEx(sesid, tableid, ptableid, grbit) \
JetDupCursorException(sesid, tableid, ptableid, grbit, \
DSID(FILENO, __LINE__))
#define JetGetCurrentIndexEx(sesid, tableid, szIndexName, cchIndexName) \
JetGetCurrentIndexException(sesid, tableid, szIndexName, cchIndexName,\
DSID(FILENO, __LINE__))
#define JetMoveEx(sesid, tableid, cRow, grbit) \
JetMoveException(sesid, tableid, cRow, grbit, DSID(FILENO, __LINE__))
#define JetMakeKeyEx(sesid, tableid, pvData, cbData, grbit) \
JetMakeKeyException(sesid, tableid, pvData, cbData, grbit, \
DSID(FILENO,__LINE__))
#define JetSeekEx(sesid, tableid, grbit) \
JetSeekException(sesid, tableid, grbit, DSID(FILENO, __LINE__))
#define JetGetBookmarkEx(sesid, tableid, pvBookmark, cbMax, pcbActual) \
JetGetBookmarkException(sesid, tableid, pvBookmark, cbMax, pcbActual, \
DSID(FILENO, __LINE__))
#define JetGotoBookmarkEx(sesid, tableid, pvBookmark, cbBookmark) \
JetGotoBookmarkException(sesid, tableid, pvBookmark, cbBookmark, \
DSID(FILENO, __LINE__))
#define JetGetSecondaryIndexBookmarkEx(sesid, tableid, \
pvSecondaryKey, cbSecondaryKeyMax, \
pcbSecondaryKeyActual, \
pvPrimaryBookmark, \
cbPrimaryBookmarkMax, \
pcbPrimaryBookmarkActual) \
JetGetSecondaryIndexBookmarkException(sesid, tableid, \
pvSecondaryKey, \
cbSecondaryKeyMax, \
pcbSecondaryKeyActual, \
pvPrimaryBookmark, \
cbPrimaryBookmarkMax, \
pcbPrimaryBookmarkActual, \
DSID(FILENO, __LINE__))
#define JetGotoSecondaryIndexBookmarkEx(sesid, tableid, \
pvSecondaryKey, cbSecondaryKey, \
pvPrimaryBookmark, cbPrimaryBookmark, \
grbit) \
JetGotoSecondaryIndexBookmarkException(sesid, tableid, \
pvSecondaryKey, \
cbSecondaryKey, \
pvPrimaryBookmark, \
cbPrimaryBookmark, \
grbit, \
DSID(FILENO, __LINE__))
#define JetComputeStatsEx(sesid, tableid) \
JetComputeStatsException(sesid, tableid, DSID(FILENO, __LINE__))
#define JetOpenTempTableEx(sesid, prgcolumndef, ccolumn, grbit, ptableid, \
prgcolumnid) \
JetOpenTempTableException(sesid, prgcolumndef, ccolumn, grbit, \
ptableid, prgcolumnid, DSID(FILENO,__LINE__))
#define JetSetIndexRangeEx(sesid, tableidSrc, grbit) \
JetSetIndexRangeException(sesid, tableidSrc, grbit, \
DSID(FILENO, __LINE__))
#define JetIntersectIndexesEx(sesid, rgindexrange, cindexrange, precordlist, grbit)\
JetIntersectIndexesException(sesid, rgindexrange, cindexrange, precordlist, grbit, \
DSID(FILENO, __LINE__))
#define JetIndexRecordCountEx(sesid, tableid, pcrec, crecMax ) \
JetIndexRecordCountException(sesid, tableid, pcrec, crecMax , \
DSID(FILENO, __LINE__))
#define JetRetrieveKeyEx(sesid, tableid, pvData, cbMax, pcbActual, grbit ) \
JetRetrieveKeyException(sesid, tableid, pvData, cbMax, pcbActual, \
grbit, TRUE, DSID(FILENO, __LINE__))
// Some wrappers to only allow succes or certain warnings.
#define JetRetrieveKeyWarnings(sesid, tableid, pvData, cbMax, \
pcbActual, grbit ) \
JetRetrieveKeyException(sesid, tableid, pvData, cbMax, pcbActual, \
grbit, FALSE, DSID(FILENO, __LINE__))
#define JetRetrieveKeySuccess(sesid, tableid, pvData, cbMax, \
pcbActual, grbit ) \
JetRetrieveKeyException(sesid, tableid, pvData, cbMax, pcbActual, \
grbit, TRUE, DSID(FILENO, __LINE__))
#define JetSetColumnWarnings(sesid,tableid,columnid,pvData, cbData, \
grbit, psetinfo) \
JetSetColumnException(sesid, tableid, columnid, pvData, cbData, grbit,\
psetinfo, FALSE, DSID(FILENO, __LINE__))
#define JetSetColumnSuccess(sesid,tableid,columnid,pvData, cbData, \
grbit, psetinfo) \
JetSetColumnException(sesid, tableid, columnid, pvData, cbData, grbit,\
psetinfo, TRUE, DSID(FILENO, __LINE__))
// A JetRetrieveColumn call that returns only success
#define JetRetrieveColumnSuccess(sesid, tableid, columnid, pvData, cbData, \
pcbActual, grbit, pretinfo) \
JetRetrieveColumnException(sesid, tableid, columnid, pvData, \
cbData, pcbActual, grbit, pretinfo,\
TRUE, DSID(FILENO, __LINE__))
// A JetRetrieveColumn call that returns success, or NULL, or buffer truncated
#define JetRetrieveColumnWarnings(sesid, tableid, columnid, pvData, cbData, \
pcbActual, grbit, pretinfo) \
JetRetrieveColumnException(sesid, tableid, columnid, pvData, cbData, \
pcbActual, grbit, pretinfo, FALSE, \
DSID(FILENO,__LINE__))
// A JetRetrieveColumns call that returns only success
#define JetRetrieveColumnsSuccess(sesid, tableid, pretrievecolumn, \
cretrievecolumn) \
JetRetrieveColumnsException(sesid, tableid, pretrievecolumn, \
cretrievecolumn, TRUE, \
DSID(FILENO, __LINE__))
// A JetRetrieveColumns call that returns success, or NULL, or buffer truncated
#define JetRetrieveColumnsWarnings(sesid, tableid, pretrievecolumn, \
cretrievecolumn) \
JetRetrieveColumnsException(sesid, tableid, pretrievecolumn, \
cretrievecolumn, FALSE, DSID(FILENO, __LINE__))
#define JetEnumerateColumnsEx(sesid, tableid, cEnumColumnId, rgEnumColumnId, \
pcEnumColumn, prgEnumColumn, pfnRealloc, \
pvReallocContext, cbDataMost, grbit) \
JetEnumerateColumnsException(sesid, tableid, cEnumColumnId, \
rgEnumColumnId, pcEnumColumn, prgEnumColumn, \
pfnRealloc, pvReallocContext, cbDataMost, grbit, \
DSID(FILENO, __LINE__))
// A JetSetCurrentIndex call that either succeeds or excepts
#define JetSetCurrentIndexSuccess(sesid, tableid, szIndexName) \
JetSetCurrentIndex2Exception(sesid, tableid, szIndexName, \
JET_bitMoveFirst, FALSE, DSID(FILENO, __LINE__))
// A JetSetCurrentIndex call that also returns expected errors (index doesn't
// exist)
#define JetSetCurrentIndexWarnings(sesid, tableid, szIndexName) \
JetSetCurrentIndex2Exception(sesid, tableid, szIndexName, \
JET_bitMoveFirst, TRUE, DSID(FILENO, __LINE__))
// A JetSetCurrentIndex call that either succeeds or excepts
#define JetSetCurrentIndex2Success(sesid, tableid, szIndexName, grbit) \
JetSetCurrentIndex2Exception(sesid, tableid, szIndexName, grbit, \
FALSE, DSID(FILENO, __LINE__))
// A JetSetCurrentIndex call that also returns expected errors (index doesn't
// exist)
#define JetSetCurrentIndex2Warnings(sesid, tableid, szIndexName,grbit) \
JetSetCurrentIndex2Exception(sesid, tableid, szIndexName, grbit, \
TRUE, DSID(FILENO, __LINE__))
// A JetSetCurrentIndex call that either succeeds or excepts
#define JetSetCurrentIndex4Success(sesid, tableid, szIndexName, pidx, grbit) \
JetSetCurrentIndex4Exception(sesid, tableid, szIndexName, pidx, grbit,\
FALSE, DSID(FILENO, __LINE__))
// A JetSetCurrentIndex call that also returns expected errors (index doesn't
// exist)
#define JetSetCurrentIndex4Warnings(sesid, tableid, szIndexName, pidx,grbit) \
JetSetCurrentIndex4Exception(sesid, tableid, szIndexName, pidx, grbit,\
TRUE, DSID(FILENO, __LINE__))
#define JetGetLockEx(sesid, tableid, grbit) \
JetGetLockException(sesid, tableid, grbit, DSID(FILENO, __LINE__))
extern
BOOL
dnReadPreProcessTransactionalData (
BOOL fCommit
);
extern
VOID
dnReadPostProcessTransactionalData (
THSTATE *pTHS,
BOOL fCommit,
BOOL fCommitted
);
extern
VOID
dbEscrowPromote(
DWORD phantomDNT,
DWORD objectDNT);
extern
BOOL
dbEscrowPreProcessTransactionalData(
DBPOS *pDB,
BOOL fCommit);
extern
VOID
dbEscrowPostProcessTransactionalData(
DBPOS *pDB,
BOOL fCommit,
BOOL fCommitted);
DWORD
dbMakeCurrent(
DBPOS *pDB,
struct _d_memname *pname);
BOOL
dnGetCacheByDNT(
DBPOS *pDB,
DWORD tag,
d_memname **ppname
);
BOOL
dnGetCacheByPDNTRdn (
DBPOS *pDB,
DWORD parenttag,
DWORD cbRDN,
WCHAR *pRDN,
ATTRTYP rdnType,
d_memname **ppname);
BOOL
dnGetCacheByGuid (
DBPOS *pDB,
GUID *pGuid,
d_memname **ppname);
d_memname *
DNcache(
IN DBPOS * pDB,
IN JET_TABLEID tblid,
IN BOOL bCheckForExisting
);
BOOL
dbIsModifiedInMetaData (
DBPOS *pDB,
ATTRTYP att
);
DWORD
dbMapiTypeFromObjClass (
ATTRTYP objClass,
wchar_t *pTemp
);
// These data structures are used to marshall and unmarshal restart args. They
// are used in dbtools. If these structures change, then the code in
// DBCreateRestart, DBCreateRestartForSAM, and DBUnmarshallRestart must all
// change in sync.
// A packed restart arg has a single PACKED_KEY_HEADER, followed by N
// PACKED_KEY_INDEXes (where N is NumIndices in the PACKED_KEY_HEADER), followed
// by M DNTs (where M is NumDNTs in the PACKED_KEY_HEADER). Note then, that the
// whole restart arg has 2 variable sized arrays in it, which is why we use this
// weird hand marshalling.
typedef struct _PACKED_KEY_HEADER {
DWORD NumIndices;
DWORD NumDNTs;
DWORD StartDNT;
DWORD cbCurrentKey;
DWORD cbCurrentBM;
DWORD ulSearchType;
RESOBJ BaseResObj;
GUID BaseGuid;
DWORD ulSorted;
DWORD indexType;
DWORD bOnCandidate;
DWORD fChangeDirection;
DWORD dupDetectionType;
BOOL bOneNC;
DWORD SearchEntriesVisited;
DWORD SearchEntriesReturned;
BOOL fVLVSearch:1;
BOOL bUsingMAPIContainer:1;
ULONG ulVLVContentCount;
ULONG ulVLVTargetPosition;
DWORD cbVLVCurrPositionKey;
DWORD MAPIContainerDNT;
DWORD asqMode;
ULONG ulASQLastUpperBound;
} PACKED_KEY_HEADER;
typedef struct _PACKED_KEY_INDEX {
DWORD bPDNT;
DWORD bIsSingleValued;
DWORD bIsEqualityBased;
DWORD bIsForSort;
ATTRTYP type;
DWORD cbIndexName;
DWORD cbDBKeyLower;
DWORD cbDBKeyUpper;
} PACKED_KEY_INDEX;
typedef struct _INDEX_RANGE {
DWORD cbValLower;
PVOID pvValLower;
DWORD cbValUpper;
PVOID pvValUpper;
} INDEX_RANGE;
#define dbmkfir_PDNT 1
#define dbmkfir_NCDNT 2
#define dbmkfir_LINK 3
#define DB_MKI_USE_SEARCH_TABLE 1
#define DB_MKI_GET_NUM_RECS 2
#define DB_MKI_SET_CURR_INDEX 4
KEY_INDEX *
dbMakeKeyIndex(
DBPOS *pDB,
DWORD dwSearchType,
BOOL bIsSingleValued,
DWORD Option,
char * szIndex,
JET_INDEXID * pindexid,
DWORD Flags,
DWORD cIndexRanges,
INDEX_RANGE * rgIndexRange
);
void
dbFreeKeyIndex(
THSTATE *pTHS,
KEY_INDEX *pIndex
);
DWORD dbFreeFilter(
DBPOS *pDB,
FILTER *pFil);
BOOL
dbFObjectInCorrectDITLocation (
DBPOS *pDB,
JET_TABLEID tblId
);
BOOL
dbFObjectInCorrectNC (
DBPOS *pDB,
ULONG DNT,
JET_TABLEID tblId
);
BOOL
dbMatchSearchCriteriaForSortedTable (
DBPOS *pDB,
BOOL *pCanRead
);
VOID
dbSearchDuplicateCreateHashTable(
IN struct _LHT** pplht
);
BOOL __inline
dbNeedToFlushDNCacheOnUpdate(ATTRTYP at)
/*++
do we need to flush the dn read cache when this attribute is updated?
--*/
{
switch(at) {
case ATT_OBJECT_GUID:
case ATT_OBJECT_SID:
case ATT_RDN:
case ATT_OBJECT_CLASS:
case ATT_NT_SECURITY_DESCRIPTOR:
// Changing these attributes changes the record's identity, so we'll
// need to flush this DNT from the read cache after we've updated the
// record.
return TRUE;
default:
return FALSE;
}
}
#define SORTED_INDEX(x) ( ((x)==TEMP_TABLE_INDEX_TYPE) || ((x)==TEMP_TABLE_MEMORY_ARRAY_TYPE) )
// allocate that much memory for SD by default (will increase if needed)
#define DEFAULT_SD_SIZE 4096
ULONG
CountAncestorsIndexSizeHelper (
DBPOS *pDB,
DWORD cAncestors,
DWORD *pAncestors
);
PSDCACHE_ENTRY
dbFindSDCacheEntry(GLOBALDNREADCACHE* pCache, SDID sdID);
int
IntExtSecDesc(DBPOS FAR *pDB, USHORT extTableOp,
ULONG intLen, UCHAR *pIntVal,
ULONG *pExtLen, UCHAR **ppExtVal,
ULONG ulUpdateDnt, JET_TABLEID jTbl,
ULONG SecurityInformation);
extern JET_TABLEID HiddenTblid;
DBPOS * dbGrabHiddenDBPOS(THSTATE *pTHS);
void dbReleaseHiddenDBPOS(DBPOS *pDB);
// How close to ends do we get before doing our own positioning
#define EPSILON 100
#define NormalizeIndexPosition(BeginNum, EndNum) ( (EndNum) < (BeginNum) ? 0 : (EndNum) - (BeginNum) + 1 )
#endif /* _dbintrnl_h_ */
| 33.889969 | 123 | 0.608115 | [
"object"
] |
942f92f37b6bf23cbd71db73dd4e4044ced2eeb6 | 1,645 | h | C | third_party/gecko-16/win32/include/nsIScriptTimeoutHandler.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | 1 | 2018-02-05T04:23:18.000Z | 2018-02-05T04:23:18.000Z | third_party/gecko-16/win32/include/nsIScriptTimeoutHandler.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | third_party/gecko-16/win32/include/nsIScriptTimeoutHandler.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsIScriptTimeoutHandler_h___
#define nsIScriptTimeoutHandler_h___
class nsIArray;
#define NS_ISCRIPTTIMEOUTHANDLER_IID \
{ 0xcaf520a5, 0x8078, 0x4cba, \
{ 0x8a, 0xb9, 0xb6, 0x8a, 0x12, 0x43, 0x4f, 0x05 } }
/**
* Abstraction of the script objects etc required to do timeouts in a
* language agnostic way.
*/
class nsIScriptTimeoutHandler : public nsISupports
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTTIMEOUTHANDLER_IID)
// Get a script object for the language suitable for passing back to
// the language's context as an event handler. If this returns nsnull,
// GetHandlerText() will be called to get the string.
virtual JSObject *GetScriptObject() = 0;
// Get the handler text of not a compiled object.
virtual const PRUnichar *GetHandlerText() = 0;
// Get the location of the script.
// Note: The memory pointed to by aFileName is owned by the
// nsIScriptTimeoutHandler and should not be freed by the caller.
virtual void GetLocation(const char **aFileName, PRUint32 *aLineNo) = 0;
// If a script object, get the argv suitable for passing back to the
// script context.
virtual nsIArray *GetArgv() = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIScriptTimeoutHandler,
NS_ISCRIPTTIMEOUTHANDLER_IID)
#endif // nsIScriptTimeoutHandler_h___
| 35 | 79 | 0.724012 | [
"object"
] |
9430f1e963f1121d9d8353a0d28080857020d556 | 28,462 | c | C | src/insmult.c | Pointer2VoidStar/CLIPS | f70ef28aca7f1d993071724276d83797998c720a | [
"MIT"
] | 1 | 2018-05-18T07:39:56.000Z | 2018-05-18T07:39:56.000Z | src/insmult.c | Pointer2VoidStar/CLIPS | f70ef28aca7f1d993071724276d83797998c720a | [
"MIT"
] | 4 | 2017-03-15T23:28:14.000Z | 2017-10-29T22:48:28.000Z | src/insmult.c | Pointer2VoidStar/CLIPS | f70ef28aca7f1d993071724276d83797998c720a | [
"MIT"
] | null | null | null | /*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.40 11/07/17 */
/* */
/* INSTANCE MULTIFIELD_TYPE SLOT MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: Access routines for Instance Multifield Slots */
/* */
/* Principal Programmer(s): */
/* Brian L. Dantes */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.23: Correction for FalseSymbol/TrueSymbol. DR0859 */
/* */
/* 6.24: Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/* Changed integer type/precision. */
/* */
/* 6.40: Added Env prefix to GetEvaluationError and */
/* SetEvaluationError functions. */
/* */
/* Pragma once and other inclusion changes. */
/* */
/* Added support for booleans with <stdbool.h>. */
/* */
/* Removed use of void pointers for specific */
/* data structures. */
/* */
/* Removed direct-mv-replace, direct-mv-insert, */
/* direct-mv-delete, mv-slot-replace, */
/* mv-slot-insert, and mv-slot-delete functions. */
/* */
/* UDF redesign. */
/* */
/* Eval support for run time and bload only. */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if OBJECT_SYSTEM
#include "argacces.h"
#include "envrnmnt.h"
#include "extnfunc.h"
#include "insfun.h"
#include "msgfun.h"
#include "msgpass.h"
#include "multifun.h"
#include "prntutil.h"
#include "router.h"
#include "insmult.h"
/* =========================================
*****************************************
CONSTANTS
=========================================
***************************************** */
#define INSERT 0
#define REPLACE 1
#define DELETE_OP 2
/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/
static Instance *CheckMultifieldSlotInstance(UDFContext *);
static InstanceSlot *CheckMultifieldSlotModify(Environment *,int,const char *,Instance *,
Expression *,long long *,long long *,UDFValue *);
static void AssignSlotToDataObject(UDFValue *,InstanceSlot *);
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/***************************************************
NAME : SetupInstanceMultifieldCommands
DESCRIPTION : Defines function interfaces for
manipulating instance multislots
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Functions defined to KB
NOTES : None
***************************************************/
void SetupInstanceMultifieldCommands(
Environment *theEnv)
{
#if (! RUN_TIME)
AddUDF(theEnv,"slot-direct-replace$","b",4,UNBOUNDED,"*;y;l;l",DirectMVReplaceCommand,"DirectMVReplaceCommand",NULL);
AddUDF(theEnv,"slot-direct-insert$","b",3,UNBOUNDED,"*;y;l",DirectMVInsertCommand,"DirectMVInsertCommand",NULL);
AddUDF(theEnv,"slot-direct-delete$","b",3,3,"l;y",DirectMVDeleteCommand,"DirectMVDeleteCommand",NULL);
AddUDF(theEnv,"slot-replace$","*",5,UNBOUNDED,"*;iny;y;l;l",MVSlotReplaceCommand,"MVSlotReplaceCommand",NULL);
AddUDF(theEnv,"slot-insert$","*",4,UNBOUNDED,"*;iny;y;l",MVSlotInsertCommand,"MVSlotInsertCommand",NULL);
AddUDF(theEnv,"slot-delete$","*",4,4,"l;iny;y",MVSlotDeleteCommand,"MVSlotDeleteCommand",NULL);
#endif
}
/***********************************************************************************
NAME : MVSlotReplaceCommand
DESCRIPTION : Allows user to replace a specified field of a multi-value slot
The slot is directly read (w/o a get- message) and the new
slot-value is placed via a put- message.
This function is not valid for single-value slots.
INPUTS : Caller's result buffer
RETURNS : True if multi-value slot successfully modified,
false otherwise
SIDE EFFECTS : Put messsage sent for slot
NOTES : H/L Syntax : (slot-replace$ <instance> <slot>
<range-begin> <range-end> <value>)
***********************************************************************************/
void MVSlotReplaceCommand(
Environment *theEnv,
UDFContext *context,
UDFValue *returnValue)
{
UDFValue newval,newseg,oldseg;
Instance *ins;
InstanceSlot *sp;
long long start, end;
size_t rs, re, srcLen, dstLen;
size_t i, j, k;
Expression arg;
returnValue->lexemeValue = FalseSymbol(theEnv);
ins = CheckMultifieldSlotInstance(context);
if (ins == NULL)
return;
sp = CheckMultifieldSlotModify(theEnv,REPLACE,"slot-replace$",ins,
GetFirstArgument()->nextArg,&start,&end,&newval);
if (sp == NULL)
return;
AssignSlotToDataObject(&oldseg,sp);
/*===========================================*/
/* Verify the start and end index arguments. */
/*===========================================*/
if ((end < start) || (start < 1) || (end < 1) || // TBD Refactor
(((long long) ((size_t) start)) != start) ||
(((long long) ((size_t) end)) != end))
{
MVRangeError(theEnv,start,end,oldseg.range,"slot-replace$");
return;
}
/*============================================*/
/* Convert the indices to unsigned zero-based */
/* values including the begin value. */
/*============================================*/
rs = (size_t) start;
re = (size_t) end;
srcLen = oldseg.range;
if ((rs > srcLen) || (re > srcLen))
{
MVRangeError(theEnv,start,end,oldseg.range,"slot-replace$");
return;
}
rs--;
re--;
rs += oldseg.begin;
re += oldseg.begin;
dstLen = srcLen - (re - rs + 1); // TBD Refactor
newseg.begin = 0;
newseg.range = dstLen;
newseg.multifieldValue = CreateMultifield(theEnv,dstLen);
/*===================================*/
/* Delete the members from the slot. */
/*===================================*/
if (newval.header->type == MULTIFIELD_TYPE) // TBD Refactor
{ dstLen = srcLen - (re - rs + 1) + newval.range; }
else
{ dstLen = srcLen - (re - rs); }
newseg.begin = 0;
newseg.range = dstLen;
newseg.multifieldValue = CreateMultifield(theEnv,dstLen);
for (i = oldseg.begin, j = 0; i < (oldseg.begin + oldseg.range); i++)
{
if (i == rs)
{
if (newval.header->type == MULTIFIELD_TYPE)
{
for (k = newval.begin; k < (newval.begin + newval.range); k++)
{ newseg.multifieldValue->contents[j++].value = newval.multifieldValue->contents[k].value; }
}
else
{ newseg.multifieldValue->contents[j++].value = newval.value; }
continue;
}
else if ((i > rs) && (i <= re))
{ continue; }
newseg.multifieldValue->contents[j++].value = oldseg.multifieldValue->contents[i].value;
}
arg.type = MULTIFIELD_TYPE;
arg.value = &newseg;
arg.nextArg = NULL;
arg.argList = NULL;
DirectMessage(theEnv,sp->desc->overrideMessage,ins,returnValue,&arg);
}
/***********************************************************************************
NAME : MVSlotInsertCommand
DESCRIPTION : Allows user to insert a specified field of a multi-value slot
The slot is directly read (w/o a get- message) and the new
slot-value is placed via a put- message.
This function is not valid for single-value slots.
INPUTS : Caller's result buffer
RETURNS : True if multi-value slot successfully modified, false otherwise
SIDE EFFECTS : Put messsage sent for slot
NOTES : H/L Syntax : (slot-insert$ <instance> <slot> <index> <value>)
***********************************************************************************/
void MVSlotInsertCommand(
Environment *theEnv,
UDFContext *context,
UDFValue *returnValue)
{
UDFValue newval,newseg,oldseg;
Instance *ins;
InstanceSlot *sp;
long long theIndex;
Expression arg;
size_t uindex;
returnValue->lexemeValue = FalseSymbol(theEnv);
ins = CheckMultifieldSlotInstance(context);
if (ins == NULL)
return;
sp = CheckMultifieldSlotModify(theEnv,INSERT,"slot-insert$",ins,
GetFirstArgument()->nextArg,&theIndex,NULL,&newval);
if (sp == NULL)
return;
AssignSlotToDataObject(&oldseg,sp);
if ((((long long) ((size_t) theIndex)) != theIndex) ||
(theIndex < 1))
{
MVRangeError(theEnv,theIndex,theIndex,oldseg.range,"slot-insert$");
return;
}
uindex = (size_t) theIndex;
if (InsertMultiValueField(theEnv,&newseg,&oldseg,uindex,&newval,"slot-insert$") == false)
return;
arg.type = MULTIFIELD_TYPE;
arg.value = &newseg;
arg.nextArg = NULL;
arg.argList = NULL;
DirectMessage(theEnv,sp->desc->overrideMessage,ins,returnValue,&arg);
}
/***********************************************************************************
NAME : MVSlotDeleteCommand
DESCRIPTION : Allows user to delete a specified field of a multi-value slot
The slot is directly read (w/o a get- message) and the new
slot-value is placed via a put- message.
This function is not valid for single-value slots.
INPUTS : Caller's result buffer
RETURNS : True if multi-value slot successfully modified, false otherwise
SIDE EFFECTS : Put message sent for slot
NOTES : H/L Syntax : (slot-delete$ <instance> <slot>
<range-begin> <range-end>)
***********************************************************************************/
void MVSlotDeleteCommand(
Environment *theEnv,
UDFContext *context,
UDFValue *returnValue)
{
UDFValue newseg,oldseg;
Instance *ins;
InstanceSlot *sp;
long long start, end;
Expression arg;
size_t rs, re, srcLen, dstLen, i, j;
returnValue->lexemeValue = FalseSymbol(theEnv);
ins = CheckMultifieldSlotInstance(context);
if (ins == NULL)
return;
sp = CheckMultifieldSlotModify(theEnv,DELETE_OP,"slot-delete$",ins,
GetFirstArgument()->nextArg,&start,&end,NULL);
if (sp == NULL)
return;
AssignSlotToDataObject(&oldseg,sp);
/*===========================================*/
/* Verify the start and end index arguments. */
/*===========================================*/
if ((end < start) || (start < 1) || (end < 1) || // TBD Refactor
(((long long) ((size_t) start)) != start) ||
(((long long) ((size_t) end)) != end))
{
MVRangeError(theEnv,start,end,oldseg.range,"slot-delete$");
SetEvaluationError(theEnv,true);
SetMultifieldErrorValue(theEnv,returnValue);
return;
}
/*============================================*/
/* Convert the indices to unsigned zero-based */
/* values including the begin value. */
/*============================================*/
rs = (size_t) start;
re = (size_t) end;
srcLen = oldseg.range;
if ((rs > srcLen) || (re > srcLen))
{
MVRangeError(theEnv,start,end,oldseg.range,"slot-delete$");
SetEvaluationError(theEnv,true);
SetMultifieldErrorValue(theEnv,returnValue);
return;
}
rs--;
re--;
rs += oldseg.begin;
re += oldseg.begin;
/*===================================*/
/* Delete the members from the slot. */
/*===================================*/
dstLen = srcLen - (re - rs + 1); // TBD Refactor
newseg.begin = 0;
newseg.range = dstLen;
newseg.multifieldValue = CreateMultifield(theEnv,dstLen);
for (i = oldseg.begin, j = 0; i < (oldseg.begin + oldseg.range); i++)
{
if ((i >= rs) && (i <= re)) continue;
newseg.multifieldValue->contents[j++].value = oldseg.multifieldValue->contents[i].value;
}
arg.type = MULTIFIELD_TYPE;
arg.value = &newseg;
arg.nextArg = NULL;
arg.argList = NULL;
DirectMessage(theEnv,sp->desc->overrideMessage,ins,returnValue,&arg);
}
/*****************************************************************
NAME : DirectMVReplaceCommand
DESCRIPTION : Directly replaces a slot's value
INPUTS : None
RETURNS : True if put OK, false otherwise
SIDE EFFECTS : Slot modified
NOTES : H/L Syntax: (direct-slot-replace$ <slot>
<range-begin> <range-end> <value>)
*****************************************************************/
void DirectMVReplaceCommand(
Environment *theEnv,
UDFContext *context,
UDFValue *returnValue)
{
InstanceSlot *sp;
Instance *ins;
long long start, end;
size_t rs, re, srcLen, dstLen;
size_t i, j, k;
UDFValue newval, newseg, oldseg;
if (CheckCurrentMessage(theEnv,"direct-slot-replace$",true) == false)
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
ins = GetActiveInstance(theEnv);
sp = CheckMultifieldSlotModify(theEnv,REPLACE,"direct-slot-replace$",ins,
GetFirstArgument(),&start,&end,&newval);
if (sp == NULL)
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
AssignSlotToDataObject(&oldseg,sp);
/*===========================================*/
/* Verify the start and end index arguments. */
/*===========================================*/
if ((end < start) || (start < 1) || (end < 1) || // TBD Refactor
(((long long) ((size_t) start)) != start) ||
(((long long) ((size_t) end)) != end))
{
MVRangeError(theEnv,start,end,oldseg.range,"direct-slot-replace$");
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
/*============================================*/
/* Convert the indices to unsigned zero-based */
/* values including the begin value. */
/*============================================*/
rs = (size_t) start;
re = (size_t) end;
srcLen = oldseg.range;
if ((rs > srcLen) || (re > srcLen))
{
MVRangeError(theEnv,start,end,oldseg.range,"direct-slot-replace$");
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
rs--;
re--;
rs += oldseg.begin;
re += oldseg.begin;
dstLen = srcLen - (re - rs + 1); // TBD Refactor
newseg.begin = 0;
newseg.range = dstLen;
newseg.multifieldValue = CreateMultifield(theEnv,dstLen);
/*===================================*/
/* Delete the members from the slot. */
/*===================================*/
if (newval.header->type == MULTIFIELD_TYPE) // TBD Refactor
{ dstLen = srcLen - (re - rs + 1) + newval.range; }
else
{ dstLen = srcLen - (re - rs); }
newseg.begin = 0;
newseg.range = dstLen;
newseg.multifieldValue = CreateMultifield(theEnv,dstLen);
for (i = oldseg.begin, j = 0; i < (oldseg.begin + oldseg.range); i++)
{
if (i == rs)
{
if (newval.header->type == MULTIFIELD_TYPE)
{
for (k = newval.begin; k < (newval.begin + newval.range); k++)
{ newseg.multifieldValue->contents[j++].value = newval.multifieldValue->contents[k].value; }
}
else
{ newseg.multifieldValue->contents[j++].value = newval.value; }
continue;
}
else if ((i > rs) && (i <= re))
{ continue; }
newseg.multifieldValue->contents[j++].value = oldseg.multifieldValue->contents[i].value;
}
if (PutSlotValue(theEnv,ins,sp,&newseg,&newval,"function direct-slot-replace$") == PSE_NO_ERROR)
{ returnValue->lexemeValue = TrueSymbol(theEnv); }
else
{ returnValue->lexemeValue = FalseSymbol(theEnv); }
}
/************************************************************************
NAME : DirectMVInsertCommand
DESCRIPTION : Directly inserts a slot's value
INPUTS : None
RETURNS : True if put OK, false otherwise
SIDE EFFECTS : Slot modified
NOTES : H/L Syntax: (direct-slot-insert$ <slot> <index> <value>)
************************************************************************/
void DirectMVInsertCommand(
Environment *theEnv,
UDFContext *context,
UDFValue *returnValue)
{
InstanceSlot *sp;
Instance *ins;
long long theIndex;
UDFValue newval,newseg,oldseg;
size_t uindex;
if (CheckCurrentMessage(theEnv,"direct-slot-insert$",true) == false)
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
ins = GetActiveInstance(theEnv);
sp = CheckMultifieldSlotModify(theEnv,INSERT,"direct-slot-insert$",ins,
GetFirstArgument(),&theIndex,NULL,&newval);
if (sp == NULL)
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
AssignSlotToDataObject(&oldseg,sp);
if ((((long long) ((size_t) theIndex)) != theIndex) ||
(theIndex < 1))
{
MVRangeError(theEnv,theIndex,theIndex,oldseg.range,"direct-slot-insert$");
return;
}
uindex = (size_t) theIndex;
if (! InsertMultiValueField(theEnv,&newseg,&oldseg,uindex,&newval,"direct-slot-insert$"))
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
if (PutSlotValue(theEnv,ins,sp,&newseg,&newval,"function direct-slot-insert$") == PSE_NO_ERROR)
{ returnValue->lexemeValue = TrueSymbol(theEnv); }
else
{ returnValue->lexemeValue = FalseSymbol(theEnv); }
}
/*****************************************************************
NAME : DirectMVDeleteCommand
DESCRIPTION : Directly deletes a slot's value
INPUTS : None
RETURNS : True if put OK, false otherwise
SIDE EFFECTS : Slot modified
NOTES : H/L Syntax: (direct-slot-delete$ <slot>
<range-begin> <range-end>)
*****************************************************************/
void DirectMVDeleteCommand(
Environment *theEnv,
UDFContext *context,
UDFValue *returnValue)
{
InstanceSlot *sp;
Instance *ins;
size_t rs, re, dstLen, srcLen, i, j;
UDFValue newseg, oldseg;
long long start, end;
if (CheckCurrentMessage(theEnv,"direct-slot-delete$",true) == false)
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
ins = GetActiveInstance(theEnv);
sp = CheckMultifieldSlotModify(theEnv,DELETE_OP,"direct-slot-delete$",ins,
GetFirstArgument(),&start,&end,NULL);
if (sp == NULL)
{
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
AssignSlotToDataObject(&oldseg,sp);
/*===========================================*/
/* Verify the start and end index arguments. */
/*===========================================*/
if ((end < start) || (start < 1) || (end < 1) || // TBD Refactor
(((long long) ((size_t) start)) != start) ||
(((long long) ((size_t) end)) != end))
{
MVRangeError(theEnv,start,end,oldseg.range,"direct-slot-delete$");
returnValue->lexemeValue = FalseSymbol(theEnv);
return;
}
/*============================================*/
/* Convert the indices to unsigned zero-based */
/* values including the begin value. */
/*============================================*/
rs = (size_t) start;
re = (size_t) end;
srcLen = oldseg.range;
if ((rs > srcLen) || (re > srcLen))
{
MVRangeError(theEnv,start,end,oldseg.range,"direct-slot-delete$");
SetEvaluationError(theEnv,true);
SetMultifieldErrorValue(theEnv,returnValue);
return;
}
rs--;
re--;
rs += oldseg.begin;
re += oldseg.begin;
/*=================================================*/
/* Delete the section out of the multifield value. */
/*=================================================*/
dstLen = srcLen - (re - rs + 1); // TBD Refactor
newseg.begin = 0;
newseg.range = dstLen;
newseg.multifieldValue = CreateMultifield(theEnv,dstLen);
for (i = oldseg.begin, j = 0; i < (oldseg.begin + oldseg.range); i++)
{
if ((i >= rs) && (i <= re)) continue;
newseg.multifieldValue->contents[j++].value = oldseg.multifieldValue->contents[i].value;
}
if (PutSlotValue(theEnv,ins,sp,&newseg,&oldseg,"function direct-slot-delete$") == PSE_NO_ERROR)
{ returnValue->lexemeValue = TrueSymbol(theEnv); }
else
{ returnValue->lexemeValue = FalseSymbol(theEnv); }
}
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/**********************************************************************
NAME : CheckMultifieldSlotInstance
DESCRIPTION : Gets the instance for the functions slot-replace$,
insert and delete
INPUTS : The function name
RETURNS : The instance address, NULL on errors
SIDE EFFECTS : None
NOTES : None
**********************************************************************/
static Instance *CheckMultifieldSlotInstance(
UDFContext *context)
{
Instance *ins;
UDFValue temp;
Environment *theEnv = context->environment;
if (! UDFFirstArgument(context,INSTANCE_BITS | SYMBOL_BIT,&temp))
{ return NULL; }
if (temp.header->type == INSTANCE_ADDRESS_TYPE)
{
ins = temp.instanceValue;
if (ins->garbage == 1)
{
StaleInstanceAddress(theEnv,UDFContextFunctionName(context),0);
SetEvaluationError(theEnv,true);
return NULL;
}
}
else
{
ins = FindInstanceBySymbol(theEnv,temp.lexemeValue);
if (ins == NULL)
NoInstanceError(theEnv,temp.lexemeValue->contents,UDFContextFunctionName(context));
}
return ins;
}
/*********************************************************************
NAME : CheckMultifieldSlotModify
DESCRIPTION : For the functions slot-replace$, insert, & delete
as well as direct-slot-replace$, insert, & delete
this function gets the slot, index, and optional
field-value for these functions
INPUTS : 1) A code indicating the type of operation
INSERT (0) : Requires one index
REPLACE (1) : Requires two indices
DELETE_OP (2) : Requires two indices
2) Function name-string
3) Instance address
4) Argument expression chain
5) Caller's buffer for index (or beginning of range)
6) Caller's buffer for end of range
(can be NULL for INSERT)
7) Caller's new-field value buffer
(can be NULL for DELETE_OP)
RETURNS : The address of the instance-slot,
NULL on errors
SIDE EFFECTS : Caller's index buffer set
Caller's new-field value buffer set (if not NULL)
Will allocate an ephemeral segment to store more
than 1 new field value
EvaluationError set on errors
NOTES : Assume the argument chain is at least 2
expressions deep - slot, index, and optional values
*********************************************************************/
static InstanceSlot *CheckMultifieldSlotModify(
Environment *theEnv,
int code,
const char *func,
Instance *ins,
Expression *args,
long long *rb,
long long *re,
UDFValue *newval)
{
UDFValue temp;
InstanceSlot *sp;
unsigned int start;
start = (args == GetFirstArgument()) ? 1 : 2;
EvaluationData(theEnv)->EvaluationError = false;
EvaluateExpression(theEnv,args,&temp);
if (temp.header->type != SYMBOL_TYPE)
{
ExpectedTypeError1(theEnv,func,start,"symbol");
SetEvaluationError(theEnv,true);
return NULL;
}
sp = FindInstanceSlot(theEnv,ins,temp.lexemeValue);
if (sp == NULL)
{
SlotExistError(theEnv,temp.lexemeValue->contents,func);
return NULL;
}
if (sp->desc->multiple == 0)
{
PrintErrorID(theEnv,"INSMULT",1,false);
WriteString(theEnv,STDERR,"Function ");
WriteString(theEnv,STDERR,func);
WriteString(theEnv,STDERR," cannot be used on single-field slot '");
WriteString(theEnv,STDERR,sp->desc->slotName->name->contents);
WriteString(theEnv,STDERR,"' in instance [");
WriteString(theEnv,STDERR,ins->name->contents);
WriteString(theEnv,STDERR,"].\n");
SetEvaluationError(theEnv,true);
return NULL;
}
EvaluateExpression(theEnv,args->nextArg,&temp);
if (temp.header->type != INTEGER_TYPE)
{
ExpectedTypeError1(theEnv,func,start+1,"integer");
SetEvaluationError(theEnv,true);
return NULL;
}
args = args->nextArg->nextArg;
*rb = temp.integerValue->contents;
if ((code == REPLACE) || (code == DELETE_OP))
{
EvaluateExpression(theEnv,args,&temp);
if (temp.header->type != INTEGER_TYPE)
{
ExpectedTypeError1(theEnv,func,start+2,"integer");
SetEvaluationError(theEnv,true);
return NULL;
}
*re = temp.integerValue->contents;
args = args->nextArg;
}
if ((code == INSERT) || (code == REPLACE))
{
if (EvaluateAndStoreInDataObject(theEnv,1,args,newval,true) == false)
return NULL;
}
return(sp);
}
/***************************************************
NAME : AssignSlotToDataObject
DESCRIPTION : Assigns the value of a multifield
slot to a data object
INPUTS : 1) The data object buffer
2) The instance slot
RETURNS : Nothing useful
SIDE EFFECTS : Data object fields set
NOTES : Assumes slot is a multislot
***************************************************/
static void AssignSlotToDataObject(
UDFValue *theDataObject,
InstanceSlot *theSlot)
{
theDataObject->value = theSlot->value;
theDataObject->begin = 0;
theDataObject->range = theSlot->multifieldValue->length;
}
#endif
| 35.356522 | 120 | 0.500176 | [
"object"
] |
ea11b439608727514bc9c9103ede8481017d0192 | 634 | h | C | include/il2cpp/System/Func_char__bool_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/System/Func_char__bool_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/System/Func_char__bool_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void System_Func_char__bool____ctor (System_Func_char__bool__o* __this, Il2CppObject* object, intptr_t method, const MethodInfo* method_info);
bool System_Func_char__bool___Invoke (System_Func_char__bool__o* __this, uint16_t arg, const MethodInfo* method_info);
System_IAsyncResult_o* System_Func_char__bool___BeginInvoke (System_Func_char__bool__o* __this, uint16_t arg, System_AsyncCallback_o* callback, Il2CppObject* object, const MethodInfo* method_info);
bool System_Func_char__bool___EndInvoke (System_Func_char__bool__o* __this, System_IAsyncResult_o* result, const MethodInfo* method_info);
| 70.444444 | 197 | 0.859621 | [
"object"
] |
ea161c9959fd1f9980e700ce33caa9931a798037 | 1,194 | h | C | k2/python/csrc/torch/v2/doc/doc.h | drawfish/k2 | acdbb2aeb2bb5edb83fec7e2eb4d4b2c35fd9021 | [
"Apache-2.0"
] | 491 | 2020-09-17T09:05:05.000Z | 2022-03-31T13:38:18.000Z | k2/python/csrc/torch/v2/doc/doc.h | drawfish/k2 | acdbb2aeb2bb5edb83fec7e2eb4d4b2c35fd9021 | [
"Apache-2.0"
] | 600 | 2020-09-17T13:55:06.000Z | 2022-03-30T23:23:40.000Z | k2/python/csrc/torch/v2/doc/doc.h | drawfish/k2 | acdbb2aeb2bb5edb83fec7e2eb4d4b2c35fd9021 | [
"Apache-2.0"
] | 121 | 2020-09-17T15:44:56.000Z | 2022-03-23T13:22:52.000Z | /**
* @copyright
* Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
*
* @copyright
* See LICENSE 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
*
* 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 K2_PYTHON_CSRC_TORCH_V2_DOC_DOC_H_
#define K2_PYTHON_CSRC_TORCH_V2_DOC_DOC_H_
#include "k2/python/csrc/torch.h"
namespace k2 {
/* Set the documentation of a method inside a class.
@param cls The class whose method's doc we are going to set
@param name The name of the method
@param doc The doc string to set.
*/
void SetMethodDoc(py::object *cls, const char *name, const char *doc);
} // namespace k2
#endif // K2_PYTHON_CSRC_TORCH_V2_DOC_DOC_H_
| 31.421053 | 75 | 0.738693 | [
"object"
] |
ea1f55fcf51a2aa0d674401236e3c72510837210 | 866 | h | C | Runtime/include/e4rt/code_mgr.h | kvakvs/E4VM | 2eac924efad972cfd488f1ad75e2f055cd18bd14 | [
"BSD-3-Clause"
] | 132 | 2017-01-28T16:51:47.000Z | 2021-11-13T10:55:49.000Z | Runtime/include/e4rt/code_mgr.h | kvakvs/E4VM | 2eac924efad972cfd488f1ad75e2f055cd18bd14 | [
"BSD-3-Clause"
] | null | null | null | Runtime/include/e4rt/code_mgr.h | kvakvs/E4VM | 2eac924efad972cfd488f1ad75e2f055cd18bd14 | [
"BSD-3-Clause"
] | 10 | 2017-03-31T22:54:12.000Z | 2021-10-01T17:41:14.000Z | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//
#pragma once
#include "e4platf/conf.h"
#include "e4platf/types.h"
#include "e4rt/module.h"
#include "e4rt/term.h"
#include "e4rt/term_as_map_key.h"
namespace e4 {
class VM;
class CodeManager {
private:
HashMap<Term, UniquePtr<Module>> mods_;
Vector<String> paths_; // Code search paths, starting with "."
public:
explicit CodeManager(): mods_() {
// TODO: load preloaded modules
paths_.push_back(String("."));
}
Term load(Term name);
void register_module(UniquePtr<Module>&& m);
Module* find_module(Term name) const;
void path_add(const String& p) {
paths_.push_back(p);
}
#if E4DEBUG
void debug_print();
#else
void debug_print() {}
#endif
};
} // ns e4
| 18.425532 | 83 | 0.682448 | [
"vector"
] |
ea2169f7bcc001d20d9b3f8138057dce50234849 | 6,239 | h | C | zircon/kernel/include/platform/crashlog.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | zircon/kernel/include/platform/crashlog.h | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | zircon/kernel/include/platform/crashlog.h | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2020 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#ifndef ZIRCON_KERNEL_INCLUDE_PLATFORM_CRASHLOG_H_
#define ZIRCON_KERNEL_INCLUDE_PLATFORM_CRASHLOG_H_
#include <stdio.h>
#include <sys/types.h>
#include <zircon/boot/crash-reason.h>
#include <zircon/compiler.h>
#include <zircon/types.h>
#include <ktl/atomic.h>
#include <ktl/span.h>
class PlatformCrashlog {
public:
// This is common interface definition for specific implementations of crashlog support.
// Depending on the platform, and the resources provided to it, users will end up with
//
// 1) A RAM mappable crashlog implementation, where the crashlog RAM is mapped
// directly accessible by the CPUs from a mapped virtual address.
// 2) An EFI capsule based implementation, where crashlogs get stored in an
// EFI capsule during a non-spontaneous crash.
// 3) A trivial, no-op implementation, because the kernel was not provided any
// way to store data which could survive a reboot.
//
// Generally speaking, the underlying implementation are not multi-thread
// safe, and users should take care to never do something like having multiple
// threads calling into Finalize at the same time.
class Interface {
public:
// Returns a span which points to the region which the kernel should render
// a crashlog payload to during a non-spontaneous crash.
virtual ktl::span<char> GetRenderTarget() = 0;
// Finalize a crashlog just before triggering a reboot. |reason| is the SW
// reboot reason which will be stored in the crashlog header, while |amt| is
// the amount of the render target (see |GetRenderTarget|) which was filled
// before calling finalize.
virtual void Finalize(zircon_crash_reason_t reason, size_t amt) = 0;
// Attempt to recover any crashlog from platform specific storage, writing
// the results to |tgt|. Returns the number of bytes written to |tgt| in
// the process. Users may pass nullptr to |tgt| if they wish to simply
// measure the size of the crashlog to be recovered.
virtual size_t Recover(FILE* tgt) = 0;
// Enable periodic updates of the uptime estimate in the crashlog header.
// This allows systems with directly mappable crashlog RAM to constantly be
// stashing a valid header with an uptime estimate and a reboot reason of
// "UNKNOWN" to be recovered in the case of a spontaneous reboot.
virtual void EnableCrashlogUptimeUpdates(bool enabled) = 0;
protected:
// No one should ever be destroying an implementation of the crashlog
// interface from an Interface* pointer. Bury the destructor as a
// protected, non-virtual destructor to prevent anyone from ever
// accidentally attempting to do so.
~Interface() = default;
};
// Interface management.
//
// By default, there is always a Crashlog implementation available, and a
// reference to it can be fetched using the |Get| method. At boot, however,
// this will be a default trivial implementation which does nothing. The
// system may switch away from this interface when it discovers usable
// non-volatile storage by calling |Bind|, and passing a reference to a
// specific Crashlog implementation. Note that this implementation must stay
// alive for the entire life of the kernel. Once bound to a non-trivial
// implementation, the interface can no longer be rebound, and any attempts to
// do so will return an error.
//
// Code may check to see if a non-trivial implementation has been bound by
// calling |HasNonTrivialImpl|.
static Interface& Get() { return *(interface_.load(ktl::memory_order_acquire)); }
static bool HasNonTrivialImpl() {
return interface_.load(ktl::memory_order_acquire) != &trivial_impl_;
}
static zx_status_t Bind(Interface& impl) {
Interface* expected = &trivial_impl_;
return interface_.compare_exchange_strong(expected, &impl, ktl::memory_order_acq_rel)
? ZX_OK
: ZX_ERR_ALREADY_BOUND;
}
private:
class TrivialImpl : public Interface {
public:
constexpr TrivialImpl() = default;
~TrivialImpl() = default;
ktl::span<char> GetRenderTarget() final { return {}; }
void Finalize(zircon_crash_reason_t reason, size_t amt) final {}
size_t Recover(FILE* tgt) final { return 0; }
void EnableCrashlogUptimeUpdates(bool enabled) final {}
};
// No one should be creating or destroying any PlatformCrashlog instances.
// Everything should be going through a PlatformCrashlog::Interface instead.
PlatformCrashlog() = default;
~PlatformCrashlog() = default;
// The singleton interface. This can be set to a non-trivial implementation
// only once via Bind.
static inline TrivialImpl trivial_impl_;
static inline ktl::atomic<Interface*> interface_{&trivial_impl_};
};
void platform_set_ram_crashlog_location(paddr_t phys, size_t len);
bool platform_has_ram_crashlog();
/* Stash the crashlog somewhere platform-specific that allows
* for recovery after reboot. This will only be called out
* of the panic() handling path on the way to reboot, and is
* not necessarily safe to be called from any other state.
*
* Calling with a NULL log returns the maximum supported size.
* It is safe to query the size at any time after boot. If the
* return is 0, no crashlog recovery is supported.
*/
extern void (*platform_stow_crashlog)(zircon_crash_reason_t reason, const void* log, size_t len);
/* Recover the crashlog, fprintf'ing its contents into the FILE |tgt|
* provided by the caller, then return the length of the recovered
* crashlog.
*
* It is safe to call this function more than once. Users may compute
* the length of the crashlog without rendering it by passing nullptr
* for |tgt|. The length of the rendered log is guaranteed to stay
* constant between calls.
*
*/
extern size_t (*platform_recover_crashlog)(FILE* tgt);
/* Either enable or disable periodic updates of the crashlog uptime. */
extern void (*platform_enable_crashlog_uptime_updates)(bool enabled);
#endif // ZIRCON_KERNEL_INCLUDE_PLATFORM_CRASHLOG_H_
| 42.732877 | 97 | 0.736977 | [
"render"
] |
ea26a550badffd35200f23c73cc1399434187348 | 1,798 | h | C | Chapter 14/Student_info.h | altugbakan/accelerated-cpp-solutions | 0087c12cf853c143a301c44eeedd041a0dc7ecfc | [
"MIT"
] | 4 | 2021-10-29T18:45:48.000Z | 2022-02-08T16:12:45.000Z | Chapter 14/Student_info.h | altugbakan/accelerated-cpp-solutions | 0087c12cf853c143a301c44eeedd041a0dc7ecfc | [
"MIT"
] | null | null | null | Chapter 14/Student_info.h | altugbakan/accelerated-cpp-solutions | 0087c12cf853c143a301c44eeedd041a0dc7ecfc | [
"MIT"
] | 1 | 2021-12-21T21:46:49.000Z | 2021-12-21T21:46:49.000Z | #ifndef GUARD_Student_info
#define GUARD_Student_info
#include <iostream>
#include <vector>
#include <string>
#include "Ptr.h"
class Core {
friend class Student_info;
public:
Core(): midterm(0), final(0) { }
Core(std::istream& is) { read(is); }
virtual ~Core() { }
std::string name() const;
virtual double grade() const;
virtual std::istream& read(std::istream&);
protected:
std::istream& read_common(std::istream&);
double midterm, final;
std::vector<double> homework;
virtual Core* clone() const { return new Core(*this); }
private:
std::string n;
};
class Grad: public Core {
public:
Grad(): thesis(0) { }
Grad(std::istream& is) { read(is); }
double grade() const;
std::istream& read(std::istream&);
protected:
Grad* clone() const { return new Grad(*this); }
private:
double thesis;
};
class Student_info {
public:
// constructors and copy control
Student_info(): cp(0) { }
Student_info(std::istream& is): cp(0) { read(is); }
// operations
std::istream& read(std::istream&);
// code is taken from §13.4/243
std::string name() const {
if (cp) return cp->name();
else throw std::runtime_error("uninitialized Student");
}
// code is taken from §13.4/243
double grade() const {
if (cp) return cp->grade();
else throw std::runtime_error("uninitialized Student");
}
// code is taken from §13.4/244
static bool compare(const Student_info& s1,
const Student_info& s2) {
return s1.name() < s2.name();
}
private:
Ptr<Core> cp; // Q3
};
std::istream& read_hw(std::istream&, std::vector<double>&);
bool compare(const Core&, const Core&);
bool compare_grades(const Core& c1, const Core& c2);
#endif | 24.630137 | 63 | 0.618465 | [
"vector"
] |
ea3190cd8fef0a5706d28305b2b62162d8c36900 | 4,029 | h | C | ll/include/liblilfes/lregex.h | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 48 | 2016-10-11T06:07:02.000Z | 2022-03-02T16:26:25.000Z | ll/include/liblilfes/lregex.h | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 7 | 2017-02-13T09:14:34.000Z | 2019-01-18T06:06:29.000Z | ll/include/liblilfes/lregex.h | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 18 | 2016-11-13T23:14:28.000Z | 2022-01-12T15:21:44.000Z | /* $Id: lregex.h,v 1.4 2011-05-02 08:48:59 matuzaki Exp $
*
* Copyright (c) 2000, Yusuke Miyao
*
* You may distribute this file under the terms of the Artistic License.
*/
#ifndef lregex_h_
#define lregex_h_
#ifdef WITH_REGEX
#if LILFES_WIN_
#include <boost/cregex.hpp>
using namespace boost;
#else
#include <regex.h>
#endif
#include <map>
#include <string>
#include <vector>
namespace lilfes {
class machine;
class FSP;
//////////////////////////////////////////////////////////////////////
class LiLFeSRegExError {
private:
std::string error_message;
static const int ERRBUF_SIZE;
static char errbuf[];
public:
LiLFeSRegExError( const std::string& m ) {
error_message = m;
}
LiLFeSRegExError( const char* s ) {
error_message = s;
}
LiLFeSRegExError( int c, const regex_t* preg ) {
regerror( c, preg, errbuf, ERRBUF_SIZE );
error_message = errbuf;
}
~LiLFeSRegExError() {}
const std::string& message( void ) const {
return error_message;
}
};
//////////////////////////////////////////////////////////////////////
class LiLFeSRegEx {
private:
// regex_t* preg;
const regex_t* preg;
std::vector< std::string > substrs;
std::string regex;
std::string target;
int cflags, eflags;
bool global;
static const int DEFAULT_CFLAGS = REG_EXTENDED;
static const int DEFAULT_EFLAGS = 0;
struct Key {
// const std::string& regex;
const std::string regex;
int cflags;
Key( const std::string& r, int c );
bool operator<( const Key& k ) const {
// return ( regex < k.regex ) && ( cflags < k.cflags );
return (regex < k.regex) || ((regex == k.regex) && (cflags < k.cflags));
}
};
static std::map< Key, regex_t > regex_hash;
int compile_internal( void );
public:
enum {
ICASE = 1,
NOSUB = 2,
NEWLINE = 4,
NOTBOL = 8,
NOTEOL = 16
};
LiLFeSRegEx( void );
LiLFeSRegEx( const std::string& r );
LiLFeSRegEx( const std::string& r, int f );
virtual ~LiLFeSRegEx();
void setRegEx( const std::string& r );
void addFlags( int c );
void addFlags( FSP arg );
void compile( void );
bool match( const std::string& str );
bool exec( const std::string& str );
bool subst( const std::string& str, const std::string& substs );
size_t numSubstr( void ) const;
const std::string& getSubstr( int i ) const;
std::string getSubstr( int i );
const std::string& getTarget( void ) const;
std::string getTarget( void );
};
inline LiLFeSRegEx::Key::Key( const std::string& r, int c ) : regex( r ) {
cflags = c;
}
inline LiLFeSRegEx::LiLFeSRegEx( void ) {
preg = NULL;
cflags = DEFAULT_CFLAGS;
eflags = DEFAULT_EFLAGS;
global = false;
}
inline LiLFeSRegEx::LiLFeSRegEx( const std::string& r ) {
preg = NULL;
regex = r;
cflags = DEFAULT_CFLAGS;
eflags = DEFAULT_EFLAGS;
global = false;
}
inline LiLFeSRegEx::LiLFeSRegEx( const std::string& r, int f ) {
preg = NULL;
regex = r;
cflags = DEFAULT_CFLAGS;
eflags = DEFAULT_EFLAGS;
global = false;
addFlags( f );
}
inline LiLFeSRegEx::~LiLFeSRegEx() {
// if ( preg != NULL ) {
// regfree( preg );
// delete preg;
// }
}
inline void LiLFeSRegEx::setRegEx( const std::string& r ) {
regex = r;
}
inline size_t LiLFeSRegEx::numSubstr( void ) const {
return substrs.size();
}
inline const std::string& LiLFeSRegEx::getSubstr( int i ) const {
return substrs[ i ];
}
inline std::string LiLFeSRegEx::getSubstr( int i ) {
return substrs[ i ];
}
inline const std::string& LiLFeSRegEx::getTarget( void ) const {
return target;
}
inline std::string LiLFeSRegEx::getTarget( void ) {
return target;
}
namespace builtin {
bool regex_match( machine&, FSP, FSP );
bool regex_match_3( machine&, FSP, FSP, FSP );
bool regex_match_4( machine&, FSP, FSP, FSP, FSP );
bool regex_subst( machine&, FSP, FSP, FSP, FSP );
bool regex_subst_5( machine&, FSP, FSP, FSP, FSP, FSP );
} // namespace builtin
} // namespace lilfes
#endif // WITH_REGEX
#endif // lregex_h_
// end of lregex.h
| 21.66129 | 75 | 0.629685 | [
"vector"
] |
ea32247bb1300879f05e88eef00f802713df3472 | 18,272 | c | C | src/f_picobj.c | Masrik-Dahir/xfigx-3.1.1 | 40ec5d16e2f7ec4a3e84940fbf6a96c7b1890645 | [
"MIT"
] | null | null | null | src/f_picobj.c | Masrik-Dahir/xfigx-3.1.1 | 40ec5d16e2f7ec4a3e84940fbf6a96c7b1890645 | [
"MIT"
] | null | null | null | src/f_picobj.c | Masrik-Dahir/xfigx-3.1.1 | 40ec5d16e2f7ec4a3e84940fbf6a96c7b1890645 | [
"MIT"
] | null | null | null | /*
* FIG : Facility for Interactive Generation of figures
* Copyright (c) 1985-1988 by Supoj Sutanthavibul
* Parts Copyright (c) 1989-2015 by Brian V. Smith
* Parts Copyright (c) 1991 by Paul King
* Parts Copyright (c) 2016-2020 by Thomas Loimer
*
* Copyright (c) 1992 by Brian Boyter
*
* Any party obtaining a copy of these files is granted, free of charge, a
* full and unrestricted irrevocable, world-wide, paid up, royalty-free,
* nonexclusive right and license to deal in this software and documentation
* files (the "Software"), including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense and/or sell copies of
* the Software, and to permit persons who receive copies from any such
* party to do so, with the only requirement being that the above copyright
* and this permission notice remain intact.
*
*/
/* GS bitmap generation added: 13 Nov 1992, by Michael C. Grant
* (mcgrant@rascals.stanford.edu) adapted from Marc Goldburg's
* (marcg@rascals.stanford.edu) original idea and code. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "f_picobj.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h> /* time_t */
#include <X11/Intrinsic.h> /* includes X11/Xlib.h, which includes X11/X.h */
#include "resources.h" /* TMPDIR */
#include "object.h"
#include "f_readpcx.h" /* read_pcx() */
#include "f_util.h" /* file_timestamp() */
#include "u_create.h" /* create_picture_entry() */
#include "w_file.h" /* check_cancel() */
#include "w_msgpanel.h"
#include "w_setup.h" /* PIX_PER_INCH, PIX_PER_CM */
#include "w_util.h" /* app_flush() */
extern int read_gif(F_pic *pic, struct xfig_stream *restrict pic_stream);
extern int read_eps(F_pic *pic, struct xfig_stream *restrict pic_stream);
extern int read_pdf(F_pic *pic, struct xfig_stream *restrict pic_stream);
extern int read_ppm(F_pic *pic, struct xfig_stream *restrict pic_stream);
#ifdef HAVE_TIFF
extern int read_tif(F_pic *pic, struct xfig_stream *restrict pic_stream);
#endif
extern int read_xbm(F_pic *pic, struct xfig_stream *restrict pic_stream);
#ifdef HAVE_JPEG
extern int read_jpg(F_pic *pic, struct xfig_stream *restrict pic_stream);
#endif
#ifdef HAVE_PNG
extern int read_png(F_pic *pic, struct xfig_stream *restrict pic_stream);
#endif
#ifdef USE_XPM
extern int read_xpm(F_pic *pic, struct xfig_stream *restrict pic_stream);
#endif
static struct _haeders {
char *type;
char *bytes;
int (*readfunc)();
} headers[] = {
{"GIF", "GIF", read_gif},
{"PCX", "\012\005\001", read_pcx},
{"EPS", "%!", read_eps},
{"PDF", "%PDF", read_pdf},
{"PPM", "P3", read_ppm},
{"PPM", "P6", read_ppm},
#ifdef HAVE_TIFF
{"TIFF", "II*\000", read_tif},
{"TIFF", "MM\000*", read_tif},
#endif
{"XBM", "#define", read_xbm},
#ifdef HAVE_JPEG
{"JPEG", "\377\330\377\340", read_jpg},
{"JPEG", "\377\330\377\341", read_jpg},
#endif
#ifdef HAVE_PNG
{"PNG", "\211\120\116\107\015\012\032\012", read_png},
#endif
#ifdef USE_XPM
{"XPM", "/* XPM */", read_xpm},
#endif
};
static void
init_stream(struct xfig_stream *restrict xf_stream)
{
xf_stream->fp = NULL;
xf_stream->name = xf_stream->name_buf;
xf_stream->name_on_disk = xf_stream->name_on_disk_buf;
xf_stream->uncompress = NULL;
xf_stream->content = xf_stream->content_buf;
*xf_stream->content = '\0';
}
void
free_stream(struct xfig_stream *restrict xf_stream)
{
if (xf_stream->content != xf_stream->name_on_disk) {
if (*xf_stream->content && unlink(xf_stream->content)) {
int err = errno;
file_msg("Cannot remove temporary file %s\nError: %s",
xf_stream->content, strerror(err));
}
if (xf_stream->content != xf_stream->content_buf)
free(xf_stream->content);
}
if (xf_stream->name != xf_stream->name_buf)
free(xf_stream->name);
if (xf_stream->name_on_disk != xf_stream->name_on_disk_buf)
free(xf_stream->name_on_disk);
}
/*
* Given name, search and return the name of the corresponding file on disk in
* found. This may be "name", or "name" with a compression suffix appended,
* e.g., "name.gz". If the file must be uncompressed, return the compression
* command in a static string pointed to by "uncompress", otherwise let
* "uncompress" point to the empty string. If the size of the character buffer
* provided in found is too small to accomodate the string, return a pointer to
* a malloc()'ed string.
* Return 0 on success, or FileInvalid if the file is not found.
* Usage:
* char found_buf[len];
* char *found = found_buf;
* file_on_disk(name, &found, sizeof found_buf, &uncompress);
* ...
* if (found != found_buf)
* free(found);
*/
static int
file_on_disk(char *restrict name, char *restrict *found, size_t len,
const char *restrict *uncompress)
{
int i;
size_t name_len;
char *suffix;
struct stat status;
static const char empty[] = "";
static const char *filetypes[][2] = {
/* sorted by popularity? */
#define FILEONDISK_ADD 5 /* must be max(strlen(filetypes[0][])) + 1 */
{ ".gz", "gunzip -c" },
{ ".Z", "gunzip -c" },
{ ".z", "gunzip -c" },
{ ".zip", "unzip -p" },
{ ".bz2", "bunzip2 -c" },
{ ".bz", "bunzip2 -c" },
{ ".xz", "unxz -c" }
};
const int filetypes_len =
(int)(sizeof filetypes / sizeof(filetypes[1]));
name_len = strlen(name);
if (name_len >= len &&
(*found = malloc(name_len + FILEONDISK_ADD)) == NULL) {
file_msg("Out of memory.");
return FileInvalid;
}
strcpy(*found, name);
/*
* Possibilities, e.g.,
* name name on disk uncompress
* img.ppm img.ppm ""
* img.ppm img.ppm.gz gunzip -c
* img.ppm.gz img.ppm.gz gunzip -c
* img.ppm.gz img.ppm ""
*/
if (stat(name, &status)) {
/* File not found. Now try, whether a file with one of
the known suffices appended exists. */
if (len < name_len + FILEONDISK_ADD && (*found =
malloc(name_len + FILEONDISK_ADD)) == NULL) {
file_msg("Out of memory.");
return FileInvalid;
}
suffix = *found + name_len;
for (i = 0; i < filetypes_len; ++i) {
strcpy(suffix, filetypes[i][0]);
if (!stat(*found, &status)) {
*uncompress = filetypes[i][1];
break;
}
}
/* Not found. Check, whether the file has one of the known
compression suffices, but the uncompressed file
exists on disk. */
*suffix = '\0';
if (i == filetypes_len && (suffix = strrchr(name, '.'))) {
for (i = 0; i < filetypes_len; ++i) {
if (!strcmp(suffix, filetypes[i][0])) {
*(*found + (suffix - name)) = '\0';
if (!stat(*found, &status)) {
*uncompress = empty;
break;
} else {
*found[0] = '\0';
i = filetypes_len;
}
}
}
}
if (i == filetypes_len) {
/* not found */
*found[0] = '\0';
return FileInvalid;
}
} else {
/* File exists. Check, whether the name has one of the known
compression suffices. */
if ((suffix = strrchr(name, '.'))) {
for (i = 0; i < filetypes_len; ++i) {
if (!strcmp(suffix, filetypes[i][0])) {
*uncompress = filetypes[i][1];
break;
}
}
} else {
i = filetypes_len;
}
if (i == filetypes_len)
*uncompress = empty;
}
return 0;
}
/*
* Compare the picture information in pic with "file". If the file on disk
* is newer than the picture information, set "reread" to true.
* If a cached picture bitmap already exists, set "existing" to true.
* Return FileInvalid, if "file" is not found, otherwise return 0.
*/
static int
get_picture_status(F_pic *pic, struct _pics *pics, char *file, bool force,
bool *reread, bool *existing)
{
char found_buf[256];
char *found = found_buf;
const char *uncompress;
time_t mtime;
/* get the name of the file on disk */
if (file_on_disk(pics->file, &found, sizeof found_buf, &uncompress)) {
if (found != found_buf)
free(found);
return FileInvalid;
}
/* check the timestamp */
mtime = file_timestamp(found);
if (found != found_buf)
free(found);
if (mtime < 0) {
/* oops, doesn't exist? */
file_msg("Error %s on %s", strerror(errno), file);
return FileInvalid;
}
if (force || mtime > pics->time_stamp) {
if (appres.DEBUG && mtime > pics->time_stamp)
fprintf(stderr, "Timestamp changed, reread file %s\n",
file);
*reread = true;
return 0;
}
pic->pic_cache = pics;
pics->refcount++;
if (appres.DEBUG)
fprintf(stderr, "Found stored picture %s, count=%d\n", file,
pics->refcount);
/* there is a cached bitmap */
if (pics->bitmap != NULL) {
*existing = true;
*reread = false;
put_msg("Reading Picture object file...found cached picture");
} else {
*existing = false;
*reread = true;
if (appres.DEBUG)
fprintf(stderr, "Re-reading file %s\n", file);
}
return 0;
}
/*
* Check through the pictures repository to see if "file" is already there.
* If so, set the pic->pic_cache pointer to that repository entry and set
* "existing" to True.
* If not, read the file via the relevant reader and add to the repository
* and set "existing" to False.
* If "force" is true, read the file unconditionally.
*/
void
read_picobj(F_pic *pic, char *file, int color, Boolean force, Boolean *existing)
{
FILE *fp;
int i;
char buf[16];
bool reread;
struct _pics *pics, *lastpic;
struct xfig_stream pic_stream;
pic->color = color;
/* don't touch the flipped flag - caller has already set it */
pic->pixmap = (Pixmap)0;
pic->hw_ratio = 0.0;
pic->pix_rotation = 0;
pic->pix_width = 0;
pic->pix_height = 0;
pic->pix_flipped = 0;
/* check if user pressed cancel button */
if (check_cancel())
return;
put_msg("Reading Picture object file...");
app_flush();
/* look in the repository for this filename */
lastpic = pictures;
for (pics = pictures; pics; pics = pics->next) {
if (strcmp(pics->file, file) == 0) {
/* check, whether picture exists, or must be re-read */
if (get_picture_status(pic, pics, file, force, &reread,
(bool *)existing) ==FileInvalid)
return;
if (!reread && *existing) {
/* must set the h/w ratio here */
pic->hw_ratio =(float)pic->pic_cache->bit_size.y
/ pic->pic_cache->bit_size.x;
return;
}
break;
}
/* keep pointer to last entry */
lastpic = pics;
}
if (pics == NULL) {
/* didn't find it in the repository, add it */
pics = create_picture_entry();
if (lastpic) {
/* add to list */
lastpic->next = pics;
pics->prev = lastpic;
} else {
/* first one */
pictures = pics;
}
pics->file = strdup(file);
pics->refcount = 1;
pics->bitmap = NULL;
pics->subtype = T_PIC_NONE;
pics->numcols = 0;
pics->size_x = 0;
pics->size_y = 0;
pics->bit_size.x = 0;
pics->bit_size.y = 0;
if (appres.DEBUG)
fprintf(stderr, "New picture %s\n", file);
}
/* put it in the pic */
pic->pic_cache = pics;
pic->pixmap = (Pixmap)0;
if (appres.DEBUG)
fprintf(stderr, "Reading file %s\n", file);
init_stream(&pic_stream);
/* open the file and read a few bytes of the header to see what it is */
if ((fp = open_stream(file, &pic_stream)) == NULL) {
file_msg("No such picture file: %s", file);
free_stream(&pic_stream);
return;
}
/* get the modified time and save it */
pics->time_stamp = file_timestamp(pic_stream.name_on_disk);
/* read some bytes from the file */
for (i = 0; i < (int)sizeof buf; ++i) {
int c;
if ((c = getc(fp)) == EOF)
break;
buf[i] = (char)c;
}
/* now find which header it is */
for (i = 0; i < (int)(sizeof headers / sizeof(headers[0])); ++i)
if (!memcmp(buf, headers[i].bytes, strlen(headers[i].bytes)))
break;
/* not found */
if (i == (int)(sizeof headers / sizeof(headers[0]))) {
file_msg("%s: Unknown image format", file);
put_msg("Reading Picture object file...Failed");
app_flush();
close_stream(&pic_stream);
free_stream(&pic_stream);
return;
}
/* readfunc() expect an open file stream, positioned not at the
start of the stream. The stream remains open after returning. */
if (headers[i].readfunc(pic, &pic_stream) != PicSuccess) {
file_msg("%s: Bad %s format", file, headers[i].type);
} else {
put_msg("Reading Picture object file...Done");
}
close_stream(&pic_stream);
free_stream(&pic_stream);
}
/*
* Return a file stream, either to a pipe or to a regular file.
* If xf_stream->uncompress[0] == '\0', it is a regular file, otherwise a pipe.
*/
FILE *
open_stream(char *restrict name, struct xfig_stream *restrict xf_stream)
{
size_t len;
if (xf_stream->name != name) {
/* strcpy (xf_stream->name, name) */
len = strlen(name);
if (len >= sizeof xf_stream->name_buf) {
if ((xf_stream->name = malloc(len + 1)) == NULL) {
file_msg("Out of memory.");
return NULL;
}
}
memcpy(xf_stream->name, name, len + 1);
}
if (file_on_disk(name, &xf_stream->name_on_disk,
sizeof xf_stream->name_on_disk_buf,
&xf_stream->uncompress)) {
free_stream(xf_stream);
return NULL;
}
if (*xf_stream->uncompress) {
/* a compressed file */
char command_buf[256];
char *command = command_buf;
len = strlen(xf_stream->name_on_disk) +
strlen(xf_stream->uncompress) + 2;
if (len > sizeof command_buf) {
if ((command = malloc(len)) == NULL) {
file_msg("Out of memory.");
return NULL;
}
}
sprintf(command, "%s '%s'",
xf_stream->uncompress, xf_stream->name_on_disk);
xf_stream->fp = popen(command, "r");
if (command != command_buf)
free(command);
} else {
/* uncompressed file */
xf_stream->fp = fopen(xf_stream->name_on_disk, "rb");
}
return xf_stream->fp;
}
/*
* Close a file stream opened by open_file(). Do not free xf_stream.
*/
int
close_stream(struct xfig_stream *restrict xf_stream)
{
if (xf_stream->fp == NULL)
return -1;
if (xf_stream->uncompress[0] == '\0') {
/* a regular file */
return fclose(xf_stream->fp);
} else {
/* a pipe */
char trash[BUFSIZ];
/* for a pipe, must read everything or
we'll get a broken pipe message */
while (fread(trash, (size_t)1, (size_t)BUFSIZ, xf_stream->fp) ==
(size_t)BUFSIZ)
;
return pclose(xf_stream->fp);
}
}
FILE *
rewind_stream(struct xfig_stream *restrict xf_stream)
{
if (xf_stream->fp == NULL)
return NULL;
if (xf_stream->uncompress[0] == '\0') {
/* a regular file */
rewind(xf_stream->fp);
return xf_stream->fp;
} else {
/* a pipe */
(void)close_stream(xf_stream);
/* if, in the meantime, e.g., the file on disk
was uncompressed, change the filetype. */
return open_stream(xf_stream->name, xf_stream);
}
}
/*
* Have xf_stream->content either point to a regular file containing the
* uncompressed content of xf_stream->name, or to xf_stream->name_on_disk, if
* name_on_disk is not compressed.
* Use after a call to open_stream():
* struct xfig_stream xf_stream;
* open_stream(name, &xf_stream);
* close_stream(&xf_stream);
* uncompressed_content(&xf_stream)
* do_something(xf_stream->content);
* free_stream(&xf_stream);
*/
int
uncompressed_content(struct xfig_stream *restrict xf_stream)
{
int ret = -1;
int fd;
int len;
char command_buf[256];
char *command = command_buf;
char *const command_fmt = "%s '%s' 1>&%d";
char *const content_fmt = "%s/xfigXXXXXX";
if (*xf_stream->uncompress == '\0') {
xf_stream->content = xf_stream->name_on_disk;
return 0;
}
/* uncompress to a temporary file */
len = snprintf(xf_stream->content, sizeof xf_stream->content_buf,
content_fmt, TMPDIR);
if (len >= (int)(sizeof xf_stream->content_buf)) {
if ((xf_stream->content = malloc(len + 1)) == NULL) {
file_msg("Out of memory.");
return ret;
}
len = sprintf(xf_stream->content, content_fmt, TMPDIR);
}
if (len < 0) {
len = errno;
file_msg("Unable to write temporary file path to string.");
file_msg("Error: %s", strerror(len));
return ret;
}
if ((fd = mkstemp(xf_stream->content)) == -1) {
fd = errno;
file_msg("Could not open temporary file %s, error: %s",
xf_stream->content, strerror(fd));
return ret;
}
/*
* One could already here redirect stdout to the fd of our tmp
* file - but then, how to re-open stdout?
* close(1);
* dup(fd); * takes the lowest integer found, now 1 *
* close(fd);
*/
len = snprintf(command, sizeof command_buf, command_fmt,
xf_stream->uncompress, xf_stream->name_on_disk, fd);
if (len >= (int)(sizeof command_buf)) {
if ((command = malloc(len + 1)) == NULL) {
file_msg("Out of memory.");
close(fd);
return ret;
}
len = sprintf(command, command_fmt, xf_stream->uncompress,
xf_stream->name_on_disk, fd);
}
if (len < 0) {
len = errno;
file_msg("Unable to write command string.");
file_msg("Error: %s", strerror(len));
return ret;
}
if (system(command) == 0)
ret = 0;
else
file_msg("Could not uncompress %s, command: %s",
xf_stream->name_on_disk, command);
close(fd);
if (command != command_buf)
free(command);
return ret;
}
/*
* Compute the image dimension (size_x, size_y) in Fig-units from the number of
* pixels and the resolution in x- and y-direction, pixels_x, pixels_y, and
* res_x and res_y, respectively.
* The resolution is given in pixels / cm or pixels / inch, depending on
* whether 'c' or 'i' is passed to unit. For any other character passed to unit,
* a resolution of 72 pixels per inch is assumed.
*/
void
image_size(int *size_x, int *size_y, int pixels_x, int pixels_y,
char unit, float res_x, float res_y)
{
/* exclude negative and absurdly small values */
if (res_x < 1. || res_y < 1.) {
res_x = 72.0f;
res_y = 72.0f;
unit = 'i';
}
if (unit == 'i') { /* pixel / inch */
if (appres.INCHES) {
*size_x = pixels_x * PIX_PER_INCH / res_x + 0.5;
*size_y = pixels_y * PIX_PER_INCH / res_y + 0.5;
} else {
*size_x = pixels_x * PIX_PER_CM * 2.54 / res_x + 0.5;
*size_y = pixels_y * PIX_PER_CM * 2.54 / res_y + 0.5;
}
} else if (unit == 'c') { /* pixel / cm */
if (appres.INCHES) {
*size_x = pixels_x * PIX_PER_INCH / (res_x * 2.54) +0.5;
*size_y = pixels_y * PIX_PER_INCH / (res_y * 2.54) +0.5;
} else {
*size_x = pixels_x * PIX_PER_CM / res_x + 0.5;
*size_y = pixels_y * PIX_PER_CM / res_y + 0.5;
}
} else { /* unknown, default to 72 ppi */
*size_x = pixels_x * PIC_FACTOR + 0.5;
*size_y = pixels_y * PIC_FACTOR * res_x / res_y + 0.5;
}
}
| 27.518072 | 80 | 0.651051 | [
"object"
] |
ea39e469214864e0f0c44a94f248a92d0957c5f1 | 7,041 | h | C | aws-cpp-sdk-comprehend/include/aws/comprehend/model/SyntaxToken.h | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-comprehend/include/aws/comprehend/model/SyntaxToken.h | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-comprehend/include/aws/comprehend/model/SyntaxToken.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/comprehend/Comprehend_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/comprehend/model/PartOfSpeechTag.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Comprehend
{
namespace Model
{
/**
* <p>Represents a work in the input text that was recognized and assigned a part
* of speech. There is one syntax token record for each word in the source
* text.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/comprehend-2017-11-27/SyntaxToken">AWS
* API Reference</a></p>
*/
class AWS_COMPREHEND_API SyntaxToken
{
public:
SyntaxToken();
SyntaxToken(Aws::Utils::Json::JsonView jsonValue);
SyntaxToken& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>A unique identifier for a token.</p>
*/
inline int GetTokenId() const{ return m_tokenId; }
/**
* <p>A unique identifier for a token.</p>
*/
inline bool TokenIdHasBeenSet() const { return m_tokenIdHasBeenSet; }
/**
* <p>A unique identifier for a token.</p>
*/
inline void SetTokenId(int value) { m_tokenIdHasBeenSet = true; m_tokenId = value; }
/**
* <p>A unique identifier for a token.</p>
*/
inline SyntaxToken& WithTokenId(int value) { SetTokenId(value); return *this;}
/**
* <p>The word that was recognized in the source text.</p>
*/
inline const Aws::String& GetText() const{ return m_text; }
/**
* <p>The word that was recognized in the source text.</p>
*/
inline bool TextHasBeenSet() const { return m_textHasBeenSet; }
/**
* <p>The word that was recognized in the source text.</p>
*/
inline void SetText(const Aws::String& value) { m_textHasBeenSet = true; m_text = value; }
/**
* <p>The word that was recognized in the source text.</p>
*/
inline void SetText(Aws::String&& value) { m_textHasBeenSet = true; m_text = std::move(value); }
/**
* <p>The word that was recognized in the source text.</p>
*/
inline void SetText(const char* value) { m_textHasBeenSet = true; m_text.assign(value); }
/**
* <p>The word that was recognized in the source text.</p>
*/
inline SyntaxToken& WithText(const Aws::String& value) { SetText(value); return *this;}
/**
* <p>The word that was recognized in the source text.</p>
*/
inline SyntaxToken& WithText(Aws::String&& value) { SetText(std::move(value)); return *this;}
/**
* <p>The word that was recognized in the source text.</p>
*/
inline SyntaxToken& WithText(const char* value) { SetText(value); return *this;}
/**
* <p>The zero-based offset from the beginning of the source text to the first
* character in the word.</p>
*/
inline int GetBeginOffset() const{ return m_beginOffset; }
/**
* <p>The zero-based offset from the beginning of the source text to the first
* character in the word.</p>
*/
inline bool BeginOffsetHasBeenSet() const { return m_beginOffsetHasBeenSet; }
/**
* <p>The zero-based offset from the beginning of the source text to the first
* character in the word.</p>
*/
inline void SetBeginOffset(int value) { m_beginOffsetHasBeenSet = true; m_beginOffset = value; }
/**
* <p>The zero-based offset from the beginning of the source text to the first
* character in the word.</p>
*/
inline SyntaxToken& WithBeginOffset(int value) { SetBeginOffset(value); return *this;}
/**
* <p>The zero-based offset from the beginning of the source text to the last
* character in the word.</p>
*/
inline int GetEndOffset() const{ return m_endOffset; }
/**
* <p>The zero-based offset from the beginning of the source text to the last
* character in the word.</p>
*/
inline bool EndOffsetHasBeenSet() const { return m_endOffsetHasBeenSet; }
/**
* <p>The zero-based offset from the beginning of the source text to the last
* character in the word.</p>
*/
inline void SetEndOffset(int value) { m_endOffsetHasBeenSet = true; m_endOffset = value; }
/**
* <p>The zero-based offset from the beginning of the source text to the last
* character in the word.</p>
*/
inline SyntaxToken& WithEndOffset(int value) { SetEndOffset(value); return *this;}
/**
* <p>Provides the part of speech label and the confidence level that Amazon
* Comprehend has that the part of speech was correctly identified. For more
* information, see <a>how-syntax</a>.</p>
*/
inline const PartOfSpeechTag& GetPartOfSpeech() const{ return m_partOfSpeech; }
/**
* <p>Provides the part of speech label and the confidence level that Amazon
* Comprehend has that the part of speech was correctly identified. For more
* information, see <a>how-syntax</a>.</p>
*/
inline bool PartOfSpeechHasBeenSet() const { return m_partOfSpeechHasBeenSet; }
/**
* <p>Provides the part of speech label and the confidence level that Amazon
* Comprehend has that the part of speech was correctly identified. For more
* information, see <a>how-syntax</a>.</p>
*/
inline void SetPartOfSpeech(const PartOfSpeechTag& value) { m_partOfSpeechHasBeenSet = true; m_partOfSpeech = value; }
/**
* <p>Provides the part of speech label and the confidence level that Amazon
* Comprehend has that the part of speech was correctly identified. For more
* information, see <a>how-syntax</a>.</p>
*/
inline void SetPartOfSpeech(PartOfSpeechTag&& value) { m_partOfSpeechHasBeenSet = true; m_partOfSpeech = std::move(value); }
/**
* <p>Provides the part of speech label and the confidence level that Amazon
* Comprehend has that the part of speech was correctly identified. For more
* information, see <a>how-syntax</a>.</p>
*/
inline SyntaxToken& WithPartOfSpeech(const PartOfSpeechTag& value) { SetPartOfSpeech(value); return *this;}
/**
* <p>Provides the part of speech label and the confidence level that Amazon
* Comprehend has that the part of speech was correctly identified. For more
* information, see <a>how-syntax</a>.</p>
*/
inline SyntaxToken& WithPartOfSpeech(PartOfSpeechTag&& value) { SetPartOfSpeech(std::move(value)); return *this;}
private:
int m_tokenId;
bool m_tokenIdHasBeenSet;
Aws::String m_text;
bool m_textHasBeenSet;
int m_beginOffset;
bool m_beginOffsetHasBeenSet;
int m_endOffset;
bool m_endOffsetHasBeenSet;
PartOfSpeechTag m_partOfSpeech;
bool m_partOfSpeechHasBeenSet;
};
} // namespace Model
} // namespace Comprehend
} // namespace Aws
| 32.298165 | 128 | 0.663542 | [
"model"
] |
ea457f772740eba1d483e203c1f19ca58075c2ff | 2,107 | h | C | Game/world/bullet.h | swick/OpenGothic | 7cc7c0539c90a820607b227a38ae1146c104d420 | [
"MIT"
] | null | null | null | Game/world/bullet.h | swick/OpenGothic | 7cc7c0539c90a820607b227a38ae1146c104d420 | [
"MIT"
] | null | null | null | Game/world/bullet.h | swick/OpenGothic | 7cc7c0539c90a820607b227a38ae1146c104d420 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include "graphics/meshobjects.h"
class World;
class Npc;
class Bullet final {
public:
Bullet(World& owner, size_t inst);
Bullet(Bullet&&)=default;
~Bullet();
Bullet& operator=(Bullet&&)=default;
enum Flg:uint8_t {
NoFlags = 0,
Stopped = 1
};
void setPosition (const std::array<float,3>& p);
void setPosition (float x,float y,float z);
void setDirection (float x,float y,float z);
void setView (MeshObjects::Mesh&& m);
void setOwner(Npc* n);
Npc* owner() const;
const std::array<float,3>& position() const { return pos; }
const std::array<float,3>& direction() const { return dir; }
float speed() const { return dirL; }
Flg flags() const { return flg; }
void setFlags(Flg f) { flg=f; }
auto damage() const -> const std::array<int32_t,Daedalus::GEngineClasses::DAM_INDEX_MAX>& { return dmg; }
void setDamage(std::array<int32_t,Daedalus::GEngineClasses::DAM_INDEX_MAX> d) { dmg=d; }
float hitChance() const { return hitCh; }
void setHitChance(float h) { hitCh=h; }
void addLen(float l) { totalL+=l; }
float pathLength() const { return totalL; }
bool tick(uint64_t dt);
private:
World* wrld=nullptr;
Npc* ow=nullptr;
std::array<int32_t,Daedalus::GEngineClasses::DAM_INDEX_MAX> dmg={};
MeshObjects::Mesh view;
std::array<float,3> pos={};
std::array<float,3> dir={};
float dirL=0.f;
float totalL=0.f;
float hitCh=1.f;
Tempest::Matrix4x4 mat;
uint8_t material=0;
Flg flg=NoFlags;
void updateMatrix();
};
| 31.924242 | 131 | 0.486948 | [
"mesh"
] |
ea461bcb1546809b7599d2e829cd6d0912db766b | 6,582 | h | C | BSP_img/BSP/BSPNode.h | Miracle2333/BSPPN | f29182972fd4a13c47d5fb08b7e4faea2aabd77d | [
"MIT"
] | null | null | null | BSP_img/BSP/BSPNode.h | Miracle2333/BSPPN | f29182972fd4a13c47d5fb08b7e4faea2aabd77d | [
"MIT"
] | null | null | null | BSP_img/BSP/BSPNode.h | Miracle2333/BSPPN | f29182972fd4a13c47d5fb08b7e4faea2aabd77d | [
"MIT"
] | null | null | null | #pragma once
#include "../geom/math/Intersection.h"
#include "../geom/Line2.h"
#include "../geom/LineSegment2.h"
#include "../geom/Polygon2.h"
#include <algorithm>
#include <iostream>
class BSPNode
{
public:
Polygon2 *polygon;
Line2 *partitioning_line;
BSPNode *child_left, *child_right;
// ---------------------------------------------------------------------------------------------------- //
BSPNode(Polygon2 *polygon)
: polygon(polygon), partitioning_line(nullptr), child_left(nullptr), child_right(nullptr) {}
~BSPNode()
{
delete polygon;
if (partitioning_line)
{
delete partitioning_line;
delete child_left;
delete child_right;
}
}
// ---------------------------------------------------------------------------------------------------- //
void Build_BSPTree(std::vector<LineSegment2 *> &partitioning_lines)
{
Sort(partitioning_lines);
partitioning_line = partitioning_lines[0];
Divide();
if (partitioning_lines.size() > 1)
{
std::vector<LineSegment2 *> partitioning_lines_left = std::vector<LineSegment2 *>();
std::vector<LineSegment2 *> partitioning_lines_right = std::vector<LineSegment2 *>();
AssignSide(std::vector<LineSegment2 *>(partitioning_lines.begin() + 1, partitioning_lines.end()), partitioning_lines_left, partitioning_lines_right);
if (partitioning_lines_left.size() > 0)
{
child_left->Build_BSPTree(partitioning_lines_left);
}
if (partitioning_lines_right.size() > 0)
{
child_right->Build_BSPTree(partitioning_lines_right);
}
}
}
// ---------------------------------------------------------------------------------------------------- //
private:
void AssignSide(std::vector<LineSegment2 *> partitioning_lines, std::vector<LineSegment2 *> &partitioning_lines_left, std::vector<LineSegment2 *> &partitioning_lines_right)
{
for (LineSegment2 *ls : partitioning_lines)
{
int pos = Position(*ls);
if (pos == -2)
{
Point2 intersection;
if (!Intersection::Intersection2D(*partitioning_line, Line2(ls->P1(), ls->P2() - ls->P1()), intersection))
{
std::cout << "Error: BSPNode -> AssignSide -> Case 1" << std::endl;
}
partitioning_lines_left.push_back(new LineSegment2(ls->P1(), intersection));
partitioning_lines_right.push_back(new LineSegment2(ls->P2(), intersection));
delete ls;
}
else if (pos == -1)
{
partitioning_lines_left.push_back(ls);
}
else if (pos == 0)
{
}
else if (pos == 1)
{
partitioning_lines_right.push_back(ls);
}
else if (pos == 2)
{
Point2 intersection;
if (!Intersection::Intersection2D(*partitioning_line, Line2(ls->P1(), ls->P2() - ls->P1()), intersection))
{
std::cout << "Error: BSPNode -> AssignSide -> Case 2" << std::endl;
}
partitioning_lines_left.push_back(new LineSegment2(ls->P2(), intersection));
partitioning_lines_right.push_back(new LineSegment2(ls->P1(), intersection));
delete ls;
}
else
{
std::cout << "Error: BSPNode -> AssignSide" << std::endl;
}
}
}
void Divide()
{
bool pos_left = true;
bool pos_right = true;
for (const Point2 &p : polygon->ExteriorRing()->Points())
{
double pos = this->partitioning_line->EstimateSide2D(p);
if (pos < 0)
{
pos_right = false;
}
else if (pos > 0)
{
pos_left = false;
}
if (!pos_left && !pos_right)
{
break;
}
}
if (pos_left)
{
child_left = new BSPNode(new Polygon2(polygon));
child_right = new BSPNode(new Polygon2());
}
else if (pos_right)
{
child_left = new BSPNode(new Polygon2());
child_right = new BSPNode(new Polygon2(polygon));
}
else
{
std::vector<Point2> points = polygon->ExteriorRing()->Points();
points.push_back(polygon->ExteriorRing()->PointAt(0));
std::vector<Point2> points_left = std::vector<Point2>();
std::vector<Point2> points_right = std::vector<Point2>();
double pos = this->partitioning_line->EstimateSide2D(points[0]);
if (pos < 0)
{
points_left.push_back(points[0]);
}
else if (pos == 0)
{
points_left.push_back(points[0]);
points_right.push_back(points[0]);
}
else if (pos > 0)
{
points_right.push_back(points[0]);
}
for (int i = 1; i < points.size(); i++)
{
double pos_prev = pos;
pos = this->partitioning_line->EstimateSide2D(points[i]);
if (pos < 0)
{
if (pos_prev > 0)
{
Point2 intersection;
if (!Intersection::Intersection2D(*this->partitioning_line, Line2(polygon->ExteriorRing()->PointAt(i - 1), points[i] - polygon->ExteriorRing()->PointAt(i - 1)), intersection))
{
std::cout << "Error: BSPNode -> Divide -> Case 1" << std::endl;
}
points_left.push_back(intersection);
points_right.push_back(intersection);
}
points_left.push_back(points[i]);
}
else if (pos == 0)
{
points_left.push_back(points[i]);
points_right.push_back(points[i]);
}
else if (pos > 0)
{
if (pos_prev < 0)
{
Point2 intersection;
if (!Intersection::Intersection2D(*this->partitioning_line, Line2(polygon->ExteriorRing()->PointAt(i - 1), points[i] - polygon->ExteriorRing()->PointAt(i - 1)), intersection))
{
std::cout << "Error: BSPNode -> Divide -> Case 2" << std::endl;
}
points_left.push_back(intersection);
points_right.push_back(intersection);
}
points_right.push_back(points[i]);
}
}
child_left = new BSPNode(new Polygon2(new LinearRing2(points_left)));
child_right = new BSPNode(new Polygon2(new LinearRing2(points_right)));
}
}
static bool IsLongerThan(LineSegment2 *ls1, LineSegment2 *ls2)
{
return (ls1->Length() > ls2->Length());
}
int Position(const LineSegment2 &ls)
{
double pos_p1 = partitioning_line->EstimateSide2D(ls.P1());
double pos_p2 = partitioning_line->EstimateSide2D(ls.P2());
if (pos_p1 < 0 && pos_p2 > 0) // left, right
{
return -2;
}
else if ((pos_p1 < 0 && pos_p2 <= 0) || // left/on, left/on
(pos_p1 <= 0 && pos_p2 < 0))
{
return -1;
}
else if (pos_p1 == 0 && pos_p2 == 0) // on, on
{
return 0;
}
else if ((pos_p1 > 0 && pos_p2 >= 0) || // right/on, right/on
(pos_p1 >= 0 && pos_p2 > 0))
{
return 1;
}
else if (pos_p1 > 0 && pos_p2 < 0) // right, left
{
return 2;
}
else
{
return 42;
}
}
void Sort(std::vector<LineSegment2 *> &partitioning_lines)
{
std::sort(partitioning_lines.begin(), partitioning_lines.end(), BSPNode::IsLongerThan);
}
}; | 24.744361 | 181 | 0.601337 | [
"vector"
] |
ea470c88e40ae1b489711f74ae4d6c5f8118398e | 7,541 | h | C | Code/Algorithms/Common/vnsMultiplyByScalarVectorImageFilter.h | spacebel/MAJA | 3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e | [
"Apache-2.0"
] | 57 | 2020-09-30T08:51:22.000Z | 2021-12-19T20:28:30.000Z | Code/Algorithms/Common/vnsMultiplyByScalarVectorImageFilter.h | spacebel/MAJA | 3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e | [
"Apache-2.0"
] | 34 | 2020-09-29T21:27:22.000Z | 2022-02-03T09:56:45.000Z | Code/Algorithms/Common/vnsMultiplyByScalarVectorImageFilter.h | spacebel/MAJA | 3e5d20bc9c744c610e608cfcf1f4c5c738d4de9e | [
"Apache-2.0"
] | 14 | 2020-10-11T13:17:59.000Z | 2022-03-09T15:58:19.000Z | /*
* Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES)
*
* 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.
*
*/
/************************************************************************************************************
* *
* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo *
* o *
* o *
* o *
* o *
* o ooooooo ooooooo o o oo *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o oooo o o o o o o *
* o o o o o o o o o *
* o o o o o o o o o o *
* oo oooooooo o o o oooooo o oooo *
* o *
* o *
* o o *
* o o oooo o o oooo *
* o o o o o o *
* o o ooo o o ooo *
* o o o o o *
* ooooo oooo o ooooo oooo *
* o *
* *
************************************************************************************************************
* *
* Author: CS Systemes d'Information (France) *
* *
************************************************************************************************************
* HISTORIQUE *
* *
* VERSION : 5-1-0 : FA : LAIG-FA-MAC-145739-CS : 27 juin 2016 : Audit code - Supp de la macro ITK_EXPORT *
* VERSION : 1-0-0 : <TypeFT> : <NumFT> : 11 mai 2010 : Creation
* *
* FIN-HISTORIQUE *
* *
* $Id$
* *
************************************************************************************************************/
#ifndef __vnsMultiplyByScalarImageFilter_h
#define __vnsMultiplyByScalarImageFilter_h
#include "itkImageToImageFilter.h"
#include "vnsMacro.h"
namespace vns
{
/** \class MultiplyByScalarToVectorImageFilter
* \brief Multiply each component of a vector image by a given scalar
*
*
* \author CS Systemes d'Information
*
* \sa ImageToImageFilter
* \sa MultiplyByScalarVectorImageFilter
*
*
*/
template <class TInputImage, class TOutputImage>
class MultiplyByScalarVectorImageFilter : public itk::ImageToImageFilter<TInputImage,TOutputImage>
{
public:
/** Standard class typedefs. */
typedef MultiplyByScalarVectorImageFilter Self;
typedef itk::ImageToImageFilter<TInputImage,TOutputImage> Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Type macro */
itkNewMacro(Self);
/** Creation through object factory macro */
itkTypeMacro(MultiplyByScalarVectorImageFilter, ImageToImageFilter );
/** Some convenient typedefs. */
typedef typename Superclass::InputImageType InputImageType;
typedef typename InputImageType::ConstPointer InputImageConstPointer;
typedef typename InputImageType::RegionType RegionType;
typedef typename InputImageType::PixelType InputImagePixelType;
typedef typename InputImageType::SizeType SizeType;
typedef typename Superclass::OutputImageType OutputImageType;
typedef typename OutputImageType::Pointer OutputImagePointer;
typedef typename OutputImageType::PixelType OutputImagePixelType;
typedef typename OutputImageType::InternalPixelType OutputImageInternalPixelType;
itkSetMacro(Coeff, double);
virtual void GenerateOutputInformation();
protected:
/** Constructor */
MultiplyByScalarVectorImageFilter();
/** Destructor */
virtual ~MultiplyByScalarVectorImageFilter();
/** PrintSelf method */
virtual void PrintSelf(std::ostream& os, itk::Indent indent) const;
/** Multi-thread version GenerateData. */
void ThreadedGenerateData (const RegionType& outputRegionForThread, itk::ThreadIdType threadId);
private:
MultiplyByScalarVectorImageFilter(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
/** Scalar factor top apply */
double m_Coeff;
};
} // End namespace vns
#ifndef VNS_MANUAL_INSTANTIATION
#include "vnsMultiplyByScalarVectorImageFilter.txx"
#endif
#endif /* __vnsMultiplyByScalarVectorImageFilter_h */
| 57.128788 | 123 | 0.371038 | [
"object",
"vector"
] |
ea523edfd624451d8521f780af48bc049216c657 | 36,015 | h | C | include/diplib/library/types.h | DIPlib/diplib | eaf03372264f050bcda2d49bdf443702308ba303 | [
"Apache-2.0"
] | 140 | 2017-04-04T23:10:16.000Z | 2022-03-24T18:21:34.000Z | include/diplib/library/types.h | DIPlib/diplib | eaf03372264f050bcda2d49bdf443702308ba303 | [
"Apache-2.0"
] | 98 | 2018-01-13T23:16:00.000Z | 2022-03-14T14:45:37.000Z | include/diplib/library/types.h | DIPlib/diplib | eaf03372264f050bcda2d49bdf443702308ba303 | [
"Apache-2.0"
] | 40 | 2017-04-11T20:41:58.000Z | 2022-03-24T18:21:36.000Z | /*
* DIPlib 3.0
* This file contains definitions for the basic data types.
*
* (c)2014-2019, Cris Luengo.
* Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
*
* 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.
*/
//
// NOTE!
// This file is included through diplib.h -- no need to include directly
//
#ifndef DIP_TYPES_H
#define DIP_TYPES_H
#include <cstddef> // std::size_t, std::ptrdiff_t
#include <cstdint> // std::uint8_t, etc.
#include <complex>
#include <vector>
#include <string>
#include <set>
#include <cctype>
#include <climits>
#include <limits>
#include "diplib/library/dimension_array.h"
/// \file
/// \brief Defines the basic types used throughout the library. This file is always included through \ref "diplib.h".
/// See \ref supporttypes, \ref pixeltypes.
namespace dip {
/// \group supporttypes Support types
/// \ingroup infrastructure
/// \brief Types used for image samples (pixels), and related support functionality
/// \addtogroup
//
// Integer types for image properties, pixel coordinates, loop indices, etc.
//
// NOTE: `uint` is defined somewhere in some header, so *always* refer to it
// as `dip::uint`, everywhere in the DIPlib code base!
// For consistency, we also use `dip::sint` everywhere we refer to `sint`.
//
// NOTE: It might be better to always use signed integer types everywhere.
// uint could lead to difficult to catch errors in loops, uint ii<0 is
// always false. I started with the uint because the standard library
// uses it for sizes of arrays, and sizeof() is unsigned also. Maybe
// better to cast these to sint?
/// An integer type to be used for strides and similar measures.
using sint = std::ptrdiff_t;
/// An integer type to be used for sizes and the like.
using uint = std::size_t;
// ptrdiff_t and size_t are signed and unsigned integers of the same length as
// pointers: 32 bits on 32-bit systems, 64 bits on 64-bit systems.
// NOTE: We don't allow any integer to be larger than the max value of ptrdiff_t.
// This is tested for in a few places (at dip::Image creation and when forging)
// but not everywhere.
constexpr dip::uint maxint = static_cast< dip::uint >( std::numeric_limits< dip::sint >::max() );
/// \endgroup
/// \addtogroup pixeltypes
//
// Types for pixel values
//
/// Type for samples in a binary image. Can store 0 or 1. Occupies 1 byte.
class DIP_NO_EXPORT bin;
/// Type for samples in an 8-bit unsigned integer image; also to be used as single byte for pointer arithmetic
using uint8 = std::uint8_t;
/// Type for samples in a 16-bit unsigned integer image
using uint16 = std::uint16_t;
/// Type for samples in a 32-bit unsigned integer image
using uint32 = std::uint32_t;
/// Type for samples in a 64-bit unsigned integer image
using uint64 = std::uint64_t;
/// Type for samples in an 8-bit signed integer image
using sint8 = std::int8_t;
/// Type for samples in a 16-bit signed integer image
using sint16 = std::int16_t;
/// Type for samples in a 32-bit signed integer image
using sint32 = std::int32_t;
/// Type for samples in a 64-bit signed integer image
using sint64 = std::int64_t;
/// Type for samples in a 32-bit floating point (single-precision) image
using sfloat = float;
/// Type for samples in a 64-bit floating point (double-precision) image
using dfloat = double;
/// Type for samples in a 64-bit complex-valued (single-precision) image
using scomplex = std::complex< sfloat >;
/// Type for samples in a 128-bit complex-valued (double-precision) image
using dcomplex = std::complex< dfloat >;
/// Type currently used for all labeled images, see \ref dip::DT_LABEL.
using LabelType = uint32;
namespace detail {
template< typename T > struct IsSampleType { static constexpr bool value = false; };
template<> struct IsSampleType< bin > { static constexpr bool value = true; };
template<> struct IsSampleType< uint8 > { static constexpr bool value = true; };
template<> struct IsSampleType< uint16 > { static constexpr bool value = true; };
template<> struct IsSampleType< uint32 > { static constexpr bool value = true; };
template<> struct IsSampleType< uint64 > { static constexpr bool value = true; };
template<> struct IsSampleType< sint8 > { static constexpr bool value = true; };
template<> struct IsSampleType< sint16 > { static constexpr bool value = true; };
template<> struct IsSampleType< sint32 > { static constexpr bool value = true; };
template<> struct IsSampleType< sint64 > { static constexpr bool value = true; };
template<> struct IsSampleType< sfloat > { static constexpr bool value = true; };
template<> struct IsSampleType< dfloat > { static constexpr bool value = true; };
template<> struct IsSampleType< scomplex > { static constexpr bool value = true; };
template<> struct IsSampleType< dcomplex > { static constexpr bool value = true; };
template< typename T > struct IsNumericType { static constexpr bool value = std::is_arithmetic< T >::value; };
template<> struct IsNumericType< bin > { static constexpr bool value = true; };
template<> struct IsNumericType< scomplex > { static constexpr bool value = true; };
template<> struct IsNumericType< dcomplex > { static constexpr bool value = true; };
template< typename T > struct IsIndexingType { static constexpr bool value = false; };
template<> struct IsIndexingType< signed int > { static constexpr bool value = true; };
template<> struct IsIndexingType< unsigned int > { static constexpr bool value = true; };
#if SIZE_MAX != UINT_MAX // we don't want to compile the next two if `dip::uint == unsigned int`.
template<> struct IsIndexingType< dip::uint > { static constexpr bool value = true; };
template<> struct IsIndexingType< dip::sint > { static constexpr bool value = true; };
#endif
} // namespace detail
/// \brief For use with `std::enable_if` to enable templates only for types that are valid for image samples.
///
/// One example usage is as follows:
///
/// ```cpp
/// template< typename T, typename = std::enable_if_t< dip::IsSampleType< T >::value >>
/// void MyFunction( T value ) { ... }
/// ```
///
/// When defining different versions of the templated function for `IsSampleType< T >` and `!IsSampleType< T >`,
/// you'll need to use the following form:
///
/// ```cpp
/// template< typename T, typename std::enable_if_t< dip::IsSampleType< T >::value, int > = 0 >
/// void MyFunction( T value ) { ... }
/// template< typename T, typename std::enable_if_t< !dip::IsSampleType< T >::value, int > = 0 >
/// void MyFunction( T value ) { ... }
/// ```
template< typename T > struct IsSampleType : public detail::IsSampleType< typename std::remove_cv_t< std::remove_reference_t< T >>> {};
/// \brief For use with `std::enable_if` to enable templates only for types that are numeric types, similar to
/// `std::is_arithmetic` but also true for complex types. See \ref dip::IsSampleType for usage details.
template< typename T > struct IsNumericType : public detail::IsNumericType< typename std::remove_cv_t< std::remove_reference_t< T >>> {};
/// \brief For use with `std::enable_if` to enable templates only for types that are indexing types, true for
/// signed and unsigned integers. See \ref dip::IsSampleType for usage details.
template< typename T > struct IsIndexingType : public detail::IsIndexingType< typename std::remove_cv_t< std::remove_reference_t< T >>> {};
/// \brief A templated function to check for positive infinity, which works also for integer types (always returning false)
template< typename TPI, typename std::enable_if_t< !std::numeric_limits< TPI >::has_infinity, int > = 0 >
bool PixelIsInfinity( TPI /*value*/ ) {
return false;
}
template< typename TPI, typename std::enable_if_t< std::numeric_limits< TPI >::has_infinity, int > = 0 >
bool PixelIsInfinity( TPI value ) {
return value == std::numeric_limits< TPI >::infinity();
}
/// \brief A templated function to check for negative infinity, which works also for integer types (always returning false)
template< typename TPI, typename std::enable_if_t< !std::numeric_limits< TPI >::has_infinity, int > = 0 >
bool PixelIsMinusInfinity( TPI /*value*/ ) {
return false;
}
template< typename TPI, typename std::enable_if_t< std::numeric_limits< TPI >::has_infinity, int > = 0 >
bool PixelIsMinusInfinity( TPI value ) {
return value == -std::numeric_limits< TPI >::infinity();
}
// dip::bin is documented above by its first declaration.
class DIP_NO_EXPORT bin {
// Binary data stored in a single byte (don't use bool for pixels, it has
// implementation-defined size). We define this class for binary data so
// that we can overload functions differently for bin and for uint8.
public:
// Default copy and move constructors, just in case the templated constructor overrides one of these.
constexpr bin( bin const& ) = default;
constexpr bin( bin&& ) = default;
bin& operator=( bin const& ) = default;
bin& operator=( bin&& ) = default;
// Overload constructors to make sure we always write 0 or 1 in the bin.
/// The default value is 0 (false)
constexpr bin() = default;
/// A bool implicitly converts to bin
constexpr bin( bool v ) : v_( static_cast< uint8 >( v )) {}
/// Any arithmetic type converts to bin by comparing to zero
template< typename T, typename = std::enable_if_t< IsNumericType< T >::value >>
constexpr explicit bin( T v ) : v_( static_cast< uint8 >( v != 0 )) {}
/// A bin implicitly converts to bool
constexpr operator bool() const { return v_ != 0; }
/// Negation operator
constexpr bin operator!() const { return v_ == 0; }
/// Bit-wise negation is the same as regular negation
constexpr bin operator~() const { return v_ == 0; }
/// And operator, prefer to use this over `std::min`
constexpr bin operator&( bin other ) const { return { ( v_ != 0 ) && ( other.v_ != 0 ) }; } // Why && and not & ? Short circuit.
/// Or operator, prefer to use this over `std::max`
constexpr bin operator|( bin other ) const { return { ( v_ != 0 ) || ( other.v_ != 0 ) }; } // Why || and not | ? Short circuit.
/// Exclusive-or operator
constexpr bin operator^( bin other ) const { return bin( v_ ^ other.v_ ); }
/// And compound operator
constexpr bin& operator&=( bin other ) { v_ &= other.v_; return *this; }
/// Or compound operator
constexpr bin& operator|=( bin other ) { v_ |= other.v_; return *this; }
/// Exclusive-or compound operator
constexpr bin& operator^=( bin other ) { v_ ^= other.v_; return *this; }
/// Equality operator
template< typename T >
constexpr bool operator==( T other ) const { return static_cast< bool >( v_ ) == static_cast< bool >( other ); }
/// Inequality operator
template< typename T >
constexpr bool operator!=( T other ) const { return static_cast< bool >( v_ ) != static_cast< bool >( other ); }
/// Allow explicit casting to a reference to the underlying type (uint8&) for binary image operations
explicit operator uint8&() { return v_; }
private:
uint8 v_ = 0;
};
/// \brief Writes the value as a `bool` to a stream.
/// \relates dip::bin
inline std::ostream& operator<<(
std::ostream& os,
bin const& v
) {
os << static_cast< bool >( v );
return os;
}
// if 8 bits is not a byte...
static_assert( sizeof( dip::uint8 ) == 1, "8 bits is not a byte in your system!" );
// Seriously, though. We rely on this property, and there is no guarantee
// that a system actually has 8 bits in a byte. Maybe we should use char
// (which is guaranteed to be size 1) for generic pointer arithmetic?
static_assert( sizeof( dip::bin ) == 1, "The binary type is not a single byte!" );
//
// Templates that help get the right types in template functions and template classes
//
namespace detail {
template< typename T > struct FloatTypeCalculator { using type = sfloat; };
template<> struct FloatTypeCalculator< uint32 > { using type = dfloat; };
template<> struct FloatTypeCalculator< sint32 > { using type = dfloat; };
template<> struct FloatTypeCalculator< uint64 > { using type = dfloat; };
template<> struct FloatTypeCalculator< sint64 > { using type = dfloat; };
template<> struct FloatTypeCalculator< dfloat > { using type = dfloat; };
template<> struct FloatTypeCalculator< dcomplex > { using type = dfloat; };
} // namespace detail
/// \brief The type to use in calculations when a floating-point type is needed. Matches \ref dip::DataType::SuggestFloat.
template< typename T > using FloatType = typename detail::FloatTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
namespace detail {
template< typename T > struct DoubleTypeCalculator { using type = dfloat; };
template<> struct DoubleTypeCalculator< scomplex > { using type = dcomplex; };
template<> struct DoubleTypeCalculator< dcomplex > { using type = dcomplex; };
} // namespace detail
/// \brief The double precision floating point type (real or complex) to use when computing large sums of any input type. Matches \ref dip::DataType::SuggestDouble.
template< typename T > using DoubleType = typename detail::DoubleTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
namespace detail {
template< typename T > struct ComplexTypeCalculator { using type = scomplex; };
template<> struct ComplexTypeCalculator< uint32 > { using type = dcomplex; };
template<> struct ComplexTypeCalculator< sint32 > { using type = dcomplex; };
template<> struct ComplexTypeCalculator< uint64 > { using type = dcomplex; };
template<> struct ComplexTypeCalculator< sint64 > { using type = dcomplex; };
template<> struct ComplexTypeCalculator< dfloat > { using type = dcomplex; };
template<> struct ComplexTypeCalculator< dcomplex > { using type = dcomplex; };
} // namespace detail
/// \brief The type to use in calculations when a complex type is needed. Matches \ref dip::DataType::SuggestComplex.
template< typename T > using ComplexType = typename detail::ComplexTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
namespace detail {
template< typename T > struct FlexTypeCalculator { using type = FloatType< T >; };
template<> struct FlexTypeCalculator< scomplex > { using type = scomplex; };
template<> struct FlexTypeCalculator< dcomplex > { using type = dcomplex; };
} // namespace detail
/// \brief The type to use in calculations. Matches \ref dip::DataType::SuggestFlex.
template< typename T > using FlexType = typename detail::FlexTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
namespace detail {
template< typename T > struct FlexBinTypeCalculator { using type = FlexType< T >; };
template<> struct FlexBinTypeCalculator< bin > { using type = bin; };
} // namespace detail
/// \brief The type to use in calculations. Matches \ref dip::DataType::SuggestFlexBin.
template< typename T > using FlexBinType = typename detail::FlexBinTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
namespace detail {
template< typename T > struct AbsTypeCalculator { using type = T; };
template<> struct AbsTypeCalculator< sint8 > { using type = uint8; };
template<> struct AbsTypeCalculator< sint16 > { using type = uint16; };
template<> struct AbsTypeCalculator< sint32 > { using type = uint32; };
template<> struct AbsTypeCalculator< sint64 > { using type = uint64; };
template<> struct AbsTypeCalculator< scomplex > { using type = sfloat; };
template<> struct AbsTypeCalculator< dcomplex > { using type = dfloat; };
} // namespace detail
/// \brief The type to use for the output of abs operations. Matches \ref dip::DataType::SuggestAbs.
template< typename T > using AbsType = typename detail::AbsTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
namespace detail {
template< typename T > struct RealTypeCalculator { using type = T; };
template<> struct RealTypeCalculator< bin > { using type = uint8; };
template<> struct RealTypeCalculator< scomplex > { using type = sfloat; };
template<> struct RealTypeCalculator< dcomplex > { using type = dfloat; };
} // namespace detail
/// \brief The type to use in calculations when a real-valued type is needed. Matches \ref dip::DataType::SuggestReal.
template< typename T > using RealType = typename detail::RealTypeCalculator< std::remove_cv_t< std::remove_reference_t< T >>>::type;
/// \endgroup
/// \addtogroup supporttypes
//
// Array types
//
/// An array to hold strides, filter sizes, etc.
using IntegerArray = DimensionArray< dip::sint >;
/// An array to hold dimensions, dimension lists, etc.
using UnsignedArray = DimensionArray< dip::uint >;
/// An array to hold filter parameters.
using FloatArray = DimensionArray< dip::dfloat >;
/// An array used as a dimension selector.
using BooleanArray = DimensionArray< bool >;
/// An array of pixel coordinates.
using CoordinateArray = std::vector< UnsignedArray >;
/// An array of subpixel coordinates.
using FloatCoordinateArray = std::vector< FloatArray >;
/// \brief Check the length of an array, and extend it if necessary and possible.
///
/// This function is used where a function's
/// input parameter is an array that is supposed to match the image dimensionality `nDims`. The user can give an
/// array of that length, or an array with a single value, which will be used for all dimensions, or an empty array,
/// in which case the default value `defaultValue` will be used for all dimensions.
template< typename T >
inline void ArrayUseParameter( DimensionArray< T >& array, dip::uint nDims, T defaultValue = {} ) {
if( array.empty() ) {
array.resize( nDims, defaultValue );
} else if( array.size() == 1 ) {
array.resize( nDims, array[ 0 ] );
} else if( array.size() != nDims ) {
DIP_THROW( E::ARRAY_PARAMETER_WRONG_LENGTH );
}
}
//
// Strings, used for parameters and other things
//
/// A string, used to specify an option
using String = std::string;
/// An array of strings, used to specify an option per dimension
using StringArray = std::vector< String >;
/// A collection of strings, used to specify multiple independent options
using StringSet = std::set< String >;
/// \brief Translates a string input parameter that is meant as a boolean value.
inline bool BooleanFromString( String const& input, String const& trueString, String const& falseString ) {
if( input == trueString ) {
return true;
}
if( input == falseString ) {
return false;
}
DIP_THROW_INVALID_FLAG( input );
}
// An overload so that we don't construct a `String` object from string literals
inline bool BooleanFromString( String const& input, String::value_type const* trueString, String::value_type const* falseString ) {
if( input == trueString ) {
return true;
}
if( input == falseString ) {
return false;
}
DIP_THROW_INVALID_FLAG( input );
}
/// \brief A case-insensitive string comparison, use only with ASCII characters!
inline bool StringCompareCaseInsensitive( String const& string1, String const& string2 ) {
if( string1.size() != string2.size() ) {
return false;
}
for( auto it1 = string1.begin(), it2 = string2.begin(); it1 != string1.end(); ++it1, ++it2 ) {
if( std::tolower( static_cast< unsigned char >( *it1 )) != std::tolower( static_cast< unsigned char >( *it2 ))) {
return false;
}
}
return true;
}
/// \brief Convert a string to lower case, use only with ASCII characters!
inline void ToLowerCase( String& string ) {
for( auto& s : string ) {
s = static_cast< char >( std::tolower( static_cast< unsigned char >( s )));
}
}
/// \brief Convert a string to upper case, use only with ASCII characters!
inline void ToUpperCase( String& string ) {
for( auto& s : string ) {
s = static_cast< char >( std::toupper( static_cast< unsigned char >( s )));
}
}
//
// Ranges, used for indexing
//
/// \brief Used in indexing to indicate a regular subset of pixels along one
/// image dimension.
///
/// `dip::Range{ start, stop }` generates a range of pixels where `start` and
/// `stop` are the first and last indices in the range. That is, `stop` is
/// \ref design_ranges "included in the range". `dip::Range{ start }` generates
/// a range for a single pixel. For example, `dip::Range{ 0 }` is the first pixel,
/// and is equivalent to `dip::Range{ 0, 0 }`. `dip::Range{ 0, N - 1 }` is
/// a range of the first `N` pixels.
///
/// `dip::Range{ start, stop, step }` generates a range of pixels where `step` is
/// the number of pixels between subsequent indices. The pixels indexed are the
/// ones generated by the following loop:
///
/// ```cpp
/// offset = start;
/// do {
/// // use this offset
/// offset += step;
/// } while( offset <= stop );
/// ```
///
/// That is, it is possible that the range does not include `stop`, if the
/// `step` would make the range step over `stop`.
///
/// Negative `start` and `stop` values indicate offset from the end (-1 is the
/// last pixel, -2 the second to last, etc.): `dip::Range{ 5, -6 }` indicates
/// a range that skips the first and last five pixels. `dip::Range{ -1, -1, 1 }`
/// (or simply `dip::Range{ -1 }` indicates the last pixel only.
///
/// `dip::Range{ 0, -1 }` is equivalent to `dip::Range{}`, and indicates all
/// pixels.
///
/// The \ref Fix method converts the negative `start` and `stop` values
/// to actual offsets:
///
/// ```cpp
/// dip::Range r{ 5, -6 };
/// r.fix( 50 );
/// // now r.stop == 50 - 6
/// ```
///
/// If `stop` comes before `start`, then the range generates pixel indices in
/// the reverse order. That is, negative steps are taken to go from `start` to `stop`.
/// `step` is always a positive integer, the direction of the steps is given
/// solely by the ordering of `start` and `stop`.
///
/// The `begin` and `end` methods yield an iterator that dereferences to the indices
/// defined by the range.
struct DIP_NO_EXPORT Range {
dip::sint start = 0; ///< First index included in range
dip::sint stop = -1; ///< Last index included in range
dip::uint step = 1; ///< Step size when going from start to stop
/// Create a range that indicates all pixels
Range() = default;
/// Create a range that indicates a single pixel
explicit Range( dip::sint i ) : start{ i }, stop{ i }, step{ 1 } {}
/// \brief Create a range using two or three values; it indicates all pixels between `i` and `j`, both inclusive.
/// The step size defaults to 1.
Range( dip::sint i, dip::sint j, dip::uint s = 1 ) : start{ i }, stop{ j }, step{ s } {}
/// \brief Modify a range so that negative values are assigned correct
/// values according to the given size. Throws if the range falls
/// out of bounds.
void Fix( dip::uint size ) {
// Check step is non-zero
DIP_THROW_IF( step == 0, E::INVALID_PARAMETER );
// Compute indices from end
dip::sint sz = static_cast< dip::sint >( size );
if( start < 0 ) { start += sz; }
if( stop < 0 ) { stop += sz; }
// Check start and stop are within range
DIP_THROW_IF( ( start < 0 ) || ( start >= sz ) || ( stop < 0 ) || ( stop >= sz ), E::INDEX_OUT_OF_RANGE );
// Compute stop given start and step
//stop = start + ((stop-start)/step)*step;
}
/// Get the number of pixels addressed by the range (must be fixed first!).
dip::uint Size() const {
if( start > stop ) {
return 1 + static_cast< dip::uint >( start - stop ) / step;
} else {
return 1 + static_cast< dip::uint >( stop - start ) / step;
}
}
/// Get the offset for the range (must be fixed first!).
dip::uint Offset() const {
return static_cast< dip::uint >( start );
}
/// Get the last index in the range (must be fixed first!).
dip::uint Last() const {
return static_cast< dip::uint >( stop );
}
/// Get the signed step size for the range (must be fixed first!).
dip::sint Step() const {
if( start > stop ) {
return -static_cast< dip::sint >( step );
} else {
return static_cast< dip::sint >( step );
}
}
/// An iterator for the range
class Iterator {
public:
/// Iterator category
using iterator_category = std::forward_iterator_tag;
/// Type of value iterator references
using value_type = dip::uint;
/// Type of reference to value
using reference = dip::sint const&;
/// Type of pointer to value
using pointer = dip::sint const*;
/// Default constructor
Iterator() = default;
/// Constructor
Iterator( dip::uint index, dip::sint step ) : index_( static_cast< dip::sint >( index )), step_( step ) {}
Iterator( dip::sint index, dip::sint step ) : index_( index ), step_( step ) {}
/// Dereference
value_type operator*() const { return static_cast< value_type >( index_ ); }
/// Dereference
pointer operator->() const { return &index_; }
/// Pre-increment
Iterator& operator++() {
index_ += step_;
return *this;
}
/// Post-increment
Iterator operator++( int ) {
Iterator tmp( *this );
index_ += step_;
return tmp;
}
/// Equality comparison
bool operator==( Iterator const& other ) const { return index_ == other.index_; }
/// Inequality comparison
bool operator!=( Iterator const& other ) const { return index_ != other.index_; }
private:
dip::sint index_ = 0; // We use signed one here in case step_<0, we need the one-past-the-end to be sensical
dip::sint step_ = 1; // (sure, we could rely on defined unsigned integer overflow, but why?)
};
/// Get an iterator to the beginning of the range (must be fixed first!).
Iterator begin() const {
return Iterator( start, Step() );
}
/// \brief Get an iterator to the end of the range (must be fixed first!). This iterator points one past
/// the `stop` value, as is usual for the end iterator.
Iterator end() const {
return Iterator( start + static_cast< dip::sint >( Size() ) * Step(), Step() );
}
};
/// \brief Display a range as "{start, stop, step}".
/// \relates dip::Range
inline std::ostream& operator<<(
std::ostream& os,
Range const& range
) {
os << '{' << range.start << ", " << range.stop << ", " << range.step << '}';
return os;
}
/// \brief An array of ranges
/// \relates dip::Range
using RangeArray = DimensionArray< Range >;
//
// The following is support for defining an options type, where the user can
// specify multiple options to pass on to a function or class. The class should
// not be used directly, only through the macro defined below it.
//
// With lots of help from Toby Speight: https://codereview.stackexchange.com/a/183260/151754
//
namespace detail {
template< typename Enum, typename = std::enable_if_t< std::is_enum< Enum >::value >>
class DIP_NO_EXPORT Options {
using value_type = unsigned long;
using enum_u_type = typename std::underlying_type< Enum >::type;
value_type values = 0;
private:
// Private constructor used by `operator+` and `operator-`.
explicit constexpr Options( value_type n ) noexcept : values{ n } {}
public:
constexpr Options() noexcept = default;
constexpr Options( Enum n ) noexcept : values{ value_type( 1u ) << static_cast< enum_u_type >( n ) } {}
// Testing
constexpr bool operator==( Options const other ) const noexcept {
return values == other.values;
}
constexpr bool operator!=( Options const other ) const noexcept {
return !operator==( other );
}
constexpr bool Contains( Options const other ) const noexcept {
return ( values & other.values ) == other.values;
}
// Combining
constexpr Options operator+( Options const other ) const noexcept {
return Options{ values | other.values };
}
constexpr Options operator-( Options const other ) const noexcept {
return Options{ values & ~other.values };
}
Options& operator+=( Options const other ) noexcept {
values |= other.values;
return *this;
}
Options& operator-=( Options const other ) noexcept {
values &= ~other.values;
return *this;
}
};
// This operator enables `enum_value + options`, for symmetry with the operator defined
// as a member of `Options`.
template< typename T >
constexpr Options< T > operator+( T a, Options< T > b ) noexcept {
return b + a;
}
/// \macro DIP_DECLARE_OPTIONS(EnumType,OptionsType)
/// \brief Declare a type used to pass enumerated options to a function or class.
///
/// This macro is used as follows:
///
/// ```cpp
/// enum class MyOption { clean, fresh, shine };
/// DIP_DECLARE_OPTIONS( MyOption, MyOptions )
/// ```
///
/// `MyOptions` will be a type that combines one or more values from MyOption.
/// These values can be combined using the `+` operator.
/// A variable of type `MyOptions` can be tested using its `Contains` method
/// which returns a `bool`:
///
/// ```cpp
/// MyOptions opts {}; // No options are set
/// opts = MyOption::fresh; // Set only one option
/// opts = MyOption::clean + MyOption::shine; // Set only these two options
/// if( opts.Contains( MyOption::clean )) {...} // Test to see if `MyOption::clean` is set
/// ```
///
/// The `Contains` method returns true only of all flags specified in the input are set.
/// The `==` operator returns true only if the two operands contain exactly the same
/// set of flags.
///
/// Note that there should be no more than 32 options within the enumerator.
///
/// This macro will not work within a class definition -- You will need to manually declare the type alias
/// and define the operator outside of the class.
#define DIP_DECLARE_OPTIONS( EnumType, OptionsType ) \
using OptionsType = dip::detail::Options< EnumType >; \
constexpr OptionsType operator+( EnumType a, EnumType b ) noexcept { return OptionsType{ a } + b; }
// The `operator+` allows the addition of two enumerator values to produce an options object.
} // namespace detail
//
// The following are some types for often-used parameters
//
/// \brief Enumerated options are defined in the namespace `dip::Option`, unless they
/// are specific to some other sub-namespace.
/// \ingroup infrastructure
namespace Option {
/// \brief Some functions that check for a condition optionally throw an exception
/// if that condition is not met.
enum class DIP_NO_EXPORT ThrowException {
DONT_THROW, ///< Do not throw and exception, return false if the condition is not met.
DO_THROW ///< Throw an exception if the condition is not met.
};
/// \brief The function \ref dip::Image::CheckIsMask takes this option to control how sizes are compared.
enum class DIP_NO_EXPORT AllowSingletonExpansion {
DONT_ALLOW, ///< Do not allow singleton expansion.
DO_ALLOW ///< Allow singleton expansion.
};
/// \brief The function \ref dip::Image::ReForge takes this option to control how to handle protected images.
enum class DIP_NO_EXPORT AcceptDataTypeChange {
DONT_ALLOW, ///< Do not allow data type change, the output image is always of the requested type.
DO_ALLOW ///< Allow data type change, if the output image is protected, it will be used as is.
};
/// \brief The function \ref dip::Image::Crop takes this option to control which pixels are taken.
enum class DIP_NO_EXPORT CropLocation {
CENTER, ///< The pixel at the origin of the input image is also at the origin in the output image.
MIRROR_CENTER, ///< Same as `CENTER`, but for even-sized images, the origin is presumed to be left of center, rather than right of center.
TOP_LEFT, ///< The corner of the image at coordinates {0,0,0...} is kept in the corner.
BOTTOM_RIGHT, ///< The corner of the image opposite that of `TOP_LEFT` is kept in the corner.
};
/// \brief Determines which properties to compare.
///
/// Implicitly casts to \ref dip::Option::CmpPropFlags. Combine constants together with the `+` operator.
enum class DIP_NO_EXPORT CmpPropEnumerator {
DataType, ///< Compares data type
Dimensionality, ///< Compares number of dimensions
Sizes, ///< Compares image size
Strides, ///< Compares image strides
TensorShape, ///< Compares tensor size and shape
TensorElements, ///< Compares number of tensor elements
TensorStride, ///< Compares tensor stride
ColorSpace, ///< Compares color space
PixelSize ///< Compares pixel size
};
/// \class dip::Option::CmpPropFlags
/// \brief Determines which properties to compare. Combines multiple \ref dip::Option::CmpPropEnumerator values,
/// predefined values are in \ref CmpProp.
DIP_DECLARE_OPTIONS( CmpPropEnumerator, CmpPropFlags )
/// \brief Namespace to emulate an enumerator, contains values
namespace CmpProp {
/// \brief \ref CmpPropEnumerator::DataType.
constexpr CmpPropFlags DataType = CmpPropEnumerator::DataType;
/// \brief \ref CmpPropEnumerator::Dimensionality.
constexpr CmpPropFlags Dimensionality = CmpPropEnumerator::Dimensionality;
/// \brief \ref CmpPropEnumerator::Sizes.
constexpr CmpPropFlags Sizes = CmpPropEnumerator::Sizes;
/// \brief \ref CmpPropEnumerator::Strides.
constexpr CmpPropFlags Strides = CmpPropEnumerator::Strides;
/// \brief \ref CmpPropEnumerator::TensorShape.
constexpr CmpPropFlags TensorShape = CmpPropEnumerator::TensorShape;
/// \brief \ref CmpPropEnumerator::TensorElements.
constexpr CmpPropFlags TensorElements = CmpPropEnumerator::TensorElements;
/// \brief \ref CmpPropEnumerator::TensorStride.
constexpr CmpPropFlags TensorStride = CmpPropEnumerator::TensorStride;
/// \brief \ref CmpPropEnumerator::ColorSpace.
constexpr CmpPropFlags ColorSpace = CmpPropEnumerator::ColorSpace;
/// \brief \ref CmpPropEnumerator::PixelSize.
constexpr CmpPropFlags PixelSize = CmpPropEnumerator::PixelSize;
/// \brief \ref Sizes + \ref TensorElements.
constexpr CmpPropFlags AllSizes = Sizes + TensorElements;
/// \brief \ref DataType + \ref Sizes + \ref TensorElements.
constexpr CmpPropFlags Samples = DataType + Sizes + TensorElements;
/// \brief \ref DataType + \ref Sizes + \ref TensorShape.
constexpr CmpPropFlags Shape = DataType + Sizes + TensorShape;
/// \brief \ref Shape + \ref Strides + \ref TensorStride.
constexpr CmpPropFlags Full = Shape + Strides + TensorStride;
/// \brief \ref Shape + \ref ColorSpace + \ref PixelSize.
constexpr CmpPropFlags All = Shape + ColorSpace + PixelSize;
}
} // namespace Option
/// \brief Represents the result of a 2D regression analysis: $y = a + bx$.
struct RegressionParameters {
dfloat intercept = 0.0; ///< intercept, $a$.
dfloat slope = 0.0; ///< slope, $b$.
};
/// \endgroup
} // namespace dip
namespace std {
// Template specialization of `std::max` for `dip::bin` types
// Note that we cannot do `return a | b;` because std::max needs to return a reference.
template<>
inline dip::bin const& max( dip::bin const& a, dip::bin const& b ) {
return a ? a : b;
}
// Template specialization of `std::min` for `dip::bin` types
template<>
inline dip::bin const& min( dip::bin const& a, dip::bin const& b ) {
return a ? b : a;
}
} // namespace std
#endif // DIP_TYPES_H
| 41.975524 | 164 | 0.681799 | [
"object",
"shape",
"vector"
] |
ea55a10ce0bdc77de5aaf23f89a5ff0ea766c50a | 5,565 | h | C | EnvironmentModule/EC_SkyDome.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | null | null | null | EnvironmentModule/EC_SkyDome.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | null | null | null | EnvironmentModule/EC_SkyDome.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | 1 | 2021-09-04T12:37:34.000Z | 2021-09-04T12:37:34.000Z | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef EC_SKYDOME_H_
#define EC_SKYDOME_H_
#include "IComponent.h"
#include "IAttribute.h"
#include "Declare_EC.h"
#include "CoreTypes.h"
#include "RexTypes.h"
#include "Quaternion.h"
#include <QVariant>
/// Makes the entity a SkyDome
/**
<table class="header">
<tr>
<td>
<h2>SkyDome Dome</h2>
Registered by Enviroment::EnvironmentModule.
<h3> Using component to syncronize sky in Taiga </h3>
Currently (not in Tundra) EC_SkyDome component can be used to syncronize sky in Taiga worlds. This can be done
so that user creates entity and sets entity EC_Name-component. If this component name is set as "SkyEnvironment" our current implementation
will create automagically a EC_SkyBox-component on it. This component is now usable for every users and all changes on it will be transfered
to all users. This syncronized sky plane component can also edit through environment editor (in world tools). Currently Caelum must be disabled
before these features can be used.
<b>Attributes</b>:
<ul>
<li> QString : materialAttr.
<div> Defines sky material </div>
<li> QString : textureAttr.
<div> Sky texture which is used in given material </div>
<li> float : distanceAttr.
<div> Distance in world coordinates from the camera to each plane of the box the dome is rendered on. </div>
<li> float : curvatureAttr.
<div>
The curvature of the dome. Good values are between 2 and 65. Higher values are more curved leading to a smoother effect,
lower values are less curved meaning more distortion at the horizons but a better distance effect. </div>
<li> float : tilingAttr.
<div> How many times to tile the texture(s) across the dome. </div>
<li> int : xSegmentsAttr.
<div> The number of segments to the dome in the x direction. </div>
<li> int : ySegmentsAttr.
<div> The number of segments to the dome in the y direction. </div>
<li> int : ySegmentsKeepAttr.
<div> </div>
<li> bool : drawFirstAttr.
<div> If true, the dome is drawn before all other geometry in the scene, without updating the depth buffer </div>
<li> Quaternion : orientationAttr
<div> Optional parameter to specify the orientation of the dome </div>
</ul>
</table>
*/
namespace OgreRenderer
{
class Renderer;
typedef boost::shared_ptr<Renderer> RendererPtr;
typedef boost::weak_ptr<Renderer> RendererWeakPtr;
}
namespace Environment
{
class EC_SkyDome : public IComponent
{
Q_OBJECT
DECLARE_EC(EC_SkyDome);
public:
virtual ~EC_SkyDome();
virtual bool IsSerializable() const { return true; }
/// Name of sky material
DEFINE_QPROPERTY_ATTRIBUTE(QString, materialAttr);
Q_PROPERTY(QString materialAttr READ getmaterialAttr WRITE setmaterialAttr);
/// Defines sky material texture
DEFINE_QPROPERTY_ATTRIBUTE(QString, textureAttr);
Q_PROPERTY(QString textureAttr READ gettextureAttr WRITE settextureAttr);
/// Defines distance in world coordinates from the camera to each plane of the box the dome is rendered on.
DEFINE_QPROPERTY_ATTRIBUTE(float, distanceAttr);
Q_PROPERTY(float distanceAttr READ getdistanceAttr WRITE setdistanceAttr);
/// The curvature of the dome.
/** Good values are between 2 and 65. Higher values are more curved leading to a smoother effect,
lower values are less curved meaning more distortion at the horizons but a better distance effect.
*/
DEFINE_QPROPERTY_ATTRIBUTE(float, curvatureAttr);
Q_PROPERTY(float curvatureAttr READ getcurvatureAttr WRITE setcurvatureAttr);
/// Defines how many times to tile the texture(s) across the dome.
DEFINE_QPROPERTY_ATTRIBUTE(float, tilingAttr);
Q_PROPERTY(float tilingAttr READ gettilingAttr WRITE settilingAttr);
DEFINE_QPROPERTY_ATTRIBUTE(int, xSegmentsAttr);
Q_PROPERTY(int xSegmentsAttr READ getxSegmentsAttr WRITE setxSegmentsAttr);
DEFINE_QPROPERTY_ATTRIBUTE(int, ySegmentsAttr);
Q_PROPERTY(int ySegmentsAttr READ getySegmentsAttr WRITE setySegmentsAttr);
/// Optional parameter to specify the orientation of the dome
DEFINE_QPROPERTY_ATTRIBUTE(Quaternion, orientationAttr);
Q_PROPERTY(Quaternion orientationAttr READ getorientationAttr WRITE setorientationAttr);
DEFINE_QPROPERTY_ATTRIBUTE(int, ySegmentsKeepAttr);
Q_PROPERTY(int ySegmentsKeepAttr READ getySegmentsKeepAttr WRITE setySegmentsKeepAttr);
/// If true, the dome is drawn before all other geometry in the scene, without updating the depth buffer
DEFINE_QPROPERTY_ATTRIBUTE(bool, drawFirstAttr);
Q_PROPERTY(bool drawFirstAttr READ getdrawFirstAttr WRITE setdrawFirstAttr);
void DisableSky();
private:
///Constuctor.
/* @param module Module where component belongs.
*/
explicit EC_SkyDome(IModule *module);
void CreateSky();
void SetTexture();
QString lastMaterial_;
float lastDistance_;
bool lastDrawFirst_;
Quaternion lastOrientation_;
QString lastTexture_;
float lastTiling_;
float lastCurvature_;
int lastxSegments_;
int lastySegments_;
int lastySegmentsKeep_;
/// Renderer
OgreRenderer::RendererWeakPtr renderer_;
private slots:
/// Called If some of the attributes has been changed.
void AttributeUpdated(IAttribute* attribute);
};
}
#endif // EC_SkyDome_H_
| 36.611842 | 144 | 0.722013 | [
"geometry"
] |
ea5973fda4907130f0b4508d550f8e00e21ca073 | 11,989 | c | C | src/string.c | dargueta/metalc | a4c6cfbb7ceebf41c83b943fd05ecd1d1dcad6ce | [
"BSD-3-Clause"
] | null | null | null | src/string.c | dargueta/metalc | a4c6cfbb7ceebf41c83b943fd05ecd1d1dcad6ce | [
"BSD-3-Clause"
] | null | null | null | src/string.c | dargueta/metalc | a4c6cfbb7ceebf41c83b943fd05ecd1d1dcad6ce | [
"BSD-3-Clause"
] | null | null | null | #include "metalc/errno.h"
#include "metalc/metalc.h"
#include "metalc/stdio.h"
#include "metalc/stdlib.h"
#include "metalc/string.h"
#include "metalc/locale.h"
/* These are copied and pasted from the Linux headers on Ubuntu 19.10. */
static const char *ERROR_STRINGS[mclib__MAX_ERRNO] = {
"Success",
"Operation not permitted",
"No such file or directory",
"No such process",
"Interrupted system call",
"Input/output error",
"No such device or address",
"Argument list too long",
"Exec format error",
"Bad file descriptor",
"No child processes",
"Resource temporarily unavailable",
"Cannot allocate memory",
"Permission denied",
"Bad address",
"Block device required",
"Device or resource busy",
"File exists",
"Invalid cross-device link",
"No such device",
"Not a directory",
"Is a directory",
"Invalid argument",
"Too many open files in system",
"Too many open files",
"Inappropriate ioctl for device",
"Text file busy",
"File too large",
"No space left on device",
"Illegal seek",
"Read-only file system",
"Too many links",
"Broken pipe",
"Numerical argument out of domain",
"Numerical result out of range",
"Resource deadlock avoided",
"File name too long",
"No locks available",
"Function not implemented",
"Directory not empty",
"Too many levels of symbolic links",
"Unknown error 41",
"No message of desired type",
"Identifier removed",
"Channel number out of range",
"Level 2 not synchronized",
"Level 3 halted",
"Level 3 reset",
"Link number out of range",
"Protocol driver not attached",
"No CSI structure available",
"Level 2 halted",
"Invalid exchange",
"Invalid request descriptor",
"Exchange full",
"No anode",
"Invalid request code",
"Invalid slot",
"Bad font file format",
"Device not a stream",
"No data available",
"Timer expired",
"Out of streams resources",
"Machine is not on the network",
"Package not installed",
"Object is remote",
"Link has been severed",
"Advertise error",
"Srmount error",
"Communication error on send",
"Protocol error",
"Multihop attempted",
"RFS specific error",
"Bad message",
"Value too large for defined data type",
"Name not unique on network",
"File descriptor in bad state",
"Remote address changed",
"Cannot access a needed shared library",
"Accessing a corrupted shared library",
".lib section in a.out corrupted",
"Attempting to link in too many shared libraries",
"Cannot exec a shared library directly",
"Invalid or incomplete multibyte or wide character",
"Interrupted system call should be restarted",
"Streams pipe error",
"Too many users",
"Socket operation on non-socket",
"Destination address required",
"Message too long",
"Protocol wrong type for socket",
"Protocol not available",
"Protocol not supported",
"Socket type not supported",
"Operation not supported",
"Protocol family not supported",
"Address family not supported by protocol",
"Address already in use",
"Cannot assign requested address",
"Network is down",
"Network is unreachable",
"Network dropped connection on reset",
"Software caused connection abort",
"Connection reset by peer",
"No buffer space available",
"Transport endpoint is already connected",
"Transport endpoint is not connected",
"Cannot send after transport endpoint shutdown",
"Too many references: cannot splice",
"Connection timed out",
"Connection refused",
"Host is down",
"No route to host",
"Operation already in progress",
"Operation now in progress",
"Stale file handle",
"Structure needs cleaning",
"Not a XENIX named type file",
"No XENIX semaphores available",
"Is a named type file",
"Remote I/O error",
"Disk quota exceeded",
"No medium found",
"Wrong medium type",
"Operation canceled",
"Required key not available",
"Key has expired",
"Key has been revoked",
"Key was rejected by service",
"Owner died",
"State not recoverable",
"Operation not possible due to RF-kill",
"Memory page has hardware error",
};
void *memchr(const void *ptr, int value, size_t num) {
const unsigned char *p;
for (p = ptr; num != 0; --num, ++p) {
if (*p == (unsigned char)value)
return (void *)p;
}
return NULL;
}
cstdlib_implement(memchr);
int memcmp(const void *ptr1, const void *ptr2, size_t num) {
const signed char *left, *right;
int diff;
diff = 0;
left = ptr1;
right = ptr2;
for (; (num > 0) && (diff == 0); ++left, ++right, --num)
diff = *left - *right;
return diff;
}
cstdlib_implement(memcmp);
void *memcpy(void *destination, const void *source, size_t num) {
char *p_dest;
const char *p_src;
p_dest = destination;
p_src = source;
for (; num > 0; --num)
*p_dest++ = *p_src++;
return destination;
}
cstdlib_implement(memcpy);
void *memmove(void *destination, const void *source, size_t num) {
char *p_dest;
const char *p_src;
if ((destination == source) || (num == 0))
return destination;
else if (destination < source) {
/* Moving source backwards. We can copy from the beginning of the source
* onwards. */
p_dest = destination;
p_src = source;
for (; num > 0; --num)
*p_dest++ = *p_src++;
}
else {
/* Moving source forwards. To avoid stomping on the end of the source
* we need to copy from the end of the source back to the beginning. */
p_dest = (char *)destination + num - 1;
p_src = (char *)source + num - 1;
for (; num > 0; --num)
*p_dest-- = *p_src--;
}
return destination;
}
cstdlib_implement(memmove);
void *memset(void *ptr, int value, size_t num) {
unsigned char *p_dest;
for (p_dest = (unsigned char *)ptr; num > 0; --num)
*p_dest++ = (unsigned char)value;
return ptr;
}
cstdlib_implement(memset);
char *strcat(char *destination, const char *source) {
return strcpy(strchr(destination, 0), source);
}
cstdlib_implement(strcat);
char *strchr(const char *str, int character) {
do {
if (*str == (char)character)
return (char *)str;
} while (*str++ != '\0');
return NULL;
}
cstdlib_implement(strchr);
int strcmp(const char *str1, const char *str2) {
int diff = 0;
for (; (*str1 != '\0') && (*str2 != '\0'); ++str1, ++str2) {
diff = *str1 - *str2;
if (diff != 0)
return diff;
}
return *(signed char *)str1 - *(signed char *)str2;
}
cstdlib_implement(strcmp);
int strcoll(const char *str1, const char *str2) {
return mcinternal_ptr_current_coll->f_strcoll(str1, str2);
}
cstdlib_implement(strcoll);
char *strcpy(char *destination, const char *source) {
char *p_dest = destination;
do {
*p_dest++ = *source;
} while (*source++ != '\0');
return destination;
}
cstdlib_implement(strcpy);
size_t strcspn(const char *str1, const char *str2) {
size_t span;
/**
* @todo There must be a better way of implementing this than O(n^2).
*/
for (span = 0; *str1 != '\0'; ++str1, ++span) {
if (strchr(str2, (int)*str1))
return span;
}
return span;
}
cstdlib_implement(strcspn);
char *strerror(int errnum) {
static char buffer[128];
if ((errnum >= 0) && (errnum < mclib__MAX_ERRNO))
return strcpy(buffer, ERROR_STRINGS[errnum]);
sprintf(buffer, "Unknown error %d", errnum);
return buffer;
}
cstdlib_implement(strerror);
size_t strlen(const char *str) {
size_t length = 0;
while (str[length] != '\0')
++length;
return length;
}
cstdlib_implement(strlen);
char *strncat(char *destination, const char *source, size_t num) {
char *p_dest;
/* Return early if `num` is 0 to avoid a potentially expensive call to
* strlen(). */
if (num == 0)
return destination;
p_dest = destination + strlen(destination);
for (; (num > 0) && (*source != '\0'); --num)
*p_dest++ = *source++;
*p_dest = '\0';
return destination;
}
cstdlib_implement(strncat);
int strncmp(const char *str1, const char *str2, size_t num) {
int diff = 0;
while ((num > 0) && (*str1 != '\0') && (*str2 != '\0')) {
diff = *str1 - *str2;
if (diff != 0)
return diff;
--num;
++str1;
++str2;
}
/* When we get out here either 1) num is 0 and all characters matched so far,
* or 2) num > 0, and we hit the end of one or both strings. In case 1 we
* want to return 0, otherwise compare the last characters. */
if (num == 0)
return 0;
return (int)(*str1 - *str2);
}
cstdlib_implement(strncmp);
char *strncpy(char *destination, const char *source, size_t num) {
char *p_dest = destination;
for (; (num > 0) && (*source != '\0'); --num)
*p_dest++ = *source++;
for (; num > 0; --num)
*p_dest++ = '\0';
return destination;
}
cstdlib_implement(strncpy);
char *strpbrk(const char *str1, const char *str2) {
size_t span = strcspn(str1, str2);
if (str1[span] == '\0')
return NULL;
return (char *)str1 + span;
}
cstdlib_implement(strpbrk);
char *strrchr(const char *str, int character) {
const char *p_end;
for (p_end = str + strlen(str); p_end != str; --p_end) {
if (*p_end == (char)character)
return (char *)p_end;
}
return NULL;
}
cstdlib_implement(strrchr);
size_t strspn(const char *str1, const char *str2) {
size_t span = 0;
for (; *str1 != '\0'; ++str1, ++span) {
if (strchr(str2, *str1) == NULL)
break;
}
return span;
}
cstdlib_implement(strspn);
char *strstr(const char *str, const char *substr) {
size_t substr_length = strlen(substr);
for (; *str != '\0'; ++str) {
if (strncmp(str, substr, substr_length) == 0)
return (char *)str;
}
return NULL;
}
cstdlib_implement(strstr);
char *strtok(char *str, const char *delimiters) {
size_t token_length;
static char *start = NULL;
if (str != NULL)
start = str;
if (start == NULL)
/* Edge case: `str` is null and so is `start`. Treat this as an empty
* string with no tokens. */
return NULL;
if (*start == '\0')
return NULL;
/* Search for the first character in `start` that *isn't* a delimiter. If we
* hit EOS, bail and return NULL forevermore. */
for (; *start != '\0'; ++start) {
if (strchr(delimiters, *start) == NULL)
break;
}
/* Hit the end of the string so there are no more tokens. Bail. */
if (*start == '\0')
return NULL;
/* else: Found the beginning of the next token. Now search for the next
* delimiter. */
token_length = strcspn(start, delimiters);
/* Found the first delimiter or hit EOS. Stomp over it with a null. */
start[token_length] = '\0';
return start;
}
cstdlib_implement(strtok);
size_t strxfrm(char *destination, const char *source, size_t num) {
return mcinternal_ptr_current_coll->f_strxfrm(destination, source, num);
}
cstdlib_implement(strxfrm);
size_t strcpy_and_update_buffer(const char *source, char **buffer) {
size_t buffer_size = strlen(source);
strcpy(*buffer, source);
*buffer += buffer_size;
return buffer_size;
}
size_t strncpy_and_update_buffer(const char *source, char **buffer, size_t n) {
size_t source_size, buffer_size;
source_size = strlen(source);
buffer_size = (source_size < n) ? source_size : n;
strncpy(*buffer, source, n);
*buffer += buffer_size;
return buffer_size;
}
| 24.873444 | 81 | 0.610393 | [
"object"
] |
ea59bda3bde8f1015301b9b48330104347ea7b1b | 1,818 | c | C | clone/lonely/tenglongjian.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 69 | 2018-03-08T18:24:44.000Z | 2022-02-24T13:43:53.000Z | clone/lonely/tenglongjian.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 3 | 2019-04-24T12:21:19.000Z | 2021-03-28T23:34:58.000Z | clone/lonely/tenglongjian.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 33 | 2017-12-23T05:06:58.000Z | 2021-08-16T02:42:59.000Z | #include <weapon.h>
#include <ansi.h>
inherit SWORD;
void create()
{
set_name(HIY "腾龙剑" NOR, ({ "tenglong jian", "tenglong", "jian", "sword" }) );
set_weight(5800);
if (clonep())
destruct(this_object());
else {
set("long", HIY "一柄锋利的长剑,剑身宛如流水,隐隐漾着青光。\n" NOR);
set("unit", "柄");
set("value", 800000);
set("no_sell", "…嗯…这剑倒是口好剑,不过这价钱不好开,我看"
"还是算了吧。");
set("material", "steel");
set("wield_msg", HIY "$N" HIY "唰的抽出一柄利剑握在手中,剑"
"身青光荡漾,寒气逼人。\n" NOR);
set("unwield_msg", HIY "$N" HIY "空舞了数个剑花,将腾龙宝剑"
"插回腰间。\n" NOR);
set("stable", 100);
}
init_sword(120);
setup();
}
mixed hit_ob(object me, object victim, int damage_bonus)
{
int n;
// int my_exp,ob_exp;
if (me->query_skill("sword") < 160)
return damage_bonus / 2;
if (me->query_skill_mapped("sword") != "miaojia-jian" &&
me->query_skill_mapped("sword") != "tianlong-jian")
return damage_bonus / 2;
switch (random(12))
{
case 0:
if (! victim->is_busy())
victim->start_busy(me->query_skill("sword") / 16 + 2);
return HIY "$N" HIY "手中腾龙剑一颤,漾起层层剑光,顿时将$n"
HIY "逼退数步!\n" NOR;
case 1:
n = me->query_skill("sword");
victim->receive_damage("qi", n * 3 / 4, me);
victim->receive_wound("qi", n * 3 / 4, me);
return HIY "只听得破空声骤响,$N" HIY "手中腾龙剑岚转不定,向"
"$n" HIY "连刺数剑!\n" NOR;
}
return damage_bonus;
} | 31.894737 | 85 | 0.445545 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.