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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e6c36000edc6b02fad8705956d6825d0775dd02 | 2,259 | h | C | ui/ozone/platform/dri/gpu_platform_support_host_gbm.h | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/ozone/platform/dri/gpu_platform_support_host_gbm.h | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/ozone/platform/dri/gpu_platform_support_host_gbm.h | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_OZONE_PLATFORM_DRI_GPU_PLATFORM_SUPPORT_HOST_GBM_H_
#define UI_OZONE_PLATFORM_DRI_GPU_PLATFORM_SUPPORT_HOST_GBM_H_
#include <queue>
#include <vector>
#include "base/observer_list.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/ozone/platform/dri/hardware_cursor_delegate.h"
#include "ui/ozone/public/gpu_platform_support_host.h"
class SkBitmap;
namespace gfx {
class Point;
}
namespace ui {
class ChannelObserver;
class GpuPlatformSupportHostGbm : public GpuPlatformSupportHost,
public HardwareCursorDelegate,
public IPC::Sender {
public:
GpuPlatformSupportHostGbm();
virtual ~GpuPlatformSupportHostGbm();
void RegisterHandler(GpuPlatformSupportHost* handler);
void UnregisterHandler(GpuPlatformSupportHost* handler);
void AddChannelObserver(ChannelObserver* observer);
void RemoveChannelObserver(ChannelObserver* observer);
// GpuPlatformSupportHost:
virtual void OnChannelEstablished(int host_id, IPC::Sender* sender) OVERRIDE;
virtual void OnChannelDestroyed(int host_id) OVERRIDE;
// IPC::Listener:
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
// IPC::Sender:
virtual bool Send(IPC::Message* message) OVERRIDE;
// HardwareCursorDelegate:
virtual void SetHardwareCursor(gfx::AcceleratedWidget widget,
const SkBitmap& bitmap,
const gfx::Point& location) OVERRIDE;
virtual void MoveHardwareCursor(gfx::AcceleratedWidget widget,
const gfx::Point& location) OVERRIDE;
private:
int host_id_;
IPC::Sender* sender_;
std::vector<GpuPlatformSupportHost*> handlers_;
// If messages are sent before the channel is created, store the messages and
// delay sending them until the channel is created. These messages are stored
// in |queued_messaged_|.
std::queue<IPC::Message*> queued_messages_;
ObserverList<ChannelObserver> channel_observers_;
};
} // namespace ui
#endif // UI_OZONE_GPU_GPU_PLATFORM_SUPPORT_HOST_GBM_H_
| 32.271429 | 79 | 0.733953 | [
"vector"
] |
2e71ad36a4f8cfbbdcfa54e0d2db541313b02246 | 28,416 | h | C | src/gpu/GrFragmentProcessor.h | clarkezone/skia | 2c2db2762809826df87e83755199db72b320685d | [
"BSD-3-Clause"
] | null | null | null | src/gpu/GrFragmentProcessor.h | clarkezone/skia | 2c2db2762809826df87e83755199db72b320685d | [
"BSD-3-Clause"
] | null | null | null | src/gpu/GrFragmentProcessor.h | clarkezone/skia | 2c2db2762809826df87e83755199db72b320685d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrFragmentProcessor_DEFINED
#define GrFragmentProcessor_DEFINED
#include "src/gpu/GrCoordTransform.h"
#include "src/gpu/GrProcessor.h"
#include "src/gpu/ops/GrOp.h"
class GrGLSLFragmentProcessor;
class GrPaint;
class GrPipeline;
class GrProcessorKeyBuilder;
class GrShaderCaps;
class GrSwizzle;
/** Provides custom fragment shader code. Fragment processors receive an input color (half4) and
produce an output color. They may reference textures and uniforms. They may use
GrCoordTransforms to receive a transformation of the local coordinates that map from local space
to the fragment being processed.
*/
class GrFragmentProcessor : public GrProcessor {
public:
class TextureSampler;
/**
* In many instances (e.g. SkShader::asFragmentProcessor() implementations) it is desirable to
* only consider the input color's alpha. However, there is a competing desire to have reusable
* GrFragmentProcessor subclasses that can be used in other scenarios where the entire input
* color is considered. This function exists to filter the input color and pass it to a FP. It
* does so by returning a parent FP that multiplies the passed in FPs output by the parent's
* input alpha. The passed in FP will not receive an input color.
*/
static std::unique_ptr<GrFragmentProcessor> MulChildByInputAlpha(
std::unique_ptr<GrFragmentProcessor> child);
/**
* Like MulChildByInputAlpha(), but reverses the sense of src and dst. In this case, return
* the input modulated by the child's alpha. The passed in FP will not receive an input color.
*
* output = input * child.a
*/
static std::unique_ptr<GrFragmentProcessor> MulInputByChildAlpha(
std::unique_ptr<GrFragmentProcessor> child);
/**
* This assumes that the input color to the returned processor will be unpremul and that the
* passed processor (which becomes the returned processor's child) produces a premul output.
* The result of the returned processor is a premul of its input color modulated by the child
* processor's premul output.
*/
static std::unique_ptr<GrFragmentProcessor> MakeInputPremulAndMulByOutput(
std::unique_ptr<GrFragmentProcessor>);
/**
* Returns a parent fragment processor that adopts the passed fragment processor as a child.
* The parent will ignore its input color and instead feed the passed in color as input to the
* child.
*/
static std::unique_ptr<GrFragmentProcessor> OverrideInput(std::unique_ptr<GrFragmentProcessor>,
const SkPMColor4f&,
bool useUniform = true);
/**
* Returns a fragment processor that premuls the input before calling the passed in fragment
* processor.
*/
static std::unique_ptr<GrFragmentProcessor> PremulInput(std::unique_ptr<GrFragmentProcessor>);
/**
* Returns a fragment processor that calls the passed in fragment processor, and then swizzles
* the output.
*/
static std::unique_ptr<GrFragmentProcessor> SwizzleOutput(std::unique_ptr<GrFragmentProcessor>,
const GrSwizzle&);
/**
* Returns a fragment processor that calls the passed in fragment processor, and then ensures
* the output is a valid premul color by clamping RGB to [0, A].
*/
static std::unique_ptr<GrFragmentProcessor> ClampPremulOutput(
std::unique_ptr<GrFragmentProcessor>);
/**
* Returns a fragment processor that runs the passed in array of fragment processors in a
* series. The original input is passed to the first, the first's output is passed to the
* second, etc. The output of the returned processor is the output of the last processor of the
* series.
*
* The array elements with be moved.
*/
static std::unique_ptr<GrFragmentProcessor> RunInSeries(std::unique_ptr<GrFragmentProcessor>[],
int cnt);
/**
* Makes a copy of this fragment processor that draws equivalently to the original.
* If the processor has child processors they are cloned as well.
*/
virtual std::unique_ptr<GrFragmentProcessor> clone() const = 0;
GrGLSLFragmentProcessor* createGLSLInstance() const;
void getGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const {
this->onGetGLSLProcessorKey(caps, b);
for (int i = 0; i < fChildProcessors.count(); ++i) {
fChildProcessors[i]->getGLSLProcessorKey(caps, b);
}
}
int numTextureSamplers() const { return fTextureSamplerCnt; }
const TextureSampler& textureSampler(int i) const;
int numCoordTransforms() const { return fCoordTransforms.count(); }
/** Returns the coordinate transformation at index. index must be valid according to
numCoordTransforms(). */
const GrCoordTransform& coordTransform(int index) const { return *fCoordTransforms[index]; }
GrCoordTransform& coordTransform(int index) { return *fCoordTransforms[index]; }
const SkTArray<GrCoordTransform*, true>& coordTransforms() const {
return fCoordTransforms;
}
int numChildProcessors() const { return fChildProcessors.count(); }
GrFragmentProcessor& childProcessor(int index) { return *fChildProcessors[index]; }
const GrFragmentProcessor& childProcessor(int index) const { return *fChildProcessors[index]; }
SkDEBUGCODE(bool isInstantiated() const;)
/** Do any of the coord transforms for this processor require local coords? */
bool usesLocalCoords() const {
// If the processor is sampled with explicit coords then we do not need to apply the
// coord transforms in the vertex shader to the local coords.
return SkToBool(fFlags & kHasCoordTransforms_Flag) &&
SkToBool(fFlags & kCoordTransformsApplyToLocalCoords_Flag);
}
bool coordTransformsApplyToLocalCoords() const {
return SkToBool(fFlags & kCoordTransformsApplyToLocalCoords_Flag);
}
void setSampledWithExplicitCoords(bool value) {
if (value) {
fFlags &= ~kCoordTransformsApplyToLocalCoords_Flag;
} else {
fFlags |= kCoordTransformsApplyToLocalCoords_Flag;
}
for (auto& child : fChildProcessors) {
child->setSampledWithExplicitCoords(value);
}
}
/**
* A GrDrawOp may premultiply its antialiasing coverage into its GrGeometryProcessor's color
* output under the following scenario:
* * all the color fragment processors report true to this query,
* * all the coverage fragment processors report true to this query,
* * the blend mode arithmetic allows for it it.
* To be compatible a fragment processor's output must be a modulation of its input color or
* alpha with a computed premultiplied color or alpha that is in 0..1 range. The computed color
* or alpha that is modulated against the input cannot depend on the input's alpha. The computed
* value cannot depend on the input's color channels unless it unpremultiplies the input color
* channels by the input alpha.
*/
bool compatibleWithCoverageAsAlpha() const {
return SkToBool(fFlags & kCompatibleWithCoverageAsAlpha_OptimizationFlag);
}
/**
* If this is true then all opaque input colors to the processor produce opaque output colors.
*/
bool preservesOpaqueInput() const {
return SkToBool(fFlags & kPreservesOpaqueInput_OptimizationFlag);
}
/**
* Tests whether given a constant input color the processor produces a constant output color
* (for all fragments). If true outputColor will contain the constant color produces for
* inputColor.
*/
bool hasConstantOutputForConstantInput(SkPMColor4f inputColor, SkPMColor4f* outputColor) const {
if (fFlags & kConstantOutputForConstantInput_OptimizationFlag) {
*outputColor = this->constantOutputForConstantInput(inputColor);
return true;
}
return false;
}
bool hasConstantOutputForConstantInput() const {
return SkToBool(fFlags & kConstantOutputForConstantInput_OptimizationFlag);
}
/** Returns true if this and other processor conservatively draw identically. It can only return
true when the two processor are of the same subclass (i.e. they return the same object from
from getFactory()).
A return value of true from isEqual() should not be used to test whether the processor would
generate the same shader code. To test for identical code generation use getGLSLProcessorKey
*/
bool isEqual(const GrFragmentProcessor& that) const;
void visitProxies(const GrOp::VisitProxyFunc& func);
// A pre-order traversal iterator over a hierarchy of FPs. It can also iterate over all the FP
// hierarchies rooted in a GrPaint, GrProcessorSet, or GrPipeline. For these collections it
// iterates the tree rooted at each color FP and then each coverage FP.
//
// Iter is the non-const version and CIter is the const version.
//
// An iterator is constructed from one of the srcs and used like this:
// for (GrFragmentProcessor::Iter iter(pipeline); iter; ++iter) {
// GrFragmentProcessor& fp = *iter;
// }
// The exit test for the loop is using Iter's operator bool().
// To use a range-for loop instead see CIterRange below.
class Iter;
class CIter;
// Used to implement a range-for loop using CIter. Src is one of GrFragmentProcessor,
// GrPaint, GrProcessorSet, or GrPipeline. Type aliases for these defined below.
// Example usage:
// for (const auto& fp : GrFragmentProcessor::PaintRange(paint)) {
// if (fp.usesLocalCoords()) {
// ...
// }
// }
template <typename Src> class CIterRange;
// Like CIterRange but non const and only constructable from GrFragmentProcessor. This could
// support GrPaint as it owns non-const FPs but no need for it as of now.
// for (auto& fp0 : GrFragmentProcessor::IterRange(fp)) {
// ...
// }
class IterRange;
// We would use template deduction guides for Iter/CIter but for:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79501
// Instead we use these specialized type aliases to make it prettier
// to construct Iters for particular sources of FPs.
using FPCRange = CIterRange<GrFragmentProcessor>;
using PaintCRange = CIterRange<GrPaint>;
// Implementation details for iterators that walk an array of Items owned by a set of FPs.
using CountFn = int (GrFragmentProcessor::*)() const;
// Defined GetFn to be a member function that returns an Item by index. The function itself is
// const if Item is a const type and non-const if Item is non-const.
template <typename Item, bool IsConst = std::is_const<Item>::value> struct GetT;
template <typename Item> struct GetT<Item, false> {
using GetFn = Item& (GrFragmentProcessor::*)(int);
};
template <typename Item> struct GetT<Item, true> {
using GetFn = const Item& (GrFragmentProcessor::*)(int) const;
};
template <typename Item> using GetFn = typename GetT<Item>::GetFn;
// This is an iterator over the Items owned by a (collection of) FP. CountFn is a FP member that
// gets the number of Items owned by each FP and GetFn is a member that gets them by index.
template <typename Item, CountFn Count, GetFn<Item> Get> class FPItemIter;
// Loops over all the GrCoordTransforms owned by GrFragmentProcessors. The possible sources for
// the iteration are the same as those for Iter and the FPs are walked in the same order as
// Iter. This provides access to the coord transform and the FP that owns it. Example usage:
// for (GrFragmentProcessor::CoordTransformIter iter(pipeline); iter; ++iter) {
// // transform is const GrCoordTransform& and owningFP is const GrFragmentProcessor&.
// auto [transform, owningFP] = *iter;
// ...
// }
// See the ranges below to make this simpler a la range-for loops.
using CoordTransformIter = FPItemIter<const GrCoordTransform,
&GrFragmentProcessor::numCoordTransforms,
&GrFragmentProcessor::coordTransform>;
// Same as CoordTransformIter but for TextureSamplers:
// for (GrFragmentProcessor::TextureSamplerIter iter(pipeline); iter; ++iter) {
// // TextureSamplerIter is const GrFragmentProcessor::TextureSampler& and
// // owningFP is const GrFragmentProcessor&.
// auto [sampler, owningFP] = *iter;
// ...
// }
// See the ranges below to make this simpler a la range-for loops.
using TextureSamplerIter = FPItemIter<const TextureSampler,
&GrFragmentProcessor::numTextureSamplers,
&GrFragmentProcessor::textureSampler>;
// Implementation detail for using CoordTransformIter and TextureSamplerIter in range-for loops.
template <typename Src, typename ItemIter> class FPItemRange;
// These allow iteration over coord transforms/texture samplers for various FP sources via
// range-for loops. An example usage for looping over the coord transforms in a pipeline:
// for (auto [transform, fp] : GrFragmentProcessor::PipelineCoordTransformRange(pipeline)) {
// ...
// }
// Only the combinations of FP sources and iterable things have been defined but it is easy
// to add more as they become useful. Maybe someday we'll have template argument deduction
// with guides for type aliases and the sources can be removed from the type aliases:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1021r5.html
using PipelineCoordTransformRange = FPItemRange<const GrPipeline, CoordTransformIter>;
using PipelineTextureSamplerRange = FPItemRange<const GrPipeline, TextureSamplerIter>;
using FPTextureSamplerRange = FPItemRange<const GrFragmentProcessor, TextureSamplerIter>;
using ProcessorSetTextureSamplerRange = FPItemRange<const GrProcessorSet, TextureSamplerIter>;
// Not used directly.
using NonConstCoordTransformIter =
FPItemIter<GrCoordTransform, &GrFragmentProcessor::numCoordTransforms,
&GrFragmentProcessor::coordTransform>;
// Iterator over non-const GrCoordTransforms owned by FP and its descendants.
using FPCoordTransformRange = FPItemRange<GrFragmentProcessor, NonConstCoordTransformIter>;
// Sentinel type for range-for using Iter.
class EndIter {};
// Sentinel type for range-for using FPItemIter.
class FPItemEndIter {};
protected:
enum OptimizationFlags : uint32_t {
kNone_OptimizationFlags,
kCompatibleWithCoverageAsAlpha_OptimizationFlag = 0x1,
kPreservesOpaqueInput_OptimizationFlag = 0x2,
kConstantOutputForConstantInput_OptimizationFlag = 0x4,
kAll_OptimizationFlags = kCompatibleWithCoverageAsAlpha_OptimizationFlag |
kPreservesOpaqueInput_OptimizationFlag |
kConstantOutputForConstantInput_OptimizationFlag
};
GR_DECL_BITFIELD_OPS_FRIENDS(OptimizationFlags)
/**
* Can be used as a helper to decide which fragment processor OptimizationFlags should be set.
* This assumes that the subclass output color will be a modulation of the input color with a
* value read from a texture of the passed color type and that the texture contains
* premultiplied color or alpha values that are in range.
*
* Since there are multiple ways in which a sampler may have its coordinates clamped or wrapped,
* callers must determine on their own if the sampling uses a decal strategy in any way, in
* which case the texture may become transparent regardless of the color type.
*/
static OptimizationFlags ModulateForSamplerOptFlags(SkAlphaType alphaType, bool samplingDecal) {
if (samplingDecal) {
return kCompatibleWithCoverageAsAlpha_OptimizationFlag;
} else {
return ModulateForClampedSamplerOptFlags(alphaType);
}
}
// As above, but callers should somehow ensure or assert their sampler still uses clamping
static OptimizationFlags ModulateForClampedSamplerOptFlags(SkAlphaType alphaType) {
if (alphaType == kOpaque_SkAlphaType) {
return kCompatibleWithCoverageAsAlpha_OptimizationFlag |
kPreservesOpaqueInput_OptimizationFlag;
} else {
return kCompatibleWithCoverageAsAlpha_OptimizationFlag;
}
}
GrFragmentProcessor(ClassID classID, OptimizationFlags optimizationFlags)
: INHERITED(classID)
, fFlags(optimizationFlags | kCoordTransformsApplyToLocalCoords_Flag) {
SkASSERT((optimizationFlags & ~kAll_OptimizationFlags) == 0);
}
OptimizationFlags optimizationFlags() const {
return static_cast<OptimizationFlags>(kAll_OptimizationFlags & fFlags);
}
/** Useful when you can't call fp->optimizationFlags() on a base class object from a subclass.*/
static OptimizationFlags ProcessorOptimizationFlags(const GrFragmentProcessor* fp) {
return fp->optimizationFlags();
}
/**
* This allows one subclass to access another subclass's implementation of
* constantOutputForConstantInput. It must only be called when
* hasConstantOutputForConstantInput() is known to be true.
*/
static SkPMColor4f ConstantOutputForConstantInput(const GrFragmentProcessor& fp,
const SkPMColor4f& input) {
SkASSERT(fp.hasConstantOutputForConstantInput());
return fp.constantOutputForConstantInput(input);
}
/**
* Fragment Processor subclasses call this from their constructor to register coordinate
* transformations. Coord transforms provide a mechanism for a processor to receive coordinates
* in their FS code. The matrix expresses a transformation from local space. For a given
* fragment the matrix will be applied to the local coordinate that maps to the fragment.
*
* When the transformation has perspective, the transformed coordinates will have
* 3 components. Otherwise they'll have 2.
*
* This must only be called from the constructor because GrProcessors are immutable. The
* processor subclass manages the lifetime of the transformations (this function only stores a
* pointer). The GrCoordTransform is typically a member field of the GrProcessor subclass.
*
* A processor subclass that has multiple methods of construction should always add its coord
* transforms in a consistent order. The non-virtual implementation of isEqual() automatically
* compares transforms and will assume they line up across the two processor instances.
*/
void addCoordTransform(GrCoordTransform*);
/**
* FragmentProcessor subclasses call this from their constructor to register any child
* FragmentProcessors they have. This must be called AFTER all texture accesses and coord
* transforms have been added.
* This is for processors whose shader code will be composed of nested processors whose output
* colors will be combined somehow to produce its output color. Registering these child
* processors will allow the ProgramBuilder to automatically handle their transformed coords and
* texture accesses and mangle their uniform and output color names.
*/
int registerChildProcessor(std::unique_ptr<GrFragmentProcessor> child);
void setTextureSamplerCnt(int cnt) {
SkASSERT(cnt >= 0);
fTextureSamplerCnt = cnt;
}
/**
* Helper for implementing onTextureSampler(). E.g.:
* return IthTexureSampler(i, fMyFirstSampler, fMySecondSampler, fMyThirdSampler);
*/
template <typename... Args>
static const TextureSampler& IthTextureSampler(int i, const TextureSampler& samp0,
const Args&... samps) {
return (0 == i) ? samp0 : IthTextureSampler(i - 1, samps...);
}
inline static const TextureSampler& IthTextureSampler(int i);
private:
// Implementation details of Iter and CIter.
template <typename> class IterBase;
virtual SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& /* inputColor */) const {
SK_ABORT("Subclass must override this if advertising this optimization.");
}
/** Returns a new instance of the appropriate *GL* implementation class
for the given GrFragmentProcessor; caller is responsible for deleting
the object. */
virtual GrGLSLFragmentProcessor* onCreateGLSLInstance() const = 0;
/** Implemented using GLFragmentProcessor::GenKey as described in this class's comment. */
virtual void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const = 0;
/**
* Subclass implements this to support isEqual(). It will only be called if it is known that
* the two processors are of the same subclass (i.e. they return the same object from
* getFactory()). The processor subclass should not compare its coord transforms as that will
* be performed automatically in the non-virtual isEqual().
*/
virtual bool onIsEqual(const GrFragmentProcessor&) const = 0;
virtual const TextureSampler& onTextureSampler(int) const { return IthTextureSampler(0); }
bool hasSameTransforms(const GrFragmentProcessor&) const;
enum PrivateFlags {
kFirstPrivateFlag = kAll_OptimizationFlags + 1,
kHasCoordTransforms_Flag = kFirstPrivateFlag,
kCoordTransformsApplyToLocalCoords_Flag = kFirstPrivateFlag << 1,
};
uint32_t fFlags = kCoordTransformsApplyToLocalCoords_Flag;
int fTextureSamplerCnt = 0;
SkSTArray<4, GrCoordTransform*, true> fCoordTransforms;
SkSTArray<1, std::unique_ptr<GrFragmentProcessor>, true> fChildProcessors;
typedef GrProcessor INHERITED;
};
/**
* Used to represent a texture that is required by a GrFragmentProcessor. It holds a GrTextureProxy
* along with an associated GrSamplerState. TextureSamplers don't perform any coord manipulation to
* account for texture origin.
*/
class GrFragmentProcessor::TextureSampler {
public:
TextureSampler() = default;
/**
* This copy constructor is used by GrFragmentProcessor::clone() implementations.
*/
explicit TextureSampler(const TextureSampler&) = default;
TextureSampler(GrSurfaceProxyView, GrSamplerState = {});
TextureSampler& operator=(const TextureSampler&) = delete;
bool operator==(const TextureSampler& that) const {
return fView == that.fView && fSamplerState == that.fSamplerState;
}
bool operator!=(const TextureSampler& other) const { return !(*this == other); }
SkDEBUGCODE(bool isInstantiated() const { return this->proxy()->isInstantiated(); })
// 'peekTexture' should only ever be called after a successful 'instantiate' call
GrTexture* peekTexture() const {
SkASSERT(this->proxy()->isInstantiated());
return this->proxy()->peekTexture();
}
const GrSurfaceProxyView& view() const { return fView; }
GrSamplerState samplerState() const { return fSamplerState; }
bool isInitialized() const { return SkToBool(this->proxy()); }
GrSurfaceProxy* proxy() const { return fView.proxy(); }
#if GR_TEST_UTILS
void set(GrSurfaceProxyView, GrSamplerState);
#endif
private:
GrSurfaceProxyView fView;
GrSamplerState fSamplerState;
};
//////////////////////////////////////////////////////////////////////////////
const GrFragmentProcessor::TextureSampler& GrFragmentProcessor::IthTextureSampler(int i) {
SK_ABORT("Illegal texture sampler index");
static const TextureSampler kBogus;
return kBogus;
}
GR_MAKE_BITFIELD_OPS(GrFragmentProcessor::OptimizationFlags)
//////////////////////////////////////////////////////////////////////////////
template <typename FP> class GrFragmentProcessor::IterBase {
public:
FP& operator*() const { return *fFPStack.back(); }
FP* operator->() const { return fFPStack.back(); }
operator bool() const { return !fFPStack.empty(); }
bool operator!=(const EndIter&) { return (bool)*this; }
// Hopefully this does not actually get called because of RVO.
IterBase(const IterBase&) = default;
// Because each iterator carries a stack we want to avoid copies.
IterBase& operator=(const IterBase&) = delete;
protected:
void increment();
IterBase() = default;
explicit IterBase(FP& fp) { fFPStack.push_back(&fp); }
SkSTArray<4, FP*, true> fFPStack;
};
template <typename FP> void GrFragmentProcessor::IterBase<FP>::increment() {
SkASSERT(!fFPStack.empty());
FP* back = fFPStack.back();
fFPStack.pop_back();
for (int i = back->numChildProcessors() - 1; i >= 0; --i) {
fFPStack.push_back(&back->childProcessor(i));
}
}
//////////////////////////////////////////////////////////////////////////////
class GrFragmentProcessor::Iter : public IterBase<GrFragmentProcessor> {
public:
explicit Iter(GrFragmentProcessor& fp) : IterBase(fp) {}
Iter& operator++() {
this->increment();
return *this;
}
};
//////////////////////////////////////////////////////////////////////////////
class GrFragmentProcessor::CIter : public IterBase<const GrFragmentProcessor> {
public:
explicit CIter(const GrFragmentProcessor& fp) : IterBase(fp) {}
explicit CIter(const GrPaint&);
explicit CIter(const GrProcessorSet&);
explicit CIter(const GrPipeline&);
CIter& operator++() {
this->increment();
return *this;
}
};
//////////////////////////////////////////////////////////////////////////////
template <typename Src> class GrFragmentProcessor::CIterRange {
public:
explicit CIterRange(const Src& t) : fT(t) {}
CIter begin() const { return CIter(fT); }
EndIter end() const { return EndIter(); }
private:
const Src& fT;
};
//////////////////////////////////////////////////////////////////////////////
template <typename Item, GrFragmentProcessor::CountFn Count, GrFragmentProcessor::GetFn<Item> Get>
class GrFragmentProcessor::FPItemIter {
public:
template <typename Src> explicit FPItemIter(Src& s);
std::pair<Item&, const GrFragmentProcessor&> operator*() const {
return {(*fFPIter.*Get)(fIndex), *fFPIter};
}
FPItemIter& operator++();
operator bool() const { return fFPIter; }
bool operator!=(const FPItemEndIter&) { return (bool)*this; }
FPItemIter(const FPItemIter&) = delete;
FPItemIter& operator=(const FPItemIter&) = delete;
private:
typename std::conditional<std::is_const<Item>::value, CIter, Iter>::type fFPIter;
int fIndex;
};
template <typename Item, GrFragmentProcessor::CountFn Count, GrFragmentProcessor::GetFn<Item> Get>
template <typename Src>
GrFragmentProcessor::FPItemIter<Item, Count, Get>::FPItemIter(Src& s) : fFPIter(s), fIndex(-1) {
if (fFPIter) {
++*this;
}
}
template <typename Item, GrFragmentProcessor::CountFn Count, GrFragmentProcessor::GetFn<Item> Get>
GrFragmentProcessor::FPItemIter<Item, Count, Get>&
GrFragmentProcessor::FPItemIter<Item, Count, Get>::operator++() {
++fIndex;
if (fIndex < ((*fFPIter).*Count)()) {
return *this;
}
fIndex = 0;
do {} while (++fFPIter && !((*fFPIter).*Count)());
return *this;
}
//////////////////////////////////////////////////////////////////////////////
template <typename Src, typename ItemIter> class GrFragmentProcessor::FPItemRange {
public:
FPItemRange(Src& src) : fSrc(src) {}
ItemIter begin() const { return ItemIter(fSrc); }
FPItemEndIter end() const { return FPItemEndIter(); }
private:
Src& fSrc;
};
#endif
| 43.317073 | 100 | 0.682925 | [
"object",
"transform"
] |
2e7c7cb90d9db2dabd53fdce25ed3ec4cedf41da | 739 | h | C | src/models/textured_model.h | Ligh7bringer/RenderEngineCpp | c72edb4f0d579df8672b592cf42402e7cbd34493 | [
"MIT"
] | 4 | 2020-05-31T21:42:18.000Z | 2022-03-10T09:51:18.000Z | src/models/textured_model.h | Ligh7bringer/RenderEngineCpp | c72edb4f0d579df8672b592cf42402e7cbd34493 | [
"MIT"
] | null | null | null | src/models/textured_model.h | Ligh7bringer/RenderEngineCpp | c72edb4f0d579df8672b592cf42402e7cbd34493 | [
"MIT"
] | null | null | null | #ifndef RENDERENGINE_TEXTURED_MODEL_H
#define RENDERENGINE_TEXTURED_MODEL_H
#include "raw_model.h"
#include "../textures/model_texture.h"
class TexturedModel {
public:
//simple constructor, store the raw model and texture
explicit TexturedModel(const RawModel &model, const ModelTexture &tex) : _rawModel(model), _texture(tex) {}
//getters
const RawModel &getModel() const {
return _rawModel;
}
const ModelTexture &getTexture() const {
return _texture;
}
bool operator <( const TexturedModel &rhs ) const
{
return ( _texture.getID() < rhs.getTexture().getID() );
}
private:
RawModel _rawModel;
ModelTexture _texture;
};
#endif //RENDERENGINE_TEXTURED_MODEL_H
| 22.393939 | 111 | 0.695535 | [
"model"
] |
2e7fcee926ec14a040c7406914d9c32a8936f4c8 | 1,059 | h | C | pcdet/ops/hybrid_geop/src/hybrid_geop.h | xiangruhuang/OpenPCDet | d82d9594a0629ffed0c457aedc304e0805e93221 | [
"Apache-2.0"
] | null | null | null | pcdet/ops/hybrid_geop/src/hybrid_geop.h | xiangruhuang/OpenPCDet | d82d9594a0629ffed0c457aedc304e0805e93221 | [
"Apache-2.0"
] | null | null | null | pcdet/ops/hybrid_geop/src/hybrid_geop.h | xiangruhuang/OpenPCDet | d82d9594a0629ffed0c457aedc304e0805e93221 | [
"Apache-2.0"
] | null | null | null | #ifndef HYBRID_GEOP_H
#define HYBRID_GEOP_H
#include <torch/serialize/tensor.h>
#include <vector>
#include <cuda.h>
#include <cuda_runtime_api.h>
typedef unsigned long long int uint64;
typedef long long int int64;
typedef unsigned int uint32;
typedef int64_t Key;
typedef int64_t index_t;
typedef float Float;
void hash_insert_gpu(at::Tensor keys, at::Tensor values, at::Tensor reverse_indices,
at::Tensor dims, at::Tensor insert_keys, at::Tensor insert_values
);
void hybrid_geop_gpu(at::Tensor keys,
at::Tensor values,
at::Tensor reverse_indices,
at::Tensor dims,
at::Tensor qmin,
at::Tensor qmax,
at::Tensor query_keys,
at::Tensor mu,
at::Tensor sigma,
Float decay_radius);
void svd3_gpu(at::Tensor input,
at::Tensor output_u,
at::Tensor output_s,
at::Tensor output_v);
#endif
| 28.621622 | 86 | 0.575071 | [
"vector"
] |
2e82a559048b7d7ce0190d6ea293433f88a6ad88 | 4,593 | h | C | src/include/fb_exception.h | Jdochoa/firebird | b5dee68393906b9cf2ccdd71b38f70171fd67e14 | [
"Condor-1.1"
] | 1 | 2021-05-25T09:15:39.000Z | 2021-05-25T09:15:39.000Z | src/include/fb_exception.h | ibaseru/firebird | d7659bed6ac7cf0ba1fae08643dfc94b8f6b738e | [
"Condor-1.1"
] | null | null | null | src/include/fb_exception.h | ibaseru/firebird | d7659bed6ac7cf0ba1fae08643dfc94b8f6b738e | [
"Condor-1.1"
] | null | null | null | /*
* PROGRAM: Firebird exceptions classes
* MODULE: fb_exception.h
* DESCRIPTION: Firebird's exception classes
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Mike Nordell
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2001 Mike Nordell <tamlin at algonet.se>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*
*/
#ifndef FB_EXCEPTION_H
#define FB_EXCEPTION_H
#include <stddef.h>
#include <string.h>
#include <new>
#include "fb_types.h"
#include "firebird/Interface.h"
namespace Firebird
{
class MemoryPool;
class DynamicStatusVector;
template <unsigned S = ISC_STATUS_LENGTH> class SimpleStatusVector;
typedef SimpleStatusVector<> StaticStatusVector;
class Exception
{
protected:
Exception() throw() { }
static void processUnexpectedException(ISC_STATUS* vector) throw();
public:
void stuffException(StaticStatusVector& status_vector) const throw()
{
stuffByException(status_vector);
}
void stuffException(DynamicStatusVector& status_vector) const throw();
void stuffException(CheckStatusWrapper* status_vector) const throw();
virtual ~Exception() throw();
private:
virtual void stuffByException(StaticStatusVector& status_vector) const throw() = 0;
public:
virtual const char* what() const throw() = 0;
};
// Used as jmpbuf to unwind when needed
class LongJump : public Exception
{
public:
virtual void stuffByException(StaticStatusVector& status_vector) const throw();
virtual const char* what() const throw();
static void raise();
LongJump() throw() : Exception() { }
};
// Used in MemoryPool
class BadAlloc : public std::bad_alloc, public Exception
{
public:
BadAlloc() throw() : std::bad_alloc(), Exception() { }
virtual void stuffByException(StaticStatusVector& status_vector) const throw();
virtual const char* what() const throw();
static void raise();
};
// Main exception class in firebird
class status_exception : public Exception
{
public:
explicit status_exception(const ISC_STATUS *status_vector) throw();
status_exception(const status_exception&) throw();
virtual ~status_exception() throw();
virtual void stuffByException(StaticStatusVector& status_vector) const throw();
virtual const char* what() const throw();
const ISC_STATUS* value() const throw() { return m_status_vector; }
static void raise(const ISC_STATUS *status_vector);
static void raise(const Arg::StatusVector& statusVector);
static void raise(const IStatus* status);
protected:
// Create exception with undefined status vector, this constructor allows
// derived classes create empty exception ...
status_exception() throw();
// .. and adjust it later using somehow created status vector.
void set_status(const ISC_STATUS *new_vector) throw();
private:
ISC_STATUS* m_status_vector;
ISC_STATUS_ARRAY m_buffer;
status_exception& operator=(const status_exception&);
};
// Parameter syscall later in both system_error & system_call_failed
// must be literal string! This helps avoid need in StringsBuffer
// when processing this dangerous errors!
// use this class if exception can be handled
class system_error : public status_exception
{
private:
int errorCode;
public:
system_error(const char* syscall, int error_code);
static void raise(const char* syscall, int error_code);
static void raise(const char* syscall);
int getErrorCode() const
{
return errorCode;
}
static int getSystemError();
};
// use this class if exception can't be handled
// it will call abort() in DEV_BUILD to create core dump
class system_call_failed : public system_error
{
public:
system_call_failed(const char* syscall, int error_code);
static void raise(const char* syscall, int error_code);
static void raise(const char* syscall);
};
class fatal_exception : public status_exception
{
public:
explicit fatal_exception(const char* message);
static void raiseFmt(const char* format, ...);
const char* what() const throw();
static void raise(const char* message);
};
} // namespace Firebird
#endif // FB_EXCEPTION_H
| 26.859649 | 84 | 0.757457 | [
"vector"
] |
2e873b49977ed54de3341949ececf571956df94b | 31,145 | c | C | utilities/decipher.c | ImageMagick/WizardsToolkit | d9d0478e7d34a6fe50c1b759b5a4205fa6717385 | [
"ImageMagick"
] | 4 | 2018-03-25T20:09:35.000Z | 2021-09-09T08:40:33.000Z | utilities/decipher.c | FLOOPI222/WizardsToolkit | 1309740445025cd615dec54dd58bad1d751551bf | [
"ImageMagick"
] | null | null | null | utilities/decipher.c | FLOOPI222/WizardsToolkit | 1309740445025cd615dec54dd58bad1d751551bf | [
"ImageMagick"
] | 6 | 2016-01-06T05:42:32.000Z | 2021-02-28T02:05:18.000Z | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD EEEEE CCCC IIIII PPPP H H EEEEE RRRR %
% D D E C I P P H H E R R %
% D D EEE C I PPPP HHHHH EEE RRRR %
% D D E C I P H H E R R %
% DDDD EEEEE CCCC IIIII P H H EEEEE R R %
% %
% %
% Convert Ciphertext to Plaintext %
% %
% Software Design %
% Cristy %
% January 2008 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "wizard/studio.h"
#include "wizard/WizardsToolkit.h"
#include "wizard/blob-private.h"
#include "wizard/exception-private.h"
#include "wizard/string-private.h"
#if defined(WIZARDSTOOLKIT_HAVE_UTIME)
#if defined(WIZARDSTOOLKIT_HAVE_UTIME_H)
#include <utime.h>
#else
#include <sys/utime.h>
#endif
#endif
#if defined(WIZARDSTOOLKIT_WINDOWS_SUPPORT)
#include <windows.h>
#endif
#include "content.h"
#include "utility_.h"
/*
Forward declaraction.
*/
static WizardBooleanType
DecipherContent(ContentInfo *,const char *,const char *,
const WizardBooleanType,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e c i p h e r C o m m a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecipherCommand() reads ciphertext from a file and converts it to plaintext.
%
% The format of the DecipherCommand method is:
%
% WizardBooleanType DecipherCommand(int argc,char **argv,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o argc: The number of elements in the argument vector.
%
% o argv: A text array containing the command line arguments.
%
% o exception: Return any errors or warnings in this structure.
%
*/
static void DecipherUsage(void)
{
static const char
*options[]=
{
"-authenticate method authenticate with this method: Secret or Public",
"-chunksize bytes number of bytes in a chunk",
"-cipher type cipher to decipher content",
"-(de)compress automagically (de)compress BZIP and ZIP files",
"-debug events display copious debugging information",
"-entropy type increase content entropy",
"-help print program options",
"-hmac hash ensure message integrity with this hash",
"-key hash strengthen the key with this hash",
"-key-length value cipher key length in bits: 256, 512, 1024, or 2048",
"-keyring filename add private key to this keyring",
"-level value entropy level: 1 (less entropy) to 9 (more entropy)",
"-list type print a list of supported option arguments",
"-log format format of debugging information",
"-mode type mode of deciphering",
"-passphrase filename get the passphrase from this file",
"-properties filename get cipher properties from this file",
"-random hash strengthen random data with this hash",
"-true-random strengthen deciphering with true random numbers",
"-verbose print detailed information about the secure content",
"-version print version information",
(char *) NULL
};
const char
**p;
(void) fprintf(stdout,"Version: %s\n",GetWizardVersion(
(size_t *) NULL));
(void) fprintf(stdout,"Copyright: %s\n\n",GetWizardCopyright());
(void) fprintf(stdout,"Usage: %s [options ...] ciphertext "
"plaintext\n",GetClientName());
(void) fprintf(stdout,"\nWhere options include:\n");
for (p=options; *p != (char *) NULL; p++)
(void) fprintf(stdout," %s\n",*p);
exit(0);
}
WizardExport WizardBooleanType DecipherCommand(int argc,char **argv,
ExceptionInfo *exception)
{
#define DestroyCipher() \
{ \
content_info=DestroyContentInfo(content_info); \
for (i=0; i < (ssize_t) argc; i++) \
argv[i]=DestroyString(argv[i]); \
argv=(char **) RelinquishWizardMemory(argv); \
}
#define ThrowCipherException(asperity,tag,context) \
{ \
(void) ThrowWizardException(exception,GetWizardModule(),asperity,tag, \
context); \
DestroyCipher(); \
return(WizardFalse); \
}
#define ThrowInvalidArgumentException(option,argument) \
{ \
(void) ThrowWizardException(exception,GetWizardModule(),OptionError, \
"invalid argument: `%s': %s",argument,option); \
DestroyCipher(); \
return(WizardFalse); \
}
const char
*cipher_filename,
*option,
*plain_filename;
ContentInfo
*content_info;
ssize_t
type;
ssize_t
i;
WizardBooleanType
compress,
status,
verbose;
/*
Parse command-line options.
*/
if (argc == 2)
{
option=argv[1];
if ((LocaleCompare("version",option+1) == 0) ||
(LocaleCompare("-version",option+1) == 0))
{
(void) fprintf(stdout,"Version: %s\n",GetWizardVersion(
(size_t *) NULL));
(void) fprintf(stdout,"Copyright: %s\n\n",GetWizardCopyright());
return(WizardTrue);
}
}
if (argc < 3)
DecipherUsage();
status=ExpandFilenames(&argc,&argv);
content_info=AcquireContentInfo();
if (status == WizardFalse)
ThrowCipherException(ResourceError,"memory allocation failed: `%s'",
strerror(errno));
plain_filename=(const char *) NULL;
cipher_filename=(const char *) NULL;
verbose=WizardFalse;
compress=WizardTrue;
for (i=1; i < (ssize_t) argc; i++)
{
option=argv[i];
if (IsWizardOption(option) == WizardFalse)
{
if (plain_filename == (char *) NULL)
plain_filename=option;
else
if (cipher_filename == (char *) NULL)
cipher_filename=option;
else
DecipherUsage();
continue;
}
switch (*(option+1))
{
case '(':
{
if (LocaleCompare(option+1,"(de)compress") == 0)
{
compress=(*option == '-') ? WizardTrue : WizardFalse;
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'a':
{
if (LocaleCompare("authenticate",option+1) == 0)
{
ssize_t
method;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing authentication method: "
"`%s'",option);
method=ParseWizardOption(WizardAuthenticateOptions,WizardFalse,
argv[i]);
if (method < 0)
ThrowCipherException(OptionFatalError,"unrecognized "
"authentication method: `%s'",argv[i]);
content_info->authenticate_method=(AuthenticateMethod) method;
if (method == PublicAuthenticateMethod)
ThrowCipherException(OptionFatalError,"Public authentication "
"method not available yet: `%s'",argv[i]);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'c':
{
if (LocaleCompare("cipher",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing cipher type: `%s'",
option);
type=ParseWizardOption(WizardCipherOptions,WizardFalse,argv[i]);
if (type < 0)
ThrowCipherException(OptionFatalError,"unrecognized cipher "
"type: `%s'",argv[i]);
content_info->cipher=(CipherType) type;
break;
}
if (LocaleCompare(option,"-chunksize") == 0)
{
char
*p;
double
value;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing chunk size: `%s'",
option);
value=StringToDouble(argv[i],&p);
(void) value;
if (p == argv[i])
ThrowInvalidArgumentException(option,argv[i]);
content_info->chunksize=(size_t) StringToDoubleInterval(argv[i],
100.0);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'd':
{
if (LocaleCompare(option,"-debug") == 0)
{
LogEventType
event_mask;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing log event mask: `%s'",
option);
event_mask=SetLogEventMask(argv[i]);
if (event_mask == UndefinedEvents)
ThrowCipherException(OptionFatalError,"unrecognized log event "
"type: `%s'",argv[i]);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'e':
{
if (LocaleCompare("entropy",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing entropy type: `%s'",
option);
type=ParseWizardOption(WizardEntropyOptions,WizardFalse,argv[i]);
if (type < 0)
ThrowCipherException(OptionFatalError,"unrecognized entropy "
"type: `%s'",argv[i]);
content_info->entropy=(EntropyType) type;
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'h':
{
if (LocaleCompare("hmac",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing HMAC hash: `%s'",
option);
type=ParseWizardOption(WizardHashOptions,WizardFalse,argv[i]);
if (type < 0)
ThrowCipherException(OptionFatalError,"unrecognized HMAC hash: "
"`%s'",argv[i]);
content_info->hmac=(HashType) type;
break;
}
if ((LocaleCompare("help",option+1) == 0) ||
(LocaleCompare("-help",option+1) == 0))
DecipherUsage();
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'k':
{
if (LocaleCompare("key",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing key hash: `%s'",option);
type=ParseWizardOption(WizardHashOptions,WizardFalse,argv[i]);
if (type < 0)
ThrowCipherException(OptionFatalError,"unrecognized key hash: "
"`%s'",argv[i]);
content_info->key_hash=(HashType) type;
break;
}
if (LocaleCompare("key-length",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing key length: `%s'",
option);
content_info->key_length=(unsigned int) StringToDouble(
option,(char **) NULL);
break;
}
if (LocaleCompare("keyring",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing keyring filename: `%s'",
option);
content_info->keyring=ConstantString(argv[i]);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'l':
{
if (LocaleCompare(option,"-level") == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing entropy level: `%s'",
option);
type=ParseWizardOption(WizardEntropyLevelOptions,WizardFalse,
argv[i]);
if (type < 0)
ThrowCipherException(OptionFatalError,"unrecognized entropy "
"level: `%s'",argv[i]);
content_info->level=(unsigned int) type;
break;
}
if (LocaleCompare(option,"-list") == 0)
{
ssize_t
list;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing list type: `%s'",
option);
if (LocaleCompare(argv[i],"configure") == 0)
{
(void) ListConfigureInfo((FILE *) NULL,exception);
Exit(0);
}
list=ParseWizardOption(WizardListOptions,WizardFalse,argv[i]);
if (list < 0)
ThrowCipherException(OptionFatalError,"unrecognized list type: "
"`%s'",argv[i]);
(void) ListWizardOptions((FILE *) NULL,(WizardOption) list,
exception);
Exit(0);
break;
}
if (LocaleCompare("log",option+1) == 0)
{
if (*option == '+')
break;
i++;
if ((i == (ssize_t) argc) ||
(strchr(argv[i],'%') == (char *) NULL))
ThrowCipherException(OptionFatalError,"missing argument: `%s'",
option);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'm':
{
if (LocaleCompare("mode",option+1) == 0)
{
ssize_t
type;
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing cipher mode: `%s'",
option);
type=ParseWizardOption(WizardModeOptions,WizardFalse,argv[i]);
if (type < 0)
ThrowCipherException(OptionFatalError,"unrecognized cipher "
"mode: `%s'",argv[i]);
content_info->mode=(CipherMode) type;
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'p':
{
if (LocaleCompare("passphrase",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing passphrase filename: "
"`%s'",option);
content_info->passphrase=ConstantString(argv[i]);
break;
}
if (LocaleCompare("properties",option+1) == 0)
{
if (*option == '+')
break;
i++;
if (i == (ssize_t) argc)
ThrowCipherException(OptionError,"missing properties filename: "
"`%s'",option);
content_info->properties=ConstantString(argv[i]);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 't':
{
if (LocaleCompare(option+1,"true-random") == 0)
{
SetRandomTrueRandom(*option == '-' ? WizardTrue : WizardFalse);
break;
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
case 'v':
{
if (LocaleCompare(option+1,"verbose") == 0)
{
verbose=(*option == '-') ? WizardTrue : WizardFalse;
break;
}
if (LocaleCompare(option,"-version") == 0)
{
(void) fprintf(stdout,"Version: %s\n",GetWizardVersion(
(size_t *) NULL));
(void) fprintf(stdout,"Copyright: %s\n\n",GetWizardCopyright());
exit(0);
}
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
default:
{
ThrowCipherException(OptionFatalError,"unrecognized option: `%s'",
option);
break;
}
}
}
/*
Decipher content.
*/
if ((plain_filename == (char *) NULL) ||
(cipher_filename == (char *) NULL))
DecipherUsage();
content_info->content=ConstantString(plain_filename);
status=DecipherContent(content_info,plain_filename,cipher_filename,compress,
exception);
if ((status != WizardFalse) && (verbose != WizardFalse))
(void) PrintCipherProperties(content_info,stdout);
/*
Free resources.
*/
DestroyCipher();
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c i p h e r C o n t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecipherContent() reads ciphertext from a file and writes it as plaintext.
%
% The format of the DecipherContent method is:
%
% WizardBooleanType DecipherContent(ContentInfo *content_info,
% const char *cipher_filename,const char *plain_filename,
% const WizardBooleanType compress,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o content_info: the cipher options.
%
% o cipher_filename: the ciphertext filename.
%
% o plain_filename: the plaintext filename.
%
% o compress: automagically (de)compress BZIP and ZIP files.
%
% o exception: return any exceptions in this structure.
%
*/
static WizardBooleanType DecipherContent(ContentInfo *content_info,
const char *cipher_filename,const char *plain_filename,
const WizardBooleanType compress,ExceptionInfo *exception)
{
#define ThrowDecipherContentException(asperity,tag,context) \
{ \
(void) ThrowWizardException(exception,GetWizardModule(),asperity, \
tag,context,strerror(errno)); \
return(WizardFalse); \
}
char
message[WizardPathExtent];
EntropyType
entropy;
size_t
blocksize,
length,
pad;
ssize_t
count;
StringInfo
*ciphertext,
*hmac,
*plaintext;
size_t
chunk;
WizardBooleanType
status;
/*
Open plaintext and ciphertext content files.
*/
content_info->cipherblob=OpenBlob(cipher_filename,ReadBinaryBlobMode,
compress,exception);
if (content_info->cipherblob == (BlobInfo *) NULL)
return(WizardFalse);
content_info->plainblob=OpenBlob(plain_filename,WriteBinaryBlobMode,compress,
exception);
if (content_info->plainblob == (BlobInfo *) NULL)
return(WizardFalse);
/*
Decipher plaintext.
*/
if (content_info->properties == (char *) NULL)
status=GetContentInfo(content_info,content_info->cipherblob,exception);
else
{
BlobInfo
*properties;
/*
Cipher properties are stored separately from the content.
*/
properties=OpenBlob(content_info->properties,ReadBinaryBlobMode,
WizardTrue,exception);
if (properties == (BlobInfo *) NULL)
return(WizardFalse);
status=GetContentInfo(content_info,properties,exception);
if (CloseBlob(properties) == WizardTrue)
ThrowFileException(exception,FileError,content_info->properties);
properties=DestroyBlob(properties);
}
if (status == WizardFalse)
return(WizardFalse);
content_info->authenticate_info=AcquireAuthenticateInfo(
content_info->authenticate_method,content_info->keyring,
content_info->key_hash);
SetAuthenticateKeyLength(content_info->authenticate_info,
content_info->key_length);
if (content_info->id != (char *) NULL)
{
StringInfo
*id;
/*
Set key id.
*/
id=HexStringToStringInfo(content_info->id);
SetAuthenticateId(content_info->authenticate_info,id);
id=DestroyStringInfo(id);
}
if (content_info->passphrase != (char *) NULL)
SetAuthenticatePassphrase(content_info->authenticate_info,
content_info->passphrase);
status=AuthenticateKey(content_info->authenticate_info,exception);
if (status == WizardFalse)
ThrowDecipherContentException(ResourceError,"authentication failed: `%s': "
"`%s'",cipher_filename);
content_info->cipher_info=AcquireCipherInfo(content_info->cipher,
content_info->mode);
SetCipherKey(content_info->cipher_info,GetAuthenticateKey(
content_info->authenticate_info));
if (content_info->nonce != (char *) NULL)
{
StringInfo
*nonce;
/*
Set cipher nonce.
*/
nonce=HexStringToStringInfo(content_info->nonce);
SetCipherNonce(content_info->cipher_info,nonce);
nonce=DestroyStringInfo(nonce);
}
hmac=(StringInfo *) NULL;
if (content_info->hmac != NoHash)
{
content_info->hmac_info=AcquireHMACInfo(content_info->hmac);
hmac=AcquireStringInfo(GetHMACDigestsize(content_info->hmac_info));
}
entropy=content_info->entropy;
if (content_info->entropy != NoEntropy)
content_info->entropy_info=AcquireEntropyInfo(content_info->entropy,
content_info->level);
blocksize=GetCipherBlocksize(content_info->cipher_info);
pad=blocksize-content_info->chunksize % blocksize;
if (pad == blocksize)
pad=0;
ciphertext=AcquireStringInfo(content_info->chunksize);
for (chunk=0; ; chunk++)
{
if (content_info->hmac != NoHash)
{
length=GetStringInfoLength(hmac);
count=ReadBlobChunk(content_info->cipherblob,length,GetStringInfoDatum(
hmac));
if (count <= 0)
break;
}
if (content_info->entropy != NoEntropy)
entropy=(EntropyType) ReadBlobByte(content_info->cipherblob);
length=content_info->chunksize;
if (content_info->mode != CFBMode)
length+=pad;
SetStringInfoLength(ciphertext,length);
count=ReadBlobChunk(content_info->cipherblob,length,GetStringInfoDatum(
ciphertext));
if (count <= 0)
break;
length=(size_t) count;
SetStringInfoLength(ciphertext,length);
plaintext=DecipherCipher(content_info->cipher_info,ciphertext);
if ((content_info->mode != CFBMode) &&
((pad != 0) || (EOFBlob(content_info->cipherblob) != WizardFalse)))
length-=GetStringInfoDatum(plaintext)[length-1]+1;
SetStringInfoLength(plaintext,length);
if (entropy != NoEntropy)
{
status=RestoreEntropy(content_info->entropy_info,length,plaintext,
exception);
if (status == WizardFalse)
ThrowDecipherContentException(FileError,"unable to restore entropy "
"`%s': `%s'",cipher_filename);
SetStringInfo(plaintext,GetEntropyChaos(content_info->entropy_info));
}
if (content_info->hmac != NoHash)
{
ConstructHMAC(content_info->hmac_info,GetAuthenticateKey(
content_info->authenticate_info),plaintext);
if (CompareStringInfo(hmac,GetHMACDigest(content_info->hmac_info)) != 0)
{
(void) FormatLocaleString(message,WizardPathExtent,"corrupt cipher "
"chunk #%.20g `%s'",(double) chunk,cipher_filename);
ThrowDecipherContentException(FileError,"%s: `%s'",message);
}
}
count=WriteBlobChunk(content_info->plainblob,length,GetStringInfoDatum(
plaintext));
if (count != (ssize_t) length)
ThrowDecipherContentException(FileError,"unable to write plaintext "
"`%s': `%s'",cipher_filename);
}
if (CloseBlob(content_info->cipherblob) != WizardFalse)
ThrowFileException(exception,FileError,content_info->content);
if (CloseBlob(content_info->plainblob) != WizardFalse)
ThrowFileException(exception,FileError,content_info->content);
#if defined(WIZARDSTOOLKIT_HAVE_UTIME)
{
struct utimbuf
properties;
properties.actime=content_info->modify_date;
properties.modtime=content_info->modify_date;
if (utime(plain_filename,&properties) < 0)
ThrowFileException(exception,FileError,plain_filename);
}
#endif
ciphertext=DestroyStringInfo(ciphertext);
if (content_info->hmac != NoHash)
hmac=DestroyStringInfo(hmac);
return(WizardTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a i n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
static int WizardMain(int argc,char **argv)
{
char
*option;
double
elapsed_time,
user_time;
ExceptionInfo
*exception;
ssize_t
i;
TimerInfo
*timer;
unsigned int
iterations;
WizardBooleanType
regard_warnings,
status;
WizardsToolkitGenesis(*argv);
exception=AcquireExceptionInfo();
iterations=1;
status=WizardTrue;
regard_warnings=WizardFalse;
for (i=1; i < (ssize_t) (argc-1); i++)
{
option=argv[i];
if ((strlen(option) == 1) || ((*option != '-') && (*option != '+')))
continue;
if (LocaleCompare("bench",option+1) == 0)
iterations=(unsigned int) StringToUnsignedLong(argv[++i]);
if (LocaleCompare("debug",option+1) == 0)
(void) SetLogEventMask(argv[++i]);
if (LocaleCompare("regard-warnings",option+1) == 0)
regard_warnings=WizardTrue;
}
timer=(TimerInfo *) NULL;
if (iterations > 1)
timer=AcquireTimerInfo();
for (i=0; i < (ssize_t) iterations; i++)
{
status=DecipherCommand(argc,argv,exception);
if ((status == WizardFalse) ||
(GetExceptionSeverity(exception) != UndefinedException))
{
if ((GetExceptionSeverity(exception) < ErrorException) &&
(regard_warnings == WizardFalse))
status=WizardTrue;
CatchException(exception);
}
}
if (iterations > 1)
{
elapsed_time=GetElapsedTime(timer);
user_time=GetUserTime(timer);
(void) fprintf(stderr,"Performance: %ui %gips %0.3fu %.20g:%02g.%03g\n",
iterations,1.0*iterations/elapsed_time,user_time,(double)
(elapsed_time/60.0+0.5),floor(fmod(elapsed_time,60.0)),(double)
(1000.0*(elapsed_time-floor(elapsed_time))+0.5));
timer=DestroyTimerInfo(timer);
}
exception=DestroyExceptionInfo(exception);
WizardsToolkitTerminus();
return(status == WizardFalse ? 1 : 0);
}
#if !defined(WIZARDSTOOLKIT_WINDOWS_SUPPORT) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__)
int main(int argc,char **argv)
{
return(WizardMain(argc,argv));
}
#else
int wmain(int argc,wchar_t *argv[])
{
char
**utf8;
int
status;
int
i;
utf8=NTArgvToUTF8(argc,argv);
status=WizardMain(argc,utf8);
for (i=0; i < argc; i++)
utf8[i]=DestroyString(utf8[i]);
utf8=(char **) RelinquishWizardMemory(utf8);
return(status);
}
#endif
| 33.381565 | 115 | 0.517547 | [
"vector"
] |
2e88cd2ec8021f9f975112afc86495a825a4d43b | 3,187 | h | C | AstriumRecode/ESP.h | OFv133769/dtzkjhf | 627c41beb17549d04aaa16e316fdca8908be1033 | [
"Apache-2.0"
] | null | null | null | AstriumRecode/ESP.h | OFv133769/dtzkjhf | 627c41beb17549d04aaa16e316fdca8908be1033 | [
"Apache-2.0"
] | null | null | null | AstriumRecode/ESP.h | OFv133769/dtzkjhf | 627c41beb17549d04aaa16e316fdca8908be1033 | [
"Apache-2.0"
] | null | null | null |
#pragma once
#include "SDK.h"
#include "singleton.hpp"
class visuals
:public singleton<visuals>
{
public:
visuals();
void OnPaintTraverse(C_BaseEntity* local);
void DrawPlayer(C_BaseEntity* entity, player_info_t pinfo, C_BaseEntity* local);
private:
struct playerlist_t
{
char *name;
char *steamid;
int money;
int health;
int mmwins;
char *mmrank;
}players[64];
// Other shit
C_BaseEntity *BombCarrier;
struct ESPBox
{
int x, y, w, h, gay;
};
void DLight(C_BaseEntity* local, C_BaseEntity* entity);
// Get player info
Color GetPlayerColor(C_BaseEntity* pEntity, C_BaseEntity* local);
bool GetBox(C_BaseEntity* pEntity, ESPBox &result);
void BoxAndText(C_BaseEntity* pEntity, std::string text);
// Draw shit about player
void DrawBox(ESPBox size, Color color);
void PlayerBox(float x, float y, float w, float h, Color clr);
void DrawHealth(Vector bot, Vector top, float health);
void DrawHealth(C_BaseEntity* pEntity, ESPBox size);
void DrawDrop(C_BaseEntity* pEntity);
void DrawBombPlanted(C_BaseEntity* entity, C_BaseEntity* local);
void DrawBomb(C_BaseEntity* pEntity, ClientClass* cClass);
void DrawThrowable(C_BaseEntity* throwable);
void NightMode();
void SpecList(C_BaseEntity *local);
};
inline float CSGO_Armor(float flDamage, int ArmorValue)
{
float flArmorRatio = 0.5f;
float flArmorBonus = 0.5f;
if (ArmorValue > 0) {
float flNew = flDamage * flArmorRatio;
float flArmor = (flDamage - flNew) * flArmorBonus;
if (flArmor > static_cast<float>(ArmorValue)) {
flArmor = static_cast<float>(ArmorValue) * (1.f / flArmorBonus);
flNew = flDamage - flArmor;
}
flDamage = flNew;
}
return flDamage;
}
template <typename T, std::size_t N> T* end_(T(&arr)[N]) { return arr + N; }
template <typename T, std::size_t N> T* begin_(T(&arr)[N]) { return arr; }
char* const itemNames[] =
{
"knife", //0 - default
"deagle",
"elite",
"fiveseven",
"glock",
"none",
"none",
"ak47",
"aug",
"awp",
"famas", //10
"g3sg1",
"none",
"galil",
"m249",
"none",
"m4a4",
"mac-10",
"none",
"p90",
"none", //20
"none",
"none",
"none",
"ump45",
"xm1014",
"bizon",
"mag7",
"negev",
"sawed-off",
"tec9", //30
"taser",
"p2000",
"mp7",
"mp9",
"nova",
"p250",
"none",
"scar20",
"sg556",
"ssg08", //40
"knife",
"knife",
"flash",
"nade",
"smoke",
"molotov",
"decoy",
"incendiary",
"c4",
"none", //50
"none",
"none",
"none",
"none",
"none",
"none",
"none",
"none",
"knife",
"m4a1", //60
"usp",
"none",
"cz75",
"revolver"
};
inline const char* ItemDefinitionIndexToString(int index)
{
if (index < 0 || index > 64)
index = 0;
return itemNames[index];
}
inline float flGetDistance(Vector from, Vector to)
{
Vector angle;
angle.x = to.x - from.x; angle.y = to.y - from.y; angle.z = to.z - from.z;
return sqrt(angle.x*angle.x + angle.y*angle.y + angle.z*angle.z);
}
| 19.083832 | 81 | 0.592407 | [
"vector"
] |
2e8ca3650277853045c43404ba65b7001bcd065a | 3,898 | h | C | attacking_anti_tamper/taint_cpp/extern/keystone/llvm/include/llvm/Support/MipsABIFlags.h | tum-i4/dta-vs-osc | b39f4d4eb6ffea501025fc3e07622251c2118fe0 | [
"MIT"
] | 15 | 2021-12-08T09:53:35.000Z | 2022-03-07T10:13:37.000Z | attacking_anti_tamper/taint_cpp/extern/keystone/llvm/include/llvm/Support/MipsABIFlags.h | tum-i4/dta-vs-osc | b39f4d4eb6ffea501025fc3e07622251c2118fe0 | [
"MIT"
] | null | null | null | attacking_anti_tamper/taint_cpp/extern/keystone/llvm/include/llvm/Support/MipsABIFlags.h | tum-i4/dta-vs-osc | b39f4d4eb6ffea501025fc3e07622251c2118fe0 | [
"MIT"
] | 1 | 2021-12-13T22:45:20.000Z | 2021-12-13T22:45:20.000Z | //===--- MipsABIFlags.h - MIPS ABI flags ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the constants for the ABI flags structure contained
// in the .MIPS.abiflags section.
//
// https://dmz-portal.mips.com/wiki/MIPS_O32_ABI_-_FR0_and_FR1_Interlinking
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_MIPSABIFLAGS_H
#define LLVM_SUPPORT_MIPSABIFLAGS_H
namespace llvm_ks {
namespace Mips {
// Values for the xxx_size bytes of an ABI flags structure.
enum AFL_REG {
AFL_REG_NONE = 0x00, // No registers
AFL_REG_32 = 0x01, // 32-bit registers
AFL_REG_64 = 0x02, // 64-bit registers
AFL_REG_128 = 0x03 // 128-bit registers
};
// Masks for the ases word of an ABI flags structure.
enum AFL_ASE {
AFL_ASE_DSP = 0x00000001, // DSP ASE
AFL_ASE_DSPR2 = 0x00000002, // DSP R2 ASE
AFL_ASE_EVA = 0x00000004, // Enhanced VA Scheme
AFL_ASE_MCU = 0x00000008, // MCU (MicroController) ASE
AFL_ASE_MDMX = 0x00000010, // MDMX ASE
AFL_ASE_MIPS3D = 0x00000020, // MIPS-3D ASE
AFL_ASE_MT = 0x00000040, // MT ASE
AFL_ASE_SMARTMIPS = 0x00000080, // SmartMIPS ASE
AFL_ASE_VIRT = 0x00000100, // VZ ASE
AFL_ASE_MSA = 0x00000200, // MSA ASE
AFL_ASE_MIPS16 = 0x00000400, // MIPS16 ASE
AFL_ASE_MICROMIPS = 0x00000800, // MICROMIPS ASE
AFL_ASE_XPA = 0x00001000 // XPA ASE
};
// Values for the isa_ext word of an ABI flags structure.
enum AFL_EXT {
AFL_EXT_NONE = 0, // None
AFL_EXT_XLR = 1, // RMI Xlr instruction
AFL_EXT_OCTEON2 = 2, // Cavium Networks Octeon2
AFL_EXT_OCTEONP = 3, // Cavium Networks OcteonP
AFL_EXT_LOONGSON_3A = 4, // Loongson 3A
AFL_EXT_OCTEON = 5, // Cavium Networks Octeon
AFL_EXT_5900 = 6, // MIPS R5900 instruction
AFL_EXT_4650 = 7, // MIPS R4650 instruction
AFL_EXT_4010 = 8, // LSI R4010 instruction
AFL_EXT_4100 = 9, // NEC VR4100 instruction
AFL_EXT_3900 = 10, // Toshiba R3900 instruction
AFL_EXT_10000 = 11, // MIPS R10000 instruction
AFL_EXT_SB1 = 12, // Broadcom SB-1 instruction
AFL_EXT_4111 = 13, // NEC VR4111/VR4181 instruction
AFL_EXT_4120 = 14, // NEC VR4120 instruction
AFL_EXT_5400 = 15, // NEC VR5400 instruction
AFL_EXT_5500 = 16, // NEC VR5500 instruction
AFL_EXT_LOONGSON_2E = 17, // ST Microelectronics Loongson 2E
AFL_EXT_LOONGSON_2F = 18, // ST Microelectronics Loongson 2F
AFL_EXT_OCTEON3 = 19 // Cavium Networks Octeon3
};
// Values for the flags1 word of an ABI flags structure.
enum AFL_FLAGS1 { AFL_FLAGS1_ODDSPREG = 1 };
// MIPS object attribute tags
enum {
Tag_GNU_MIPS_ABI_FP = 4, // Floating-point ABI used by this object file
Tag_GNU_MIPS_ABI_MSA = 8, // MSA ABI used by this object file
};
// Values for the fp_abi word of an ABI flags structure
// and for the Tag_GNU_MIPS_ABI_FP attribute tag.
enum Val_GNU_MIPS_ABI_FP {
Val_GNU_MIPS_ABI_FP_ANY = 0, // not tagged
Val_GNU_MIPS_ABI_FP_DOUBLE = 1, // hard float / -mdouble-float
Val_GNU_MIPS_ABI_FP_SINGLE = 2, // hard float / -msingle-float
Val_GNU_MIPS_ABI_FP_SOFT = 3, // soft float
Val_GNU_MIPS_ABI_FP_OLD_64 = 4, // -mips32r2 -mfp64
Val_GNU_MIPS_ABI_FP_XX = 5, // -mfpxx
Val_GNU_MIPS_ABI_FP_64 = 6, // -mips32r2 -mfp64
Val_GNU_MIPS_ABI_FP_64A = 7 // -mips32r2 -mfp64 -mno-odd-spreg
};
// Values for the Tag_GNU_MIPS_ABI_MSA attribute tag.
enum Val_GNU_MIPS_ABI_MSA {
Val_GNU_MIPS_ABI_MSA_ANY = 0, // not tagged
Val_GNU_MIPS_ABI_MSA_128 = 1 // 128-bit MSA
};
}
}
#endif
| 37.84466 | 80 | 0.653412 | [
"object",
"3d"
] |
2e93ab6f317bd01d5e9ab1e99eeca45c5a2dce20 | 3,321 | h | C | include/coppelia_controller/sim_devices/robot_sim.h | lyh458/irl_robot_drivers | beeef5b9798725c01e8c6bbac741e47461b518e4 | [
"MIT"
] | 1 | 2020-08-05T01:58:26.000Z | 2020-08-05T01:58:26.000Z | include/coppelia_controller/sim_devices/robot_sim.h | lyh458/irl_robot_drivers | beeef5b9798725c01e8c6bbac741e47461b518e4 | [
"MIT"
] | null | null | null | include/coppelia_controller/sim_devices/robot_sim.h | lyh458/irl_robot_drivers | beeef5b9798725c01e8c6bbac741e47461b518e4 | [
"MIT"
] | 2 | 2020-08-05T01:58:52.000Z | 2020-12-24T02:42:37.000Z | #include <array>
#include <mutex>
#include "ros/ros.h"
#include <sensor_msgs/JointState.h>
#include <std_msgs/Int32.h>
#include <string>
#include <vector>
#include <unordered_map>
/*!
Robot class for interacting with CoppeliaSim
*/
class RobotSim
{
public:
const static int NUM_JOINTS = 6;
struct sim_object {
std::string name;
int handle;
};
RobotSim(
std::vector<std::string> joints,
std::string ik_target,
std::string ik_tip,
int client_id,
std::mutex &mtx
);
/*!
Set the IK target to an arbitrary 3D position (joint modes must be ik)
@param coords The coordinates of the desired/target 3D position
*/
void set_ik_pos(std::array<float, 3> coords);
/*!
Wait until the robot reaches the threshold of the desired/target 3D position
*/
bool wait_for_target_pos(std::array<float, 3> target_coords);
/*!
Set the target angles for the robot (joint modes must be force)
@param angles The array of desired/target angles
*/
void set_force_angles(std::array<float, NUM_JOINTS> angles);
/*!
Wait until the robot reaches the threshold of the target angles
@param angles The array of desired/target angles
*/
bool wait_for_target_angles(std::array<float, NUM_JOINTS> target_angles);
/*!
Reset the IK targets to the initial position
*/
void reset_ik_target_to_initial();
/*!
Get/Set the current state (joint angles) of the interaction
@param joints Passed by reference; Sets the incomming array to the current joint angles
*/
void get_state(std::array<float,6>& in_joints);
/*!
Get the position of the end effector
*/
std::array<float, 3> get_ee_pos();
/*!
Get handle from simulator by name
@param name Name of the handles
@returns handle ID
*/
int get_handle(std::string name);
/*!
Returns the difference between two positions.
@param target Target position for end effector
@param current Current position of end effector
*/
float get_position_difference(std::array<float, 3>& target, std::array<float, 3>& current);
/*!
Returns the difference between two joint angles
@param target Target angles for the robot
@param current Current angles of the robot
*/
float get_joint_position_difference(float target, float current);
/*!
Control the robot per the command received from CoppeliaController
@param message The message that Intprim inference generates for the new position
*/
void control_robot(const sensor_msgs::JointState::ConstPtr& message);
std::array<sim_object, NUM_JOINTS> m_joints;
bool m_kill_interaction;
std::array<float, NUM_JOINTS> m_initial_angles;
std::mutex& m_sim_mutex;
private:
std::unordered_map<std::string, int> m_name_handle_map;
std::array<float,NUM_JOINTS> m_current_state;
sim_object m_ik_target;
sim_object m_ik_tip;
std::array<float, 3> m_ik_tip_initial_pos;
int m_client_id;
};
| 29.918919 | 95 | 0.630834 | [
"vector",
"3d"
] |
2e97712d98268d38c80c9df5d8c11d20bfef1edb | 26,780 | c | C | sys/dev/drm/i915/intel_psr.c | raJeev-M/DragonFlyBSD | 2f9f168a13010344973c10c56a71514a10643642 | [
"BSD-3-Clause"
] | 1 | 2019-12-22T07:21:10.000Z | 2019-12-22T07:21:10.000Z | sys/dev/drm/i915/intel_psr.c | raJeev-M/DragonFlyBSD | 2f9f168a13010344973c10c56a71514a10643642 | [
"BSD-3-Clause"
] | null | null | null | sys/dev/drm/i915/intel_psr.c | raJeev-M/DragonFlyBSD | 2f9f168a13010344973c10c56a71514a10643642 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright © 2014 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* DOC: Panel Self Refresh (PSR/SRD)
*
* Since Haswell Display controller supports Panel Self-Refresh on display
* panels witch have a remote frame buffer (RFB) implemented according to PSR
* spec in eDP1.3. PSR feature allows the display to go to lower standby states
* when system is idle but display is on as it eliminates display refresh
* request to DDR memory completely as long as the frame buffer for that
* display is unchanged.
*
* Panel Self Refresh must be supported by both Hardware (source) and
* Panel (sink).
*
* PSR saves power by caching the framebuffer in the panel RFB, which allows us
* to power down the link and memory controller. For DSI panels the same idea
* is called "manual mode".
*
* The implementation uses the hardware-based PSR support which automatically
* enters/exits self-refresh mode. The hardware takes care of sending the
* required DP aux message and could even retrain the link (that part isn't
* enabled yet though). The hardware also keeps track of any frontbuffer
* changes to know when to exit self-refresh mode again. Unfortunately that
* part doesn't work too well, hence why the i915 PSR support uses the
* software frontbuffer tracking to make sure it doesn't miss a screen
* update. For this integration intel_psr_invalidate() and intel_psr_flush()
* get called by the frontbuffer tracking code. Note that because of locking
* issues the self-refresh re-enable code is done from a work queue, which
* must be correctly synchronized/cancelled when shutting down the pipe."
*/
#include <drm/drmP.h>
#include "intel_drv.h"
#include "i915_drv.h"
static bool is_edp_psr(struct intel_dp *intel_dp)
{
return intel_dp->psr_dpcd[0] & DP_PSR_IS_SUPPORTED;
}
static bool vlv_is_psr_active_on_pipe(struct drm_device *dev, int pipe)
{
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t val;
val = I915_READ(VLV_PSRSTAT(pipe)) &
VLV_EDP_PSR_CURR_STATE_MASK;
return (val == VLV_EDP_PSR_ACTIVE_NORFB_UP) ||
(val == VLV_EDP_PSR_ACTIVE_SF_UPDATE);
}
static void intel_psr_write_vsc(struct intel_dp *intel_dp,
const struct edp_vsc_psr *vsc_psr)
{
struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_crtc *crtc = to_intel_crtc(dig_port->base.base.crtc);
enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
i915_reg_t ctl_reg = HSW_TVIDEO_DIP_CTL(cpu_transcoder);
const uint32_t *data = (const uint32_t *) vsc_psr;
unsigned int i;
/* As per BSPec (Pipe Video Data Island Packet), we need to disable
the video DIP being updated before program video DIP data buffer
registers for DIP being updated. */
I915_WRITE(ctl_reg, 0);
POSTING_READ(ctl_reg);
for (i = 0; i < sizeof(*vsc_psr); i += 4) {
I915_WRITE(HSW_TVIDEO_DIP_VSC_DATA(cpu_transcoder,
i >> 2), *data);
data++;
}
for (; i < VIDEO_DIP_VSC_DATA_SIZE; i += 4)
I915_WRITE(HSW_TVIDEO_DIP_VSC_DATA(cpu_transcoder,
i >> 2), 0);
I915_WRITE(ctl_reg, VIDEO_DIP_ENABLE_VSC_HSW);
POSTING_READ(ctl_reg);
}
static void vlv_psr_setup_vsc(struct intel_dp *intel_dp)
{
struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = intel_dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc = intel_dig_port->base.base.crtc;
enum i915_pipe pipe = to_intel_crtc(crtc)->pipe;
uint32_t val;
/* VLV auto-generate VSC package as per EDP 1.3 spec, Table 3.10 */
val = I915_READ(VLV_VSCSDP(pipe));
val &= ~VLV_EDP_PSR_SDP_FREQ_MASK;
val |= VLV_EDP_PSR_SDP_FREQ_EVFRAME;
I915_WRITE(VLV_VSCSDP(pipe), val);
}
static void skl_psr_setup_su_vsc(struct intel_dp *intel_dp)
{
struct edp_vsc_psr psr_vsc;
/* Prepare VSC Header for SU as per EDP 1.4 spec, Table 6.11 */
memset(&psr_vsc, 0, sizeof(psr_vsc));
psr_vsc.sdp_header.HB0 = 0;
psr_vsc.sdp_header.HB1 = 0x7;
psr_vsc.sdp_header.HB2 = 0x3;
psr_vsc.sdp_header.HB3 = 0xb;
intel_psr_write_vsc(intel_dp, &psr_vsc);
}
static void hsw_psr_setup_vsc(struct intel_dp *intel_dp)
{
struct edp_vsc_psr psr_vsc;
/* Prepare VSC packet as per EDP 1.3 spec, Table 3.10 */
memset(&psr_vsc, 0, sizeof(psr_vsc));
psr_vsc.sdp_header.HB0 = 0;
psr_vsc.sdp_header.HB1 = 0x7;
psr_vsc.sdp_header.HB2 = 0x2;
psr_vsc.sdp_header.HB3 = 0x8;
intel_psr_write_vsc(intel_dp, &psr_vsc);
}
static void vlv_psr_enable_sink(struct intel_dp *intel_dp)
{
drm_dp_dpcd_writeb(&intel_dp->aux, DP_PSR_EN_CFG,
DP_PSR_ENABLE | DP_PSR_MAIN_LINK_ACTIVE);
}
static i915_reg_t psr_aux_ctl_reg(struct drm_i915_private *dev_priv,
enum port port)
{
if (INTEL_INFO(dev_priv)->gen >= 9)
return DP_AUX_CH_CTL(port);
else
return EDP_PSR_AUX_CTL;
}
static i915_reg_t psr_aux_data_reg(struct drm_i915_private *dev_priv,
enum port port, int index)
{
if (INTEL_INFO(dev_priv)->gen >= 9)
return DP_AUX_CH_DATA(port, index);
else
return EDP_PSR_AUX_DATA(index);
}
static void hsw_psr_enable_sink(struct intel_dp *intel_dp)
{
struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t aux_clock_divider;
i915_reg_t aux_ctl_reg;
static const uint8_t aux_msg[] = {
[0] = DP_AUX_NATIVE_WRITE << 4,
[1] = DP_SET_POWER >> 8,
[2] = DP_SET_POWER & 0xff,
[3] = 1 - 1,
[4] = DP_SET_POWER_D0,
};
enum port port = dig_port->port;
u32 aux_ctl;
int i;
BUILD_BUG_ON(sizeof(aux_msg) > 20);
aux_clock_divider = intel_dp->get_aux_clock_divider(intel_dp, 0);
/* Enable AUX frame sync at sink */
if (dev_priv->psr.aux_frame_sync)
drm_dp_dpcd_writeb(&intel_dp->aux,
DP_SINK_DEVICE_AUX_FRAME_SYNC_CONF,
DP_AUX_FRAME_SYNC_ENABLE);
if (dev_priv->psr.link_standby)
drm_dp_dpcd_writeb(&intel_dp->aux, DP_PSR_EN_CFG,
DP_PSR_ENABLE | DP_PSR_MAIN_LINK_ACTIVE);
else
drm_dp_dpcd_writeb(&intel_dp->aux, DP_PSR_EN_CFG,
DP_PSR_ENABLE);
aux_ctl_reg = psr_aux_ctl_reg(dev_priv, port);
/* Setup AUX registers */
for (i = 0; i < sizeof(aux_msg); i += 4)
I915_WRITE(psr_aux_data_reg(dev_priv, port, i >> 2),
intel_dp_pack_aux(&aux_msg[i], sizeof(aux_msg) - i));
aux_ctl = intel_dp->get_aux_send_ctl(intel_dp, 0, sizeof(aux_msg),
aux_clock_divider);
I915_WRITE(aux_ctl_reg, aux_ctl);
}
static void vlv_psr_enable_source(struct intel_dp *intel_dp)
{
struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc = dig_port->base.base.crtc;
enum i915_pipe pipe = to_intel_crtc(crtc)->pipe;
/* Transition from PSR_state 0 to PSR_state 1, i.e. PSR Inactive */
I915_WRITE(VLV_PSRCTL(pipe),
VLV_EDP_PSR_MODE_SW_TIMER |
VLV_EDP_PSR_SRC_TRANSMITTER_STATE |
VLV_EDP_PSR_ENABLE);
}
static void vlv_psr_activate(struct intel_dp *intel_dp)
{
struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc = dig_port->base.base.crtc;
enum i915_pipe pipe = to_intel_crtc(crtc)->pipe;
/* Let's do the transition from PSR_state 1 to PSR_state 2
* that is PSR transition to active - static frame transmission.
* Then Hardware is responsible for the transition to PSR_state 3
* that is PSR active - no Remote Frame Buffer (RFB) update.
*/
I915_WRITE(VLV_PSRCTL(pipe), I915_READ(VLV_PSRCTL(pipe)) |
VLV_EDP_PSR_ACTIVE_ENTRY);
}
static void hsw_psr_enable_source(struct intel_dp *intel_dp)
{
struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t max_sleep_time = 0x1f;
/* Lately it was identified that depending on panel idle frame count
* calculated at HW can be off by 1. So let's use what came
* from VBT + 1.
* There are also other cases where panel demands at least 4
* but VBT is not being set. To cover these 2 cases lets use
* at least 5 when VBT isn't set to be on the safest side.
*/
uint32_t idle_frames = dev_priv->vbt.psr.idle_frames + 1;
uint32_t val = EDP_PSR_ENABLE;
val |= max_sleep_time << EDP_PSR_MAX_SLEEP_TIME_SHIFT;
val |= idle_frames << EDP_PSR_IDLE_FRAME_SHIFT;
if (IS_HASWELL(dev))
val |= EDP_PSR_MIN_LINK_ENTRY_TIME_8_LINES;
if (dev_priv->psr.link_standby)
val |= EDP_PSR_LINK_STANDBY;
if (dev_priv->vbt.psr.tp1_wakeup_time > 5)
val |= EDP_PSR_TP1_TIME_2500us;
else if (dev_priv->vbt.psr.tp1_wakeup_time > 1)
val |= EDP_PSR_TP1_TIME_500us;
else if (dev_priv->vbt.psr.tp1_wakeup_time > 0)
val |= EDP_PSR_TP1_TIME_100us;
else
val |= EDP_PSR_TP1_TIME_0us;
if (dev_priv->vbt.psr.tp2_tp3_wakeup_time > 5)
val |= EDP_PSR_TP2_TP3_TIME_2500us;
else if (dev_priv->vbt.psr.tp2_tp3_wakeup_time > 1)
val |= EDP_PSR_TP2_TP3_TIME_500us;
else if (dev_priv->vbt.psr.tp2_tp3_wakeup_time > 0)
val |= EDP_PSR_TP2_TP3_TIME_100us;
else
val |= EDP_PSR_TP2_TP3_TIME_0us;
if (intel_dp_source_supports_hbr2(intel_dp) &&
drm_dp_tps3_supported(intel_dp->dpcd))
val |= EDP_PSR_TP1_TP3_SEL;
else
val |= EDP_PSR_TP1_TP2_SEL;
I915_WRITE(EDP_PSR_CTL, val);
if (!dev_priv->psr.psr2_support)
return;
/* FIXME: selective update is probably totally broken because it doesn't
* mesh at all with our frontbuffer tracking. And the hw alone isn't
* good enough. */
val = EDP_PSR2_ENABLE | EDP_SU_TRACK_ENABLE;
if (dev_priv->vbt.psr.tp2_tp3_wakeup_time > 5)
val |= EDP_PSR2_TP2_TIME_2500;
else if (dev_priv->vbt.psr.tp2_tp3_wakeup_time > 1)
val |= EDP_PSR2_TP2_TIME_500;
else if (dev_priv->vbt.psr.tp2_tp3_wakeup_time > 0)
val |= EDP_PSR2_TP2_TIME_100;
else
val |= EDP_PSR2_TP2_TIME_50;
I915_WRITE(EDP_PSR2_CTL, val);
}
static bool intel_psr_match_conditions(struct intel_dp *intel_dp)
{
struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc = dig_port->base.base.crtc;
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
lockdep_assert_held(&dev_priv->psr.lock);
WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
WARN_ON(!drm_modeset_is_locked(&crtc->mutex));
dev_priv->psr.source_ok = false;
/*
* HSW spec explicitly says PSR is tied to port A.
* BDW+ platforms with DDI implementation of PSR have different
* PSR registers per transcoder and we only implement transcoder EDP
* ones. Since by Display design transcoder EDP is tied to port A
* we can safely escape based on the port A.
*/
if (HAS_DDI(dev) && dig_port->port != PORT_A) {
DRM_DEBUG_KMS("PSR condition failed: Port not supported\n");
return false;
}
if (!i915.enable_psr) {
DRM_DEBUG_KMS("PSR disable by flag\n");
return false;
}
if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
!dev_priv->psr.link_standby) {
DRM_ERROR("PSR condition failed: Link off requested but not supported on this platform\n");
return false;
}
if (IS_HASWELL(dev) &&
I915_READ(HSW_STEREO_3D_CTL(intel_crtc->config->cpu_transcoder)) &
S3D_ENABLE) {
DRM_DEBUG_KMS("PSR condition failed: Stereo 3D is Enabled\n");
return false;
}
if (IS_HASWELL(dev) &&
intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
DRM_DEBUG_KMS("PSR condition failed: Interlaced is Enabled\n");
return false;
}
dev_priv->psr.source_ok = true;
return true;
}
static void intel_psr_activate(struct intel_dp *intel_dp)
{
struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = intel_dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
WARN_ON(I915_READ(EDP_PSR_CTL) & EDP_PSR_ENABLE);
WARN_ON(dev_priv->psr.active);
lockdep_assert_held(&dev_priv->psr.lock);
/* Enable/Re-enable PSR on the host */
if (HAS_DDI(dev))
/* On HSW+ after we enable PSR on source it will activate it
* as soon as it match configure idle_frame count. So
* we just actually enable it here on activation time.
*/
hsw_psr_enable_source(intel_dp);
else
vlv_psr_activate(intel_dp);
dev_priv->psr.active = true;
}
/**
* intel_psr_enable - Enable PSR
* @intel_dp: Intel DP
*
* This function can only be called after the pipe is fully trained and enabled.
*/
void intel_psr_enable(struct intel_dp *intel_dp)
{
struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = intel_dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_crtc *crtc = to_intel_crtc(intel_dig_port->base.base.crtc);
if (!HAS_PSR(dev)) {
DRM_DEBUG_KMS("PSR not supported on this platform\n");
return;
}
if (!is_edp_psr(intel_dp)) {
DRM_DEBUG_KMS("PSR not supported by this panel\n");
return;
}
mutex_lock(&dev_priv->psr.lock);
if (dev_priv->psr.enabled) {
DRM_DEBUG_KMS("PSR already in use\n");
goto unlock;
}
if (!intel_psr_match_conditions(intel_dp))
goto unlock;
dev_priv->psr.busy_frontbuffer_bits = 0;
if (HAS_DDI(dev)) {
hsw_psr_setup_vsc(intel_dp);
if (dev_priv->psr.psr2_support) {
/* PSR2 is restricted to work with panel resolutions upto 3200x2000 */
if (crtc->config->pipe_src_w > 3200 ||
crtc->config->pipe_src_h > 2000)
dev_priv->psr.psr2_support = false;
else
skl_psr_setup_su_vsc(intel_dp);
}
/*
* Per Spec: Avoid continuous PSR exit by masking MEMUP and HPD.
* Also mask LPSP to avoid dependency on other drivers that
* might block runtime_pm besides preventing other hw tracking
* issues now we can rely on frontbuffer tracking.
*/
I915_WRITE(EDP_PSR_DEBUG_CTL, EDP_PSR_DEBUG_MASK_MEMUP |
EDP_PSR_DEBUG_MASK_HPD | EDP_PSR_DEBUG_MASK_LPSP);
/* Enable PSR on the panel */
hsw_psr_enable_sink(intel_dp);
if (INTEL_INFO(dev)->gen >= 9)
intel_psr_activate(intel_dp);
} else {
vlv_psr_setup_vsc(intel_dp);
/* Enable PSR on the panel */
vlv_psr_enable_sink(intel_dp);
/* On HSW+ enable_source also means go to PSR entry/active
* state as soon as idle_frame achieved and here would be
* to soon. However on VLV enable_source just enable PSR
* but let it on inactive state. So we might do this prior
* to active transition, i.e. here.
*/
vlv_psr_enable_source(intel_dp);
}
/*
* FIXME: Activation should happen immediately since this function
* is just called after pipe is fully trained and enabled.
* However on every platform we face issues when first activation
* follows a modeset so quickly.
* - On VLV/CHV we get bank screen on first activation
* - On HSW/BDW we get a recoverable frozen screen until next
* exit-activate sequence.
*/
if (INTEL_INFO(dev)->gen < 9)
schedule_delayed_work(&dev_priv->psr.work,
msecs_to_jiffies(intel_dp->panel_power_cycle_delay * 5));
dev_priv->psr.enabled = intel_dp;
unlock:
mutex_unlock(&dev_priv->psr.lock);
}
static void vlv_psr_disable(struct intel_dp *intel_dp)
{
struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = intel_dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_crtc *intel_crtc =
to_intel_crtc(intel_dig_port->base.base.crtc);
uint32_t val;
if (dev_priv->psr.active) {
/* Put VLV PSR back to PSR_state 0 that is PSR Disabled. */
if (intel_wait_for_register(dev_priv,
VLV_PSRSTAT(intel_crtc->pipe),
VLV_EDP_PSR_IN_TRANS,
0,
1))
WARN(1, "PSR transition took longer than expected\n");
val = I915_READ(VLV_PSRCTL(intel_crtc->pipe));
val &= ~VLV_EDP_PSR_ACTIVE_ENTRY;
val &= ~VLV_EDP_PSR_ENABLE;
val &= ~VLV_EDP_PSR_MODE_MASK;
I915_WRITE(VLV_PSRCTL(intel_crtc->pipe), val);
dev_priv->psr.active = false;
} else {
WARN_ON(vlv_is_psr_active_on_pipe(dev, intel_crtc->pipe));
}
}
static void hsw_psr_disable(struct intel_dp *intel_dp)
{
struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = intel_dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
if (dev_priv->psr.active) {
I915_WRITE(EDP_PSR_CTL,
I915_READ(EDP_PSR_CTL) & ~EDP_PSR_ENABLE);
/* Wait till PSR is idle */
if (intel_wait_for_register(dev_priv,
EDP_PSR_STATUS_CTL,
EDP_PSR_STATUS_STATE_MASK,
0,
2000))
DRM_ERROR("Timed out waiting for PSR Idle State\n");
dev_priv->psr.active = false;
} else {
WARN_ON(I915_READ(EDP_PSR_CTL) & EDP_PSR_ENABLE);
}
}
/**
* intel_psr_disable - Disable PSR
* @intel_dp: Intel DP
*
* This function needs to be called before disabling pipe.
*/
void intel_psr_disable(struct intel_dp *intel_dp)
{
struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
struct drm_device *dev = intel_dig_port->base.base.dev;
struct drm_i915_private *dev_priv = dev->dev_private;
mutex_lock(&dev_priv->psr.lock);
if (!dev_priv->psr.enabled) {
mutex_unlock(&dev_priv->psr.lock);
return;
}
/* Disable PSR on Source */
if (HAS_DDI(dev))
hsw_psr_disable(intel_dp);
else
vlv_psr_disable(intel_dp);
/* Disable PSR on Sink */
drm_dp_dpcd_writeb(&intel_dp->aux, DP_PSR_EN_CFG, 0);
dev_priv->psr.enabled = NULL;
mutex_unlock(&dev_priv->psr.lock);
cancel_delayed_work_sync(&dev_priv->psr.work);
}
static void intel_psr_work(struct work_struct *work)
{
struct drm_i915_private *dev_priv =
container_of(work, typeof(*dev_priv), psr.work.work);
struct intel_dp *intel_dp = dev_priv->psr.enabled;
struct drm_crtc *crtc = dp_to_dig_port(intel_dp)->base.base.crtc;
enum i915_pipe pipe = to_intel_crtc(crtc)->pipe;
/* We have to make sure PSR is ready for re-enable
* otherwise it keeps disabled until next full enable/disable cycle.
* PSR might take some time to get fully disabled
* and be ready for re-enable.
*/
if (HAS_DDI(dev_priv)) {
if (intel_wait_for_register(dev_priv,
EDP_PSR_STATUS_CTL,
EDP_PSR_STATUS_STATE_MASK,
0,
50)) {
DRM_ERROR("Timed out waiting for PSR Idle for re-enable\n");
return;
}
} else {
if (intel_wait_for_register(dev_priv,
VLV_PSRSTAT(pipe),
VLV_EDP_PSR_IN_TRANS,
0,
1)) {
DRM_ERROR("Timed out waiting for PSR Idle for re-enable\n");
return;
}
}
mutex_lock(&dev_priv->psr.lock);
intel_dp = dev_priv->psr.enabled;
if (!intel_dp)
goto unlock;
/*
* The delayed work can race with an invalidate hence we need to
* recheck. Since psr_flush first clears this and then reschedules we
* won't ever miss a flush when bailing out here.
*/
if (dev_priv->psr.busy_frontbuffer_bits)
goto unlock;
intel_psr_activate(intel_dp);
unlock:
mutex_unlock(&dev_priv->psr.lock);
}
static void intel_psr_exit(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_dp *intel_dp = dev_priv->psr.enabled;
struct drm_crtc *crtc = dp_to_dig_port(intel_dp)->base.base.crtc;
enum i915_pipe pipe = to_intel_crtc(crtc)->pipe;
u32 val;
if (!dev_priv->psr.active)
return;
if (HAS_DDI(dev)) {
val = I915_READ(EDP_PSR_CTL);
WARN_ON(!(val & EDP_PSR_ENABLE));
I915_WRITE(EDP_PSR_CTL, val & ~EDP_PSR_ENABLE);
} else {
val = I915_READ(VLV_PSRCTL(pipe));
/* Here we do the transition from PSR_state 3 to PSR_state 5
* directly once PSR State 4 that is active with single frame
* update can be skipped. PSR_state 5 that is PSR exit then
* Hardware is responsible to transition back to PSR_state 1
* that is PSR inactive. Same state after
* vlv_edp_psr_enable_source.
*/
val &= ~VLV_EDP_PSR_ACTIVE_ENTRY;
I915_WRITE(VLV_PSRCTL(pipe), val);
/* Send AUX wake up - Spec says after transitioning to PSR
* active we have to send AUX wake up by writing 01h in DPCD
* 600h of sink device.
* XXX: This might slow down the transition, but without this
* HW doesn't complete the transition to PSR_state 1 and we
* never get the screen updated.
*/
drm_dp_dpcd_writeb(&intel_dp->aux, DP_SET_POWER,
DP_SET_POWER_D0);
}
dev_priv->psr.active = false;
}
/**
* intel_psr_single_frame_update - Single Frame Update
* @dev: DRM device
* @frontbuffer_bits: frontbuffer plane tracking bits
*
* Some platforms support a single frame update feature that is used to
* send and update only one frame on Remote Frame Buffer.
* So far it is only implemented for Valleyview and Cherryview because
* hardware requires this to be done before a page flip.
*/
void intel_psr_single_frame_update(struct drm_device *dev,
unsigned frontbuffer_bits)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc;
enum i915_pipe pipe;
u32 val;
/*
* Single frame update is already supported on BDW+ but it requires
* many W/A and it isn't really needed.
*/
if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev))
return;
mutex_lock(&dev_priv->psr.lock);
if (!dev_priv->psr.enabled) {
mutex_unlock(&dev_priv->psr.lock);
return;
}
crtc = dp_to_dig_port(dev_priv->psr.enabled)->base.base.crtc;
pipe = to_intel_crtc(crtc)->pipe;
if (frontbuffer_bits & INTEL_FRONTBUFFER_ALL_MASK(pipe)) {
val = I915_READ(VLV_PSRCTL(pipe));
/*
* We need to set this bit before writing registers for a flip.
* This bit will be self-clear when it gets to the PSR active state.
*/
I915_WRITE(VLV_PSRCTL(pipe), val | VLV_EDP_PSR_SINGLE_FRAME_UPDATE);
}
mutex_unlock(&dev_priv->psr.lock);
}
/**
* intel_psr_invalidate - Invalidade PSR
* @dev: DRM device
* @frontbuffer_bits: frontbuffer plane tracking bits
*
* Since the hardware frontbuffer tracking has gaps we need to integrate
* with the software frontbuffer tracking. This function gets called every
* time frontbuffer rendering starts and a buffer gets dirtied. PSR must be
* disabled if the frontbuffer mask contains a buffer relevant to PSR.
*
* Dirty frontbuffers relevant to PSR are tracked in busy_frontbuffer_bits."
*/
void intel_psr_invalidate(struct drm_device *dev,
unsigned frontbuffer_bits)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc;
enum i915_pipe pipe;
mutex_lock(&dev_priv->psr.lock);
if (!dev_priv->psr.enabled) {
mutex_unlock(&dev_priv->psr.lock);
return;
}
crtc = dp_to_dig_port(dev_priv->psr.enabled)->base.base.crtc;
pipe = to_intel_crtc(crtc)->pipe;
frontbuffer_bits &= INTEL_FRONTBUFFER_ALL_MASK(pipe);
dev_priv->psr.busy_frontbuffer_bits |= frontbuffer_bits;
if (frontbuffer_bits)
intel_psr_exit(dev);
mutex_unlock(&dev_priv->psr.lock);
}
/**
* intel_psr_flush - Flush PSR
* @dev: DRM device
* @frontbuffer_bits: frontbuffer plane tracking bits
* @origin: which operation caused the flush
*
* Since the hardware frontbuffer tracking has gaps we need to integrate
* with the software frontbuffer tracking. This function gets called every
* time frontbuffer rendering has completed and flushed out to memory. PSR
* can be enabled again if no other frontbuffer relevant to PSR is dirty.
*
* Dirty frontbuffers relevant to PSR are tracked in busy_frontbuffer_bits.
*/
void intel_psr_flush(struct drm_device *dev,
unsigned frontbuffer_bits, enum fb_op_origin origin)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc;
enum i915_pipe pipe;
mutex_lock(&dev_priv->psr.lock);
if (!dev_priv->psr.enabled) {
mutex_unlock(&dev_priv->psr.lock);
return;
}
crtc = dp_to_dig_port(dev_priv->psr.enabled)->base.base.crtc;
pipe = to_intel_crtc(crtc)->pipe;
frontbuffer_bits &= INTEL_FRONTBUFFER_ALL_MASK(pipe);
dev_priv->psr.busy_frontbuffer_bits &= ~frontbuffer_bits;
/* By definition flush = invalidate + flush */
if (frontbuffer_bits)
intel_psr_exit(dev);
if (!dev_priv->psr.active && !dev_priv->psr.busy_frontbuffer_bits)
#if 0
if (!work_busy(&dev_priv->psr.work.work))
#endif
schedule_delayed_work(&dev_priv->psr.work,
msecs_to_jiffies(100));
mutex_unlock(&dev_priv->psr.lock);
}
/**
* intel_psr_init - Init basic PSR work and mutex.
* @dev: DRM device
*
* This function is called only once at driver load to initialize basic
* PSR stuff.
*/
void intel_psr_init(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
dev_priv->psr_mmio_base = IS_HASWELL(dev_priv) ?
HSW_EDP_PSR_BASE : BDW_EDP_PSR_BASE;
/* Per platform default */
if (i915.enable_psr == -1) {
if (IS_HASWELL(dev) || IS_BROADWELL(dev))
i915.enable_psr = 1;
else
i915.enable_psr = 0;
}
/* Set link_standby x link_off defaults */
if (IS_HASWELL(dev) || IS_BROADWELL(dev))
/* HSW and BDW require workarounds that we don't implement. */
dev_priv->psr.link_standby = false;
else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
/* On VLV and CHV only standby mode is supported. */
dev_priv->psr.link_standby = true;
else
/* For new platforms let's respect VBT back again */
dev_priv->psr.link_standby = dev_priv->vbt.psr.full_link;
/* Override link_standby x link_off defaults */
if (i915.enable_psr == 2 && !dev_priv->psr.link_standby) {
DRM_DEBUG_KMS("PSR: Forcing link standby\n");
dev_priv->psr.link_standby = true;
}
if (i915.enable_psr == 3 && dev_priv->psr.link_standby) {
DRM_DEBUG_KMS("PSR: Forcing main link off\n");
dev_priv->psr.link_standby = false;
}
INIT_DELAYED_WORK(&dev_priv->psr.work, intel_psr_work);
lockinit(&dev_priv->psr.lock, "i915dpl", 0, LK_CANRECURSE);
}
| 31.542992 | 93 | 0.736445 | [
"mesh",
"3d"
] |
2ea72b2708c2ce8094a948dde7b49e75943410f6 | 37,147 | c | C | source/lib/font/Speedo/out_scrn.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | 1 | 2021-09-08T21:13:25.000Z | 2021-09-08T21:13:25.000Z | source/lib/font/Speedo/out_scrn.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | null | null | null | source/lib/font/Speedo/out_scrn.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | 1 | 2021-01-22T00:19:47.000Z | 2021-01-22T00:19:47.000Z | /*
Copyright 1989-1991, Bitstream Inc., Cambridge, MA.
You are hereby granted permission under all Bitstream propriety rights to
use, copy, modify, sublicense, sell, and redistribute the Bitstream Speedo
software and the Bitstream Charter outline font for any purpose and without
restrictions; provided, that this notice is left intact on all copies of such
software or font and that Bitstream's trademark is acknowledged as shown below
on all unmodified copies of such font.
BITSTREAM CHARTER is a registered trademark of Bitstream Inc.
BITSTREAM INC. DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. BITSTREAM SHALL NOT BE LIABLE FOR ANY DIRECT OR INDIRECT
DAMAGES, INCLUDING BUT NOT LIMITED TO LOST PROFITS, LOST DATA, OR ANY OTHER
INCIDENTAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF OR IN ANY WAY CONNECTED
WITH THE SPEEDO SOFTWARE OR THE BITSTREAM CHARTER OUTLINE FONT.
*/
/* $XFree86: xc/lib/font/Speedo/out_scrn.c,v 1.7 2006/12/10 15:58:24 tsi Exp $ */
/*************************** O U T _ S C R N . C *****************************
* *
* This is an output module for screen-writer mode. *
* *
*****************************************************************************/
#include "spdo_prv.h" /* General definitions for Speedo */
#ifndef DEBUG
#define DEBUG 0
#endif
#define LOCAL static
#define ABS(X) ( (X < 0) ? -X : X)
#if DEBUG
#include <stdio.h>
#define SHOW(X) printf("X = %lx\n", (unsigned long)X)
#else
#define SHOW(X)
#endif
/***** GLOBAL VARIABLES *****/
/***** GLOBAL FUNCTIONS *****/
/***** EXTERNAL VARIABLES *****/
/***** EXTERNAL FUNCTIONS *****/
/***** STATIC VARIABLES *****/
/***** STATIC FUNCTIONS *****/
static void sp_add_intercept_screen(PROTO_DECL2 fix15 y,fix31 x);
static void sp_proc_intercepts_screen(PROTO_DECL1);
#if INCL_SCREEN
FUNCTION boolean init_screen(
GDECL
specs_t FONTFAR *specsarg)
/*
* init_out0() is called by sp_set_specs() to initialize the output module.
* Returns TRUE if output module can accept requested specifications.
* Returns FALSE otherwise.
*/
{
#if DEBUG
printf("INIT_SCREEN()\n");
#endif
return (TRUE);
}
#endif
#if INCL_SCREEN
FUNCTION boolean begin_char_screen(
GDECL
point_t Psw,
point_t Pmin,
point_t Pmax)
/* Called once at the start of the character generation process
*/
{
#if DEBUG
printf("BEGIN_CHAR_SCREEN(%3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f\n",
(real)Psw.x / (real)sp_globals.onepix, (real)Psw.y / (real)sp_globals.onepix,
(real)Pmin.x / (real)sp_globals.onepix, (real)Pmin.y / (real)sp_globals.onepix,
(real)Pmax.x / (real)sp_globals.onepix, (real)Pmax.y / (real)sp_globals.onepix);
#endif
if (sp_globals.pixshift > 8)
sp_intercepts.fracpix = sp_globals.onepix << (8 - sp_globals.pixshift);
else
sp_intercepts.fracpix = sp_globals.onepix >> (sp_globals.pixshift - 8);
init_char_out(Psw,Pmin,Pmax);
return TRUE;
}
#endif
#if INCL_SCREEN
FUNCTION void begin_contour_screen(
GDECL
point_t P1,
boolean outside)
/* Called at the start of each contour
*/
{
#if DEBUG
printf("BEGIN_CONTOUR_SCREEN(%3.1f, %3.1f, %s)\n",
(real)P1.x / (real)sp_globals.onepix, (real)P1.y / (real)sp_globals.onepix, outside? "outside": "inside");
#endif
sp_globals.x0_spxl = P1.x;
sp_globals.y0_spxl = P1.y;
sp_globals.y_pxl = (sp_globals.y0_spxl + sp_globals.pixrnd) >> sp_globals.pixshift;
}
#endif
#if INCL_SCREEN
FUNCTION void curve_screen(
GDECL
point_t P1, point_t P2, point_t P3,
fix15 depth)
{
fix31 X0;
fix31 Y0;
fix31 X1;
fix31 Y1;
fix31 X2;
fix31 Y2;
fix31 X3;
fix31 Y3;
#if DEBUG
printf("CURVE_SCREEN(%6.4f, %6.4f, %6.4f, %6.4f, %6.4f, %6.4f)\n",
(real)P1.x / (real)sp_globals.onepix, (real)P1.y / (real)sp_globals.onepix,
(real)P2.x / (real)sp_globals.onepix, (real)P2.y / (real)sp_globals.onepix,
(real)P3.x / (real)sp_globals.onepix, (real)P3.y / (real)sp_globals.onepix);
#endif
if (sp_globals.extents_running) /* Accumulate actual character extents if required */
{
if (P3.x > sp_globals.bmap_xmax)
sp_globals.bmap_xmax = P3.x;
if (P3.x < sp_globals.bmap_xmin)
sp_globals.bmap_xmin = P3.x;
if (P3.y > sp_globals.bmap_ymax)
sp_globals.bmap_ymax = P3.y;
if (P3.y < sp_globals.bmap_ymin)
sp_globals.bmap_ymin = P3.y;
}
X0 = ((fix31)sp_globals.x0_spxl << sp_globals.poshift) + (fix31)32768;
Y0 = ((fix31)sp_globals.y0_spxl << sp_globals.poshift) + (fix31)32768;
X1 = ((fix31)P1.x << sp_globals.poshift) + (fix31)32768;
Y1 = ((fix31)P1.y << sp_globals.poshift) + (fix31)32768;
X2 = ((fix31)P2.x << sp_globals.poshift) + (fix31)32768;
Y2 = ((fix31)P2.y << sp_globals.poshift) + (fix31)32768;
X3 = ((fix31)P3.x << sp_globals.poshift) + (fix31)32768;
Y3 = ((fix31)P3.y << sp_globals.poshift) + (fix31)32768;
if (((Y0 - Y3) * sp_globals.tcb.mirror) > 0)
{
sp_intercepts.leftedge = LEFT_INT;
}
else
{
sp_intercepts.leftedge = 0;
}
scan_curve_screen(X0,Y0,X1,Y1,X2,Y2,X3,Y3);
sp_globals.x0_spxl = P3.x;
sp_globals.y0_spxl = P3.y;
sp_globals.y_pxl = (P3.y + sp_globals.pixrnd) >> sp_globals.pixshift; /* calculate new end-scan sp_globals.line */
}
FUNCTION void scan_curve_screen(
GDECL
fix31 X0, fix31 Y0, fix31 X1, fix31 Y1, fix31 X2, fix31 Y2, fix31 X3, fix31 Y3)
/* Called for each curve in the transformed character if curves out enabled
*/
{
fix31 Pmidx;
fix31 Pmidy;
fix31 Pctrl1x;
fix31 Pctrl1y;
fix31 Pctrl2x;
fix31 Pctrl2y;
#ifdef DBGCRV
printf("SCAN_CURVE_SCREEN(%6.4f, %6.4f, %6.4f, %6.4f, %6.4f, %6.4f, %6.4f, %6.4f)\n",
(real)(X0-32768) / 65536.0, (real)(Y0-32768) / 65536.0,
(real)(X1-32768) / 65536.0, (real)(Y1-32768) / 65536.0,
(real)(X2-32768) / 65536.0, (real)(Y2-32768) / 65536.0,
(real)(X3-32768) / 65536.0, (real)(Y3-32768) / 65536.0);
#endif
if (((Y3 >> 16)) == (Y0 >> 16) || (Y3+1) == Y0 || Y3 == (Y0+1))
{
return;
}
if ((X3 >> 16) == (X0 >> 16))
{
vert_line_screen(X3,(fix15)(Y0>>16),(fix15)(Y3>>16));
return;
}
Pmidx = (X0 + (X1 + X2) * 3 + X3 + 4 ) >> 3;
Pmidy = (Y0 + (Y1 + Y2) * 3 + Y3 + 4 ) >> 3;
Pctrl1x = (X0 + X1 + 1 ) >> 1;
Pctrl1y = (Y0 + Y1 + 1) >> 1;
Pctrl2x = (X0 + (X1 << 1) + X2 + 2 ) >> 2;
Pctrl2y = (Y0 + (Y1 << 1) + Y2 + 2 ) >> 2;
scan_curve_screen(X0,Y0, Pctrl1x, Pctrl1y, Pctrl2x,Pctrl2y, Pmidx,Pmidy);
Pctrl1x = (X1 + (X2 << 1) + X3 + 2 ) >> 2;
Pctrl1y = (Y1 + (Y2 << 1) + Y3 + 2 ) >> 2;
Pctrl2x = (X2 + X3 + 1 ) >> 1;
Pctrl2y = (Y2 + Y3 + 1 ) >> 1;
scan_curve_screen(Pmidx,Pmidy, Pctrl1x,Pctrl1y, Pctrl2x,Pctrl2y, X3,Y3);
}
FUNCTION void vert_line_screen(
GDECL
fix31 x,
fix15 y1, fix15 y2)
{
#ifdef DBGCRV
printf("VERT_LINE_SCREEN(%6.4f, %6.4f, %6.4f)\n",
(real)(x - 32768) / 65536.0,
(real)(y1 - 32768) / 65536.0,
(real)(y2 - 32768) / 65536.0);
#endif
if (sp_globals.intercept_oflo)
return;
if (y1 > y2) /* Line goes downwards ? */
{
if (y1 > (sp_globals.y_band.band_max + 1)) /* Start point above top of band? */
y1 = sp_globals.y_band.band_max + 1; /* Adjust start point to top of band */
if (y2 < sp_globals.y_band.band_min) /* End point below bottom of band? */
y2 = sp_globals.y_band.band_min; /* Adjust end point bottom of band */
y1 -= sp_globals.y_band.band_min; /* Translate start point to band origin */
y2 -= sp_globals.y_band.band_min; /* Translate end point to band origin */
while (y2 < y1) /* At least one intercept left? */
{
sp_add_intercept_screen(--y1, x); /* Add intercept */
}
}
else if (y2 > y1) /* Line goes upwards ? */
{
if (y1 < sp_globals.y_band.band_min) /* Start point below bottom of band? */
y1 = sp_globals.y_band.band_min; /* Adjust start point to bottom of band */
if (y2 > (sp_globals.y_band.band_max + 1)) /* End point above top of band? */
y2 = sp_globals.y_band.band_max + 1; /* Adjust end point to top of band */
y1 -= sp_globals.y_band.band_min; /* Translate start point to band origin */
y2 -= sp_globals.y_band.band_min; /* Translate end point to band origin */
while (y1 < y2) /* At least one intercept left? */
{
sp_add_intercept_screen(y1++, x); /* Add intercept */
}
}
}
#endif
#if INCL_SCREEN
FUNCTION void line_screen(
GDECL
point_t P1)
/* Called for each vector in the transformed character
*/
{
register fix15 how_many_y; /* # of intercepts at y = n + 1/2 */
register fix15 yc; /* Current scan-line */
fix15 temp1; /* various uses */
fix15 temp2; /* various uses */
register fix31 dx_dy; /* slope of line in 16.16 form */
register fix31 xc; /* high-precision (16.16) x coordinate */
fix15 x0,y0,x1,y1; /* PIX.FRAC start and endpoints */
x0 = sp_globals.x0_spxl; /* get start of line (== current point) */
y0 = sp_globals.y0_spxl;
sp_globals.x0_spxl = x1 = P1.x; /* end of line */
sp_globals.y0_spxl = y1 = P1.y; /* (also update current point to end of line) */
yc = sp_globals.y_pxl; /* current scan line = end of last line */
sp_globals.y_pxl = (y1 + sp_globals.pixrnd) >> sp_globals.pixshift; /* calculate new end-scan sp_globals.line */
#if DEBUG
printf("LINE_SCREEN(%3.4f, %3.4f)\n",
(real)P1.x/(real)sp_globals.onepix,
(real)P1.y/(real)sp_globals.onepix);
#endif
if (sp_globals.extents_running)
{
if (sp_globals.x0_spxl > sp_globals.bmap_xmax)
sp_globals.bmap_xmax = sp_globals.x0_spxl;
if (sp_globals.x0_spxl < sp_globals.bmap_xmin)
sp_globals.bmap_xmin = sp_globals.x0_spxl;
if (sp_globals.y0_spxl > sp_globals.bmap_ymax)
sp_globals.bmap_ymax = sp_globals.y0_spxl;
if (sp_globals.y0_spxl < sp_globals.bmap_ymin)
sp_globals.bmap_ymin = sp_globals.y0_spxl;
}
if (sp_globals.intercept_oflo) return;
if ((how_many_y = sp_globals.y_pxl - yc) == 0) return; /* Don't draw a null line */
xc = (fix31)(x0 + sp_globals.pixrnd) << (16 - sp_globals.pixshift); /* Original x coordinate with built in */
/* rounding. 16.16 form */
if (how_many_y < 0)
{
yc--; /* Predecrment downward lines */
}
if ((how_many_y * sp_globals.tcb.mirror) < 0)
{
sp_intercepts.leftedge = LEFT_INT;
}
else
{
sp_intercepts.leftedge = 0;
}
if (yc > sp_globals.y_band.band_max) /* Is start point above band? */
{
if (sp_globals.y_pxl > sp_globals.y_band.band_max) return; /* line has to go down! */
how_many_y = sp_globals.y_pxl - (yc = sp_globals.y_band.band_max) - 1; /* Yes, limit it */
}
if (yc < sp_globals.y_band.band_min) /* Is start point below band? */
{
if (sp_globals.y_pxl < sp_globals.y_band.band_min) return; /* line has to go up! */
how_many_y = sp_globals.y_pxl - (yc = sp_globals.y_band.band_min); /* Yes, limit it */
}
if ( (temp1 = (x1 - x0)) == 0) /* check for vertical line */
{
dx_dy = 0L; /* Zero slope, leave xc alone */
goto skip_calc;
}
/* calculate dx_dy at 16.16 fixed point */
dx_dy = ( (fix31)temp1 << 16 )/(fix31)(y1 - y0);
/* We have to check for a @#$%@# possible multiply overflow */
/* by doing another @#$*& multiply. In assembly language, */
/* the program could just check the OVerflow flag or whatever*/
/* works on the particular processor. This C code is meant */
/* to be processor independant. */
temp1 = (yc << sp_globals.pixshift) - y0 + sp_globals.pixrnd;
/* This sees if the sign bits start at bit 15 */
/* if they do, no overflow has occurred */
temp2 = (fix15)(MULT16(temp1,(fix15)(dx_dy >> 16)) >> 15);
if ( (temp2 != (fix15)-1) &&
(temp2 != 0x0000) )
{ /* Overflow. Pick point closest to yc + .5 */
if (ABS(temp1) < ABS((yc << sp_globals.pixshift) - y1 + sp_globals.pixrnd))
{ /* use x1 instead of x0 */
xc = (fix31)(x1 + sp_globals.pixrnd) << (16 - sp_globals.pixshift);
}
goto skip_calc;
}
/* calculate new xc at the center of the *current* scan line */
/* due to banding, yc may be several lines away from y0 */
/* xc += (yc + .5 - y0) * dx_dy */
/* This multiply generates a subpixel delta. */
/* So we shift it to be a 16.16 delta */
xc += ((fix31)temp1 * dx_dy) >> sp_globals.pixshift;
skip_calc:
yc -= sp_globals.y_band.band_min; /* yc is now an offset relative to the band */
if (how_many_y < 0)
{ /* Vector down */
if ((how_many_y += yc + 1) < 0) how_many_y = 0; /* can't go below 0 */
while(yc >= how_many_y)
{
sp_add_intercept_screen(yc--,xc);
xc -= dx_dy;
}
}
else
{ /* Vector up */
/* check to see that line doesn't extend beyond top of band */
if ((how_many_y += yc) > sp_globals.no_y_lists) how_many_y = sp_globals.no_y_lists;
while(yc != how_many_y)
{
sp_add_intercept_screen(yc++,xc);
xc += dx_dy;
}
}
}
#endif
#if INCL_SCREEN
FUNCTION void end_contour_screen()
GDECL
/* Called after the last vector in each contour
*/
{
#if DEBUG
printf("END_CONTOUR_SCREEN()\n");
#endif
sp_intercepts.inttype[sp_globals.next_offset-1] |= END_INT;
}
#endif
#if INCL_SCREEN
FUNCTION boolean end_char_screen()
GDECL
/* Called when all character data has been output
* Return TRUE if output process is complete
* Return FALSE to repeat output of the transformed data beginning
* with the first contour
*/
{
fix31 xorg;
fix31 yorg;
#if INCL_CLIPPING
fix31 em_max, em_min, bmap_max, bmap_min;
#endif
#if DEBUG
printf("END_CHAR_SCREEN()\n");
#endif
if (sp_globals.first_pass)
{
if (sp_globals.bmap_xmax >= sp_globals.bmap_xmin)
{
sp_globals.xmin = (sp_globals.bmap_xmin + sp_globals.pixrnd + 1) >> sp_globals.pixshift;
sp_globals.xmax = (sp_globals.bmap_xmax + sp_globals.pixrnd) >> sp_globals.pixshift;
}
else
{
sp_globals.xmin = sp_globals.xmax = 0;
}
if (sp_globals.bmap_ymax >= sp_globals.bmap_ymin)
{
#if INCL_CLIPPING
switch(sp_globals.tcb0.xtype)
{
case 1: /* 180 degree rotation */
if (sp_globals.specs.flags & CLIP_TOP)
{
sp_globals.clip_ymin = (fix31)((fix31)EM_TOP * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_ymin = sp_globals.clip_ymin >> sp_globals.multshift;
bmap_min = (sp_globals.bmap_ymin + sp_globals.pixrnd + 1) >> sp_globals.pixshift;
sp_globals.clip_ymin = -1 * sp_globals.clip_ymin;
if (bmap_min < sp_globals.clip_ymin)
sp_globals.ymin = sp_globals.clip_ymin;
else
sp_globals.ymin = bmap_min;
}
if (sp_globals.specs.flags & CLIP_BOTTOM)
{
sp_globals.clip_ymax = (fix31)((fix31)(-1 * EM_BOT) * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_ymax = sp_globals.clip_ymax >> sp_globals.multshift;
bmap_max = (sp_globals.bmap_ymax + sp_globals.pixrnd) >> sp_globals.pixshift;
if (bmap_max < sp_globals.clip_ymax)
sp_globals.ymax = bmap_max;
else
sp_globals.ymax = sp_globals.clip_ymax;
}
sp_globals.clip_xmax = -sp_globals.xmin;
sp_globals.clip_xmin = ((sp_globals.set_width.x+32768L) >> 16) -
sp_globals.xmin;
break;
case 2: /* 90 degree rotation */
if (sp_globals.specs.flags & CLIP_TOP)
{
sp_globals.clip_xmin = (fix31)((fix31)(-1 * EM_BOT) * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_xmin = sp_globals.clip_xmin >> sp_globals.multshift;
sp_globals.clip_xmin = -1 * sp_globals.clip_xmin;
bmap_min = (sp_globals.bmap_xmin + sp_globals.pixrnd + 1) >> sp_globals.pixshift;
if (bmap_min > sp_globals.clip_xmin)
sp_globals.clip_xmin = bmap_min;
/* normalize to x origin */
sp_globals.clip_xmin -= sp_globals.xmin;
}
if (sp_globals.specs.flags & CLIP_BOTTOM)
{
sp_globals.clip_xmax = (fix31)((fix31)EM_TOP * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_xmax = sp_globals.clip_xmax >> sp_globals.multshift;
bmap_max = (sp_globals.bmap_xmax + sp_globals.pixrnd) >> sp_globals.pixshift;
if (bmap_max < sp_globals.clip_xmax)
sp_globals.xmax = bmap_max;
else
sp_globals.xmax = sp_globals.clip_xmax;
sp_globals.clip_ymax = 0;
if ((sp_globals.specs.flags & CLIP_TOP) &&
(sp_globals.ymax > sp_globals.clip_ymax))
sp_globals.ymax = sp_globals.clip_ymax;
sp_globals.clip_ymin = ((sp_globals.set_width.y+32768L) >> 16);
if ((sp_globals.specs.flags & CLIP_BOTTOM) &&
(sp_globals.ymin < sp_globals.clip_ymin))
sp_globals.ymin = sp_globals.clip_ymin;
/* normalize to x origin */
sp_globals.clip_xmax -= sp_globals.xmin;
}
break;
case 3: /* 270 degree rotation */
if (sp_globals.specs.flags & CLIP_TOP)
{
sp_globals.clip_xmin = (fix31)((fix31)EM_TOP * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_xmin = sp_globals.clip_xmin >> sp_globals.multshift;
sp_globals.clip_xmin = -1 * sp_globals.clip_xmin;
bmap_min = (sp_globals.bmap_xmin + sp_globals.pixrnd + 1) >> sp_globals.pixshift;
/* let the minimum be the larger of these two values */
if (bmap_min > sp_globals.clip_xmin)
sp_globals.clip_xmin = bmap_min;
/* normalize the x value to new xorgin */
sp_globals.clip_xmin -= sp_globals.xmin;
}
if (sp_globals.specs.flags & CLIP_BOTTOM)
{
sp_globals.clip_xmax = (fix31)((fix31)(-1 * EM_BOT) * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_xmax = sp_globals.clip_xmax >> sp_globals.multshift;
bmap_max = (sp_globals.bmap_xmax + sp_globals.pixrnd) >> sp_globals.pixshift;
/* let the max be the lesser of these two values */
if (bmap_max < sp_globals.clip_xmax)
{
sp_globals.xmax = bmap_max;
sp_globals.clip_xmax = bmap_max;
}
else
sp_globals.xmax = sp_globals.clip_xmax;
/* normalize the x value to new x origin */
sp_globals.clip_xmax -= sp_globals.xmin;
}
/* compute y clip values */
sp_globals.clip_ymax = ((sp_globals.set_width.y+32768L) >> 16);
if ((sp_globals.specs.flags & CLIP_TOP) &&
(sp_globals.ymax > sp_globals.clip_ymax))
sp_globals.ymax = sp_globals.clip_ymax;
sp_globals.clip_ymin = 0;
if ((sp_globals.specs.flags & CLIP_BOTTOM) &&
(sp_globals.ymin < sp_globals.clip_ymin))
sp_globals.ymin = sp_globals.clip_ymin;
break;
default: /* this is for zero degree rotation and arbitrary rotation */
if (sp_globals.specs.flags & CLIP_TOP)
{
sp_globals.clip_ymax = (fix31)((fix31)EM_TOP * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_ymax = sp_globals.clip_ymax >> sp_globals.multshift;
bmap_max = (sp_globals.bmap_ymax + sp_globals.pixrnd) >> sp_globals.pixshift;
if (bmap_max > sp_globals.clip_ymax)
sp_globals.ymax = bmap_max;
else
sp_globals.ymax = sp_globals.clip_ymax;
}
if (sp_globals.specs.flags & CLIP_BOTTOM)
{
sp_globals.clip_ymin = (fix31)((fix31)(-1 * EM_BOT) * sp_globals.tcb0.yppo + ((1<<sp_globals.multshift)/2));
sp_globals.clip_ymin = sp_globals.clip_ymin >> sp_globals.multshift;
sp_globals.clip_ymin = - sp_globals.clip_ymin;
bmap_min = (sp_globals.bmap_ymin + sp_globals.pixrnd + 1) >> sp_globals.pixshift;
if (bmap_min < sp_globals.clip_ymin)
sp_globals.ymin = sp_globals.clip_ymin;
else
sp_globals.ymin = bmap_min;
}
sp_globals.clip_xmin = -sp_globals.xmin;
sp_globals.clip_xmax = ((sp_globals.set_width.x+32768L) >> 16) -
sp_globals.xmin;
break;
}
if ( !(sp_globals.specs.flags & CLIP_TOP))
#endif
sp_globals.ymax = (sp_globals.bmap_ymax + sp_globals.pixrnd) >> sp_globals.pixshift;
#if INCL_CLIPPING
if ( !(sp_globals.specs.flags & CLIP_BOTTOM))
#endif
sp_globals.ymin = (sp_globals.bmap_ymin + sp_globals.pixrnd + 1) >> sp_globals.pixshift;
}
else
{
sp_globals.ymin = sp_globals.ymax = 0;
}
/* add in the rounded out part (from xform.) of the left edge */
if (sp_globals.tcb.xmode == 0) /* for X pix is function of X orus only add the round */
xorg = (((fix31)sp_globals.xmin << 16) + (sp_globals.rnd_xmin << sp_globals.poshift));
else
if (sp_globals.tcb.xmode == 1) /* for X pix is function of -X orus only, subtr. round */
xorg = (((fix31)sp_globals.xmin << 16) - (sp_globals.rnd_xmin << sp_globals.poshift)) ;
else
xorg = (fix31)sp_globals.xmin << 16; /* for other cases don't use round on x */
if (sp_globals.tcb.ymode == 2) /* for Y pix is function of X orus only, add round error */
yorg = (((fix31)sp_globals.ymin << 16) + (sp_globals.rnd_xmin << sp_globals.poshift));
else
if (sp_globals.tcb.ymode == 3) /* for Y pix is function of -X orus only, sub round */
yorg = (((fix31)sp_globals.ymin << 16) - (sp_globals.rnd_xmin << sp_globals.poshift));
else /* all other cases have no round error on yorg */
yorg = (fix31)sp_globals.ymin << 16;
open_bitmap(sp_globals.set_width.x, sp_globals.set_width.y, xorg, yorg,
sp_globals.xmax - sp_globals.xmin, sp_globals.ymax - sp_globals.ymin);
if (sp_globals.intercept_oflo)
{
sp_globals.y_band.band_min = sp_globals.ymin;
sp_globals.y_band.band_max = sp_globals.ymax;
init_intercepts_out();
sp_globals.first_pass = FALSE;
sp_globals.extents_running = FALSE;
return FALSE;
}
else
{
sp_proc_intercepts_screen();
close_bitmap();
return TRUE;
}
}
else
{
if (sp_globals.intercept_oflo)
{
reduce_band_size_out();
init_intercepts_out();
return FALSE;
}
else
{
sp_proc_intercepts_screen();
if (next_band_out())
{
init_intercepts_out();
return FALSE;
}
close_bitmap();
return TRUE;
}
}
}
#endif
#if INCL_SCREEN
FUNCTION LOCAL void sp_add_intercept_screen(
GDECL
fix15 y, /* Y coordinate in relative pixel units */
/* (0 is lowest sample in band) */
fix31 x) /* X coordinate of intercept in subpixel units */
/* Called by line() to add an intercept to the intercept list structure
*/
{
register fix15 from; /* Insertion pointers for the linked list sort */
register fix15 to;
register fix15 xloc;
register fix15 xfrac;
#if DEBUG
printf(" Add intercept(%2d, %x)\n", y + sp_globals.y_band.band_min, x);
/* Bounds checking IS done in debug mode */
if (y < 0) /* Y value below bottom of current band? */
{
printf(" Intecerpt less than 0!!!\007\n");
return;
}
if (y > (sp_globals.no_y_lists - 1)) /* Y value above top of current band? */
{
printf(" Intercept too big for band!!!!!\007\n");
return;
}
#endif
/* Store new values */
sp_intercepts.car[sp_globals.next_offset] = xloc = (fix15)(x >> 16);
sp_intercepts.inttype[sp_globals.next_offset] = sp_intercepts.leftedge | (xfrac = ((x >> 8) & FRACTION));
/* Find slot to insert new element (between from and to) */
from = y; /* Start at list head */
while( (to = sp_intercepts.cdr[from]) != 0) /* Until to == end of list */
{
if (xloc < sp_intercepts.car[to]) /* If next item is larger than or same as this one... */
goto insert_element; /* ... drop out and insert here */
else if (xloc == sp_intercepts.car[to] && xfrac < (sp_intercepts.inttype[to] & FRACTION))
goto insert_element; /* ... drop out and insert here */
from = to; /* move forward in list */
}
insert_element: /* insert element "sp_globals.next_offset" between elements "from" */
/* and "to" */
sp_intercepts.cdr[from] = sp_globals.next_offset;
sp_intercepts.cdr[sp_globals.next_offset] = to;
if (++sp_globals.next_offset >= MAX_INTERCEPTS) /* Intercept buffer full? */
{
sp_globals.intercept_oflo = TRUE;
/* There may be a few more calls to "add_intercept" from the current line */
/* To avoid problems, we set next_offset to a safe value. We don't care */
/* if the intercept table gets trashed at this point */
sp_globals.next_offset = sp_globals.first_offset;
}
}
#endif
#if INCL_SCREEN
FUNCTION LOCAL void sp_proc_intercepts_screen()
GDECL
/* Called by sp_make_char to output accumulated intercept lists
* Clips output to sp_globals.xmin, sp_globals.xmax, sp_globals.ymin, sp_globals.ymax boundaries
*/
{
register fix15 i,j, jplus1, iminus1;
fix15 k,nextk, previ;
register fix15 from, to; /* Start and end of run in pixel units
relative to left extent of character */
register fix15 y;
register fix15 scan_line;
fix15 first_y, last_y;
fix15 xsave;
fix15 diff;
#if DEBUG
printf("\nPROC_INTERCEPTS_SCREEN: Intercept lists before:\n");
#endif
#if INCL_CLIPPING
if ((sp_globals.specs.flags & CLIP_LEFT) != 0)
clipleft = TRUE;
else
clipleft = FALSE;
if ((sp_globals.specs.flags & CLIP_RIGHT) != 0)
clipright = TRUE;
else
clipright = FALSE;
if (clipleft || clipright)
{
xmax = sp_globals.clip_xmax + sp_globals.xmin;
xmin = sp_globals.clip_xmin + sp_globals.xmin;
}
if (!clipright)
xmax = ((sp_globals.set_width.x+32768L) >> 16);
#endif
if ((first_y = sp_globals.y_band.band_max) >= sp_globals.ymax)
first_y = sp_globals.ymax - 1; /* Clip to sp_globals.ymax boundary */
if ((last_y = sp_globals.y_band.band_min) < sp_globals.ymin)
last_y = sp_globals.ymin; /* Clip to sp_globals.ymin boundary */
last_y -= sp_globals.y_band.band_min;
#if DEBUG
/* Print out all of the intercept info */
scan_line = sp_globals.ymax - first_y - 1;
for (y = first_y - sp_globals.y_band.band_min; y >= last_y; y--, scan_line++)
{
i = y; /* Index head of intercept list */
while ((i = sp_intercepts.cdr[i]) != 0) /* Link to next intercept if present */
{
if ((from = sp_intercepts.car[i] - sp_globals.xmin) < 0)
from = 0; /* Clip to sp_globals.xmin boundary */
i = sp_intercepts.cdr[i]; /* Link to next intercept */
if (i == 0) /* End of list? */
{
printf("****** proc_intercepts: odd number of intercepts\n");
break;
}
if ((to = sp_intercepts.car[i]) > sp_globals.xmax)
to = sp_globals.xmax - sp_globals.xmin; /* Clip to sp_globals.xmax boundary */
else
to -= sp_globals.xmin;
printf(" Y = %2d (scanline %2d): %d %d:\n",
y + sp_globals.y_band.band_min, scan_line, from, to);
}
}
#endif
/* CHECK INTERCEPT LIST FOR DROPOUT AND WINDING, FIX IF NECESSARY */
for (y = first_y - sp_globals.y_band.band_min; y >= last_y; y--)
{
previ = y;
i = sp_intercepts.cdr[y]; /* Index head of intercept list */
while (i != 0) /* Link to next intercept if present */
{
j = i;
i = sp_intercepts.cdr[i]; /* Link to next intercept */
if (sp_intercepts.inttype[i] & LEFT_INT)
{
if (sp_intercepts.inttype[j] & LEFT_INT)
{
do { i = sp_intercepts.cdr[i]; } while (sp_intercepts.inttype[i] & LEFT_INT);
do { i = sp_intercepts.cdr[i]; } while (sp_intercepts.cdr[i] && !(sp_intercepts.inttype[sp_intercepts.cdr[i]] & LEFT_INT));
sp_intercepts.cdr[j] = i;
}
else
{
xsave = sp_intercepts.car[j];
sp_intercepts.car[j] = sp_intercepts.car[i];
sp_intercepts.car[i] = xsave;
xsave = sp_intercepts.inttype[j];
sp_intercepts.inttype[j] = sp_intercepts.inttype[i] & FRACTION;
sp_intercepts.inttype[i] = xsave | LEFT_INT;
sp_intercepts.cdr[previ] = i;
sp_intercepts.cdr[j] = sp_intercepts.cdr[i];
sp_intercepts.cdr[i] = j;
i = j;
j = sp_intercepts.cdr[previ];
}
}
if (sp_intercepts.car[j] < sp_globals.xmin)
sp_intercepts.car[j] = sp_globals.xmin; /* Clip to sp_globals.xmin boundary */
if (sp_intercepts.car[i] > sp_globals.xmax)
sp_intercepts.car[i] = sp_globals.xmax;
if (sp_intercepts.car[j] >= sp_intercepts.car[i])
{
if ((ufix16)(sp_intercepts.inttype[j] & FRACTION) + (ufix16)(sp_intercepts.inttype[i] & FRACTION) > sp_intercepts.fracpix)
++sp_intercepts.car[i];
else
--sp_intercepts.car[j];
}
if (sp_globals.first_pass)
{
if (sp_intercepts.inttype[i-1] & END_INT)
{
for (iminus1 = i+1; !(sp_intercepts.inttype[iminus1] & END_INT); iminus1++)
;
}
else
iminus1 = i-1;
if (sp_intercepts.inttype[j] & END_INT)
{
for (jplus1 = j-1; !(sp_intercepts.inttype[jplus1] & END_INT); jplus1--)
;
jplus1++;
}
else
jplus1 = j+1;
if ((sp_intercepts.inttype[iminus1] & LEFT_INT))
{
if ( sp_intercepts.car[jplus1] > sp_intercepts.car[i])
{
diff = sp_intercepts.car[jplus1] - sp_intercepts.car[i];
sp_intercepts.car[i] += diff/2;
sp_intercepts.car[jplus1] -= diff/2;
if (diff & 1)
{
if ((ufix16)(sp_intercepts.inttype[i] & FRACTION) + (ufix16)(sp_intercepts.inttype[jplus1] & FRACTION) > sp_intercepts.fracpix)
sp_intercepts.car[i] ++;
else
sp_intercepts.car[jplus1]--;
}
}
}
else if (!(sp_intercepts.inttype[jplus1] & LEFT_INT))
{
if (sp_intercepts.car[iminus1] < sp_intercepts.car[j])
{
diff = sp_intercepts.car[j] - sp_intercepts.car[iminus1];
sp_intercepts.car[j] -= diff/2;
sp_intercepts.car[iminus1] += diff/2;
if (diff & 1)
{
if ((ufix16)(sp_intercepts.inttype[j] & FRACTION) +
(ufix16)(sp_intercepts.inttype[iminus1] & FRACTION) > sp_intercepts.fracpix)
sp_intercepts.car[iminus1]++;
else
sp_intercepts.car[j]--;
}
}
}
if (sp_globals.tcb.mirror == -1)
{
if (sp_intercepts.inttype[j-1] & END_INT)
{
for (jplus1 = j+1; !(sp_intercepts.inttype[jplus1] & END_INT); jplus1++)
;
}
else
{
jplus1 = j-1;
}
}
if (!(sp_intercepts.inttype[jplus1] & LEFT_INT) &&
sp_intercepts.car[j] > sp_intercepts.car[jplus1])
{
k = sp_intercepts.cdr[y - 1];
while (k > 0)
{
nextk = sp_intercepts.cdr[k];
if (!(sp_intercepts.inttype[k] & LEFT_INT) &&
(sp_intercepts.inttype[nextk] & LEFT_INT) &&
sp_intercepts.car[nextk] > sp_intercepts.car[jplus1])
{
if ((diff=sp_intercepts.car[j] - sp_intercepts.car[k]) > 0)
{
if (diff <= (sp_intercepts.car[nextk] - sp_intercepts.car[jplus1]))
{
sp_intercepts.car[j] -= diff/2;
sp_intercepts.car[k] += diff/2;
if (diff & 1)
{
if ((ufix16)(sp_intercepts.inttype[j] & FRACTION) +
(ufix16)(sp_intercepts.inttype[k] & FRACTION) > sp_intercepts.fracpix)
sp_intercepts.car[j]--;
else
sp_intercepts.car[k]++;
}
}
else
{
diff = sp_intercepts.car[nextk] - sp_intercepts.car[jplus1];
sp_intercepts.car[nextk] -= diff/2;
sp_intercepts.car[jplus1] += diff/2;
if (diff & 1)
{
if ((ufix16)(sp_intercepts.inttype[jplus1] & FRACTION) +
(ufix16)(sp_intercepts.inttype[nextk] & FRACTION) > sp_intercepts.fracpix)
sp_intercepts.car[nextk]--;
else
sp_intercepts.car[jplus1]++;
}
}
}
break;
}
k = nextk;
}
}
if (j > 0 && sp_intercepts.car[j-1] > sp_intercepts.car[i] && !(sp_intercepts.inttype[j-1] & END_INT))
{
diff = sp_intercepts.car[j-1] - sp_intercepts.car[i];
sp_intercepts.car[i] += diff/2;
sp_intercepts.car[j-1] -= diff/2;
if (diff & 1)
{
if ((ufix16)(sp_intercepts.inttype[i] & FRACTION) + (ufix16)(sp_intercepts.inttype[j-1] & FRACTION) > sp_intercepts.fracpix)
sp_intercepts.car[i]++;
else
sp_intercepts.car[j-1]--;
}
}
if (sp_intercepts.car[i+1] < sp_intercepts.car[j] && !(sp_intercepts.inttype[i] & END_INT))
{
diff = sp_intercepts.car[j] - sp_intercepts.car[i+1];
sp_intercepts.car[j] -= diff/2;
sp_intercepts.car[i+1] += diff/2;
if (diff & 1)
{
if ((ufix16)(sp_intercepts.inttype[j] & FRACTION) + (ufix16)(sp_intercepts.inttype[i+1] & FRACTION) > sp_intercepts.fracpix)
sp_intercepts.car[i+1]++;
else
sp_intercepts.car[j]--;
}
}
previ = i;
}
i = sp_intercepts.cdr[i];
}
}
#if DEBUG
printf("\nPROC_INTERCEPTS_SCREEN: Intercept lists after:\n");
/* Print out all of the intercept info */
scan_line = sp_globals.ymax - first_y - 1;
for (y = first_y - sp_globals.y_band.band_min; y >= last_y; y--, scan_line++)
{
i = y; /* Index head of intercept list */
while ((i = sp_intercepts.cdr[i]) != 0) /* Link to next intercept if present */
{
if ((from = sp_intercepts.car[i] - sp_globals.xmin) < 0)
from = 0; /* Clip to sp_globals.xmin boundary */
i = sp_intercepts.cdr[i]; /* Link to next intercept */
if (i == 0) /* End of list? */
{
printf("****** proc_intercepts: odd number of intercepts\n");
break;
}
if ((to = sp_intercepts.car[i]) > sp_globals.xmax)
to = sp_globals.xmax - sp_globals.xmin; /* Clip to sp_globals.xmax boundary */
else
to -= sp_globals.xmin;
printf(" Y = %2d (scanline %2d): %d %d:\n",
y + sp_globals.y_band.band_min, scan_line, from, to);
}
}
#endif
/* INTERCEPTS ALL PATCHED, NOW DRAW THE IMAGE */
scan_line = sp_globals.ymax - first_y - 1;
for (y = first_y - sp_globals.y_band.band_min; y >= last_y; y--, scan_line++)
{
i = sp_intercepts.cdr[y]; /* Index head of intercept list */
while (i != 0) /* Link to next intercept if present */
{
from = sp_intercepts.car[i];
i = sp_intercepts.cdr[i]; /* Link to next intercept */
to = sp_intercepts.car[i];
#if INCL_CLIPPING
if (clipleft)
{
if (to <= xmin)
{
i = sp_intercepts.cdr[i];
continue;
}
if (from < xmin)
from = xmin;
}
if (clipright)
{
if (from >= xmax)
{
i = sp_intercepts.cdr[i];
continue;
}
if (to > xmax)
to = xmax;
}
#endif
set_bitmap_bits(scan_line, from-sp_globals.xmin, to-sp_globals.xmin);
i = sp_intercepts.cdr[i];
}
}
}
#endif
| 34.173873 | 133 | 0.583654 | [
"vector"
] |
2ea8df065dc741cee511be0bb8d9a2c8f363b12c | 4,829 | h | C | Modules/AlgorithmsExt/mitkAnisotropicRegistrationCommon.h | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | null | null | null | Modules/AlgorithmsExt/mitkAnisotropicRegistrationCommon.h | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | null | null | null | Modules/AlgorithmsExt/mitkAnisotropicRegistrationCommon.h | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __ANISOTROPICREGISTRATIONCOMMON_H__
#define __ANISOTROPICREGISTRATIONCOMMON_H__
#include <mitkCommon.h>
#include <itkMatrix.h>
#include <mitkVector.h>
#include "MitkAlgorithmsExtExports.h"
// forward declarations
class vtkPoints;
namespace mitk
{
class PointSet;
/**
* \ingroup AnisotropicRegistration
* \brief A Class that provides common static functions used by all classes
* and tests in the anisotropic iterative closest point algorithm
* (AnisotropicIterativeClosestPointRegistration).
*
* The class provides common functionality used by the A-ICP algorithm like:
* compute weightmatrices (@ref CalculateWeightMatrix()),
* transform points (@ref TransformPoints()), propagate 3 x 3 matrices
* (@ref PropagateMatrices()) and compute the target registration error (TRE)
* (@ref ComputeTargetRegistrationError()).
*/
class MitkAlgorithmsExt_EXPORT AnisotropicRegistrationCommon
{
protected:
// local typedefs
/** Definition of the 3 x 3 weight matrix.*/
typedef itk::Matrix <double, 3, 3> WeightMatrix;
/** Definition of a rotation matrix.*/
typedef WeightMatrix Rotation;
/** Definition of the covariance matrix.*/
typedef WeightMatrix CovarianceMatrix;
/** Definition of the translation vector.*/
typedef mitk::Vector3D Translation;
/** Definition of the weight matrix list.*/
typedef std::vector< WeightMatrix > MatrixList;
AnisotropicRegistrationCommon(){}
~AnisotropicRegistrationCommon(){}
public:
/** @brief Method that computes a WeightMatrix with two CovarianceMatrices.
* @param sigma_X CovarianceMatrix from the moving point set.
* @param sigma_Y CovarianceMatrix from the fixed point set.
* @return The computed WeighMatrix.
*/
static WeightMatrix CalculateWeightMatrix( const CovarianceMatrix &sigma_X,
const CovarianceMatrix &sigma_Y );
/**
* @brief Transforms a point cloud with a Rotation and Translation.
*
* The method uses two point sets as input. It transforms every point from the
* source point set and saves the result in the destination. The soure is not
* modified. If the same point set is used as source and destination. The method
* will modify the source and the transformation is done in place.
*
* @warning No bound check is done. Ensure that source and destination are
* allocated and have the same size.
*
* @param src The source point set.
* @param dst The destination point set.
* @param rotation The rotation matrix.
* @param translation The translation vector.
*
*/
static void TransformPoints( vtkPoints* src,
vtkPoints* dst,
const Rotation& rotation,
const Translation& translation );
/**
* @brief Propagate a list of matrices with a rotation matrix.
*
* Method that propagate the source list and saves the result in the destination.
* If the source and destination lists are the same the matrices will be computed
* in place.
*
* @warning No bound check is done. Make sure that both lists are allocated and
* have the same size.
*
* @param src Reference to the source matrices list.
* @param dst Reference to the destination list
* @param rotation Reference to a rotation matrix.
*/
static void PropagateMatrices( const MatrixList &src,
MatrixList& dst,
const Rotation &rotation );
/**
* @brief Compute the target registration error between two point sets.
*
* Method that is used for testing and evaluation. It computes the target
* registration error (TRE) between two point sets with a rotation matrix and
* a translation vector.
*
* @param movingTargets The target points of the moving point set.
* @param fixedTargets The target points of the fixed point set.
* @param rotation A 3x3 rotation matrix.
* @param translation A 3x1 translation vector.
*
* @return The Target Registration Error (TRE).
*/
static double ComputeTargetRegistrationError( const mitk::PointSet* movingTargets,
const mitk::PointSet* fixedTargets,
const Rotation& rotation,
const Translation& translation
);
};
}
#endif
| 33.769231 | 82 | 0.682957 | [
"vector",
"transform"
] |
2eaf5156dd20b0bc7951a40828f38dc98c86262d | 535 | h | C | Source/Ejecta/EJAppViewController.h | maxcwfeng/Ejecta-demo | bf36f3dc27d2cbae5fbac3dec695097e490a1591 | [
"MIT"
] | 1,347 | 2015-01-01T06:12:12.000Z | 2022-03-31T13:41:53.000Z | Source/Ejecta/EJAppViewController.h | maryrosecook/dasher | 6542bf8620fa9627c22a55b908dbdabec5043c30 | [
"MIT"
] | 247 | 2015-01-02T10:40:16.000Z | 2022-03-06T09:24:21.000Z | Source/Ejecta/EJAppViewController.h | maryrosecook/dasher | 6542bf8620fa9627c22a55b908dbdabec5043c30 | [
"MIT"
] | 196 | 2015-01-20T01:52:25.000Z | 2022-03-05T07:32:17.000Z | // Well, this is actually the place where most of the stuff from the
// EJJavaScriptView should happen, if we'd follow the Model-View-Controller
// (MVC) methodology.
// Since the EJJavaScriptView is so tightly coupled to the JS execution and run
// loop, the View Controller here is mostly an empty shell that just
// instantiates a EJJavaScriptView, but does little else.
#import <Foundation/Foundation.h>
@interface EJAppViewController : UIViewController {
NSString *path;
}
- (id)initWithScriptAtPath:(NSString *)pathp;
@end
| 29.722222 | 79 | 0.768224 | [
"model"
] |
2eb06cdda6af691625bf7e5cd6f4dba084122618 | 281 | h | C | QuestEngine/API/OpenGL/ModelLoaderExceptions.h | paulburgess1357/Quest | 16c9513a28478cd56e25420aac1f0d4cd2c38734 | [
"MIT"
] | 1 | 2021-11-02T15:38:47.000Z | 2021-11-02T15:38:47.000Z | QuestEngine/API/OpenGL/ModelLoaderExceptions.h | paulburgess1357/Quest | 16c9513a28478cd56e25420aac1f0d4cd2c38734 | [
"MIT"
] | null | null | null | QuestEngine/API/OpenGL/ModelLoaderExceptions.h | paulburgess1357/Quest | 16c9513a28478cd56e25420aac1f0d4cd2c38734 | [
"MIT"
] | null | null | null | #pragma once
#include <exception>
namespace QuestEngine::API::OpenGL {
class IndexedModelLoaderError final : public std::exception {
[[nodiscard]] const char* what() const override {
return "Unable to load indexed model!";
}
};
} // namespace QuestEngine::API::OpenGL | 20.071429 | 62 | 0.711744 | [
"model"
] |
2eb191f56b36675224e5f15cd97ad32b59703832 | 8,018 | c | C | libckteec/src/pkcs11_processing.c | apalos/optee_client | c0c925384c1d7e3558d27d2708857482952d7907 | [
"BSD-2-Clause"
] | null | null | null | libckteec/src/pkcs11_processing.c | apalos/optee_client | c0c925384c1d7e3558d27d2708857482952d7907 | [
"BSD-2-Clause"
] | null | null | null | libckteec/src/pkcs11_processing.c | apalos/optee_client | c0c925384c1d7e3558d27d2708857482952d7907 | [
"BSD-2-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2017-2018, Linaro Limited
*/
#include <pkcs11.h>
#include <pkcs11_ta.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tee_client_api.h>
#include "pkcs11_processing.h"
#include "invoke_ta.h"
#include "serializer.h"
#include "serialize_ck.h"
CK_RV ck_create_object(CK_SESSION_HANDLE session, CK_ATTRIBUTE_PTR attribs,
CK_ULONG count, CK_OBJECT_HANDLE_PTR handle)
{
CK_RV rv = CKR_GENERAL_ERROR;
struct serializer obj = { };
size_t ctrl_size = 0;
TEEC_SharedMemory *ctrl = NULL;
TEEC_SharedMemory *out_shm = NULL;
uint32_t session_handle = session;
uint32_t key_handle = 0;
char *buf = NULL;
size_t out_size = 0;
if (!handle || !attribs || !count)
return CKR_ARGUMENTS_BAD;
rv = serialize_ck_attributes(&obj, attribs, count);
if (rv)
goto out;
/* Shm io0: (i/o) [session-handle][serialized-attributes] / [status] */
ctrl_size = sizeof(session_handle) + obj.size;
ctrl = ckteec_alloc_shm(ctrl_size, CKTEEC_SHM_INOUT);
if (!ctrl) {
rv = CKR_HOST_MEMORY;
goto out;
}
buf = ctrl->buffer;
memcpy(buf, &session_handle, sizeof(session_handle));
buf += sizeof(session_handle);
memcpy(buf, obj.buffer, obj.size);
/* Shm io2: (out) [object handle] */
out_shm = ckteec_alloc_shm(sizeof(key_handle), CKTEEC_SHM_OUT);
if (!out_shm) {
rv = CKR_HOST_MEMORY;
goto out;
}
rv = ckteec_invoke_ctrl_out(PKCS11_CMD_CREATE_OBJECT,
ctrl, out_shm, &out_size);
if (rv != CKR_OK || out_size != out_shm->size) {
if (rv == CKR_OK)
rv = CKR_DEVICE_ERROR;
goto out;
}
memcpy(&key_handle, out_shm->buffer, sizeof(key_handle));
*handle = key_handle;
out:
release_serial_object(&obj);
ckteec_free_shm(out_shm);
ckteec_free_shm(ctrl);
return rv;
}
CK_RV ck_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE obj)
{
CK_RV rv = CKR_GENERAL_ERROR;
TEEC_SharedMemory *ctrl = NULL;
size_t ctrl_size = 0;
char *buf = NULL;
uint32_t session_handle = session;
uint32_t obj_id = obj;
/* Shm io0: (i/o) ctrl = [session-handle][object-handle] / [status] */
ctrl_size = sizeof(session_handle) + sizeof(obj_id);
ctrl = ckteec_alloc_shm(ctrl_size, CKTEEC_SHM_INOUT);
if (!ctrl)
return CKR_HOST_MEMORY;
buf = ctrl->buffer;
memcpy(buf, &session_handle, sizeof(session_handle));
buf += sizeof(session_handle);
memcpy(buf, &obj_id, sizeof(obj_id));
rv = ckteec_invoke_ctrl(PKCS11_CMD_DESTROY_OBJECT, ctrl);
ckteec_free_shm(ctrl);
return rv;
}
CK_RV ck_encdecrypt_init(CK_SESSION_HANDLE session,
CK_MECHANISM_PTR mechanism,
CK_OBJECT_HANDLE key,
int decrypt)
{
CK_RV rv = CKR_GENERAL_ERROR;
TEEC_SharedMemory *ctrl = NULL;
struct serializer obj = { };
uint32_t session_handle = session;
uint32_t key_handle = key;
size_t ctrl_size = 0;
char *buf = NULL;
if (!mechanism)
return CKR_ARGUMENTS_BAD;
rv = serialize_ck_mecha_params(&obj, mechanism);
if (rv)
return rv;
/*
* Shm io0: (in/out) ctrl
* (in) [session-handle][key-handle][serialized-mechanism-blob]
* (out) [status]
*/
ctrl_size = sizeof(session_handle) + sizeof(key_handle) + obj.size;
ctrl = ckteec_alloc_shm(ctrl_size, CKTEEC_SHM_INOUT);
if (!ctrl) {
rv = CKR_HOST_MEMORY;
goto bail;
}
buf = ctrl->buffer;
memcpy(buf, &session_handle, sizeof(session_handle));
buf += sizeof(session_handle);
memcpy(buf, &key_handle, sizeof(key_handle));
buf += sizeof(key_handle);
memcpy(buf, obj.buffer, obj.size);
rv = ckteec_invoke_ctrl(decrypt ? PKCS11_CMD_DECRYPT_INIT :
PKCS11_CMD_ENCRYPT_INIT, ctrl);
bail:
ckteec_free_shm(ctrl);
release_serial_object(&obj);
return rv;
}
CK_RV ck_encdecrypt_update(CK_SESSION_HANDLE session,
CK_BYTE_PTR in,
CK_ULONG in_len,
CK_BYTE_PTR out,
CK_ULONG_PTR out_len,
int decrypt)
{
CK_RV rv = CKR_GENERAL_ERROR;
TEEC_SharedMemory *ctrl = NULL;
TEEC_SharedMemory *in_shm = NULL;
TEEC_SharedMemory *out_shm = NULL;
uint32_t session_handle = session;
size_t out_size = 0;
if ((out_len && *out_len && !out) || (in_len && !in))
return CKR_ARGUMENTS_BAD;
/* Shm io0: (in/out) ctrl = [session-handle] / [status] */
ctrl = ckteec_alloc_shm(sizeof(session_handle), CKTEEC_SHM_INOUT);
if (!ctrl) {
rv = CKR_HOST_MEMORY;
goto bail;
}
memcpy(ctrl->buffer, &session_handle, sizeof(session_handle));
/* Shm io1: input data buffer if any */
if (in_len) {
in_shm = ckteec_register_shm(in, in_len, CKTEEC_SHM_IN);
if (!in_shm) {
rv = CKR_HOST_MEMORY;
goto bail;
}
}
/* Shm io2: output data buffer */
if (out_len && *out_len) {
out_shm = ckteec_register_shm(out, *out_len, CKTEEC_SHM_OUT);
} else {
/* Query output data size */
out_shm = ckteec_alloc_shm(0, CKTEEC_SHM_OUT);
}
if (!out_shm) {
rv = CKR_HOST_MEMORY;
goto bail;
}
/* Invoke */
rv = ckteec_invoke_ta(decrypt ? PKCS11_CMD_DECRYPT_UPDATE :
PKCS11_CMD_ENCRYPT_UPDATE, ctrl,
in_shm, out_shm, &out_size, NULL, NULL);
if (out_len && (rv == CKR_OK || rv == CKR_BUFFER_TOO_SMALL))
*out_len = out_size;
if (rv == CKR_BUFFER_TOO_SMALL && out_size && !out)
rv = CKR_OK;
bail:
ckteec_free_shm(out_shm);
ckteec_free_shm(in_shm);
ckteec_free_shm(ctrl);
return rv;
}
CK_RV ck_encdecrypt_oneshot(CK_SESSION_HANDLE session,
CK_BYTE_PTR in,
CK_ULONG in_len,
CK_BYTE_PTR out,
CK_ULONG_PTR out_len,
int decrypt)
{
CK_RV rv = CKR_GENERAL_ERROR;
TEEC_SharedMemory *ctrl = NULL;
TEEC_SharedMemory *in_shm = NULL;
TEEC_SharedMemory *out_shm = NULL;
uint32_t session_handle = session;
size_t out_size = 0;
if ((out_len && *out_len && !out) || (in_len && !in))
return CKR_ARGUMENTS_BAD;
/* Shm io0: (in/out) ctrl = [session-handle] / [status] */
ctrl = ckteec_alloc_shm(sizeof(session_handle), CKTEEC_SHM_INOUT);
if (!ctrl) {
rv = CKR_HOST_MEMORY;
goto bail;
}
memcpy(ctrl->buffer, &session_handle, sizeof(session_handle));
/* Shm io1: input data buffer */
if (in_len) {
in_shm = ckteec_register_shm(in, in_len, CKTEEC_SHM_IN);
if (!in_shm) {
rv = CKR_HOST_MEMORY;
goto bail;
}
}
/* Shm io2: output data buffer */
if (out_len && *out_len) {
out_shm = ckteec_register_shm(out, *out_len, CKTEEC_SHM_OUT);
} else {
/* Query output data size */
out_shm = ckteec_alloc_shm(0, CKTEEC_SHM_OUT);
}
if (!out_shm) {
rv = CKR_HOST_MEMORY;
goto bail;
}
rv = ckteec_invoke_ta(decrypt ? PKCS11_CMD_DECRYPT_ONESHOT :
PKCS11_CMD_ENCRYPT_ONESHOT, ctrl,
in_shm, out_shm, &out_size, NULL, NULL);
if (out_len && (rv == CKR_OK || rv == CKR_BUFFER_TOO_SMALL))
*out_len = out_size;
if (rv == CKR_BUFFER_TOO_SMALL && out_size && !out)
rv = CKR_OK;
bail:
ckteec_free_shm(out_shm);
ckteec_free_shm(in_shm);
ckteec_free_shm(ctrl);
return rv;
}
CK_RV ck_encdecrypt_final(CK_SESSION_HANDLE session,
CK_BYTE_PTR out,
CK_ULONG_PTR out_len,
int decrypt)
{
CK_RV rv = CKR_GENERAL_ERROR;
TEEC_SharedMemory *ctrl = NULL;
TEEC_SharedMemory *out_shm = NULL;
uint32_t session_handle = session;
size_t out_size = 0;
if (out_len && *out_len && !out)
return CKR_ARGUMENTS_BAD;
/* Shm io0: (in/out) ctrl = [session-handle] / [status] */
ctrl = ckteec_alloc_shm(sizeof(session_handle), CKTEEC_SHM_INOUT);
if (!ctrl) {
rv = CKR_HOST_MEMORY;
goto bail;
}
memcpy(ctrl->buffer, &session_handle, sizeof(session_handle));
/* Shm io2: output buffer reference */
if (out_len && *out_len) {
out_shm = ckteec_register_shm(out, *out_len, CKTEEC_SHM_OUT);
} else {
/* Query output data size */
out_shm = ckteec_alloc_shm(0, CKTEEC_SHM_OUT);
}
if (!out_shm) {
rv = CKR_HOST_MEMORY;
goto bail;
}
rv = ckteec_invoke_ctrl_out(decrypt ? PKCS11_CMD_DECRYPT_FINAL :
PKCS11_CMD_ENCRYPT_FINAL,
ctrl, out_shm, &out_size);
if (out_len && (rv == CKR_OK || rv == CKR_BUFFER_TOO_SMALL))
*out_len = out_size;
if (rv == CKR_BUFFER_TOO_SMALL && out_size && !out)
rv = CKR_OK;
bail:
ckteec_free_shm(out_shm);
ckteec_free_shm(ctrl);
return rv;
}
| 23.24058 | 75 | 0.69793 | [
"object"
] |
2eb1aab3f122cdbff485a5c333d4d9bd7311ffb6 | 24,549 | h | C | aws-cpp-sdk-fsx/include/aws/fsx/model/OntapVolumeConfiguration.h | blinemedical/aws-sdk-cpp | c7c814b2d6862b4cb48f3fb3ac083a9e419674e8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-fsx/include/aws/fsx/model/OntapVolumeConfiguration.h | blinemedical/aws-sdk-cpp | c7c814b2d6862b4cb48f3fb3ac083a9e419674e8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-fsx/include/aws/fsx/model/OntapVolumeConfiguration.h | blinemedical/aws-sdk-cpp | c7c814b2d6862b4cb48f3fb3ac083a9e419674e8 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/fsx/FSx_EXPORTS.h>
#include <aws/fsx/model/FlexCacheEndpointType.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/fsx/model/SecurityStyle.h>
#include <aws/fsx/model/TieringPolicy.h>
#include <aws/fsx/model/OntapVolumeType.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace FSx
{
namespace Model
{
/**
* <p>The configuration of an Amazon FSx for NetApp ONTAP volume</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/fsx-2018-03-01/OntapVolumeConfiguration">AWS
* API Reference</a></p>
*/
class AWS_FSX_API OntapVolumeConfiguration
{
public:
OntapVolumeConfiguration();
OntapVolumeConfiguration(Aws::Utils::Json::JsonView jsonValue);
OntapVolumeConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Specifies the FlexCache endpoint type of the volume. Valid values are the
* following:</p> <ul> <li> <p> <code>NONE</code> specifies that the volume doesn't
* have a FlexCache configuration. <code>NONE</code> is the default.</p> </li> <li>
* <p> <code>ORIGIN</code> specifies that the volume is the origin volume for a
* FlexCache volume.</p> </li> <li> <p> <code>CACHE</code> specifies that the
* volume is a FlexCache volume.</p> </li> </ul>
*/
inline const FlexCacheEndpointType& GetFlexCacheEndpointType() const{ return m_flexCacheEndpointType; }
/**
* <p>Specifies the FlexCache endpoint type of the volume. Valid values are the
* following:</p> <ul> <li> <p> <code>NONE</code> specifies that the volume doesn't
* have a FlexCache configuration. <code>NONE</code> is the default.</p> </li> <li>
* <p> <code>ORIGIN</code> specifies that the volume is the origin volume for a
* FlexCache volume.</p> </li> <li> <p> <code>CACHE</code> specifies that the
* volume is a FlexCache volume.</p> </li> </ul>
*/
inline bool FlexCacheEndpointTypeHasBeenSet() const { return m_flexCacheEndpointTypeHasBeenSet; }
/**
* <p>Specifies the FlexCache endpoint type of the volume. Valid values are the
* following:</p> <ul> <li> <p> <code>NONE</code> specifies that the volume doesn't
* have a FlexCache configuration. <code>NONE</code> is the default.</p> </li> <li>
* <p> <code>ORIGIN</code> specifies that the volume is the origin volume for a
* FlexCache volume.</p> </li> <li> <p> <code>CACHE</code> specifies that the
* volume is a FlexCache volume.</p> </li> </ul>
*/
inline void SetFlexCacheEndpointType(const FlexCacheEndpointType& value) { m_flexCacheEndpointTypeHasBeenSet = true; m_flexCacheEndpointType = value; }
/**
* <p>Specifies the FlexCache endpoint type of the volume. Valid values are the
* following:</p> <ul> <li> <p> <code>NONE</code> specifies that the volume doesn't
* have a FlexCache configuration. <code>NONE</code> is the default.</p> </li> <li>
* <p> <code>ORIGIN</code> specifies that the volume is the origin volume for a
* FlexCache volume.</p> </li> <li> <p> <code>CACHE</code> specifies that the
* volume is a FlexCache volume.</p> </li> </ul>
*/
inline void SetFlexCacheEndpointType(FlexCacheEndpointType&& value) { m_flexCacheEndpointTypeHasBeenSet = true; m_flexCacheEndpointType = std::move(value); }
/**
* <p>Specifies the FlexCache endpoint type of the volume. Valid values are the
* following:</p> <ul> <li> <p> <code>NONE</code> specifies that the volume doesn't
* have a FlexCache configuration. <code>NONE</code> is the default.</p> </li> <li>
* <p> <code>ORIGIN</code> specifies that the volume is the origin volume for a
* FlexCache volume.</p> </li> <li> <p> <code>CACHE</code> specifies that the
* volume is a FlexCache volume.</p> </li> </ul>
*/
inline OntapVolumeConfiguration& WithFlexCacheEndpointType(const FlexCacheEndpointType& value) { SetFlexCacheEndpointType(value); return *this;}
/**
* <p>Specifies the FlexCache endpoint type of the volume. Valid values are the
* following:</p> <ul> <li> <p> <code>NONE</code> specifies that the volume doesn't
* have a FlexCache configuration. <code>NONE</code> is the default.</p> </li> <li>
* <p> <code>ORIGIN</code> specifies that the volume is the origin volume for a
* FlexCache volume.</p> </li> <li> <p> <code>CACHE</code> specifies that the
* volume is a FlexCache volume.</p> </li> </ul>
*/
inline OntapVolumeConfiguration& WithFlexCacheEndpointType(FlexCacheEndpointType&& value) { SetFlexCacheEndpointType(std::move(value)); return *this;}
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline const Aws::String& GetJunctionPath() const{ return m_junctionPath; }
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline bool JunctionPathHasBeenSet() const { return m_junctionPathHasBeenSet; }
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline void SetJunctionPath(const Aws::String& value) { m_junctionPathHasBeenSet = true; m_junctionPath = value; }
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline void SetJunctionPath(Aws::String&& value) { m_junctionPathHasBeenSet = true; m_junctionPath = std::move(value); }
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline void SetJunctionPath(const char* value) { m_junctionPathHasBeenSet = true; m_junctionPath.assign(value); }
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline OntapVolumeConfiguration& WithJunctionPath(const Aws::String& value) { SetJunctionPath(value); return *this;}
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline OntapVolumeConfiguration& WithJunctionPath(Aws::String&& value) { SetJunctionPath(std::move(value)); return *this;}
/**
* <p>Specifies the directory that NAS clients use to mount the volume, along with
* the SVM DNS name or IP address. You can create a <code>JunctionPath</code>
* directly below a parent volume junction or on a directory within a volume. A
* <code>JunctionPath</code> for a volume named vol3 might be /vol1/vol2/vol3, or
* /vol1/dir2/vol3, or even /dir1/dir2/vol3..</p>
*/
inline OntapVolumeConfiguration& WithJunctionPath(const char* value) { SetJunctionPath(value); return *this;}
/**
* <p>The security style for the volume, which can be <code>UNIX</code>,
* <code>NTFS</code>, or <code>MIXED</code>.</p>
*/
inline const SecurityStyle& GetSecurityStyle() const{ return m_securityStyle; }
/**
* <p>The security style for the volume, which can be <code>UNIX</code>,
* <code>NTFS</code>, or <code>MIXED</code>.</p>
*/
inline bool SecurityStyleHasBeenSet() const { return m_securityStyleHasBeenSet; }
/**
* <p>The security style for the volume, which can be <code>UNIX</code>,
* <code>NTFS</code>, or <code>MIXED</code>.</p>
*/
inline void SetSecurityStyle(const SecurityStyle& value) { m_securityStyleHasBeenSet = true; m_securityStyle = value; }
/**
* <p>The security style for the volume, which can be <code>UNIX</code>,
* <code>NTFS</code>, or <code>MIXED</code>.</p>
*/
inline void SetSecurityStyle(SecurityStyle&& value) { m_securityStyleHasBeenSet = true; m_securityStyle = std::move(value); }
/**
* <p>The security style for the volume, which can be <code>UNIX</code>,
* <code>NTFS</code>, or <code>MIXED</code>.</p>
*/
inline OntapVolumeConfiguration& WithSecurityStyle(const SecurityStyle& value) { SetSecurityStyle(value); return *this;}
/**
* <p>The security style for the volume, which can be <code>UNIX</code>,
* <code>NTFS</code>, or <code>MIXED</code>.</p>
*/
inline OntapVolumeConfiguration& WithSecurityStyle(SecurityStyle&& value) { SetSecurityStyle(std::move(value)); return *this;}
/**
* <p>The configured size of the volume, in megabytes (MBs).</p>
*/
inline int GetSizeInMegabytes() const{ return m_sizeInMegabytes; }
/**
* <p>The configured size of the volume, in megabytes (MBs).</p>
*/
inline bool SizeInMegabytesHasBeenSet() const { return m_sizeInMegabytesHasBeenSet; }
/**
* <p>The configured size of the volume, in megabytes (MBs).</p>
*/
inline void SetSizeInMegabytes(int value) { m_sizeInMegabytesHasBeenSet = true; m_sizeInMegabytes = value; }
/**
* <p>The configured size of the volume, in megabytes (MBs).</p>
*/
inline OntapVolumeConfiguration& WithSizeInMegabytes(int value) { SetSizeInMegabytes(value); return *this;}
/**
* <p>The volume's storage efficiency setting.</p>
*/
inline bool GetStorageEfficiencyEnabled() const{ return m_storageEfficiencyEnabled; }
/**
* <p>The volume's storage efficiency setting.</p>
*/
inline bool StorageEfficiencyEnabledHasBeenSet() const { return m_storageEfficiencyEnabledHasBeenSet; }
/**
* <p>The volume's storage efficiency setting.</p>
*/
inline void SetStorageEfficiencyEnabled(bool value) { m_storageEfficiencyEnabledHasBeenSet = true; m_storageEfficiencyEnabled = value; }
/**
* <p>The volume's storage efficiency setting.</p>
*/
inline OntapVolumeConfiguration& WithStorageEfficiencyEnabled(bool value) { SetStorageEfficiencyEnabled(value); return *this;}
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline const Aws::String& GetStorageVirtualMachineId() const{ return m_storageVirtualMachineId; }
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline bool StorageVirtualMachineIdHasBeenSet() const { return m_storageVirtualMachineIdHasBeenSet; }
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline void SetStorageVirtualMachineId(const Aws::String& value) { m_storageVirtualMachineIdHasBeenSet = true; m_storageVirtualMachineId = value; }
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline void SetStorageVirtualMachineId(Aws::String&& value) { m_storageVirtualMachineIdHasBeenSet = true; m_storageVirtualMachineId = std::move(value); }
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline void SetStorageVirtualMachineId(const char* value) { m_storageVirtualMachineIdHasBeenSet = true; m_storageVirtualMachineId.assign(value); }
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline OntapVolumeConfiguration& WithStorageVirtualMachineId(const Aws::String& value) { SetStorageVirtualMachineId(value); return *this;}
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline OntapVolumeConfiguration& WithStorageVirtualMachineId(Aws::String&& value) { SetStorageVirtualMachineId(std::move(value)); return *this;}
/**
* <p>The ID of the volume's storage virtual machine.</p>
*/
inline OntapVolumeConfiguration& WithStorageVirtualMachineId(const char* value) { SetStorageVirtualMachineId(value); return *this;}
/**
* <p>A boolean flag indicating whether this volume is the root volume for its
* storage virtual machine (SVM). Only one volume on an SVM can be the root volume.
* This value defaults to false. If this value is true, then this is the SVM root
* volume.</p> <p>This flag is useful when you're deleting an SVM, because you must
* first delete all non-root volumes. This flag, when set to false, helps you
* identify which volumes to delete before you can delete the SVM.</p>
*/
inline bool GetStorageVirtualMachineRoot() const{ return m_storageVirtualMachineRoot; }
/**
* <p>A boolean flag indicating whether this volume is the root volume for its
* storage virtual machine (SVM). Only one volume on an SVM can be the root volume.
* This value defaults to false. If this value is true, then this is the SVM root
* volume.</p> <p>This flag is useful when you're deleting an SVM, because you must
* first delete all non-root volumes. This flag, when set to false, helps you
* identify which volumes to delete before you can delete the SVM.</p>
*/
inline bool StorageVirtualMachineRootHasBeenSet() const { return m_storageVirtualMachineRootHasBeenSet; }
/**
* <p>A boolean flag indicating whether this volume is the root volume for its
* storage virtual machine (SVM). Only one volume on an SVM can be the root volume.
* This value defaults to false. If this value is true, then this is the SVM root
* volume.</p> <p>This flag is useful when you're deleting an SVM, because you must
* first delete all non-root volumes. This flag, when set to false, helps you
* identify which volumes to delete before you can delete the SVM.</p>
*/
inline void SetStorageVirtualMachineRoot(bool value) { m_storageVirtualMachineRootHasBeenSet = true; m_storageVirtualMachineRoot = value; }
/**
* <p>A boolean flag indicating whether this volume is the root volume for its
* storage virtual machine (SVM). Only one volume on an SVM can be the root volume.
* This value defaults to false. If this value is true, then this is the SVM root
* volume.</p> <p>This flag is useful when you're deleting an SVM, because you must
* first delete all non-root volumes. This flag, when set to false, helps you
* identify which volumes to delete before you can delete the SVM.</p>
*/
inline OntapVolumeConfiguration& WithStorageVirtualMachineRoot(bool value) { SetStorageVirtualMachineRoot(value); return *this;}
/**
* <p>The volume's <code>TieringPolicy</code> setting.</p>
*/
inline const TieringPolicy& GetTieringPolicy() const{ return m_tieringPolicy; }
/**
* <p>The volume's <code>TieringPolicy</code> setting.</p>
*/
inline bool TieringPolicyHasBeenSet() const { return m_tieringPolicyHasBeenSet; }
/**
* <p>The volume's <code>TieringPolicy</code> setting.</p>
*/
inline void SetTieringPolicy(const TieringPolicy& value) { m_tieringPolicyHasBeenSet = true; m_tieringPolicy = value; }
/**
* <p>The volume's <code>TieringPolicy</code> setting.</p>
*/
inline void SetTieringPolicy(TieringPolicy&& value) { m_tieringPolicyHasBeenSet = true; m_tieringPolicy = std::move(value); }
/**
* <p>The volume's <code>TieringPolicy</code> setting.</p>
*/
inline OntapVolumeConfiguration& WithTieringPolicy(const TieringPolicy& value) { SetTieringPolicy(value); return *this;}
/**
* <p>The volume's <code>TieringPolicy</code> setting.</p>
*/
inline OntapVolumeConfiguration& WithTieringPolicy(TieringPolicy&& value) { SetTieringPolicy(std::move(value)); return *this;}
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline const Aws::String& GetUUID() const{ return m_uUID; }
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline bool UUIDHasBeenSet() const { return m_uUIDHasBeenSet; }
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline void SetUUID(const Aws::String& value) { m_uUIDHasBeenSet = true; m_uUID = value; }
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline void SetUUID(Aws::String&& value) { m_uUIDHasBeenSet = true; m_uUID = std::move(value); }
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline void SetUUID(const char* value) { m_uUIDHasBeenSet = true; m_uUID.assign(value); }
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline OntapVolumeConfiguration& WithUUID(const Aws::String& value) { SetUUID(value); return *this;}
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline OntapVolumeConfiguration& WithUUID(Aws::String&& value) { SetUUID(std::move(value)); return *this;}
/**
* <p>The volume's UUID (universally unique identifier).</p>
*/
inline OntapVolumeConfiguration& WithUUID(const char* value) { SetUUID(value); return *this;}
/**
* <p>Specifies the type of volume. Valid values are the following:</p> <ul> <li>
* <p> <code>RW</code> specifies a read-write volume. <code>RW</code> is the
* default.</p> </li> <li> <p> <code>DP</code> specifies a data protection volume.
* You can protect data by replicating it to data protection mirror copies and use
* data protection mirror copies to recover data when a disaster occurs.</p> </li>
* <li> <p> <code>LS</code> specifies a load-sharing mirror volume. A load-sharing
* mirror reduces the network traffic to a FlexVol volume by providing additional
* read-only access to clients.</p> </li> </ul>
*/
inline const OntapVolumeType& GetOntapVolumeType() const{ return m_ontapVolumeType; }
/**
* <p>Specifies the type of volume. Valid values are the following:</p> <ul> <li>
* <p> <code>RW</code> specifies a read-write volume. <code>RW</code> is the
* default.</p> </li> <li> <p> <code>DP</code> specifies a data protection volume.
* You can protect data by replicating it to data protection mirror copies and use
* data protection mirror copies to recover data when a disaster occurs.</p> </li>
* <li> <p> <code>LS</code> specifies a load-sharing mirror volume. A load-sharing
* mirror reduces the network traffic to a FlexVol volume by providing additional
* read-only access to clients.</p> </li> </ul>
*/
inline bool OntapVolumeTypeHasBeenSet() const { return m_ontapVolumeTypeHasBeenSet; }
/**
* <p>Specifies the type of volume. Valid values are the following:</p> <ul> <li>
* <p> <code>RW</code> specifies a read-write volume. <code>RW</code> is the
* default.</p> </li> <li> <p> <code>DP</code> specifies a data protection volume.
* You can protect data by replicating it to data protection mirror copies and use
* data protection mirror copies to recover data when a disaster occurs.</p> </li>
* <li> <p> <code>LS</code> specifies a load-sharing mirror volume. A load-sharing
* mirror reduces the network traffic to a FlexVol volume by providing additional
* read-only access to clients.</p> </li> </ul>
*/
inline void SetOntapVolumeType(const OntapVolumeType& value) { m_ontapVolumeTypeHasBeenSet = true; m_ontapVolumeType = value; }
/**
* <p>Specifies the type of volume. Valid values are the following:</p> <ul> <li>
* <p> <code>RW</code> specifies a read-write volume. <code>RW</code> is the
* default.</p> </li> <li> <p> <code>DP</code> specifies a data protection volume.
* You can protect data by replicating it to data protection mirror copies and use
* data protection mirror copies to recover data when a disaster occurs.</p> </li>
* <li> <p> <code>LS</code> specifies a load-sharing mirror volume. A load-sharing
* mirror reduces the network traffic to a FlexVol volume by providing additional
* read-only access to clients.</p> </li> </ul>
*/
inline void SetOntapVolumeType(OntapVolumeType&& value) { m_ontapVolumeTypeHasBeenSet = true; m_ontapVolumeType = std::move(value); }
/**
* <p>Specifies the type of volume. Valid values are the following:</p> <ul> <li>
* <p> <code>RW</code> specifies a read-write volume. <code>RW</code> is the
* default.</p> </li> <li> <p> <code>DP</code> specifies a data protection volume.
* You can protect data by replicating it to data protection mirror copies and use
* data protection mirror copies to recover data when a disaster occurs.</p> </li>
* <li> <p> <code>LS</code> specifies a load-sharing mirror volume. A load-sharing
* mirror reduces the network traffic to a FlexVol volume by providing additional
* read-only access to clients.</p> </li> </ul>
*/
inline OntapVolumeConfiguration& WithOntapVolumeType(const OntapVolumeType& value) { SetOntapVolumeType(value); return *this;}
/**
* <p>Specifies the type of volume. Valid values are the following:</p> <ul> <li>
* <p> <code>RW</code> specifies a read-write volume. <code>RW</code> is the
* default.</p> </li> <li> <p> <code>DP</code> specifies a data protection volume.
* You can protect data by replicating it to data protection mirror copies and use
* data protection mirror copies to recover data when a disaster occurs.</p> </li>
* <li> <p> <code>LS</code> specifies a load-sharing mirror volume. A load-sharing
* mirror reduces the network traffic to a FlexVol volume by providing additional
* read-only access to clients.</p> </li> </ul>
*/
inline OntapVolumeConfiguration& WithOntapVolumeType(OntapVolumeType&& value) { SetOntapVolumeType(std::move(value)); return *this;}
private:
FlexCacheEndpointType m_flexCacheEndpointType;
bool m_flexCacheEndpointTypeHasBeenSet;
Aws::String m_junctionPath;
bool m_junctionPathHasBeenSet;
SecurityStyle m_securityStyle;
bool m_securityStyleHasBeenSet;
int m_sizeInMegabytes;
bool m_sizeInMegabytesHasBeenSet;
bool m_storageEfficiencyEnabled;
bool m_storageEfficiencyEnabledHasBeenSet;
Aws::String m_storageVirtualMachineId;
bool m_storageVirtualMachineIdHasBeenSet;
bool m_storageVirtualMachineRoot;
bool m_storageVirtualMachineRootHasBeenSet;
TieringPolicy m_tieringPolicy;
bool m_tieringPolicyHasBeenSet;
Aws::String m_uUID;
bool m_uUIDHasBeenSet;
OntapVolumeType m_ontapVolumeType;
bool m_ontapVolumeTypeHasBeenSet;
};
} // namespace Model
} // namespace FSx
} // namespace Aws
| 47.209615 | 161 | 0.68459 | [
"model"
] |
2eb1bd576f627477f6327c1364f75034e1f61d53 | 459 | h | C | Source/MainGameplay/Public/Data/SpaceshipType.h | jtferson/UnrealFlecsQuickstart | 53ecc500b6946fa115f61a73232ca66de942c355 | [
"MIT"
] | 25 | 2021-02-14T21:39:34.000Z | 2022-03-03T18:13:50.000Z | Source/MainGameplay/Public/Data/SpaceshipType.h | jtferson/UnrealFlecsQuickstart | 53ecc500b6946fa115f61a73232ca66de942c355 | [
"MIT"
] | 2 | 2021-02-19T19:08:14.000Z | 2021-03-23T19:03:58.000Z | Source/MainGameplay/Public/Data/SpaceshipType.h | jtferson/UnrealFlecsQuickstart | 53ecc500b6946fa115f61a73232ca66de942c355 | [
"MIT"
] | 2 | 2021-12-27T02:25:33.000Z | 2022-01-18T13:26:50.000Z | // Copyright 2021 Red J
#pragma once
#include "CoreMinimal.h"
#include "SpaceshipWeapon.h"
#include "SpaceshipType.generated.h"
/**
*
*/
UCLASS()
class MAINGAMEPLAY_API USpaceshipType : public UDataAsset
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere)
UStaticMesh* Mesh = nullptr;
UPROPERTY(EditAnywhere)
UMaterial* Material = nullptr;
UPROPERTY(EditAnywhere)
USpaceshipWeapon* Weapons = nullptr;
UPROPERTY(EditAnywhere)
float MaxSpeed;
};
| 17.653846 | 57 | 0.760349 | [
"mesh"
] |
2ec388f0d1a8879fce86155b8e1cca3e807441dd | 3,529 | h | C | Modules/Meshing/VolumeFromSTL/include/angiotkPolyBallLine.h | vivabrain/angiotk | 56187d726691576bc90ac727f28ed08bb0633830 | [
"Apache-2.0"
] | 4 | 2016-06-26T18:47:22.000Z | 2020-06-20T20:54:38.000Z | Modules/Meshing/VolumeFromSTL/include/angiotkPolyBallLine.h | feelpp/angiotk | 3faac75cc6eeeb49e9c85dc20ad44038f185e5f6 | [
"Apache-2.0"
] | 7 | 2018-05-10T18:31:22.000Z | 2018-07-20T09:19:31.000Z | Modules/Meshing/VolumeFromSTL/include/angiotkPolyBallLine.h | feelpp/angiotk | 3faac75cc6eeeb49e9c85dc20ad44038f185e5f6 | [
"Apache-2.0"
] | 3 | 2015-07-06T08:07:46.000Z | 2021-02-01T16:01:25.000Z | /*=========================================================================
Program: VMTK
Module: $RCSfile: vtkvmtkPolyBallLine.h,v $
Language: C++
Date: $Date: 2006/04/06 16:46:43 $
Version: $Revision: 1.4 $
Copyright (c) Luca Antiga, David Steinman. All rights reserved.
See LICENCE file for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// .NAME angiotkPolyBallLine -
// .SECTION Description
// ..
#ifndef __angiotkPolyBallLine_h
#define __angiotkPolyBallLine_h
#include <map>
#include <set>
#include <vtkImplicitFunction.h>
#include <vtkPolyData.h>
#include <vtkIdList.h>
//#include "vtkvmtkComputationalGeometryWin32Header.h"
#include <vtkvmtkWin32Header.h>
class VTK_VMTK_COMPUTATIONAL_GEOMETRY_EXPORT angiotkPolyBallLine : public vtkImplicitFunction
{
public:
static angiotkPolyBallLine *New();
vtkTypeMacro(angiotkPolyBallLine,vtkImplicitFunction);
void PrintSelf(ostream& os, vtkIndent indent);
// Description
// Evaluate polyball.
double EvaluateFunction(double x[3]);
double EvaluateFunction(double x, double y, double z)
{return this->vtkImplicitFunction::EvaluateFunction(x, y, z); } ;
// Description
// Evaluate polyball gradient.
void EvaluateGradient(double x[3], double n[3]);
// Description:
// Set / get input poly data.
vtkSetObjectMacro(Input,vtkPolyData);
vtkGetObjectMacro(Input,vtkPolyData);
// Description:
// Set / get input cell ids used for the function.
vtkSetObjectMacro(InputCellIds,vtkIdList);
vtkGetObjectMacro(InputCellIds,vtkIdList);
// Description:
// Set / get a single input cell id used for the function.
vtkSetMacro(InputCellId,vtkIdType);
vtkGetMacro(InputCellId,vtkIdType);
// Description:
// Set / get poly ball radius array name.
vtkSetStringMacro(PolyBallRadiusArrayName);
vtkGetStringMacro(PolyBallRadiusArrayName);
// Description:
// Get the id of the last nearest poly ball center.
vtkGetMacro(LastPolyBallCellId,vtkIdType);
vtkGetMacro(LastPolyBallCellSubId,vtkIdType);
vtkGetMacro(LastPolyBallCellPCoord,double);
vtkGetVectorMacro(LastPolyBallCenter,double,3);
vtkGetMacro(LastPolyBallCenterRadius,double);
vtkSetMacro(UseRadiusInformation,int);
vtkGetMacro(UseRadiusInformation,int);
vtkBooleanMacro(UseRadiusInformation,int);
void Update();
std::set<vtkIdType> pointIsOnBranchBounds(double x[3]) const;
static double ComplexDot(double x[4], double y[4]);
protected:
angiotkPolyBallLine();
~angiotkPolyBallLine();
vtkPolyData* Input;
vtkIdList* InputCellIds;
vtkIdType InputCellId;
char* PolyBallRadiusArrayName;
vtkIdType LastPolyBallCellId;
vtkIdType LastPolyBallCellSubId;
double LastPolyBallCellPCoord;
double LastPolyBallCenter[3];
double LastPolyBallCenterRadius;
int UseRadiusInformation;
vtkDataArray *polyballRadiusArray;
vtkIdList* cellIds;
std::map<vtkIdType, std::vector<double> > branchBounds;
std::map<vtkIdType, double > branchRadiusMax;
private:
angiotkPolyBallLine(const angiotkPolyBallLine&); // Not implemented.
void operator=(const angiotkPolyBallLine&); // Not implemented.
};
#endif
| 28.691057 | 93 | 0.727685 | [
"vector"
] |
2ec48959f634f28e7573a26ea52ec6b47212864c | 2,865 | c | C | test/cbmc/proofs/HTTPClient_Send/HTTPClient_Send_harness.c | markrtuttle/coreHTTP | 2631204ee9b6a3e2068b0d59c3a6c2d1144628ea | [
"MIT"
] | null | null | null | test/cbmc/proofs/HTTPClient_Send/HTTPClient_Send_harness.c | markrtuttle/coreHTTP | 2631204ee9b6a3e2068b0d59c3a6c2d1144628ea | [
"MIT"
] | null | null | null | test/cbmc/proofs/HTTPClient_Send/HTTPClient_Send_harness.c | markrtuttle/coreHTTP | 2631204ee9b6a3e2068b0d59c3a6c2d1144628ea | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file HTTPClient_Send_harness.c
* @brief Implements the proof harness for HTTPClient_Send function.
*/
#include "core_http_client.h"
#include "http_cbmc_state.h"
#include "transport_interface_stubs.h"
void HTTPClient_Send_harness()
{
HTTPRequestHeaders_t * pRequestHeaders;
HTTPResponse_t * pResponse;
TransportInterface_t * pTransportInterface;
uint8_t * pRequestBodyBuf;
size_t reqBodyBufLen;
uint32_t sendFlags;
/* Initialize and make assumptions for request headers. */
pRequestHeaders = allocateHttpRequestHeaders( NULL );
__CPROVER_assume( isValidHttpRequestHeaders( pRequestHeaders ) );
/* Initialize and make assumptions for buffer to receive request body. */
__CPROVER_assume( reqBodyBufLen < CBMC_MAX_OBJECT_SIZE );
pRequestBodyBuf = mallocCanFail( reqBodyBufLen );
/* Initialize and make assumptions for response object. */
pResponse = allocateHttpResponse( NULL );
__CPROVER_assume( isValidHttpResponse( pResponse ) );
/* Initialize transport interface. */
pTransportInterface = allocateTransportInterface( NULL );
if( pTransportInterface != NULL )
{
/* Ideally, we want to set the function pointers below with __CPROVER_assume()
* but doing so makes CBMC run out of memory. */
pTransportInterface->send = nondet_bool() ? NULL : TransportInterfaceSendStub;
pTransportInterface->recv = nondet_bool() ? NULL : TransportInterfaceReceiveStub;
}
HTTPClient_Send( pTransportInterface,
pRequestHeaders,
pRequestBodyBuf,
reqBodyBufLen,
pResponse,
sendFlags );
}
| 40.928571 | 89 | 0.721815 | [
"object"
] |
2ec61ec4dd30bf94a920f95083e095a082349d67 | 17,905 | h | C | onnxruntime/test/mlas/unittest/test_qgemm.h | ChenHuaYou/onnxruntime | e61301917442486e6ef9c7f39cddab72739f0fc5 | [
"MIT"
] | null | null | null | onnxruntime/test/mlas/unittest/test_qgemm.h | ChenHuaYou/onnxruntime | e61301917442486e6ef9c7f39cddab72739f0fc5 | [
"MIT"
] | null | null | null | onnxruntime/test/mlas/unittest/test_qgemm.h | ChenHuaYou/onnxruntime | e61301917442486e6ef9c7f39cddab72739f0fc5 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "test_util.h"
template <bool Packed, bool Threaded>
class MlasQgemmTestBase : public MlasTestBase {
private:
void* PackB(size_t N, size_t K, const uint8_t* B, size_t ldb, bool AIsSigned, bool BIsSigned) {
size_t PackedBSize = MlasGemmPackBSize(N, K, AIsSigned, BIsSigned);
void* PackedB = BufferBPacked.GetBuffer(PackedBSize);
MlasGemmPackB(N, K, B, ldb, AIsSigned, BIsSigned, PackedB);
return PackedB;
}
protected:
MLAS_THREADPOOL* threadpool_;
MlasQgemmTestBase() : threadpool_(Threaded ? GetMlasThreadPool() : nullptr) {}
void TestGemm(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const uint8_t* A,
size_t lda,
uint8_t offa,
bool AIsSigned,
const uint8_t* B,
size_t ldb,
uint8_t offb,
bool BIsSigned,
int32_t* C,
size_t ldc) {
MLAS_GEMM_QUANT_SHAPE_PARAMS GemmShape;
GemmShape.M = M;
GemmShape.N = N;
GemmShape.K = K;
GemmShape.AIsSigned = AIsSigned;
GemmShape.BIsSigned = BIsSigned;
std::vector<MLAS_GEMM_QUANT_DATA_PARAMS> GemmParameters(BatchSize);
for (size_t i = 0; i < GemmParameters.size(); i++) {
auto& params = GemmParameters[i];
params.A = A + (M * K * i);
params.lda = lda;
params.ZeroPointA = offa;
params.ZeroPointB = &offb;
params.C = C + (M * N * i);
params.ldc = ldc;
if (Packed) {
ASSERT_EQ(BatchSize, size_t(1)) << "Packing B not supported in batching yet!";
params.B = PackB(N, K, B, ldb, AIsSigned, BIsSigned);
params.BIsPacked = true;
} else {
params.B = B + (K * N * i);
params.ldb = ldb;
}
}
MlasGemmBatch(GemmShape, GemmParameters.data(), BatchSize, threadpool_);
}
void TestGemm(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const uint8_t* A,
size_t lda,
uint8_t offa,
bool AIsSigned,
const uint8_t* B,
size_t ldb,
const uint8_t* offb,
bool BIsSigned,
int32_t* C,
size_t ldc) {
MLAS_GEMM_QUANT_SHAPE_PARAMS GemmShape;
GemmShape.M = M;
GemmShape.N = N;
GemmShape.K = K;
GemmShape.AIsSigned = AIsSigned;
GemmShape.BIsSigned = BIsSigned;
std::vector<MLAS_GEMM_QUANT_DATA_PARAMS> GemmParameters(BatchSize);
for (size_t i = 0; i < GemmParameters.size(); i++) {
auto& params = GemmParameters[i];
params.A = A + M * K * i;
params.lda = lda;
params.ZeroPointA = offa;
params.ZeroPointB = offb;
params.PerColumnZeroPoints = true;
params.C = C + M * N * i;
params.ldc = ldc;
if (Packed) {
ASSERT_EQ(BatchSize, size_t(1)) << "Packing B not supported in batching yet!";
params.B = PackB(N, K, B, ldb, AIsSigned, BIsSigned);
params.BIsPacked = true;
} else {
params.B = B + K * N * i;
params.ldb = ldb;
}
}
MlasGemmBatch(GemmShape, GemmParameters.data(), BatchSize, threadpool_);
}
void TestGemm(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const uint8_t* A,
size_t lda,
uint8_t offa,
bool AIsSigned,
const uint8_t* B,
size_t ldb,
uint8_t offb,
bool BIsSigned,
float* C,
size_t ldc,
float CScale,
const float* Bias) {
MLAS_GEMM_QUANT_SHAPE_PARAMS GemmShape;
GemmShape.M = M;
GemmShape.N = N;
GemmShape.K = K;
GemmShape.AIsSigned = AIsSigned;
GemmShape.BIsSigned = BIsSigned;
std::vector<MLAS_QGEMM_SCALE_BIAS_OUTPUT_PROCESSOR> ScaleBiasProcessors;
ScaleBiasProcessors.reserve(BatchSize);
std::vector<MLAS_GEMM_QUANT_DATA_PARAMS> GemmParameters(BatchSize);
for (size_t i = 0; i < BatchSize; i++) {
auto& params = GemmParameters[i];
params.A = A + M * K * i;
params.lda = lda;
params.ZeroPointA = offa;
params.ZeroPointB = &offb;
params.C = reinterpret_cast<int32_t*>(C + M * N * i);
params.ldc = ldc;
if (Packed) {
ASSERT_EQ(BatchSize, size_t(1)) << "Packing B not supported in batching yet!";
params.B = PackB(N, K, B, ldb, AIsSigned, BIsSigned);
params.BIsPacked = true;
} else {
params.B = B + K * N * i;
params.ldb = ldb;
}
ScaleBiasProcessors.emplace_back(C + M * N * i, ldc, &CScale, Bias);
params.OutputProcessor = &(ScaleBiasProcessors[i]);
}
MlasGemmBatch(GemmShape, GemmParameters.data(), BatchSize, threadpool_);
}
private:
MatrixGuardBuffer<uint8_t> BufferBPacked;
};
template <typename AType, typename BType, typename OutputType, bool Packed, bool Threaded>
class MlasQgemmTest;
template <typename AType, typename BType, bool Packed, bool Threaded>
class MlasQgemmTest<AType, BType, int32_t, Packed, Threaded> : public MlasQgemmTestBase<Packed, Threaded> {
public:
void Test(size_t M, size_t N, size_t K, size_t BatchSize, uint8_t offa, uint8_t offb) {
const uint8_t* A = BufferA.GetBuffer(K * M * BatchSize);
const uint8_t* B = BufferB.GetBuffer(N * K * BatchSize);
int32_t* C = BufferC.GetBuffer(N * M * BatchSize);
int32_t* CReference = BufferCReference.GetBuffer(N * M * BatchSize);
Test(M, N, K, BatchSize, A, K, offa, B, N, offb, C, CReference, N);
}
void Test(size_t M, size_t N, size_t K, size_t BatchSize, uint8_t offa) {
const uint8_t* A = BufferA.GetBuffer(K * M * BatchSize);
const uint8_t* B = BufferB.GetBuffer(N * K * BatchSize);
const uint8_t* ZeroPointB = BufferZeroPointB.GetBuffer(N);
int32_t* C = BufferC.GetBuffer(N * M * BatchSize);
int32_t* CReference = BufferCReference.GetBuffer(N * M * BatchSize);
Test(M, N, K, BatchSize, A, K, offa, B, N, ZeroPointB, C, CReference, N);
}
void Test(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const uint8_t* A,
size_t lda,
uint8_t offa,
const uint8_t* B,
size_t ldb,
uint8_t offb,
int32_t* C,
int32_t* CReference,
size_t ldc) {
std::fill_n(C, M * N * BatchSize, -1);
std::fill_n(CReference, M * N * BatchSize, -1);
this->TestGemm(M, N, K, BatchSize, A, lda, offa, AIsSigned, B, ldb, offb, BIsSigned, C, ldc);
ReferenceQgemm(M, N, K, BatchSize, (const AType*)A, lda, (AType)offa, (const BType*)B, ldb, (BType)offb, CReference, ldc);
for (size_t batch = 0, f = 0; batch < BatchSize; batch++) {
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++, f++) {
ASSERT_EQ(C[f], CReference[f]) << "@[" << batch << "x" << m << "x" << n << "], "
<< "Batch=" << BatchSize << "M=" << M << ", N=" << N << ", K=" << K
<< ", offa=" << int(offa) << ", offb=" << int(offb);
}
}
}
}
void Test(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const uint8_t* A,
size_t lda,
uint8_t offa,
const uint8_t* B,
size_t ldb,
const uint8_t* offb,
int32_t* C,
int32_t* CReference,
size_t ldc) {
std::fill_n(C, M * N * BatchSize, -1);
std::fill_n(CReference, M * N * BatchSize, -1);
this->TestGemm(M, N, K, BatchSize, A, lda, offa, AIsSigned, B, ldb, offb, BIsSigned, C, ldc);
ReferenceQgemm(M, N, K, BatchSize, (const AType*)A, lda, (AType)offa, (const BType*)B, ldb, (const BType*)offb, CReference, ldc);
for (size_t batch = 0, f = 0; batch < BatchSize; batch++) {
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++, f++) {
ASSERT_EQ(C[f], CReference[f]) << "@[" << batch << "x" << m << "x" << n << "], "
<< "Batch=" << BatchSize << "M=" << M << ", N=" << N << ", K=" << K
<< ", offa=" << int(offa) << ", offb=--";
}
}
}
}
private:
void ReferenceQgemm(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const AType* A,
size_t lda,
AType offa,
const BType* B,
size_t ldb,
BType offb,
int32_t* C,
size_t ldc) {
for (size_t batch = 0; batch < BatchSize; batch++) {
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
const AType* a = A + (M * K * batch) + (m * lda);
const BType* b = B + (K * N * batch) + n;
int32_t* c = C + (M * N * batch) + (m * ldc) + n;
int32_t sum = 0;
for (size_t k = 0; k < K; k++) {
sum += ((int32_t(*b) - offb) * (int32_t(*a) - offa));
b += ldb;
a += 1;
}
*c = sum;
}
}
}
}
void ReferenceQgemm(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const AType* A,
size_t lda,
AType offa,
const BType* B,
size_t ldb,
const BType* offb,
int32_t* C,
size_t ldc) {
for (size_t batch = 0; batch < BatchSize; batch++) {
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
const AType* a = A + (M * K * batch) + (m * lda);
const BType* b = B + (K * N * batch) + n;
int32_t* c = C + (M * N * batch) + (m * ldc) + n;
int32_t sum = 0;
for (size_t k = 0; k < K; k++) {
sum += ((int32_t(*b) - offb[n]) * (int32_t(*a) - offa));
b += ldb;
a += 1;
}
*c = sum;
}
}
}
}
MatrixGuardBuffer<uint8_t> BufferA;
MatrixGuardBuffer<uint8_t> BufferB;
MatrixGuardBuffer<uint8_t> BufferZeroPointB;
MatrixGuardBuffer<int32_t> BufferC;
MatrixGuardBuffer<int32_t> BufferCReference;
const bool AIsSigned = std::is_signed<AType>::value;
const bool BIsSigned = std::is_signed<BType>::value;
public:
static const char* GetTestSuiteName() {
static std::string suite_name = std::string("QGemm") +
(std::is_signed<AType>::value ? "S8" : "U8") +
(std::is_signed<BType>::value ? "S8" : "U8") +
(Packed ? "_Int32_Packed" : "_Int32_NoPack") +
(Threaded ? "_Threaded" : "_SingleThread");
return suite_name.c_str();
}
void ExecuteLong(void) override {
static const uint8_t zero_points[] = {0, 18, 75, 128, 157, 231, 255};
for (size_t a = 0; a < _countof(zero_points); a++) {
uint8_t offa = zero_points[a];
for (size_t b = 0; b < _countof(zero_points); b++) {
uint8_t offb = zero_points[b];
for (size_t M = 16; M < 160; M += 32) {
for (size_t N = 16; N < 160; N += 32) {
static const size_t ks[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 20, 32, 48, 64, 118, 119, 120, 121, 122, 160, 240, 320};
for (size_t k = 0; k < _countof(ks); k++) {
size_t K = ks[k];
Test(M, N, K, 1, offa, offb);
Test(M + 1, N, K, 1, offa, offb);
Test(M, N + 1, K, 1, offa, offb);
Test(M + 1, N + 1, K, 1, offa, offb);
Test(M + 3, N + 2, K, 1, offa, offb);
Test(M + 4, N, K, 1, offa, offb);
Test(M, N + 4, K, 1, offa, offb);
Test(M + 4, N + 4, K, 1, offa, offb);
Test(M + 3, N + 7, K, 1, offa, offb);
Test(M + 8, N, K, 1, offa, offb);
Test(M, N + 8, K, 1, offa, offb);
Test(M + 12, N + 12, K, 1, offa, offb);
Test(M + 13, N, K, 1, offa, offb);
Test(M, N + 15, K, 1, offa, offb);
Test(M + 15, N + 15, K, 1, offa, offb);
if (!Packed) {
Test(M, N, K, 7 + a, offa, offb);
Test(M + 3, N, K, 7 + a, offa, offb);
Test(M, N + 1, K, 7 + a, offa, offb);
Test(M + 12, N, K, 7 + a, offa, offb);
Test(M, N + 15, K, 7 + a, offa, offb);
Test(M + 15, N + 15, K,7 + a, offa, offb);
}
}
}
printf("a %zd/%zd b %zd/%zd M %zd\n", a, _countof(zero_points), b, _countof(zero_points), M);
}
}
}
for (size_t M = 1; M < 160; M++) {
for (size_t N = 1; N < 160; N++) {
for (size_t K = 1; K < 160; K++) {
Test(M, N, K, 1, 18, 24);
}
}
printf("M %zd\n", M);
}
for (size_t M = 160; M < 320; M += 24) {
for (size_t N = 112; N < 320; N += 24) {
for (size_t K = 1; K < 16; K++) {
Test(M, N, K, 1, 1, 3);
}
for (size_t K = 16; K < 160; K += 32) {
Test(M, N, K, 1, 5, 7);
}
}
printf("M %zd\n", M);
}
}
};
template <typename AType, typename BType, bool Packed, bool Threaded>
class MlasQgemmTest<AType, BType, float, Packed, Threaded> : public MlasQgemmTestBase<Packed, Threaded> {
public:
void Test(size_t M, size_t N, size_t K, size_t BatchSize, uint8_t offa, uint8_t offb) {
const uint8_t* A = BufferA.GetBuffer(K * M * BatchSize);
const uint8_t* B = BufferB.GetBuffer(N * K * BatchSize);
float* C = BufferC.GetBuffer(N * M * BatchSize);
float* CReference = BufferCReference.GetBuffer(N * M * BatchSize);
const float* Bias = BufferBias.GetBuffer(N);
const float AScale = 0.5f;
float* AFloat = BufferAFloat.GetBuffer(K * M * BatchSize);
for (size_t b = 0; b < BatchSize; b++) {
DequantizeLinear((AType*)(A + K * M * b), AFloat + K * M * b, K * M, AScale, (AType)offa);
}
const float BScale = 0.25f;
float* BFloat = BufferBFloat.GetBuffer(N * K * BatchSize);
for (size_t b = 0; b < BatchSize; b++) {
DequantizeLinear((BType*)(B + N * K * b), BFloat + N * K * b, N * K, BScale, BType(offb));
}
const float CScale = AScale * BScale;
Test(M, N, K, BatchSize, A, AFloat, K, offa, B, BFloat, N, offb, C, CReference, N, CScale, nullptr);
Test(M, N, K, BatchSize, A, AFloat, K, offa, B, BFloat, N, offb, C, CReference, N, CScale, Bias);
}
void Test(size_t M,
size_t N,
size_t K,
size_t BatchSize,
const uint8_t* A,
const float* AFloat,
size_t lda,
uint8_t offa,
const uint8_t* B,
const float* BFloat,
size_t ldb,
uint8_t offb,
float* C,
float* CReference,
size_t ldc,
float CScale,
const float* Bias) {
for (size_t b = 0; b < BatchSize; b++) {
MlasGemm(CblasNoTrans, CblasNoTrans, M, N, K, 1.0f,
AFloat + K * M * b, lda,
BFloat + N * K * b, ldb, 0.0f,
CReference + N * M * b, ldc,
MlasQgemmTestBase<Packed, Threaded>::threadpool_);
}
if (Bias != nullptr) {
for (size_t b = 0; b < BatchSize; b++) {
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++) {
CReference[N * M * b + m * ldc + n] += Bias[n];
}
}
}
}
this->TestGemm(M, N, K, BatchSize, A, lda, offa, AIsSigned, B, ldb, offb, BIsSigned, C, ldc, CScale, Bias);
for (size_t batch = 0, f = 0; batch < BatchSize; batch++) {
for (size_t m = 0; m < M; m++) {
for (size_t n = 0; n < N; n++, f++) {
// Sensitive to comparing positive/negative zero.
ASSERT_EQ(C[f], CReference[f]) << "@[" << batch << "x" << m << "x" << n << "], "
<< "Batch=" << BatchSize << "M=" << M << ", N=" << N << ", K=" << K
<< ", offa=" << int(offa) << ", offb=" << offb;
}
}
}
}
private:
template <typename qint8_t>
void DequantizeLinear(const qint8_t* Input,
float* Output,
size_t N,
float scale,
qint8_t offset) {
for (size_t n = 0; n < N; n++) {
Output[n] = float((int32_t(Input[n]) - offset)) * scale;
}
}
MatrixGuardBuffer<uint8_t> BufferA;
MatrixGuardBuffer<uint8_t> BufferB;
MatrixGuardBuffer<float> BufferAFloat;
MatrixGuardBuffer<float> BufferBFloat;
MatrixGuardBuffer<float> BufferC;
MatrixGuardBuffer<float> BufferCReference;
MatrixGuardBuffer<float> BufferBias;
const bool AIsSigned = std::is_signed<AType>::value;
const bool BIsSigned = std::is_signed<BType>::value;
public:
static const char* GetTestSuiteName() {
static std::string suite_name = std::string("QGemm") +
(std::is_signed<AType>::value ? "S8" : "U8") +
(std::is_signed<BType>::value ? "S8" : "U8") +
(Packed ? "_Fp32_Packed" : "_Fp32_NoPack") +
(Threaded ? "_Threaded" : "_SingleThread");
return suite_name.c_str();
}
};
| 34.76699 | 133 | 0.497626 | [
"vector"
] |
2ec9a89d42a9a0884523a2ec29b1aa7c1b19cca9 | 3,509 | h | C | Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/include/openfl/_v2/display/InteractiveObject.h | as3boyan/Uber-Duper-Simulation | a3942831a1acf08479f06fd8cfe8896ec00ac32c | [
"MIT"
] | null | null | null | Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/include/openfl/_v2/display/InteractiveObject.h | as3boyan/Uber-Duper-Simulation | a3942831a1acf08479f06fd8cfe8896ec00ac32c | [
"MIT"
] | null | null | null | Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/include/openfl/_v2/display/InteractiveObject.h | as3boyan/Uber-Duper-Simulation | a3942831a1acf08479f06fd8cfe8896ec00ac32c | [
"MIT"
] | null | null | null | #ifndef INCLUDED_openfl__v2_display_InteractiveObject
#define INCLUDED_openfl__v2_display_InteractiveObject
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#include <openfl/_v2/display/DisplayObject.h>
HX_DECLARE_CLASS3(openfl,_v2,display,DisplayObject)
HX_DECLARE_CLASS3(openfl,_v2,display,IBitmapDrawable)
HX_DECLARE_CLASS3(openfl,_v2,display,InteractiveObject)
HX_DECLARE_CLASS3(openfl,_v2,events,EventDispatcher)
HX_DECLARE_CLASS3(openfl,_v2,events,IEventDispatcher)
namespace openfl{
namespace _v2{
namespace display{
class HXCPP_CLASS_ATTRIBUTES InteractiveObject_obj : public ::openfl::_v2::display::DisplayObject_obj{
public:
typedef ::openfl::_v2::display::DisplayObject_obj super;
typedef InteractiveObject_obj OBJ_;
InteractiveObject_obj();
Void __construct(Dynamic handle,::String type);
public:
inline void *operator new( size_t inSize, bool inContainer=true)
{ return hx::Object::operator new(inSize,inContainer); }
static hx::ObjectPtr< InteractiveObject_obj > __new(Dynamic handle,::String type);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~InteractiveObject_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
::String __ToString() const { return HX_CSTRING("InteractiveObject"); }
bool doubleClickEnabled;
bool __mouseEnabled;
virtual bool __dismissSoftKeyboard( );
Dynamic __dismissSoftKeyboard_dyn();
virtual bool requestSoftKeyboard( );
Dynamic requestSoftKeyboard_dyn();
virtual ::openfl::_v2::display::InteractiveObject __asInteractiveObject( );
virtual bool get_mouseEnabled( );
Dynamic get_mouseEnabled_dyn();
virtual bool set_mouseEnabled( bool value);
Dynamic set_mouseEnabled_dyn();
virtual bool set_moveForSoftKeyboard( bool value);
Dynamic set_moveForSoftKeyboard_dyn();
virtual bool get_moveForSoftKeyboard( );
Dynamic get_moveForSoftKeyboard_dyn();
virtual bool set_needsSoftKeyboard( bool value);
Dynamic set_needsSoftKeyboard_dyn();
virtual bool get_needsSoftKeyboard( );
Dynamic get_needsSoftKeyboard_dyn();
static Dynamic lime_display_object_set_mouse_enabled;
static Dynamic &lime_display_object_set_mouse_enabled_dyn() { return lime_display_object_set_mouse_enabled;}
static Dynamic lime_display_object_set_needs_soft_keyboard;
static Dynamic &lime_display_object_set_needs_soft_keyboard_dyn() { return lime_display_object_set_needs_soft_keyboard;}
static Dynamic lime_display_object_get_needs_soft_keyboard;
static Dynamic &lime_display_object_get_needs_soft_keyboard_dyn() { return lime_display_object_get_needs_soft_keyboard;}
static Dynamic lime_display_object_set_moves_for_soft_keyboard;
static Dynamic &lime_display_object_set_moves_for_soft_keyboard_dyn() { return lime_display_object_set_moves_for_soft_keyboard;}
static Dynamic lime_display_object_get_moves_for_soft_keyboard;
static Dynamic &lime_display_object_get_moves_for_soft_keyboard_dyn() { return lime_display_object_get_moves_for_soft_keyboard;}
static Dynamic lime_display_object_dismiss_soft_keyboard;
static Dynamic &lime_display_object_dismiss_soft_keyboard_dyn() { return lime_display_object_dismiss_soft_keyboard;}
static Dynamic lime_display_object_request_soft_keyboard;
static Dynamic &lime_display_object_request_soft_keyboard_dyn() { return lime_display_object_request_soft_keyboard;}
};
} // end namespace openfl
} // end namespace _v2
} // end namespace display
#endif /* INCLUDED_openfl__v2_display_InteractiveObject */
| 39.875 | 130 | 0.829296 | [
"object"
] |
2ecdcf6a696930a70a14a0012b20989e0d464ceb | 31,217 | h | C | cds/container/michael_set.h | radiansz/libcds | 24a9e5ee830c66ae5c928796f59369da2bb41c68 | [
"BSD-2-Clause"
] | null | null | null | cds/container/michael_set.h | radiansz/libcds | 24a9e5ee830c66ae5c928796f59369da2bb41c68 | [
"BSD-2-Clause"
] | null | null | null | cds/container/michael_set.h | radiansz/libcds | 24a9e5ee830c66ae5c928796f59369da2bb41c68 | [
"BSD-2-Clause"
] | 1 | 2018-10-28T11:44:57.000Z | 2018-10-28T11:44:57.000Z | /*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CDSLIB_CONTAINER_MICHAEL_SET_H
#define CDSLIB_CONTAINER_MICHAEL_SET_H
#include <cds/container/details/michael_set_base.h>
#include <cds/details/allocator.h>
namespace cds { namespace container {
/// Michael's hash set
/** @ingroup cds_nonintrusive_set
\anchor cds_nonintrusive_MichaelHashSet_hp
Source:
- [2002] Maged Michael "High performance dynamic lock-free hash tables and list-based sets"
Michael's hash table algorithm is based on lock-free ordered list and it is very simple.
The main structure is an array \p T of size \p M. Each element in \p T is basically a pointer
to a hash bucket, implemented as a singly linked list. The array of buckets cannot be dynamically expanded.
However, each bucket may contain unbounded number of items.
Template parameters are:
- \p GC - Garbage collector used. You may use any \ref cds_garbage_collector "Garbage collector"
from the \p libcds library.
Note the \p GC must be the same as the \p GC used for \p OrderedList
- \p OrderedList - ordered list implementation used as bucket for hash set, for example, \p MichaelList.
The ordered list implementation specifies the type \p T to be stored in the hash-set,
the comparing functor for the type \p T and other features specific for the ordered list.
- \p Traits - set traits, default is \p michael_set::traits.
Instead of defining \p Traits struct you may use option-based syntax with \p michael_set::make_traits metafunction.
There are the specializations:
- for \ref cds_urcu_desc "RCU" - declared in <tt>cd/container/michael_set_rcu.h</tt>,
see \ref cds_nonintrusive_MichaelHashSet_rcu "MichaelHashSet<RCU>".
- for \ref cds::gc::nogc declared in <tt>cds/container/michael_set_nogc.h</tt>,
see \ref cds_nonintrusive_MichaelHashSet_nogc "MichaelHashSet<gc::nogc>".
\anchor cds_nonintrusive_MichaelHashSet_hash_functor
<b>Hash functor</b>
Some member functions of Michael's hash set accept the key parameter of type \p Q which differs from node type \p value_type.
It is expected that type \p Q contains full key of node type \p value_type, and if keys of type \p Q and \p value_type
are equal the hash values of these keys must be equal too.
The hash functor \p Traits::hash should accept parameters of both type:
\code
// Our node type
struct Foo {
std::string key_ ; // key field
// ... other fields
};
// Hash functor
struct fooHash {
size_t operator()( const std::string& s ) const
{
return std::hash( s );
}
size_t operator()( const Foo& f ) const
{
return (*this)( f.key_ );
}
};
\endcode
<b>Iterators</b>
The class supports a forward iterator (\ref iterator and \ref const_iterator).
The iteration is unordered.
The iterator object is thread-safe: the element pointed by the iterator object is guarded,
so, the element cannot be reclaimed while the iterator object is alive.
However, passing an iterator object between threads is dangerous.
@warning Due to concurrent nature of Michael's set it is not guarantee that you can iterate
all elements in the set: any concurrent deletion can exclude the element
pointed by the iterator from the set, and your iteration can be terminated
before end of the set. Therefore, such iteration is more suitable for debugging purpose only
Remember, each iterator object requires an additional hazard pointer, that may be
a limited resource for \p GC like \p gc::HP (for \p gc::DHP the total count of
guards is unlimited).
The iterator class supports the following minimalistic interface:
\code
struct iterator {
// Default ctor
iterator();
// Copy ctor
iterator( iterator const& s);
value_type * operator ->() const;
value_type& operator *() const;
// Pre-increment
iterator& operator ++();
// Copy assignment
iterator& operator = (const iterator& src);
bool operator ==(iterator const& i ) const;
bool operator !=(iterator const& i ) const;
};
\endcode
Note, the iterator object returned by \ref end, \p cend member functions points to \p nullptr and should not be dereferenced.
<b>How to use</b>
Suppose, we have the following type \p Foo that we want to store in our \p %MichaelHashSet:
\code
struct Foo {
int nKey ; // key field
int nVal ; // value field
};
\endcode
To use \p %MichaelHashSet for \p Foo values, you should first choose suitable ordered list class
that will be used as a bucket for the set. We will use \p gc::DHP reclamation schema and
\p MichaelList as a bucket type. Also, for ordered list we should develop a comparator for our \p Foo
struct.
\code
#include <cds/container/michael_list_dhp.h>
#include <cds/container/michael_set.h>
namespace cc = cds::container;
// Foo comparator
struct Foo_cmp {
int operator ()(Foo const& v1, Foo const& v2 ) const
{
if ( std::less( v1.nKey, v2.nKey ))
return -1;
return std::less(v2.nKey, v1.nKey) ? 1 : 0;
}
};
// Our ordered list
typedef cc::MichaelList< cds::gc::DHP, Foo,
typename cc::michael_list::make_traits<
cc::opt::compare< Foo_cmp > // item comparator option
>::type
> bucket_list;
// Hash functor for Foo
struct foo_hash {
size_t operator ()( int i ) const
{
return std::hash( i );
}
size_t operator()( Foo const& i ) const
{
return std::hash( i.nKey );
}
};
// Declare set type.
// Note that \p GC template parameter of ordered list must be equal \p GC for the set.
typedef cc::MichaelHashSet< cds::gc::DHP, bucket_list,
cc::michael_set::make_traits<
cc::opt::hash< foo_hash >
>::type
> foo_set;
// Set variable
foo_set fooSet;
\endcode
*/
template <
class GC,
class OrderedList,
#ifdef CDS_DOXYGEN_INVOKED
class Traits = michael_set::traits
#else
class Traits
#endif
>
class MichaelHashSet
{
public:
typedef GC gc; ///< Garbage collector
typedef OrderedList bucket_type; ///< type of ordered list used as a bucket implementation
typedef Traits traits; ///< Set traits
typedef typename bucket_type::value_type value_type; ///< type of value to be stored in the list
typedef typename bucket_type::key_comparator key_comparator; ///< key comparison functor
/// Hash functor for \ref value_type and all its derivatives that you use
typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
typedef typename traits::item_counter item_counter; ///< Item counter type
/// Bucket table allocator
typedef cds::details::Allocator< bucket_type, typename traits::allocator > bucket_table_allocator;
typedef typename bucket_type::guarded_ptr guarded_ptr; ///< Guarded pointer
protected:
item_counter m_ItemCounter; ///< Item counter
hash m_HashFunctor; ///< Hash functor
bucket_type * m_Buckets; ///< bucket table
private:
//@cond
const size_t m_nHashBitmask;
//@endcond
protected:
//@cond
/// Calculates hash value of \p key
template <typename Q>
size_t hash_value( Q const& key ) const
{
return m_HashFunctor( key ) & m_nHashBitmask;
}
/// Returns the bucket (ordered list) for \p key
template <typename Q>
bucket_type& bucket( Q const& key )
{
return m_Buckets[ hash_value( key ) ];
}
//@endcond
public:
/// Forward iterator
typedef michael_set::details::iterator< bucket_type, false > iterator;
/// Const forward iterator
typedef michael_set::details::iterator< bucket_type, true > const_iterator;
/// Returns a forward iterator addressing the first element in a set
/**
For empty set \code begin() == end() \endcode
*/
iterator begin()
{
return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
}
/// Returns an iterator that addresses the location succeeding the last element in a set
/**
Do not use the value returned by <tt>end</tt> function to access any item.
The returned value can be used only to control reaching the end of the set.
For empty set \code begin() == end() \endcode
*/
iterator end()
{
return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
}
/// Returns a forward const iterator addressing the first element in a set
//@{
const_iterator begin() const
{
return get_const_begin();
}
const_iterator cbegin() const
{
return get_const_begin();
}
//@}
/// Returns an const iterator that addresses the location succeeding the last element in a set
//@{
const_iterator end() const
{
return get_const_end();
}
const_iterator cend() const
{
return get_const_end();
}
//@}
private:
//@cond
const_iterator get_const_begin() const
{
return const_iterator( const_cast<bucket_type const&>(m_Buckets[0]).begin(), m_Buckets, m_Buckets + bucket_count() );
}
const_iterator get_const_end() const
{
return const_iterator( const_cast<bucket_type const&>(m_Buckets[bucket_count() - 1]).end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
}
//@endcond
public:
/// Initialize hash set
/** @anchor cds_nonintrusive_MichaelHashSet_hp_ctor
The Michael's hash set is non-expandable container. You should point the average count of items \p nMaxItemCount
when you create an object.
\p nLoadFactor parameter defines average count of items per bucket and it should be small number between 1 and 10.
Remember, since the bucket implementation is an ordered list, searching in the bucket is linear [<tt>O(nLoadFactor)</tt>].
The ctor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
*/
MichaelHashSet(
size_t nMaxItemCount, ///< estimation of max item count in the hash set
size_t nLoadFactor ///< load factor: estimation of max number of items in the bucket
) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
{
// GC and OrderedList::gc must be the same
static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
// atomicity::empty_item_counter is not allowed as a item counter
static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
"cds::atomicity::empty_item_counter is not allowed as a item counter");
m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
}
/// Clears hash set and destroys it
~MichaelHashSet()
{
clear();
bucket_table_allocator().Delete( m_Buckets, bucket_count() );
}
/// Inserts new node
/**
The function creates a node with copy of \p val value
and then inserts the node created into the set.
The type \p Q should contain as minimum the complete key for the node.
The object of \ref value_type should be constructible from a value of type \p Q.
In trivial case, \p Q is equal to \ref value_type.
Returns \p true if \p val is inserted into the set, \p false otherwise.
*/
template <typename Q>
bool insert( Q const& val )
{
const bool bRet = bucket( val ).insert( val );
if ( bRet )
++m_ItemCounter;
return bRet;
}
/// Inserts new node
/**
The function allows to split creating of new item into two part:
- create item with key only
- insert new item into the set
- if inserting is success, calls \p f functor to initialize value-fields of \p val.
The functor signature is:
\code
void func( value_type& val );
\endcode
where \p val is the item inserted.
The user-defined functor is called only if the inserting is success.
@warning For \ref cds_nonintrusive_MichaelList_gc "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
@ref cds_nonintrusive_LazyList_gc "LazyList" provides exclusive access to inserted item and does not require any node-level
synchronization.
*/
template <typename Q, typename Func>
bool insert( Q const& val, Func f )
{
const bool bRet = bucket( val ).insert( val, f );
if ( bRet )
++m_ItemCounter;
return bRet;
}
/// Updates the element
/**
The operation performs inserting or changing data with lock-free manner.
If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
Otherwise, the functor \p func is called with item found.
The functor signature is:
\code
struct functor {
void operator()( bool bNew, value_type& item, Q const& val );
};
\endcode
with arguments:
- \p bNew - \p true if the item has been inserted, \p false otherwise
- \p item - item of the set
- \p val - argument \p val passed into the \p %update() function
The functor may change non-key fields of the \p item.
Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successfull,
\p second is \p true if new item has been added or \p false if the item with \p key
already is in the set.
@warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
\ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
synchronization.
*/
template <typename Q, typename Func>
std::pair<bool, bool> update( const Q& val, Func func, bool bAllowUpdate = true )
{
std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowUpdate );
if ( bRet.second )
++m_ItemCounter;
return bRet;
}
//@cond
template <typename Q, typename Func>
CDS_DEPRECATED("ensure() is deprecated, use update()")
std::pair<bool, bool> ensure( const Q& val, Func func )
{
return update( val, func, true );
}
//@endcond
/// Inserts data of type \p value_type constructed from \p args
/**
Returns \p true if inserting successful, \p false otherwise.
*/
template <typename... Args>
bool emplace( Args&&... args )
{
bool bRet = bucket( value_type(std::forward<Args>(args)...) ).emplace( std::forward<Args>(args)... );
if ( bRet )
++m_ItemCounter;
return bRet;
}
/// Deletes \p key from the set
/** \anchor cds_nonintrusive_MichaelSet_erase_val
Since the key of MichaelHashSet's item type \ref value_type is not explicitly specified,
template parameter \p Q defines the key type searching in the list.
The set item comparator should be able to compare the type \p value_type
and the type \p Q.
Return \p true if key is found and deleted, \p false otherwise
*/
template <typename Q>
bool erase( Q const& key )
{
const bool bRet = bucket( key ).erase( key );
if ( bRet )
--m_ItemCounter;
return bRet;
}
/// Deletes the item from the set using \p pred predicate for searching
/**
The function is an analog of \ref cds_nonintrusive_MichaelSet_erase_val "erase(Q const&)"
but \p pred is used for key comparing.
\p Less functor has the interface like \p std::less.
\p Less must imply the same element order as the comparator used for building the set.
*/
template <typename Q, typename Less>
bool erase_with( Q const& key, Less pred )
{
const bool bRet = bucket( key ).erase_with( key, pred );
if ( bRet )
--m_ItemCounter;
return bRet;
}
/// Deletes \p key from the set
/** \anchor cds_nonintrusive_MichaelSet_erase_func
The function searches an item with key \p key, calls \p f functor
and deletes the item. If \p key is not found, the functor is not called.
The functor \p Func interface:
\code
struct extractor {
void operator()(value_type& item);
};
\endcode
where \p item - the item found.
Since the key of %MichaelHashSet's \p value_type is not explicitly specified,
template parameter \p Q defines the key type searching in the list.
The list item comparator should be able to compare the type \p T of list item
and the type \p Q.
Return \p true if key is found and deleted, \p false otherwise
*/
template <typename Q, typename Func>
bool erase( Q const& key, Func f )
{
const bool bRet = bucket( key ).erase( key, f );
if ( bRet )
--m_ItemCounter;
return bRet;
}
/// Deletes the item from the set using \p pred predicate for searching
/**
The function is an analog of \ref cds_nonintrusive_MichaelSet_erase_func "erase(Q const&, Func)"
but \p pred is used for key comparing.
\p Less functor has the interface like \p std::less.
\p Less must imply the same element order as the comparator used for building the set.
*/
template <typename Q, typename Less, typename Func>
bool erase_with( Q const& key, Less pred, Func f )
{
const bool bRet = bucket( key ).erase_with( key, pred, f );
if ( bRet )
--m_ItemCounter;
return bRet;
}
/// Extracts the item with specified \p key
/** \anchor cds_nonintrusive_MichaelHashSet_hp_extract
The function searches an item with key equal to \p key,
unlinks it from the set, and returns it as \p guarded_ptr.
If \p key is not found the function returns an empty guadd pointer.
Note the compare functor should accept a parameter of type \p Q that may be not the same as \p value_type.
The extracted item is freed automatically when returned \p guarded_ptr object will be destroyed or released.
@note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
Usage:
\code
typedef cds::container::MichaelHashSet< your_template_args > michael_set;
michael_set theSet;
// ...
{
michael_set::guarded_ptr gp( theSet.extract( 5 ));
if ( gp ) {
// Deal with gp
// ...
}
// Destructor of gp releases internal HP guard
}
\endcode
*/
template <typename Q>
guarded_ptr extract( Q const& key )
{
guarded_ptr gp( bucket( key ).extract( key ));
if ( gp )
--m_ItemCounter;
return gp;
}
/// Extracts the item using compare functor \p pred
/**
The function is an analog of \ref cds_nonintrusive_MichaelHashSet_hp_extract "extract(Q const&)"
but \p pred predicate is used for key comparing.
\p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
in any order.
\p pred must imply the same element order as the comparator used for building the set.
*/
template <typename Q, typename Less>
guarded_ptr extract_with( Q const& key, Less pred )
{
guarded_ptr gp( bucket( key ).extract_with( key, pred ));
if ( gp )
--m_ItemCounter;
return gp;
}
/// Finds the key \p key
/** \anchor cds_nonintrusive_MichaelSet_find_func
The function searches the item with key equal to \p key and calls the functor \p f for item found.
The interface of \p Func functor is:
\code
struct functor {
void operator()( value_type& item, Q& key );
};
\endcode
where \p item is the item found, \p key is the <tt>find</tt> function argument.
The functor may change non-key fields of \p item. Note that the functor is only guarantee
that \p item cannot be disposed during functor is executing.
The functor does not serialize simultaneous access to the set's \p item. If such access is
possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
can modify both arguments.
Note the hash functor specified for class \p Traits template parameter
should accept a parameter of type \p Q that may be not the same as \p value_type.
The function returns \p true if \p key is found, \p false otherwise.
*/
template <typename Q, typename Func>
bool find( Q& key, Func f )
{
return bucket( key ).find( key, f );
}
//@cond
template <typename Q, typename Func>
bool find( Q const& key, Func f )
{
return bucket( key ).find( key, f );
}
//@endcond
/// Finds the key \p key using \p pred predicate for searching
/**
The function is an analog of \ref cds_nonintrusive_MichaelSet_find_func "find(Q&, Func)"
but \p pred is used for key comparing.
\p Less functor has the interface like \p std::less.
\p Less must imply the same element order as the comparator used for building the set.
*/
template <typename Q, typename Less, typename Func>
bool find_with( Q& key, Less pred, Func f )
{
return bucket( key ).find_with( key, pred, f );
}
//@cond
template <typename Q, typename Less, typename Func>
bool find_with( Q const& key, Less pred, Func f )
{
return bucket( key ).find_with( key, pred, f );
}
//@endcond
/// Checks whether the set contains \p key
/**
The function searches the item with key equal to \p key
and returns \p true if the key is found, and \p false otherwise.
Note the hash functor specified for class \p Traits template parameter
should accept a parameter of type \p Q that can be not the same as \p value_type.
*/
template <typename Q>
bool contains( Q const& key )
{
return bucket( key ).contains( key );
}
//@cond
template <typename Q>
CDS_DEPRECATED("use contains()")
bool find( Q const& key )
{
return contains( key );
}
//@endcond
/// Checks whether the set contains \p key using \p pred predicate for searching
/**
The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
\p Less functor has the interface like \p std::less.
\p Less must imply the same element order as the comparator used for building the set.
*/
template <typename Q, typename Less>
bool contains( Q const& key, Less pred )
{
return bucket( key ).contains( key, pred );
}
//@cond
template <typename Q, typename Less>
CDS_DEPRECATED("use contains()")
bool find_with( Q const& key, Less pred )
{
return contains( key, pred );
}
//@endcond
/// Finds the key \p key and return the item found
/** \anchor cds_nonintrusive_MichaelHashSet_hp_get
The function searches the item with key equal to \p key
and returns the guarded pointer to the item found.
If \p key is not found the functin returns an empty guarded pointer.
@note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
Usage:
\code
typedef cds::container::MichaeHashSet< your_template_params > michael_set;
michael_set theSet;
// ...
{
michael_set::guarded_ptr gp( theSet.get( 5 ));
if ( gp ) {
// Deal with gp
//...
}
// Destructor of guarded_ptr releases internal HP guard
}
\endcode
Note the compare functor specified for \p OrderedList template parameter
should accept a parameter of type \p Q that can be not the same as \p value_type.
*/
template <typename Q>
guarded_ptr get( Q const& key )
{
return bucket( key ).get( key );
}
/// Finds the key \p key and return the item found
/**
The function is an analog of \ref cds_nonintrusive_MichaelHashSet_hp_get "get( Q const&)"
but \p pred is used for comparing the keys.
\p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
in any order.
\p pred must imply the same element order as the comparator used for building the set.
*/
template <typename Q, typename Less>
guarded_ptr get_with( Q const& key, Less pred )
{
return bucket( key ).get_with( key, pred );
}
/// Clears the set (non-atomic)
/**
The function erases all items from the set.
The function is not atomic. It cleans up each bucket and then resets the item counter to zero.
If there are a thread that performs insertion while \p clear is working the result is undefined in general case:
<tt> empty() </tt> may return \p true but the set may contain item(s).
Therefore, \p clear may be used only for debugging purposes.
*/
void clear()
{
for ( size_t i = 0; i < bucket_count(); ++i )
m_Buckets[i].clear();
m_ItemCounter.reset();
}
/// Checks if the set is empty
/**
Emptiness is checked by item counting: if item count is zero then the set is empty.
Thus, the correct item counting feature is an important part of Michael's set implementation.
*/
bool empty() const
{
return size() == 0;
}
/// Returns item count in the set
size_t size() const
{
return m_ItemCounter;
}
/// Returns the size of hash table
/**
Since MichaelHashSet cannot dynamically extend the hash table size,
the value returned is an constant depending on object initialization parameters;
see MichaelHashSet::MichaelHashSet for explanation.
*/
size_t bucket_count() const
{
return m_nHashBitmask + 1;
}
};
}} // namespace cds::container
#endif // ifndef CDSLIB_CONTAINER_MICHAEL_SET_H
| 39.970551 | 165 | 0.591761 | [
"object"
] |
2ed3bd12c7f6ed64964fe2cdf73c652b4066cd8b | 11,448 | h | C | kratos/tests/cpp_tests/auxiliar_files_for_cpp_unnitest/test_constitutive_law.h | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | kratos/tests/cpp_tests/auxiliar_files_for_cpp_unnitest/test_constitutive_law.h | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | kratos/tests/cpp_tests/auxiliar_files_for_cpp_unnitest/test_constitutive_law.h | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
//
// Main authors: Alejandro Cornejo
//
//
#if !defined (KRATOS_TEST_CONSTITUTIVE_LAW_H_INCLUDED)
#define KRATOS_TEST_CONSTITUTIVE_LAW_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/constitutive_law.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class TestConstitutiveLaw
* @ingroup StructuralMechanicsApplication
* @brief This class defines a small deformation linear elastic constitutive model for 3D cases
* @details This class derives from the base constitutive law
* @author Riccardo Rossi
* @author Vicente Mataix Ferrandiz
*/
class TestConstitutiveLaw
: public ConstitutiveLaw
{
public:
///@name Type Definitions
///@{
/// The process info type definition
typedef ProcessInfo ProcessInfoType;
/// The base class ConstitutiveLaw type definition
typedef ConstitutiveLaw BaseType;
/// The size type definition
typedef std::size_t SizeType;
/// Static definition of the dimension
static constexpr SizeType Dimension = 3;
/// Static definition of the VoigtSize
static constexpr SizeType VoigtSize = 6;
// Adding the respective using to avoid overload conflicts
using BaseType::Has;
using BaseType::GetValue;
/// Counted pointer of TestConstitutiveLaw
KRATOS_CLASS_POINTER_DEFINITION( TestConstitutiveLaw );
///@}
///@name Lyfe Cycle
///@{
/**
* @brief Default constructor.
*/
TestConstitutiveLaw();
/**
* @brief Clone method
*/
ConstitutiveLaw::Pointer Clone() const override;
/**
* Copy constructor.
*/
TestConstitutiveLaw (const TestConstitutiveLaw& rOther);
/**
* @brief Destructor.
*/
~TestConstitutiveLaw() override;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief This function is designed to be called once to check compatibility with element
* @param rFeatures The Features of the law
*/
void GetLawFeatures(Features& rFeatures) override;
/**
* @brief Dimension of the law:
*/
SizeType WorkingSpaceDimension() override
{
return Dimension;
};
/**
* @brief Voigt tensor size:
*/
SizeType GetStrainSize() const override
{
return VoigtSize;
};
/**
* @brief Returns the expected strain measure of this constitutive law (by default Green-Lagrange)
* @return the expected strain measure
*/
StrainMeasure GetStrainMeasure() override
{
return StrainMeasure_Infinitesimal;
}
/**
* @brief Returns the stress measure of this constitutive law (by default 2st Piola-Kirchhoff stress in voigt notation)
* @return the expected stress measure
*/
StressMeasure GetStressMeasure() override
{
return StressMeasure_Cauchy;
}
/**
* @brief Computes the material response:
* @details PK1 stresses and algorithmic ConstitutiveMatrix
* @param rValues The internal values of the law
* @see Parameters
*/
void CalculateMaterialResponsePK1 (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Computes the material response:
* @details PK2 stresses and algorithmic ConstitutiveMatrix
* @param rValues The internal values of the law
* @see Parameters
*/
void CalculateMaterialResponsePK2 (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Computes the material response:
* @details Kirchhoff stresses and algorithmic ConstitutiveMatrix
* @param rValues The internal values of the law
* @see Parameters
*/
void CalculateMaterialResponseKirchhoff (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Computes the material response:
* @details Cauchy stresses and algorithmic ConstitutiveMatrix
* @param rValues The internal values of the law
* @see Parameters
*/
void CalculateMaterialResponseCauchy (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Initialize the material response in terms of 1st Piola-Kirchhoff stresses
* @see Parameters
*/
void InitializeMaterialResponsePK1 (ConstitutiveLaw::Parameters& rValues) override;
/**
* @brief Initialize the material response in terms of 2nd Piola-Kirchhoff stresses
* @see Parameters
*/
void InitializeMaterialResponsePK2 (ConstitutiveLaw::Parameters& rValues) override;
/**
* @brief Initialize the material response in terms of Kirchhoff stresses
* @see Parameters
*/
void InitializeMaterialResponseKirchhoff (ConstitutiveLaw::Parameters& rValues) override;
/**
* @brief Initialize the material response in terms of Cauchy stresses
* @see Parameters
*/
void InitializeMaterialResponseCauchy (ConstitutiveLaw::Parameters& rValues) override;
/**
* @brief Updates the material response:
* @details Cauchy stresses and Internal Variables
* @param rValues The internal values of the law
* @see Parameters
*/
void FinalizeMaterialResponsePK1 (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Updates the material response:
* Cauchy stresses and Internal Variables
* @param rValues The internal values of the law
* @see Parameters
*/
void FinalizeMaterialResponsePK2 (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Updates the material response:
* @details Cauchy stresses and Internal Variables
* @param rValues The internal values of the law
* @see Parameters
*/
void FinalizeMaterialResponseKirchhoff (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief Updates the material response:
* @details Cauchy stresses and Internal Variables
* @param rValues The internal values of the law
* @see Parameters
*/
void FinalizeMaterialResponseCauchy (ConstitutiveLaw::Parameters & rValues) override;
/**
* @brief If the CL requires to initialize the material response, called by the element in InitializeSolutionStep.
*/
bool RequiresInitializeMaterialResponse() override
{
return false;
}
/**
* @brief If the CL requires to finalize the material response, called by the element in FinalizeSolutionStep.
*/
bool RequiresFinalizeMaterialResponse() override
{
return false;
}
/**
* @brief It calculates the value of a specified variable (double case)
* @param rParameterValues the needed parameters for the CL calculation
* @param rThisVariable the variable to be returned
* @param rValue a reference to the returned value
* @return rValue output: the value of the specified variable
*/
double& CalculateValue(
ConstitutiveLaw::Parameters& rParameterValues,
const Variable<double>& rThisVariable,
double& rValue
) override;
/**
* @brief It calculates the value of a specified variable (Vector case)
* @param rParameterValues the needed parameters for the CL calculation
* @param rThisVariable the variable to be returned
* @param rValue a reference to the returned value
* @return rValue output: the value of the specified variable
*/
Vector& CalculateValue(
ConstitutiveLaw::Parameters& rParameterValues,
const Variable<Vector>& rThisVariable,
Vector& rValue
) override;
/**
* @brief It calculates the value of a specified variable (Matrix case)
* @param rParameterValues the needed parameters for the CL calculation
* @param rThisVariable the variable to be returned
* @param rValue a reference to the returned value
* @return rValue output: the value of the specified variable
*/
Matrix& CalculateValue(
ConstitutiveLaw::Parameters& rParameterValues,
const Variable<Matrix>& rThisVariable,
Matrix& rValue
) override;
/**
* @brief This function provides the place to perform checks on the completeness of the input.
* @details It is designed to be called only once (or anyway, not often) typically at the beginning of the calculations, so to verify that nothing is missing from the input or that no common error is found.
* @param rMaterialProperties The properties of the material
* @param rElementGeometry The geometry of the element
* @param rCurrentProcessInfo The current process info instance
* @return 0 if OK, 1 otherwise
*/
int Check(
const Properties& rMaterialProperties,
const GeometryType& rElementGeometry,
const ProcessInfo& rCurrentProcessInfo
) const override;
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* @brief It checks the size of the constitutive matrix rConstitutiveMatrix and resize it if neccessary
* @param rConstitutiveMatrix The constitutive matrix
*/
void CheckClearElasticMatrix(Matrix& rConstitutiveMatrix);
/**
* @brief It calculates the constitutive matrix rConstitutiveMatrix
* @param rConstitutiveMatrix The constitutive matrix
* @param rValues Parameters of the constitutive law
*/
virtual void CalculateElasticMatrix(
Matrix& rConstitutiveMatrix,
ConstitutiveLaw::Parameters& rValues
);
/**
* @brief It calculates the stress vector
* @param rStrainVector The strain vector in Voigt notation
* @param rStressVector The stress vector in Voigt notation
* @param rValues Parameters of the constitutive law
*/
virtual void CalculatePK2Stress(
const Vector& rStrainVector,
Vector& rStressVector,
ConstitutiveLaw::Parameters& rValues
);
/**
* @brief It calculates the strain vector
* @param rValues The internal values of the law
* @param rStrainVector The strain vector in Voigt notation
*/
virtual void CalculateCauchyGreenStrain(
ConstitutiveLaw::Parameters& rValues,
Vector& rStrainVector
);
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
friend class Serializer;
void save(Serializer& rSerializer) const override
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, ConstitutiveLaw )
}
void load(Serializer& rSerializer) override
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, ConstitutiveLaw)
}
}; // Class TestConstitutiveLaw
} // namespace Kratos.
#endif // KRATOS_ELASTIC_ISOTROPIC_3D_LAW_H_INCLUDED defined
| 27.99022 | 210 | 0.661076 | [
"geometry",
"vector",
"model",
"3d"
] |
2ed63b47b8b019aa430c30149e244cde9142e663 | 728 | h | C | src/IdWrap.h | TooTallNate/node-objc | 7a1ee57fb091a040869cc83d69d5328fa06c3ba7 | [
"MIT"
] | 2 | 2015-05-02T16:00:56.000Z | 2015-12-18T17:20:12.000Z | src/IdWrap.h | TooTallNate/node-objc | 7a1ee57fb091a040869cc83d69d5328fa06c3ba7 | [
"MIT"
] | null | null | null | src/IdWrap.h | TooTallNate/node-objc | 7a1ee57fb091a040869cc83d69d5328fa06c3ba7 | [
"MIT"
] | null | null | null | #include <node.h>
#include <v8.h>
namespace node_objc {
// `IdWrap` is a node ObjectWrap that wraps up an ObjC `id`. This allows
// arbitrary ObjectiveC objects to be passed around the V8 environment.
extern v8::Persistent<v8::FunctionTemplate> id_constructor_template;
class IdWrap : public node::ObjectWrap {
public:
IdWrap();
~IdWrap();
id ref;
static void Init(v8::Handle<v8::Object>);
static v8::Handle<v8::Value> New(const v8::Arguments&);
// 'toString()' override
static v8::Handle<v8::Value> ToString(const v8::Arguments&);
static v8::Handle<v8::Value> IntToNumber(const v8::Arguments&);
static v8::Handle<v8::Value> Unwrap(const v8::Arguments&);
}; // class IdWrap
} // namespace node_objc
| 23.483871 | 72 | 0.706044 | [
"object"
] |
2ed671ef69efb0003b22c2394a53c7c52ac77b04 | 4,789 | h | C | src/CCA/Components/Models/HEChem/LightTime.h | abagusetty/Uintah | fa1bf819664fa6f09c5a7cd076870a40816d35c9 | [
"MIT"
] | null | null | null | src/CCA/Components/Models/HEChem/LightTime.h | abagusetty/Uintah | fa1bf819664fa6f09c5a7cd076870a40816d35c9 | [
"MIT"
] | null | null | null | src/CCA/Components/Models/HEChem/LightTime.h | abagusetty/Uintah | fa1bf819664fa6f09c5a7cd076870a40816d35c9 | [
"MIT"
] | null | null | null | /*
* The MIT License
*
* Copyright (c) 1997-2021 The University of Utah
*
* 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 Packages_Uintah_CCA_Components_Models_LightTime_h
#define Packages_Uintah_CCA_Components_Models_LightTime_h
#include <CCA/Components/Models/HEChem/HEChemModel.h>
#include <Core/Grid/Variables/ComputeSet.h>
namespace Uintah {
class ICELabel;
/**************************************
CLASS
LightTime
GENERAL INFORMATION
LightTime.h
Jim Guilkey
Department of Mechanical Engineering
University of Utah
Center for the Simulation of Accidental Fires and Explosions (C-SAFE)
KEYWORDS
"Program Burn" "Lighting Time Model"
DESCRIPTION
This model was constructed based on a collection of notes provided
to Jim Guilkey by Peter Vitello at LLNL. These are excerpts from national
lab code manuals such as HEMP and Kovec, but don't contain enough information
to pull actual references.
The model is pretty straightforward, on specifies the reactant material
and the product material, indicates an origin of the detonation and a detonation
velocity. Cells start to burn once the distance from the origin to the cell
center, divided by the detonation velocity, meets or exceeds the elapsed
simulation time. One can also specify an origin as a plane rather than a point.
WARNING
****************************************/
class LightTime : public HEChemModel {
public:
LightTime(const ProcessorGroup* myworld,
const MaterialManagerP& materialManager,
const ProblemSpecP& params);
virtual ~LightTime();
virtual void outputProblemSpec(ProblemSpecP& ps);
virtual void problemSetup(GridP& grid,
const bool isRestart);
virtual void scheduleInitialize(SchedulerP&,
const LevelP& level);
virtual void scheduleRestartInitialize(SchedulerP&,
const LevelP& level){};
virtual void scheduleComputeStableTimeStep(SchedulerP&,
const LevelP& level);
virtual void scheduleComputeModelSources(SchedulerP&,
const LevelP& level);
virtual void scheduleErrorEstimate(const LevelP& coarseLevel,
SchedulerP& sched);
private:
void initialize(const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset* matls,
DataWarehouse*,
DataWarehouse*);
void computeModelSources(const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset* matls,
DataWarehouse*,
DataWarehouse* new_dw);
void errorEstimate(const ProcessorGroup*,
const PatchSubset* patches,
const MaterialSubset*,
DataWarehouse*,
DataWarehouse* new_dw);
LightTime(const LightTime&);
LightTime& operator=(const LightTime&);
const VarLabel* reactedFractionLabel; // diagnostic labels
const VarLabel* mag_grad_Fr_Label;
const VarLabel* delFLabel;
ProblemSpecP d_params;
const Material* matl0;
const Material* matl1;
ICELabel* Ilb;
MaterialSet* mymatls;
double d_D; // detonation wave velocity
double d_E0;
Point d_start_place;
Vector d_direction;
bool d_react_mixed_cells;
double d_refineCriteria;
};
}
#endif
| 32.80137 | 80 | 0.643767 | [
"vector",
"model"
] |
2edff860ff7fca199e311e327fd3ee93c5ffe245 | 9,804 | h | C | include/Lucia/Utils/OpenGL.h | Polynominal/Lucy3D | a55fc331bc509a69ad7fb70a1eda70c409d22271 | [
"MIT"
] | 1 | 2017-02-22T23:47:22.000Z | 2017-02-22T23:47:22.000Z | include/Lucia/Utils/OpenGL.h | Polynominal/Lucy3D | a55fc331bc509a69ad7fb70a1eda70c409d22271 | [
"MIT"
] | null | null | null | include/Lucia/Utils/OpenGL.h | Polynominal/Lucy3D | a55fc331bc509a69ad7fb70a1eda70c409d22271 | [
"MIT"
] | null | null | null | #ifndef LUCIA_UTILITIES_OPENGL_ANDBUFFER_H
#define LUCIA_UTILITIES_OPENGL_ANDBUFFER_H
#include <Lucia/Settings.h>
#include <Lucia/Utils/Log.h>
#include <vector>
#include <memory>
#include <fstream>
#include <iostream>
#include <cstdarg>
namespace Lucia {
namespace Utils
{
namespace OpenGL
{
typedef unsigned int uint;
template<typename T>
using ptr = typename std::shared_ptr<T>;
struct Vertex_Buffer
{
std::vector<GLfloat> Data;
// the order is messed up with the constructor so I have to write two varidiac templates.
// I originally had a diagnostic varidiac function but it would cause sigill via va_arg as expected
template <typename T>
void add(T var)
{
Data.push_back(var);
};
template <class T, class... T2>
void add(T first,T2... rest)
{
add(first);
add(rest...);
}
template <typename T>
Vertex_Buffer(T var)
{
add(var);
}
template <class T, class... T2>
Vertex_Buffer(T first, T2... rest)
{
add(first);
add(rest...);
};
Vertex_Buffer(){};
};
struct Shader_Var_Atribute
{
int location;
int start;
int finish;
Shader_Var_Atribute(int tlocation,int tstart,int tfinish):
location(tlocation),start(tstart),finish(tfinish){};
void apply(int vsize);
};
struct Shader_Vars
{
std::vector <Shader_Var_Atribute> Attributes;
int VertexSize = 0;
int programID;
uint VBufferIter=0;
Shader_Vars(){};
int find(std::string name);
int findAttribute(std::string name);
void send(std::string name,double v0){send(name,float(v0));};
void send(std::string name,double v0,double v1){send(name,float(v0),float(v1));};
void send(std::string name,double v0,double v1,double v2){send(name,float(v0),float(v1),float(v2));};
void send(std::string name,double v0,double v1,double v2,double v3){send(name,float(v0),float(v1),float(v2),float(v3));};
void send(std::string name,float v0);
void send(std::string name,float v0,float v1);
void send(std::string name,float v0,float v1,float v2);
void send(std::string name,float v0,float v1,float v2,float v3);
void send(std::string name,int v0);
void send(std::string name,int v0,int v1);
void send(std::string name,int v0,int v1,int v2);
void send(std::string name,int v0,int v1,int v2,int v3);
#ifndef LUCIA_USE_GLES2
void send(std::string name,uint v0);
void send(std::string name,uint v0,uint v1);
void send(std::string name,uint v0,uint v1,uint v2);
void send(std::string name,uint v0,uint v1,uint v2,uint v3);
#endif
void sendArray(std::string name,float* data,uint arraySize);
void sendArray(std::string name,int* data,uint arraySize);
void sendArray(std::string name,uint* data,uint arraySize);
void sendMatrix(std::string name,int width,int height,bool transpose,float* value);
void use(){glUseProgram(programID);};
void clear(){Attributes.clear();VertexSize=0;};
void setProgram(int ID){programID = ID;clear();};
int getID(){return programID;};
void add(const char* name, int start,int finish);
int getVertexSize();
void apply();
};
extern ptr<Shader_Vars>shaderVars;
void setGlobalShaderVars(std::shared_ptr<Shader_Vars> v);
std::shared_ptr<Shader_Vars> getGlobalShaderVars();
class Buffer
{
public:
GLuint vao=0;
GLuint vbo=0;
#ifndef LUCIA_USE_GLES2
GLuint ivbo=0; //instanced VBO
#endif
GLuint ebo=0;
uint size;
int boundInstanceSize = 0;
std::vector<std::shared_ptr<Buffer>> Buffers;
std::shared_ptr<Shader_Vars> Vars;
bool Attached = false;
void setShaderVars(std::shared_ptr<Shader_Vars> s);
std::shared_ptr<Shader_Vars> getShaderVars();
void generate(bool genEBO=false);
void setData(std::vector<ptr<Vertex_Buffer>> Data);
void setData(std::vector<Vertex_Buffer> Data);
void setData(float *array,uint number_of_vertexes);
void allocateData(uint number_of_vertexes);
void applyData(uint VertexSize, uint size,GLfloat* array,uint datasize);
void applyDynamicData(uint index,uint VertexSize, uint size,GLfloat* array,uint datasize);
void sendData(std::vector<ptr<Vertex_Buffer>> Data,uint index=0);
void sendData(std::vector<Vertex_Buffer> Data,uint index=0);
void sendData(float *array,uint number_of_vertexes,uint index=0);
#ifndef LUCIA_USE_GLES2
void bindInstanced(uint componentNo,uint size,std::string where,uint nth);
void setInstanced(std::vector<ptr<Buffer>> items,float* data,std::string where,uint componentNo,uint size,uint perNThInstance);
void setInstanced(std::vector<ptr<Buffer>> items,std::vector<Vertex_Buffer> data,std::string where,int componentNo,uint perNThInstance);
void addInstanced(float* data,std::string where,uint componentNo,uint size,uint perNthInstance);
void addInstanced(std::vector<Vertex_Buffer> data,std::string where,uint componentNo,uint perNthInstance);
void allocateInstanced(uint number_of_values,uint value_size);
void addInstancedAssisted(int id,int componentNo,int size,int stride,int perNThInstance);
#endif
void setIndices(std::vector<GLint> indicies);
void allocateIndices(uint size);
void sendIndices(GLint* data, uint number,uint index=0);
void setIndices(GLint* data, uint size);
void setSize(uint s);
void attach(bool attachVBO=false);
void render(GLenum mode,uint start,uint lenght);
void render(GLenum mode);
#ifndef LUCIA_USE_GLES2
void renderInstanced(GLenum mode);
void renderInstanced(GLenum mode,uint totalitems);
void renderInstanced(GLenum mode,uint totalitems,uint start,uint lenght);
#endif
void draw(GLenum mode);
void draw(GLenum mode,Shader_Vars *Vars);
void draw(GLenum mode,uint start,uint lenght,Shader_Vars *Vars);
void detach(bool detachVBO=false);
template <typename T>
std::vector<ptr<Vertex_Buffer>> convertToData(const T* f,uint start,int finish=-1)
{
if (finish == -1){start = 0; finish = start;};
uint VertexSize = getShaderVars()->getVertexSize();
std::vector<ptr<Vertex_Buffer>> output;
for (uint i = start; i < (uint)finish;i++)
{
auto buff = std::make_shared<Vertex_Buffer>();
for (uint j=0;j < VertexSize; j++)
{
auto x = VertexSize*i;
auto n = f[x+j];
buff->add(n);
};
output.push_back(buff);
}
return output;
};
template <typename T>
void convertToArray(T* f,GLfloat* data)
{
int no = 0;
for (auto v: *f)
{
data[no]=v;
no++;
};
};
template <typename T>
std::vector<ptr<Vertex_Buffer>> convertToData(T* s){
int siz = s->size();
GLfloat data[siz];
convertToArray(s,data);
return convertToData(data,0,siz/getShaderVars()->getVertexSize());
};
template <typename T>
std::vector<int> converToIndicies(T f,uint start,uint finish)
{
std::vector <int> Data;
for (uint i = start;i < finish;i++){Data.push_back((int)f[i]);};
return Data;
};
template <typename T>
std::vector<int> converToIndicies(std::vector<T>s){return converToIndicies(s,0,s.size());};
void destroy();
//constructors
Buffer(bool genEBO);
Buffer(uint size,bool genEBO=false);
Buffer(std::shared_ptr<Shader_Vars> s);
Buffer(){};
virtual ~Buffer(){destroy();};
};
void printShaderLog( GLuint shader );
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path);
GLuint LoadShaderSource(const char * vertex_source,const char * fragment_source);
}
}
}
#endif // UTILITIES_OPENGL_H
| 42.258621 | 152 | 0.533252 | [
"render",
"vector"
] |
2ee05ee9c39a1e8a656e3f9cd5264b7dc609b64f | 7,402 | h | C | src/chrome/browser/ui/cocoa/status_bubble_mac.h | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/browser/ui/cocoa/status_bubble_mac.h | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-02-02T06:55:08.000Z | 2016-01-20T06:11:59.000Z | chrome/browser/ui/cocoa/status_bubble_mac.h | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_COCOA_STATUS_BUBBLE_MAC_H_
#define CHROME_BROWSER_UI_COCOA_STATUS_BUBBLE_MAC_H_
#include <string>
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
#include "base/compiler_specific.h"
#include "base/memory/weak_ptr.h"
#include "base/string16.h"
#include "chrome/browser/ui/status_bubble.h"
#include "googleurl/src/gurl.h"
class StatusBubbleMacTest;
class StatusBubbleMac : public StatusBubble {
public:
// The various states that a status bubble may be in. Public for delegate
// access (for testing).
enum StatusBubbleState {
kBubbleHidden, // Fully hidden
kBubbleShowingTimer, // Waiting to fade in
kBubbleShowingFadeIn, // In a fade-in transition
kBubbleShown, // Fully visible
kBubbleHidingTimer, // Waiting to fade out
kBubbleHidingFadeOut // In a fade-out transition
};
StatusBubbleMac(NSWindow* parent, id delegate);
virtual ~StatusBubbleMac();
// StatusBubble implementation.
virtual void SetStatus(const string16& status) OVERRIDE;
virtual void SetURL(const GURL& url, const std::string& languages) OVERRIDE;
virtual void Hide() OVERRIDE;
virtual void MouseMoved(const gfx::Point& location,
bool left_content) OVERRIDE;
virtual void UpdateDownloadShelfVisibility(bool visible) OVERRIDE;
// Mac-specific method: Update the size and position of the status bubble to
// match the parent window. Safe to call even when the status bubble does not
// exist.
void UpdateSizeAndPosition();
// Mac-specific method: Change the parent window of the status bubble. Safe to
// call even when the status bubble does not exist.
void SwitchParentWindow(NSWindow* parent);
// Delegate method called when a fade-in or fade-out transition has
// completed. This is public so that it may be visible to the CAAnimation
// delegate, which is an Objective-C object.
void AnimationDidStop(CAAnimation* animation, bool finished);
// Expand the bubble to fit a URL too long for the standard bubble size.
void ExpandBubble();
protected:
// Get the current location of the mouse. Protected so that it can be
// stubbed out for testing.
virtual gfx::Point GetMouseLocation();
private:
friend class StatusBubbleMacTest;
// Setter for state_. Use this instead of writing to state_ directly so
// that state changes can be observed by unit tests.
void SetState(StatusBubbleState state);
// Sets the bubble text for SetStatus and SetURL.
void SetText(const string16& text, bool is_url);
// Construct the window/widget if it does not already exist. (Safe to call if
// it does.)
void Create();
// Attaches the status bubble window to its parent window. Safe to call even
// when already attached.
void Attach();
// Detaches the status bubble window from its parent window.
void Detach();
// Is the status bubble attached to the browser window? It should be attached
// when shown and during any fades, but should be detached when hidden.
bool is_attached() { return [window_ parentWindow] != nil; }
// Begins fading the status bubble window in or out depending on the value
// of |show|. This must be called from the appropriate fade state,
// kBubbleShowingFadeIn or kBubbleHidingFadeOut, or from the appropriate
// fully-shown/hidden state, kBubbleShown or kBubbleHidden. This may be
// called at any point during a fade-in or fade-out; it is even possible to
// reverse a transition before it has completed.
void Fade(bool show);
// One-shot timer operations to manage the delays associated with the
// kBubbleShowingTimer and kBubbleHidingTimer states. StartTimer and
// TimerFired must be called from one of these states. StartTimer may be
// called while the timer is still running; in that case, the timer will be
// reset. CancelTimer may be called from any state.
void StartTimer(int64 time_ms);
void CancelTimer();
void TimerFired();
// Begin the process of showing or hiding the status bubble. These may be
// called from any state, and will take the appropriate action to initiate
// any state changes that may be needed.
void StartShowing();
void StartHiding();
// Cancel the expansion timer.
void CancelExpandTimer();
// Sets the frame of the status bubble window to |window_frame|, adjusting
// for the given mouse position if necessary. Protected for use in tests.
void SetFrameAvoidingMouse(NSRect window_frame, const gfx::Point& mouse_pos);
// The timer factory used for show and hide delay timers.
base::WeakPtrFactory<StatusBubbleMac> timer_factory_;
// The timer factory used for the expansion delay timer.
base::WeakPtrFactory<StatusBubbleMac> expand_timer_factory_;
// Calculate the appropriate frame for the status bubble window. If
// |expanded_width|, use entire width of parent frame.
NSRect CalculateWindowFrame(bool expanded_width);
// Returns the flags to be used to round the corners of the status bubble.
// Before 10.7, windows have square bottom corners, but in 10.7, the bottom
// corners are rounded. This method considers the bubble's placement (as
// proposed in window_frame) relative to its parent window in determining
// which flags to return. This function may choose to round any corner,
// including top corners. Note that there may be other reasons that a
// status bubble's corner may be rounded in addition to those dependent on
// OS version, and flags will be set or unset elsewhere to address these
// concerns.
unsigned long OSDependentCornerFlags(NSRect window_frame);
// The window we attach ourselves to.
NSWindow* parent_; // WEAK
// The object that we query about our vertical offset for positioning.
id delegate_; // WEAK
// The window we own.
NSWindow* window_;
// The status text we want to display when there are no URLs to display.
NSString* status_text_;
// The url we want to display when there is no status text to display.
NSString* url_text_;
// The status bubble's current state. Do not write to this field directly;
// use SetState().
StatusBubbleState state_;
// True if operations are to be performed immediately rather than waiting
// for delays and transitions. Normally false, this should only be set to
// true for testing.
bool immediate_;
// True if the status bubble has been expanded. If the bubble is in the
// expanded state and encounters a new URL, change size immediately,
// with no hover delay.
bool is_expanded_;
// The original, non-elided URL.
GURL url_;
// Needs to be passed to ElideURL if the original URL string is wider than
// the standard bubble width.
std::string languages_;
DISALLOW_COPY_AND_ASSIGN(StatusBubbleMac);
};
// Delegate interface
@interface NSObject(StatusBubbleDelegate)
// Called to query the delegate about the frame StatusBubble should position
// itself in. Frame is returned in the parent window coordinates.
- (NSRect)statusBubbleBaseFrame;
// Called from SetState to notify the delegate of state changes.
- (void)statusBubbleWillEnterState:(StatusBubbleMac::StatusBubbleState)state;
@end
#endif // CHROME_BROWSER_UI_COCOA_STATUS_BUBBLE_MAC_H_
| 38.352332 | 80 | 0.744529 | [
"object"
] |
2ee10ff46877f3ad791e0206fd9a2e6946c56a1b | 1,248 | h | C | _cpp_test/utf8/HexVector.h | judemin/euphony | f954af71696a1e8b7ab5e863f4a0848f5e6fed0b | [
"Apache-2.0"
] | null | null | null | _cpp_test/utf8/HexVector.h | judemin/euphony | f954af71696a1e8b7ab5e863f4a0848f5e6fed0b | [
"Apache-2.0"
] | null | null | null | _cpp_test/utf8/HexVector.h | judemin/euphony | f954af71696a1e8b7ab5e863f4a0848f5e6fed0b | [
"Apache-2.0"
] | null | null | null | #ifndef EUPHONY_HEXVECTOR_H
#define EUPHONY_HEXVECTOR_H
#include <cstdint>
#include <vector>
#include <stdint.h>
#include <string>
namespace Euphony
{
class HexVector
{
public:
HexVector(int size);
HexVector(const HexVector ©);
HexVector(const std::string &hexString);
HexVector(const std::vector<u_int8_t> &hexVectorCopy);
~HexVector();
void pushBack(u_int8_t hexByte);
void popBack();
std::string toString() const;
const std::vector<u_int8_t> &getHexSource() const;
void setHexSource(const std::vector<u_int8_t> &hexSource);
int getSize() const;
void clear();
typedef std::vector<u_int8_t> HexSource;
typedef HexSource::iterator iterator;
typedef const HexSource::const_iterator const_iterator;
const_iterator begin() const;
const_iterator end() const;
// std::__wrap_iter<std::vector<unsigned char, std::allocator<unsigned char>>::const_pointer>
// begin() const;
// std::__wrap_iter<std::vector<unsigned char, std::allocator<unsigned char>>::const_pointer>
// end() const;
private:
HexSource hexSource;
};
}
#endif //EUPHONY_HEXVECTOR_H
| 27.733333 | 101 | 0.648237 | [
"vector"
] |
2ee4c8f21e755fc5e301a5621561a71fe4555451 | 2,020 | h | C | core/LZerD/gh.h | tecdatalab/legacy | 9b5286d3375fff691a80ceb44172549e9a6bdee5 | [
"Apache-2.0"
] | null | null | null | core/LZerD/gh.h | tecdatalab/legacy | 9b5286d3375fff691a80ceb44172549e9a6bdee5 | [
"Apache-2.0"
] | 15 | 2019-06-17T16:13:39.000Z | 2022-02-27T05:23:59.000Z | db/Updater/generators/LZerD/gh.h | tecdatalab/biostructure | a30e907e83fa5bbfb934d951b7c663b622104fcc | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <valarray>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
#include "basis.h"
#include "bvertex.h"
#include "constants.h"
#include "cp.h"
#include "pdb.h"
#include "utils.h"
#include "docksolution.h"
#include <ANN/ANN.h>
typedef valarray<double> Vertex;
/* gh */
void dock(vector<cp>&, vector<atom>&, vector<cp>&,
vector<atom>&, double, double,
double, double, double, int, double, string);
void transform_atoms(Transform, vector<atom>&);
void print_vector(vector<int>&);
void transform_points(Transform, vector<cp>&, vector<cp>&);
/* matrix */
void matrix3_inverse(T3Matrix, T3Matrix);
void matrix_inverse(Transform, Transform, double*);
void matrix_prod(Transform, Transform, Transform);
/* merge */
void merge_cp(vector<vector<cp> >&, vector<cp>&);
/* bipartite */
bool verify_transformation(vector<bvertex>&, vector<bvertex>&, vector<int>&, vector<int>&,
basis&, basis&, vector<vector<double> >&, vector<vector<double> >&,
vector<vector<double> >&, vector<vector<double> >&,
vector<cp>&, vector<cp>&, Transform);
bool verify_alignment(vector<bvertex>&, vector<bvertex>&, vector<int>&, vector<int>&,
basis&, basis&, vector<vector<double> >&, vector<vector<double> >&,
vector<vector<double> >&, vector<vector<double> >&,
vector<cp>&, vector<cp>&, Transform, int);
bool find_point(vector<int>&, int);
/* zd */
void calculate_correlation_values(vector<cp>&, vector<cp>&, vector<vector<double> >&);
void calculate_euclidean_distances(vector<cp>&, vector<cp>&, vector<vector<double> >&);
double zd_correlation(vector<double>&, vector<double>&);
/* score */
double get_excluded_volume(vector<atom>&, vector<atom>&, ANNkd_tree*);
double get_sasa(vector<atom>&, vector<atom>&);
double calculate_sas(vector<atom>&);
void get_score(vector<cp>&, vector<cp>&, vector<vector<double> >&, ANNkd_tree*, double&, double&);
| 28.450704 | 98 | 0.701485 | [
"vector",
"transform"
] |
2ee989695768007638ee0d1869ac5dd1fa865b5e | 33,117 | h | C | Visibility_2/include/CGAL/Rotational_sweep_visibility_2.h | brucerennie/cgal | 314b94aafa9b08a1d086accd2cadff1aae1b57a9 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Visibility_2/include/CGAL/Rotational_sweep_visibility_2.h | brucerennie/cgal | 314b94aafa9b08a1d086accd2cadff1aae1b57a9 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Visibility_2/include/CGAL/Rotational_sweep_visibility_2.h | brucerennie/cgal | 314b94aafa9b08a1d086accd2cadff1aae1b57a9 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z | // Copyright (c) 2013 Technical University Braunschweig (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s): Kan Huang <huangkandiy@gmail.com>
//
#ifndef CGAL_ROTATIONAL_SWEEP_VISIBILITY_2_H
#define CGAL_ROTATIONAL_SWEEP_VISIBILITY_2_H
#include <CGAL/license/Visibility_2.h>
#include <CGAL/Visibility_2/visibility_utils.h>
#include <CGAL/Arrangement_2.h>
#include <CGAL/bounding_box.h>
#include <CGAL/assertions.h>
#include <CGAL/Kernel/global_functions_2.h>
#include <boost/unordered_map.hpp>
#include <iterator>
namespace CGAL {
template<class Arrangement_2_ , class RegularizationCategory = CGAL::Tag_true >
class Rotational_sweep_visibility_2 {
public:
typedef Arrangement_2_ Arrangement_2;
typedef typename Arrangement_2::Traits_2 Traits_2;
typedef typename Arrangement_2::Geometry_traits_2 Geometry_traits_2;
typedef typename Arrangement_2::Vertex_const_handle Vertex_const_handle;
typedef typename Arrangement_2::Vertex_handle Vertex_handle;
typedef typename Arrangement_2::Halfedge_const_handle Halfedge_const_handle;
typedef typename Arrangement_2::Halfedge_handle Halfedge_handle;
typedef typename Arrangement_2::
Ccb_halfedge_const_circulator Ccb_halfedge_const_circulator;
typedef typename Arrangement_2::Face_const_handle Face_const_handle;
typedef typename Arrangement_2::Face_handle Face_handle;
typedef typename Geometry_traits_2::Kernel K;
typedef typename Geometry_traits_2::Point_2 Point_2;
typedef typename Geometry_traits_2::Ray_2 Ray_2;
typedef typename Geometry_traits_2::Segment_2 Segment_2;
typedef typename Geometry_traits_2::Line_2 Line_2;
typedef typename Geometry_traits_2::Vector_2 Vector_2;
typedef typename Geometry_traits_2::Direction_2 Direction_2;
typedef typename Geometry_traits_2::FT Number_type;
typedef typename Geometry_traits_2::Object_2 Object_2;
typedef RegularizationCategory Regularization_category;
typedef CGAL::Tag_true Supports_general_polygon_category;
typedef CGAL::Tag_true Supports_simple_polygon_category;
private:
typedef std::vector<Point_2> Points;
typedef Vertex_const_handle VH;
typedef std::vector<VH> VHs;
typedef Halfedge_const_handle EH;
typedef std::vector<EH> EHs;
class Less_edge: public CGAL::cpp98::binary_function<EH, EH, bool> {
const Geometry_traits_2* geom_traits;
public:
Less_edge() {}
Less_edge(const Geometry_traits_2* traits):geom_traits(traits) {}
bool operator() (const EH e1, const EH e2) const {
if (e1 == e2)
return false;
else {
return &(*e1)<&(*e2);
}
// if (e1->source() == e2->source())
// return Visibility_2::compare_xy_2(geom_traits,
// e1->target()->point(), e2->target()->point()) == SMALLER;
// else
// return Visibility_2::compare_xy_2(geom_traits,
// e1->source()->point(), e2->source()->point()) == SMALLER;
}
};
class Less_vertex: public CGAL::cpp98::binary_function<VH, VH, bool> {
const Geometry_traits_2* geom_traits;
public:
Less_vertex() {}
Less_vertex(const Geometry_traits_2* traits):geom_traits(traits) {}
bool operator() (const VH v1, const VH v2) const {
if (v1 == v2)
return false;
else
// I know this is dirty but it speeds up by 25%. Michael
return &(*v1)<&(*v2);
// return Visibility_2::
// compare_xy_2(geom_traits, v1->point(), v2->point()) == SMALLER;
}
};
class Closer_edge: public CGAL::cpp98::binary_function<EH, EH, bool> {
const Geometry_traits_2* geom_traits;
Point_2 q;
public:
Closer_edge() {}
Closer_edge(const Geometry_traits_2* traits, const Point_2& q) :
geom_traits(traits), q(q) {}
int vtype(const Point_2& c, const Point_2& p) const {
switch(Visibility_2::orientation_2(geom_traits, q, c, p)) {
case COLLINEAR:
if (Visibility_2::less_distance_to_point_2(geom_traits, q, c, p))
return 0;
else
return 3;
case RIGHT_TURN:
return 1;
case LEFT_TURN:
return 2;
default: CGAL_unreachable();
}
return -1;
}
bool operator() (const EH& e1, const EH& e2) const {
if (e1 == e2)
return false;
const Point_2& s1=e1->source()->point(),
t1=e1->target()->point(),
s2=e2->source()->point(),
t2=e2->target()->point();
if (e1->source() == e2->source()) {
int vt1 = vtype(s1, t1),
vt2 = vtype(s1, t2);
if (vt1 != vt2)
return vt1 > vt2;
else
return (Visibility_2::orientation_2(geom_traits, s1, t2, t1)==
Visibility_2::orientation_2(geom_traits, s1, t2, q));
}
if (e1->target() == e2->source()) {
// const Point_2& p1 = s1,
// p2 = t2,
// c = s2;
int vt1 = vtype(t1, s1),
vt2 = vtype(t1, t2);
if (vt1 != vt2)
return vt1 > vt2;
else
return (Visibility_2::orientation_2(geom_traits, s2, t2, s1)==
Visibility_2::orientation_2(geom_traits, s2, t2, q));
}
if (e1->source() == e2->target()) {
// const Point_2& p1 = t1,
// p2 = s2,
// c = s1;
int vt1 = vtype(s1, t1),
vt2 = vtype(s1, s2);
if (vt1 != vt2)
return vt1 > vt2;
else return (Visibility_2::orientation_2(geom_traits, s1, s2, t1)==
Visibility_2::orientation_2(geom_traits, s1, s2, q));
}
if (e1->target() == e2->target()) {
// const Point_2& p1 = s1,
// p2 = s2,
// c = t1;
int vt1 = vtype(t1, s1),
vt2 = vtype(t1, s2);
if (vt1 != vt2)
return vt1 > vt2;
else return (Visibility_2::orientation_2(geom_traits, t1, s2, s1)==
Visibility_2::orientation_2(geom_traits, t1, s2, q));
}
Orientation e1q = Visibility_2::orientation_2(geom_traits, s1, t1, q);
switch (e1q)
{
case COLLINEAR:
if (Visibility_2::collinear(geom_traits, q, s2, t2)) {
//q is collinear with e1 and e2.
return (Visibility_2::less_distance_to_point_2(geom_traits, q, s1, s2)
|| Visibility_2::less_distance_to_point_2(geom_traits, q, t1, t2));
}
else {
//q is collinear with e1 not with e2.
if (Visibility_2::collinear(geom_traits, s2, t2, s1))
return (Visibility_2::orientation_2(geom_traits, s2, t2, q)
== Visibility_2::orientation_2(geom_traits, s2, t2, t1));
else
return (Visibility_2::orientation_2(geom_traits, s2, t2, q)
== Visibility_2::orientation_2(geom_traits, s2, t2, s1));
}
break;
case RIGHT_TURN:
switch (Visibility_2::orientation_2(geom_traits, s1, t1, s2)) {
case COLLINEAR:
return Visibility_2::orientation_2(geom_traits, s1, t1, t2)!=e1q;
case RIGHT_TURN:
if (Visibility_2::orientation_2(geom_traits, s1, t1, t2) == LEFT_TURN)
return Visibility_2::orientation_2(geom_traits, s2, t2, q)
== Visibility_2::orientation_2(geom_traits, s2, t2, s1);
else
return false;
case LEFT_TURN:
if(Visibility_2::orientation_2(geom_traits, s1, t1, t2) == RIGHT_TURN)
return Visibility_2::orientation_2(geom_traits, s2, t2, q)
== Visibility_2::orientation_2(geom_traits, s2, t2, s1);
else
return true;
default: CGAL_unreachable();
}
break;
case LEFT_TURN:
switch (Visibility_2::orientation_2(geom_traits, s1, t1, s2)) {
case COLLINEAR:
return Visibility_2::orientation_2(geom_traits, s1, t1, t2)!=e1q;
case LEFT_TURN:
if(Visibility_2::orientation_2(geom_traits, s1, t1, t2) == RIGHT_TURN)
return Visibility_2::orientation_2(geom_traits, s2, t2, q)
== Visibility_2::orientation_2(geom_traits, s2, t2, s1);
else
return false;
case RIGHT_TURN:
if (Visibility_2::orientation_2(geom_traits, s1, t1, t2) == LEFT_TURN)
return Visibility_2::orientation_2(geom_traits, s2, t2, q)
== Visibility_2::orientation_2(geom_traits, s2, t2, s1);
else
return true;
default: CGAL_unreachable();
}
}
CGAL_unreachable();
return false;
}
};
const Arrangement_2 *p_arr;
const Geometry_traits_2 *geom_traits;
mutable Point_2 q; //query point
mutable Points polygon; //visibility polygon
mutable std::map<VH, EHs, Less_vertex> incident_edges;
mutable std::map<EH, int, Less_edge> edx; //index of active edges in
//the heap
mutable std::set<EH, Closer_edge> active_edges; //a set of edges that
//intersect the current
//vision ray.
mutable VHs vs; //angular sorted vertices
mutable EHs bad_edges; //edges that pass the query point
mutable VH cone_end1; //an end of visibility cone
mutable VH cone_end2; //another end of visibility cone
mutable typename Points::size_type cone_end1_idx;
//index of cone_end1->point() in
//visibility polygon
mutable typename Points::size_type cone_end2_idx;
//index of cone_end2->point() in
//visibility polygon
mutable bool is_vertex_query;
mutable bool is_edge_query;
mutable bool is_face_query;
mutable bool is_big_cone; //whether the angle of
//visibility_cone is greater than pi.
public:
Rotational_sweep_visibility_2(): p_arr(nullptr), geom_traits(nullptr) {}
Rotational_sweep_visibility_2(const Arrangement_2& arr): p_arr(&arr) {
geom_traits = p_arr->geometry_traits();
}
const std::string name() const { return std::string("R_visibility_2"); }
template <typename VARR>
typename VARR::Face_handle
compute_visibility(
const Point_2& q, const Halfedge_const_handle e, VARR& arr_out) const
{
arr_out.clear();
bad_edges.clear();
this->q = q;
if (Visibility_2::compare_xy_2(geom_traits, q, e->target()->point())==EQUAL)
{
is_vertex_query = true;
is_edge_query = false;
is_face_query = false;
cone_end1 = e->source();
cone_end2 = e->next()->target();
is_big_cone = CGAL::right_turn(cone_end1->point(), q, cone_end2->point());
typename Arrangement_2::
Halfedge_around_vertex_const_circulator first, curr;
first = curr = e->target()->incident_halfedges();
do {
if (curr->face() == e->face())
bad_edges.push_back(curr);
else if (curr->twin()->face() == e->face())
bad_edges.push_back(curr->twin());
} while (++curr != first);
}
else {
is_vertex_query = false;
is_edge_query = true;
is_face_query = false;
cone_end1 = e->source();
cone_end2 = e->target();
bad_edges.push_back(e);
is_big_cone = false;
}
visibility_region_impl(e->face(), q);
//decide which inside of the visibility butterfly is needed.
typename Points::size_type small_idx, big_idx;
if ( cone_end1_idx < cone_end2_idx ) {
small_idx = cone_end1_idx;
big_idx = cone_end2_idx;
}
else {
small_idx = cone_end2_idx;
big_idx = cone_end1_idx;
}
typename Points::size_type next_idx = small_idx + 1;
bool is_between;
//indicate whether the shape between small_idx and big_idx is the visibility
//region required.
if (CGAL::right_turn(cone_end1->point(), q, cone_end2->point())) {
is_between = false;
while (next_idx != big_idx) {
if (CGAL::left_turn(cone_end1->point(), q, polygon[next_idx]) ||
CGAL::left_turn(q, cone_end2->point(), polygon[next_idx]))
{
is_between = true;
break;
}
next_idx++;
}
}
else {
is_between = true;
while (next_idx != big_idx) {
if (CGAL::right_turn(cone_end1->point(), q, polygon[next_idx]) ||
CGAL::right_turn(q, cone_end2->point(), polygon[next_idx]))
{
is_between = false;
break;
}
next_idx++;
}
}
typename Points::iterator first = polygon.begin();
std::advance(first, small_idx);
typename Points::iterator last = polygon.begin();
std::advance(last, big_idx);
if (is_between) {
Points polygon_out(first, last+1);
if (is_vertex_query)
polygon_out.push_back(q);
Visibility_2::report_while_handling_needles<Rotational_sweep_visibility_2>
(geom_traits, q, polygon_out, arr_out);
}
else {
Points polygon_out(polygon.begin(), first+1);
if (is_vertex_query) polygon_out.push_back(q);
for (typename Points::size_type i = big_idx; i != polygon.size(); i++) {
polygon_out.push_back(polygon[i]);
}
Visibility_2::report_while_handling_needles<Rotational_sweep_visibility_2>
(geom_traits, q, polygon_out, arr_out);
}
Visibility_2::conditional_regularize(arr_out, Regularization_category());
if (arr_out.faces_begin()->is_unbounded())
return ++arr_out.faces_begin();
else
return arr_out.faces_begin();
}
template <typename VARR>
typename VARR::Face_handle
compute_visibility(
const Point_2& q, const Face_const_handle f, VARR& arr_out) const
{
arr_out.clear();
this->q = q;
is_vertex_query = false;
is_edge_query = false;
is_face_query = true;
visibility_region_impl(f, q);
Visibility_2::report_while_handling_needles<Rotational_sweep_visibility_2>
(geom_traits, q, polygon, arr_out);
Visibility_2::conditional_regularize(arr_out, Regularization_category());
if (arr_out.faces_begin()->is_unbounded())
return ++arr_out.faces_begin();
else
return arr_out.faces_begin();
}
bool is_attached() const {
return (p_arr != nullptr);
}
void attach(const Arrangement_2& arr) {
p_arr = &arr;
geom_traits = p_arr->geometry_traits();
}
void detach() {
p_arr = nullptr;
geom_traits = nullptr;
}
const Arrangement_2& arrangement_2() const {
return *p_arr;
}
private:
//get the neighbor of v along edge e
VH get_neighbor(const EH e, const VH v) const {
if (e->source() == v)
return e->target();
else
return e->source();
}
//check whether ray(q->dp) intersects segment(p1, p2)
bool do_intersect_ray(const Point_2& q,
const Point_2& dp,
const Point_2& p1,
const Point_2& p2) const
{
return (CGAL::orientation(q, dp, p1) != CGAL::orientation(q, dp, p2) &&
CGAL::orientation(q, p1, dp) == CGAL::orientation(q, p1, p2));
}
//arrange vertices that on a same vision ray in a 'funnel' order
void funnel(typename VHs::size_type i, typename VHs::size_type j) const {
VHs right, left;
//whether the edges incident to a vertex block the left side and right side
//of current vision ray.
bool block_left(false), block_right(false);
VH former = vs[i], nb;
for (typename VHs::size_type l=i; l<j; l++) {
bool left_v(false), right_v(false), has_predecessor(false);
EHs& edges = incident_edges[vs[l]];
for (typename EHs::size_type k=0; k<edges.size(); k++) {
nb = get_neighbor(edges[k], vs[l]);
if ( nb == former ) {
has_predecessor = true;
break;
}
if (CGAL::left_turn(q, vs[l]->point(), nb->point()))
left_v = true;
else
right_v = CGAL::right_turn(q, vs[l]->point(), nb->point());
}
if (has_predecessor) {
//if the current vertex connects to the vertex before by an edge,
//the vertex before can help it to block.
block_left = block_left || left_v;
block_right = block_right || right_v;
}
else {
block_left = left_v;
block_right = right_v;
}
if (block_left && block_right) {
//when both sides are blocked,
//there is no need to change the vertex after.
right.push_back(vs[l]);
break;
}
else {
if (block_left)
left.push_back(vs[l]);
else
right.push_back(vs[l]);
}
former = vs[l];
}
for (typename VHs::size_type l=0; l!=right.size(); l++)
vs[i+l] = right[l];
for (typename VHs::size_type l=0; l!=left.size(); l++)
vs[i+l+right.size()] = left[left.size()-1-l];
}
void visibility_region_impl(const Face_const_handle f, const Point_2& q) const
{
vs.clear();
polygon.clear();
active_edges = std::set<EH, Closer_edge>(Closer_edge(geom_traits, q));
incident_edges = std::map<VH, EHs, Less_vertex>(Less_vertex(geom_traits));
edx = std::map<EH, int, Less_edge>(Less_edge(geom_traits));
EHs relevant_edges; //edges that can affect the visibility of query point.
Arrangement_2 bbox;
if (is_face_query)
input_face(f);
else
input_face(f, relevant_edges, bbox);
//the following code is the initiation of vision ray.
//the direction of the initial ray is between the direction from q to last
//vertex in vs and positive x-axis. By choosing this direction, we make sure
//that all plane is swept and there is not needle at the beginning of
//sweeping.
Vector_2 dir;
if (Direction_2(-1, 0) < Direction_2(Vector_2(q, vs.back()->point())))
dir = Vector_2(1, 0) + Vector_2(q, vs.back()->point());
else
dir = Vector_2(0, -1);
Point_2 dp = q + dir;
//initiation of active_edges. for face queries,
//all edges on the boundary can affect visibility.
//for non-face queries, only relevant_edges has to be considered.
if (is_face_query) {
Ccb_halfedge_const_circulator curr = f->outer_ccb();
Ccb_halfedge_const_circulator circ = curr;
do {
if (do_intersect_ray(
q, dp, curr->target()->point(), curr->source()->point()))
active_edges.insert(curr);
} while (++curr != circ);
typename Arrangement_2::Hole_const_iterator hi;
for (hi = f->holes_begin(); hi != f->holes_end(); ++hi) {
Ccb_halfedge_const_circulator curr = circ = *hi;
do {
if (do_intersect_ray(
q, dp, curr->target()->point(), curr->source()->point()))
active_edges.insert(curr);
} while (++curr != circ);
}
}
else {
for (typename EHs::size_type i=0; i!=relevant_edges.size(); i++)
if (do_intersect_ray(q, dp, relevant_edges[i]->source()->point(),
relevant_edges[i]->target()->point()))
active_edges.insert(relevant_edges[i]);
}
//angular sweep begins
// std::cout<<active_edges.size()<<std::endl;
for (typename VHs::size_type i=0; i!=vs.size(); i++) {
VH vh = vs[i];
EH closest_e = *active_edges.begin();
EHs& edges = incident_edges[vh];
EHs insert_ehs, remove_ehs;
for (typename EHs::size_type j=0; j!=edges.size(); j++) {
EH& e = edges[j];
if (active_edges.find(e) == active_edges.end())
insert_ehs.push_back(e);
else
remove_ehs.push_back(e);
}
typename EHs::size_type insert_cnt = insert_ehs.size();
typename EHs::size_type remove_cnt = remove_ehs.size();
if (insert_cnt == 1 && remove_cnt == 1) {
const EH& ctemp_eh = *active_edges.find(remove_ehs.front());
EH& temp_eh = const_cast<EH&>(ctemp_eh);
temp_eh = insert_ehs.front();
}
else {
for (typename EHs::size_type j=0; j!=remove_cnt; j++)
active_edges.erase(remove_ehs[j]);
for (typename EHs::size_type j=0; j!=insert_cnt; j++)
active_edges.insert(insert_ehs[j]);
}
if (closest_e != *active_edges.begin()) {
//when the closest edge changed
if (is_face_query) {
if (remove_cnt > 0 && insert_cnt > 0) {
//some edges are added and some are deleted,
//which means the vertex swept is part of visibility polygon.
update_visibility(vh->point());
}
if (remove_cnt == 0 && insert_cnt > 0) {
//only add some edges, means the view ray is blocked by new edges.
//therefore first add the intersection of view ray and
//former closet edge, then add the vertice swept.
update_visibility(ray_seg_intersection(q,
vh->point(),
closest_e->target()->point(),
closest_e->source()->point())
);
update_visibility(vh->point());
}
if (remove_cnt > 0 && insert_cnt == 0) {
//only delete some edges, means some block is moved and the view ray
//can reach the segments after the block.
update_visibility(vh->point());
update_visibility(
ray_seg_intersection(q,
vh->point(),
(*active_edges.begin())->target()->point(),
(*active_edges.begin())->source()->point()
)
);
}
}
else {
//extra work here for edge/vertex query is the index of cone_end1 and
//cone_end2 will be recorded.
if (remove_cnt > 0 && insert_cnt > 0) {
//some edges are added and some are deleted,
//which means the vertice swept is part of visibility polygon.
if (update_visibility(vh->point())) {
if (vh == cone_end1)
cone_end1_idx = polygon.size()-1;
else if (vh == cone_end2)
cone_end2_idx = polygon.size()-1;
}
}
if (remove_cnt == 0 && insert_cnt > 0) {
//only add some edges, means the view ray is blocked by new edges.
//therefore first add the intersection of view ray and former closet
//edge, then add the vertice swept.
update_visibility(ray_seg_intersection(q,
vh->point(),
closest_e->target()->point(),
closest_e->source()->point())
);
if (update_visibility(vh->point())) {
if (vh == cone_end1)
cone_end1_idx = polygon.size()-1;
else if (vh == cone_end2)
cone_end2_idx = polygon.size()-1;
}
}
if (remove_cnt > 0 && insert_cnt == 0) {
//only delete some edges, means some block is removed and the vision
//ray can reach the segments after the block.
if (update_visibility(vh->point())) {
if (vh == cone_end1)
cone_end1_idx = polygon.size()-1;
else if (vh == cone_end2)
cone_end2_idx = polygon.size()-1;
}
update_visibility(
ray_seg_intersection(q,
vh->point(),
(*active_edges.begin())->target()->point(),
(*active_edges.begin())->source()->point())
);
}
}
}
}
}
void print_edge(const EH e) const {
std::cout << e->source()->point() <<"->"<< e->target()->point() <<std::endl;
}
//compute the intersection of ray(q->dp) and segment(s, t)
//if they are collinear then return the endpoint which is closer to q.
Point_2 ray_seg_intersection(
const Point_2& q, const Point_2& dp, // the ray
const Point_2& s, const Point_2& t) // the segment
const
{
if (CGAL::collinear(q, dp, s)) {
if (CGAL::collinear(q, dp, t)) {
if (CGAL::compare_distance_to_point(q, s, t)==CGAL::SMALLER)
return s;
else
return t;
}
else
return s;
}
Ray_2 ray(q,dp);
Segment_2 seg(s,t);
CGAL::Object result = CGAL::intersection(ray, seg);
return *(CGAL::object_cast<Point_2>(&result));
}
//check if p has been discovered before, if not update the visibility polygon
bool update_visibility(const Point_2& p) const {
if (polygon.empty()) {
polygon.push_back(p);
return true;
}
else if (Visibility_2::compare_xy_2(geom_traits, polygon.back(), p)
!= EQUAL)
{
polygon.push_back(p);
return true;
}
return false;
}
//functor to decide which vertex is swept earlier by the rotational sweeping
//ray
class Is_swept_earlier:public CGAL::cpp98::binary_function<VH, VH, bool> {
const Point_2& q;
const Geometry_traits_2* geom_traits;
public:
Is_swept_earlier(const Point_2& q, const Geometry_traits_2* traits) :
q(q), geom_traits(traits) {}
bool operator() (const VH v1, const VH v2) const {
const Point_2& p1 = v1->point();
const Point_2& p2 = v2->point();
int qua1 = quadrant(q, p1);
int qua2 = quadrant(q, p2);
if (qua1 < qua2)
return true;
if (qua1 > qua2)
return false;
if (collinear(q, p1, p2))
return (CGAL::compare_distance_to_point(q, p1, p2) == CGAL::SMALLER);
else
return CGAL::right_turn(p1, q, p2);
}
//return the quadrant of p with respect to o.
int quadrant(const Point_2& o, const Point_2& p) const {
typename Geometry_traits_2::Compare_x_2 compare_x =
geom_traits->compare_x_2_object();
typename Geometry_traits_2::Compare_y_2 compare_y =
geom_traits->compare_y_2_object();
Comparison_result dx = compare_x(p, o);
Comparison_result dy = compare_y(p, o);
if (dx==LARGER && dy!=SMALLER)
return 1;
if (dx!=LARGER && dy==LARGER)
return 2;
if (dx==SMALLER && dy!=LARGER)
return 3;
if (dx!=SMALLER && dy==SMALLER)
return 4;
return 0;
}
};
//when the query point is in face, every edge is good.
void input_neighbor_f( const Halfedge_const_handle e) const {
VH v = e->target();
if (!incident_edges.count(v))
vs.push_back(v);
incident_edges[v].push_back(e);
incident_edges[v].push_back(e->next());
}
//check if p is in the visibility cone
bool is_in_cone(const Point_2& p) const{
if (is_big_cone)
return (!CGAL::right_turn(cone_end1->point(), q, p)) ||
(!CGAL::left_turn(cone_end2->point(), q, p));
else
return (!CGAL::right_turn(cone_end1->point(), q, p)) &&
(!CGAL::left_turn(cone_end2->point(), q, p));
}
//for vertex and edge query: the visibility is limited in a cone.
void input_edge(const Halfedge_const_handle e,
EHs& good_edges) const {
for (typename EHs::size_type i = 0; i < bad_edges.size(); i++)
if (e == bad_edges[i])
return;
VH v1 = e->target();
VH v2 = e->source();
//an edge will affect visibility only if it has an endpoint in the
//visibility cone or it crosses the boundary of the cone.
if (is_in_cone(v1->point()) || is_in_cone(v2->point()) ||
do_intersect_ray(q, cone_end1->point(), v1->point(), v2->point()))
{
good_edges.push_back(e);
if (!incident_edges.count(v1))
vs.push_back(v1);
incident_edges[v1].push_back(e);
if (!incident_edges.count(v2))
vs.push_back(v2);
incident_edges[v2].push_back(e);
}
}
//for face query: traverse the face to get all edges
//and sort vertices in counter-clockwise order.
void input_face (Face_const_handle fh) const
{
Ccb_halfedge_const_circulator curr = fh->outer_ccb();
Ccb_halfedge_const_circulator circ = curr;
do {
CGAL_assertion(curr->face() == fh);
input_neighbor_f(curr);
} while (++curr != circ);
typename Arrangement_2::Hole_const_iterator hi;
for (hi = fh->holes_begin(); hi != fh->holes_end(); ++hi) {
Ccb_halfedge_const_circulator curr = *hi, circ = *hi;
do {
CGAL_assertion(curr->face() == fh);
input_neighbor_f(curr);
} while (++curr != circ);
}
std::sort(vs.begin(), vs.end(), Is_swept_earlier(q, geom_traits));
for (typename VHs::size_type i=0; i!=vs.size(); i++) {
typename VHs::size_type j = i+1;
while (j != vs.size()) {
if (!CGAL::collinear(q, vs[i]->point(), vs[j]->point()))
break;
j++;
}
if (j-i>1)
funnel(i, j);
i = j-1;
}
}
//for vertex or edge query: traverse the face to get all edges
//and sort vertices in counter-clockwise order.
void input_face (Face_const_handle fh,
EHs& good_edges,
Arrangement_2& bbox) const
{
Ccb_halfedge_const_circulator curr = fh->outer_ccb();
Ccb_halfedge_const_circulator circ = curr;
do {
CGAL_assertion(curr->face() == fh);
input_edge(curr, good_edges);
} while (++curr != circ);
typename Arrangement_2::Hole_const_iterator hi;
for (hi = fh->holes_begin(); hi != fh->holes_end(); ++hi) {
Ccb_halfedge_const_circulator curr = circ = *hi;
do {
CGAL_assertion(curr->face() == fh);
input_edge(curr, good_edges);
} while (++curr != circ);
}
//create a box that cover all vertices such that during the sweeping,
//the vision ray will always intersect at least an edge.
//this box doesn't intersect any relevant_edge.
Points points;
for (typename VHs::size_type i=0; i<vs.size(); i++) {
points.push_back(vs[i]->point());
}
points.push_back(q);
//first get the bounding box of all relevant points.
typename Geometry_traits_2::Iso_rectangle_2 bb =
bounding_box(points.begin(), points.end());
Number_type xmin, xmax, ymin, ymax;
typename Geometry_traits_2::Compute_x_2 compute_x =
geom_traits->compute_x_2_object();
typename Geometry_traits_2::Compute_y_2 compute_y =
geom_traits->compute_y_2_object();
//make the box a little bigger than bb so that it won't intersect any
//relevant_edge.
xmin = compute_x((bb.min)())-1;
ymin = compute_y((bb.min)())-1;
xmax = compute_x((bb.max)())+1;
ymax = compute_y((bb.max)())+1;
Point_2 box[4] = {Point_2(xmin, ymin), Point_2(xmax, ymin),
Point_2(xmax, ymax), Point_2(xmin, ymax)};
Halfedge_handle e1 = bbox.insert_in_face_interior(Segment_2(box[0], box[1]),
bbox.unbounded_face());
Halfedge_handle e2 = bbox.insert_from_left_vertex(Segment_2(box[1], box[2]),
e1->target());
Halfedge_handle e3 = bbox.insert_from_right_vertex(Segment_2(box[2],box[3]),
e2->target());
bbox.insert_at_vertices(Segment_2(box[0], box[3]),
e1->source(), e3->target());
circ = curr = e1->face()->outer_ccb();
do {
VH v = curr->target();
vs.push_back(v);
incident_edges[v].push_back(curr);
incident_edges[v].push_back(curr->next());
good_edges.push_back(curr);
} while(++curr != circ);
std::sort(vs.begin(), vs.end(), Is_swept_earlier(q, geom_traits));
for (typename VHs::size_type i=0; i!=vs.size(); i++) {
typename VHs::size_type j = i+1;
while (j != vs.size()) {
if (!CGAL::collinear(q, vs[i]->point(), vs[j]->point()))
break;
j++;
}
if (j-i>1)
funnel(i, j);
i = j-1;
}
}
};
} // end namespace CGAL
#endif
| 35.34365 | 80 | 0.574116 | [
"object",
"shape",
"vector"
] |
2eedc63d6200feff6e1c86440b8c1e76eeeb007d | 6,327 | h | C | envlogger/converters/xtensor_codec.h | LaudateCorpus1/envlogger | 87a185d35ab8a9fdbac7d4ca30a64aa61dbb8690 | [
"Apache-2.0"
] | null | null | null | envlogger/converters/xtensor_codec.h | LaudateCorpus1/envlogger | 87a185d35ab8a9fdbac7d4ca30a64aa61dbb8690 | [
"Apache-2.0"
] | 1 | 2021-10-05T16:07:37.000Z | 2021-10-05T16:07:37.000Z | envlogger/converters/xtensor_codec.h | LaudateCorpus1/envlogger | 87a185d35ab8a9fdbac7d4ca30a64aa61dbb8690 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 DeepMind Technologies Limited..
//
// 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.
// Functions for manipulating storage.proto:{Datum, Data} objects.
//
// It can produce Datum objects from C++ types using the Encode() method, and
// conversely it can parse Datum objects into C++ types using the Decode()
// method. Besides "scalar" types, this library also supports handling
// xt::xarray objects, which are multidimensional arrays analogous to Python's
// numpy ndarrays.
//
// Please see xtensor_codec_test.cc for usage examples.
//
// Consumers of Decode() may also want to use a library for writing visitors to
// reduce the boilerplate when dealing with the output. Here's one:
// //learning/deepmind/datasets/environment_logger/converters/make_visitor.h
#ifndef THIRD_PARTY_PY_ENVLOGGER_CONVERTERS_XTENSOR_CODEC_H_
#define THIRD_PARTY_PY_ENVLOGGER_CONVERTERS_XTENSOR_CODEC_H_
#include <cstdint>
#include <iterator>
#include <string>
#include <vector>
#include <cstdint>
#include "absl/strings/cord.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include <gmpxx.h>
#include "envlogger/proto/storage.pb.h"
#include "xtensor/xarray.hpp"
namespace envlogger {
// BasicType is the set union of all types that are supported in each Datum.
using BasicType = absl::variant<
float, double, int32_t, int64_t, uint32_t, uint64_t, bool, std::string,
absl::Cord, mpz_class, int8_t, int16_t, uint8_t, uint16_t,
xt::xarray<float>, xt::xarray<double>, xt::xarray<int32_t>,
xt::xarray<int64_t>, xt::xarray<uint32_t>, xt::xarray<uint64_t>,
xt::xarray<bool>, xt::xarray<std::string>, xt::xarray<absl::Cord>,
xt::xarray<mpz_class>, xt::xarray<int8_t>, xt::xarray<int16_t>,
xt::xarray<uint8_t>, xt::xarray<uint16_t>>;
// Encode() transforms a C++ object into a Datum that can be serialized to disk.
// Scalars.
Datum Encode(const float value);
Datum Encode(const double value);
Datum Encode(const int32_t value);
Datum Encode(const int64_t value);
Datum Encode(const uint32_t value);
Datum Encode(const uint64_t value);
Datum Encode(const bool value);
Datum Encode(const std::string& value);
// Define an explicit `const char*` overload to avoid using the `bool` overload.
// Please see: https://godbolt.org/z/Pntp3S
Datum Encode(const char* value);
// We use Cord to represent bytes.
Datum Encode(absl::Cord value);
// GNU gmp's mpz_class is used to represent arbitrary precision ints.
Datum Encode(mpz_class value);
Datum Encode(const int8_t value);
Datum Encode(const int16_t value);
Datum Encode(const uint8_t value);
Datum Encode(const uint16_t value);
// xt::xarrays.
// as_bytes indicates that `value` will be written as a big chunk of big-endian
// floats. This is much faster than individually writing float entries in the
// proto field, but the output is (obviously) not human-readable. This is the
// native format for Numpy's `frombuffer` method.
Datum Encode(const xt::xarray<float>& value, bool as_bytes = true);
Datum Encode(const xt::xarray<double>& value);
Datum Encode(const xt::xarray<int32_t>& value);
Datum Encode(const xt::xarray<int64_t>& value);
Datum Encode(const xt::xarray<uint32_t>& value);
Datum Encode(const xt::xarray<uint64_t>& value);
Datum Encode(const xt::xarray<bool>& value);
Datum Encode(const xt::xarray<std::string>& value);
Datum Encode(const xt::xarray<absl::Cord>& value);
Datum Encode(const xt::xarray<mpz_class>& value);
Datum Encode(const xt::xarray<int8_t>& value);
Datum Encode(const xt::xarray<int16_t>& value);
Datum Encode(const xt::xarray<uint8_t>& value);
Datum Encode(const xt::xarray<uint16_t>& value);
// Decode() parses a Datum proto and maybe returns a BasicType.
absl::optional<BasicType> Decode(const Datum& datum);
// A non-owning view of envlogger::Data.
class DataView {
public:
using value_type = Data;
// An iterator for arrays and tuples.
class const_iterator {
public:
const_iterator(const DataView* view, int index)
: view_(view), index_(index) {}
using iterator_category = std::input_iterator_tag;
using value_type = Data;
using difference_type = ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
bool operator==(const const_iterator& rhs) const;
bool operator!=(const const_iterator& rhs) const;
const const_iterator& operator++();
const Data& operator*() const;
private:
const DataView* view_ = nullptr;
// Current index for iteration.
int index_ = 0;
};
// `data` MUST outlive this DataView instance.
explicit DataView(const Data* data);
// Returns the type that this view holds, VALUE_NOT_SET if nullptr.
Data::ValueCase Type() const;
// Returns the number of elements that this view has.
// Returns 0 if data is nullptr or Type() == Data::kDatum.
size_t size() const;
// Returns whether this view is empty.
bool empty() const;
const Data* data() const;
// Returns the value if this data is an array or tuple.
// Returns nullptr if data is nullptr or index not in [0, size()).
const Data* operator[](int index) const;
// Returns the value if this data is a dict.
// Returns nullptr if the key is not found.
//
// Notice that we take a const string ref instead of a string view to avoid a
// costly conversion in order to lookup the internal proto map.
const Data* operator[](const std::string& key) const;
const_iterator begin() const;
const_iterator end() const;
// Accessor for dictionary contents.
//
// Also supports iteration like:
// for (const auto [key, value] : my_view.items()) {
// ...
// }
const google::protobuf::Map<std::string, Data>& items() const;
private:
const Data* data_ = nullptr;
};
} // namespace envlogger
#endif // THIRD_PARTY_PY_ENVLOGGER_CONVERTERS_XTENSOR_CODEC_H_
| 36.154286 | 80 | 0.72973 | [
"object",
"vector"
] |
2ef07af6ed0ecef3051c263d1877ae1732a6137c | 29,971 | h | C | src/util/lp/mps_reader.h | katelaan/z3 | b6c56e71858bf5afb8e1c025d5437b0c5d9a71d4 | [
"MIT"
] | 1 | 2022-02-17T06:24:20.000Z | 2022-02-17T06:24:20.000Z | z3-4.8.4/src/util/lp/mps_reader.h | horn-ice/sorcar | ce192c37f839cc1c35a0f3655e308b08fb87c4c4 | [
"MIT"
] | 6 | 2018-01-29T18:13:30.000Z | 2019-03-01T23:03:44.000Z | z3-4.8.4/src/util/lp/mps_reader.h | horn-ice/sorcar | ce192c37f839cc1c35a0f3655e308b08fb87c4c4 | [
"MIT"
] | 2 | 2018-08-11T00:27:10.000Z | 2019-01-25T23:21:36.000Z | /*++
Copyright (c) 2017 Microsoft Corporation
Module Name:
<name>
Abstract:
<abstract>
Author:
Lev Nachmanson (levnach)
Revision History:
--*/
#pragma once
// reads an MPS file reperesenting a Mixed Integer Program
#include <functional>
#include <algorithm>
#include <string>
#include "util/vector.h"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <locale>
#include "util/lp/lp_primal_simplex.h"
#include "util/lp/lp_dual_simplex.h"
#include "util/lp/lar_solver.h"
#include "util/lp/lp_utils.h"
#include "util/lp/lp_solver.h"
namespace lp {
inline bool my_white_space(const char & a) {
return a == ' ' || a == '\t';
}
inline size_t number_of_whites(const std::string & s) {
size_t i = 0;
for(;i < s.size(); i++)
if (!my_white_space(s[i])) return i;
return i;
}
inline size_t number_of_whites_from_end(const std::string & s) {
size_t ret = 0;
for(int i = static_cast<int>(s.size()) - 1;i >= 0; i--)
if (my_white_space(s[i])) ret++;else break;
return ret;
}
// trim from start
inline std::string <rim(std::string &s) {
s.erase(0, number_of_whites(s));
return s;
}
// trim from end
inline std::string &rtrim(std::string &s) {
// s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
s.erase(s.end() - number_of_whites_from_end(s), s.end());
return s;
}
// trim from both ends
inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
inline std::string trim(std::string const &r) {
std::string s = r;
return ltrim(rtrim(s));
}
inline vector<std::string> string_split(const std::string &source, const char *delimiter, bool keep_empty) {
vector<std::string> results;
size_t prev = 0;
size_t next = 0;
while ((next = source.find_first_of(delimiter, prev)) != std::string::npos) {
if (keep_empty || (next - prev != 0)) {
results.push_back(source.substr(prev, next - prev));
}
prev = next + 1;
}
if (prev < source.size()) {
results.push_back(source.substr(prev));
}
return results;
}
inline vector<std::string> split_and_trim(const std::string &line) {
auto split = string_split(line, " \t", false);
vector<std::string> ret;
for (auto s : split) {
ret.push_back(trim(s));
}
return ret;
}
template <typename T, typename X>
class mps_reader {
enum row_type { Cost, Less_or_equal, Greater_or_equal, Equal };
struct bound {
T m_low;
T m_upper;
bool m_low_is_set;
bool m_upper_is_set;
bool m_value_is_fixed;
T m_fixed_value;
bool m_free;
// constructor
bound() : m_low(numeric_traits<T>::zero()),
m_low_is_set(true),
m_upper_is_set(false),
m_value_is_fixed(false),
m_free(false) {} // it seems all mps files I have seen have the default low value 0 on a variable
};
struct column {
std::string m_name;
bound * m_bound;
unsigned m_index;
column(const std::string &name, unsigned index): m_name(name),
m_bound(nullptr),
m_index(index) {
}
};
struct row {
row_type m_type;
std::string m_name;
std::unordered_map<std::string, T> m_row_columns;
unsigned m_index;
T m_right_side;
T m_range;
row(row_type type, const std::string &name, unsigned index) :
m_type(type),
m_name(name),
m_index(index),
m_right_side(zero_of_type<T>()),
m_range(zero_of_type<T>())
{
}
};
bool m_is_OK;
std::string m_file_name;
std::unordered_map<std::string, row *> m_rows;
std::unordered_map<std::string, column *> m_columns;
std::unordered_map<std::string, unsigned> m_names_to_var_index;
std::string m_line;
std::string m_name;
std::string m_cost_row_name;
std::ifstream m_file_stream;
// needed to adjust the index row
unsigned m_cost_line_count;
unsigned m_line_number;
std::ostream * m_message_stream;
void set_m_ok_to_false() {
*m_message_stream << "setting m_is_OK to false" << std::endl;
m_is_OK = false;
}
std::string get_string_from_position(unsigned offset) {
unsigned i = offset;
for (; i < m_line.size(); i++){
if (m_line[i] == ' ')
break;
}
lp_assert(m_line.size() >= offset);
lp_assert(m_line.size() >> i);
lp_assert(i >= offset);
return m_line.substr(offset, i - offset);
}
void set_boundary_for_column(unsigned col, bound * b, lp_solver<T, X> * solver){
if (b == nullptr) {
solver->set_lower_bound(col, numeric_traits<T>::zero());
return;
}
if (b->m_free) {
return;
}
if (b->m_low_is_set) {
solver->set_lower_bound(col, b->m_low);
}
if (b->m_upper_is_set) {
solver->set_upper_bound(col, b->m_upper);
}
if (b->m_value_is_fixed) {
solver->set_fixed_value(col, b->m_fixed_value);
}
}
bool all_white_space() {
for (unsigned i = 0; i < m_line.size(); i++) {
char c = m_line[i];
if (c != ' ' && c != '\t') {
return false;
}
}
return true;
}
void read_line() {
while (m_is_OK) {
if (!getline(m_file_stream, m_line)) {
m_line_number++;
set_m_ok_to_false();
*m_message_stream << "cannot read from file" << std::endl;
}
m_line_number++;
if (!m_line.empty() && m_line[0] != '*' && !all_white_space())
break;
}
}
void read_name() {
do {
read_line();
if (m_line.find("NAME") != 0) {
continue;
}
m_line = m_line.substr(4);
m_name = trim(m_line);
break;
} while (m_is_OK);
}
void read_rows() {
// look for start of the rows
read_line();
do {
if (static_cast<int>(m_line.find("ROWS")) >= 0) {
break;
}
} while (m_is_OK);
do {
read_line();
if (m_line.find("COLUMNS") == 0) {
break;
}
add_row();
} while (m_is_OK);
}
void read_column_by_columns(const std::string & column_name, std::string column_data) {
// uph, let us try to work with columns
if (column_data.size() >= 22) {
std::string ss = column_data.substr(0, 8);
std::string row_name = trim(ss);
auto t = m_rows.find(row_name);
if (t == m_rows.end()) {
*m_message_stream << "cannot find " << row_name << std::endl;
goto fail;
} else {
row * row = t->second;
row->m_row_columns[column_name] = numeric_traits<T>::from_string(column_data.substr(8));
if (column_data.size() > 24) {
column_data = column_data.substr(25);
if (column_data.size() >= 22) {
read_column_by_columns(column_name, column_data);
}
}
}
} else {
fail:
set_m_ok_to_false();
*m_message_stream << "cannot understand this line" << std::endl;
*m_message_stream << "line = " << m_line << ", line number is " << m_line_number << std::endl;
return;
}
}
void read_column(const std::string & column_name, const std::string & column_data){
auto tokens = split_and_trim(column_data);
for (unsigned i = 0; i < tokens.size() - 1; i+= 2) {
auto row_name = tokens[i];
if (row_name == "'MARKER'") return; // it is the integrality marker, no real data here
auto t = m_rows.find(row_name);
if (t == m_rows.end()) {
read_column_by_columns(column_name, column_data);
return;
}
row *r = t->second;
r->m_row_columns[column_name] = numeric_traits<T>::from_string(tokens[i + 1]);
}
}
void read_columns(){
std::string column_name;
do {
read_line();
if (m_line.find("RHS") == 0) {
break;
}
if (m_line.size() < 22) {
(*m_message_stream) << "line is too short for a column" << std::endl;
(*m_message_stream) << m_line << std::endl;
(*m_message_stream) << "line number is " << m_line_number << std::endl;
set_m_ok_to_false();
return;
}
std::string column_name_tmp = trim(m_line.substr(4, 8));
if (!column_name_tmp.empty()) {
column_name = column_name_tmp;
}
auto col_it = m_columns.find(column_name);
mps_reader::column * col;
if (col_it == m_columns.end()) {
col = new mps_reader::column(column_name, static_cast<unsigned>(m_columns.size()));
m_columns[column_name] = col;
// (*m_message_stream) << column_name << '[' << col->m_index << ']'<< std::endl;
} else {
col = col_it->second;
}
read_column(column_name, m_line.substr(14));
} while (m_is_OK);
}
void read_rhs() {
do {
read_line();
if (m_line.find("BOUNDS") == 0 || m_line.find("ENDATA") == 0 || m_line.find("RANGES") == 0) {
break;
}
fill_rhs();
} while (m_is_OK);
}
void fill_rhs_by_columns(std::string rhsides) {
// uph, let us try to work with columns
if (rhsides.size() >= 22) {
std::string ss = rhsides.substr(0, 8);
std::string row_name = trim(ss);
auto t = m_rows.find(row_name);
if (t == m_rows.end()) {
(*m_message_stream) << "cannot find " << row_name << std::endl;
goto fail;
} else {
row * row = t->second;
row->m_right_side = numeric_traits<T>::from_string(rhsides.substr(8));
if (rhsides.size() > 24) {
rhsides = rhsides.substr(25);
if (rhsides.size() >= 22) {
fill_rhs_by_columns(rhsides);
}
}
}
} else {
fail:
set_m_ok_to_false();
(*m_message_stream) << "cannot understand this line" << std::endl;
(*m_message_stream) << "line = " << m_line << ", line number is " << m_line_number << std::endl;
return;
}
}
void fill_rhs() {
if (m_line.size() < 14) {
(*m_message_stream) << "line is too short" << std::endl;
(*m_message_stream) << m_line << std::endl;
(*m_message_stream) << "line number is " << m_line_number << std::endl;
set_m_ok_to_false();
return;
}
std::string rhsides = m_line.substr(14);
vector<std::string> splitted_line = split_and_trim(rhsides);
for (unsigned i = 0; i < splitted_line.size() - 1; i += 2) {
auto t = m_rows.find(splitted_line[i]);
if (t == m_rows.end()) {
fill_rhs_by_columns(rhsides);
return;
}
row * row = t->second;
row->m_right_side = numeric_traits<T>::from_string(splitted_line[i + 1]);
}
}
void read_bounds() {
if (m_line.find("BOUNDS") != 0) {
return;
}
do {
read_line();
if (m_line[0] != ' ') {
break;
}
create_or_update_bound();
} while (m_is_OK);
}
void read_ranges() {
if (m_line.find("RANGES") != 0) {
return;
}
do {
read_line();
auto sl = split_and_trim(m_line);
if (sl.size() < 2) {
break;
}
read_range(sl);
} while (m_is_OK);
}
void read_bound_by_columns(const std::string & colstr) {
if (colstr.size() < 14) {
(*m_message_stream) << "line is too short" << std::endl;
(*m_message_stream) << m_line << std::endl;
(*m_message_stream) << "line number is " << m_line_number << std::endl;
set_m_ok_to_false();
return;
}
// uph, let us try to work with columns
if (colstr.size() >= 22) {
std::string ss = colstr.substr(0, 8);
std::string column_name = trim(ss);
auto t = m_columns.find(column_name);
if (t == m_columns.end()) {
(*m_message_stream) << "cannot find " << column_name << std::endl;
goto fail;
} else {
vector<std::string> bound_string;
bound_string.push_back(column_name);
if (colstr.size() > 14) {
bound_string.push_back(colstr.substr(14));
}
mps_reader::column * col = t->second;
bound * b = col->m_bound;
if (b == nullptr) {
col->m_bound = b = new bound();
}
update_bound(b, bound_string);
}
} else {
fail:
set_m_ok_to_false();
(*m_message_stream) << "cannot understand this line" << std::endl;
(*m_message_stream) << "line = " << m_line << ", line number is " << m_line_number << std::endl;
return;
}
}
void update_bound(bound * b, vector<std::string> bound_string) {
/*
UP means an upper bound is applied to the variable. A bound of type LO means a lower bound is applied. A bound type of FX ("fixed") means that the variable has upper and lower bounds equal to a single value. A bound type of FR ("free") means the variable has neither lower nor upper bounds and so can take on negative values. A variation on that is MI for free negative, giving an upper bound of 0 but no lower bound. Bound type PL is for a free positive for zero to plus infinity, but as this is the normal default, it is seldom used. There are also bound types for use in MIP models - BV for binary, being 0 or 1. UI for upper integer and LI for lower integer. SC stands for semi-continuous and indicates that the variable may be zero, but if not must be equal to at least the value given.
*/
std::string bound_type = get_string_from_position(1);
if (bound_type == "BV") {
b->m_upper_is_set = true;
b->m_upper = 1;
return;
}
if (bound_type == "UP" || bound_type == "UI" || bound_type == "LIMITMAX") {
if (bound_string.size() <= 1){
set_m_ok_to_false();
return;
}
b->m_upper_is_set = true;
b->m_upper= numeric_traits<T>::from_string(bound_string[1]);
} else if (bound_type == "LO" || bound_type == "LI") {
if (bound_string.size() <= 1){
set_m_ok_to_false();
return;
}
b->m_low_is_set = true;
b->m_low = numeric_traits<T>::from_string(bound_string[1]);
} else if (bound_type == "FR") {
b->m_free = true;
} else if (bound_type == "FX") {
if (bound_string.size() <= 1){
set_m_ok_to_false();
return;
}
b->m_value_is_fixed = true;
b->m_fixed_value = numeric_traits<T>::from_string(bound_string[1]);
} else if (bound_type == "PL") {
b->m_low_is_set = true;
b->m_low = 0;
} else if (bound_type == "MI") {
b->m_upper_is_set = true;
b->m_upper = 0;
} else {
(*m_message_stream) << "unexpected bound type " << bound_type << " at line " << m_line_number << std::endl;
set_m_ok_to_false();
throw;
}
}
void create_or_update_bound() {
const unsigned name_offset = 14;
lp_assert(m_line.size() >= 14);
vector<std::string> bound_string = split_and_trim(m_line.substr(name_offset, m_line.size()));
if (bound_string.empty()) {
set_m_ok_to_false();
(*m_message_stream) << "error at line " << m_line_number << std::endl;
throw m_line;
}
std::string name = bound_string[0];
auto it = m_columns.find(name);
if (it == m_columns.end()){
read_bound_by_columns(m_line.substr(14));
return;
}
mps_reader::column * col = it->second;
bound * b = col->m_bound;
if (b == nullptr) {
col->m_bound = b = new bound();
}
update_bound(b, bound_string);
}
void read_range_by_columns(std::string rhsides) {
if (m_line.size() < 14) {
(*m_message_stream) << "line is too short" << std::endl;
(*m_message_stream) << m_line << std::endl;
(*m_message_stream) << "line number is " << m_line_number << std::endl;
set_m_ok_to_false();
return;
}
// uph, let us try to work with columns
if (rhsides.size() >= 22) {
std::string ss = rhsides.substr(0, 8);
std::string row_name = trim(ss);
auto t = m_rows.find(row_name);
if (t == m_rows.end()) {
(*m_message_stream) << "cannot find " << row_name << std::endl;
goto fail;
} else {
row * row = t->second;
row->m_range = numeric_traits<T>::from_string(rhsides.substr(8));
maybe_modify_current_row_and_add_row_for_range(row);
if (rhsides.size() > 24) {
rhsides = rhsides.substr(25);
if (rhsides.size() >= 22) {
read_range_by_columns(rhsides);
}
}
}
} else {
fail:
set_m_ok_to_false();
(*m_message_stream) << "cannot understand this line" << std::endl;
(*m_message_stream) << "line = " << m_line << ", line number is " << m_line_number << std::endl;
return;
}
}
void read_range(vector<std::string> & splitted_line){
for (unsigned i = 1; i < splitted_line.size() - 1; i += 2) {
auto it = m_rows.find(splitted_line[i]);
if (it == m_rows.end()) {
read_range_by_columns(m_line.substr(14));
return;
}
row * row = it->second;
row->m_range = numeric_traits<T>::from_string(splitted_line[i + 1]);
maybe_modify_current_row_and_add_row_for_range(row);
}
}
void maybe_modify_current_row_and_add_row_for_range(row * row_with_range) {
unsigned index= static_cast<unsigned>(m_rows.size() - m_cost_line_count);
std::string row_name = row_with_range->m_name + "_range";
row * other_bound_range_row;
switch (row_with_range->m_type) {
case row_type::Greater_or_equal:
m_rows[row_name] = other_bound_range_row = new row(row_type::Less_or_equal, row_name, index);
other_bound_range_row->m_right_side = row_with_range->m_right_side + abs(row_with_range->m_range);
break;
case row_type::Less_or_equal:
m_rows[row_name] = other_bound_range_row = new row(row_type::Greater_or_equal, row_name, index);
other_bound_range_row->m_right_side = row_with_range->m_right_side - abs(row_with_range->m_range);
break;
case row_type::Equal:
if (row_with_range->m_range > 0) {
row_with_range->m_type = row_type::Greater_or_equal; // the existing row type change
m_rows[row_name] = other_bound_range_row = new row(row_type::Less_or_equal, row_name, index);
} else { // row->m_range < 0;
row_with_range->m_type = row_type::Less_or_equal; // the existing row type change
m_rows[row_name] = other_bound_range_row = new row(row_type::Greater_or_equal, row_name, index);
}
other_bound_range_row->m_right_side = row_with_range->m_right_side + row_with_range->m_range;
break;
default:
(*m_message_stream) << "unexpected bound type " << row_with_range->m_type << " at line " << m_line_number << std::endl;
set_m_ok_to_false();
throw;
}
for (auto s : row_with_range->m_row_columns) {
lp_assert(m_columns.find(s.first) != m_columns.end());
other_bound_range_row->m_row_columns[s.first] = s.second;
}
}
void add_row() {
if (m_line.length() < 2) {
return;
}
m_line = trim(m_line);
char c = m_line[0];
m_line = m_line.substr(1);
m_line = trim(m_line);
add_row(c);
}
void add_row(char c) {
unsigned index= static_cast<unsigned>(m_rows.size() - m_cost_line_count);
switch (c) {
case 'E':
m_rows[m_line] = new row(row_type::Equal, m_line, index);
break;
case 'L':
m_rows[m_line] = new row(row_type::Less_or_equal, m_line, index);
break;
case 'G':
m_rows[m_line] = new row(row_type::Greater_or_equal, m_line, index);
break;
case 'N':
m_rows[m_line] = new row(row_type::Cost, m_line, index);
m_cost_row_name = m_line;
m_cost_line_count++;
break;
}
}
unsigned range_count() {
unsigned ret = 0;
for (auto s : m_rows) {
if (s.second->m_range != 0) {
ret++;
}
}
return ret;
}
/*
If rhs is a constraint's right-hand-side value and range is the constraint's range value, then the range interval is defined according to the following table:
sense interval
G [rhs, rhs + |range|]
L [rhs - |range|, rhs]
E [rhs, rhs + |range|] if range > 0,
[rhs - |range|, rhs] if range < 0
where |range| is range's absolute value.
*/
lp_relation get_relation_from_row(row_type rt) {
switch (rt) {
case mps_reader::Less_or_equal: return lp_relation::Less_or_equal;
case mps_reader::Greater_or_equal: return lp_relation::Greater_or_equal;
case mps_reader::Equal: return lp_relation::Equal;
default:
(*m_message_stream) << "Unexpected rt " << rt << std::endl;
set_m_ok_to_false();
throw;
}
}
unsigned solver_row_count() {
return m_rows.size() - m_cost_line_count + range_count();
}
void fill_solver_on_row(row * row, lp_solver<T, X> *solver) {
if (row->m_name != m_cost_row_name) {
solver->add_constraint(get_relation_from_row(row->m_type), row->m_right_side, row->m_index);
for (auto s : row->m_row_columns) {
lp_assert(m_columns.find(s.first) != m_columns.end());
solver->set_row_column_coefficient(row->m_index, m_columns[s.first]->m_index, s.second);
}
} else {
set_solver_cost(row, solver);
}
}
T abs(T & t) { return t < numeric_traits<T>::zero() ? -t: t; }
void fill_solver_on_rows(lp_solver<T, X> * solver) {
for (auto row_it : m_rows) {
fill_solver_on_row(row_it.second, solver);
}
}
void fill_solver_on_columns(lp_solver<T, X> * solver){
for (auto s : m_columns) {
mps_reader::column * col = s.second;
unsigned index = col->m_index;
set_boundary_for_column(index, col->m_bound, solver);
// optional call
solver->give_symbolic_name_to_column(col->m_name, col->m_index);
}
}
void fill_solver(lp_solver<T, X> *solver) {
fill_solver_on_rows(solver);
fill_solver_on_columns(solver);
}
void set_solver_cost(row * row, lp_solver<T, X> *solver) {
for (auto s : row->m_row_columns) {
std::string name = s.first;
lp_assert(m_columns.find(name) != m_columns.end());
mps_reader::column * col = m_columns[name];
solver->set_cost_for_column(col->m_index, s.second);
}
}
public:
void set_message_stream(std::ostream * o) {
lp_assert(o != nullptr);
m_message_stream = o;
}
vector<std::string> column_names() {
vector<std::string> v;
for (auto s : m_columns) {
v.push_back(s.first);
}
return v;
}
~mps_reader() {
for (auto s : m_rows) {
delete s.second;
}
for (auto s : m_columns) {
auto col = s.second;
auto b = col->m_bound;
if (b != nullptr) {
delete b;
}
delete col;
}
}
mps_reader(const std::string & file_name):
m_is_OK(true),
m_file_name(file_name),
m_file_stream(file_name),
m_cost_line_count(0),
m_line_number(0),
m_message_stream(& std::cout) {}
void read() {
if (!m_file_stream.is_open()){
set_m_ok_to_false();
return;
}
read_name();
read_rows();
read_columns();
read_rhs();
if (m_line.find("BOUNDS") == 0) {
read_bounds();
read_ranges();
} else if (m_line.find("RANGES") == 0) {
read_ranges();
read_bounds();
}
}
bool is_ok() {
return m_is_OK;
}
lp_solver<T, X> * create_solver(bool dual) {
lp_solver<T, X> * solver = dual? (lp_solver<T, X>*)new lp_dual_simplex<T, X>() : new lp_primal_simplex<T, X>();
fill_solver(solver);
return solver;
}
lconstraint_kind get_lar_relation_from_row(row_type rt) {
switch (rt) {
case Less_or_equal: return LE;
case Greater_or_equal: return GE;
case Equal: return EQ;
default:
(*m_message_stream) << "Unexpected rt " << rt << std::endl;
set_m_ok_to_false();
throw;
}
}
unsigned get_var_index(std::string s) {
auto it = m_names_to_var_index.find(s);
if (it != m_names_to_var_index.end())
return it->second;
unsigned ret = static_cast<unsigned>(m_names_to_var_index.size());
m_names_to_var_index[s] = ret;
return ret;
}
void fill_lar_solver_on_row(row * row, lar_solver *solver) {
if (row->m_name != m_cost_row_name) {
auto kind = get_lar_relation_from_row(row->m_type);
vector<std::pair<mpq, var_index>> ls;
for (auto s : row->m_row_columns) {
var_index i = solver->add_var(get_var_index(s.first), false);
ls.push_back(std::make_pair(s.second, i));
}
solver->add_constraint(ls, kind, row->m_right_side);
} else {
// ignore the cost row
}
}
void fill_lar_solver_on_rows(lar_solver * solver) {
for (auto row_it : m_rows) {
fill_lar_solver_on_row(row_it.second, solver);
}
}
void create_low_constraint_for_var(column* col, bound * b, lar_solver *solver) {
vector<std::pair<mpq, var_index>> ls;
var_index i = solver->add_var(col->m_index, false);
ls.push_back(std::make_pair(numeric_traits<T>::one(), i));
solver->add_constraint(ls, GE, b->m_low);
}
void create_upper_constraint_for_var(column* col, bound * b, lar_solver *solver) {
var_index i = solver->add_var(col->m_index, false);
vector<std::pair<mpq, var_index>> ls;
ls.push_back(std::make_pair(numeric_traits<T>::one(), i));
solver->add_constraint(ls, LE, b->m_upper);
}
void create_equality_contraint_for_var(column* col, bound * b, lar_solver *solver) {
var_index i = solver->add_var(col->m_index, false);
vector<std::pair<mpq, var_index>> ls;
ls.push_back(std::make_pair(numeric_traits<T>::one(), i));
solver->add_constraint(ls, EQ, b->m_fixed_value);
}
void fill_lar_solver_on_columns(lar_solver * solver) {
for (auto s : m_columns) {
mps_reader::column * col = s.second;
solver->add_var(col->m_index, false);
auto b = col->m_bound;
if (b == nullptr) return;
if (b->m_free) continue;
if (b->m_low_is_set) {
create_low_constraint_for_var(col, b, solver);
}
if (b->m_upper_is_set) {
create_upper_constraint_for_var(col, b, solver);
}
if (b->m_value_is_fixed) {
create_equality_contraint_for_var(col, b, solver);
}
}
}
void fill_lar_solver(lar_solver * solver) {
fill_lar_solver_on_columns(solver);
fill_lar_solver_on_rows(solver);
}
lar_solver * create_lar_solver() {
lar_solver * solver = new lar_solver();
fill_lar_solver(solver);
return solver;
}
};
}
| 33.375278 | 801 | 0.530646 | [
"vector"
] |
2ef1ccafd781cdbf8ebba8711b48238a047178b6 | 6,681 | h | C | net/config/netcfg/wlbscfg/wlbscfg.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/config/netcfg/wlbscfg/wlbscfg.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/config/netcfg/wlbscfg/wlbscfg.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright(c) 1998,99 Microsoft Corporation
Module Name:
wlbscfg.h
Abstract:
Windows Load Balancing Service (WLBS)
Notifier object - Provide the functionality of notifier object
Author:
fengsun
--*/
#pragma once
#include <netcfgx.h>
#include "wlbsparm.h"
#define WLBS_MAX_PASSWORD 16
struct NETCFG_WLBS_PORT_RULE {
TCHAR virtual_ip_addr [CVY_MAX_CL_IP_ADDR + 1]; // Virtual IP Address
DWORD start_port; // Starting port number.
DWORD end_port; // Ending port number.
DWORD mode; // Filtering mode. WLBS_PORT_RULE_XXXX
DWORD protocol; // WLBS_TCP, WLBS_UDP or WLBS_TCP_UDP
union {
struct {
DWORD priority; // Mastership priority: 1..32 or 0 for not-specified.
} single; // Data for single server mode.
struct {
WORD equal_load; // TRUE - Even load distribution.
WORD affinity; // WLBS_AFFINITY_XXX
DWORD load; // Percentage of load to handle locally 0..100.
} multi; // Data for multi-server mode.
} mode_data; // Data for appropriate port group mode.
};
/* This is not visible from the UI, but we need it
to correct some bad configuration on binding. */
struct NETCFG_WLBS_BDA_TEAMING {
WCHAR team_id[CVY_MAX_BDA_TEAM_ID + 1]; /* The team ID - MUST be a GUID. */
ULONG active; /* On write, this flag determines whether to create BDATeaming key - BDA on/off switch. */
ULONG master; /* Boolean indication of master status. */
ULONG reverse_hash; /* Sets direction of hashing - forward (normal) or reverse. */
};
struct NETCFG_WLBS_CONFIG {
DWORD dwHostPriority; // Host priority ID.
DWORD dwPersistedStates; // The states that will be persisted across reboot.
DWORD dwInitialState; // The states that will be persisted across reboot.
bool fRctEnabled; // TRUE - remote control enabled.
bool fMcastSupport; // TRUE - multicast mode, FALSE - unicast mode.
bool fIGMPSupport; // TRUE - IGMP enabled.
bool fIpToMCastIp; // TRUE - derive multicast IP from cluster IP.
WCHAR szMCastIpAddress[CVY_MAX_CL_IP_ADDR + 1]; // The multicast IP address, if user-specified.
TCHAR cl_mac_addr[CVY_MAX_NETWORK_ADDR + 1]; // Cluster MAC address.
TCHAR cl_ip_addr[CVY_MAX_CL_IP_ADDR + 1]; // Cluster IP address.
TCHAR cl_net_mask[CVY_MAX_CL_NET_MASK + 1]; // Netmask for cluster IP.
TCHAR ded_ip_addr[CVY_MAX_DED_IP_ADDR + 1]; // Dedicated IP address or "" for none.
TCHAR ded_net_mask[CVY_MAX_DED_NET_MASK + 1]; // Netmask for dedicated IP address or "" for none.
TCHAR domain_name[CVY_MAX_DOMAIN_NAME + 1]; // Full Qualified Domain Name of the cluster.
bool fChangePassword; // Whether to change password, valid for SetAdapterConfig only.
TCHAR szPassword[CVY_MAX_RCT_CODE + 1]; // Remote control password, valid for SetAdapterConfig only.
bool fConvertMac; // Whether the mac address is generated from IP.
DWORD dwMaxHosts; // Maximum # hosts allowed.
DWORD dwMaxRules; // Maximum # port group rules allowed.
DWORD dwNumRules; // # active port group rules
NETCFG_WLBS_BDA_TEAMING bda_teaming; /* The BDA teaming config, which is NOT visible in the UI. */
NETCFG_WLBS_PORT_RULE port_rules[CVY_MAX_RULES]; // Port rules
};
class CNetcfgCluster;
struct WlbsApiFuncs;
//+----------------------------------------------------------------------------
//
// class CWlbsConfig
//
// Description: Provide the functionality for the notifier object.
// It would be used by TCPIP notifier if WLBS UI merged with TCPIP
//
// History: fengsun Created Header 2/11/00
//
//+----------------------------------------------------------------------------
class CWlbsConfig
{
public:
CWlbsConfig(VOID);
~CWlbsConfig(VOID);
STDMETHOD (Initialize) (IN INetCfg* pINetCfg, IN BOOL fInstalling);
STDMETHOD (ReadAnswerFile) (PCWSTR szAnswerFile, PCWSTR szAnswerSections);
STDMETHOD (Upgrade) (DWORD, DWORD);
STDMETHOD (Install) (DWORD);
STDMETHOD (Removing) ();
STDMETHOD (QueryBindingPath) (DWORD dwChangeFlag, INetCfgComponent * pAdapter);
STDMETHOD (NotifyBindingPath) (DWORD dwChangeFlag, INetCfgBindingPath * pncbp);
STDMETHOD (GetAdapterConfig) (const GUID & AdapterGuid, NETCFG_WLBS_CONFIG * pClusterConfig);
STDMETHOD (SetAdapterConfig) (const GUID & AdapterGuid, NETCFG_WLBS_CONFIG * pClusterConfig);
STDMETHOD_(void, SetDefaults) (NETCFG_WLBS_CONFIG * pClusterConfig);
STDMETHOD (ApplyRegistryChanges) ();
STDMETHOD (ApplyPnpChanges) ();
STDMETHOD (ValidateProperties) (HWND hwndSheet, GUID adapterGUID, NETCFG_WLBS_CONFIG * adapterConfig);
STDMETHOD (CheckForDuplicateCLusterIPAddresses) (GUID adapterGUID, NETCFG_WLBS_CONFIG * adapterConfig);
STDMETHOD (CheckForDuplicateBDATeamMasters) (GUID adapterGUID, NETCFG_WLBS_CONFIG * adapterConfig);
#ifdef DEBUG
void AssertValid();
#endif
protected:
CNetcfgCluster * GetCluster (const GUID& AdapterGuid);
HRESULT LoadAllAdapterSettings (bool fUpgradeFromWin2k);
vector<CNetcfgCluster*> m_vtrCluster; // List of clusters.
HANDLE m_hDeviceWlbs; // Handle to the WLBS device object.
enum ENUM_WLBS_SERVICE {
WLBS_SERVICE_NONE,
WLBS_SERVICE_INSTALL,
WLBS_SERVICE_REMOVE,
WLBS_SERVICE_UPGRADE
};
ENUM_WLBS_SERVICE m_ServiceOperation; // Operations to be applied
INetCfgComponent * m_pWlbsComponent; // Wlbs Component.
public:
HRESULT IsBoundTo (INetCfgComponent* pAdapter);
ULONG CountNLBBindings ();
//
// To avoid link with wlbsctrl.dll, which only shiped in adavanced server
// Can not put them as global variables, because multiple instance of this
// object could exist
//
INetCfg * m_pNetCfg;
HINSTANCE m_hdllWlbsCtrl;
WlbsApiFuncs * m_pWlbsApiFuncs;
};
| 40.98773 | 137 | 0.60934 | [
"object",
"vector"
] |
2ef286f03d39c646f91dfc18c594c84318b139c5 | 4,935 | h | C | Game/OGRE/OgreMain/include/OgreArchiveManager.h | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/OgreMain/include/OgreArchiveManager.h | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/OgreMain/include/OgreArchiveManager.h | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef _ArchiveManager_H__
#define _ArchiveManager_H__
#include "OgrePrerequisites.h"
#include "OgreResourceManager.h"
#include "OgreSingleton.h"
namespace Ogre {
/** This class manages the available ArchiveFactory plugins.
*/
class _OgreExport ArchiveManager : public Singleton<ArchiveManager>
{
protected:
typedef std::map<String, ArchiveFactory*> ArchiveFactoryMap;
/// Factories available to create archives, indexed by archive type (String identifier e.g. 'Zip')
ArchiveFactoryMap mArchFactories;
/// Currently loaded archives
typedef std::map<String, Archive*> ArchiveMap;
ArchiveMap mArchives;
public:
/** Default constructor - should never get called by a client app.
*/
ArchiveManager() {}
/** Default destructor.
*/
virtual ~ArchiveManager();
/** Opens an archive for file reading.
@remarks
The archives are created using class factories within
extension libraries.
@param filename
The filename that will be opened
@param refLibrary
The library that contains the data-handling code
@returns
If the function succeeds, a valid pointer to an Archive
object is returened.
@par
If the function fails, an exception is thrown.
*/
Archive* load( const String& filename, const String& archiveType);
/** Unloads an archive.
@remarks
You must ensure that this archive is not being used before removing it.
*/
void unload(Archive* arch);
/** Unloads an archive by name.
@remarks
You must ensure that this archive is not being used before removing it.
*/
void unload(const String& filename);
/** Adds a new ArchiveFactory to the list of available factories.
@remarks
Plugin developers who add new archive codecs need to call
this after defining their ArchiveFactory subclass and
Archive subclasses for their archive type.
*/
void addArchiveFactory(ArchiveFactory* factory);
/** Override standard Singleton retrieval.
@remarks
Why do we do this? Well, it's because the Singleton
implementation is in a .h file, which means it gets compiled
into anybody who includes it. This is needed for the
Singleton template to work, but we actually only want it
compiled into the implementation of the class based on the
Singleton, not all of them. If we don't change this, we get
link errors when trying to use the Singleton-based class from
an outside dll.
@par
This method just delegates to the template version anyway,
but the implementation stays in this single compilation unit,
preventing link errors.
*/
static ArchiveManager& getSingleton(void);
/** Override standard Singleton retrieval.
@remarks
Why do we do this? Well, it's because the Singleton
implementation is in a .h file, which means it gets compiled
into anybody who includes it. This is needed for the
Singleton template to work, but we actually only want it
compiled into the implementation of the class based on the
Singleton, not all of them. If we don't change this, we get
link errors when trying to use the Singleton-based class from
an outside dll.
@par
This method just delegates to the template version anyway,
but the implementation stays in this single compilation unit,
preventing link errors.
*/
static ArchiveManager* getSingletonPtr(void);
};
}
#endif
| 38.858268 | 106 | 0.653698 | [
"object"
] |
2ef6cc69e105eaab89a43c383cad211ca165658f | 9,011 | h | C | aws-cpp-sdk-marketplace-catalog/include/aws/marketplace-catalog/model/DescribeEntityResult.h | grujicbr/aws-sdk-cpp | bdd43c178042f09c6739645e3f6cd17822a7c35c | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-marketplace-catalog/include/aws/marketplace-catalog/model/DescribeEntityResult.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-marketplace-catalog/include/aws/marketplace-catalog/model/DescribeEntityResult.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/marketplace-catalog/MarketplaceCatalog_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace MarketplaceCatalog
{
namespace Model
{
class AWS_MARKETPLACECATALOG_API DescribeEntityResult
{
public:
DescribeEntityResult();
DescribeEntityResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeEntityResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline const Aws::String& GetEntityType() const{ return m_entityType; }
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline void SetEntityType(const Aws::String& value) { m_entityType = value; }
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline void SetEntityType(Aws::String&& value) { m_entityType = std::move(value); }
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline void SetEntityType(const char* value) { m_entityType.assign(value); }
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline DescribeEntityResult& WithEntityType(const Aws::String& value) { SetEntityType(value); return *this;}
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline DescribeEntityResult& WithEntityType(Aws::String&& value) { SetEntityType(std::move(value)); return *this;}
/**
* <p>The named type of the entity, in the format of
* <code>EntityType@Version</code>.</p>
*/
inline DescribeEntityResult& WithEntityType(const char* value) { SetEntityType(value); return *this;}
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline const Aws::String& GetEntityIdentifier() const{ return m_entityIdentifier; }
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline void SetEntityIdentifier(const Aws::String& value) { m_entityIdentifier = value; }
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline void SetEntityIdentifier(Aws::String&& value) { m_entityIdentifier = std::move(value); }
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline void SetEntityIdentifier(const char* value) { m_entityIdentifier.assign(value); }
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline DescribeEntityResult& WithEntityIdentifier(const Aws::String& value) { SetEntityIdentifier(value); return *this;}
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline DescribeEntityResult& WithEntityIdentifier(Aws::String&& value) { SetEntityIdentifier(std::move(value)); return *this;}
/**
* <p>The identifier of the entity, in the format of
* <code>EntityId@RevisionId</code>.</p>
*/
inline DescribeEntityResult& WithEntityIdentifier(const char* value) { SetEntityIdentifier(value); return *this;}
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline const Aws::String& GetEntityArn() const{ return m_entityArn; }
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline void SetEntityArn(const Aws::String& value) { m_entityArn = value; }
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline void SetEntityArn(Aws::String&& value) { m_entityArn = std::move(value); }
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline void SetEntityArn(const char* value) { m_entityArn.assign(value); }
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline DescribeEntityResult& WithEntityArn(const Aws::String& value) { SetEntityArn(value); return *this;}
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline DescribeEntityResult& WithEntityArn(Aws::String&& value) { SetEntityArn(std::move(value)); return *this;}
/**
* <p>The ARN associated to the unique identifier for the change set referenced in
* this request.</p>
*/
inline DescribeEntityResult& WithEntityArn(const char* value) { SetEntityArn(value); return *this;}
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline const Aws::String& GetLastModifiedDate() const{ return m_lastModifiedDate; }
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline void SetLastModifiedDate(const Aws::String& value) { m_lastModifiedDate = value; }
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline void SetLastModifiedDate(Aws::String&& value) { m_lastModifiedDate = std::move(value); }
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline void SetLastModifiedDate(const char* value) { m_lastModifiedDate.assign(value); }
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline DescribeEntityResult& WithLastModifiedDate(const Aws::String& value) { SetLastModifiedDate(value); return *this;}
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline DescribeEntityResult& WithLastModifiedDate(Aws::String&& value) { SetLastModifiedDate(std::move(value)); return *this;}
/**
* <p>The last modified date of the entity, in ISO 8601 format
* (2018-02-27T13:45:22Z).</p>
*/
inline DescribeEntityResult& WithLastModifiedDate(const char* value) { SetLastModifiedDate(value); return *this;}
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline const Aws::String& GetDetails() const{ return m_details; }
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline void SetDetails(const Aws::String& value) { m_details = value; }
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline void SetDetails(Aws::String&& value) { m_details = std::move(value); }
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline void SetDetails(const char* value) { m_details.assign(value); }
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline DescribeEntityResult& WithDetails(const Aws::String& value) { SetDetails(value); return *this;}
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline DescribeEntityResult& WithDetails(Aws::String&& value) { SetDetails(std::move(value)); return *this;}
/**
* <p>This stringified JSON object includes the details of the entity.</p>
*/
inline DescribeEntityResult& WithDetails(const char* value) { SetDetails(value); return *this;}
private:
Aws::String m_entityType;
Aws::String m_entityIdentifier;
Aws::String m_entityArn;
Aws::String m_lastModifiedDate;
Aws::String m_details;
};
} // namespace Model
} // namespace MarketplaceCatalog
} // namespace Aws
| 33.623134 | 130 | 0.663966 | [
"object",
"model"
] |
2ef74876a85edb5ce85e7fd4f812c694a8878f2a | 1,511 | h | C | Common/track/UMAppNetwork_SDK/SDK/UMUFPWebView.h | 1box/onedayapp | 576255d230a4508fd8de2a0b14a8108b44479809 | [
"MIT"
] | 2 | 2016-04-20T06:57:18.000Z | 2017-09-18T08:16:23.000Z | Common/track/UMAppNetwork_SDK/SDK/UMUFPWebView.h | 1box/onedayapp | 576255d230a4508fd8de2a0b14a8108b44479809 | [
"MIT"
] | null | null | null | Common/track/UMAppNetwork_SDK/SDK/UMUFPWebView.h | 1box/onedayapp | 576255d230a4508fd8de2a0b14a8108b44479809 | [
"MIT"
] | null | null | null | //
// UMUFPWebView.h
// UFP
//
// Created by liu yu on 1/9/12.
// Updated by liu yu on 04/02/13.
// Copyright 2010-2013 Umeng.com. All rights reserved.
// Version 3.5.4
#import <UIKit/UIKit.h>
/**
UMUFPWebView is a subclass of UIWebView that supports Ads impression in webview.
*/
@interface UMUFPWebView : UIWebView {
@private
NSString *_mAppkey;
NSString *_mSlotId;
NSString *_mKeywords;
BOOL _mAutoFill;
}
@property (nonatomic) BOOL mAutoFill; //shows whether automatic add other promoters when data of this position is not enough
@property (nonatomic, copy) NSString *mKeywords; //keywords for the promoters data, promoter list will return according to this property, default is @""
/**
This method return a UMUFPWebView object
@param frame frame for the UMUFPWebView
@param appkey appkey get from www.umeng.com, if you want use ufp service only, set this parameter empty
@param slotId slotId get from ufp.umeng.com
@return a UMUFPWebView object
*/
- (id)initWithFrame:(CGRect)frame appKey:(NSString *)appkey slotId:(NSString *)slotId;
/**
This method start the releated url request load
*/
- (void)startLoadRequest;
/**
This method set channel for this app, the default channel is App Store, call this method if you want to set channel for another value, don't need to call this method among different views, only once is enough
@param channel channel name for the app
*/
+ (void)setAppChannel:(NSString *)channel;
@end
| 23.984127 | 209 | 0.718068 | [
"object"
] |
2efbb1237c8b71e4ba91979d25331a385f9bd7dc | 25,280 | c | C | sapi/phpdbg/phpdbg_watch.c | abugnais/php-src | 886fafc34f046c1887ea97eed9faf256be1dc3eb | [
"PHP-3.01"
] | 1 | 2020-11-07T15:39:06.000Z | 2020-11-07T15:39:06.000Z | sapi/phpdbg/phpdbg_watch.c | abugnais/php-src | 886fafc34f046c1887ea97eed9faf256be1dc3eb | [
"PHP-3.01"
] | null | null | null | sapi/phpdbg/phpdbg_watch.c | abugnais/php-src | 886fafc34f046c1887ea97eed9faf256be1dc3eb | [
"PHP-3.01"
] | null | null | null | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2014 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Felipe Pena <felipe@php.net> |
| Authors: Joe Watkins <joe.watkins@live.co.uk> |
| Authors: Bob Weinand <bwoebi@php.net> |
+----------------------------------------------------------------------+
*/
#include "zend.h"
#include "phpdbg.h"
#include "phpdbg_btree.h"
#include "phpdbg_watch.h"
#include "phpdbg_utils.h"
#ifndef _WIN32
# include <unistd.h>
# include <sys/mman.h>
#endif
ZEND_EXTERN_MODULE_GLOBALS(phpdbg);
typedef struct {
void *page;
size_t size;
char reenable_writing;
/* data must be last element */
void *data;
} phpdbg_watch_memdump;
#define MEMDUMP_SIZE(size) (sizeof(phpdbg_watch_memdump) - sizeof(void *) + (size))
static phpdbg_watchpoint_t *phpdbg_check_for_watchpoint(void *addr TSRMLS_DC) {
phpdbg_watchpoint_t *watch;
phpdbg_btree_result *result = phpdbg_btree_find_closest(&PHPDBG_G(watchpoint_tree), (zend_ulong)phpdbg_get_page_boundary(addr) + phpdbg_pagesize - 1);
if (result == NULL) {
return NULL;
}
watch = result->ptr;
/* check if that addr is in a mprotect()'ed memory area */
if ((char *)phpdbg_get_page_boundary(watch->addr.ptr) > (char *)addr || (char *)phpdbg_get_page_boundary(watch->addr.ptr) + phpdbg_get_total_page_size(watch->addr.ptr, watch->size) < (char *)addr) {
/* failure */
return NULL;
}
return watch;
}
static void phpdbg_change_watchpoint_access(phpdbg_watchpoint_t *watch, int access TSRMLS_DC) {
int m;
/* pagesize is assumed to be in the range of 2^x */
m = mprotect(phpdbg_get_page_boundary(watch->addr.ptr), phpdbg_get_total_page_size(watch->addr.ptr, watch->size), access);
}
static inline void phpdbg_activate_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
phpdbg_change_watchpoint_access(watch, PROT_READ TSRMLS_CC);
}
static inline void phpdbg_deactivate_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
phpdbg_change_watchpoint_access(watch, PROT_READ | PROT_WRITE TSRMLS_CC);
}
static inline void phpdbg_store_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
phpdbg_btree_insert(&PHPDBG_G(watchpoint_tree), (zend_ulong)watch->addr.ptr, watch);
}
static inline void phpdbg_remove_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
phpdbg_btree_delete(&PHPDBG_G(watchpoint_tree), (zend_ulong)watch->addr.ptr);
}
void phpdbg_create_addr_watchpoint(void *addr, size_t size, phpdbg_watchpoint_t *watch) {
watch->addr.ptr = addr;
watch->size = size;
}
void phpdbg_create_zval_watchpoint(zval *zv, phpdbg_watchpoint_t *watch) {
phpdbg_create_addr_watchpoint(zv, sizeof(zval), watch);
watch->type = WATCH_ON_ZVAL;
}
void phpdbg_create_ht_watchpoint(HashTable *ht, phpdbg_watchpoint_t *watch) {
phpdbg_create_addr_watchpoint(ht, sizeof(HashTable), watch);
watch->type = WATCH_ON_HASHTABLE;
}
void phpdbg_watch_HashTable_dtor(zval **ptr);
static int phpdbg_create_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
watch->flags |= PHPDBG_WATCH_SIMPLE;
phpdbg_store_watchpoint(watch TSRMLS_CC);
zend_hash_add(&PHPDBG_G(watchpoints), watch->str, watch->str_len, &watch, sizeof(phpdbg_watchpoint_t *), NULL);
if (watch->type == WATCH_ON_ZVAL) {
phpdbg_btree_insert(&PHPDBG_G(watch_HashTables), (zend_ulong)watch->parent_container, watch->parent_container->pDestructor);
watch->parent_container->pDestructor = (dtor_func_t)phpdbg_watch_HashTable_dtor;
}
phpdbg_activate_watchpoint(watch TSRMLS_CC);
return SUCCESS;
}
static int phpdbg_create_array_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
HashTable *ht;
switch (Z_TYPE_P(watch->addr.zv)) {
case IS_ARRAY:
ht = Z_ARRVAL_P(watch->addr.zv);
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(watch->addr.zv);
break;
default:
return FAILURE;
}
phpdbg_create_ht_watchpoint(ht, watch);
phpdbg_create_watchpoint(watch TSRMLS_CC);
return SUCCESS;
}
static char *phpdbg_get_property_key(char *key) {
if (*key != 0) {
return key;
}
return strchr(key + 1, 0) + 1;
}
static int phpdbg_create_recursive_watchpoint(phpdbg_watchpoint_t *watch TSRMLS_DC) {
HashTable *ht;
if (watch->type != WATCH_ON_ZVAL) {
return FAILURE;
}
watch->flags |= PHPDBG_WATCH_RECURSIVE;
phpdbg_create_watchpoint(watch TSRMLS_CC);
switch (Z_TYPE_P(watch->addr.zv)) {
case IS_ARRAY:
ht = Z_ARRVAL_P(watch->addr.zv);
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(watch->addr.zv);
break;
default:
return SUCCESS;
}
{
HashPosition position;
zval **zv;
zval key;
for (zend_hash_internal_pointer_reset_ex(ht, &position);
zend_hash_get_current_data_ex(ht, (void **)&zv, &position) == SUCCESS;
zend_hash_move_forward_ex(ht, &position)) {
phpdbg_watchpoint_t *new_watch = emalloc(sizeof(phpdbg_watchpoint_t));
new_watch->flags = PHPDBG_WATCH_RECURSIVE;
new_watch->parent = watch;
new_watch->parent_container = ht;
zend_hash_get_current_key_zval_ex(ht, &key, &position);
if (Z_TYPE(key) == IS_STRING) {
new_watch->name_in_parent = zend_strndup(Z_STRVAL(key), Z_STRLEN(key));
new_watch->name_in_parent_len = Z_STRLEN(key);
} else {
new_watch->name_in_parent = NULL;
new_watch->name_in_parent_len = asprintf(&new_watch->name_in_parent, "%ld", Z_LVAL(key));
}
new_watch->str = NULL;
new_watch->str_len = asprintf(&new_watch->str, "%.*s%s%s%s", (int)watch->str_len, watch->str, Z_TYPE_P(watch->addr.zv) == IS_ARRAY?"[":"->", phpdbg_get_property_key(new_watch->name_in_parent), Z_TYPE_P(watch->addr.zv) == IS_ARRAY?"]":"");
phpdbg_create_zval_watchpoint(*zv, new_watch);
phpdbg_create_recursive_watchpoint(new_watch TSRMLS_CC);
}
}
{
phpdbg_watchpoint_t *new_watch = emalloc(sizeof(phpdbg_watchpoint_t));
new_watch->parent = watch;
new_watch->parent_container = watch->parent_container;
new_watch->name_in_parent = zend_strndup(watch->name_in_parent, watch->name_in_parent_len);
new_watch->name_in_parent_len = watch->name_in_parent_len;
new_watch->str = NULL;
new_watch->str_len = asprintf(&new_watch->str, "%.*s[]", (int)watch->str_len, watch->str);
new_watch->flags = PHPDBG_WATCH_RECURSIVE;
phpdbg_create_ht_watchpoint(ht, new_watch);
phpdbg_create_watchpoint(new_watch TSRMLS_CC);
}
return SUCCESS;
}
static int phpdbg_delete_watchpoint_recursive(phpdbg_watchpoint_t *watch, zend_bool user_request TSRMLS_DC) {
if (watch->type == WATCH_ON_HASHTABLE || (watch->type == WATCH_ON_ZVAL && (Z_TYPE_P(watch->addr.zv) == IS_ARRAY || Z_TYPE_P(watch->addr.zv) == IS_OBJECT))) {
HashTable *ht;
phpdbg_btree_result *result;
if (watch->type == WATCH_ON_HASHTABLE && user_request) {
HashPosition position;
zval **zv;
zval key;
char *str;
int str_len;
phpdbg_watchpoint_t **watchpoint;
ht = watch->addr.ht;
for (zend_hash_internal_pointer_reset_ex(ht, &position);
zend_hash_get_current_data_ex(ht, (void **)&zv, &position) == SUCCESS;
zend_hash_move_forward_ex(ht, &position)) {
zend_hash_get_current_key_zval_ex(ht, &key, &position);
str = NULL;
if (Z_TYPE(key) == IS_STRING) {
str_len = asprintf(&str, "%.*s%s%s%s", (int)watch->parent->str_len, watch->parent->str, Z_TYPE_P(watch->parent->addr.zv) == IS_ARRAY?"[":"->", phpdbg_get_property_key(Z_STRVAL(key)), Z_TYPE_P(watch->parent->addr.zv) == IS_ARRAY?"]":"");
} else {
str_len = asprintf(&str, "%.*s%s%li%s", (int)watch->parent->str_len, watch->parent->str, Z_TYPE_P(watch->parent->addr.zv) == IS_ARRAY?"[":"->", Z_LVAL(key), Z_TYPE_P(watch->parent->addr.zv) == IS_ARRAY?"]":"");
}
if (zend_hash_find(&PHPDBG_G(watchpoints), str, str_len, (void **) &watchpoint) == SUCCESS) {
phpdbg_delete_watchpoint_recursive(*watchpoint, 1 TSRMLS_CC);
}
}
} else {
switch (Z_TYPE_P(watch->addr.zv)) {
case IS_ARRAY:
ht = Z_ARRVAL_P(watch->addr.zv);
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(watch->addr.zv);
break;
}
if ((result = phpdbg_btree_find(&PHPDBG_G(watchpoint_tree), (zend_ulong) ht))) {
phpdbg_delete_watchpoint_recursive((phpdbg_watchpoint_t *) result->ptr, user_request TSRMLS_CC);
}
}
}
return zend_hash_del(&PHPDBG_G(watchpoints), watch->str, watch->str_len);
}
static int phpdbg_delete_watchpoint(phpdbg_watchpoint_t *tmp_watch TSRMLS_DC) {
int ret;
phpdbg_watchpoint_t *watch;
phpdbg_btree_result *result;
if ((result = phpdbg_btree_find(&PHPDBG_G(watchpoint_tree), (zend_ulong)tmp_watch->addr.ptr)) == NULL) {
return FAILURE;
}
watch = result->ptr;
if (watch->flags & PHPDBG_WATCH_RECURSIVE) {
ret = phpdbg_delete_watchpoint_recursive(watch, 1 TSRMLS_CC);
} else {
ret = zend_hash_del(&PHPDBG_G(watchpoints), watch->str, watch->str_len);
}
free(tmp_watch->str);
efree(tmp_watch);
return ret;
}
static int phpdbg_watchpoint_parse_input(char *input, size_t len, HashTable *parent, size_t i, int (*callback)(phpdbg_watchpoint_t * TSRMLS_DC), zend_bool silent TSRMLS_DC) {
int ret = FAILURE;
zend_bool new_index = 1;
char *last_index;
int index_len = 0;
zval **zv;
if (len < 2 || *input != '$') {
goto error;
}
while (i++ < len) {
if (i == len) {
new_index = 1;
} else {
switch (input[i]) {
case '[':
new_index = 1;
break;
case ']':
break;
case '>':
if (last_index[index_len - 1] == '-') {
new_index = 1;
index_len--;
}
break;
default:
if (new_index) {
last_index = input + i;
new_index = 0;
}
if (input[i - 1] == ']') {
goto error;
}
index_len++;
}
}
if (new_index && index_len == 0) {
HashPosition position;
for (zend_hash_internal_pointer_reset_ex(parent, &position);
zend_hash_get_current_data_ex(parent, (void **)&zv, &position) == SUCCESS;
zend_hash_move_forward_ex(parent, &position)) {
if (i == len || (i == len - 1 && input[len - 1] == ']')) {
zval *key = emalloc(sizeof(zval));
phpdbg_watchpoint_t *watch = emalloc(sizeof(phpdbg_watchpoint_t));
watch->flags = 0;
zend_hash_get_current_key_zval_ex(parent, key, &position);
convert_to_string(key);
watch->str = malloc(i + Z_STRLEN_P(key) + 2);
watch->str_len = sprintf(watch->str, "%.*s%s%s", (int)i, input, phpdbg_get_property_key(Z_STRVAL_P(key)), input[len - 1] == ']'?"]":"");
efree(key);
watch->name_in_parent = zend_strndup(last_index, index_len);
watch->name_in_parent_len = index_len;
watch->parent_container = parent;
phpdbg_create_zval_watchpoint(*zv, watch);
ret = callback(watch TSRMLS_CC) == SUCCESS || ret == SUCCESS?SUCCESS:FAILURE;
} else if (Z_TYPE_PP(zv) == IS_OBJECT) {
phpdbg_watchpoint_parse_input(input, len, Z_OBJPROP_PP(zv), i, callback, silent TSRMLS_CC);
} else if (Z_TYPE_PP(zv) == IS_ARRAY) {
phpdbg_watchpoint_parse_input(input, len, Z_ARRVAL_PP(zv), i, callback, silent TSRMLS_CC);
} else {
/* Ignore silently */
}
}
return ret;
} else if (new_index) {
char last_chr = last_index[index_len];
last_index[index_len] = 0;
if (zend_symtable_find(parent, last_index, index_len + 1, (void **)&zv) == FAILURE) {
if (!silent) {
phpdbg_error("%.*s is undefined", (int)i, input);
}
return FAILURE;
}
last_index[index_len] = last_chr;
if (i == len) {
phpdbg_watchpoint_t *watch = emalloc(sizeof(phpdbg_watchpoint_t));
watch->flags = 0;
watch->str = zend_strndup(input, len);
watch->str_len = len;
watch->name_in_parent = zend_strndup(last_index, index_len);
watch->name_in_parent_len = index_len;
watch->parent_container = parent;
phpdbg_create_zval_watchpoint(*zv, watch);
ret = callback(watch TSRMLS_CC) == SUCCESS || ret == SUCCESS?SUCCESS:FAILURE;
} else if (Z_TYPE_PP(zv) == IS_OBJECT) {
parent = Z_OBJPROP_PP(zv);
} else if (Z_TYPE_PP(zv) == IS_ARRAY) {
parent = Z_ARRVAL_PP(zv);
} else {
phpdbg_error("%.*s is nor an array nor an object", (int)i, input);
return FAILURE;
}
index_len = 0;
}
}
return ret;
error:
phpdbg_error("Malformed input");
return FAILURE;
}
static int phpdbg_watchpoint_parse_symtables(char *input, size_t len, int (*callback)(phpdbg_watchpoint_t * TSRMLS_DC) TSRMLS_DC) {
if (EG(This) && len >= 5 && !memcmp("$this", input, 5)) {
zend_hash_add(EG(active_symbol_table), "this", sizeof("this"), &EG(This), sizeof(zval *), NULL);
}
if (zend_is_auto_global(input, len TSRMLS_CC) && phpdbg_watchpoint_parse_input(input, len, &EG(symbol_table), 0, callback, 1 TSRMLS_CC) != FAILURE) {
return SUCCESS;
}
return phpdbg_watchpoint_parse_input(input, len, EG(active_symbol_table), 0, callback, 0 TSRMLS_CC);
}
PHPDBG_WATCH(delete) /* {{{ */
{
switch (param->type) {
case STR_PARAM:
if (phpdbg_delete_var_watchpoint(param->str, param->len TSRMLS_CC) == FAILURE) {
phpdbg_error("Nothing was deleted, no corresponding watchpoint found");
} else {
phpdbg_notice("Removed watchpoint %.*s", (int)param->len, param->str);
}
break;
phpdbg_default_switch_case();
}
return SUCCESS;
} /* }}} */
PHPDBG_WATCH(recursive) /* {{{ */
{
if (phpdbg_rebuild_symtable(TSRMLS_C) == FAILURE) {
return SUCCESS;
}
switch (param->type) {
case STR_PARAM:
if (phpdbg_watchpoint_parse_symtables(param->str, param->len, phpdbg_create_recursive_watchpoint TSRMLS_CC) != FAILURE) {
phpdbg_notice("Set recursive watchpoint on %.*s", (int)param->len, param->str);
}
break;
phpdbg_default_switch_case();
}
return SUCCESS;
} /* }}} */
PHPDBG_WATCH(array) /* {{{ */
{
if (phpdbg_rebuild_symtable(TSRMLS_C) == FAILURE) {
return SUCCESS;
}
switch (param->type) {
case STR_PARAM:
if (phpdbg_watchpoint_parse_symtables(param->str, param->len, phpdbg_create_array_watchpoint TSRMLS_CC) != FAILURE) {
phpdbg_notice("Set array watchpoint on %.*s", (int)param->len, param->str);
}
break;
phpdbg_default_switch_case();
}
return SUCCESS;
} /* }}} */
void phpdbg_watch_HashTable_dtor(zval **zv) {
phpdbg_btree_result *result;
TSRMLS_FETCH();
zval_ptr_dtor_wrapper(zv);
if ((result = phpdbg_btree_find(&PHPDBG_G(watchpoint_tree), (zend_ulong)*zv))) {
phpdbg_watchpoint_t *watch = result->ptr;
PHPDBG_G(watchpoint_hit) = 1;
phpdbg_notice("%.*s was removed, removing watchpoint%s", (int)watch->str_len, watch->str, (watch->flags & PHPDBG_WATCH_RECURSIVE)?" recursively":"");
if (watch->flags & PHPDBG_WATCH_RECURSIVE) {
phpdbg_delete_watchpoint_recursive(watch, 0 TSRMLS_CC);
} else {
zend_hash_del(&PHPDBG_G(watchpoints), watch->str, watch->str_len);
}
}
}
int phpdbg_create_var_watchpoint(char *input, size_t len TSRMLS_DC) {
if (phpdbg_rebuild_symtable(TSRMLS_C) == FAILURE) {
return FAILURE;
}
return phpdbg_watchpoint_parse_symtables(input, len, phpdbg_create_watchpoint TSRMLS_CC);
}
int phpdbg_delete_var_watchpoint(char *input, size_t len TSRMLS_DC) {
if (phpdbg_rebuild_symtable(TSRMLS_C) == FAILURE) {
return FAILURE;
}
return phpdbg_watchpoint_parse_symtables(input, len, phpdbg_delete_watchpoint TSRMLS_CC);
}
#ifdef _WIN32
int phpdbg_watchpoint_segfault_handler(void *addr TSRMLS_DC) {
#else
int phpdbg_watchpoint_segfault_handler(siginfo_t *info, void *context TSRMLS_DC) {
#endif
void *page;
phpdbg_watch_memdump *dump;
phpdbg_watchpoint_t *watch;
size_t size;
watch = phpdbg_check_for_watchpoint(
#ifdef _WIN32
addr
#else
info->si_addr
#endif
TSRMLS_CC);
if (watch == NULL) {
return FAILURE;
}
page = phpdbg_get_page_boundary(watch->addr.ptr);
size = phpdbg_get_total_page_size(watch->addr.ptr, watch->size);
/* re-enable writing */
mprotect(page, size, PROT_READ | PROT_WRITE);
dump = malloc(MEMDUMP_SIZE(size));
dump->page = page;
dump->size = size;
memcpy(&dump->data, page, size);
zend_llist_add_element(&PHPDBG_G(watchlist_mem), &dump);
return SUCCESS;
}
void phpdbg_watchpoints_clean(TSRMLS_D) {
zend_hash_clean(&PHPDBG_G(watchpoints));
}
static void phpdbg_watch_dtor(void *pDest) {
phpdbg_watchpoint_t *watch = *(phpdbg_watchpoint_t **)pDest;
TSRMLS_FETCH();
phpdbg_deactivate_watchpoint(watch TSRMLS_CC);
phpdbg_remove_watchpoint(watch TSRMLS_CC);
free(watch->str);
free(watch->name_in_parent);
efree(watch);
}
static void phpdbg_watch_mem_dtor(void *llist_data) {
phpdbg_watch_memdump *dump = *(phpdbg_watch_memdump **)llist_data;
/* Disble writing again */
if (dump->reenable_writing) {
mprotect(dump->page, dump->size, PROT_READ);
}
free(*(void **)llist_data);
}
void phpdbg_setup_watchpoints(TSRMLS_D) {
#if _SC_PAGE_SIZE
phpdbg_pagesize = sysconf(_SC_PAGE_SIZE);
#elif _SC_PAGESIZE
phpdbg_pagesize = sysconf(_SC_PAGESIZE);
#elif _SC_NUTC_OS_PAGESIZE
phpdbg_pagesize = sysconf(_SC_NUTC_OS_PAGESIZE);
#else
phpdbg_pagesize = 4096; /* common pagesize */
#endif
zend_llist_init(&PHPDBG_G(watchlist_mem), sizeof(void *), phpdbg_watch_mem_dtor, 1);
phpdbg_btree_init(&PHPDBG_G(watchpoint_tree), sizeof(void *) * 8);
phpdbg_btree_init(&PHPDBG_G(watch_HashTables), sizeof(void *) * 8);
_zend_hash_init(&PHPDBG_G(watchpoints), 8, phpdbg_watch_dtor, 0 ZEND_FILE_LINE_CC);
}
static void phpdbg_print_changed_zval(phpdbg_watch_memdump *dump TSRMLS_DC) {
/* fetch all changes between dump->page and dump->page + dump->size */
phpdbg_btree_position pos = phpdbg_btree_find_between(&PHPDBG_G(watchpoint_tree), (zend_ulong)dump->page, (zend_ulong)dump->page + dump->size);
phpdbg_btree_result *result, *htresult;
int elementDiff;
void *curTest;
dump->reenable_writing = 0;
while ((result = phpdbg_btree_next(&pos))) {
phpdbg_watchpoint_t *watch = result->ptr, *htwatch;
void *oldPtr = (char *)&dump->data + ((size_t)watch->addr.ptr - (size_t)dump->page);
char reenable = 1;
if ((size_t)watch->addr.ptr < (size_t)dump->page || (size_t)watch->addr.ptr + watch->size > (size_t)dump->page + dump->size) {
continue;
}
/* Test if the zval was separated and if necessary move the watchpoint */
if (zend_hash_find(watch->parent_container, watch->name_in_parent, watch->name_in_parent_len + 1, &curTest) == SUCCESS) {
if (watch->type == WATCH_ON_HASHTABLE) {
switch (Z_TYPE_PP((zval **)curTest)) {
case IS_ARRAY:
curTest = (void *)Z_ARRVAL_PP((zval **)curTest);
break;
case IS_OBJECT:
curTest = (void *)Z_OBJPROP_PP((zval **)curTest);
break;
}
} else {
curTest = *(void **)curTest;
}
if (curTest != watch->addr.ptr) {
phpdbg_deactivate_watchpoint(watch TSRMLS_CC);
phpdbg_remove_watchpoint(watch TSRMLS_CC);
watch->addr.ptr = curTest;
phpdbg_store_watchpoint(watch TSRMLS_CC);
phpdbg_activate_watchpoint(watch TSRMLS_CC);
reenable = 0;
}
}
/* Show to the user what changed and delete watchpoint upon removal */
if (memcmp(oldPtr, watch->addr.ptr, watch->size) != SUCCESS) {
if (PHPDBG_G(flags) & PHPDBG_SHOW_REFCOUNTS || (watch->type == WATCH_ON_ZVAL && memcmp(oldPtr, watch->addr.zv, sizeof(zvalue_value))) || (watch->type == WATCH_ON_HASHTABLE
#if ZEND_DEBUG
&& !watch->addr.ht->inconsistent
#endif
&& zend_hash_num_elements((HashTable *)oldPtr) != zend_hash_num_elements(watch->addr.ht))) {
PHPDBG_G(watchpoint_hit) = 1;
phpdbg_notice("Breaking on watchpoint %s", watch->str);
}
switch (watch->type) {
case WATCH_ON_ZVAL: {
int removed = ((zval *)oldPtr)->refcount__gc != watch->addr.zv->refcount__gc && !zend_symtable_exists(watch->parent_container, watch->name_in_parent, watch->name_in_parent_len + 1);
int show_value = memcmp(oldPtr, watch->addr.zv, sizeof(zvalue_value));
int show_ref = ((zval *)oldPtr)->refcount__gc != watch->addr.zv->refcount__gc || ((zval *)oldPtr)->is_ref__gc != watch->addr.zv->is_ref__gc;
if (removed || show_value) {
phpdbg_write("Old value: ");
if ((Z_TYPE_P((zval *)oldPtr) == IS_ARRAY || Z_TYPE_P((zval *)oldPtr) == IS_OBJECT) && removed) {
phpdbg_writeln("Value inaccessible, HashTable already destroyed");
} else {
zend_print_flat_zval_r((zval *)oldPtr TSRMLS_CC);
phpdbg_writeln("");
}
}
if (PHPDBG_G(flags) & PHPDBG_SHOW_REFCOUNTS && (removed || show_ref)) {
phpdbg_writeln("Old refcount: %d; Old is_ref: %d", ((zval *)oldPtr)->refcount__gc, ((zval *)oldPtr)->is_ref__gc);
}
/* check if zval was removed */
if (removed) {
phpdbg_notice("Watchpoint %s was unset, removing watchpoint", watch->str);
zend_hash_del(&PHPDBG_G(watchpoints), watch->str, watch->str_len);
reenable = 0;
if (Z_TYPE_P((zval *)oldPtr) == IS_ARRAY || Z_TYPE_P((zval *)oldPtr) == IS_OBJECT) {
goto remove_ht_watch;
}
break;
}
if (show_value) {
phpdbg_write("New value: ");
zend_print_flat_zval_r(watch->addr.zv TSRMLS_CC);
phpdbg_writeln("");
}
if (PHPDBG_G(flags) & PHPDBG_SHOW_REFCOUNTS && show_ref) {
phpdbg_writeln("New refcount: %d; New is_ref: %d", watch->addr.zv->refcount__gc, watch->addr.zv->is_ref__gc);
}
if ((Z_TYPE_P(watch->addr.zv) == IS_ARRAY && Z_ARRVAL_P(watch->addr.zv) != Z_ARRVAL_P((zval *)oldPtr)) || (Z_TYPE_P(watch->addr.zv) != IS_OBJECT && Z_OBJ_HANDLE_P(watch->addr.zv) == Z_OBJ_HANDLE_P((zval *)oldPtr))) {
/* add new watchpoints if necessary */
if (watch->flags & PHPDBG_WATCH_RECURSIVE) {
phpdbg_create_recursive_watchpoint(watch TSRMLS_CC);
}
}
if ((Z_TYPE_P((zval *)oldPtr) != IS_ARRAY || Z_ARRVAL_P(watch->addr.zv) == Z_ARRVAL_P((zval *)oldPtr)) && (Z_TYPE_P((zval *)oldPtr) != IS_OBJECT || Z_OBJ_HANDLE_P(watch->addr.zv) == Z_OBJ_HANDLE_P((zval *)oldPtr))) {
break;
}
remove_ht_watch:
if ((htresult = phpdbg_btree_find(&PHPDBG_G(watchpoint_tree), (zend_ulong)Z_ARRVAL_P((zval *)oldPtr)))) {
htwatch = htresult->ptr;
zend_hash_del(&PHPDBG_G(watchpoints), htwatch->str, htwatch->str_len);
}
break;
}
case WATCH_ON_HASHTABLE:
#if ZEND_DEBUG
if (watch->addr.ht->inconsistent) {
phpdbg_notice("Watchpoint %s was unset, removing watchpoint", watch->str);
zend_hash_del(&PHPDBG_G(watchpoints), watch->str, watch->str_len);
reenable = 0;
break;
}
#endif
elementDiff = zend_hash_num_elements((HashTable *)oldPtr) - zend_hash_num_elements(watch->addr.ht);
if (elementDiff) {
if (elementDiff > 0) {
phpdbg_writeln("%d elements were removed from the array", elementDiff);
} else {
phpdbg_writeln("%d elements were added to the array", -elementDiff);
/* add new watchpoints if necessary */
if (watch->flags & PHPDBG_WATCH_RECURSIVE) {
phpdbg_create_recursive_watchpoint(watch TSRMLS_CC);
}
}
}
if (((HashTable *)oldPtr)->pInternalPointer != watch->addr.ht->pInternalPointer) {
phpdbg_writeln("Internal pointer of array was changed");
}
break;
}
}
dump->reenable_writing = dump->reenable_writing | reenable;
}
}
int phpdbg_print_changed_zvals(TSRMLS_D) {
zend_llist_position pos;
phpdbg_watch_memdump **dump;
int ret;
if (zend_llist_count(&PHPDBG_G(watchlist_mem)) == 0) {
return FAILURE;
}
dump = (phpdbg_watch_memdump **)zend_llist_get_last_ex(&PHPDBG_G(watchlist_mem), &pos);
do {
phpdbg_print_changed_zval(*dump TSRMLS_CC);
} while ((dump = (phpdbg_watch_memdump **)zend_llist_get_prev_ex(&PHPDBG_G(watchlist_mem), &pos)));
zend_llist_clean(&PHPDBG_G(watchlist_mem));
ret = PHPDBG_G(watchpoint_hit)?SUCCESS:FAILURE;
PHPDBG_G(watchpoint_hit) = 0;
return ret;
}
void phpdbg_list_watchpoints(TSRMLS_D) {
HashPosition position;
phpdbg_watchpoint_t **watch;
for (zend_hash_internal_pointer_reset_ex(&PHPDBG_G(watchpoints), &position);
zend_hash_get_current_data_ex(&PHPDBG_G(watchpoints), (void**) &watch, &position) == SUCCESS;
zend_hash_move_forward_ex(&PHPDBG_G(watchpoints), &position)) {
phpdbg_writeln("%.*s", (int)(*watch)->str_len, (*watch)->str);
}
}
void phpdbg_watch_efree(void *ptr) {
phpdbg_btree_result *result;
TSRMLS_FETCH();
result = phpdbg_btree_find_closest(&PHPDBG_G(watchpoint_tree), (zend_ulong)ptr);
if (result) {
phpdbg_watchpoint_t *watch = result->ptr;
if ((size_t)watch->addr.ptr + watch->size > (size_t)ptr) {
zend_hash_del(&PHPDBG_G(watchpoints), watch->str, watch->str_len);
}
}
PHPDBG_G(original_free_function)(ptr);
}
| 32 | 241 | 0.681487 | [
"object"
] |
2c03d13f0fc92fae672c6736e2aaf114b71c9a17 | 4,115 | h | C | src/OutputMapper.h | tristanseifert/lichtenstein_server | 172754817ce9d1c60ebf454aac8c65faee4627c8 | [
"BSD-3-Clause"
] | null | null | null | src/OutputMapper.h | tristanseifert/lichtenstein_server | 172754817ce9d1c60ebf454aac8c65faee4627c8 | [
"BSD-3-Clause"
] | 1 | 2019-01-16T16:40:34.000Z | 2019-01-26T21:51:17.000Z | src/OutputMapper.h | tristanseifert/lichtenstein_server | 172754817ce9d1c60ebf454aac8c65faee4627c8 | [
"BSD-3-Clause"
] | null | null | null | /**
* The output mapper builds a relation between output groups (or a collection of
* groups, called an ubergroup) and an effect routine.
*/
#ifndef OUTPUTMAPPER_H
#define OUTPUTMAPPER_H
#include "HSIPixel.h"
#include "db/Group.h"
#include <map>
#include <set>
#include <vector>
#include <mutex>
#include <exception>
#include "INIReader.h"
class Routine;
class DataStore;
class Framebuffer;
class OutputMapper {
friend class EffectRunner;
public:
struct invalid_ubergroup : public std::exception {
const char *what() const throw () {
return "Invalid ubergroup";
}
};
public:
class OutputGroup {
friend class OutputMapper;
public:
OutputGroup() = delete;
OutputGroup(DbGroup *g);
virtual ~OutputGroup();
/**
* Returns the group ID.
*/
int getGroupId() const {
return this->group->getId();
}
/**
* Returns an iterator into the group's framebuffer.
*/
HSIPixel *getDataPointer() {
return this->buffer;
}
/**
* Sets the brightness of this group.
*/
virtual void setBrightness(double brightness) {
// bounds checking: [0, 1]
if(brightness >= 0.0 && brightness <= 1.0) {
this->brightness = brightness;
}
}
/**
* Returns the brightness of the group.
*/
double getBrightness() const {
return this->brightness;
}
virtual int numPixels();
virtual void bindBufferToRoutine(Routine *r);
virtual void copyIntoFramebuffer(Framebuffer *fb, HSIPixel *buffer = nullptr);
private:
virtual void _resizeBuffer();
bool bufferChanged = false;
Routine *bufferBoundRoutine = nullptr;
HSIPixel *buffer = nullptr;
size_t bufferSz = 0;
/// brightness to scale each output pixel by
double brightness = 1.0;
private:
DbGroup *group = nullptr;
friend bool operator==(const OutputGroup& lhs, const OutputGroup& rhs);
friend bool operator< (const OutputGroup& lhs, const OutputGroup& rhs);
friend std::ostream &operator<<(std::ostream& strm, const OutputGroup& obj);
};
class OutputUberGroup: public OutputGroup {
friend class OutputMapper;
public:
OutputUberGroup();
OutputUberGroup(std::vector<OutputGroup *> &members);
~OutputUberGroup();
public:
// overrides from OutputGroup
virtual int numPixels();
virtual void copyIntoFramebuffer(Framebuffer *fb, HSIPixel *buffer = nullptr);
int numMembers() {
return this->groups.size();
}
private:
// virtual void _resizeBuffer();
void addMember(OutputGroup *group);
void removeMember(OutputGroup *group);
bool containsMember(OutputGroup *group);
private:
// std::recursive_mutex groupsLock;
std::set<OutputGroup *> groups;
// operators
friend bool operator==(const OutputUberGroup& lhs, const OutputUberGroup& rhs);
friend bool operator< (const OutputUberGroup& lhs, const OutputUberGroup& rhs);
friend std::ostream &operator<<(std::ostream& strm, const OutputUberGroup& obj);
};
public:
OutputMapper(DataStore *s, Framebuffer *f, INIReader *reader);
~OutputMapper();
public:
void addMapping(OutputGroup *g, Routine *r);
void removeMappingForGroup(OutputGroup *g);
inline Routine *routineForMapping(OutputGroup *g) {
return this->outputMap[g];
}
void getAllGroups(std::vector<OutputGroup *> &groups);
private:
void _removeMappingsInUbergroup(OutputUberGroup *ug);
void removeEmptyUbergroups(void);
void printMap(void);
private:
DataStore *store;
Framebuffer *fb;
INIReader *config;
// TODO: indicate if the output config was changed
std::recursive_mutex outputMapLock;
std::map<OutputGroup *, Routine *> outputMap;
};
// operators
inline std::ostream &operator<<(std::ostream& strm, const OutputMapper::OutputGroup *obj) {
strm << *obj;
return strm;
}
inline std::ostream &operator<<(std::ostream& strm, const OutputMapper::OutputUberGroup *obj) {
strm << *obj;
return strm;
}
#endif
| 22.861111 | 95 | 0.660753 | [
"vector"
] |
2c0b0c3b187658cf0a9501722df4f8e8be33ff94 | 8,627 | h | C | src/Dependencies/EASTL/include/EASTL/internal/generic_iterator.h | Connway/Shibboleth | 23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35 | [
"MIT"
] | 1 | 2020-04-06T17:35:47.000Z | 2020-04-06T17:35:47.000Z | src/Dependencies/EASTL/include/EASTL/internal/generic_iterator.h | Connway/Shibboleth | 23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35 | [
"MIT"
] | null | null | null | src/Dependencies/EASTL/include/EASTL/internal/generic_iterator.h | Connway/Shibboleth | 23dda9a066db8dfaf8c8d56cb1e3d9929b6ced35 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Implements a generic iterator from a given iteratable type, such as a pointer.
// We cannot put this file into our own iterator.h file because we need to
// still be able to use this file when we have our iterator.h disabled.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_INTERNAL_GENERIC_ITERATOR_H
#define EASTL_INTERNAL_GENERIC_ITERATOR_H
#include <EABase/eabase.h>
#if defined(EA_PRAGMA_ONCE_SUPPORTED)
#pragma once
#endif
#include <EASTL/internal/config.h>
#include <EASTL/iterator.h>
#include <EASTL/type_traits.h>
// There is no warning number 'number'.
// Member template functions cannot be used for copy-assignment or copy-construction.
EA_DISABLE_VC_WARNING(4619 4217);
namespace eastl
{
/// generic_iterator
///
/// Converts something which can be iterated into a formal iterator.
/// While this class' primary purpose is to allow the conversion of
/// a pointer to an iterator, you can convert anything else to an
/// iterator by defining an iterator_traits<> specialization for that
/// object type. See EASTL iterator.h for this.
///
/// Example usage:
/// typedef generic_iterator<int*> IntArrayIterator;
/// typedef generic_iterator<int*, char> IntArrayIteratorOther;
///
template <typename Iterator, typename Container = void>
class generic_iterator
{
protected:
Iterator mIterator;
public:
typedef typename eastl::iterator_traits<Iterator>::iterator_category iterator_category;
typedef typename eastl::iterator_traits<Iterator>::value_type value_type;
typedef typename eastl::iterator_traits<Iterator>::difference_type difference_type;
typedef typename eastl::iterator_traits<Iterator>::reference reference;
typedef typename eastl::iterator_traits<Iterator>::pointer pointer;
typedef Iterator iterator_type;
typedef iterator_type wrapped_iterator_type; // This is not in the C++ Standard; it's used by use to identify it as a wrapping iterator type.
typedef Container container_type;
typedef generic_iterator<Iterator, Container> this_type;
generic_iterator()
: mIterator(iterator_type()) { }
explicit generic_iterator(const iterator_type& x)
: mIterator(x) { }
this_type& operator=(const iterator_type& x)
{ mIterator = x; return *this; }
template <typename Iterator2>
generic_iterator(const generic_iterator<Iterator2, Container>& x)
: mIterator(x.base()) { }
reference operator*() const
{ return *mIterator; }
pointer operator->() const
{ return mIterator; }
this_type& operator++()
{ ++mIterator; return *this; }
this_type operator++(int)
{ return this_type(mIterator++); }
this_type& operator--()
{ --mIterator; return *this; }
this_type operator--(int)
{ return this_type(mIterator--); }
reference operator[](const difference_type& n) const
{ return mIterator[n]; }
this_type& operator+=(const difference_type& n)
{ mIterator += n; return *this; }
this_type operator+(const difference_type& n) const
{ return this_type(mIterator + n); }
this_type& operator-=(const difference_type& n)
{ mIterator -= n; return *this; }
this_type operator-(const difference_type& n) const
{ return this_type(mIterator - n); }
const iterator_type& base() const
{ return mIterator; }
}; // class generic_iterator
template <typename IteratorL, typename IteratorR, typename Container>
inline bool operator==(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() == rhs.base(); }
template <typename Iterator, typename Container>
inline bool operator==(const generic_iterator<Iterator, Container>& lhs, const generic_iterator<Iterator, Container>& rhs)
{ return lhs.base() == rhs.base(); }
template <typename IteratorL, typename IteratorR, typename Container>
inline bool operator!=(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() != rhs.base(); }
template <typename Iterator, typename Container>
inline bool operator!=(const generic_iterator<Iterator, Container>& lhs, const generic_iterator<Iterator, Container>& rhs)
{ return lhs.base() != rhs.base(); }
template <typename IteratorL, typename IteratorR, typename Container>
inline bool operator<(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() < rhs.base(); }
template <typename Iterator, typename Container>
inline bool operator<(const generic_iterator<Iterator, Container>& lhs, const generic_iterator<Iterator, Container>& rhs)
{ return lhs.base() < rhs.base(); }
template <typename IteratorL, typename IteratorR, typename Container>
inline bool operator>(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() > rhs.base(); }
template <typename Iterator, typename Container>
inline bool operator>(const generic_iterator<Iterator, Container>& lhs, const generic_iterator<Iterator, Container>& rhs)
{ return lhs.base() > rhs.base(); }
template <typename IteratorL, typename IteratorR, typename Container>
inline bool operator<=(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() <= rhs.base(); }
template <typename Iterator, typename Container>
inline bool operator<=(const generic_iterator<Iterator, Container>& lhs, const generic_iterator<Iterator, Container>& rhs)
{ return lhs.base() <= rhs.base(); }
template <typename IteratorL, typename IteratorR, typename Container>
inline bool operator>=(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() >= rhs.base(); }
template <typename Iterator, typename Container>
inline bool operator>=(const generic_iterator<Iterator, Container>& lhs, const generic_iterator<Iterator, Container>& rhs)
{ return lhs.base() >= rhs.base(); }
template <typename IteratorL, typename IteratorR, typename Container>
inline typename generic_iterator<IteratorL, Container>::difference_type
operator-(const generic_iterator<IteratorL, Container>& lhs, const generic_iterator<IteratorR, Container>& rhs)
{ return lhs.base() - rhs.base(); }
template <typename Iterator, typename Container>
inline generic_iterator<Iterator, Container>
operator+(typename generic_iterator<Iterator, Container>::difference_type n, const generic_iterator<Iterator, Container>& x)
{ return generic_iterator<Iterator, Container>(x.base() + n); }
/// is_generic_iterator
///
/// Tells if an iterator is one of these generic_iterators. This is useful if you want to
/// write code that uses miscellaneous iterators but wants to tell if they are generic_iterators.
/// A primary reason to do so is that you can get at the pointer within the generic_iterator.
///
template <typename Iterator>
struct is_generic_iterator : public false_type { };
template <typename Iterator, typename Container>
struct is_generic_iterator<generic_iterator<Iterator, Container> > : public true_type { };
/// unwrap_generic_iterator
///
/// Returns Iterator::get_base() if it's a generic_iterator, else returns Iterator as-is.
///
/// Example usage:
/// vector<int> intVector;
/// eastl::generic_iterator<vector<int>::iterator> genericIterator(intVector.begin());
/// vector<int>::iterator it = unwrap_generic_iterator(genericIterator);
///
template <typename Iterator>
inline typename eastl::is_iterator_wrapper_helper<Iterator, eastl::is_generic_iterator<Iterator>::value>::iterator_type unwrap_generic_iterator(Iterator it)
{ return eastl::is_iterator_wrapper_helper<Iterator, eastl::is_generic_iterator<Iterator>::value>::get_base(it); }
} // namespace eastl
EA_RESTORE_VC_WARNING();
#endif // Header include guard
| 41.277512 | 193 | 0.687029 | [
"object",
"vector"
] |
2c1070b8ab8037128077bfdda3dfe56956d020da | 10,318 | c | C | drivers/net/irda/mknet/sys/winreg.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/net/irda/mknet/sys/winreg.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/net/irda/mknet/sys/winreg.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*****************************************************************************
** **
** COPYRIGHT (C) 2000, 2001 MKNET CORPORATION **
** DEVELOPED FOR THE MK7100-BASED VFIR PCI CONTROLLER. **
** **
*****************************************************************************/
/**********************************************************************
Module Name:
WINREG.C
Routines:
ParseRegistryParameters
ProcessRegistry
Comments:
Parse Windows Registry.
*****************************************************************************/
#include "precomp.h"
#pragma hdrstop
//************************************************************
// MK7RegTabType
//
// One instance of this structure will be used for every configuration
// parameter that this driver supports. The table contains all of the
// relavent information about each parameter: Name, whether or not it is
// required, where it is located in the "Adapter" structure, the size of
// the parameter in bytes, the default value for the parameter, and what
// the minimum and maximum values are for the parameter. In the debug
// version of the driver, this table also contains a field for the ascii
// name of the parameter.
//************************************************************
typedef struct _MK7RegTabType {
NDIS_STRING RegVarName; // variable name text
char *RegAscName; // variable name text
UINT Mandantory; // 1 -> manditory, 0 -> optional
#define MK7OPTIONAL 0
#define MK7MANDATORY 1
UINT FieldOffset; // offset to MK7_ADAPTER field loaded
UINT FieldSize; // size (in bytes) of the field
UINT Default; // default value to use
UINT Min; // minimum value allowed
UINT Max; // maximum value allowed
} MK7RegTabType;
//************************************************************
// Registry Parameters Table
//
// This table contains a list of all of the configuration parameters
// that the driver supports. The driver will attempt to find these
// parameters in the registry and use the registry value for these
// parameters. If the parameter is not found in the registry, then the
// default value is used. This is a way for us to set defaults for
// certain parameters.
//
//************************************************************
MK7RegTabType MK7RegTab[ ] = {
//
// REGISTRY NAME TEXT NAME MAN/OPT OFFSET
// SIZE DEF VAL MIN MAX
//
//#if DBG
// {NDIS_STRING_CONST("Debug"), "Debug", MK7OPTIONAL, MK7_OFFSET(Debug),
// MK7_SIZE(Debug), DBG_NORMAL, 0, 0xffffffff},
//#endif
{NDIS_STRING_CONST("MaxConnectRate"), "MaxConnectRate", MK7OPTIONAL, MK7_OFFSET(MaxConnSpeed),
MK7_SIZE(MaxConnSpeed), 16000000, 9600, 16000000},
{NDIS_STRING_CONST("MinTurnAroundTime"), "MinTurnAroundTime", MK7OPTIONAL, MK7_OFFSET(turnAroundTime_usec),
MK7_SIZE(turnAroundTime_usec), DEFAULT_TURNAROUND_usec, 0, DEFAULT_TURNAROUND_usec},
//
// All the ones from here down are not really necessary except for testing.
//
{NDIS_STRING_CONST("BusNumber"), "BusNumber", MK7OPTIONAL, MK7_OFFSET(BusNumber),
MK7_SIZE(BusNumber), 0, 0, 16},
{NDIS_STRING_CONST("SlotNumber"), "SlotNumber", MK7OPTIONAL, MK7_OFFSET(MKSlot),
MK7_SIZE(MKSlot), 0, 0, 32},
#if DBG
{NDIS_STRING_CONST("Loopback"), "Loopback", MK7OPTIONAL, MK7_OFFSET(LB),
MK7_SIZE(LB), 0, 0, 2},
#endif
{NDIS_STRING_CONST("RingSize"), "RingSize", MK7OPTIONAL, MK7_OFFSET(RingSize),
MK7_SIZE(RingSize), DEF_RING_SIZE, MIN_RING_SIZE, MAX_RING_SIZE},
{NDIS_STRING_CONST("RXRingSize"), "RXRingSize", MK7OPTIONAL, MK7_OFFSET(RegNumRcb),
MK7_SIZE(RegNumRcb), DEF_RXRING_SIZE,MIN_RING_SIZE, DEF_RXRING_SIZE},
{NDIS_STRING_CONST("TXRingSize"), "TXRingSize", MK7OPTIONAL, MK7_OFFSET(RegNumTcb),
MK7_SIZE(RegNumTcb), DEF_TXRING_SIZE,MIN_RING_SIZE, DEF_TXRING_SIZE},
{NDIS_STRING_CONST("ExtraBOFs"), "ExtraBOFs", MK7OPTIONAL, MK7_OFFSET(RegExtraBOFs),
MK7_SIZE(RegExtraBOFs), DEF_EBOFS, MIN_EBOFS, MAX_EBOFS},
{NDIS_STRING_CONST("Speed"), "Speed", MK7OPTIONAL, MK7_OFFSET(RegSpeed),
MK7_SIZE(RegSpeed), 16000000, 4000000, 16000000},
{NDIS_STRING_CONST("BusType"), "BusType", MK7OPTIONAL, MK7_OFFSET(MKBusType),
MK7_SIZE(MKBusType), PCIBUS, PCIBUS, PCIBUS},
{NDIS_STRING_CONST("IoSize"), "IoSize", MK7OPTIONAL, MK7_OFFSET(MKBaseSize),
MK7_SIZE(MKBaseSize), MK7_IO_SIZE, MK7_IO_SIZE, MK7_IO_SIZE},
{NDIS_STRING_CONST("Wireless"), "Wireless", MK7OPTIONAL, MK7_OFFSET(Wireless),
MK7_SIZE(Wireless), 1, 0, 1},
};
#define NUM_REG_PARAM ( sizeof (MK7RegTab) / sizeof (MK7RegTabType) )
//-----------------------------------------------------------------------------
// Procedure: ParseRegistryParameters
//
// Description: This routine will parse all of the parameters out of the
// registry/PROTOCOL.INI, and store the values in the "Adapter"
// Structure. If the parameter is not present in the registry, then the
// default value for the parameter will be placed into the "Adapter"
// structure. This routine also checks the validity of the parameter
// value, and if the value is out of range, the driver will the min/max
// value allowed.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// ConfigHandle - NDIS Configuration Registery handle
//
// Returns:
// NDIS_STATUS_SUCCESS - All mandatory parameters were parsed
// NDIS_STATUS_FAILED - A mandatory parameter was not present
//-----------------------------------------------------------------------------
NDIS_STATUS
ParseRegistryParameters(IN PMK7_ADAPTER Adapter,
IN NDIS_HANDLE ConfigHandle)
{
UINT i;
NDIS_STATUS Status;
MK7RegTabType *RegTab;
UINT value;
PUCHAR fieldPtr;
PNDIS_CONFIGURATION_PARAMETER ReturnedValue;
#if DBG
char ansiRegName[32];
ULONG paramval;
#endif
//****************************************
// Grovel through the registry parameters and aquire all of the values
// stored therein.
//****************************************
for (i=0, RegTab=MK7RegTab; i<NUM_REG_PARAM; i++, RegTab++) {
fieldPtr = ((PUCHAR) Adapter) + RegTab->FieldOffset;
#if DBG
strcpy(ansiRegName, RegTab->RegAscName);
#endif
//****************************************
// Get the configuration value for a specific parameter. Under NT the
// parameters are all read in as DWORDs.
//****************************************
NdisReadConfiguration(&Status,
&ReturnedValue,
ConfigHandle,
&RegTab->RegVarName,
NdisParameterInteger);
//****************************************
// Param in Reg:
// Check that it's w/i the min-max range. If not set it to
// default, else just set to that in the Reg.
//
// Param not in Reg:
// If it's a mandatory param, error out.
// If it's optional (non-mandatory), again use default.
//****************************************
if (Status == NDIS_STATUS_SUCCESS) {
#if DBG
paramval = ReturnedValue->ParameterData.IntegerData;
#endif
if (ReturnedValue->ParameterData.IntegerData < RegTab->Min ||
ReturnedValue->ParameterData.IntegerData > RegTab->Max) {
value = RegTab->Default;
}
else {
value = ReturnedValue->ParameterData.IntegerData;
}
}
else if (RegTab->Mandantory) {
DBGSTR(("Could not find mandantory in registry\n"));
DBGLOG("<= ParseRegistryParameters (ERROR out)", 0);
return (NDIS_STATUS_FAILURE);
}
else { // non-mandatory
value = RegTab->Default;
}
//****************************************
// Store the value in the adapter structure.
//****************************************
switch (RegTab->FieldSize) {
case 1:
*((PUCHAR) fieldPtr) = (UCHAR) value;
break;
case 2:
*((PUSHORT) fieldPtr) = (USHORT) value;
break;
case 4:
*((PULONG) fieldPtr) = (ULONG) value;
break;
default:
DBGSTR(("Bogus field size %d\n", RegTab->FieldSize));
break;
}
}
return (NDIS_STATUS_SUCCESS);
}
//----------------------------------------------------------------------
// Procedure: [ProcessRegistry]
//
// Description: Do all the one time Registry stuff.
//
// Return: NDIS_STATUS_SUCCESS
// (!NDIS_STATUS_SUCCESS)
//----------------------------------------------------------------------
NDIS_STATUS ProcessRegistry(PMK7_ADAPTER Adapter,
NDIS_HANDLE WrapperConfigurationContext)
{
NDIS_STATUS Status;
NDIS_HANDLE ConfigHandle;
PVOID OverrideNetAddress;
ULONG i;
NdisOpenConfiguration(&Status,
&ConfigHandle,
WrapperConfigurationContext);
if (Status != NDIS_STATUS_SUCCESS) {
return (NDIS_STATUS_FAILURE);
}
//****************************************
// Parse all our configuration parameters. Error out if bad
// status returned -- Required param not in Registry.
//****************************************
Status = ParseRegistryParameters(Adapter, ConfigHandle);
if (Status != NDIS_STATUS_SUCCESS) {
NdisCloseConfiguration(ConfigHandle);
return (Status);
}
NdisCloseConfiguration(ConfigHandle);
// Adapter->NumRcb = Adapter->RegNumRcb;
// Adapter->NumTcb = Adapter->RegNumTcb;
Adapter->NumRcb = DEF_RXRING_SIZE;
Adapter->NumTcb = DEF_TXRING_SIZE;
Adapter->NumRpd = CalRpdSize(Adapter->NumRcb);
Adapter->extraBOFsRequired = Adapter->RegExtraBOFs;
return(Status);
}
| 35.095238 | 109 | 0.552433 | [
"object"
] |
2c131c2bc26e9e7e9a52a5afb5597345b8210c90 | 3,514 | h | C | libs/num_theory.h | teacup123123/win_competitive_programming_console | d043e775d836f8400ff4602623a556f292a4754e | [
"MIT"
] | null | null | null | libs/num_theory.h | teacup123123/win_competitive_programming_console | d043e775d836f8400ff4602623a556f292a4754e | [
"MIT"
] | null | null | null | libs/num_theory.h | teacup123123/win_competitive_programming_console | d043e775d836f8400ff4602623a556f292a4754e | [
"MIT"
] | null | null | null | //
// Created by tchang on 2/5/2021.
//
#ifndef CODEJAM_PRIME_LADDER_H
#define CODEJAM_PRIME_LADDER_H
template<class T>
vector <T> unique_pfacs(T in) {
ll n = in;
vector <T> ans;
for (ll p = 2; p * p <= n; p++) {
if (n % p == 0LL) {
while (n % p == 0LL)n /= p;
ans.eb(p);
}
}
if (n != 1)ans.emplace_back(n);
return ans;
}
void smallest_prime_factor_ladder(vi &into) {
trav(e, into)e = INT_MAX;
into[0] = 1;
into[1] = 1;
for (int p = 2; p < sz(into); p++) {
if (into[p] == INT_MAX) {
into[p] = p;
for (int x = 2 * p; x < sz(into); x += p) {
ckmin(into[x], p);
}
}
}
}
int number_of_factors(ll N, vi *smallest_prime_factor = nullptr, vi *ordered_prime_numbers = nullptr) {
/**
* @brief Copies fields of __rhs into this.
* @param N O(sqrt(N))
* @return O(sqrt(N))
*
* O(sqrt(N))
*/
prime_fac_num_complexity:
if (smallest_prime_factor != nullptr and N < smallest_prime_factor->size()) {
map<int, int> decompo;
while (N != 1) {
decompo[(*smallest_prime_factor)[N]]++;
N /= (*smallest_prime_factor)[N];
}
int ans = 1;
trav(kv, decompo)ans *= kv.second + 1;
return ans;
}
log_sz_primes_complexity:
if (ordered_prime_numbers != nullptr) {
map<int, int> decompo;
//divide in reverse order big primes first, until acceleratable if acceleratable
vi &primes = *ordered_prime_numbers;
ll last = primes.back();
if (last * last < N)goto bruteforce_sqrtN_complexity;
while (N != 1) {
//last*last>=N
int a, b;
f0r(_, 2) {
a = -1, b = primes.size() - 1;//bad, good
while (b != a + 1) {
int m = (a + b) / 2;
ll p = primes[m];
if (p * p < (_ ? N : N * N))
a = m;//m bad
else
b = m;//m good
}
if (primes[b] == N)
break;
}
b = b;
for (; b >= 0; b--) {
if (N % primes[b] == 0) {
decompo[primes[b]]++;
N /= primes[b];
break;
}
}
}
int ans = 1;
trav(kv, decompo)ans *= kv.second + 1;
return ans;
}
bruteforce_sqrtN_complexity:
{
ll sq = sqrt(N), ans = 0;
while (sq * sq < N)sq++;
while (sq * sq > N)sq--;
for (ll i = 1; i <= sq; i++) if (N % i == 0) ans += 2;
if (sq * sq == N) ans--;
return ans;
}
}
void demonstration_numfac() {
int until = 2000000;
vi smallest_pf(until + 2);
vi primes;
//start here
smallest_prime_factor_ladder(smallest_pf);
for (int p = 2; p < sz(smallest_pf); p++)if (smallest_pf[p] == p)primes.eb(p);
vi sol, sol2;
tic();
for (int i = 1; i <= until; i++) {
sol2.eb(number_of_factors(i, &smallest_pf));
}
ps(toc());
tic();
for (int i = 1; i <= until; i++) {
sol2[i - 1] = number_of_factors(i, nullptr, &primes);
}
ps(toc());
tic();
for (int i = 1; i <= until; i++) {
sol.eb(number_of_factors(i));
}
ps(toc());
f0r(i, sz(sol))assert(sol[i] == sol2[i]);
}
#endif //CODEJAM_PRIME_LADDER_H
| 26.621212 | 103 | 0.450199 | [
"vector"
] |
2c14e5742cd3d429b69ecf182522b31e12645f36 | 11,172 | h | C | Include/PipelineManagerDX11.h | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | 25 | 2017-08-05T07:29:00.000Z | 2022-02-02T06:28:27.000Z | Include/PipelineManagerDX11.h | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | null | null | null | Include/PipelineManagerDX11.h | zgpxgame/hieroglyph3 | bb1c59d82a69062bb76431b691fbcb381930768a | [
"MIT"
] | 9 | 2018-07-14T08:40:29.000Z | 2021-03-19T08:51:30.000Z | //--------------------------------------------------------------------------------
// This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed
// under the MIT License, available in the root of this distribution and
// at the following URL:
//
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) Jason Zink
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// PipelineManagerDX11
//
//--------------------------------------------------------------------------------
#ifndef PipelineManagerDX11_h
#define PipelineManagerDX11_h
//--------------------------------------------------------------------------------
#include "VertexStageDX11.h"
#include "HullStageDX11.h"
#include "DomainStageDX11.h"
#include "GeometryStageDX11.h"
#include "StreamOutputStageDX11.h"
#include "RasterizerStageDX11.h"
#include "PixelStageDX11.h"
#include "ComputeStageDX11.h"
#include "InputAssemblerStageDX11.h"
#include "OutputMergerStageDX11.h"
#include "GeometryDX11.h"
#include "RenderEffectDX11.h"
#include "ResourceProxyDX11.h"
#include "ResourceDX11.h"
//--------------------------------------------------------------------------------
namespace Glyph3
{
class CommandListDX11;
typedef Microsoft::WRL::ComPtr<ID3DUserDefinedAnnotation> UserDefinedAnnotationComPtr;
class PipelineManagerDX11
{
public:
PipelineManagerDX11();
~PipelineManagerDX11();
// Allow the creator to set the context and feature level
void SetDeviceContext( DeviceContextComPtr pContext, D3D_FEATURE_LEVEL level );
// All of the 'Bind/Unbind' functions below are used to bind various resources to the
// pipeline. Currently only the CS can accept unordered access views. A method is
// provided to apply the resource changes as an optimization, which allows for the
// renderer to cache resource changes between rendering calls if appropriate.
void BindConstantBufferParameter( ShaderType type, RenderParameterDX11* pParam, UINT slot, IParameterManager* pParamManager );
void BindShaderResourceParameter( ShaderType type, RenderParameterDX11* pParam, UINT slot, IParameterManager* pParamManager );
void BindUnorderedAccessParameter( ShaderType type, RenderParameterDX11* pParam, UINT slot, IParameterManager* pParamManager );
void BindSamplerStateParameter( ShaderType type, RenderParameterDX11* pParam, UINT slot, IParameterManager* pParamManager );
void BindShader( ShaderType type, int ID, IParameterManager* pParamManager );
// The pipeline state is managed through the following methods. The user must
// configure each pipeline stage as they want it, and then utilize these Apply
// and Clear methods to manage when the state is actually sent to the API.
//
// The groups of state are split roughly into the following groups:
// 1. Input Resources: These determine the input configuration of the pipeline.
// 2. Pipeline Resources: The state for all processing done inside the pipeline.
// 3. Render Targets: The state for receiving the output of the pipeline.
//
// The changes made to the pipeline resources with the Bind calls are cached and
// applied or cleared all at once with these calls. This reduces the number
// of API function calls needed to configure the pipeline.
void ApplyInputResources();
void ClearInputResources();
void ApplyPipelineResources();
void ClearPipelineResources();
void ClearRenderTargets();
void ApplyRenderTargets();
void ClearPipelineState();
void ClearPipelineSRVs();
// Pipeline execution calls - these are the methods for executing the
// pipeline with the given configuration (supplied by the render effect).
// With the dispatch call, the same configuration is used except that you
// specify the dimensions of the thread groups to instantiate.
void Draw( RenderEffectDX11& effect, GeometryPtr chunk, IParameterManager* pParamManager );
void Draw( RenderEffectDX11& effect, ResourcePtr vb, ResourcePtr ib,
int inputLayout, D3D11_PRIMITIVE_TOPOLOGY primType,
UINT vertexStride, UINT numIndices, IParameterManager* pParamManager);
void DrawNonIndexed( RenderEffectDX11& effect, ResourcePtr vb, int inputLayout,
D3D11_PRIMITIVE_TOPOLOGY primType, UINT vertexStride, UINT vertexCount,
UINT startVertexLocation, IParameterManager* pParamManager);
void DrawInstanced( RenderEffectDX11& effect, GeometryPtr chunk,
ResourcePtr instanceData, UINT instanceDataStride,
UINT numInstances, IParameterManager* pParamManager );
void DrawInstanced( RenderEffectDX11& effect, ResourcePtr vb,
D3D11_PRIMITIVE_TOPOLOGY primType, ResourcePtr ib,
int inputLayout, UINT vertexStride, UINT numIndices,
ResourcePtr instanceData, UINT instanceDataStride,
UINT numInstances, IParameterManager* pParamManager );
void Dispatch( RenderEffectDX11& effect, UINT x, UINT y, UINT z, IParameterManager* pParamManager );
void DispatchIndirect( RenderEffectDX11& effect, ResourcePtr args, UINT offset, IParameterManager* pParamManager );
void DrawIndirect( RenderEffectDX11& effect, ResourcePtr args, UINT offset, int inputLayout,
D3D11_PRIMITIVE_TOPOLOGY primType, UINT vertexStride, IParameterManager* pParamManager);
// These draw calls are thin wrappers around the basic API draw calls. They are intended
// to be used by the PipelineExecutorDX11 subclasses to invoke the pipeline.
void Draw( UINT VertexCount, UINT StartVertex );
void DrawIndexed( UINT IndexCount, UINT StartIndex, int VertexOffset );
void DrawIndexedInstanced( UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation );
void DrawInstancedIndirect( ID3D11Buffer* argsBuffer, UINT offset );
// The pipeline state can be modified with command lists. This allows
// the renderer to generate a command list on a deferred context, and
// then utilize the list to perform rendering on an immediate context.
void GenerateCommandList( CommandListDX11* pList );
void ExecuteCommandList( CommandListDX11* pList );
//--------------------------------------------------------------------------------------
// Each of the following methods are used to modify resources in some way. The user is
// required to understand the implications of using these methods on both immediate
// contexts and deferred contexts - this means for immediate that the command is carried
// out more or less right away (placed in the instruction queue of the driver anyways)
// while the deferred context command goes into a command list to be executed later on.
// Please check to make sure what you are trying to do will work in both contexts!!!
//--------------------------------------------------------------------------------------
// Clear buffers does what it says - the currently bound render target views and depth
// stencil view are cleared to the provided values.
void ClearBuffers( const Vector4f& color, float depth = 1.0f, UINT stencil = 0 );
void ClearColorBuffers( const Vector4f& color );
void ClearDepthStencilBuffers( float depth = 1.0f, UINT stencil = 0 );
// Resources can be mapped in order to manually modify or read their contents. The
// returned structure provides information about the resource including the pitch and
// width to be used in accessing it.
D3D11_MAPPED_SUBRESOURCE MapResource( int index, UINT subresource, D3D11_MAP actions, UINT flags );
void UnMapResource( int index, UINT subresource );
D3D11_MAPPED_SUBRESOURCE MapResource( ResourcePtr pGlyphResource, UINT subresource, D3D11_MAP actions, UINT flags );
void UnMapResource( ResourcePtr pGlyphResource, UINT subresource );
D3D11_MAPPED_SUBRESOURCE MapResource( ResourceDX11* pGlyphResource, UINT subresource, D3D11_MAP actions, UINT flags );
void UnMapResource( ResourceDX11* pGlyphResource, UINT subresource );
// This is an alternative method to mapping for updating resources. In certain
// situations one method may or may not be more efficient than the other, so it is
// worth trying both to see which is more performant in a given situation.
void UpdateSubresource( int rid, UINT DstSubresource, const D3D11_BOX *pDstBox, const void *pSrcData,
UINT SrcRowPitch, UINT SrcDepthPitch );
// Copy from one resource to another resource. Check the documentation for restrictions
// if you get errors when performing the copying.
void CopySubresourceRegion( ResourcePtr DestResource, UINT DstSubresource, UINT DstX, UINT DstY, UINT DstZ,
ResourcePtr SrcResource, UINT SrcSubresource, D3D11_BOX* pSrcBox );
void CopyResource( ResourcePtr DestResource, ResourcePtr SrcResource );
// Resolve a subresource from a MSAA texture to a non-MSAA texture.
void ResolveSubresource ( ResourcePtr DestResource, UINT DstSubresource,
ResourcePtr SrcResource, UINT SrcSubresource,
DXGI_FORMAT format );
// Copy the internal counter variable from a UAV (either from Append/Consume
// functionality, or directly a StructuredBuffer internal counter) to the specified
// output buffer.
void CopyStructureCount( ResourcePtr dest, UINT offset, ResourcePtr uav );
// Pipeline statistics are available through the query objects in D3D11.
// Call start, do some rendering, call end, and then print the results to
// a string and either log them or display them.
void StartPipelineStatistics( );
void EndPipelineStatistics( );
std::wstring PrintPipelineStatistics( );
// Provide the ability to set markers and event notifications for use in a debugging
// tool such as the Graphics Debugger in VS2012.
void BeginEvent( std::wstring& name );
void EndEvent();
void SetMarker( std::wstring& name );
void SaveTextureScreenShot( int ID, std::wstring filename );
ID3D11DeviceContext* GetDeviceContext();
D3D_FEATURE_LEVEL m_FeatureLevel;
DeviceContextComPtr m_pContext;
UserDefinedAnnotationComPtr m_pAnnotation;
static const int NumQueries = 3;
int m_iCurrentQuery;
QueryComPtr m_Queries[NumQueries];
D3D11_QUERY_DATA_PIPELINE_STATISTICS m_PipelineStatsData;
// The shader stage resources are managed by these classes.
VertexStageDX11 VertexShaderStage;
HullStageDX11 HullShaderStage;
DomainStageDX11 DomainShaderStage;
GeometryStageDX11 GeometryShaderStage;
PixelStageDX11 PixelShaderStage;
ComputeStageDX11 ComputeShaderStage;
// Each of the shader stages are stored in array that is indexed by the shader
// type enumeration for fast access.
ShaderStageDX11* ShaderStages[6];
InputAssemblerStageDX11 InputAssemblerStage;
StreamOutputStageDX11 StreamOutputStage;
RasterizerStageDX11 RasterizerStage;
OutputMergerStageDX11 OutputMergerStage;
};
};
#endif // PipelineManagerDX11_h
| 44.86747 | 155 | 0.712675 | [
"render"
] |
2c1c97c81dbe9440f85298e358d07cb0e16d75da | 439 | h | C | test/collections.h | BrainTwister/record | 3fe88f18fa4b4e5f1f10879711e8ef866a13d2c5 | [
"MIT"
] | 3 | 2018-05-08T20:37:38.000Z | 2019-12-16T09:03:45.000Z | test/collections.h | BrainTwister/record | 3fe88f18fa4b4e5f1f10879711e8ef866a13d2c5 | [
"MIT"
] | 1 | 2018-05-17T11:44:56.000Z | 2018-05-17T11:44:56.000Z | test/collections.h | BrainTwister/record | 3fe88f18fa4b4e5f1f10879711e8ef866a13d2c5 | [
"MIT"
] | null | null | null | #pragma once
#include "BrainTwister/Record.h"
#include <list>
#include <vector>
BRAINTWISTER_RECORD(Collection1, \
((int, i, 0)) \
((double, d, 0.0)) \
((std::string, s, "foo")) \
)
BRAINTWISTER_RECORD(Collection2, \
((std::vector<int>, v1, std::vector<int>())) \
((std::vector<Collection1>, v2, std::vector<Collection1>())) \
)
BRAINTWISTER_RECORD(Collection3, \
((std::list<int>, list, std::list<int>())) \
)
| 20.904762 | 66 | 0.612756 | [
"vector"
] |
2c20952d28cf1e74ab2718f79c8ac58fe81890cf | 8,090 | h | C | src/core/provider.h | AliAzG/triton-inference-server | fbce250035d049d13f32c362e2d76a5cb787da51 | [
"BSD-3-Clause"
] | null | null | null | src/core/provider.h | AliAzG/triton-inference-server | fbce250035d049d13f32c362e2d76a5cb787da51 | [
"BSD-3-Clause"
] | null | null | null | src/core/provider.h | AliAzG/triton-inference-server | fbce250035d049d13f32c362e2d76a5cb787da51 | [
"BSD-3-Clause"
] | 1 | 2021-06-09T11:16:23.000Z | 2021-06-09T11:16:23.000Z | // Copyright (c) 2018-2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#if defined(TRTIS_ENABLE_HTTP) || defined(TRTIS_ENABLE_METRICS)
#include <event2/buffer.h>
#endif
#include "src/core/api.pb.h"
#include "src/core/constants.h"
#include "src/core/grpc_service.pb.h"
#include "src/core/infer_request.h"
#include "src/core/memory.h"
#include "src/core/model_config.h"
#include "src/core/status.h"
#include "src/core/tritonserver.h"
#include "src/core/trtserver.h"
namespace nvidia { namespace inferenceserver {
class InferenceBackend;
class LabelProvider;
//
// Provide support for reporting inference response outputs and
// response meta-data
//
class InferResponseProvider {
public:
using SecondaryLabelProvider =
std::pair<std::string, std::shared_ptr<LabelProvider>>;
using SecondaryLabelProviderMap =
std::unordered_map<std::string, SecondaryLabelProvider>;
static Status Create(
const std::shared_ptr<InferenceRequest>& irequest,
const std::shared_ptr<LabelProvider>& label_provider,
TRTSERVER_ResponseAllocator* allocator,
TRTSERVER_ResponseAllocatorAllocFn_t alloc_fn, void* alloc_userp,
TRTSERVER_ResponseAllocatorReleaseFn_t release_fn,
const uint32_t protocol_version,
std::shared_ptr<InferResponseProvider>* infer_provider);
static Status Create(
const std::shared_ptr<InferenceRequest>& irequest,
const std::shared_ptr<LabelProvider>& label_provider,
TRITONSERVER_ResponseAllocator* allocator,
TRITONSERVER_ResponseAllocatorAllocFn_t alloc_fn, void* alloc_userp,
TRITONSERVER_ResponseAllocatorReleaseFn_t release_fn,
const uint32_t protocol_version,
std::shared_ptr<InferResponseProvider>* infer_provider);
~InferResponseProvider();
// Get the full response header for this inference request.
const InferResponseHeader& ResponseHeader() const;
// Get a mutuable full response header for this inference request.
InferResponseHeader* MutableResponseHeader();
// Return true if this provider requires a named output.
bool RequiresOutput(const std::string& name);
// Get a buffer to store results for a named output. Must be called
// exactly once for each output that is being returned for the
// request. The output must be listed in the request header.
Status AllocateOutputBuffer(
const std::string& name, void** content, size_t content_byte_size,
const std::vector<int64_t>& content_shape,
const TRTSERVER_Memory_Type preferred_memory_type,
const int64_t preferred_memory_type_id,
TRTSERVER_Memory_Type* actual_memory_type,
int64_t* actual_memory_type_id);
// Get the address and byte-size of an output buffer. Error is
// returned if the buffer is not already allocated.
Status OutputBufferContents(
const std::string& name, const void** content, size_t* content_byte_size,
TRTSERVER_Memory_Type* memory_type, int64_t* memory_type_id) const;
// Get the address and byte-size of an output buffer. Error is
// returned if the buffer is not already allocated.
Status OutputBufferContents(
const std::string& name, const void** content, size_t* content_byte_size,
TRITONSERVER_Memory_Type* memory_type, int64_t* memory_type_id) const;
// Get the shape of an output buffer. Error is
// returned if the buffer is not already allocated.
Status OutputShape(
const std::string& name, const int64_t** shape,
uint64_t* dim_count) const;
// Get label provider.
const std::shared_ptr<LabelProvider>& GetLabelProvider() const
{
return label_provider_;
}
// Get secondary label provider. Return true if the secondary provider for
// the 'name' is found. False otherwise,
bool GetSecondaryLabelProvider(
const std::string& name, SecondaryLabelProvider* provider);
// Set secondary label provider.
void SetSecondaryLabelProvider(
const std::string& name, const SecondaryLabelProvider& provider);
// Finalize response based on a backend.
Status FinalizeResponse(const InferenceBackend& is);
private:
InferResponseProvider(
const std::shared_ptr<InferenceRequest>& irequest,
const std::shared_ptr<LabelProvider>& label_provider,
TRTSERVER_ResponseAllocator* allocator,
TRTSERVER_ResponseAllocatorAllocFn_t alloc_fn, void* alloc_userp,
TRTSERVER_ResponseAllocatorReleaseFn_t release_fn,
const uint32_t protocol_version);
InferResponseProvider(
const std::shared_ptr<InferenceRequest>& irequest,
const std::shared_ptr<LabelProvider>& label_provider,
TRITONSERVER_ResponseAllocator* allocator,
TRITONSERVER_ResponseAllocatorAllocFn_t alloc_fn, void* alloc_userp,
TRITONSERVER_ResponseAllocatorReleaseFn_t release_fn,
const uint32_t protocol_version);
std::shared_ptr<InferenceRequest> irequest_;
// Map from output name to the InferenceRequest output information
// for that output.
std::unordered_map<std::string, const InferenceRequest::RequestedOutput>
output_map_;
// Information about each output.
struct Output {
std::string name_;
std::vector<int64_t> shape_;
size_t cls_count_;
void* ptr_;
size_t byte_size_;
TRTSERVER_Memory_Type memory_type_;
int64_t memory_type_id_;
// Created buffer for non-RAW results
std::unique_ptr<char[]> buffer_;
// Classification contents in binary format (length bytes + raw data)
std::vector<char> cls_contents_;
void* release_buffer_;
void* release_userp_;
};
// Ordered list of outputs as they "added" by AllocateOutputBuffer().
std::vector<Output> outputs_;
// label provider used to generate classification results.
std::shared_ptr<LabelProvider> label_provider_;
// Map from output name to external label provider and name for that provider.
// This map should only be non-empty if the response provider is for models
// that doesn't provide labels directly, i.e. ensemble models.
SecondaryLabelProviderMap secondary_label_provider_map_;
TRTSERVER_ResponseAllocator* allocator_;
TRTSERVER_ResponseAllocatorAllocFn_t alloc_fn_;
void* alloc_userp_;
TRTSERVER_ResponseAllocatorReleaseFn_t release_fn_;
bool using_triton_;
TRITONSERVER_ResponseAllocator* triton_allocator_;
TRITONSERVER_ResponseAllocatorAllocFn_t triton_alloc_fn_;
TRITONSERVER_ResponseAllocatorReleaseFn_t triton_release_fn_;
// FIXMEV2 use to differentiate how outputs should be represented
const uint32_t protocol_version_;
InferResponseHeader response_header_;
};
}} // namespace nvidia::inferenceserver
| 39.656863 | 80 | 0.764524 | [
"shape",
"vector"
] |
2c232898b9339551ffc180e72f57923dc1542c23 | 4,116 | c | C | kernel/linux-5.4/arch/powerpc/crypto/crc32c-vpmsum_glue.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 27 | 2021-10-04T18:56:52.000Z | 2022-03-28T08:23:06.000Z | kernel/linux-5.4/arch/powerpc/crypto/crc32c-vpmsum_glue.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 1 | 2022-01-12T04:05:36.000Z | 2022-01-16T15:48:42.000Z | kernel/linux-5.4/arch/powerpc/crypto/crc32c-vpmsum_glue.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | // SPDX-License-Identifier: GPL-2.0-only
#include <linux/crc32.h>
#include <crypto/internal/hash.h>
#include <crypto/internal/simd.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/cpufeature.h>
#include <asm/simd.h>
#include <asm/switch_to.h>
#define CHKSUM_BLOCK_SIZE 1
#define CHKSUM_DIGEST_SIZE 4
#define VMX_ALIGN 16
#define VMX_ALIGN_MASK (VMX_ALIGN-1)
#define VECTOR_BREAKPOINT 512
u32 __crc32c_vpmsum(u32 crc, unsigned char const *p, size_t len);
static u32 crc32c_vpmsum(u32 crc, unsigned char const *p, size_t len)
{
unsigned int prealign;
unsigned int tail;
if (len < (VECTOR_BREAKPOINT + VMX_ALIGN) || !crypto_simd_usable())
return __crc32c_le(crc, p, len);
if ((unsigned long)p & VMX_ALIGN_MASK) {
prealign = VMX_ALIGN - ((unsigned long)p & VMX_ALIGN_MASK);
crc = __crc32c_le(crc, p, prealign);
len -= prealign;
p += prealign;
}
if (len & ~VMX_ALIGN_MASK) {
preempt_disable();
pagefault_disable();
enable_kernel_altivec();
crc = __crc32c_vpmsum(crc, p, len & ~VMX_ALIGN_MASK);
disable_kernel_altivec();
pagefault_enable();
preempt_enable();
}
tail = len & VMX_ALIGN_MASK;
if (tail) {
p += len & ~VMX_ALIGN_MASK;
crc = __crc32c_le(crc, p, tail);
}
return crc;
}
static int crc32c_vpmsum_cra_init(struct crypto_tfm *tfm)
{
u32 *key = crypto_tfm_ctx(tfm);
*key = ~0;
return 0;
}
/*
* Setting the seed allows arbitrary accumulators and flexible XOR policy
* If your algorithm starts with ~0, then XOR with ~0 before you set
* the seed.
*/
static int crc32c_vpmsum_setkey(struct crypto_shash *hash, const u8 *key,
unsigned int keylen)
{
u32 *mctx = crypto_shash_ctx(hash);
if (keylen != sizeof(u32)) {
crypto_shash_set_flags(hash, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
*mctx = le32_to_cpup((__le32 *)key);
return 0;
}
static int crc32c_vpmsum_init(struct shash_desc *desc)
{
u32 *mctx = crypto_shash_ctx(desc->tfm);
u32 *crcp = shash_desc_ctx(desc);
*crcp = *mctx;
return 0;
}
static int crc32c_vpmsum_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
u32 *crcp = shash_desc_ctx(desc);
*crcp = crc32c_vpmsum(*crcp, data, len);
return 0;
}
static int __crc32c_vpmsum_finup(u32 *crcp, const u8 *data, unsigned int len,
u8 *out)
{
*(__le32 *)out = ~cpu_to_le32(crc32c_vpmsum(*crcp, data, len));
return 0;
}
static int crc32c_vpmsum_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_vpmsum_finup(shash_desc_ctx(desc), data, len, out);
}
static int crc32c_vpmsum_final(struct shash_desc *desc, u8 *out)
{
u32 *crcp = shash_desc_ctx(desc);
*(__le32 *)out = ~cpu_to_le32p(crcp);
return 0;
}
static int crc32c_vpmsum_digest(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_vpmsum_finup(crypto_shash_ctx(desc->tfm), data, len,
out);
}
static struct shash_alg alg = {
.setkey = crc32c_vpmsum_setkey,
.init = crc32c_vpmsum_init,
.update = crc32c_vpmsum_update,
.final = crc32c_vpmsum_final,
.finup = crc32c_vpmsum_finup,
.digest = crc32c_vpmsum_digest,
.descsize = sizeof(u32),
.digestsize = CHKSUM_DIGEST_SIZE,
.base = {
.cra_name = "crc32c",
.cra_driver_name = "crc32c-vpmsum",
.cra_priority = 200,
.cra_flags = CRYPTO_ALG_OPTIONAL_KEY,
.cra_blocksize = CHKSUM_BLOCK_SIZE,
.cra_ctxsize = sizeof(u32),
.cra_module = THIS_MODULE,
.cra_init = crc32c_vpmsum_cra_init,
}
};
static int __init crc32c_vpmsum_mod_init(void)
{
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
return crypto_register_shash(&alg);
}
static void __exit crc32c_vpmsum_mod_fini(void)
{
crypto_unregister_shash(&alg);
}
module_cpu_feature_match(PPC_MODULE_FEATURE_VEC_CRYPTO, crc32c_vpmsum_mod_init);
module_exit(crc32c_vpmsum_mod_fini);
MODULE_AUTHOR("Anton Blanchard <anton@samba.org>");
MODULE_DESCRIPTION("CRC32C using vector polynomial multiply-sum instructions");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CRYPTO("crc32c");
MODULE_ALIAS_CRYPTO("crc32c-vpmsum");
| 23.386364 | 80 | 0.724004 | [
"vector"
] |
2c2379406572e6396a4e54f9838148817f5d1fa5 | 3,191 | c | C | kernel/main.c | richardchien/chcore-lab | c15b482b47a7d50ad1018ed946cf6f074fe8d4a2 | [
"MulanPSL-1.0"
] | 7 | 2021-05-14T16:37:53.000Z | 2021-12-01T13:25:33.000Z | kernel/main.c | fakeanalysier/chcore-lab | c15b482b47a7d50ad1018ed946cf6f074fe8d4a2 | [
"MulanPSL-1.0"
] | null | null | null | kernel/main.c | fakeanalysier/chcore-lab | c15b482b47a7d50ad1018ed946cf6f074fe8d4a2 | [
"MulanPSL-1.0"
] | 5 | 2020-12-02T13:35:58.000Z | 2022-01-03T03:36:17.000Z | /*
* Copyright (c) 2020 Institute of Parallel And Distributed Systems (IPADS), Shanghai Jiao Tong University (SJTU)
* OS-Lab-2020 (i.e., ChCore) is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
* http://license.coscl.org.cn/MulanPSL
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
* PURPOSE.
* See the Mulan PSL v1 for more details.
*/
#include <common/kprint.h>
#include <common/lock.h>
#include <lib/machine.h>
#include <common/macro.h>
#include <common/mm.h>
#include <common/smp.h>
#include <common/uart.h>
#include <common/vars.h>
#include <exception/exception.h>
#include <ipc/ipc.h>
#include <common/types.h>
#include <process/thread.h>
#include <sched/sched.h>
#include <tests/tests.h>
ALIGN(STACK_ALIGNMENT)
char kernel_stack[PLAT_CPU_NUM][KERNEL_STACK_SIZE];
int mon_backtrace();
// Test the stack backtrace function (lab 1 only)
__attribute__((optimize("O1"))) void test_backtrace(long x)
{
kinfo("entering test_backtrace %d\n", x);
if (x > 0)
test_backtrace(x - 1);
else
mon_backtrace(0, 0, 0);
kinfo("leaving test_backtrace %d\n", x);
}
void main(void *addr)
{
/* Init uart */
uart_init();
kinfo("[ChCore] uart init finished\n");
kinfo("6828 decimal is %x hex!\n", 6828);
test_backtrace(5);
mm_init(NULL);
kinfo("mm init finished\n");
/* Init exception vector */
exception_init();
kinfo("[ChCore] interrupt init finished\n");
/**
* Lab 4
* Initialize and then acquire the big kernel lock.
*/
kernel_lock_init();
lock_kernel();
kinfo("[ChCore] lock init finished\n");
/* Init scheduler with specified policy. */
sched_init(&rr);
kinfo("[ChCore] sched init finished\n");
#ifndef TEST
/* We will run the kernel test if you do not type make bin=xxx */
init_test();
#endif
/* Other cores are busy looping on the addr, wake up those cores */
enable_smp_cores(addr);
kinfo("[ChCore] boot multicore finished\n");
#ifdef TEST
/* Create initial thread here*/
process_create_root(TEST);
kinfo("[ChCore] root thread init finished\n");
#else
/* We will run the kernel test if you do not type make bin=xxx */
run_test(true);
break_point();
BUG("No given TEST!");
#endif
/**
* Where the pimary CPU first returns to the user mode
* Leave the scheduler to do its job
*/
sched();
eret_to_thread(switch_context());
/* Should provide panic and use here */
BUG("[FATAL] Should never be here!\n");
}
void secondary_start(void)
{
kinfo("AP %u is activated!\n", smp_get_cpu_id());
exception_init_per_cpu();
/**
* Lab 4
* Inform the BSP at last to start cpu one by one
* Hints: use cpu_status
*/
cpu_status[smp_get_cpu_id()] = cpu_run;
#ifndef TEST
run_test(false);
#endif
/**
* Lab 4
* Acquire the big kernel lock
*/
lock_kernel();
/* Where the AP first returns to the user mode */
sched();
eret_to_thread(switch_context());
/* Should provide panic and use here */
BUG("[FATAL] Should never be here!\n");
}
| 23.813433 | 113 | 0.69414 | [
"vector"
] |
2c296eba756711971ebacde5f1f2c6b9b9bfbc65 | 21,512 | h | C | client/compile_service.h | uazo/goma-client | 1cffeb7978539ac2fee02257ca0a95a05b4c6cc0 | [
"BSD-3-Clause"
] | null | null | null | client/compile_service.h | uazo/goma-client | 1cffeb7978539ac2fee02257ca0a95a05b4c6cc0 | [
"BSD-3-Clause"
] | null | null | null | client/compile_service.h | uazo/goma-client | 1cffeb7978539ac2fee02257ca0a95a05b4c6cc0 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2011 The Goma 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 DEVTOOLS_GOMA_CLIENT_COMPILE_SERVICE_H_
#define DEVTOOLS_GOMA_CLIENT_COMPILE_SERVICE_H_
#include <stdint.h>
#include <deque>
#include <map>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "atomic_stats_counter.h"
#include "basictypes.h"
#include "compiler_info.h"
#include "compiler_info_builder.h"
#include "compiler_info_cache.h"
#include "compiler_info_state.h"
#include "compiler_type_specific.h"
#include "compiler_type_specific_collection.h"
#include "get_compiler_info_param.h"
#include "lockhelper.h"
#include "rbe/stats_manager.h"
#include "subprocess_option_setter.h"
#include "threadpool_http_server.h"
#include "watchdog.h"
#include "worker_thread.h"
#include "worker_thread_manager.h"
namespace devtools_goma {
class BlobClient;
class CompileTask;
class CompilerFlags;
class CompilerProxyHistogram;
class ExecReq;
class ExecResp;
class ExecServiceClient;
class FileServiceBlobClient;
class FileServiceHttpClient;
class FileHashCache;
class GomaStats;
class HttpClient;
class HttpRPC;
class LogServiceClient;
class MultiFileStore;
class RpcController;
// CompileService provides ExecService API in compiler proxy.
// It is proxy to goma service's ExecService API and FileService API, which is
// managed by CompileTask.
// It also provides the followings:
// configurations for compile task.
// remote APIs: http_rpc, file_service.
// stats histograms.
// global data shared by all compile tasks.
// file hash cache, local compiler path, compiler info,
// command version mismatches.
class CompileService {
public:
enum ForcedFallbackReasonInSetup {
kFailToParseFlags,
kNoRemoteCompileSupported,
kHTTPDisabled,
kFailToGetCompilerInfo,
kCompilerDisabled,
kRequestedByUser,
kFailToUpdateRequiredFiles,
kNumForcedFallbackReasonInSetup,
};
enum HumanReadability {
kFastHumanUnreadable,
kHumanReadable,
};
CompileService(WorkerThreadManager* wm, int compiler_info_pool);
~CompileService();
WorkerThreadManager* wm() { return wm_; }
CompilerTypeSpecificCollection* compiler_type_specific_collection() {
return compiler_type_specific_collection_.get();
}
// Configurations.
void SetActiveTaskThrottle(int max_active_tasks);
void SetCompileTaskHistorySize(int max_finished_tasks,
int max_failed_tasks,
int max_long_tasks);
const std::string& username() const { return username_; }
const std::string& nodename() const { return nodename_; }
const std::string& service_account_id() const { return service_account_id_; }
void SetServiceAccountId(std::string account) LOCKS_EXCLUDED(id_mu_);
const std::string& oauth2_email() const LOCKS_EXCLUDED(id_mu_) {
AUTO_SHARED_LOCK(lock, &id_mu_);
return oauth2_email_;
}
void SetOAuth2Email(std::string email);
absl::Time start_time() const { return start_time_; }
const std::string& compiler_proxy_id_prefix() const {
return compiler_proxy_id_prefix_;
}
void SetCompilerProxyIdPrefix(const std::string& prefix);
void SetSubProcessOptionSetter(
std::unique_ptr<SubProcessOptionSetter> option_setter);
void SetHttpClient(std::unique_ptr<HttpClient> http_client);
HttpClient* http_client() const { return http_client_.get(); }
void SetHttpRPC(std::unique_ptr<HttpRPC> http_rpc);
HttpRPC* http_rpc() const { return http_rpc_.get(); }
void SetExecServiceClient(
std::unique_ptr<ExecServiceClient> exec_service_client);
ExecServiceClient* exec_service_client() const {
return exec_service_client_.get();
}
void SetMultiFileStore(std::unique_ptr<MultiFileStore> multi_file_store);
MultiFileStore* multi_file_store() const {
return multi_file_store_.get();
}
void SetFileServiceHttpClient(
std::unique_ptr<FileServiceHttpClient> file_service);
BlobClient* blob_client() const;
FileHashCache* file_hash_cache() const { return file_hash_cache_.get(); }
CompilerProxyHistogram* histogram() const { return histogram_.get(); }
void StartIncludeProcessorWorkers(int num_threads);
int include_processor_pool() const { return include_processor_pool_; }
void SetLogServiceClient(
std::unique_ptr<LogServiceClient> log_service_client);
LogServiceClient* log_service() const { return log_service_client_.get(); }
void SetWatchdog(std::unique_ptr<Watchdog> watchdog,
const std::vector<std::string>& goma_ipc_env);
void WatchdogStart(ThreadpoolHttpServer* server, int count) {
watchdog_->Start(server, count);
}
void CheckLongActiveTasks();
void RunCheckLongActiveTasks();
void StartCheckLongActiveTasks(absl::Duration interval,
absl::Duration threshold);
void SetNeedToSendContent(bool need_to_send_content) {
need_to_send_content_ = need_to_send_content;
}
bool need_to_send_content() const { return need_to_send_content_; }
void SetNewFileThresholdDuration(absl::Duration threshold) {
new_file_threshold_duration_ = threshold;
}
absl::Duration new_file_threshold_duration() const {
return new_file_threshold_duration_;
}
void SetEnableGchHack(bool enable) { enable_gch_hack_ = enable; }
bool enable_gch_hack() const { return enable_gch_hack_; }
void SetUseRelativePathsInArgv(bool use_relative_paths_in_argv) {
use_relative_paths_in_argv_ = use_relative_paths_in_argv;
}
bool use_relative_paths_in_argv() const {
return use_relative_paths_in_argv_;
}
void SetSendExpectedOutputs(bool send_expected_outputs) {
send_expected_outputs_ = send_expected_outputs;
}
bool send_expected_outputs() const {
return send_expected_outputs_;
}
void SetSendCompilerBinaryAsInput(bool flag) {
send_compiler_binary_as_input_ = flag;
}
bool send_compiler_binary_as_input() const {
return send_compiler_binary_as_input_;
}
void SetUseUserSpecifiedPathForSubprograms(bool flag) {
use_user_specified_path_for_subprograms_ = flag;
}
bool use_user_specified_path_for_subprograms() const {
return use_user_specified_path_for_subprograms_;
}
void SetCommandCheckLevel(const std::string& level) {
command_check_level_ = level;
}
const std::string& command_check_level() const {
return command_check_level_;
}
void SetHermetic(bool hermetic) {
hermetic_ = hermetic;
}
bool hermetic() const { return hermetic_; }
void SetHermeticFallback(bool fallback) {
hermetic_fallback_ = fallback;
}
bool hermetic_fallback() const { return hermetic_fallback_; }
void SetDontKillSubprocess(bool dont_kill_subprocess) {
dont_kill_subprocess_ = dont_kill_subprocess;
}
bool dont_kill_subprocess() const { return dont_kill_subprocess_; }
void SetMaxSubProcsPending(int max_subprocs_pending) {
max_subprocs_pending_ = max_subprocs_pending;
}
int max_subprocs_pending() const { return max_subprocs_pending_; }
void SetLocalRunPreference(int local_run_preference) {
local_run_preference_ = local_run_preference;
}
int local_run_preference() const { return local_run_preference_; }
void SetLocalRunForFailedInput(bool local_run_for_failed_input) {
local_run_for_failed_input_ = local_run_for_failed_input;
}
bool local_run_for_failed_input() const {
return local_run_for_failed_input_;
}
void SetLocalRunDelay(absl::Duration local_run_delay) {
local_run_delay_ = local_run_delay;
}
absl::Duration local_run_delay() const { return local_run_delay_; }
void SetStoreLocalRunOutput(bool store_local_run_output) {
store_local_run_output_ = store_local_run_output;
}
bool store_local_run_output() const { return store_local_run_output_; }
void SetShouldFailForUnsupportedCompilerFlag(bool f) {
should_fail_for_unsupported_compiler_flag_ = f;
}
bool should_fail_for_unsupported_compiler_flag() const {
return should_fail_for_unsupported_compiler_flag_;
}
void SetEnableCWDNormalization(bool b) { enable_cwd_normalization_ = b; }
bool enable_cwd_normalization() const { return enable_cwd_normalization_; }
void SetFailFast(bool f) { fail_fast_ = f; }
bool fail_fast() const { return fail_fast_; }
void SetTmpDir(const std::string& tmp_dir) { tmp_dir_ = tmp_dir; }
const std::string& tmp_dir() const { return tmp_dir_; }
void SetTimeouts(const std::vector<absl::Duration>& timeouts) {
timeouts_ = timeouts;
}
const std::vector<absl::Duration>& timeouts() const { return timeouts_; }
// Allow to send info. when this function is called.
// All method that use username() and nodename() should check the flag first.
void AllowToSendUserInfo() { can_send_user_info_ = true; }
bool CanSendUserInfo() const { return can_send_user_info_; }
void SetAllowedNetworkErrorDuration(absl::Duration duration) {
allowed_network_error_duration_ = duration;
}
absl::optional<absl::Duration> AllowedNetworkErrorDuration() const {
return allowed_network_error_duration_;
}
void SetMaxActiveFailFallbackTasks(int num) {
max_active_fail_fallback_tasks_ = num;
}
void SetAllowedMaxActiveFailFallbackDuration(absl::Duration duration) {
allowed_max_active_fail_fallback_duration_ = duration;
}
void SetMaxCompilerDisabledTasks(int num) {
max_compiler_disabled_tasks_ = num;
}
// ExecService API.
// Starts new CompileTask. done will be called on the same thread.
void Exec(RpcController* rpc,
const ExecReq& exec_req,
ExecResp* exec_resp,
OneshotClosure* done);
// Called when CompileTask is finished.
void CompileTaskDone(CompileTask* task);
// Requests to quit service.
void Quit();
bool quit() const;
// Waits for all tasks finish.
void Wait();
bool DumpTask(int task_id, std::string* out);
bool DumpTaskRequest(int task_id, std::string* message);
// Dump the tasks whose state is active or frozen time stamp is after |after|.
void DumpToJson(Json::Value* json, absl::Time after);
void DumpStats(std::ostringstream* ss);
void DumpStatsToFile(const std::string& filename);
// Dump stats in json form (converted from GomaStatzStats).
void DumpStatsJson(std::string* json_string, HumanReadability human_readable);
Json::Value DumpRbeStats() const;
void ClearTasks();
// Finds local compiler for |basename| invoked by |gomacc_path| at |cwd|
// from |local_path|, and sets the local compiler's path in
// |local_compiler_path| and PATH that goma dir is removed in
// |no_goma_local_path|.
// If |local_compiler_path| is given (and |basename| may be full path),
// it just checks |local_compiler_path| is not gomacc.
// Returns true if it finds local compiler.
// *local_compiler_path returned from this is not be gomacc.
// |pathext| should only be given on Windows, which represents PATHEXT
// environment variable.
bool FindLocalCompilerPath(const std::string& gomacc_path,
const std::string& basename,
const std::string& cwd,
const std::string& local_path,
const std::string& pathext,
std::string* local_compiler_path,
std::string* no_goma_local_path);
void GetCompilerInfo(GetCompilerInfoParam* param,
OneshotClosure* callback);
bool DisableCompilerInfo(CompilerInfoState* state,
const std::string& disabled_reason);
void DumpCompilerInfo(std::ostringstream* ss);
bool RecordCommandSpecVersionMismatch(
const std::string& exec_command_version_mismatch);
bool RecordCommandSpecBinaryHashMismatch(
const std::string& exec_command_binary_hash_mismatch);
bool RecordSubprogramMismatch(const std::string& subprogram_mismatch);
// Record |error_message| is logged with LOG(ERROR) or LOG(WARNING).
// If |is_error| is true, logged to LOG(ERROR), otherwise LOG(WARNING).
// Statistics would be kept in CompileService.
void RecordErrorToLog(const std::string& error_message, bool is_error);
// Record |error_message| is sent to gomacc as GOMA Error.
// Statistics would be kept in CompileService.
void RecordErrorsToUser(const std::vector<std::string>& error_messages);
// Records result for inputs.
void RecordInputResult(const std::vector<std::string>& inputs, bool success);
// Returns true if RecordInputResult recorded any of inputs as not succuess
// before.
bool ContainFailedInput(const std::vector<std::string>& inputs) const;
void SetMaxSumOutputSize(size_t size) LOCKS_EXCLUDED(buf_mu_) {
AUTO_EXCLUSIVE_LOCK(lock, &buf_mu_);
max_sum_output_size_ = size;
}
// Acquire output buffer in buf for filesize. buf must be empty.
// Returns true when succeeded and buf would have filesize buffer.
// Returns false otherwise, and buf remains empty.
bool AcquireOutputBuffer(size_t filesize, std::string* buf)
LOCKS_EXCLUDED(buf_mu_);
// Release output buffer acquired by AcquireOutputBuffer.
// filesize and buf should be the same with AcquireOutputBuffer.
void ReleaseOutputBuffer(size_t filesize, std::string* buf)
LOCKS_EXCLUDED(buf_mu_);
// Records output file is renamed or not.
void RecordOutputRename(bool rename);
// Returns duration to delay subprocess setup.
absl::Duration GetEstimatedSubprocessDelayTime();
void DumpErrorStatus(std::ostringstream* ss);
// Returns false if it reached max_active_fail_fallback_tasks_.
bool IncrementActiveFailFallbackTasks();
void RecordForcedFallbackInSetup(ForcedFallbackReasonInSetup r);
private:
typedef std::pair<GetCompilerInfoParam*, OneshotClosure*> CompilerInfoWaiter;
typedef std::vector<CompilerInfoWaiter> CompilerInfoWaiterList;
// Called when reply from Exec.
void ExecDone(WorkerThread::ThreadId thread_id, OneshotClosure* done);
bool FindLocalCompilerPathUnlocked(const std::string& key,
const std::string& key_cwd,
std::string* local_compiler_path,
std::string* no_goma_local_path) const
SHARED_LOCKS_REQUIRED(compiler_mu_);
bool FindLocalCompilerPathAndUpdate(const std::string& key,
const std::string& key_cwd,
const std::string& gomacc_path,
const std::string& basename,
const std::string& cwd,
const std::string& local_path,
const std::string& pathext,
std::string* local_compiler_path,
std::string* no_goma_local_path);
void ClearTasksUnlocked();
const CompileTask* FindTaskByIdUnlocked(int task_id, bool include_active);
void DumpCommonStatsUnlocked(GomaStats* stats) SHARED_LOCKS_REQUIRED(buf_mu_)
EXCLUSIVE_LOCKS_REQUIRED(mu_);
void GetCompilerInfoInternal(GetCompilerInfoParam* param,
OneshotClosure* callback);
WorkerThreadManager* wm_;
mutable Lock quit_mu_;
bool quit_ GUARDED_BY(quit_mu_) = false;
mutable Lock task_id_mu_;
int task_id_ GUARDED_BY(task_id_mu_) = 0;
// TODO: add thread annotation
mutable Lock mu_; // protects other fields.
ConditionVariable cond_;
int max_active_tasks_;
int max_finished_tasks_;
int max_failed_tasks_;
int max_long_tasks_;
std::deque<CompileTask*> pending_tasks_;
absl::flat_hash_set<CompileTask*> active_tasks_;
std::deque<CompileTask*> finished_tasks_;
std::deque<CompileTask*> failed_tasks_;
// long_tasks_ is a heap compared by task's handler time.
// A task with the shortest handler time would come to front of long_tasks_.
std::vector<CompileTask*> long_tasks_;
// CompileTask's input that failed.
mutable ReadWriteLock failed_inputs_mu_;
absl::flat_hash_set<std::string> failed_inputs_ GUARDED_BY(failed_inputs_mu_);
// TODO: add thread annotations to others.
mutable ReadWriteLock id_mu_;
std::string oauth2_email_ GUARDED_BY(id_mu_);
std::string username_;
std::string nodename_;
std::string service_account_id_;
absl::Time start_time_;
std::string compiler_proxy_id_prefix_;
std::unique_ptr<SubProcessOptionSetter> subprocess_option_setter_;
std::unique_ptr<HttpClient> http_client_;
std::unique_ptr<HttpRPC> http_rpc_;
std::unique_ptr<ExecServiceClient> exec_service_client_;
std::unique_ptr<MultiFileStore> multi_file_store_;
std::unique_ptr<BlobClient> blob_client_;
std::unique_ptr<CompilerTypeSpecificCollection>
compiler_type_specific_collection_;
int compiler_info_pool_;
mutable Lock compiler_info_mu_;
// key: key_cwd: value: a list of waiting param+closure.
absl::flat_hash_map<std::string, CompilerInfoWaiterList*>
compiler_info_waiters_ GUARDED_BY(compiler_info_mu_);
std::unique_ptr<FileHashCache> file_hash_cache_;
int include_processor_pool_;
std::unique_ptr<LogServiceClient> log_service_client_;
std::unique_ptr<CompilerProxyHistogram> histogram_;
std::unique_ptr<Watchdog> watchdog_;
bool need_to_send_content_ = false;
absl::Duration new_file_threshold_duration_;
std::vector<absl::Duration> timeouts_;
// TODO: moving enable_gch_hack to compiler specific place.
// The code using the flag scatters in compile_task.
// It is difficult to omit all the use case in one CL.
bool enable_gch_hack_;
bool use_relative_paths_in_argv_ = false;
bool send_expected_outputs_ = false;
std::string command_check_level_;
bool send_compiler_binary_as_input_ = false;
bool use_user_specified_path_for_subprograms_ = false;
// Set hermetic_mode in ExecReq, that is, don't choose different compiler
// than local one.
bool hermetic_ = false;
// If true, local fallback when no compiler in server side.
// If false, error when no compiler in server side.
bool hermetic_fallback_ = false;
bool dont_kill_subprocess_ = false;
int max_subprocs_pending_ = 0;
int local_run_preference_ = 0;
bool local_run_for_failed_input_ = false;
absl::Duration local_run_delay_;
bool store_local_run_output_ = false;
bool should_fail_for_unsupported_compiler_flag_ = false;
bool fail_fast_ = false;
bool enable_cwd_normalization_ = false;
std::string tmp_dir_;
// key: "req_ver - resp_ver", value: count
absl::flat_hash_map<std::string, int> command_version_mismatch_;
absl::flat_hash_map<std::string, int> command_binary_hash_mismatch_;
// key: "path hash", value: count
absl::flat_hash_map<std::string, int> subprogram_mismatch_;
// key: error reason, value: pair<is_error, count>
absl::flat_hash_map<std::string, std::pair<bool, int>> error_to_log_;
// key: error reason, value: count
absl::flat_hash_map<std::string, int> error_to_user_;
mutable ReadWriteLock compiler_mu_;
// key: <gomacc_path>:<basename>:<cwd>:<local_path>
// if all path in <local_path> are absolute, "." is used for <cwd>.
// value: (local_compiler_path, no_goma_local_path)
absl::flat_hash_map<std::string, std::pair<std::string, std::string>>
local_compiler_paths_ GUARDED_BY(compiler_mu_);
int num_exec_request_ = 0;
int num_exec_success_ = 0;
int num_exec_failure_ = 0;
int num_exec_compiler_proxy_failure_ = 0;
int num_exec_goma_finished_ = 0;
int num_exec_goma_cache_hit_ = 0;
int num_exec_goma_local_cache_hit_ = 0;
int num_exec_goma_aborted_ = 0;
int num_exec_goma_retry_ = 0;
int num_exec_local_run_ = 0;
int num_exec_local_killed_ = 0;
int num_exec_local_finished_ = 0;
int num_exec_fail_fallback_ = 0;
std::map<std::string, int> local_run_reason_;
mutable ReadWriteLock buf_mu_;
int num_file_requested_ = 0;
int num_file_uploaded_ = 0;
int num_file_missed_ = 0;
int num_file_dropped_ = 0;
int num_file_output_ = 0;
int num_file_rename_output_ = 0;
int num_file_output_buf_ GUARDED_BY(buf_mu_) = 0;
int num_include_processor_total_files_ = 0;
int num_include_processor_skipped_files_ = 0;
absl::Duration include_processor_total_wait_time_;
absl::Duration include_processor_total_run_time_;
size_t cur_sum_output_size_ GUARDED_BY(buf_mu_) = 0;
size_t max_sum_output_size_ GUARDED_BY(buf_mu_) = 0;
size_t req_sum_output_size_ GUARDED_BY(buf_mu_) = 0;
size_t peak_req_sum_output_size_ GUARDED_BY(buf_mu_) = 0;
bool can_send_user_info_ = false;
absl::optional<absl::Duration> allowed_network_error_duration_;
int num_active_fail_fallback_tasks_ = 0;
int max_active_fail_fallback_tasks_ = -1;
absl::Duration allowed_max_active_fail_fallback_duration_;
absl::optional<absl::Time> reached_max_active_fail_fallback_time_;
int num_forced_fallback_in_setup_[kNumForcedFallbackReasonInSetup];
int max_compiler_disabled_tasks_ = -1;
rbe::StatsManager rbe_stats_mgr_;
absl::optional<PeriodicClosureId> check_long_active_tasks_closure_id_;
absl::Duration long_active_task_threshold_;
DISALLOW_COPY_AND_ASSIGN(CompileService);
};
} // namespace devtools_goma
#endif // DEVTOOLS_GOMA_CLIENT_COMPILE_SERVICE_H_
| 35.734219 | 80 | 0.742144 | [
"vector"
] |
2c2bd6c38f7aaa2a4b428dd5510852e7b652b360 | 4,226 | h | C | src/bkDataset/image/filter/FFTShiftImageFilter.h | BenKoehler/bk | 53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3 | [
"MIT"
] | 4 | 2018-12-08T15:35:38.000Z | 2021-08-06T03:23:06.000Z | src/bkDataset/image/filter/FFTShiftImageFilter.h | BenKoehler/bk | 53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3 | [
"MIT"
] | null | null | null | src/bkDataset/image/filter/FFTShiftImageFilter.h | BenKoehler/bk | 53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2018-2019 Benjamin Köhler
*
* 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.
*/
#pragma once
#ifndef BK_FFTSHIFTIMAGEFILTER_H
#define BK_FFTSHIFTIMAGEFILTER_H
#include <cassert>
#include <complex>
#include <vector>
#include <bk/FFT>
namespace bk
{
class FFTShiftImageFilter
{
//====================================================================================================
//===== DEFINITIONS
//====================================================================================================
using self_type = FFTShiftImageFilter;
//====================================================================================================
//===== CONSTRUCTORS & DESTRUCTOR
//====================================================================================================
public:
/// @{ -------------------------------------------------- CTOR
constexpr FFTShiftImageFilter() = default;
constexpr FFTShiftImageFilter(const self_type&) = default;
constexpr FFTShiftImageFilter(self_type&&) noexcept = default;
/// @}
/// @{ -------------------------------------------------- DTOR
~FFTShiftImageFilter() = default;
/// @}
//====================================================================================================
//===== SETTER
//====================================================================================================
/// @{ -------------------------------------------------- OPERATOR =
[[maybe_unused]] constexpr auto operator=(const self_type& other) -> self_type& = default;
[[maybe_unused]] constexpr auto operator=(self_type&& other) noexcept -> self_type& = default;
/// @}
//====================================================================================================
//===== FUNCTIONS
//====================================================================================================
/// @{ -------------------------------------------------- APPLY
template<typename TImage>
[[nodiscard]] static constexpr TImage apply(const TImage& img)
{
const unsigned int nDims = img.num_dimensions();
assert(nDims >= 1 && nDims <= 4 && "fftshift is only implemented for 1/2/3/4D images");
const auto size = img.size();
TImage res = img;
switch (nDims)
{
case 1:
{
FFTShift1D(res.data(), size[0]);
break;
}
case 2:
{
FFTShift2D(res.data(), size[0], size[1]);
break;
}
case 3:
{
FFTShift3D(res.data(), size[0], size[1], size[2]);
break;
}
case 4:
{
FFTShift4D(res.data(), size[0], size[1], size[2], size[3]);
break;
}
}
return res;
}
/// @}
}; // class FFTShiftImageFilter
} // namespace bk
#endif //BK_FFTSHIFTIMAGEFILTER_H
| 37.732143 | 108 | 0.443682 | [
"vector"
] |
2c2d04f06e6ccf26493412c1da0e31c23bc17a03 | 1,832 | h | C | build/linux-build/Sources/include/hxinc/kha/kore/Video.h | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/include/hxinc/kha/kore/Video.h | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/include/hxinc/kha/kore/Video.h | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | // Generated by Haxe 4.0.5
#ifndef INCLUDED_kha_kore_Video
#define INCLUDED_kha_kore_Video
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_kha_Video
#include <hxinc/kha/Video.h>
#endif
HX_DECLARE_CLASS1(kha,Resource)
HX_DECLARE_CLASS1(kha,Video)
HX_DECLARE_CLASS2(kha,kore,Video)
#include <Kore/pch.h>
#include <Kore/Video.h>
namespace kha{
namespace kore{
class HXCPP_CLASS_ATTRIBUTES Video_obj : public ::kha::Video_obj
{
public:
typedef ::kha::Video_obj super;
typedef Video_obj OBJ_;
Video_obj();
public:
enum { _hx_ClassId = 0x6263e2c0 };
void __construct(::String filename);
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="kha.kore.Video")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,false,"kha.kore.Video"); }
static hx::ObjectPtr< Video_obj > __new(::String filename);
static hx::ObjectPtr< Video_obj > __alloc(hx::Ctx *_hx_ctx,::String filename);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~Video_obj();
HX_DO_RTTI_ALL;
hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("Video",5b,84,29,ca); }
void init(::String filename);
::Dynamic init_dyn();
void play(hx::Null< bool > loop);
void pause();
void stop();
int getLength();
int getCurrentPos();
int get_position();
int set_position(int value);
bool isFinished();
int width();
int height();
void unload();
Kore::Video* video;
};
} // end namespace kha
} // end namespace kore
#endif /* INCLUDED_kha_kore_Video */
| 21.809524 | 102 | 0.716703 | [
"object"
] |
2c30213cb2dd86d776cd0b130233ad2cca155e32 | 913 | h | C | Tran_Dan_Maku/Generated Code/Tran_Dan_Maku_Instruction1.h | Dan-Tran/Dan-Maku | 7428e32d3010f0c82f5552b36e90ee907f284cb1 | [
"Apache-2.0"
] | 1 | 2017-12-28T10:33:22.000Z | 2017-12-28T10:33:22.000Z | Tran_Dan_Maku/Generated Code/Tran_Dan_Maku_Instruction1.h | Dan-Tran/Dan-Maku | 7428e32d3010f0c82f5552b36e90ee907f284cb1 | [
"Apache-2.0"
] | null | null | null | Tran_Dan_Maku/Generated Code/Tran_Dan_Maku_Instruction1.h | Dan-Tran/Dan-Maku | 7428e32d3010f0c82f5552b36e90ee907f284cb1 | [
"Apache-2.0"
] | null | null | null | #ifndef _TRAN_DAN_MAKU_INSTRUCTION1_H_
#define _TRAN_DAN_MAKU_INSTRUCTION1_H_
class Instruction1:public ProjectFun::Sprite
{
protected:
DECLARE_LUA_VARS(Instruction1)
public:
Instruction1();
Instruction1(const std::vector<ProjectFun::SpriteAnimationPtr> & animations);
Instruction1(const Instruction1 & other);
~Instruction1() ;
Instruction1 * Clone();
void Destroy() ;
void Save(Core::File & file) const;
void Load(Core::File & file) ;
void NetworkSave(ProjectFun::NetworkFile &file) const;
void NetworkLoad(ProjectFun::NetworkFile &file) ;
void NetworkSyncSend(ProjectFun::NetworkFile &file) const;
void NetworkSyncReceive(ProjectFun::NetworkFile & file) ;
void OnStart() ;
void OnEnd() ;
void OnClone(const Instruction1 & other) ;
protected:
void Update(float dt) ;
private:
DECLARE_OBJECT(Instruction1);
};
#endif
| 18.632653 | 81 | 0.708653 | [
"vector"
] |
2c3432c286db7f16951abe059e3a44fec5d40c70 | 7,701 | h | C | third_party/gecko-2/win32/include/nsILocaleService.h | akiellor/selenium | 239490f9c5f3c7e7d4082bbe53c86eb5158d70a3 | [
"Apache-2.0"
] | 1 | 2018-08-24T18:01:34.000Z | 2018-08-24T18:01:34.000Z | third_party/gecko-2/win32/include/nsILocaleService.h | akiellor/selenium | 239490f9c5f3c7e7d4082bbe53c86eb5158d70a3 | [
"Apache-2.0"
] | 1 | 2021-10-18T12:23:37.000Z | 2021-10-18T12:23:37.000Z | third_party/gecko-2/win32/include/nsILocaleService.h | akiellor/selenium | 239490f9c5f3c7e7d4082bbe53c86eb5158d70a3 | [
"Apache-2.0"
] | 2 | 2018-04-30T21:35:30.000Z | 2021-05-14T08:11:46.000Z | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/intl/locale/idl/nsILocaleService.idl
*/
#ifndef __gen_nsILocaleService_h__
#define __gen_nsILocaleService_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
#ifndef __gen_nsILocale_h__
#include "nsILocale.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsILocaleService */
#define NS_ILOCALESERVICE_IID_STR "c2edc848-4219-4440-abbf-98119882c83f"
#define NS_ILOCALESERVICE_IID \
{0xc2edc848, 0x4219, 0x4440, \
{ 0xab, 0xbf, 0x98, 0x11, 0x98, 0x82, 0xc8, 0x3f }}
/**
* The Locale service interface. This is a singleton object, and should be
* obtained from the <tt>nsServiceManager</tt>.
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsILocaleService : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ILOCALESERVICE_IID)
/**
* Create a new nsILocale from a locale string.
*
* @param aLocale
* A locale code as described in nsILocale.
* @return A nsILocale representing the given locale.
*/
/* nsILocale newLocale (in AString aLocale); */
NS_SCRIPTABLE NS_IMETHOD NewLocale(const nsAString & aLocale, nsILocale **_retval NS_OUTPARAM) = 0;
/**
* Get the user preference for locale from the operating system.
*
* @return User's OS setting for preferred locale.
*/
/* nsILocale getSystemLocale (); */
NS_SCRIPTABLE NS_IMETHOD GetSystemLocale(nsILocale **_retval NS_OUTPARAM) = 0;
/**
* Get the user preference for locale from the operating system.
*
* NOTE: This has nothing to do with the locale used for localization of
* the application (UI text strings etc.). This method returns something
* similar to getSystemLocale.
*
* @return User's OS setting for preferred locale.
*/
/* nsILocale getApplicationLocale (); */
NS_SCRIPTABLE NS_IMETHOD GetApplicationLocale(nsILocale **_retval NS_OUTPARAM) = 0;
/**
* Get the most preferred locale from a list of locale preferences.
*
* @param acceptLanguage
* Locale preference in the same format as the Accept-Language HTTP
* header.
* @return The most preferred locale according to the acceptLanguage
* parameter.
*/
/* nsILocale getLocaleFromAcceptLanguage (in string acceptLanguage); */
NS_SCRIPTABLE NS_IMETHOD GetLocaleFromAcceptLanguage(const char *acceptLanguage, nsILocale **_retval NS_OUTPARAM) = 0;
/**
* Get the user preference for locale from the operating system.
*
* NOTE: This has nothing to do with any HTTP User-Agent. This method
* returns the same as getSystemLocale, but as a string.
*
* @return User's OS setting for preferred locale in the format described
* in nsILocale.
*/
/* AString getLocaleComponentForUserAgent (); */
NS_SCRIPTABLE NS_IMETHOD GetLocaleComponentForUserAgent(nsAString & _retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsILocaleService, NS_ILOCALESERVICE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSILOCALESERVICE \
NS_SCRIPTABLE NS_IMETHOD NewLocale(const nsAString & aLocale, nsILocale **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetSystemLocale(nsILocale **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetApplicationLocale(nsILocale **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetLocaleFromAcceptLanguage(const char *acceptLanguage, nsILocale **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetLocaleComponentForUserAgent(nsAString & _retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSILOCALESERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD NewLocale(const nsAString & aLocale, nsILocale **_retval NS_OUTPARAM) { return _to NewLocale(aLocale, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetSystemLocale(nsILocale **_retval NS_OUTPARAM) { return _to GetSystemLocale(_retval); } \
NS_SCRIPTABLE NS_IMETHOD GetApplicationLocale(nsILocale **_retval NS_OUTPARAM) { return _to GetApplicationLocale(_retval); } \
NS_SCRIPTABLE NS_IMETHOD GetLocaleFromAcceptLanguage(const char *acceptLanguage, nsILocale **_retval NS_OUTPARAM) { return _to GetLocaleFromAcceptLanguage(acceptLanguage, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetLocaleComponentForUserAgent(nsAString & _retval NS_OUTPARAM) { return _to GetLocaleComponentForUserAgent(_retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSILOCALESERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD NewLocale(const nsAString & aLocale, nsILocale **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->NewLocale(aLocale, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetSystemLocale(nsILocale **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemLocale(_retval); } \
NS_SCRIPTABLE NS_IMETHOD GetApplicationLocale(nsILocale **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetApplicationLocale(_retval); } \
NS_SCRIPTABLE NS_IMETHOD GetLocaleFromAcceptLanguage(const char *acceptLanguage, nsILocale **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocaleFromAcceptLanguage(acceptLanguage, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetLocaleComponentForUserAgent(nsAString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocaleComponentForUserAgent(_retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsLocaleService : public nsILocaleService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSILOCALESERVICE
nsLocaleService();
private:
~nsLocaleService();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsLocaleService, nsILocaleService)
nsLocaleService::nsLocaleService()
{
/* member initializers and constructor code */
}
nsLocaleService::~nsLocaleService()
{
/* destructor code */
}
/* nsILocale newLocale (in AString aLocale); */
NS_IMETHODIMP nsLocaleService::NewLocale(const nsAString & aLocale, nsILocale **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsILocale getSystemLocale (); */
NS_IMETHODIMP nsLocaleService::GetSystemLocale(nsILocale **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsILocale getApplicationLocale (); */
NS_IMETHODIMP nsLocaleService::GetApplicationLocale(nsILocale **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsILocale getLocaleFromAcceptLanguage (in string acceptLanguage); */
NS_IMETHODIMP nsLocaleService::GetLocaleFromAcceptLanguage(const char *acceptLanguage, nsILocale **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* AString getLocaleComponentForUserAgent (); */
NS_IMETHODIMP nsLocaleService::GetLocaleComponentForUserAgent(nsAString & _retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
// {C8E518C1-47AE-11d3-91CD-00105AA3F7DC}
#define NS_LOCALESERVICE_CID {0xc8e518c1,0x47ae,0x11d3,{0x91,0xcd,0x0,0x10,0x5a,0xa3,0xf7,0xdc}}
#define NS_LOCALESERVICE_CONTRACTID "@mozilla.org/intl/nslocaleservice;1"
extern nsresult
NS_NewLocaleService(nsILocaleService** result);
#endif /* __gen_nsILocaleService_h__ */
| 40.109375 | 219 | 0.745228 | [
"object"
] |
2c35aa941f4b7162a30933e64d6285176ae082d0 | 3,280 | h | C | include/SGDocument.h | RastislavKamenickyOnsemi/couchbase-lite-cpp | 302bdae8980257d92da29add452190aa4d4c28b5 | [
"Apache-2.0"
] | 2 | 2019-08-09T09:23:39.000Z | 2020-10-02T06:35:53.000Z | include/SGDocument.h | RastislavKamenickyOnsemi/couchbase-lite-cpp | 302bdae8980257d92da29add452190aa4d4c28b5 | [
"Apache-2.0"
] | 3 | 2019-10-21T19:06:05.000Z | 2020-09-11T23:55:15.000Z | include/SGDocument.h | RastislavKamenickyOnsemi/couchbase-lite-cpp | 302bdae8980257d92da29add452190aa4d4c28b5 | [
"Apache-2.0"
] | 3 | 2019-05-16T18:36:49.000Z | 2020-07-10T05:48:20.000Z | //
// SGDocument.h
//
// Copyright 2014 ON Semiconductor.
// All rights reserved. This software and/or documentation is licensed by ON Semiconductor under
// limited terms and conditions. The terms and conditions pertaining to the software and/or documentation are available at
// http://www.onsemi.com/site/pdf/ONSEMI_T&C.pdf (“ON Semiconductor Standard Terms and Conditions of Sale, Section 8 Software”).
// Do not use this software and/or documentation unless you have carefully read and you agree to the limited terms and conditions.
// By using this software and/or documentation, you agree to the limited terms and conditions.
//
// Copyright 2019 ON Semiconductor
//
// 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 SGDOCUMENT_H
#define SGDOCUMENT_H
#include <string>
#include "SGDatabase.h"
#include <litecore/c4Document+Fleece.h>
#include <fleece/FleeceImpl.hh>
#include <fleece/MutableArray.hh>
#include <fleece/MutableDict.hh>
namespace Strata {
// Forward declaration is required due to the circular include for SGDatabase<->SGDocument.
class SGDatabase;
class SGDocument {
public:
SGDocument();
virtual ~SGDocument();
SGDocument(SGDatabase *database, const std::string &docId);
C4Document *getC4document() const;
const std::string &getId() const;
void setId(const std::string &id);
/** SGDocument getBody.
* @brief Stringify fleece object (mutable_dict_) to string json format.
*/
const std::string getBody() const;
/** SGDocument asDict.
* @brief Return the internal mutable_dict_ as fleece Dict object.
*/
const fleece::impl::Dict *asDict() const;
/** SGDocument empty.
* @brief check if MutableDict is empty.
*/
bool empty() const;
/** SGDocument get.
* @brief MutableDict wrapper to access document data.
* @param keyToFind The reference to the key.
*/
const fleece::impl::Value *get(const std::string &keyToFind);
/** SGDocument exist.
* @brief Check if the document exist in the DB.
*/
bool exist() const;
std::string getRevision();
private:
C4Database *c4db_{nullptr};
C4Document *c4document_{nullptr};
// Document ID
std::string id_;
void setC4document(C4Document *);
friend SGDatabase;
protected:
/** SGDocument initMutableDict.
* @brief Loads the document's body and set it to mutable_dict_, if the document exist. Otherwise init mutable_dict_
*/
void initMutableDict();
fleece::Retained<fleece::impl::MutableDict> mutable_dict_;
};
}
#endif //SGDOCUMENT_H
| 32.156863 | 131 | 0.672256 | [
"object"
] |
2c3f065a5ad7b3faf6fb33cf77dfc8fc16d46cbf | 2,644 | h | C | aws-cpp-sdk-iot/include/aws/iot/model/GetTopicRuleResult.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-iot/include/aws/iot/model/GetTopicRuleResult.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-iot/include/aws/iot/model/GetTopicRuleResult.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/iot/IoT_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iot/model/TopicRule.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace IoT
{
namespace Model
{
/**
* <p>The output from the GetTopicRule operation.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/iot-2015-05-28/GetTopicRuleResponse">AWS
* API Reference</a></p>
*/
class AWS_IOT_API GetTopicRuleResult
{
public:
GetTopicRuleResult();
GetTopicRuleResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetTopicRuleResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The rule ARN.</p>
*/
inline const Aws::String& GetRuleArn() const{ return m_ruleArn; }
/**
* <p>The rule ARN.</p>
*/
inline void SetRuleArn(const Aws::String& value) { m_ruleArn = value; }
/**
* <p>The rule ARN.</p>
*/
inline void SetRuleArn(Aws::String&& value) { m_ruleArn = std::move(value); }
/**
* <p>The rule ARN.</p>
*/
inline void SetRuleArn(const char* value) { m_ruleArn.assign(value); }
/**
* <p>The rule ARN.</p>
*/
inline GetTopicRuleResult& WithRuleArn(const Aws::String& value) { SetRuleArn(value); return *this;}
/**
* <p>The rule ARN.</p>
*/
inline GetTopicRuleResult& WithRuleArn(Aws::String&& value) { SetRuleArn(std::move(value)); return *this;}
/**
* <p>The rule ARN.</p>
*/
inline GetTopicRuleResult& WithRuleArn(const char* value) { SetRuleArn(value); return *this;}
/**
* <p>The rule.</p>
*/
inline const TopicRule& GetRule() const{ return m_rule; }
/**
* <p>The rule.</p>
*/
inline void SetRule(const TopicRule& value) { m_rule = value; }
/**
* <p>The rule.</p>
*/
inline void SetRule(TopicRule&& value) { m_rule = std::move(value); }
/**
* <p>The rule.</p>
*/
inline GetTopicRuleResult& WithRule(const TopicRule& value) { SetRule(value); return *this;}
/**
* <p>The rule.</p>
*/
inline GetTopicRuleResult& WithRule(TopicRule&& value) { SetRule(std::move(value)); return *this;}
private:
Aws::String m_ruleArn;
TopicRule m_rule;
};
} // namespace Model
} // namespace IoT
} // namespace Aws
| 23.607143 | 110 | 0.623298 | [
"model"
] |
2c40dedb05f161913e2c0d908fcd01a878eaf64c | 1,392 | h | C | SDLProjekt/Game.h | TheKrzyko/SokobanSDL | dfc6e5cefcc84d069fcaad6908e9a1ba44444d29 | [
"MIT"
] | null | null | null | SDLProjekt/Game.h | TheKrzyko/SokobanSDL | dfc6e5cefcc84d069fcaad6908e9a1ba44444d29 | [
"MIT"
] | null | null | null | SDLProjekt/Game.h | TheKrzyko/SokobanSDL | dfc6e5cefcc84d069fcaad6908e9a1ba44444d29 | [
"MIT"
] | null | null | null | #pragma once
#include <SDL.h>
#include "Vector2.h"
#include "Resources.h"
#include "FrameAnimation.h"
#include "Sprite.h"
#include "Player.h"
#include "String.h"
#include "Text.h"
#include "Board.h"
#include "Rectangle.h"
#include "Menu.h"
using namespace std;
enum GameState
{
menuView,
gameView
};
class Game
{
SDL_Window* window;
SDL_Renderer* renderer;
double frameTime;
String title;
bool isRunning = true;
const double moveTime = 0.2;//as seconds
Clock moveClock;
Menu menu;
bool loadRes();
void handleEvents();
void handleInput();
void render();
bool loadBoard(String boardPath);
void reactOnPlayerMove(Vector2i move);
void updatePlayerMove();
BoardObject* movingBox;
Vector2i moveVector;
Text text;
Board board;
Player player;
Clock frameClock;
Clock gameTime;
Vector2f screenSize;
Vector2f screenCenter;
public:
Game();
~Game();
bool init(Vector2f screenSize, String title);
void run();
static Game& getInstance();
Resources<SDL_Texture> textures;
Resources<SDL_Surface> surfaces;
GameState state = menuView;
SDL_Surface* tryLoadSurface(String path) const;
SDL_Texture* tryLoadTexture(String path) const;
void showError(String title, String message) const;
void showInfo(String title, String message) const;
double getFrameTime() const;
SDL_Window* getWindow() const;
SDL_Renderer* getRenderer() const;
friend class Menu;
};
| 18.077922 | 52 | 0.742816 | [
"render"
] |
2c4b2d46261020c6c2b5887df25c91a17ba4e724 | 3,423 | h | C | MSCL/source/mscl/MicroStrain/Inertial/Commands/HeadingUpdateControl.h | offworld-projects/MSCL | 8388e97c92165e16c26c554aadf1e204ebcf93cf | [
"BSL-1.0",
"OpenSSL",
"MIT"
] | 53 | 2015-08-28T02:41:41.000Z | 2022-03-03T07:50:53.000Z | MSCL/source/mscl/MicroStrain/Inertial/Commands/HeadingUpdateControl.h | offworld-projects/MSCL | 8388e97c92165e16c26c554aadf1e204ebcf93cf | [
"BSL-1.0",
"OpenSSL",
"MIT"
] | 209 | 2015-09-30T19:36:11.000Z | 2022-03-04T21:52:20.000Z | MSCL/source/mscl/MicroStrain/Inertial/Commands/HeadingUpdateControl.h | offworld-projects/MSCL | 8388e97c92165e16c26c554aadf1e204ebcf93cf | [
"BSL-1.0",
"OpenSSL",
"MIT"
] | 55 | 2015-09-03T14:40:01.000Z | 2022-02-04T02:02:01.000Z | /*******************************************************************************
Copyright(c) 2015-2021 Parker Hannifin Corp. All rights reserved.
MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License.
*******************************************************************************/
#pragma once
#include "mscl/MicroStrain/MIP/Commands/GenericMipCommand.h"
#include "mscl/MicroStrain/ResponseCollector.h"
#include "mscl/MicroStrain/Inertial/ExposedInertialTypes.h"
#include "mscl/MicroStrain/MIP/Commands/MipCommand.h"
namespace mscl
{
#ifndef SWIG
//Class: HeadingUpdateControl
// Contains the logic for the Inertial HeadingUpdateControl command.
class HeadingUpdateControl : public MipCommand
{
public:
//Function: commandName
//
//Returns:
// std::string - the string name for this class.
virtual std::string commandName() const { return "HeadingUpdateControl"; }
//Function: MakeSetCommand
//
//Parameter: dataToUse
// The <HeadingUpdateOptions> object to set.
//
//Returns:
// HeadingUpdateControl - object set up for sending a set command.
static HeadingUpdateControl MakeSetCommand(const HeadingUpdateOptions& headingUpdateOptions);
//Function: MakeGetCommand
//
//Returns:
// HeadingUpdateControl - object set up for sending a get command.
static HeadingUpdateControl MakeGetCommand();
//Function: getResponseData
//
//Parameter:
// response - The <GenericMipCmdResponse> object from which to get formatted data.
//
//Returns:
// ConstellationSettingsData - An object with the data returned from the device.
static HeadingUpdateOptions getResponseData(const GenericMipCmdResponse& response);
//Function: operator ByteStream
// Converts this class to a ByteStream.
operator ByteStream() const;
private:
// Function: Constructor HeadingUpdateControl
// Private constructor creates a HeadingUpdateControl object. Use Make___Command methods to create an object.
HeadingUpdateControl(MipTypes::FunctionSelector function_selector, const HeadingUpdateOptions& dataToUse);
HeadingUpdateControl(MipTypes::FunctionSelector function_selector);
//Function: commandType
//
//Returns:
// MipTypes::Command - the command ID.
virtual MipTypes::Command commandType() const { return MipTypes::CMD_EF_HEADING_UPDATE_CTRL; }
//Function: fieldDataByte
//
//Returns:
// uint8 - the byte ID for field data in the reply.
virtual uint8 fieldDataByte() const { return 0x87; }
//Function: responseExpected
//
//Returns:
// bool - True indicates that a response should return from the device.
virtual bool responseExpected() const;
//Variable: m_functionSelector
// The FunctionSelector type of command to send, get/set, reset to factory defaults, et al.
MipTypes::FunctionSelector m_functionSelector;
//Variable: m_HeadingUpdateOptions
// The uint8 to send to the device.
HeadingUpdateOptions m_HeadingUpdateOptions;
public:
// Destructor
~HeadingUpdateControl() { }
};
#endif
}
| 35.65625 | 121 | 0.632778 | [
"object"
] |
2c4f27d6224e47e2e1f8badec951284deb527466 | 4,985 | h | C | chrome/browser/extensions/extension_toolbar_model.h | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 7 | 2015-05-20T22:41:35.000Z | 2021-11-18T19:07:59.000Z | chrome/browser/extensions/extension_toolbar_model.h | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 1 | 2015-02-02T06:55:08.000Z | 2016-01-20T06:11:59.000Z | chrome/browser/extensions/extension_toolbar_model.h | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 2 | 2015-12-08T00:37:41.000Z | 2017-04-06T05:34:05.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_TOOLBAR_MODEL_H_
#define CHROME_BROWSER_EXTENSIONS_EXTENSION_TOOLBAR_MODEL_H_
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
class Browser;
class ExtensionService;
class PrefService;
// Model for the browser actions toolbar.
class ExtensionToolbarModel : public content::NotificationObserver {
public:
explicit ExtensionToolbarModel(ExtensionService* service);
virtual ~ExtensionToolbarModel();
// The action that should be taken as a result of clicking a browser action.
enum Action {
ACTION_NONE,
ACTION_SHOW_POPUP,
// Unlike LocationBarController there is no ACTION_SHOW_CONTEXT_MENU,
// because UI implementations tend to handle this themselves at a higher
// level.
};
// A class which is informed of changes to the model; represents the view of
// MVC.
class Observer {
public:
// An extension with a browser action button has been added, and should go
// in the toolbar at |index|.
virtual void BrowserActionAdded(const extensions::Extension* extension,
int index) {}
// The browser action button for |extension| should no longer show.
virtual void BrowserActionRemoved(const extensions::Extension* extension) {}
// The browser action button for |extension| has been moved to |index|.
virtual void BrowserActionMoved(const extensions::Extension* extension,
int index) {}
// Called when the model has finished loading.
virtual void ModelLoaded() {}
protected:
virtual ~Observer() {}
};
// Functions called by the view.
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
void MoveBrowserAction(const extensions::Extension* extension, int index);
// Executes the browser action for an extension and returns the action that
// the UI should perform in response.
// |popup_url_out| will be set if the extension should show a popup, with
// the URL that should be shown, if non-NULL.
Action ExecuteBrowserAction(const extensions::Extension* extension,
Browser* browser,
GURL* popup_url_out);
// If count == size(), this will set the visible icon count to -1, meaning
// "show all actions".
void SetVisibleIconCount(int count);
// As above, a return value of -1 represents "show all actions".
int GetVisibleIconCount() const { return visible_icon_count_; }
bool extensions_initialized() const { return extensions_initialized_; }
size_t size() const {
return toolitems_.size();
}
extensions::ExtensionList::iterator begin() {
return toolitems_.begin();
}
extensions::ExtensionList::iterator end() {
return toolitems_.end();
}
const extensions::Extension* GetExtensionByIndex(int index) const;
// Utility functions for converting between an index into the list of
// incognito-enabled browser actions, and the list of all browser actions.
int IncognitoIndexToOriginal(int incognito_index);
int OriginalIndexToIncognito(int original_index);
private:
// content::NotificationObserver implementation.
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE;
// To be called after the extension service is ready; gets loaded extensions
// from the extension service and their saved order from the pref service
// and constructs |toolitems_| from these data.
void InitializeExtensionList();
// Save the model to prefs.
void UpdatePrefs();
// Our observers.
ObserverList<Observer> observers_;
void AddExtension(const extensions::Extension* extension);
void RemoveExtension(const extensions::Extension* extension);
// Our ExtensionService, guaranteed to outlive us.
ExtensionService* service_;
PrefService* prefs_;
// True if we've handled the initial EXTENSIONS_READY notification.
bool extensions_initialized_;
// Ordered list of browser action buttons.
extensions::ExtensionList toolitems_;
// Keeps track of what the last extension to get disabled was.
std::string last_extension_removed_;
// Keeps track of where the last extension to get disabled was in the list.
size_t last_extension_removed_index_;
// The number of icons visible (the rest should be hidden in the overflow
// chevron).
int visible_icon_count_;
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(ExtensionToolbarModel);
};
#endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_TOOLBAR_MODEL_H_
| 35.35461 | 80 | 0.732197 | [
"model"
] |
2c507383ee0291795a53791f78e81a17b35831c6 | 15,584 | h | C | bigneuron_ported/daisuke/neurontracing_vn2/app2/my_fastmarching.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | bigneuron_ported/daisuke/neurontracing_vn2/app2/my_fastmarching.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | bigneuron_ported/daisuke/neurontracing_vn2/app2/my_fastmarching.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #ifndef __MY_FASTMARCHING_H__
#define __MY_FASTMARCHING_H__
#include "fastmarching_dt.h"
#include "fastmarching_tree.h"
#ifdef USE_OPENMP
#include <omp.h>
#endif
#include <algorithm>
#ifndef SET_CLOCK
#define SET_CLOCK clock_gettime(CLOCK_MONOTONIC, &(ts[clock_id])); printf("[ timer %d - %d ]\n", area_id, clock_id++);
#endif
template<class T> bool my_fastmarching_dt_XY(T * inimg1d, float * &phi, int sz0, int sz1, int sz2, int cnn_type = 3, int bkg_thresh = 0)
{
#ifdef NEB_DEBUG
struct timespec ts[4];
int clock_id=0, area_id=2;
printf("-----start my fastmarching(sz0=%d, sz1=%d, sz2=%d)-----\n", sz0, sz1, sz2);
SET_CLOCK
#endif
#ifdef USE_OPENMP
//omp_set_num_threads(1);
printf("OpenMP thread=%d / %d\n", omp_get_max_threads(), omp_get_num_procs());
#endif
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
const long tol_sz = sz0 * sz1 * sz2;
const long sz01 = sz0 * sz1;
//int cnn_type = 3; // ?
if(phi == 0) phi = new float[tol_sz];
char * state = new char[tol_sz];
int bkg_count = 0; // for process counting
int bdr_count = 0; // for process counting
for(long i = 0; i < tol_sz; i++)
{
if(inimg1d[i] <= bkg_thresh)
{
phi[i] = inimg1d[i];
state[i] = ALIVE;
//cout<<"+";cout.flush();
bkg_count++;
}
else
{
phi[i] = INF;
state[i] = FAR;
}
}
cout<<endl;
#ifdef NEB_DEBUG
SET_CLOCK
#endif
BasicHeap<HeapElem> heap;
map<long, HeapElem*> elems;
// init heap
{
//long i = -1, j = -1, k = -1;
/*
for(long ind = 0; ind < tol_sz; ind++)
{
long i = ind%sz0;
long j = (ind/sz0)%sz1;
long k = ind/(sz0*sz1);
*/
/*
i++;
if(i%sz0 == 0)
{
i=0; j++;
if(j%sz1==0){j=0; k++;}
}
*/
const long sz1sz0 =sz1*sz0;
#ifdef USE_OPENMP
printf("start omp\n");
#pragma omp parallel for
#endif
for(long k=0; k<sz2; k++){
//long nth = omp_get_thread_num();
for(long j=0; j<sz1; j++){
for(long i=0; i<sz0; i++){
long ind = k*sz1sz0 + j*sz0 + i;
if(state[ind] == ALIVE){
for(int kk = 0; kk <= 0; kk++){
long k2 = k+kk;
if(k2 < 0 || k2 >= sz2) continue;
for(int jj = -1; jj <= 1; jj++){
long j2 = j+jj;
if(j2 < 0 || j2 >= sz1) continue;
for(int ii = -1; ii <=1; ii++){
long i2 = i+ii;
if(i2 < 0 || i2 >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
long ind2 = k2 * sz01 + j2 * sz0 + i2;
if(state[ind2] == FAR){
long min_ind = ind;
// get minimum Alive point around ind2
if(phi[min_ind] > 0.0){
//for(int kkk = 0; kkk <= 0; kkk++){
//long k3 = k2 + kkk;
//if(k3 >= sz2 || k3 < 0) continue;
{
long j3, i3, ind3, jjj, iii, offset2;
jjj=-1; iii=-1; offset2=2;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=-1; iii=0; offset2=1;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=-1; iii=1; offset2=2;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=0; iii=-1; offset2=1;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=0; iii=1; offset2=1;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=1; iii=-1; offset2=2;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=1; iii= 0; offset2=1;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
jjj=1; iii=1; offset2=2;
j3=j2+jjj; i3=i2+iii; ind3 = k2 * sz01 + j3 * sz0 + i3;
if(state[ind3] == ALIVE && phi[ind3] < phi[min_ind]){ if(!(i3 >= sz0 || i3 < 0 || j3 >= sz1 || j3 < 0 || offset2 > cnn_type)){ min_ind = ind3; } }
}
}
// over
phi[ind2] = phi[min_ind] + inimg1d[ind2];
state[ind2] = TRIAL;
HeapElem * elem = new HeapElem(ind2, phi[ind2]);
#pragma omp critical
{
heap.insert(elem);
elems[ind2] = elem;
bdr_count++;
}
}
}
}
}
}
}
}
}
}
cout<<"bkg_count = "<<bkg_count<<" ("<<bkg_count/(double)tol_sz<<")"<<endl;
cout<<"bdr_count = "<<bdr_count<<" ("<<bdr_count/(double)tol_sz<<")"<<endl;
cout<<"elems.size() = "<<elems.size()<<endl;
#ifdef NEB_DEBUG
SET_CLOCK
#endif
// loop
int time_counter = bkg_count;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*100000.0/tol_sz;
if(process2 - process1 >= 10) {cout<<"\r"<<((int)process2)/1000.0<<"%";cout.flush(); process1 = process2;
//SAVE_PHI_IMAGE(phi, sz0, sz1, sz2, string("phi") + num2str((int)process1) + ".tif");
}
HeapElem* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
delete min_elem;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int w, h, d;
for(int kk = 0; kk <= 0; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
long index = d*sz01 + h*sz0 + w;
if(state[index] != ALIVE)
{
float new_dist = phi[min_ind] + inimg1d[index] * sqrt(double(offset));
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElem * elem = new HeapElem(index, phi[index]);
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if(phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElem * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
}
}
}
}
}
}
}
assert(elems.empty());
if(state) {
printf("delete state\n");
delete [] state; state = 0;
}
#ifdef NEB_DEBUG
SET_CLOCK
printf("*************************************\n");
for(int i; i<clock_id-1; i++){
printf("* time(ts[%d - %d] - tm[%d - %d]) = %3.2f\n", area_id, i, area_id, i+1, (ts[i+1].tv_sec - ts[i].tv_sec) + 0.000000001*(ts[i+1].tv_nsec - ts[i].tv_nsec));
}
printf("*************************************\n");
#endif
return true;
}
typedef struct _parent{
long id;
long parent;
} ParentList;
/*********************************************************************
* Function : fastmarching_tree
*
* Features :
* 1. Create fast marcing tree from root marker only
* 2. Background (intensity 0) will be ignored.
* 3. Graph augumented distance is used
*
* Input : root root marker
* inimg1d original 8bit image
*
* Output : tree output swc
* phi the distance for each pixels
* *******************************************************************/
template<class T> bool my_fastmarching_tree(MyMarker root
, T * inimg1d
, vector<MyMarker*> &outtree
, float * &phi
, long sz0
, long sz1
, long sz2
, int cnn_type = 3
, double bkg_thresh = 20
, bool is_break_accept = false
)
{
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
long i;
//int cnn_type = 3; // ?
//float * phi = 0;
//long * parent = 0;
char * state = 0;
printf("-----start my fastmarching tree(sz0=%d, sz1=%d, sz2=%d)-----\n", sz0, sz1, sz2);
#ifdef NEB_DEBUG
struct timespec ts[10];
int clock_id=0, area_id=3;
printf("-----start my fastmarching tree(sz0=%d, sz1=%d, sz2=%d)-----\n", sz0, sz1, sz2);
SET_CLOCK ;
#endif
/*
long *parent;
long parent_index=0, parent_allocate_span=tol_sz/10;
parent = (long *)malloc(parent_allocate_span * sizeof(long));
*/
vector<ParentList> parentlist;
parentlist.clear();
try
{
if(phi==0){ phi = new float[tol_sz]; }
//parent = new long[tol_sz];
state = new char[tol_sz];
}
catch (...)
{
cout << "********* Fail to allocate memory. quit fastmarching_tree()." << endl;
if (phi) {delete []phi; phi=0;}
//if (parent) {delete []parent; parent=0;}
if (state) {delete []state; state=0;}
return false;
}
#ifdef NEB_DEBUG
SET_CLOCK ;
#endif
fill(phi, &(phi[tol_sz]), INF);
//fill(parent, &(parent[tol_sz]), -1);
// change initialization value of parent to constant (i -> -1)
//fill(parent, &(parent[tol_sz]), -1);
//for(long i = 0; i < tol_sz; i++){ parent[i] = i; }
memset(state, FAR, tol_sz);
/*
for(long i = 0; i < tol_sz; i++){
phi[i] = INF;
parent[i] = i;
state[i] = FAR;
}
*/
#ifdef NEB_DEBUG
printf("INF=%f\n", (float)INF);
for(long i=0; i<10; i++){ printf("%d : %f %d\n", i, phi[i], state[i]); }
for(long i=tol_sz-1; i>tol_sz-10; i--){ printf("%d : %f %d\n", i, phi[i], state[i]); }
#endif
#ifdef NEB_DEBUG
SET_CLOCK ;
#endif
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(i = 0; i < tol_sz; i++)
{
if (inimg1d[i] > max_int) max_int = inimg1d[i];
else if (inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
// init state and phi for root
long rootx = root.x + 0.5;
long rooty = root.y + 0.5;
long rootz = root.z + 0.5;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
#ifdef NEB_DEBUG
SET_CLOCK ;
#endif
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*10000.0/tol_sz;
//cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush();
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush(); process1 = process2;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
//change_parent_style
//parent[min_ind] = prev_ind;
ParentList tmp_plist;
tmp_plist.id = min_ind;
tmp_plist.parent = prev_ind;
parentlist.push_back(tmp_plist);
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if (is_break_accept)
{
if(inimg1d[index] <= bkg_thresh &&
inimg1d[min_ind] <= bkg_thresh)
continue;
}
else
{
if(inimg1d[index] <= bkg_thresh)
continue;
}
if(state[index] != ALIVE)
{
double new_dist = phi[min_ind] + (GI(index) + GI(min_ind))*factor*0.5;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if (phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
printf("psize = %d\n", parentlist.size());
#ifdef NEB_DEBUG
SET_CLOCK ;
#endif
// save current swc tree
if (1)
{
map<long, MyMarker*> tmp_map;
const long sz1sz0 = sz1 * sz0;
for(long k=0; k<sz2; k++){
for(long j=0; j<sz1; j++){
for(long i=0; i<sz0; i++){
long ind = (k*sz1sz0) + (j*sz0) + i;
if(state[ind] != ALIVE) continue;
MyMarker * marker = new MyMarker(i,j,k);
tmp_map[ind] = marker;
outtree.push_back(marker);
}
}
}
for(long i=0; i<tmp_map.size(); i++){
if(state[i] != ALIVE) continue;
tmp_map[i]->parent = 0;
}
for(long i=0; i<parentlist.size(); i++){
if(state[parentlist[i].id] != ALIVE) continue;
MyMarker * marker1 = tmp_map[parentlist[i].id];
if(parentlist[i].parent>0 && parentlist[i].parent!=parentlist[i].id){
MyMarker * marker2 = tmp_map[parentlist[i].parent];
marker1->parent = marker2;
}
}
/*
long counter=0;
for(long k=0; k<sz2; k++){
for(long j=0; j<sz1; j++){
for(long i=0; i<sz0; i++){
long ind = (k*sz1sz0) + (j*sz0) + i;
if(state[ind] != ALIVE) continue;
long ind2 = parent[ind];
MyMarker * marker1 = tmp_map[ind];
if(ind2 < 0 || marker1 == tmp_map[ind2]){
marker1->parent = 0;
}else{
MyMarker * marker2 = tmp_map[ind2];
marker1->parent = marker2;
counter++;
//tmp_map[ind]->parent = tmp_map[ind2];
}
}
}
}
printf("counter=%d\n", counter);
*/
}
#ifdef NEB_DEBUG
SET_CLOCK ;
#endif
// over
map<long, HeapElemX*>::iterator mit = elems.begin();
while (mit != elems.end())
{
HeapElemX * elem = mit->second; delete elem; mit++;
}
parentlist.clear();
if(phi){delete [] phi; phi = 0;}
//if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
#ifdef NEB_DEBUG
SET_CLOCK
printf("*************************************\n");
for(int i; i<clock_id-1; i++){
printf("* time(ts[%d - %d] - tm[%d - %d]) = %3.2f\n", area_id, i, area_id, i+1, (ts[i+1].tv_sec - ts[i].tv_sec) + 0.000000001*(ts[i+1].tv_nsec - ts[i].tv_nsec));
}
printf("*************************************\n");
#endif
return true;
}
#endif /* __MY_FASTMARCHING_H__ */
| 25.973333 | 165 | 0.525154 | [
"vector"
] |
2c51910c195dc29e4d5d57ce8eb3adfee36b3205 | 2,700 | h | C | Pod/Classes/Objective-C/UIColor+CIELAB.h | lowell/Chameleon | db46864d0791b13751462c3212a36bd2babe3147 | [
"MIT"
] | 527 | 2015-10-07T07:37:08.000Z | 2022-02-08T16:23:33.000Z | Pods/ChameleonFramework/Pod/Classes/Objective-C/UIColor+CIELAB.h | CallMeDK/MrCode | 3630c785d6d105417b051f1ab54d9bde39959f5b | [
"MIT"
] | 4 | 2015-11-21T18:11:26.000Z | 2018-04-12T06:26:15.000Z | Pods/ChameleonFramework/Pod/Classes/Objective-C/UIColor+CIELAB.h | CallMeDK/MrCode | 3630c785d6d105417b051f1ab54d9bde39959f5b | [
"MIT"
] | 115 | 2015-10-08T01:03:09.000Z | 2022-02-08T16:23:45.000Z |
// UIColor+CIELAB.h
/*
The MIT License (MIT)
Copyright (c) 2014-2015 Vicc Alexander.
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.
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIColor (CIELAB)
/**
* Returns the components that make up the color in the XYZ color space.
*
* @param X On return, the X component of the color object, specified as a value between 0.0 and 100.0.
* @param Y On return, the Y component of the color object, specified as a value between 0.0 and 100.0.
* @param Z On return, the Z component of the color object, specified as a value between 0.0 and 100.0.
* @param alpha On return, the opacity component of the color object, specified as a value between 0.0 and 1.0.
*
* @return YES if the color could be converted, NO otherwise.
*/
- (BOOL)getValueForX:(CGFloat *)X
valueForY:(CGFloat *)Y
valueForZ:(CGFloat *)Z
alpha:(CGFloat *)alpha;
/**
* Returns the components that make up the color in the LAB color space.
*
* @param L On return, the L component of the color object, specified as a value between 0.0 and 100.0.
* @param A On return, the A component of the color object, specified as a value between -100.0 and 100.0.
* @param B On return, the B component of the color object, specified as a value between -100.0 and 100.0.
* @param alpha On return, the opacity component of the color object, specified as a value between 0.0 and 1.0.
*
* @return YES if the color could be converted, NO otherwise.
*/
- (BOOL)getLightness:(CGFloat *)L
valueForA:(CGFloat *)A
valueForB:(CGFloat *)B
alpha:(CGFloat *)alpha;
@end
| 40.298507 | 112 | 0.717778 | [
"object"
] |
2c55688cb5a3791299452db478260a707f91020a | 4,145 | h | C | deps/webrtc/include/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h | QueenConch/quick_start_webrtc_native | 0321fb204a076b437e0d708c2ec55cae6464c4f3 | [
"MIT"
] | 2 | 2018-07-04T00:29:09.000Z | 2020-07-05T09:24:59.000Z | deps/webrtc/include/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h | QueenConch/quick_start_webrtc_native | 0321fb204a076b437e0d708c2ec55cae6464c4f3 | [
"MIT"
] | null | null | null | deps/webrtc/include/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h | QueenConch/quick_start_webrtc_native | 0321fb204a076b437e0d708c2ec55cae6464c4f3 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CSSImageGeneratorValue_h
#define CSSImageGeneratorValue_h
#include "core/CoreExport.h"
#include "core/css/CSSValue.h"
#include "platform/geometry/IntSizeHash.h"
#include "platform/geometry/LayoutSize.h"
#include "platform/heap/SelfKeepAlive.h"
#include "platform/wtf/HashCountedSet.h"
#include "platform/wtf/RefPtr.h"
namespace blink {
class Document;
class Image;
class FloatSize;
class ComputedStyle;
class ImageResourceObserver;
struct SizeAndCount {
DISALLOW_NEW();
SizeAndCount(IntSize new_size = IntSize(), int new_count = 0)
: size(new_size), count(new_count) {}
IntSize size;
int count;
};
using ClientSizeCountMap = HashMap<const ImageResourceObserver*, SizeAndCount>;
class CORE_EXPORT CSSImageGeneratorValue : public CSSValue {
public:
~CSSImageGeneratorValue();
void AddClient(const ImageResourceObserver*, const IntSize&);
void RemoveClient(const ImageResourceObserver*);
// The |container_size| is the container size with subpixel snapping, where
// the |logical_size| is without it. Both sizes include zoom.
RefPtr<Image> GetImage(const ImageResourceObserver&,
const Document&,
const ComputedStyle&,
const IntSize& container_size,
const LayoutSize* logical_size);
bool IsFixedSize() const;
IntSize FixedSize(const Document&, const FloatSize& default_object_size);
bool IsPending() const;
bool KnownToBeOpaque(const Document&, const ComputedStyle&) const;
void LoadSubimages(const Document&);
CSSImageGeneratorValue* ValueWithURLsMadeAbsolute();
DEFINE_INLINE_TRACE_AFTER_DISPATCH() {
CSSValue::TraceAfterDispatch(visitor);
}
protected:
explicit CSSImageGeneratorValue(ClassType);
Image* GetImage(const ImageResourceObserver*,
const Document&,
const ComputedStyle&,
const IntSize&);
void PutImage(const IntSize&, RefPtr<Image>);
const ClientSizeCountMap& Clients() const { return clients_; }
HashCountedSet<IntSize>
sizes_; // A count of how many times a given image size is in use.
ClientSizeCountMap
clients_; // A map from LayoutObjects (with entry count) to image sizes.
HashMap<IntSize, RefPtr<Image>>
images_; // A cache of Image objects by image size.
// TODO(Oilpan): when/if we can make the layoutObject point directly to the
// CSSImageGenerator value using a member we don't need to have this hack
// where we keep a persistent to the instance as long as there are clients in
// the ClientSizeCountMap.
SelfKeepAlive<CSSImageGeneratorValue> keep_alive_;
};
DEFINE_CSS_VALUE_TYPE_CASTS(CSSImageGeneratorValue, IsImageGeneratorValue());
} // namespace blink
#endif // CSSImageGeneratorValue_h
| 36.681416 | 79 | 0.738963 | [
"geometry"
] |
2c5ae626239439e649d49e84b7220bb0fca7dec7 | 8,240 | c | C | src/common/io/socket/client.c | crunchyheath/pgbackrest | 927d9adbee780a51639955edb74ce7a4850db100 | [
"MIT"
] | null | null | null | src/common/io/socket/client.c | crunchyheath/pgbackrest | 927d9adbee780a51639955edb74ce7a4850db100 | [
"MIT"
] | null | null | null | src/common/io/socket/client.c | crunchyheath/pgbackrest | 927d9adbee780a51639955edb74ce7a4850db100 | [
"MIT"
] | null | null | null | /***********************************************************************************************************************************
Socket Client
***********************************************************************************************************************************/
#include "build.auto.h"
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include "common/debug.h"
#include "common/log.h"
#include "common/io/client.intern.h"
#include "common/io/socket/client.h"
#include "common/io/socket/common.h"
#include "common/io/socket/session.h"
#include "common/memContext.h"
#include "common/stat.h"
#include "common/type/object.h"
#include "common/wait.h"
/***********************************************************************************************************************************
Io client type
***********************************************************************************************************************************/
STRING_EXTERN(IO_CLIENT_SOCKET_TYPE_STR, IO_CLIENT_SOCKET_TYPE);
/***********************************************************************************************************************************
Statistics constants
***********************************************************************************************************************************/
STRING_EXTERN(SOCKET_STAT_CLIENT_STR, SOCKET_STAT_CLIENT);
STRING_EXTERN(SOCKET_STAT_RETRY_STR, SOCKET_STAT_RETRY);
STRING_EXTERN(SOCKET_STAT_SESSION_STR, SOCKET_STAT_SESSION);
/***********************************************************************************************************************************
Object type
***********************************************************************************************************************************/
#define SOCKET_CLIENT_TYPE SocketClient
#define SOCKET_CLIENT_PREFIX sckClient
typedef struct SocketClient
{
MemContext *memContext; // Mem context
String *host; // Hostname or IP address
unsigned int port; // Port to connect to host on
String *name; // Socket name (host:port)
TimeMSec timeout; // Timeout for any i/o operation (connect, read, etc.)
} SocketClient;
/***********************************************************************************************************************************
Macros for function logging
***********************************************************************************************************************************/
static String *
sckClientToLog(const THIS_VOID)
{
THIS(const SocketClient);
return strNewFmt("{host: %s, port: %u, timeout: %" PRIu64 "}", strZ(this->host), this->port, this->timeout);
}
#define FUNCTION_LOG_SOCKET_CLIENT_TYPE \
SocketClient *
#define FUNCTION_LOG_SOCKET_CLIENT_FORMAT(value, buffer, bufferSize) \
FUNCTION_LOG_STRING_OBJECT_FORMAT(value, sckClientToLog, buffer, bufferSize)
/**********************************************************************************************************************************/
static IoSession *
sckClientOpen(THIS_VOID)
{
THIS(SocketClient);
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(SOCKET_CLIENT, this);
FUNCTION_LOG_END();
ASSERT(this != NULL);
IoSession *result = NULL;
MEM_CONTEXT_TEMP_BEGIN()
{
bool retry;
Wait *wait = waitNew(this->timeout);
do
{
// Assume there will be no retry
retry = false;
int fd = -1;
TRY_BEGIN()
{
// Set hints that narrow the type of address we are looking for -- we'll take ipv4 or ipv6
struct addrinfo hints = (struct addrinfo)
{
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
.ai_protocol = IPPROTO_TCP,
};
// Convert the port to a zero-terminated string for use with getaddrinfo()
char port[CVT_BASE10_BUFFER_SIZE];
cvtUIntToZ(this->port, port, sizeof(port));
// Get an address for the host. We are only going to try the first address returned.
struct addrinfo *hostAddress;
int resultAddr;
if ((resultAddr = getaddrinfo(strZ(this->host), port, &hints, &hostAddress)) != 0)
{
THROW_FMT(
HostConnectError, "unable to get address for '%s': [%d] %s", strZ(this->host), resultAddr,
gai_strerror(resultAddr));
}
// Connect to the host
TRY_BEGIN()
{
fd = socket(hostAddress->ai_family, hostAddress->ai_socktype, hostAddress->ai_protocol);
THROW_ON_SYS_ERROR(fd == -1, HostConnectError, "unable to create socket");
sckOptionSet(fd);
sckConnect(fd, this->host, this->port, hostAddress, waitRemaining(wait));
}
FINALLY()
{
freeaddrinfo(hostAddress);
}
TRY_END();
// Create the session
MEM_CONTEXT_PRIOR_BEGIN()
{
result = sckSessionNew(ioSessionRoleClient, fd, this->host, this->port, this->timeout);
}
MEM_CONTEXT_PRIOR_END();
}
CATCH_ANY()
{
if (fd != -1)
close(fd);
// Retry if wait time has not expired
if (waitMore(wait))
{
LOG_DEBUG_FMT("retry %s: %s", errorTypeName(errorType()), errorMessage());
retry = true;
statInc(SOCKET_STAT_RETRY_STR);
}
else
RETHROW();
}
TRY_END();
}
while (retry);
statInc(SOCKET_STAT_SESSION_STR);
}
MEM_CONTEXT_TEMP_END();
FUNCTION_LOG_RETURN(IO_SESSION, result);
}
/**********************************************************************************************************************************/
static const String *
sckClientName(THIS_VOID)
{
THIS(SocketClient);
FUNCTION_TEST_BEGIN();
FUNCTION_TEST_PARAM(SOCKET_CLIENT, this);
FUNCTION_TEST_END();
ASSERT(this != NULL);
FUNCTION_TEST_RETURN(this->name);
}
/**********************************************************************************************************************************/
static const IoClientInterface sckClientInterface =
{
.type = &IO_CLIENT_SOCKET_TYPE_STR,
.name = sckClientName,
.open = sckClientOpen,
.toLog = sckClientToLog,
};
IoClient *
sckClientNew(const String *host, unsigned int port, TimeMSec timeout)
{
FUNCTION_LOG_BEGIN(logLevelDebug)
FUNCTION_LOG_PARAM(STRING, host);
FUNCTION_LOG_PARAM(UINT, port);
FUNCTION_LOG_PARAM(TIME_MSEC, timeout);
FUNCTION_LOG_END();
ASSERT(host != NULL);
IoClient *this = NULL;
MEM_CONTEXT_NEW_BEGIN("SocketClient")
{
SocketClient *driver = memNew(sizeof(SocketClient));
*driver = (SocketClient)
{
.memContext = MEM_CONTEXT_NEW(),
.host = strDup(host),
.port = port,
.name = strNewFmt("%s:%u", strZ(host), port),
.timeout = timeout,
};
statInc(SOCKET_STAT_CLIENT_STR);
this = ioClientNew(driver, &sckClientInterface);
}
MEM_CONTEXT_NEW_END();
FUNCTION_LOG_RETURN(IO_CLIENT, this);
}
| 37.117117 | 132 | 0.423665 | [
"object"
] |
c803f868428967cf404b6dad4fb18c3ade408eb0 | 9,660 | h | C | kratos/containers/periodic_variables_container.h | lcirrott/Kratos | 8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea | [
"BSD-4-Clause"
] | 2 | 2020-04-30T19:13:08.000Z | 2021-04-14T19:40:47.000Z | kratos/containers/periodic_variables_container.h | lcirrott/Kratos | 8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea | [
"BSD-4-Clause"
] | 13 | 2019-10-07T12:06:51.000Z | 2020-02-18T08:48:33.000Z | kratos/containers/periodic_variables_container.h | lcirrott/Kratos | 8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea | [
"BSD-4-Clause"
] | 1 | 2020-06-12T08:51:24.000Z | 2020-06-12T08:51:24.000Z | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela Dalmau
//
//
#ifndef KRATOS_PERIODIC_VARIABLES_CONTAINER_H
#define KRATOS_PERIODIC_VARIABLES_CONTAINER_H
// System includes
#include <string>
#include <iostream>
// External includes
#include <boost/iterator/indirect_iterator.hpp>
// Project includes
#include "includes/define.h"
#include "includes/serializer.h"
#include "containers/variable.h"
#include "containers/variable_component.h"
#include "containers/vector_component_adaptor.h"
namespace Kratos
{
///@addtogroup FluidDynamicsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// A container of Kratos variables used to define a periodic boundary condition.
/** It can be filled using either Kratos::Variable<double> or
* array_1d<double,3> components (VariableComponent< VectorComponentAdaptor< array_1d<double, 3 > > >).
* It is used by PeriodicCondition to identify the Dofs where the periodic condition applies.
* @see PeriodicCondition
*/
class PeriodicVariablesContainer
{
public:
///@name Type Definitions
///@{
/// Pointer definition of PeriodicVariablesContainer
KRATOS_CLASS_POINTER_DEFINITION(PeriodicVariablesContainer);
/// Kratos double Variable
typedef Variable<double> DoubleVariableType;
/// Container of pointers to Kratos double variables
typedef std::vector<const DoubleVariableType*> DoubleVariablesContainerType;
/// Double Variable iterator
typedef boost::indirect_iterator<DoubleVariablesContainerType::const_iterator> DoubleVariablesConstIterator;
/// Component of a Kratos array_1d<double,3> Variable
typedef VariableComponent< VectorComponentAdaptor< array_1d<double, 3 > > > VariableComponentType;
/// Vector of pointers to Kratos double variables
typedef std::vector<const VariableComponentType*> VariableComponentsContainerType;
/// Variable component iterator
typedef boost::indirect_iterator<VariableComponentsContainerType::const_iterator> VariableComponentsConstIterator;
typedef std::size_t SizeType;
///@}
///@name Life Cycle
///@{
/// Default constructor.
PeriodicVariablesContainer():
mPeriodicDoubleVars(),
mPeriodicVarComponents()
{
}
/// Copy constructor.
PeriodicVariablesContainer(PeriodicVariablesContainer const& rOther):
mPeriodicDoubleVars(rOther.mPeriodicDoubleVars),
mPeriodicVarComponents(rOther.mPeriodicVarComponents)
{
}
/// Destructor.
virtual ~PeriodicVariablesContainer()
{
}
///@}
///@name Operators
///@{
/// Assignment operator.
PeriodicVariablesContainer& operator=(PeriodicVariablesContainer const& rOther)
{
this->mPeriodicDoubleVars = rOther.mPeriodicDoubleVars;
this->mPeriodicVarComponents = rOther.mPeriodicVarComponents;
return *this;
}
///@}
///@name Operations
///@{
/// Add a scalar variable to the list of variables where periodic conditions will be imposed.
void Add(DoubleVariableType const& rThisVariable)
{
if(rThisVariable.Key()== 0)
KRATOS_THROW_ERROR(std::logic_error,
"Adding uninitialized variable to a list of periodic variables: ",rThisVariable.Name());
mPeriodicDoubleVars.push_back(&rThisVariable);
}
/// Add a component of a vector variable to the list of variables where periodic conditions will be imposed.
void Add(VariableComponentType const& rThisVariable)
{
if(rThisVariable.Key()== 0)
KRATOS_THROW_ERROR(std::logic_error,
"Adding uninitialized variable to a list of periodic variables: ",rThisVariable.Name());
mPeriodicVarComponents.push_back(&rThisVariable);
}
/// Erase all information contained in this object.
void Clear()
{
mPeriodicDoubleVars.clear();
mPeriodicVarComponents.clear();
}
///@}
///@name Access
///@{
/// Iterator for the list of scalar variables
DoubleVariablesConstIterator DoubleVariablesBegin() const
{
return DoubleVariablesConstIterator( mPeriodicDoubleVars.begin() );
}
/// Iterator for the list of scalar variables
DoubleVariablesConstIterator DoubleVariablesEnd() const
{
return DoubleVariablesConstIterator( mPeriodicDoubleVars.end() );
}
/// Iterator for the list of vector components
VariableComponentsConstIterator VariableComponentsBegin() const
{
return VariableComponentsConstIterator( mPeriodicVarComponents.begin() );
}
/// Iterator for the list of vector components
VariableComponentsConstIterator VariableComponentsEnd() const
{
return VariableComponentsConstIterator( mPeriodicVarComponents.end() );
}
/// Total number of periodic variables (including scalars and vector components)
SizeType size() const
{
return mPeriodicDoubleVars.size() + mPeriodicVarComponents.size();
}
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
virtual std::string Info() const
{
std::stringstream buffer;
buffer << "PeriodicVariablesContainer";
return buffer.str();
}
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const
{
rOStream << "PeriodicVariablesContainer";
}
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const
{
rOStream << "Double Variables:" << std::endl;
for (DoubleVariablesContainerType::const_iterator it = mPeriodicDoubleVars.begin(); it != mPeriodicDoubleVars.end(); ++it)
{
(*it)->PrintInfo(rOStream);
rOStream << std::endl;
}
rOStream << "Variable Components:" << std::endl;
for (VariableComponentsContainerType::const_iterator it = mPeriodicVarComponents.begin(); it != mPeriodicVarComponents.end(); ++it)
{
(*it)->PrintInfo(rOStream);
rOStream << std::endl;
}
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
/// Container for double variables
DoubleVariablesContainerType mPeriodicDoubleVars;
/// Container for variable components
VariableComponentsContainerType mPeriodicVarComponents;
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Serialization
///@{
friend class Serializer;
virtual void save(Serializer& rSerializer) const
{
std::size_t DoubleVarSize= mPeriodicDoubleVars.size();
rSerializer.save("DoubleVarSize",DoubleVarSize);
for(std::size_t i = 0; i < DoubleVarSize; i++)
rSerializer.save("Variable Name", mPeriodicDoubleVars[i]->Name());
std::size_t VarComponentSize= mPeriodicVarComponents.size();
rSerializer.save("VarComponentSize",VarComponentSize);
for(std::size_t i = 0; i < VarComponentSize; i++)
rSerializer.save("Variable Name", mPeriodicVarComponents[i]->Name());
}
virtual void load(Serializer& rSerializer)
{
std::string Name;
std::size_t DoubleVarSize;
rSerializer.load("DoubleVarSize",DoubleVarSize);
for(std::size_t i = 0; i < DoubleVarSize; i++)
{
rSerializer.load("Variable Name", Name);
Add( *(static_cast<DoubleVariableType*>(KratosComponents<VariableData>::pGet(Name))) );
}
std::size_t VarComponentSize;
rSerializer.load("VarComponentSize",VarComponentSize);
for(std::size_t i = 0; i < VarComponentSize; i++)
{
rSerializer.load("Variable Name", Name);
Add( *(static_cast<VariableComponentType*>(KratosComponents<VariableData>::pGet(Name))) );
}
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; // Class PeriodicVariablesContainer
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// input stream function
inline std::istream & operator >>(std::istream& rIStream,
PeriodicVariablesContainer& rThis)
{
return rIStream;
}
/// output stream function
inline std::ostream & operator <<(std::ostream& rOStream,
const PeriodicVariablesContainer& rThis)
{
rThis.PrintInfo(rOStream);
rOStream << std::endl;
rThis.PrintData(rOStream);
return rOStream;
}
///@}
///@} addtogroup block
} // namespace Kratos.
#endif /* KRATOS_PERIODIC_VARIABLES_CONTAINER_H */
| 24.332494 | 139 | 0.633437 | [
"object",
"vector"
] |
c80a9e1c9054de573c96ca4c34a548ba3c0e75c2 | 22,476 | h | C | Source/External/NVIDIA_Nsight_Aftermath/include/GFSDK_Aftermath.h | AlexScapillati/RenderingEngine | a0315ca054db555b56ca4ff84bc2ae42d16440c6 | [
"MIT"
] | 1 | 2022-03-11T18:12:09.000Z | 2022-03-11T18:12:09.000Z | Source/External/NVIDIA_Nsight_Aftermath/include/GFSDK_Aftermath.h | AlexScapillati/RenderingEngine | a0315ca054db555b56ca4ff84bc2ae42d16440c6 | [
"MIT"
] | null | null | null | Source/External/NVIDIA_Nsight_Aftermath/include/GFSDK_Aftermath.h | AlexScapillati/RenderingEngine | a0315ca054db555b56ca4ff84bc2ae42d16440c6 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017-2022, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
/*
* █████ █████ ██████ ████ ████ ███████ ████ ██████ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██████ ████ ██ ████ █████ ██ ██ ██ ██████ ██ ███████
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██ ██ ██ ██ █████ ██ ██ ██ ██ ██ ██ ██ ██ ██ DEBUGGER
* ██ ██
* ████████████████████████████████████████████████████████ ██ █ ██ ████████████
*
*
* HOW TO USE AFTERMATH for DX11 and DX12
* --------------------------------------
*
* NOTES: Some of the Aftermath 1.x functionality will go away in a future release.
* The functions and structures to be removed are indicated with a DEPRECATED comment.
* The supported method for accessing this data is provided via the GPU crash dump functionality.
* Please refer to the GFSDK_Aftermath_GpuCrashDump.h header file for more details.
*
* Call 'GFSDK_Aftermath_DXxx_Initialize', to initialize the library and to enable
* the desired Aftermath feature set. See 'GFSDK_Aftermath_FeatureFlags' below for
* the list of supported features.
* This must be done before any other library calls are made, and the method must
* return 'GFSDK_Aftermath_Result_Success' for initialization to be complete.
*
* Initialization of Aftermath may fail for a variety of reasons, including:
*
* o) The initialization function was already called for the device:
* GFSDK_Aftermath_Result_FAIL_AlreadyInitialized.
*
*
* o) Aftermath isn't supported on the GPU associated with the device or the NVIDIA
* display driver version installed:
* GFSDK_Aftermath_Result_FAIL_InvalidAdapter,
* GFSDK_Aftermath_Result_FAIL_DriverInitFailed,
* GFSDK_Aftermath_Result_FAIL_DriverVersionNotSupported,
* GFSDK_Aftermath_Result_FAIL_NvApiIncompatible.
*
*
* o) A D3D API debug layer, such as PIX, was detected that is incompatible with
* Aftermath:
* GFSDK_Aftermath_Result_FAIL_D3dDllInterceptionNotSupported
*
*
* o) Aftermath was disabled on the system by the current user setting the
* 'HKEY_CURRENT_USER\Software\NVIDIA Corporation\Nsight Aftermath\ForceOff'
* Windows registry key:
* GFSDK_Aftermath_Result_FAIL_Disabled
*
*
* After detecting D3D device lost (TDR):
*
* o) To query the fault reason after TDR, use the 'GFSDK_Aftermath_GetDeviceStatus'
* call. See 'GFSDK_Aftermath_Device_Status', for the full list of possible
* status.
*
*
* o) In the event of a GPU page fault, use the'GFSDK_Aftermath_GetPageFaultInformation'
* method to return more information about what might of gone wrong. A GPU VA is
* returned, along with the resource descriptor of the resource that VA lands in.
* NOTE: It's not 100% certain that this is the resource which caused the fault,
* only that the faulting VA lands within this resource in memory.
*
*
* Optionally, instrument the application with Aftermath event markers:
*
* 1) For each commandlist/device context you expect to use with Aftermath,
* initialize them using the 'GFSDK_Aftermath_DXxx_CreateContextHandle',
* function.
*
*
* 2) Call 'GFSDK_Aftermath_SetEventMarker', to inject an event
* marker directly into the command stream at that point.
*
* PERFORMANCE TIP:
*
* Do not use 'GFSDK_Aftermath_SetEventMarker' in high frequency code paths.
* Injecting event markers introduces considerable CPU overhead. For reduced CPU
* overhead, use 'GFSDK_Aftermath_SetEventMarker' with markerSize=0. This
* instructs Aftermath not to allocate and copy off memory internally, relying on
* the application to manage marker pointers itself.
*
*
* 3) Once TDR/hang occurs, call the 'GFSDK_Aftermath_GetData' API
* to fetch the event marker last processed by the GPU for each context.
* This API also supports fetching the current execution state for each
* the GPU.
*
*
* 4) Before the app shuts down, each Aftermath context handle must be cleaned
* up, this is done with the 'GFSDK_Aftermath_ReleaseContextHandle' call.
*
*
* HOW TO USE AFTERMATH for Vulkan
* -------------------------------
*
* For Vulkan use the VK_NV_device_diagnostics_config extension to initialize and
* configure the Aftermath feature set to use.
*
* Use the VK_NV_device_diagnostic_checkpoints extension to add event markers into
* the command stream.
*
*/
#ifndef GFSDK_Aftermath_H
#define GFSDK_Aftermath_H
#include "GFSDK_Aftermath_Defines.h"
#pragma pack(push, 8)
#ifdef __cplusplus
extern "C" {
#endif
// Here is defined a set of features that can be enabled/disable when using Aftermath
GFSDK_AFTERMATH_DECLARE_ENUM(FeatureFlags)
{
// The minimal flag only allows use of the GetDeviceStatus entry point.
GFSDK_Aftermath_FeatureFlags_Minimum = 0x00000000,
// With this flag set, the SetEventMarker and GetData entry points are available.
//
// Using event markers should be considered carefully as they can cause
// very high CPU overhead when used in high frequency code paths. Due to
// the inherent overhead, event markers should be used only for debugging
// purposes on development or QA systems. Therefore, starting with the R495
// driver, Aftermath event marker tracking on D3D11 and D3D12 is only
// available if the Nsight Aftermath GPU Crash Dump Monitor is running on
// the system. No Aftermath configuration needs to be made in the Monitor.
// It serves only as a dongle to ensure Aftermath event markers do not
// impact application performance on end user systems. That means this flag
// will be ignored if the monitor process is not detected.
//
GFSDK_Aftermath_FeatureFlags_EnableMarkers = 0x00000001,
// With this flag set, resources are tracked, and information about
// possible page fault candidates can be accessed using GetPageFaultInformation.
GFSDK_Aftermath_FeatureFlags_EnableResourceTracking = 0x00000002,
// With this flag set, event markers are automatically set for all draw calls,
// compute dispatches and copy operations to capture the call stack for the
// corresponding API call as the event marker payload.
// Requires also GFSDK_Aftermath_FeatureFlags_EnableMarkers to be set.
//
// Using this option should be considered carefully. Enabling call stack capturing
// can cause considerable CPU overhead.
//
GFSDK_Aftermath_FeatureFlags_CallStackCapturing = 0x40000000,
// With this flag set, shader debug information is generated.
//
// Not supported for UWP applications.
//
GFSDK_Aftermath_FeatureFlags_GenerateShaderDebugInfo = 0x00000008,
// Use all Aftermath features
//
// Be careful when using this! Some features can cause considerable performance overhead,
// for example, GFSDK_Aftermath_FeatureFlags_EnableMarkers.
//
GFSDK_Aftermath_FeatureFlags_Maximum = GFSDK_Aftermath_FeatureFlags_Minimum |
GFSDK_Aftermath_FeatureFlags_EnableMarkers |
GFSDK_Aftermath_FeatureFlags_EnableResourceTracking |
GFSDK_Aftermath_FeatureFlags_CallStackCapturing |
GFSDK_Aftermath_FeatureFlags_GenerateShaderDebugInfo,
};
#if defined(__d3d11_h__) || defined(__d3d12_h__)
// Used with Aftermath entry points to reference an API object.
GFSDK_AFTERMATH_DECLARE_HANDLE(GFSDK_Aftermath_ContextHandle);
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
GFSDK_AFTERMATH_DECLARE_HANDLE(GFSDK_Aftermath_ResourceHandle);
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// Used with, 'GFSDK_Aftermath_GetData'. Filled with information,
// about each requested context.
typedef struct GFSDK_Aftermath_ContextData
{
GFSDK_AFTERMATH_DECLARE_POINTER_MEMBER(void*, markerData);
uint32_t markerSize;
GFSDK_Aftermath_Context_Status status;
} GFSDK_Aftermath_ContextData;
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// Minimal description of a graphics resource.
typedef struct GFSDK_Aftermath_ResourceDescriptor
{
// This is available in DX12 only and only if the application registers the
// resource pointers using GFSDK_Aftermath_DX12_RegisterResource().
#ifdef __d3d12_h__
GFSDK_AFTERMATH_DECLARE_POINTER_MEMBER(ID3D12Resource*, pAppResource);
#else
GFSDK_AFTERMATH_DECLARE_POINTER_MEMBER(void*, pAppResource);
#endif
uint64_t size;
uint32_t width;
uint32_t height;
uint32_t depth;
uint32_t mipLevels;
uint32_t format; // DXGI_FORMAT
GFSDK_AFTERMATH_DECLARE_BOOLEAN_MEMBER(bIsBufferHeap);
GFSDK_AFTERMATH_DECLARE_BOOLEAN_MEMBER(bIsStaticTextureHeap);
GFSDK_AFTERMATH_DECLARE_BOOLEAN_MEMBER(bIsRtvDsvTextureHeap);
GFSDK_AFTERMATH_DECLARE_BOOLEAN_MEMBER(bPlacedResource);
GFSDK_AFTERMATH_DECLARE_BOOLEAN_MEMBER(bWasDestroyed);
} GFSDK_Aftermath_ResourceDescriptor;
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// Used with GFSDK_Aftermath_GetPageFaultInformation
typedef struct GFSDK_Aftermath_PageFaultInformation
{
uint64_t faultingGpuVA;
GFSDK_Aftermath_ResourceDescriptor resourceDesc;
GFSDK_AFTERMATH_DECLARE_BOOLEAN_MEMBER(bHasPageFaultOccured);
} GFSDK_Aftermath_PageFaultInformation;
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_DX11_Initialize
// GFSDK_Aftermath_DX12_Initialize
// ---------------------------------
//
// [pDx11Device]; DX11-Only
// the current dx11 device pointer.
//
// [pDx12Device]; DX12-Only
// the current dx12 device pointer.
//
// flags;
// set of features to enable when initializing Aftermath
//
// version;
// Must be set to GFSDK_Aftermath_Version_API. Used for checking
// against library version.
//
//// DESCRIPTION;
// Library must be initialized before any other call is made.
// This should be done after device creation.
// Aftermath currently only supports one D3D device,
// the first one that is initialized.
//
/////////////////////////////////////////////////////////////////////////
#ifdef __d3d11_h__
GFSDK_Aftermath_API GFSDK_Aftermath_DX11_Initialize(GFSDK_Aftermath_Version version, uint32_t flags, ID3D11Device* const pDx11Device);
#endif
#ifdef __d3d12_h__
GFSDK_Aftermath_API GFSDK_Aftermath_DX12_Initialize(GFSDK_Aftermath_Version version, uint32_t flags, ID3D12Device* const pDx12Device);
#endif
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_DX11_CreateContextHandle
// GFSDK_Aftermath_DX12_CreateContextHandle
// ---------------------------------
//
// (pDx11DeviceContext); DX11-Only
// Device context to use with Aftermath.
//
// (pDx12Unknown); DX12-Only
// Command list, Command Queue, or Device to use with Aftermath
// If a device, must be the same device given to GFSDK_Aftermath_DX12_Initialize()
//
// pOutContextHandle;
// The context handle for the specified context/command list/command queue/device
// to be used with future Aftermath calls.
//
//// DESCRIPTION;
// Before Aftermath event markers can be inserted,
// a context handle reference must first be fetched.
//
/////////////////////////////////////////////////////////////////////////
#ifdef __d3d11_h__
GFSDK_Aftermath_API GFSDK_Aftermath_DX11_CreateContextHandle(ID3D11DeviceContext* const pDx11DeviceContext, GFSDK_Aftermath_ContextHandle* pOutContextHandle);
#endif
#ifdef __d3d12_h__
GFSDK_Aftermath_API GFSDK_Aftermath_DX12_CreateContextHandle(IUnknown* const pDx12Unknown, GFSDK_Aftermath_ContextHandle* pOutContextHandle);
#endif
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_API GFSDK_Aftermath_ReleaseContextHandle
// -------------------------------------
//
// contextHandle;
// Context to release
//
// DESCRIPTION;
// Cleans up any resources associated with an Aftermath context
//
/////////////////////////////////////////////////////////////////////////
GFSDK_Aftermath_API GFSDK_Aftermath_ReleaseContextHandle(const GFSDK_Aftermath_ContextHandle contextHandle);
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_SetEventMarker
// -------------------------------------
//
// contextHandle;
// Command list currently being populated.
//
// markerData;
// Pointer to data used for event marker.
// NOTE: If markerSize is also provided, an internal copy will be
// made of this data. In that case there is no need to keep it
// around after this call - stack alloc is safe.
//
// markerSize;
// Size of event marker data in bytes.
// NOTE: Passing a 0 for this parameter is valid, and will instruct
// Aftermath to only copy off the pointer supplied by markerData,
// rather than internally making a copy. This, however, precludes
// Aftermath from storing the marker data in GPU crash dumps.
// NOTE: Aftermath will internally truncate marker data to a maximum
// size of 1024 bytes. Use markerSize=0 and manually manage
// memory for markers if the application requires larger ones.
//
// DESCRIPTION;
// Drops a event into the command stream with a payload that can be
// linked back to the data given here, 'markerData'. It's
// safe to call from multiple threads simultaneously, normal D3D
// API threading restrictions apply.
//
// Using event markers should be considered carefully as they can cause considerable
// CPU overhead when used in high frequency code paths.
//
/////////////////////////////////////////////////////////////////////////
GFSDK_Aftermath_API GFSDK_Aftermath_SetEventMarker(const GFSDK_Aftermath_ContextHandle contextHandle, const void* markerData, const uint32_t markerSize);
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_GetData
// ------------------------------
//
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// numContexts;
// Number of contexts to fetch information for.
//
// pContextHandles;
// Array of contexts containing Aftermath event markers.
//
// pOutContextData;
// OUTPUT: context data for each context requested. Contains event
// last reached on the GPU, and status of context if
// applicable (DX12-Only).
// NOTE: must allocate enough space for 'numContexts' worth of structures.
// stack allocation is fine.
//
// DESCRIPTION;
// Once a TDR/crash/hang has occurred (or whenever you like), call
// this API to retrieve the event last processed by the GPU on the
// given context.
//
/////////////////////////////////////////////////////////////////////////
GFSDK_Aftermath_API GFSDK_Aftermath_GetData(const uint32_t numContexts, const GFSDK_Aftermath_ContextHandle* pContextHandles, GFSDK_Aftermath_ContextData* pOutContextData);
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_GetContextError()
// ------------------------------
//
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// pContextData;
// Context data for which to determine error status.
//
// DESCRIPTION;
// Call this to determine the detailed failure reason for GFSDK_Aftermath_ContextData
// with 'status == GFSDK_Aftermath_Context_Status_Invalid'.
//
/////////////////////////////////////////////////////////////////////////
GFSDK_Aftermath_API GFSDK_Aftermath_GetContextError(const GFSDK_Aftermath_ContextData* pContextData);
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_GetDeviceStatus
// ---------------------------------
//
// pOutStatus;
// OUTPUT: Device status.
//
//// DESCRIPTION;
// Return the status of a D3D device. See GFSDK_Aftermath_Device_Status.
//
/////////////////////////////////////////////////////////////////////////
GFSDK_Aftermath_API GFSDK_Aftermath_GetDeviceStatus(GFSDK_Aftermath_Device_Status* pOutStatus);
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_GetPageFaultInformation
// ---------------------------------
//
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// pOutPageFaultInformation;
// OUTPUT: Information about a page fault which may have occurred.
//
//// DESCRIPTION;
// Return any information available about a recent page fault which
// may have occurred, causing a device removed scenario.
// See GFSDK_Aftermath_PageFaultInformation.
//
// Requires WDDMv2 (Windows 10) or later
//
/////////////////////////////////////////////////////////////////////////
GFSDK_Aftermath_API GFSDK_Aftermath_GetPageFaultInformation(GFSDK_Aftermath_PageFaultInformation* pOutPageFaultInformation);
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_DX12_RegisterResource
// ---------------------------------
//
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// pResource;
// ID3D12Resource to register.
//
// pOutResourceHandle;
// OUTPUT: Aftermath resource handle for the resource that was registered.
//
//// DESCRIPTION;
// Register an ID3D12Resource with Aftermath. This allows Aftermath
// to map a GpuVA of a page fault to the corresponding ID3D12Resource.
//
// NOTE1: This function is only supported on Windows 10 RS4 and RS5.
// It will return GFSDK_Aftermath_Result_FAIL_D3dDllNotSupported, if the
// version of the D3D DLL is not supported.
// NOTE2: This function is not supported in UWP applications.
// NOTE3: This function is not compatible with graphics debuggers, such as
// Nsight Graphics or the Visual Studio Graphics Debugger. It may fail with
// GFSDK_Aftermath_Result_FAIL_D3dDllInterceptionNotSupported when called,
// if such a debugger is active.
//
// This is a BETA FEATURE and may not work with all versions of Windows.
//
/////////////////////////////////////////////////////////////////////////
#if defined(__d3d12_h__)
GFSDK_Aftermath_API GFSDK_Aftermath_DX12_RegisterResource(ID3D12Resource* const pResource, GFSDK_Aftermath_ResourceHandle* pOutResourceHandle);
#endif
/////////////////////////////////////////////////////////////////////////
// GFSDK_Aftermath_DX12_UnregisterResource
// ---------------------------------
//
// DEPRECATED – this functionality will go away in a future release. Do not use!
//
// resourceHandle;
// Aftermath resource handle for a resource that was reagister earlier
// with GFSDK_Aftermath_DX12_RegisterResource().
//
//// DESCRIPTION;
// Unregisters a previously registered resource.
//
// This is a BETA FEATURE and may not work with all versions of Windows.
//
/////////////////////////////////////////////////////////////////////////
#if defined(__d3d12_h__)
GFSDK_Aftermath_API GFSDK_Aftermath_DX12_UnregisterResource(const GFSDK_Aftermath_ResourceHandle resourceHandle);
#endif
/////////////////////////////////////////////////////////////////////////
//
// NOTE: Function table provided - if dynamic loading is preferred.
//
/////////////////////////////////////////////////////////////////////////
#if defined(__d3d11_h__)
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_DX11_Initialize)(GFSDK_Aftermath_Version version, uint32_t flags, ID3D11Device* const pDx11Device);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_DX11_CreateContextHandle)(ID3D11DeviceContext* const pDx11DeviceContext, GFSDK_Aftermath_ContextHandle* pOutContextHandle);
#endif
#if defined(__d3d12_h__)
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_DX12_Initialize)(GFSDK_Aftermath_Version version, uint32_t flags, ID3D12Device* const pDx12Device);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_DX12_CreateContextHandle)(IUnknown* const pDx12CommandList, GFSDK_Aftermath_ContextHandle* pOutContextHandle);
#endif
#if defined(__d3d11_h__) || defined(__d3d12_h__)
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_ReleaseContextHandle)(const GFSDK_Aftermath_ContextHandle contextHandle);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_SetEventMarker)(const GFSDK_Aftermath_ContextHandle contextHandle, const void* markerData, const uint32_t markerSize);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_GetData)(const uint32_t numContexts, const GFSDK_Aftermath_ContextHandle* ppContextHandles, GFSDK_Aftermath_ContextData* pOutContextData);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_GetContextError)(const GFSDK_Aftermath_ContextData* pContextData);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_GetDeviceStatus)(GFSDK_Aftermath_Device_Status* pOutStatus);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_GetPageFaultInformation)(GFSDK_Aftermath_PageFaultInformation* pOutPageFaultInformation);
#endif
#if defined(__d3d12_h__)
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_DX12_RegisterResource)(ID3D12Resource* const pResource, GFSDK_Aftermath_ResourceHandle* pOutResourceHandle);
GFSDK_Aftermath_PFN(GFSDK_AFTERMATH_CALL *PFN_GFSDK_Aftermath_DX12_UnregisterResource)(const GFSDK_Aftermath_ResourceHandle resourceHandle);
#endif
#endif // defined(__d3d11_h__) || defined(__d3d12_h__)
#if defined(VULKAN_H_)
// See VK_NV_device_diagnostics_config
// See VK_NV_device_diagnostic_checkpoints
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#pragma pack(pop)
#endif // GFSDK_Aftermath_H
| 43.306358 | 200 | 0.677389 | [
"object"
] |
c811020e0fe820c998160f2252053614878c3d51 | 3,605 | h | C | src/third_party/swiftshader/third_party/llvm-7.0/llvm/tools/llvm-exegesis/lib/Clustering.h | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 59 | 2019-10-22T16:21:33.000Z | 2022-02-01T20:32:32.000Z | src/third_party/swiftshader/third_party/llvm-7.0/llvm/tools/llvm-exegesis/lib/Clustering.h | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 51 | 2019-10-23T11:55:08.000Z | 2021-12-21T06:32:11.000Z | src/third_party/swiftshader/third_party/llvm-7.0/llvm/tools/llvm-exegesis/lib/Clustering.h | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 15 | 2019-10-22T19:56:12.000Z | 2022-01-12T14:45:15.000Z | //===-- Clustering.h --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Utilities to compute benchmark result clusters.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_EXEGESIS_CLUSTERING_H
#define LLVM_TOOLS_LLVM_EXEGESIS_CLUSTERING_H
#include "BenchmarkResult.h"
#include "llvm/Support/Error.h"
#include <vector>
namespace exegesis {
class InstructionBenchmarkClustering {
public:
// Clusters `Points` using DBSCAN with the given parameters. See the cc file
// for more explanations on the algorithm.
static llvm::Expected<InstructionBenchmarkClustering>
create(const std::vector<InstructionBenchmark> &Points, size_t MinPts,
double Epsilon);
class ClusterId {
public:
static ClusterId noise() { return ClusterId(kNoise); }
static ClusterId error() { return ClusterId(kError); }
static ClusterId makeValid(size_t Id) { return ClusterId(Id); }
ClusterId() : Id_(kUndef) {}
bool operator==(const ClusterId &O) const { return Id_ == O.Id_; }
bool operator<(const ClusterId &O) const { return Id_ < O.Id_; }
bool isValid() const { return Id_ <= kMaxValid; }
bool isUndef() const { return Id_ == kUndef; }
bool isNoise() const { return Id_ == kNoise; }
bool isError() const { return Id_ == kError; }
// Precondition: isValid().
size_t getId() const {
assert(isValid());
return Id_;
}
private:
explicit ClusterId(size_t Id) : Id_(Id) {}
static constexpr const size_t kMaxValid =
std::numeric_limits<size_t>::max() - 4;
static constexpr const size_t kNoise = kMaxValid + 1;
static constexpr const size_t kError = kMaxValid + 2;
static constexpr const size_t kUndef = kMaxValid + 3;
size_t Id_;
};
struct Cluster {
Cluster() = delete;
explicit Cluster(const ClusterId &Id) : Id(Id) {}
const ClusterId Id;
// Indices of benchmarks within the cluster.
std::vector<int> PointIndices;
};
ClusterId getClusterIdForPoint(size_t P) const {
return ClusterIdForPoint_[P];
}
const std::vector<InstructionBenchmark> &getPoints() const { return Points_; }
const Cluster &getCluster(ClusterId Id) const {
assert(!Id.isUndef() && "unlabeled cluster");
if (Id.isNoise()) {
return NoiseCluster_;
}
if (Id.isError()) {
return ErrorCluster_;
}
return Clusters_[Id.getId()];
}
const std::vector<Cluster> &getValidClusters() const { return Clusters_; }
// Returns true if the given point is within a distance Epsilon of each other.
bool isNeighbour(const std::vector<BenchmarkMeasure> &P,
const std::vector<BenchmarkMeasure> &Q) const;
private:
InstructionBenchmarkClustering(
const std::vector<InstructionBenchmark> &Points, double EpsilonSquared);
llvm::Error validateAndSetup();
void dbScan(size_t MinPts);
std::vector<size_t> rangeQuery(size_t Q) const;
const std::vector<InstructionBenchmark> &Points_;
const double EpsilonSquared_;
int NumDimensions_ = 0;
// ClusterForPoint_[P] is the cluster id for Points[P].
std::vector<ClusterId> ClusterIdForPoint_;
std::vector<Cluster> Clusters_;
Cluster NoiseCluster_;
Cluster ErrorCluster_;
};
} // namespace exegesis
#endif // LLVM_TOOLS_LLVM_EXEGESIS_CLUSTERING_H
| 31.622807 | 80 | 0.651318 | [
"vector"
] |
c8172f0038f6a196e83b2854bf4ddab4552c929a | 90,538 | h | C | thirdparty/cgal/CGAL-4.13/include/CGAL/Dart_iterators.h | st4ll1/dust3d | c1de02f7ddcfdacc730cc96740f8073f87e7818c | [
"MIT"
] | null | null | null | thirdparty/cgal/CGAL-4.13/include/CGAL/Dart_iterators.h | st4ll1/dust3d | c1de02f7ddcfdacc730cc96740f8073f87e7818c | [
"MIT"
] | null | null | null | thirdparty/cgal/CGAL-4.13/include/CGAL/Dart_iterators.h | st4ll1/dust3d | c1de02f7ddcfdacc730cc96740f8073f87e7818c | [
"MIT"
] | null | null | null | // Copyright (c) 2010-2011 CNRS and LIRIS' Establishments (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0+
//
// Author(s) : Guillaume Damiand <guillaume.damiand@liris.cnrs.fr>
//
#ifndef CGAL_DART_ITERATORS_HH
#define CGAL_DART_ITERATORS_HH 1
#include <CGAL/Combinatorial_map_iterators_base.h>
namespace CGAL {
/** @file Dart_iterators.h
* Definition of dart iterators. There are 9 iterators:
* - CMap_dart_iterator_basic_of_orbit<Map,Beta...>
* - CMap_dart_iterator_basic_of_cell<Map,i,d>
* - CMap_dart_iterator_basic_of_all
* - CMap_dart_iterator_basic_of_involution<Map,i,d>
* - CMap_dart_iterator_basic_of_involution_inv<Map,i,d>
* - CMap_dart_iterator_of_orbit<Map,Beta...>
* - CMap_dart_iterator_of_cell<Map,i,d>
* - CMap_dart_iterator_of_involution<Map,i,d>
* - CMap_dart_iterator_of_involution_inv<Map,i,d>
* but many specializations to optimize specific cases.
*
*/
//****************************************************************************
//**********************BASIC ITERATORS***************************************
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_orbit<Map, Beta...>: to iterate
* on the darts of the orbit <Beta...>
*/
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template<typename Map,bool Const,int... Beta>
class CMap_dart_iterator_basic_of_orbit_generic;
#else
template <typename Map,bool Const,int B1=-1,int B2=-1,int B3=-1,int B4=-1,
int B5=-1,int B6=-1,int B7=-1,int B8=-1,int B9=-1>
class CMap_dart_iterator_basic_of_orbit_generic;
template <typename Map,bool Const,int B1=-1,int B2=-1,int B3=-1,int B4=-1,
int B5=-1,int B6=-1,int B7=-1,int B8=-1,int B9=-1>
struct Get_CMap_dart_iterator_basic_of_orbit;
template<typename Map,bool Const,int B1,int B2,int B3,int B4,int B5,int B6,
int B7,int B8,int B9>
struct Get_CMap_dart_iterator_basic_of_orbit
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1,B2,B3,B4,
B5,B6,B7,B8,B9> type;
};
template<typename Map,bool Const,int B1,int B2,int B3,int B4,int B5,int B6,
int B7,int B8>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,B3,B4,B5,B6,B7,B8,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1,B2,B3,B4,B5,
B6,B7,B8> type;
};
template<typename Map,bool Const,int B1,int B2,int B3,int B4,int B5,int B6,
int B7>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,B3,B4,B5,B6,B7,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,
B1,B2,B3,B4,B5,
B6,B7> type;
};
template<typename Map,bool Const,int B1,int B2,int B3,int B4,int B5,int B6>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,B3,B4,B5,B6,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1,B2,B3,B4,
B5,B6> type;
};
template<typename Map,bool Const,int B1,int B2,int B3,int B4,int B5>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,B3,B4,B5,-1,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,B1,B2,B3,B4,
B5,Const> type;
};
template<typename Map,bool Const,int B1,int B2,int B3,int B4>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,B3,B4,-1,-1,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1,B2,B3,
B4> type;
};
template<typename Map, int B1,int B2,int B3,bool Const>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,B3,-1,-1,-1,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1,B2,B3> type;
};
template<typename Map, int B1,int B2,bool Const>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,B2,-1,-1,-1,-1,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1,B2> type;
};
template<typename Map, int B1,bool Const>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
B1,-1,-1,-1,-1,-1,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const,B1> type;
};
template<typename Map,bool Const>
struct Get_CMap_dart_iterator_basic_of_orbit<Map,Const,
-1,-1,-1,-1,-1,-1,-1,-1,-1>
{
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,Const> type;
};
#endif //CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
//****************************************************************************
// Case when Beta... is empty: iterator of self
template <typename Map_,bool Const>
class CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_orbit<Map,0>: iterate onto orbit <beta0>.
* Begin by turning around the facet with beta0, then turn if
* necessary in the second direction by using beta1.
*/
template <typename Map_,bool Const>
class CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart):
Base(amap, adart),
mfirst_dir(true)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mfirst_dir(true)
{}
/// Assignment operator.
Self& operator= (const Self & aiterator)
{
if (this != &aiterator)
{
Base::operator=(aiterator);
mfirst_dir = aiterator.mfirst_dir;
}
return *this;
}
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mfirst_dir = true;
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mfirst_dir && this->mmap->is_free(*this, 0))
{
this->set_current_dart(this->mfirst_dart);
mfirst_dir = false;
this->mprev_op = OP_JUMP;
}
else
{
this->mprev_op = OP_BETAI;
}
if (mfirst_dir)
{
CGAL_assertion(!this->mmap->is_free(*this, 0));
this->set_current_dart(this->mmap->beta(*this, 0));
if ((*this)==this->mfirst_dart)
{
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
}
}
else
{
if (this->mmap->is_free(*this, 1))
{
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
}
else
{
this->set_current_dart(this->mmap->beta(*this, 1));
this->mprev_op = OP_BETAI_INV;
}
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Boolean: true iff we turn in the first direction (i.e. using beta0).
bool mfirst_dir;
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_orbit<Map,1>: iterate onto orbit <beta1>.
* Begin by turning around the facet with beta1, then turn if
* necessary in the second direction by using beta0.
*/
template <typename Map_,bool Const>
class CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart):
Base(amap, adart),
mfirst_dir(true)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mfirst_dir(true)
{}
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mfirst_dir = true;
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mfirst_dir && this->mmap->is_free(*this, 1))
{
this->set_current_dart(this->mfirst_dart);
mfirst_dir = false;
this->mprev_op = OP_JUMP;
}
else
{
this->mprev_op = OP_BETAI;
}
if (mfirst_dir)
{
CGAL_assertion(!this->mmap->is_free(*this, 1));
this->set_current_dart(this->mmap->beta(*this, 1));
if ((*this)==this->mfirst_dart)
{
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
}
}
else
{
if (this->mmap->is_free(*this, 0))
{
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
}
else
{
this->set_current_dart(this->mmap->beta(*this, 0));
this->mprev_op = OP_BETAI_INV;
}
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Boolean: true iff we turn in the first direction (i.e. using beta0).
bool mfirst_dir;
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_orbit<Bi>: to iterate
* on the darts of the orbit <Bi> (2<=Bi<=dimension)
* (not for beta0 and beta1 which are special cases).
*/
template <typename Map_,bool Const,int Bi>
class CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,Bi>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,Bi> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart):
Base(amap, adart)
{ CGAL_static_assertion( Bi>=2 && Bi<=Map::dimension ); }
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{ CGAL_static_assertion( Bi>=2 && Bi<=Map::dimension ); }
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if ((*this)!=this->mfirst_dart || this->mmap->is_free(*this, Bi))
{
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
}
else
{
this->set_current_dart(this->mmap->beta(*this, Bi));
this->mprev_op = OP_BETAI;
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_two_beta<Bi,delta>: to iterate
* on the darts of the orbit <Bi,Bi+delta>: Bi<Bi+delta<=dimension.
* This general case if for Bi>1 and delta>1.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_two_beta.
*/
template <typename Map_,bool Const,int Bi,unsigned int delta>
class CMap_dart_iterator_basic_of_two_beta :
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,Bi,delta> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
CGAL_static_assertion( Bi>1 && delta>1 && Bi+delta<=Map::dimension );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart):
Base(amap, adart),
mcurdart(0)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mcurdart(0)
{}
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mcurdart=0;
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mcurdart==0)
{
if (!this->mmap->is_free(*this, Bi))
{
this->set_current_dart(this->mmap->beta(*this, Bi));
this->mprev_op = OP_BETAI;
mcurdart=1;
}
else
{
if (!this->mmap->is_free(*this, Bi+delta))
{
this->set_current_dart(this->mmap->beta(*this, Bi+delta));
this->mprev_op = OP_BETAJ;
mcurdart=3;
}
else
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
}
}
else if (mcurdart==1)
{
if (!this->mmap->is_free(*this, Bi+delta))
{
this->set_current_dart(this->mmap->beta(*this, Bi+delta));
this->mprev_op = OP_BETAJ;
mcurdart=2;
}
else
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
}
else if (mcurdart==2)
{
CGAL_assertion(!this->mmap->is_free(*this, Bi));
this->set_current_dart(this->mmap->beta(*this, Bi));
this->mprev_op = OP_BETAI;
mcurdart=3;
}
else
{
CGAL_assertion (mcurdart==3);
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
private:
/// mcurdart: number of the current dart (0,1,2 or 3).
char mcurdart;
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_two_beta<Bi,delta>: to iterate
* on the darts of the orbit <Bi,Bi+delta>: Bi<Bi+delta<=dimension.
* Special case for Bi==0 and delta==2.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_two_beta.
*/
template <typename Map_,bool Const>
class CMap_dart_iterator_basic_of_two_beta<Map_,Const,0,2> :
public CMap_extend_iterator
<Map_, CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0>, 2>
{
public:
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,0,2> Self;
typedef CMap_extend_iterator
<Map_, CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0>, 2> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
CGAL_static_assertion( 2<=Map::dimension );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_two_beta<Bi,delta>: to iterate
* on the darts of the orbit <Bi,Bi+delta>: Bi<Bi+delta<=dimension.
* Special case for Bi==1 and delta==1.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_two_beta.
*/
template <typename Map_,bool Const>
class CMap_dart_iterator_basic_of_two_beta<Map_,Const,1,1> :
public CMap_extend_iterator
<Map_, CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1>, 2>
{
public:
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,1,1> Self;
typedef CMap_extend_iterator
<Map_, CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1>, 2> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
CGAL_static_assertion( 2<=Map::dimension );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_two_beta<Bi,delta>: to iterate
* on the darts of the orbit <Bi,Bi+delta>: Bi<Bi+delta<=dimension.
* Special case for Bi==0 and delta>2.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_two_beta.
*/
template <typename Map_,bool Const, unsigned int delta>
class CMap_dart_iterator_basic_of_two_beta<Map_,Const,0,delta> :
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,0,delta> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
CGAL_static_assertion( delta>1 && delta<=Map::dimension );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart):
Base(amap, adart),
mit(amap, adart),
mexist_betaj(false),
mprev_betaj(false),
mfirst_border(true)
{ if (adart!=this->mmap->null_handle)
mexist_betaj=!this->mmap->is_free(adart, delta); }
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mit(amap, adart),
mexist_betaj(false),
mprev_betaj(false),
mfirst_border(true)
{ if (adart!=this->mmap->null_handle)
mexist_betaj=!this->mmap->is_free(adart, delta); }
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mexist_betaj && !mprev_betaj)
{
mprev_betaj = true;
mfirst_border = ! mfirst_border;
this->set_current_dart(this->mmap->beta(*this, delta));
this->mprev_op = OP_BETAJ;
}
else
{
mprev_betaj = false;
++mit;
this->mprev_op = mit.prev_operation();
if ( !mit.cont() )
this->set_current_dart(this->mmap->null_handle);
else
{
if ( !mfirst_border )
this->set_current_dart(this->mmap->beta(mit, delta));
else
this->set_current_dart(mit);
}
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mit.rewind();
mprev_betaj = false;
mfirst_border = true;
}
private:
/// Iterator on beta0
CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0> mit;
/// Boolean: true iff there are two half facets.
bool mexist_betaj;
/// Boolean: true iff the last ++ used betaj.
bool mprev_betaj;
/// Boolean: true iff the current dart is on the first border.
bool mfirst_border;
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_two_beta<Bi,delta>: to iterate
* on the darts of the orbit <Bi,Bi+delta>: Bi<Bi+delta<=dimension.
* Special case for Bi==1 and delta>1.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_two_beta.
*/
template <typename Map_,bool Const, unsigned int delta>
class CMap_dart_iterator_basic_of_two_beta<Map_,Const,1,delta> :
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,1,delta> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
CGAL_static_assertion( delta>1 && delta+1<=Map::dimension );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart):
Base(amap, adart),
mit(amap, adart),
mexist_betaj(false),
mprev_betaj(false),
mfirst_border(true)
{ if (adart!=this->mmap->null_handle)
mexist_betaj=!this->mmap->is_free(adart, 1+delta); }
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mit(amap, adart),
mexist_betaj(false),
mprev_betaj(false),
mfirst_border(true)
{ if (adart!=this->mmap->null_handle)
mexist_betaj=!this->mmap->is_free(adart, 1+delta); }
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mexist_betaj && !mprev_betaj)
{
mprev_betaj = true;
mfirst_border = ! mfirst_border;
this->set_current_dart(this->mmap->beta(*this, 1+delta));
this->mprev_op = OP_BETAJ;
}
else
{
mprev_betaj = false;
++mit;
this->mprev_op = mit.prev_operation();
if ( !mit.cont() )
this->set_current_dart(this->mmap->null_handle);
else
{
if ( !mfirst_border )
this->set_current_dart(this->mmap->beta(mit, 1+delta));
else
this->set_current_dart(mit);
}
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mit.rewind();
mprev_betaj = false;
mfirst_border = true;
}
private:
/// Iterator on beta1
CMap_dart_iterator_basic_of_orbit_generic<Map_,Const, 1> mit;
/// Boolean: true iff there are two half facets.
bool mexist_betaj;
/// Boolean: true iff the last ++ used betaj.
bool mprev_betaj;
/// Boolean: true iff the current dart is on the first border.
bool mfirst_border;
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_two_beta<Bi,delta>: to iterate
* on the darts of the orbit <Bi,Bi+delta>: Bi<Bi+delta<=dimension.
* Special case for Bi>1 and delta==1.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_two_beta.
*/
template <typename Map_,bool Const, int Bi>
class CMap_dart_iterator_basic_of_two_beta<Map_,Const,Bi,1> :
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,Bi,1> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
CGAL_static_assertion( Bi>1 && Bi+1<=Map::dimension );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart):
Base(amap, adart),
mfirst_dir(true),
mnext_try_betai(true)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_two_beta(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mfirst_dir(true),
mnext_try_betai(true)
{}
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mfirst_dir = true;
mnext_try_betai = true;
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mfirst_dir)
{
if (mnext_try_betai)
{
if (this->mmap->is_free(*this, Bi))
{
mfirst_dir = false;
if (this->mmap->is_free(this->mfirst_dart, Bi+1))
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
{
this->set_current_dart(this->mmap->beta(this->mfirst_dart, Bi+1));
this->mprev_op = OP_JUMP;
}
}
else
{
this->set_current_dart(this->mmap->beta(*this, Bi));
mnext_try_betai = false;
this->mprev_op = OP_BETAI;
}
}
else
{
if (this->mmap->is_free(*this, Bi+1))
{
mfirst_dir = false;
if (this->mmap->is_free(this->mfirst_dart, Bi+1))
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
{
this->set_current_dart(this->mmap->beta(this->mfirst_dart, Bi+1));
mnext_try_betai = true;
this->mprev_op = OP_JUMP;
}
}
else
{
this->set_current_dart(this->mmap->beta(*this, Bi+1));
if ((*this)==this->mfirst_dart)
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
{
mnext_try_betai = true;
this->mprev_op = OP_BETAJ;
}
}
}
}
else
{
if (mnext_try_betai)
{
if (this->mmap->is_free(*this, Bi))
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
{
this->set_current_dart(this->mmap->beta(*this, Bi));
mnext_try_betai = false;
this->mprev_op = OP_BETAI;
}
}
else
{
if (this->mmap->is_free(*this, Bi+1))
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
{
this->set_current_dart(this->mmap->beta(*this, Bi+1));
mnext_try_betai = true;
this->mprev_op = OP_BETAJ;
}
}
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
private:
/// Boolean: true iff we turn in the first direction (i.e. using betai).
bool mfirst_dir;
/// Boolean: true iff the next ++ must use betai.
bool mnext_try_betai;
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_orbit<Bi,Bj>: to iterate
* on the darts of the orbit <Bi,Bj>: Bi<Bj<=dimension.
* Basic classes do not guaranty correct marks (i.e. do not unmark darts in
* the destructor, possible problem with the rewind). If you are not sure,
* use CMap_dart_iterator_basic_of_orbit.
*/
template <typename Map_,bool Const,int Bi,int Bj>
class CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,Bi,Bj>:
public CMap_dart_iterator_basic_of_two_beta<Map_,Const,Bi,Bj-Bi>
{
public:
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,Bi,Bj> Self;
typedef CMap_dart_iterator_basic_of_two_beta<Map_,Const,Bi,Bj-Bi> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef typename Base::Use_mark Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart) :
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
//****************************************************************************
/* Generic nD version.
*/
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template <typename Map_,bool Const,int Bi,int Bj, int Bk, int... Beta>
class CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,Bi,Bj,Bk,Beta...>:
public CMap_extend_iterator<Map_,
CMap_dart_iterator_basic_of_orbit_generic
<Map_,Const,Bi,Bj,Beta...>,
Bk>
{
public:
typedef CMap_dart_iterator_basic_of_orbit_generic
<Map_,Const,Bi,Bj,Bk,Beta...> Self;
typedef CMap_extend_iterator<Map_,
CMap_dart_iterator_basic_of_orbit_generic
<Map_,Const,Bi,Bj,Beta...>,
Bk> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
#else //CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template <typename Map_,bool Const,int B1,int B2,int B3,int B4,int B5,int B6,
int B7,int B8,int B9>
class CMap_dart_iterator_basic_of_orbit_generic:
public CMap_extend_iterator
<Map_,typename Get_CMap_dart_iterator_basic_of_orbit
<Map_,Const,B1,B2,B4,B5,B6,B7,B8,B9>::type, B3>
{
public:
typedef typename Get_CMap_dart_iterator_basic_of_orbit
<Map_,Const,B1,B2,B3,B4,B5,B6,B7,B8,B9>::type Self;
typedef CMap_extend_iterator
<Map_,typename Get_CMap_dart_iterator_basic_of_orbit
<Map_,Const,B1,B2,B4,B5,B6,B7,B8,B9>::type, B3> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_orbit_generic(Map& amap, Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
#endif //CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
//****************************************************************************
// TODO? we can optimize the iterators<Bi,Bj,Bk> when
// 1<Bi and Bi+2<=Bj and Bj+2<=Bk but there is no real interest...
//****************************************************************************
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template<typename Map,int...Beta>
class CMap_dart_iterator_basic_of_orbit:
public CMap_dart_iterator_basic_of_orbit_generic<Map,false,Beta...>
{
public:
typedef CMap_dart_iterator_basic_of_orbit<Map,Beta...> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map,false,Beta...> Base;
typedef typename Map::Dart_handle Dart_handle;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_orbit(Map& amap,Dart_handle adart):
Base(amap,adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_orbit(Map& amap,Dart_handle adart,size_type amark):
Base(amap,adart,amark)
{}
};
#else
//****************************************************************************
template<typename Map,int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1,
int B6=-1,int B7=-1,int B8=-1,int B9=-1>
class CMap_dart_iterator_basic_of_orbit:
public Get_CMap_dart_iterator_basic_of_orbit<Map,false,B1,B2,B3,B4,
B5,B6,B7,B8,B9>::type
{
public:
typedef CMap_dart_iterator_basic_of_orbit<Map,B1,B2,B3,B4,B5,B6,B7,B8,B9>
Self;
typedef typename Get_CMap_dart_iterator_basic_of_orbit
<Map,false,B1,B2,B3,B4,B5,B6,B7,B8,B9>::type Base;
typedef typename Map::Dart_handle Dart_handle;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_orbit(Map& amap,Dart_handle adart):
Base(amap,adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_orbit(Map& amap,Dart_handle adart,size_type amark):
Base(amap,adart,amark)
{}
};
#endif // CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_all: to iterate onto all the
* darts of the map.
*/
template <typename Map_,bool Const=false>
class CMap_dart_iterator_basic_of_all: public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_all Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_all(Map& amap):
Base(amap, amap.darts().begin())
{}
/// Main constructor.
CMap_dart_iterator_basic_of_all(Map& amap, size_type /*amark*/):
Base(amap, amap.darts().begin())
{}
/// Constructor with a dart in parameter (for end iterator).
CMap_dart_iterator_basic_of_all(Map& amap, Dart_handle adart):
Base(amap, adart)
{}
/// Constructor with a dart in parameter (for end iterator).
CMap_dart_iterator_basic_of_all(Map& amap, Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
Base::operator++();
if ( (*this) != this->mmap->darts().end())
{ this->mprev_op = OP_POP; }
else
{
this->set_current_dart(this->mmap->null_handle);
this->mprev_op = OP_END;
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
};
//****************************************************************************
//***************************CELL*ITERATORS***********************************
//****************************************************************************
//****************************************************************************
// i-Cell iterator in combinatorial map of dimension d, i>1
// i<=Map::dimension+1 (for i==Map::dimension+1, iterate on the connected
// component)
template<typename Map_,int i,int d=Map_::dimension,bool Const=false>
class CMap_dart_iterator_basic_of_cell: public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,i,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
CGAL_static_assertion( i>1 && i<=Map::dimension+1 );
public:
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{
if (adart!=this->mmap->null_handle)
{
this->mmap->mark_null_dart(mmark_number);
this->mmap->mark(adart, mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark(*this, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( unsigned int k=0; k<i; ++k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
for ( unsigned int k=i+1; k<=d; ++k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// i-Cell iterator in combinatorial map of dimension d, i==1.
template<typename Map_,int d,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,1,d,Const>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,1,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{
if (adart!=this->mmap->null_handle)
{
this->mmap->mark(adart, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark((*this), mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( unsigned int k=2; k<=d; ++k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
CGAL_assertion(nd!=this->mmap->null_dart_handle);
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// 0-Cell iterator in combinatorial map of dimension d
template<typename Map_,int d,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,0,d,Const>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,0,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{ if (adart!=this->mmap->null_handle)
{
this->mmap->mark(adart, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark((*this), mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( unsigned int k=2; k<=d; ++k )
{
if ( this->is_unmarked2((*this), 0, k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, 0, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETA0I;
}
else
{
mto_treat.push(this->mmap->beta(*this, 0, k));
}
this->mmap->mark(this->mmap->beta(*this, 0, k), mmark_number);
}
if ( this->is_unmarked2((*this), k, 1, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k, 1);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI1;
}
else
{
mto_treat.push(this->mmap->beta(*this, k, 1));
}
this->mmap->mark(this->mmap->beta(*this, k, 1), mmark_number);
}
for ( unsigned int l=k+1; l<=d; ++l )
{
if ( this->is_unmarked2((*this), k, l, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k, l);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAIJ;
}
else
{
mto_treat.push(this->mmap->beta(*this, k, l));
}
this->mmap->mark(this->mmap->beta(*this, k, l), mmark_number);
}
if ( this->is_unmarked2((*this), l, k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, l, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAJI;
}
else
{
mto_treat.push(this->mmap->beta(*this, l, k));
}
this->mmap->mark(this->mmap->beta(*this, l, k), mmark_number);
}
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
CGAL_assertion(nd!=this->mmap->null_dart_handle);
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// Specialization for edge in 2D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,1,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,2>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,1,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,2> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
};
//****************************************************************************
// Specialization for facet in 2D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,2,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,2,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
};
//****************************************************************************
// Specialization for cc in 2D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,3,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,2>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,3,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,2> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
//****************************************************************************
// Specialization for edge in 3D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,1,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,2,3>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,1,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,2,3> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type /*amark*/): Base(amap, adart)
{}
};
//****************************************************************************
// Specialization for facet in 3D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,2,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,3>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,2,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,3> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type /*amark*/): Base(amap, adart)
{}
};
//****************************************************************************
// Specialization for volume in 3D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,3,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,2>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,3,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,2> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
//****************************************************************************
// Specialization for cc in 3D
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,4,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,2,3>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,4,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1,2,3> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart, amark)
{}
};
//****************************************************************************
/* Class CMap_dart_iterator_basic_of_cell<Map,0,2>: to iterate onto the
* darts of the orbit vertex in 2D.
*/
template <typename Map_,bool Const>
class CMap_dart_iterator_basic_of_cell<Map_,0,2,Const>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,0,2,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart):
Base(amap, adart),
mfirst_dir(true)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_cell(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart),
mfirst_dir(true)
{}
/// Rewind of the iterator to its beginning.
void rewind()
{
Base::rewind();
mfirst_dir = true;
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(this->cont());
if (mfirst_dir)
{
this->set_current_dart(this->mmap->beta(*this, 0, 2));
if ((*this)==this->mmap->null_dart_handle)
{
mfirst_dir = false;
this->set_current_dart(this->mmap->beta(this->mfirst_dart, 2, 1));
if ((*this)==this->mmap->null_dart_handle)
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
{
this->mprev_op = OP_BETAI1;
}
}
else
{
if ((*this)==this->mfirst_dart)
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
this->mprev_op = OP_BETA0I;
}
}
else
{
this->set_current_dart(this->mmap->beta(*this, 2, 1));
if ((*this) == this->mmap->null_dart_handle)
{
this->mprev_op = OP_END;
this->set_current_dart(this->mmap->null_handle);
}
else
this->mprev_op = OP_BETA21;
}
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Boolean: true iff we turn in the first direction (i.e. using beta02).
bool mfirst_dir;
};
//****************************************************************************
//*************************ITERATORS*NON*BASIC********************************
//****************************************************************************
//****************************************************************************
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template<typename Map_,bool Const,int...Beta>
class CMap_dart_iterator_of_orbit_generic:
public CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_orbit_generic
<Map_,Const,Beta...> >
{
public:
typedef CMap_dart_iterator_of_orbit_generic<Map_,Const,Beta...> Self;
typedef CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_orbit_generic
<Map_,Const,Beta...> > Base;
typedef typename Base::Map Map;
typedef typename Base::Dart_handle Dart_handle;
/// Main constructor.
CMap_dart_iterator_of_orbit_generic(Map& amap, Dart_handle adart1):
Base(amap, adart1)
{}
};
//****************************************************************************
template<typename Map_,unsigned int...Beta>
class CMap_dart_iterator_of_orbit:
public CMap_dart_iterator_of_orbit_generic<Map_,false,Beta...>
{
public:
typedef CMap_dart_iterator_of_orbit<Map_,Beta...> Self;
typedef CMap_dart_iterator_of_orbit_generic<Map_,false,Beta...> Base;
typedef typename Base::Dart_handle Dart_handle;
/// Main constructor.
CMap_dart_iterator_of_orbit(Map_& amap, Dart_handle adart):
Base(amap, adart)
{}
};
#else
//****************************************************************************
template<typename Map_,bool Const,int B1=-1,int B2=-1,int B3=-1,int B4=-1,
int B5=-1,int B6=-1,int B7=-1,int B8=-1,int B9=-1>
class CMap_dart_iterator_of_orbit_generic:
public CMap_non_basic_iterator<Map_,
typename
Get_CMap_dart_iterator_basic_of_orbit
<Map_,Const,B1,B2,B3,B4,B5,
B6,B7,B8,B9>::type>
{
public:
typedef CMap_dart_iterator_of_orbit_generic<Map_,Const,B1,B2,B3,B4,B5,
B6,B7,B8,B9> Self;
typedef CMap_non_basic_iterator<Map_,
typename
Get_CMap_dart_iterator_basic_of_orbit
<Map_,Const,B1,B2,B3,B4,B5,
B6,B7,B8,B9>::type> Base;
typedef typename Base::Map Map;
typedef typename Base::Dart_handle Dart_handle;
/// Main constructor.
CMap_dart_iterator_of_orbit_generic(Map& amap, Dart_handle adart1):
Base(amap, adart1)
{}
};
//****************************************************************************
template<typename Map,int B1=-1,int B2=-1,int B3=-1,int B4=-1,
int B5=-1,int B6=-1,int B7=-1,int B8=-1,int B9=-1>
class CMap_dart_iterator_of_orbit:
public CMap_dart_iterator_of_orbit_generic<Map,false,
B1,B2,B3,B4,B5,B6,B7,B8,B9>
{
public:
typedef CMap_dart_iterator_of_orbit<Map,B1,B2,B3,B4,B5,B6,B7,B8,B9> Self;
typedef CMap_dart_iterator_of_orbit_generic<Map,false,
B1,B2,B3,B4,B5,B6,B7,B8,B9> Base;
typedef typename Base::Dart_handle Dart_handle;
/// Main constructor.
CMap_dart_iterator_of_orbit(Map& amap, Dart_handle adart):
Base(amap, adart)
{}
};
#endif // CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
//****************************************************************************
template<typename Map_,int i,int d=Map_::dimension,bool Const=false>
class CMap_dart_iterator_of_cell:
public CMap_non_basic_iterator<Map_,CMap_dart_iterator_basic_of_cell
<Map_,i,d,Const> >
{
public:
typedef CMap_dart_iterator_basic_of_cell<Map_,i,d,Const> Self;
typedef CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_cell
<Map_,i,d,Const> > Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
/// Main constructor.
CMap_dart_iterator_of_cell(Map& amap, Dart_handle adart1):
Base(amap, adart1)
{}
};
//****************************************************************************
//********************ITERATOR*INVOLUTION*************************************
//****************************************************************************
// i-involution iterator in combinatorial map of dimension d,
// 2<i<=Map::dimension. Iterate by using all beta between 0 and d,
// except beta(i-1), betai and beta(i+1)
template<typename Map_,int i,int d=Map_::dimension,bool Const=false>
class CMap_dart_iterator_basic_of_involution;
template<typename Map_,int i,int d,bool Const>
class CMap_dart_iterator_basic_of_involution:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,i,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{
CGAL_assertion( d>=3 && d<=Map::dimension );
CGAL_assertion( i>=3 && i<=Map::dimension );
if (adart!=this->mmap->null_handle)
{
this->mmap->mark(adart, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark((*this), mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( int k=0; k<2; ++k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
for ( int k=2; k<=d; ++k )
{
if ( k!=i-1 && k!=i && k!=i+1 &&
this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// i-involution iterator in combinatorial map of dimension d,
// 2<i<=Map::dimension. Iterate by using all beta between 0 and d,
// except beta(i-1), betai and beta(i+1), by inversing order between
// beta0 and beta1
template<typename Map_,int i,int d=Map_::dimension,bool Const=false>
class CMap_dart_iterator_basic_of_involution_inv:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,i,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{
CGAL_assertion( i>=3 && i<=Map::dimension );
if (adart!=this->mmap->null_handle)
{
this->mmap->mark(adart, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark((*this), mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( int k=1; k>=0; --k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
for ( int k=2; k<=d; ++k )
{
if ( k!=i-1 && k!=i && k!=i+1 &&
this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension d.
// Iterate by using all beta between 3 and d.
template<typename Map_,int d,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,1,d,Const>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,1,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{ if (adart!=this->mmap->null_handle)
{
this->mmap->mark(adart, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark_null_dart(mmark_number);
this->mmap->mark((*this), mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( unsigned int k=3; k<=d; ++k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension d.
// Iterate by using all beta between 3 and d.
template<typename Map_,int d,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,1,d,Const>:
public CMap_dart_iterator_basic_of_involution<Map_,1,d,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,1,d,Const> Self;
typedef CMap_dart_iterator_basic_of_involution<Map_,1,d,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart,amark)
{}
};
//****************************************************************************
// 2-involution iterator in combinatorial map of dimension d.
// Iterate by using all beta between 4 and d.
template<typename Map_,int d,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,2,d,Const>:
public CMap_dart_iterator<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,2,d,Const> Self;
typedef CMap_dart_iterator<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart),
mmark_number(amark)
{ if ( adart!=this->mmap->null_handle)
{
this->mmap->mark(adart, mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
}
/// Rewind of the iterator to its beginning.
void rewind()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
Base::rewind();
mto_treat = std::queue<Dart_handle>();
this->mmap->mark((*this), mmark_number);
this->mmap->mark_null_dart(mmark_number);
}
/// Prefix ++ operator.
Self& operator++()
{
CGAL_assertion(mmark_number != Map::INVALID_MARK);
CGAL_assertion(this->cont());
Dart_handle nd = this->mmap->null_handle;
for ( unsigned int k=4; k<=d; ++k )
{
if ( this->is_unmarked((*this), k, mmark_number) )
{
if (nd == this->mmap->null_handle)
{
nd = this->mmap->beta(*this, k);
CGAL_assertion(nd!=this->mmap->null_dart_handle);
this->mprev_op = OP_BETAI;
}
else
{
mto_treat.push(this->mmap->beta(*this, k));
}
this->mmap->mark(this->mmap->beta(*this, k), mmark_number);
}
}
if (nd == this->mmap->null_handle)
{
if (!mto_treat.empty())
{
nd = mto_treat.front();
mto_treat.pop();
this->mprev_op = OP_POP;
}
else
{
this->mprev_op = OP_END;
}
}
this->set_current_dart(nd);
return *this;
}
/// Postfix ++ operator.
Self operator++(int)
{ Self res=*this; operator ++(); return res; }
protected:
/// Queue of darts to process.
std::queue<Dart_handle> mto_treat;
/// Index of the used mark.
size_type mmark_number;
};
//****************************************************************************
// 2-involution iterator in combinatorial map of dimension d.
// Iterate by using all beta between 4 and d.
template<typename Map_,int d,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,2,d,Const>:
public CMap_dart_iterator_basic_of_involution<Map_,2,d,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,2,d,Const> Self;
typedef CMap_dart_iterator_basic_of_involution<Map_,2,d,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_true Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type amark):
Base(amap, adart,amark)
{}
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension 2.
// Empty iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,1,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,1,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension 2.
// self iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,1,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,1,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 2-involution iterator in combinatorial map of dimension 2.
// self iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,2,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,2,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 2-involution iterator in combinatorial map of dimension 2.
// self iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,2,2,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,2,2,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension 3.
// Beta3 iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,1,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,3>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,1,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,3> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension 3.
// Beta3 iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,1,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,3>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,1,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,3> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 2-involution iterator in combinatorial map of dimension 3.
// Self iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,2,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,2,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type /* amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 2-involution iterator in combinatorial map of dimension 3.
// Self iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,2,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,2,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension 3.
// Beta1 iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution<Map_,3,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1>
{
public:
typedef CMap_dart_iterator_basic_of_involution<Map_,3,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,1> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
// 1-involution iterator in combinatorial map of dimension 3.
// Beta0 iterator.
template<typename Map_,bool Const>
class CMap_dart_iterator_basic_of_involution_inv<Map_,3,3,Const>:
public CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0>
{
public:
typedef CMap_dart_iterator_basic_of_involution_inv<Map_,3,3,Const> Self;
typedef CMap_dart_iterator_basic_of_orbit_generic<Map_,Const,0> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Map Map;
typedef typename Map::size_type size_type;
typedef Tag_false Use_mark;
/// True iff this iterator is basic
typedef Tag_true Basic_iterator;
public:
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart,
size_type /*amark*/):
Base(amap, adart)
{}
/// Main constructor.
CMap_dart_iterator_basic_of_involution_inv(Map& amap,
Dart_handle adart):
Base(amap, adart)
{}
};
//****************************************************************************
template<typename Map_,int i,int d=Map_::dimension,bool Const=false>
class CMap_dart_iterator_of_involution:
public CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_involution
<Map_,i,d,Const> >
{
public:
typedef CMap_dart_iterator_of_involution<Map_,i,d,Const> Self;
typedef CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_involution
<Map_,i,d,Const> > Base;
/// Main constructor.
CMap_dart_iterator_of_involution(typename Base::Map& amap,
typename Base::Dart_handle adart1):
Base(amap, adart1)
{}
};
//****************************************************************************
template<typename Map_,int i,int d=Map_::dimension,bool Const=false>
class CMap_dart_iterator_of_involution_inv:
public CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_involution_inv
<Map_,i,d,Const> >
{
public:
typedef CMap_dart_iterator_of_involution_inv<Map_,i,d,Const> Self;
typedef CMap_non_basic_iterator<Map_,
CMap_dart_iterator_basic_of_involution_inv
<Map_,i,d,Const> > Base;
/// Main constructor.
CMap_dart_iterator_of_involution_inv(typename Base::Map& amap,
typename Base::Dart_handle adart1):
Base(amap, adart1)
{}
};
//****************************************************************************
} // namespace CGAL
//******************************************************************************
#endif // CGAL_DART_ITERATORS_HH
//******************************************************************************
| 32.661616 | 83 | 0.570987 | [
"3d"
] |
c818f4b032b9f321a53aca81df4828076c42c1a2 | 459 | h | C | DataStructure/tree/bst.h | CloudHolic/algorithms | cfae9b723e432fd9a84600c2a0082a5412759821 | [
"MIT"
] | null | null | null | DataStructure/tree/bst.h | CloudHolic/algorithms | cfae9b723e432fd9a84600c2a0082a5412759821 | [
"MIT"
] | null | null | null | DataStructure/tree/bst.h | CloudHolic/algorithms | cfae9b723e432fd9a84600c2a0082a5412759821 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
using namespace std;
class bst
{
public:
// Constructor
bst(int size);
// Destructor
~bst();
// Operator overloading
int operator[](const int index);
void insert(const int value);
void remove(const int value);
int find_index(const int value) const;
void clear();
private:
vector<int*> nodes_;
int max_size_, current_size_;
void move_subtree(int parent, int child);
}; | 15.3 | 45 | 0.647059 | [
"vector"
] |
c81947ccbeec5012fd4496d05dcceed39f384b8f | 2,231 | h | C | inc/json.h | github188/GPSTracker-1 | c31580e95d91dfb7da7c12aa02ee4d813f6866dc | [
"BSD-2-Clause"
] | 25 | 2019-08-02T02:45:23.000Z | 2022-03-08T15:48:25.000Z | inc/json.h | PaulPan007/GPSTracker | c31580e95d91dfb7da7c12aa02ee4d813f6866dc | [
"BSD-2-Clause"
] | null | null | null | inc/json.h | PaulPan007/GPSTracker | c31580e95d91dfb7da7c12aa02ee4d813f6866dc | [
"BSD-2-Clause"
] | 20 | 2020-09-06T02:56:27.000Z | 2022-03-19T07:13:50.000Z | /**
* Copyright @ Goome Technologies Co., Ltd. 2009-2019. All rights reserved.
* File name: log_service.h
* Author: 王志华
* Version: 1.0
* Date: 2019-05-21
* Description: 来自于cJSON,删除了大部分不用的功能和特性,print函数完全重写
* Others:
* Function List:
1. 创建对象
2. 添加数字
3. 添加字符串
4. 打印到字符串
5. 释放内存
* History:
1. Date: 2019-03-01
Author: 王志华
Modification: 创建初始版本
2. Date:
Author:
Modification:
*/
#ifndef __JSON_H__
#define __JSON_H__
typedef enum
{
JSON_OBJECT = 0,
JSON_INT,
JSON_DOUBLE,
JSON_STRING,
}JsonDataType;
typedef struct
{
struct JsonObject* next;
struct JsonObject* prev;
struct JsonObject* child;
char* name;
JsonDataType type;
S32 int_value;
char* str_value;
double double_value;
}JsonObject;
/**
* Function: 创建json对象
* Description:无
* Input: 无
* Output: 无
* Return: 指向对象的指针
* Others:
*/
JsonObject* json_create(void);
/**
* Function: 销毁json对象
* Description:使用完以后必须销毁,否则内存泄露
* Input: p_object:指向对象的指针
* Output: 无
* Return: 无
* Others:
*/
void json_destroy(JsonObject* p_object);
/**
* Function: 在json对象中添加一个整数
* Description:
* Input: p_object:指向对象的指针;name:名称;value:值
* Output: 无
* Return: 无
* Others:
*/
JsonObject* json_add_int(JsonObject* p_object, const char* name, const int value);
/**
* Function: 在json对象中添加一个double数值
* Description:float类型也用这个函数
* Input: p_object:指向对象的指针;name:名称;value:值
* Output: 无
* Return: 无
* Others:
*/
JsonObject* json_add_double(JsonObject* p_object, const char* name, const double value);
/**
* Function: 在json对象中添加一个字符串
* Description:对象内部会申请新的内存存储字符串,在销毁对象时释放
* Input: p_object:指向对象的指针;name:名称;value:值
* Output: 无
* Return: 无
* Others:
*/
JsonObject* json_add_string(JsonObject* p_object, const char* name, const char* string);
/**
* Function: 把json对象转成字符串打印到缓存
* Description:
* Input: p_object:指向对象的指针;buffer:缓存;length:缓存长度
* Output: 无
* Return: 无
* Others:
*/
bool json_print_to_buffer(JsonObject* object, char* buffer, const int length);
#endif
| 20.099099 | 92 | 0.621246 | [
"object"
] |
c823ac3b337a705b2dd43ba7ba524ca60d69efa1 | 6,817 | h | C | src/v2i-hub/PortDrayagePlugin/src/PortDrayagePlugin.h | usdot-fhwa-OPS/V2X-Hub | c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c | [
"Apache-2.0"
] | 56 | 2019-04-25T19:06:11.000Z | 2022-03-25T20:26:25.000Z | src/v2i-hub/PortDrayagePlugin/src/PortDrayagePlugin.h | usdot-fhwa-OPS/V2X-Hub | c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c | [
"Apache-2.0"
] | 184 | 2019-04-24T18:20:08.000Z | 2022-03-22T18:56:45.000Z | src/v2i-hub/PortDrayagePlugin/src/PortDrayagePlugin.h | usdot-fhwa-OPS/V2X-Hub | c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c | [
"Apache-2.0"
] | 34 | 2019-04-03T15:21:16.000Z | 2022-03-20T04:26:53.000Z | /**
* Copyright (C) 2019 LEIDOS.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this 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 SRC_PortDrayagePlugin_H_
#define SRC_PortDrayagePlugin_H_
#include "PluginClient.h"
#include <tmx/j2735_messages/testMessage03.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/optional/optional.hpp>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <tmx/j2735_messages/J2735MessageFactory.hpp>
#include <OAIDefaultApi.h>
#include <QEventLoop>
#include <QTimer>
#include <OAIHelpers.h>
#include <QCoreApplication>
#include "WebServiceClient.h"
using namespace std;
using namespace tmx;
using namespace tmx::utils;
using namespace tmx::messages;
using namespace boost::property_tree;
using namespace OpenAPI;
namespace PortDrayagePlugin {
// constant for MobilityOperation strategy
static CONSTEXPR const char *PORT_DRAYAGE_STRATEGY = "carma/port_drayage";
// Enumeration for different operations
enum Operation {
PICKUP,DROPOFF,CHECKPOINT,HOLDING,ENTER_STAGING,EXIT_STAGING,ENTER_PORT,EXIT_PORT
};
std::string operation_to_string( Operation operation ) {
switch(operation) {
case PICKUP:
return "PICKUP";
case DROPOFF:
return "DROPOFF";
case CHECKPOINT:
return "PORT_CHECKPOINT";
case HOLDING:
return "HOLDING_AREA";
case ENTER_STAGING:
return "ENTER_STAGING_AREA";
case EXIT_STAGING:
return "EXIT_STAGING_AREA";
case ENTER_PORT:
return "ENTER_PORT";
case EXIT_PORT:
return "EXIT_PORT";
default:
return "INVALID_OPERATION";
}
}
/**
* PortDrayagePlugin is a V2X-Hub plugin for automating Freight truck interactions for
* moving containers between and Port and a Staging Area. The plugin process MobilityOperation
* messages with the strategy PORT_DRAYAGE_STRATEGY. The payload of this MobilityOperation
* message is a JSON object consisting of mainly :
* action_id : unique identifier for the action
* vehicle_id : unique static identifier for the vehicle (NOT BSMID)
* operation : string enumeration describing the action that is to take place
* This Plugin requires a MySQL database with two table to store all vehicle action (table name: freight) and
* to store the first action for any given vehicle (table name : first_action). Upon initial communication
* with V2X-Hub the vehicle will just send an ENTER_STAGING_AREA actions with no action ID. When this initial
* message is received by V2X-Hub it will query the first_action table for the vehicle first action. Every action
* in the database is linked to a next action. Once the vehicle completes an action it notifies V2X-Hub of completion
* by sending out the action it just completed. V2X-Hub will then query the database for the next linked action
*
* @author Paul Bourelly
* @version 6.2
*/
class PortDrayagePlugin: public PluginClient {
public:
struct PortDrayage_Object {
std::string cmv_id;
std::string cargo_id;
bool cargo;
std::string operation;
double location_lat;
double location_long;
double destination_lat;
double destination_long;
std::string action_id;
std::string next_action;
};
/**
* Construct a new MobililtyOperationPlugin with the given name.
*
* @param name The name to give the plugin for identification purposes
*/
PortDrayagePlugin(std::string);
/**
* Constructor without paramaters
*/
virtual ~PortDrayagePlugin();
int Main();
protected:
/**
* Update Configuration
*/
void UpdateConfigSettings();
// Virtual method overrides.
/**
* Method triggers UpdateConfigSettings() on configuration changes
*/
void OnConfigChanged(const char *key, const char *value);
void OnStateChange(IvpPluginState state);
/**
* Method to create port drayage payload JSON ptree using a PortDrayage_Object.
*
* @param pd_obj Port Drayage object.
* @return json ptree
*/
ptree createPortDrayageJson( const PortDrayage_Object &pd_obj);
/**
* Method to create MobilityOperation XML ptree.
*
* @param ptree json payload
* @return MobilityOperation message XML ptree
*/
ptree createMobilityOperationXml( const ptree &json_payload);
/**
* Handle MobilityOperation message.
*
* @param tsm3Message J2735 MobilityOperation message
* @param routeableMsg JSON MobilityOperation message
*/
void HandleMobilityOperationMessage(tsm3Message &msg, routeable_message &routeableMsg);
/**
* Retrieve next action from freight table using action_id
*
* @param action_id string
*/
PortDrayage_Object retrieveNextAction( const std::string &action_id );
/**
* Retrieve first action from first_action table using cmv_id.
*
* @param cmv_id
* @return PortDrayage_Object of first action
*/
PortDrayage_Object retrieveFirstAction( const std::string &cmv_id );
/**
* Create PortDrayage_Object from ptree JSON.
*
* @param pr PortDrayage JSON
* @return PortDrayage_Object
*/
PortDrayage_Object readPortDrayageJson( const ptree &pr );
/**
* Dynamically inserts HOLDING_AREA action into mysql table between
* current_action and next_action. Current action should be PORT_CHECKPOINT
* and next_action should be EXIT_PORT
*
* @param current_action PORT_CHECKPOINT action
*/
void insert_holding_action_into_table(const PortDrayage_Object ¤t_action );
/**
* Retrieves HOLDING_AREA action when provided with PORT_CHECKPOINT action
* from mysql freight table.
*
* @return action_id of HOLDING_AREA action
*/
std::string retrieve_holding_inspection_action_id( const std::string &action_id );
private:
// Database configuration values
sql::Driver *driver;
sql::Connection *con;
// Prepared Statements
sql::PreparedStatement *next_action_id;
sql::PreparedStatement *current_action;
sql::PreparedStatement *first_action;
sql::PreparedStatement *insert_action;
sql::PreparedStatement *get_action_id_for_previous_action;
sql::PreparedStatement *update_current_action;
// Message Factory for J2735 messages
J2735MessageFactory factory;
// Web Service Client
std::shared_ptr<WebServiceClient> client;
// Port HOLDING_AREA Configuration
double _holding_lat;
double _holding_lon;
};
std::mutex _cfgLock;
}
#endif | 30.569507 | 117 | 0.761772 | [
"object"
] |
c82b84c152d39cef8f1008d78b7d76c1fd06a389 | 2,739 | c | C | src/vm/parrot/6model/reprs/VMIter.c | hoelzro/nqp | 4b5986517e1f56b97ce71704383a8bd073013f3e | [
"Artistic-2.0"
] | 1 | 2015-11-09T01:49:34.000Z | 2015-11-09T01:49:34.000Z | src/vm/parrot/6model/reprs/VMIter.c | tokuhirom/nqp | d317008d0c46e6e62810441f92b8bc4c71063d38 | [
"Artistic-2.0"
] | null | null | null | src/vm/parrot/6model/reprs/VMIter.c | tokuhirom/nqp | d317008d0c46e6e62810441f92b8bc4c71063d38 | [
"Artistic-2.0"
] | null | null | null | #define PARROT_IN_EXTENSION
#include "parrot/parrot.h"
#include "parrot/extend.h"
#include "../sixmodelobject.h"
#include "VMIter.h"
/* This representation's function pointer table. */
static REPROps *this_repr;
/* Creates a new type object of this representation, and associates it with
* the given HOW. */
static PMC * type_object_for(PARROT_INTERP, PMC *HOW) {
/* Create new object instance. */
VMIterInstance *obj = mem_allocate_zeroed_typed(VMIterInstance);
/* Build an STable. */
PMC *st_pmc = create_stable(interp, this_repr, HOW);
STable *st = STABLE_STRUCT(st_pmc);
/* Create type object and point it back at the STable. */
obj->common.stable = st_pmc;
st->WHAT = wrap_object(interp, obj);
PARROT_GC_WRITE_BARRIER(interp, st_pmc);
/* Flag it as a type object. */
MARK_AS_TYPE_OBJECT(st->WHAT);
return st->WHAT;
}
/* Composes the representation. */
static void compose(PARROT_INTERP, STable *st, PMC *repr_info) {
/* Nothing to do yet, but should handle type in the future. */
}
/* Creates a new instance based on the type object. */
static PMC * allocate(PARROT_INTERP, STable *st) {
VMIterInstance *obj = mem_allocate_zeroed_typed(VMIterInstance);
obj->common.stable = st->stable_pmc;
return wrap_object(interp, obj);
}
/* Initialize a new instance. */
static void initialize(PARROT_INTERP, STable *st, void *data) {
/* Nothing to do here. */
}
/* Copies to the body of one object to another. */
static void copy_to(PARROT_INTERP, STable *st, void *src, void *dest) {
VMIterBody *src_body = (VMIterBody *)src;
VMIterBody *dest_body = (VMIterBody *)dest;
/* Nothing to do yet. */
}
/* This Parrot-specific addition to the API is used to free an object. */
static void gc_free(PARROT_INTERP, PMC *obj) {
mem_sys_free(PMC_data(obj));
PMC_data(obj) = NULL;
}
/* Gets the storage specification for this representation. */
static storage_spec get_storage_spec(PARROT_INTERP, STable *st) {
storage_spec spec;
spec.inlineable = STORAGE_SPEC_REFERENCE;
spec.boxed_primitive = STORAGE_SPEC_BP_NONE;
spec.can_box = 0;
spec.bits = sizeof(void *) * 8;
spec.align = ALIGNOF1(void *);
return spec;
}
/* Initializes the VMIter representation. */
REPROps * VMIter_initialize(PARROT_INTERP) {
/* Allocate and populate the representation function table. */
this_repr = mem_allocate_zeroed_typed(REPROps);
this_repr->type_object_for = type_object_for;
this_repr->compose = compose;
this_repr->allocate = allocate;
this_repr->initialize = initialize;
this_repr->copy_to = copy_to;
this_repr->gc_free = gc_free;
this_repr->get_storage_spec = get_storage_spec;
return this_repr;
}
| 32.223529 | 75 | 0.706097 | [
"object"
] |
c82cbecfa74ee9e23f3ecef31068771e0c272b61 | 19,275 | h | C | src/include/ngram/ngram-count.h | mjansche/opengrm-ngram | f68e8207cdff0ba771d3b31d87cba471275a4d3c | [
"Apache-2.0"
] | 6 | 2016-02-19T18:04:04.000Z | 2020-06-16T19:19:28.000Z | src/include/ngram/ngram-count.h | mjansche/opengrm-ngram | f68e8207cdff0ba771d3b31d87cba471275a4d3c | [
"Apache-2.0"
] | null | null | null | src/include/ngram/ngram-count.h | mjansche/opengrm-ngram | f68e8207cdff0ba771d3b31d87cba471275a4d3c | [
"Apache-2.0"
] | 4 | 2016-11-20T03:37:49.000Z | 2021-07-09T08:56:07.000Z |
// 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.
//
// Copyright 2005-2016 Brian Roark and Google, Inc.
// NGram counting class.
#ifndef NGRAM_NGRAM_COUNT_H_
#define NGRAM_NGRAM_COUNT_H_
#include <string>
#include <type_traits>
#include <vector>
#include <fst/log.h>
#include <fst/extensions/far/far.h>
#include <fst/fstlib.h>
#include <ngram/hist-arc.h>
#include <ngram/ngram-count-of-counts.h>
#include <ngram/ngram-model.h>
#include <ngram/util.h>
#include <unordered_map>
namespace ngram {
// NGramCounter class.
template <class Weight, class Label = int32>
class NGramCounter {
public:
// Construct an NGramCounter object counting n-grams of order less
// or equal to 'order'. When 'epsilon_as_backoff' is 'true', the epsilon
// transition in the input Fst are treated as failure backoff transitions
// and would trigger the length of the current context to be decreased
// by one ("pop front").
explicit NGramCounter(size_t order, bool epsilon_as_backoff = false,
float delta = 1e-9F)
: order_(order),
pair_arc_maps_(order),
epsilon_as_backoff_(epsilon_as_backoff),
delta_(delta),
error_(false) {
if (order == 0) {
NGRAMERROR() << "order must be greater than 0";
SetError();
return;
}
backoff_ = states_.size();
states_.push_back(CountState(-1, 1, Weight::Zero(), -1));
if (order == 1) {
initial_ = backoff_;
} else {
initial_ = states_.size();
states_.push_back(CountState(backoff_, 2, Weight::Zero(), -1));
}
}
// Extract counts from the input acyclic Fst. Return 'true' when
// the counting from the Fst was successful and false otherwise.
template <class Arc>
bool Count(const fst::Fst<Arc> &fst) {
if (Error()) return false;
if (fst.Properties(fst::kString, false)) {
return CountFromStringFst(fst);
} else if (fst.Properties(fst::kTopSorted, true)) {
return CountFromTopSortedFst(fst);
} else {
fst::VectorFst<Arc> vfst(fst);
return Count(&vfst);
}
}
// Extract counts from input mutable acyclic Fst, top sort the input
// fst in place when needed. Return 'true' when the counting from
// the Fst was successful and false otherwise.
template <class Arc>
bool Count(fst::MutableFst<Arc> *fst) {
if (Error()) {
return false;
}
if (fst->Properties(fst::kString, true)) {
return CountFromStringFst(*fst);
}
bool acyclic = TopSort(fst);
if (!acyclic) {
// TODO(allauzen): support key in error message.
LOG(ERROR) << "NGramCounter::Count: input not an acyclic fst";
return false;
}
return CountFromTopSortedFst(*fst);
}
// Get an FST representation of the ngram counts.
template <class Arc>
void GetFst(fst::MutableFst<Arc> *fst) {
fst->DeleteStates();
if (Error()) return;
for (size_t s = 0; s < states_.size(); ++s) {
fst->AddState();
fst->SetFinal(s, states_[s].final_count.Value());
if (states_[s].backoff_state != -1)
fst->AddArc(s, Arc(0, 0, Arc::Weight::Zero(),
states_[s].backoff_state));
}
for (size_t a = 0; a < arcs_.size(); ++a) {
const CountArc &arc = arcs_[a];
fst->AddArc(arc.origin, Arc(arc.label, arc.label, arc.count.Value(),
arc.destination));
}
fst->SetStart(initial_);
StateCounts(fst);
}
// Returns strings of ngram counts, in reverse context order, e.g., for the
// ngram "feed the angry duck", returns "<{angry,the,feed}, <duck,count>>".
template <class Arc>
void GetReverseContextNGrams(
std::vector<std::pair<std::vector<int>, std::pair<Label, double>>>
*ngram_counts) {
if (Error()) return;
std::vector<int> incoming_words(states_.size(), -1);
std::vector<int> previous_states(states_.size(), -1);
if (order_ > 1) incoming_words[NGramStartState()] = 0;
for (size_t a = 0; a < arcs_.size(); ++a) {
const CountArc &arc = arcs_[a];
if (states_[arc.origin].order < states_[arc.destination].order) {
previous_states[arc.destination] = arc.origin;
incoming_words[arc.destination] = arc.label;
}
}
std::vector<std::vector<int>> reverse_context(states_.size());
for (size_t s = 0; s < states_.size(); ++s) {
int ps = s;
while (ps >= 0) {
if (incoming_words[ps] >= 0)
reverse_context[s].push_back(incoming_words[ps]);
ps = previous_states[ps];
}
if (states_[s].final_count.Value() != Weight::Zero().Value()) {
ngram_counts->push_back(
std::make_pair(reverse_context[s],
std::make_pair(0, states_[s].final_count.Value())));
}
}
for (size_t a = 0; a < arcs_.size(); ++a) {
const CountArc &arc = arcs_[a];
ngram_counts->push_back(
std::make_pair(reverse_context[arc.origin],
std::make_pair(arc.label, arc.count.Value())));
}
}
// Given a state ID and a label, returns the ID of the corresponding
// arc, creating the arc if it does not exist already.
ssize_t FindArc(ssize_t state_id, Label label) {
const CountState &count_state = states_[state_id];
// First determines if there already exists a corresponding arc.
if (count_state.first_arc != -1) {
if (arcs_[count_state.first_arc].label == label)
return count_state.first_arc;
const PairArcMap &arc_map = pair_arc_maps_[count_state.order - 1];
auto iter = arc_map.find(std::make_pair(label, state_id));
if (iter != arc_map.end()) return iter->second;
}
// Otherwise, this arc needs to be created.
return AddArc(state_id, label);
}
// Gets the start state of the counts (<s>).
ssize_t NGramStartState() { return initial_; }
// Gets the unigram state of the counts.
ssize_t NGramUnigramState() { return backoff_; }
// Gets the backoff state for a given state.
ssize_t NGramBackoffState(ssize_t state_id) {
return states_[state_id].backoff_state;
}
// Gets the next state from a found arc.
ssize_t NGramNextState(ssize_t arc_id) {
if (arc_id < 0 || arc_id >= arcs_.size()) return -1;
return arcs_[arc_id].destination;
}
// Sets the weight for an n-gram ending with the stop symbol </s>.
bool SetFinalNGramWeight(ssize_t state_id, Weight weight) {
if (state_id < 0 || state_id >= states_.size()) return false;
states_[state_id].final_count = weight;
return true;
}
// Sets the weight for a found n-gram.
bool SetNGramWeight(ssize_t arc_id, Weight weight) {
if (arc_id < 0 || arc_id >= arcs_.size()) return false;
arcs_[arc_id].count = weight;
return true;
}
// Size of ngram model is the sum of the number of states and number of arcs.
ssize_t GetSize() const { return states_.size() + arcs_.size(); }
// Returns true if counter setup is in a bad state.
bool Error() const { return error_; }
protected:
void SetError() { error_ = true; }
private:
// Data representation for a state.
struct CountState {
ssize_t backoff_state; // ID of the backoff state for the current state.
size_t order; // N-gram order of the state (of the outgoing arcs).
Weight final_count; // Count for n-gram corresponding to superfinal arc.
ssize_t first_arc; // ID of the first outgoing arc at that state.
CountState(ssize_t s, size_t o, Weight c, ssize_t a)
: backoff_state(s), order(o), final_count(c), first_arc(a) {}
};
// Data represention for an arc.
struct CountArc {
ssize_t origin; // ID of the origin state for this arc.
ssize_t destination; // ID of the destination state for this arc.
Label label; // Label.
Weight count; // Count of the n-gram corresponding to this arc.
ssize_t backoff_arc; // ID of backoff arc.
CountArc(ssize_t o, size_t d, Label l, Weight c, ssize_t b)
: origin(o), destination(d), label(l), count(c), backoff_arc(b) {}
};
// A pair (Label, State ID) or (State ID, State ID)
using Pair = std::pair<ssize_t, ssize_t>;
struct PairHash {
size_t operator()(const Pair &p) const {
return (static_cast<size_t>(p.first) * 55697) ^
(static_cast<size_t>(p.second) * 54631);
// TODO(allauzen): run benchmark using Compose's hash function
// return static_cast<size_t>(p.first + p.second * 7853);
}
};
// TODO(allauzen): run benchmark using map instead of unordered map
using PairArcMap = std::unordered_map<Pair, size_t, PairHash>;
// Creates the arc corresponding to label 'label' out of the state
// with ID 'state_id'.
size_t AddArc(ssize_t state_id, Label label) {
CountState count_state = states_[state_id];
ssize_t arc_id = arcs_.size();
// Updates the hash entry for the new arc.
if (count_state.first_arc == -1) {
states_[state_id].first_arc = arc_id;
} else {
pair_arc_maps_[count_state.order - 1].insert(
std::make_pair(std::make_pair(label, state_id), arc_id));
}
// Pre-fills arc with values valid when order_ == 1 and returns
// if nothing else needs to be done.
arcs_.push_back(CountArc(state_id, initial_, label, Weight::Zero(), -1));
if (order_ == 1) return arc_id;
// First compute the backoff arc
ssize_t backoff_arc = count_state.backoff_state == -1
? -1
: FindArc(count_state.backoff_state, label);
// Second compute the destination state.
ssize_t destination;
if (count_state.order == order_) {
// The destination state is the destination of the backoff arc.
destination = arcs_[backoff_arc].destination;
} else {
// The destination state needs to be created.
destination = states_.size();
CountState next_count_state(
backoff_arc == -1 ? backoff_ : arcs_[backoff_arc].destination,
count_state.order + 1, Weight::Zero(), -1);
states_.push_back(next_count_state);
}
// Updates destination and backoff_arc with the newly computed values.
arcs_[arc_id].destination = destination;
arcs_[arc_id].backoff_arc = backoff_arc;
return arc_id;
}
// Increase the count of n-gram corresponding to the arc labeled 'label'
// out of state of ID 'state_id' by 'count'.
ssize_t UpdateCount(ssize_t state_id, Label label, Weight count) {
ssize_t arc_id = FindArc(state_id, label);
ssize_t nextstate_id = arcs_[arc_id].destination;
while (arc_id != -1) {
arcs_[arc_id].count = Plus(arcs_[arc_id].count, count);
arc_id = arcs_[arc_id].backoff_arc;
}
return nextstate_id;
}
// Increase the count of n-gram corresponding to the super-final arc
// out of state of ID 'state_id' by 'count'.
void UpdateFinalCount(ssize_t state_id, Weight count) {
while (state_id != -1) {
states_[state_id].final_count =
Plus(states_[state_id].final_count, count);
state_id = states_[state_id].backoff_state;
}
}
// Puts the sum of counts of non-backoff arcs leaving s on the backoff arc.
template <class Arc>
void StateCounts(fst::MutableFst<Arc> *fst) {
for (size_t s = 0; s < states_.size(); ++s) {
Weight state_count = states_[s].final_count;
if (states_[s].backoff_state != -1) {
fst::MutableArcIterator<fst::MutableFst<Arc>> aiter(fst, s);
ssize_t bo_pos = -1;
for (; !aiter.Done(); aiter.Next()) {
const auto &arc = aiter.Value();
if (arc.ilabel != 0) {
state_count = Plus(state_count, arc.weight.Value());
} else {
bo_pos = aiter.Position();
}
}
if (bo_pos < 0) {
NGRAMERROR() << "backoff arc not found";
SetError();
return;
}
aiter.Seek(bo_pos);
auto arc = aiter.Value();
arc.weight = state_count.Value();
aiter.SetValue(arc);
}
}
}
template <class Arc>
bool CountFromTopSortedFst(const Fst<Arc> &fst);
template <class Arc>
bool CountFromStringFst(const Fst<Arc> &fst);
struct PairCompare {
bool operator()(const Pair &p1, const Pair &p2) const {
return p1.first == p2.first ? p1.second > p2.second : p1.first > p2.first;
}
};
size_t order_; // Maximal order of n-gram being counted
std::vector<CountState> states_; // Vector mapping state IDs to CountStates
std::vector<CountArc> arcs_; // Vector mapping arc IDs to CountArcs
ssize_t initial_; // ID of start state
ssize_t backoff_; // ID of unigram/backoff state
std::vector<PairArcMap> pair_arc_maps_; // Maps pairs to arc IDs.
bool epsilon_as_backoff_; // Treat epsilons as backoff trans. in input Fsts
float delta_; // Delta value used by shortest-distance
bool error_;
NGramCounter(const NGramCounter &) = delete;
NGramCounter &operator=(const NGramCounter &) = delete;
};
template <class Weight, class Label>
template <class Arc>
bool NGramCounter<Weight, Label>::CountFromStringFst(const Fst<Arc> &fst) {
if (!fst.Properties(fst::kString, false)) {
NGRAMERROR() << "Input FST is not a string";
return false;
}
ssize_t count_state = initial_;
auto fst_state = fst.Start();
Weight weight = fst.Properties(fst::kUnweighted, false)
? Weight::One()
: Weight(ShortestDistance(fst).Value());
while (fst.Final(fst_state) == Arc::Weight::Zero()) {
fst::ArcIterator<fst::Fst<Arc>> aiter(fst, fst_state);
const auto &arc = aiter.Value();
if (arc.ilabel) {
count_state = UpdateCount(count_state, arc.ilabel, weight);
} else if (epsilon_as_backoff_) {
ssize_t next_count_state = NGramBackoffState(count_state);
count_state = next_count_state == -1 ? count_state : next_count_state;
}
fst_state = arc.nextstate;
aiter.Next();
if (!aiter.Done()) {
NGRAMERROR() << "More than one arc leaving state " << fst_state;
return false;
}
}
UpdateFinalCount(count_state, weight);
return true;
}
template <class Weight, class Label>
template <class Arc>
bool NGramCounter<Weight, Label>::CountFromTopSortedFst(const Fst<Arc> &fst) {
if (!fst.Properties(fst::kTopSorted, false)) {
NGRAMERROR() << "Input not topologically sorted";
return false;
}
// Computes shortest-distances from the initial state and to the final
// states.
std::vector<typename Arc::Weight> fdistance;
ShortestDistance(fst, &fdistance, true, delta_);
std::vector<Pair> heap;
std::unordered_map<Pair, typename Arc::Weight, PairHash> pair2weight;
PairCompare compare;
Pair start_pair = std::make_pair(fst.Start(), initial_);
pair2weight[start_pair] = Arc::Weight::One();
heap.push_back(start_pair);
std::push_heap(heap.begin(), heap.end(), compare);
size_t i = 0;
while (!heap.empty()) {
std::pop_heap(heap.begin(), heap.end(), compare);
Pair current_pair = heap.back();
auto fst_state = current_pair.first;
ssize_t count_state = current_pair.second;
auto current_weight = pair2weight[current_pair];
pair2weight.erase(current_pair);
heap.pop_back();
++i;
for (fst::ArcIterator<fst::Fst<Arc>> aiter(fst, fst_state);
!aiter.Done(); aiter.Next()) {
const auto &arc = aiter.Value();
Pair next_pair(arc.nextstate, count_state);
if (arc.ilabel) {
Weight count = Times(current_weight,
Times(arc.weight,
fdistance[arc.nextstate])).Value();
next_pair.second = UpdateCount(count_state, arc.ilabel, count.Value());
} else if (epsilon_as_backoff_) {
ssize_t next_count_state = NGramBackoffState(count_state);
next_pair.second =
next_count_state == -1 ? count_state : next_count_state;
}
typename Arc::Weight next_weight = Times(current_weight, arc.weight);
auto iter = pair2weight.find(next_pair);
if (iter == pair2weight.end()) { // If pair not in heap, inserts it.
pair2weight[next_pair] = next_weight;
heap.push_back(next_pair);
std::push_heap(heap.begin(), heap.end(), compare);
} else { // Otherwise, updates the weight stored for it.
iter->second = Plus(iter->second, next_weight);
}
}
if (fst.Final(fst_state) != Arc::Weight::Zero()) {
UpdateFinalCount(count_state,
Times(current_weight, fst.Final(fst_state)).Value());
}
}
return true;
}
// Computes ngram counts and returns ngram format FST.
bool GetNGramCounts(fst::FarReader<fst::StdArc> *far_reader,
fst::StdMutableFst *fst, int order,
bool require_symbols = true,
bool epsilon_as_backoff = false, bool round_to_int = false);
bool GetNGramCounts(fst::FarReader<fst::StdArc> *far_reader,
std::vector<string> *ngrams, int order,
bool epsilon_as_backoff = false);
// Computes counts using the HistogramArc template.
bool GetNGramHistograms(fst::FarReader<fst::StdArc> *far_reader,
fst::VectorFst<fst::HistogramArc> *fst,
int order, bool epsilon_as_backoff = false,
int backoff_label = 0, double norm_eps = kNormEps,
bool check_consistency = false, bool normalize = false,
double alpha = 1.0, double beta = 1.0);
// Computes count-of-counts.
template <class Arc>
void GetNGramCountOfCounts(const Fst<Arc> &fst, StdMutableFst *ccfst,
int in_order, const string &context_pattern) {
NGramModel<Arc> ngram(fst, 0, kNormEps, !context_pattern.empty());
int order = ngram.HiOrder() > in_order ? ngram.HiOrder() : in_order;
NGramCountOfCounts<Arc> count_of_counts(context_pattern, order);
count_of_counts.CalculateCounts(ngram);
count_of_counts.GetFst(ccfst);
}
namespace internal {
// Mapper for going to Log64 arcs from other float arc types.
template <class Arc>
struct ToLog64Mapper {
using FromArc = Arc;
using ToArc = fst::Log64Arc;
ToArc operator()(const FromArc &arc) const {
return ToArc(arc.ilabel, arc.olabel, arc.weight.Value(), arc.nextstate);
}
fst::MapFinalAction FinalAction() const {
return fst::MAP_NO_SUPERFINAL;
}
fst::MapSymbolsAction InputSymbolsAction() const {
return fst::MAP_COPY_SYMBOLS;
}
fst::MapSymbolsAction OutputSymbolsAction() const {
return fst::MAP_COPY_SYMBOLS;
}
uint64 Properties(uint64 props) const { return props; }
};
} // namespace internal
} // namespace ngram
#endif // NGRAM_NGRAM_COUNT_H_
| 36.436673 | 80 | 0.643165 | [
"object",
"vector",
"model"
] |
c8537ec23616a55e49819762895dc0e1f0b554cc | 1,871 | h | C | src/shogun/structure/IntronList.h | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | 2 | 2015-01-13T15:18:27.000Z | 2015-05-01T13:28:48.000Z | src/shogun/structure/IntronList.h | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | null | null | null | src/shogun/structure/IntronList.h | cloner1984/shogun | 901c04b2c6550918acf0594ef8afeb5dcd840a7d | [
"BSD-3-Clause"
] | 1 | 2020-06-02T09:15:40.000Z | 2020-06-02T09:15:40.000Z | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Soeren Sonnenburg, Evan Shelhamer, Yuyu Zhang
*/
#ifndef __INTRON_LIST__
#define __INTRON_LIST__
#include <shogun/lib/config.h>
#include <shogun/lib/common.h>
#include <shogun/base/SGObject.h>
namespace shogun
{
/** @brief class IntronList */
class CIntronList : public CSGObject
{
public:
/** constructor
*/
CIntronList();
virtual ~CIntronList();
/** initialize all arrays with the number of candidate positions
*
* @param all_pos list of candidate positions
* @param len number of candidate positions
*/
void init_list(int32_t* all_pos, int32_t len);
/** read introns
*
* @param start_pos array of start positions
* @param end_pos array of end positions
* @param quality quality scores for introns in list
* @param len number of items in all three previous arguments
*/
void read_introns(int32_t* start_pos, int32_t* end_pos, int32_t* quality, int32_t len);
/** get coverage and quality score
*
* @param values values[0]: coverage of that intron; values[1]: associated quality score
* @param from_pos start position of intron
* @param to_pos end position of intron
*/
void get_intron_support(int32_t* values, int32_t from_pos, int32_t to_pos);
/**
* @return object name
*/
virtual const char* get_name() const { return "IntronList"; }
protected:
/** number of positions */
int32_t m_length;
/** index of positions in the DNA sequence*/
int32_t* m_all_pos;
/** data structure storing the introns;
* for all posible end positions there is a
* list of start positions stored
*/
int32_t** m_intron_list;
/** data structure storing the intron quality scores;
* the shape is exactly the same as for the introns
*/
int32_t** m_quality_list;
};
}
#endif
| 24.618421 | 90 | 0.701764 | [
"object",
"shape"
] |
c855bc4433a187f4dc1d90eeea89be99f8157311 | 1,513 | h | C | include/vrep_ros_interface.h | shuklaayush/v_repExtRosInterface | d4bd7cb8e1079f9506af18381db7632da6237a33 | [
"BSD-3-Clause"
] | 4 | 2018-06-07T11:36:21.000Z | 2021-11-23T07:12:05.000Z | include/vrep_ros_interface.h | kasperg3/vrep_ros_interface | 8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e | [
"BSD-3-Clause"
] | null | null | null | include/vrep_ros_interface.h | kasperg3/vrep_ros_interface | 8e68a1b37591e7fe8576ca8b8cce9d6859a6bf5e | [
"BSD-3-Clause"
] | 1 | 2019-12-05T15:38:24.000Z | 2019-12-05T15:38:24.000Z | #ifndef VREP_ROS_INTERFACE_H_INCLUDED
#define VREP_ROS_INTERFACE_H_INCLUDED
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <boost/lexical_cast.hpp>
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include "config.h"
#define PLUGIN_NAME "RosInterface"
#define PLUGIN_VERSION 5
struct ScriptCallback
{
int scriptId;
std::string name;
};
struct Proxy
{
bool destroyAfterSimulationStop;
};
#include <ros_msg_builtin_io.h>
struct SubscriberProxy : Proxy
{
int handle;
std::string topicName;
std::string topicType;
ScriptCallback topicCallback;
ros::Subscriber subscriber;
image_transport::Subscriber imageTransportSubscriber;
WriteOptions wr_opt;
};
struct PublisherProxy : Proxy
{
int handle;
std::string topicName;
std::string topicType;
ros::Publisher publisher;
image_transport::Publisher imageTransportPublisher;
ReadOptions rd_opt;
};
struct ServiceClientProxy : Proxy
{
int handle;
std::string serviceName;
std::string serviceType;
ros::ServiceClient client;
ReadOptions rd_opt;
WriteOptions wr_opt;
};
struct ServiceServerProxy : Proxy
{
int handle;
std::string serviceName;
std::string serviceType;
ScriptCallback serviceCallback;
ros::ServiceServer server;
ReadOptions rd_opt;
WriteOptions wr_opt;
};
#include <stubs.h>
#include <ros_msg_io.h>
#include <ros_srv_io.h>
#endif // VREP_ROS_INTERFACE_H_INCLUDED
| 18.9125 | 57 | 0.736286 | [
"vector"
] |
c855d9705d00633c1d4cc7113b7880e91cda5ee9 | 4,040 | h | C | bridge/go-llvm-irbuilders.h | guyezi/gollvm | 690719bf273cdeda6649045d05e65a2182ddcb56 | [
"BSD-3-Clause"
] | null | null | null | bridge/go-llvm-irbuilders.h | guyezi/gollvm | 690719bf273cdeda6649045d05e65a2182ddcb56 | [
"BSD-3-Clause"
] | null | null | null | bridge/go-llvm-irbuilders.h | guyezi/gollvm | 690719bf273cdeda6649045d05e65a2182ddcb56 | [
"BSD-3-Clause"
] | null | null | null | //===-- go-llvm-cabi-irbuilders.h - IR builder helper classes -------------===//
//
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
//===----------------------------------------------------------------------===//
//
// Assorted helper classes for IR building.
//
//===----------------------------------------------------------------------===//
#ifndef LLVMGOFRONTEND_GO_LLVM_IRBUILDER_H
#define LLVMGOFRONTEND_GO_LLVM_IRBUILDER_H
#include "go-llvm-bexpression.h"
#include "llvm/IR/IRBuilder.h"
class NameGen;
// Generic "no insert" builder
typedef llvm::IRBuilder<> LIRBuilder;
// Insertion helper for Bexpressions; inserts any instructions
// created by IRBuilder into the specified Bexpression's inst list.
class BexprInserter : public llvm::IRBuilderDefaultInserter {
public:
BexprInserter() : expr_(nullptr) { }
void setDest(Bexpression *expr) { assert(!expr_); expr_ = expr; }
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
llvm::BasicBlock *BB,
llvm::BasicBlock::iterator InsertPt) const {
assert(expr_);
expr_->appendInstruction(I);
I->setName(Name);
}
private:
mutable Bexpression *expr_;
};
// Builder that appends to a specified Bexpression
class BexprLIRBuilder :
public llvm::IRBuilder<llvm::ConstantFolder, BexprInserter> {
typedef llvm::IRBuilder<llvm::ConstantFolder, BexprInserter> IRBuilderB;
public:
BexprLIRBuilder(llvm::LLVMContext &context, Bexpression *expr) :
IRBuilderB(context, llvm::ConstantFolder()) {
getInserter().setDest(expr);
}
};
// Similar to the above, but adds to a Binstructions object.
class BinstructionsInserter : public llvm::IRBuilderDefaultInserter {
public:
BinstructionsInserter() : insns_(nullptr) { }
void setDest(Binstructions *insns) { assert(!insns_); insns_ = insns; }
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
llvm::BasicBlock *BB,
llvm::BasicBlock::iterator InsertPt) const {
assert(insns_);
insns_->appendInstruction(I);
I->setName(Name);
}
private:
mutable Binstructions *insns_;
};
// Builder that appends to a specified Binstructions object
class BinstructionsLIRBuilder :
public llvm::IRBuilder<llvm::ConstantFolder, BinstructionsInserter> {
typedef llvm::IRBuilder<llvm::ConstantFolder,
BinstructionsInserter> IRBuilderB;
public:
BinstructionsLIRBuilder(llvm::LLVMContext &context, Binstructions *insns) :
IRBuilderB(context, llvm::ConstantFolder()) {
getInserter().setDest(insns);
}
};
// Some of the methods in the LLVM IRBuilder class (ex: CreateMemCpy)
// assume that you are appending to an existing basic block (which is
// typically not what we want to do in many cases in the bridge code).
// Furthermore it is required that the block in question be already
// parented within an llvm::Function (the IRBuilder code relies on
// being able to call getParent() to trace back up to the enclosing
// context).
//
// This builder works around this issue by creating a dummy basic
// block to capture any instructions generated, then when the builder
// is destroyed it detaches the instructions from the block so that
// they can be returned in a list. A dummy function has to be passed in
// as well in order to host the dummy BB, however the dummy block will
// be detached in the destructor.
class BlockLIRBuilder : public LIRBuilder {
public:
BlockLIRBuilder(llvm::Function *dummyFcn, NameGen *namegen);
~BlockLIRBuilder();
// Return the instructions generated by this builder. Note that
// this detaches them from the dummy block we emitted them into,
// hence is not intended to be invoked more than once.
std::vector<llvm::Instruction*> instructions();
private:
std::unique_ptr<llvm::BasicBlock> dummyBlock_;
NameGen *namegen_;
};
#endif // LLVMGOFRONTEND_GO_LLVM_IRBUILDER_H
| 33.666667 | 80 | 0.692327 | [
"object",
"vector"
] |
c85746b09c02eae7045384be3e38a89cd84085d1 | 19,588 | c | C | glucas-2.9.2/src/radixmm_6.c | Kasual/GIMPS | a09c0d4cc1489558725eef0578613c66bd65a708 | [
"Intel"
] | null | null | null | glucas-2.9.2/src/radixmm_6.c | Kasual/GIMPS | a09c0d4cc1489558725eef0578613c66bd65a708 | [
"Intel"
] | null | null | null | glucas-2.9.2/src/radixmm_6.c | Kasual/GIMPS | a09c0d4cc1489558725eef0578613c66bd65a708 | [
"Intel"
] | null | null | null | /*$Id$*/
/* This file is a part of
YEAFFT. A library to make real convolutions using Fast Fourier
Transforms.
Copyright (C) 2003-2006 Guillermo Ballester Valor
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact to the author:
Guillermo Ballester Valor
c/ Cordoba 19. 18151-Ogijares (Granada), Spain.
gbv@oxixares.com
*/
/*
About read/write mode
if y_rmode == 0 then it reads from normal (legacy mode)
y_rmode == 1 then it reads from fast scramble mode
if y_wmode == 0 then it writes in normal mode
y_wmode == 1 then it writes in fast mode
*/
#include <stdlib.h>
#include <stdio.h>
#include "yeafft.h"
#include "mccomp.h"
#include "ydebug.h"
#if defined(Y_USE_SSE2)
#include "ygensse2.h"
#include "fft3sse2.h"
#define NDEBUG1
/**********************************************************************/
/* common blocks code and macros */
/**********************************************************************/
/* Prefetch the needed constants */
# define set_sse2_6_constants \
prefetch_data ( &MM_F_1_3r, 0);\
prefetch_data ( &MM_F_1_6r, 0);
/* asign the correct values to every pad */
#define get_pads_6 \
jj = pad; \
pd0 = d; \
prefetch_data( pd0, addr((n0<<1)));\
pd1 = d + addr((jj<<1)); \
jj += pad; \
prefetch_data( pd1, addr((n0<<1)));\
pd2 = d + addr((jj<<1)); \
jj += pad; \
prefetch_data( pd2, addr((n0<<1)));\
pd3 = d + addr((jj<<1)); \
jj += pad; \
prefetch_data( pd3, addr((n0<<1)));\
pd4 = d + addr((jj<<1)); \
jj += pad; \
prefetch_data( pd4, addr((n0<<1)));\
pd5 = d + addr((jj<<1)); \
prefetch_data( pd5, addr((n0<<1)));\
bigpad = 6 * pad;
#if defined(Y_MINIMUM)
# ifdef Y_STEP
# undef Y_STEP
# endif
# define Y_STEP 2
/* get the basic twiddle from memory and computes its powers */
# include "yminimum.h"
# define get_twiddle_factors_sse2_6 \
Y_MM_LOAD_INTER_PAIR(tw1##r, tw1##i, px, px + Y_STEP);\
sse2_square (tw2, tw1); \
sse2_square (tw4, tw2); \
sse2_divmul (tw3, tw5, tw4, tw1); \
prefetch_p_trig(px);
# define get_twiddle_factors_sse2_6_doubled \
Y_MM_LOAD_INTER_DOUBLED(tw1##r, tw1##i, px); \
sse2_square (tw2, tw1); \
sse2_square (tw4, tw2); \
sse2_divmul (tw3, tw5, tw4, tw1); \
prefetch_p_trig(px);
/* this version loads ones and trig factor */
# define get_twiddle_factors_sse2_6_one \
Y_MM_LOAD_INTER_ONE_HALF(tw1##r, tw1##i, px);\
sse2_square(tw2,tw1); \
sse2_square(tw4,tw2); \
sse2_divmul(tw3,tw5,tw4,tw1); \
prefetch_p_trig(px);
#elif defined(Y_MAXIMUM)
# ifdef Y_STEP
# undef Y_STEP
# endif
# define Y_STEP 10
# define get_twiddle_factors_sse2_6 \
Y_MM_LOAD_INTER_PAIR(tw1##r, tw1##i, px, px + Y_STEP); \
Y_MM_LOAD_INTER_PAIR(tw2##r, tw2##i, px + 2, px + Y_STEP + 2); \
Y_MM_LOAD_INTER_PAIR(tw3##r, tw3##i, px + 4, px + Y_STEP + 4); \
Y_MM_LOAD_INTER_PAIR(tw4##r, tw4##i, px + 6, px + Y_STEP + 6); \
Y_MM_LOAD_INTER_PAIR(tw5##r, tw5##i, px + 8, px + Y_STEP + 8);
# define get_twiddle_factors_sse2_6_doubled \
Y_MM_LOAD_INTER_DOUBLED(tw1##r, tw1##i, px); \
Y_MM_LOAD_INTER_DOUBLED(tw2##r, tw2##i, px + 2); \
Y_MM_LOAD_INTER_DOUBLED(tw3##r, tw3##i, px + 4); \
Y_MM_LOAD_INTER_DOUBLED(tw4##r, tw4##i, px + 6); \
Y_MM_LOAD_INTER_DOUBLED(tw5##r, tw5##i, px + 8);
# define get_twiddle_factors_sse2_6_one \
Y_MM_LOAD_INTER_ONE_HALF(tw1##r, tw1##i, px); \
Y_MM_LOAD_INTER_ONE_HALF(tw2##r, tw2##i, px + 2); \
Y_MM_LOAD_INTER_ONE_HALF(tw3##r, tw3##i, px + 4); \
Y_MM_LOAD_INTER_ONE_HALF(tw4##r, tw4##i, px + 6); \
Y_MM_LOAD_INTER_ONE_HALF(tw5##r, tw5##i, px + 8);
#else
# ifdef Y_STEP
# undef Y_STEP
# endif
# define Y_STEP 4
# define get_twiddle_factors_sse2_6 \
Y_MM_LOAD_INTER_PAIR(tw1r, tw1i, px, px + Y_STEP); \
Y_MM_LOAD_INTER_PAIR(tw4r, tw4i, px + 2, px + Y_STEP + 2); \
sse2_square(tw2, tw1); \
sse2_divmul(tw3, tw5, tw4, tw1); \
prefetch_data_trig(px, 2 * Y_STEP); \
prefetch_data_trig(px, 3 * Y_STEP);
# define get_twiddle_factors_sse2_6_doubled \
Y_MM_LOAD_INTER_DOUBLED (tw1r, tw1i, px); \
Y_MM_LOAD_INTER_DOUBLED (tw4r, tw4i, px + 2); \
sse2_square(tw2, tw1); \
sse2_divmul(tw3, tw5, tw4, tw1); \
prefetch_data_trig (px, Y_STEP); \
prefetch_data_trig (px, Y_STEP + Y_CACHE_LINE);
# define get_twiddle_factors_sse2_6_one \
Y_MM_LOAD_INTER_ONE_HALF(tw1r, tw1i, px); \
Y_MM_LOAD_INTER_ONE_HALF(tw4r, tw4i, px + 2); \
sse2_square(tw2, tw1); \
sse2_divmul(tw3, tw5, tw4, tw1); \
prefetch_data_trig (px, Y_STEP); \
prefetch_data_trig (px, Y_STEP + Y_CACHE_LINE);
#endif
/*
Get data from memory, mul by twiddle trig factors,
make a complex 9-length FFT and store the data to memory
*/
/* read 0 write 0 */
# define radixmm0_6_twd_pp(_S, _j) \
sse2_data_to_local_pp_inter (t0, _j, pd0); \
sse2_load_inter_mulmul_pp (t1, t2, tw2, tw4, _j, pd2, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_load_inter_mul_pp (t3, tw1, _j, pd1); \
sse2_load_inter_mulmul_pp (t4, t5, tw3, tw5, _j, pd3, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_inter_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_inter_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_inter_p (_j, pd2, pd5, t2, t5, MM_##_S##_1_3);
# define radixmm0_6_notwd_pp(_S, _j) \
sse2_data_to_local_pp_inter (t0, _j, pd0); \
sse2_data_to_local_pp_inter (t1, _j, pd2); \
sse2_data_to_local_pp_inter (t2, _j, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_data_to_local_pp_inter (t3, _j, pd1); \
sse2_data_to_local_pp_inter (t4, _j, pd3); \
sse2_data_to_local_pp_inter (t5, _j, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_inter_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_inter_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_inter_p( _j, pd2, pd5, t2, t5, MM_##_S##_1_3);
/* read 0 write 1 */
# define radixmm1_6_twd_pp(_S, _j) \
sse2_data_to_local_pp_inter (t0, _j, pd0); \
sse2_load_inter_mulmul_pp (t1, t2, tw2, tw4, _j, pd2, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_load_inter_mul_pp (t3, tw1, _j, pd1); \
sse2_load_inter_mulmul_pp (t4, t5, tw3, tw5, _j, pd3, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_p (_j, pd2, pd5, t2, t5, MM_##_S##_1_3);
# define radixmm1_6_notwd_pp(_S, _j) \
sse2_data_to_local_pp_inter (t0, _j, pd0); \
sse2_data_to_local_pp_inter (t1, _j, pd2); \
sse2_data_to_local_pp_inter (t2, _j, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_data_to_local_pp_inter (t3, _j, pd1); \
sse2_data_to_local_pp_inter (t4, _j, pd3); \
sse2_data_to_local_pp_inter (t5, _j, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_p( _j, pd2, pd5, t2, t5, MM_##_S##_1_3);
/* read 1 write 0 */
# define radixmm2_6_twd_pp(_S, _j) \
sse2_data_to_local_pp (t0, _j, pd0); \
sse2_load_mulmul_pp (t1, t2, tw2, tw4, _j, pd2, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_load_mul_pp (t3, tw1, _j, pd1); \
sse2_load_mulmul_pp (t4, t5, tw3, tw5, _j, pd3, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_inter_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_inter_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_inter_p (_j, pd2, pd5, t2, t5, MM_##_S##_1_3);
# define radixmm2_6_notwd_pp(_S, _j) \
sse2_data_to_local_pp (t0, _j, pd0); \
sse2_data_to_local_pp (t1, _j, pd2); \
sse2_data_to_local_pp (t2, _j, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_data_to_local_pp (t3, _j, pd1); \
sse2_data_to_local_pp (t4, _j, pd3); \
sse2_data_to_local_pp (t5, _j, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_inter_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_inter_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_inter_p( _j, pd2, pd5, t2, t5, MM_##_S##_1_3);
/* read 1 write 1 */
# define radixmm3_6_twd_pp(_S, _j) \
sse2_data_to_local_pp (t0, _j, pd0); \
sse2_load_mulmul_pp (t1, t2, tw2, tw4, _j, pd2, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_load_mul_pp (t3, tw1, _j, pd1); \
sse2_load_mulmul_pp (t4, t5, tw3, tw5, _j, pd3, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_p (_j, pd2, pd5, t2, t5, MM_##_S##_1_3);
# define radixmm3_6_notwd_pp(_S, _j) \
sse2_data_to_local_pp (t0, _j, pd0); \
sse2_data_to_local_pp (t1, _j, pd2); \
sse2_data_to_local_pp (t2, _j, pd4); \
sse2_fft3 (_S, t0, t1, t2); \
sse2_data_to_local_pp (t3, _j, pd1); \
sse2_data_to_local_pp (t4, _j, pd3); \
sse2_data_to_local_pp (t5, _j, pd5); \
sse2_fft3 (_S, t3, t4, t5); \
sse2_addsub_store_p (_j, pd0, pd3, t0, t3); \
sse2_muladdsub_store_p (_j, pd1, pd4, t1, t4, MM_##_S##_1_6);\
sse2_muladdsub_store_p( _j, pd2, pd5, t2, t5, MM_##_S##_1_3);
/*************************************************************************
This is a prototype of an Inplace Forward Decimation in Frecuency
Fast Numeric Transform Radix - r WITHOUT TWIDDLE
INPUTS:
d[] =all the data. Because of padding, d[0] must be the first
element of the whole data array.
tw[] = NULL in this no twiddle version.
n = number of data to transform in this call.
n0 = index of first data.
pad = the pad (logical) between data.
*************************************************************************/
void radixmm0_6_dif_notw(y_ptr d, y_ptr tw, y_size_t n, y_size_t n0,
y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t nc, i, j, jj;
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm0_6_dif_notw n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
set_sse2_6_constants;
get_pads_6;
nc = n + n0;
for(i = n0; i < nc; i += bigpad)
{
for(j = i; j < (pad + i);j += 2)
{
jj = addr(j << 1);
radixmm0_6_notwd_pp (F, jj);
}
}
}
void radixmm1_6_dif_notw(y_ptr d, y_ptr tw, y_size_t n, y_size_t n0,
y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t nc, i, j, jj;
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm1_6_dif_notw n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
set_sse2_6_constants;
get_pads_6;
nc = n + n0;
for(i = n0; i < nc; i += bigpad)
{
for(j = i; j < (pad + i);j += 2)
{
jj = addr(j << 1);
radixmm1_6_notwd_pp (F, jj);
}
}
}
void radixmm2_6_dif_notw(y_ptr d, y_ptr tw, y_size_t n, y_size_t n0,
y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t nc, i, j, jj;
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm1_6_dif_notw n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
set_sse2_6_constants;
get_pads_6;
nc = n + n0;
for(i = n0; i < nc; i += bigpad)
{
for(j = i; j < (pad + i);j += 2)
{
jj = addr(j << 1);
radixmm2_6_notwd_pp (F, jj);
}
}
}
void radixmm3_6_dif_notw(y_ptr d, y_ptr tw, y_size_t n, y_size_t n0,
y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t nc, i, j, jj;
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm3_6_dif_notw n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
set_sse2_6_constants;
get_pads_6;
nc = n + n0;
for(i = n0; i < nc; i += bigpad)
{
for(j = i; j < (pad + i);j += 2)
{
jj = addr(j << 1);
radixmm3_6_notwd_pp (F, jj);
}
}
}
/*************************************************************************
This is a prototype of an Inplace Backward Decimation in Time
Fast Numeric Transform Radix - r
INPUTS:
d[] =all the data. Because of padding, d[0] must be the first
element of the whole data array.
tw[] = Twidle Backward factors. Not scrambled.
n = number of data to transform in this call.
n0 = index of first data.
pad = the pad (logical) between data.
*************************************************************************/
void radixmm0_6_dit (y_ptr d, y_ptr tw, y_size_t n , y_size_t n0, y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i,
tw1r, tw1i, tw2r, tw2i, tw3r, tw3i, tw4r, tw4i, tw5r, tw5i;
y_ptr px;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t i, j, jj, nc;
/*DEBUG_VARS;*/
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm0_6_dit n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
nc = n0 + n;
set_sse2_6_constants;
get_pads_6;
for(i = n0; i < nc; i += bigpad)
{
px = tw;
get_twiddle_factors_sse2_6_one;
jj = addr (i << 1);
radixmm0_6_twd_pp(B,jj);
j = i + 2;
px += Y_STEP;
for( ;j < (pad + i); j += 2, px += 2 * Y_STEP)
{
get_twiddle_factors_sse2_6;
jj = addr (j << 1);
radixmm0_6_twd_pp (B, jj);
}
}
}
void radixmm1_6_dit (y_ptr d, y_ptr tw, y_size_t n , y_size_t n0, y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i,
tw1r, tw1i, tw2r, tw2i, tw3r, tw3i, tw4r, tw4i, tw5r, tw5i;
y_ptr px;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t i, j, jj, nc;
/*DEBUG_VARS;*/
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm1_6_dit n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
nc = n0 + n;
set_sse2_6_constants;
get_pads_6;
for(i = n0; i < nc; i += bigpad)
{
px = tw;
get_twiddle_factors_sse2_6_one;
jj = addr (i << 1);
radixmm1_6_twd_pp(B,jj);
j = i + 2;
px += Y_STEP;
for( ;j < (pad + i); j += 2, px += 2 * Y_STEP)
{
get_twiddle_factors_sse2_6;
jj = addr (j << 1);
radixmm1_6_twd_pp (B, jj);
}
}
}
void radixmm2_6_dit (y_ptr d, y_ptr tw, y_size_t n , y_size_t n0, y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i,
tw1r, tw1i, tw2r, tw2i, tw3r, tw3i, tw4r, tw4i, tw5r, tw5i;
y_ptr px;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t i, j, jj, nc;
/*DEBUG_VARS;*/
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm2_6_dit n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
nc = n0 + n;
set_sse2_6_constants;
get_pads_6;
for(i = n0; i < nc; i += bigpad)
{
px = tw;
get_twiddle_factors_sse2_6_one;
jj = addr (i << 1);
radixmm2_6_twd_pp(B,jj);
j = i + 2;
px += Y_STEP;
for( ;j < (pad + i); j += 2, px += 2 * Y_STEP)
{
get_twiddle_factors_sse2_6;
jj = addr (j << 1);
radixmm2_6_twd_pp (B, jj);
}
}
}
void radixmm3_6_dit (y_ptr d, y_ptr tw, y_size_t n , y_size_t n0, y_size_t pad)
{
Y__M128D t0r, t0i, t1r, t1i, t2r, t2i, t3r, t3i, t4r, t4i, t5r, t5i,
tw1r, tw1i, tw2r, tw2i, tw3r, tw3i, tw4r, tw4i, tw5r, tw5i;
y_ptr px;
y_size_t bigpad;
y_ptr pd0, pd1, pd2, pd3, pd4, pd5;
y_size_t i, j, jj, nc;
/*DEBUG_VARS;*/
ASSERT_ALIGNED_DOUBLE();
#ifndef NDEBUG1
printf(" Radixmm3_6_dit n=%i n0=%i pad=%i \n", n, n0, pad);
#endif
nc = n0 + n;
set_sse2_6_constants;
get_pads_6;
for(i = n0; i < nc; i += bigpad)
{
px = tw;
get_twiddle_factors_sse2_6_one;
jj = addr (i << 1);
radixmm3_6_twd_pp(B,jj);
j = i + 2;
px += Y_STEP;
for( ;j < (pad + i); j += 2, px += 2 * Y_STEP)
{
get_twiddle_factors_sse2_6;
jj = addr (j << 1);
radixmm3_6_twd_pp (B, jj);
}
}
}
#else /* Y_USE_SSE2 */
/* This line avoids errors on compilers expecting something to do in a file */
void radixmm_6_void( void )
{
printf("The routine radixmm_6_void should never be called\n");
exit(EXIT_FAILURE);
}
#endif /*Y_USE_SSE2*/
/*$Id$*/
| 33.369676 | 79 | 0.52864 | [
"transform"
] |
c857d55e925948fa5447a39c05c2776aed76a066 | 3,622 | h | C | itpp/itbase.h | indianshannon/minimal_itpp | d502993d20a81531558437c19fae2c2d12cb163b | [
"MIT"
] | null | null | null | itpp/itbase.h | indianshannon/minimal_itpp | d502993d20a81531558437c19fae2c2d12cb163b | [
"MIT"
] | null | null | null | itpp/itbase.h | indianshannon/minimal_itpp | d502993d20a81531558437c19fae2c2d12cb163b | [
"MIT"
] | null | null | null | /*!
* \file
* \brief Include file for the IT++ base module
* \author Tony Ottosson
*
* -------------------------------------------------------------------------
*
* Copyright (C) 1995-2010 (see AUTHORS file for a list of contributors)
*
* This file is part of IT++ - a C++ library of mathematical, signal
* processing, speech processing, and communications classes and functions.
*
* IT++ is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* IT++ 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 IT++. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
#ifndef ITBASE_H
#define ITBASE_H
/*!
* \defgroup base Base Module
* @{
*/
//! \defgroup arr_vec_mat Array, Vector and Matrix Classes
//! \defgroup parser Argument Parser
/*!
* \defgroup math Basic and Miscellaneous Math Functions
* @{
*/
//! \defgroup errorfunc Error Functions
//! \defgroup hypfunc Hyperbolic Functions
//! \defgroup logexpfunc Logarithmic and Exponential Functions
//! \defgroup miscfunc Miscellaneous Functions
//! \defgroup integration Numerical Integration
//! \defgroup trifunc Trigonometric Functions
/*!
* @} end of math group
*/
//! \defgroup besselfunctions Bessel Functions
//! \defgroup convertfunc Conversion Functions
//! \defgroup diag Diagonal Matrices and Functions
//! \defgroup errorhandlingfunc Error and Warning Handling
//! \defgroup matrix_functions Functions on Matrices
//! \defgroup itfile IT++ File Format
/*!
* \defgroup algebra Linear Algebra
* @{
*/
//! \defgroup determinant Determinant
//! \defgroup inverse Inverse Matrix
//! \defgroup matrixdecomp Matrix Decompositions
//! \defgroup linearequations Solving Linear Equation Systems
/*!
* @} end of algebra group
*/
//! \defgroup randgen Random Number Generation
//! \defgroup reshaping Reshaping of Vectors and Matrices
//! \defgroup specmat Special Matrices
//! \defgroup timers Timers
/*!
* @} end of base group
*/
#include <itpp/base/math/elem_math.h>
#include <itpp/base/math/elem_math.cpp>
#include <itpp/base/math/error.h>
#include <itpp/base/math/error.cpp>
#include <itpp/base/math/log_exp.h>
#include <itpp/base/math/log_exp.cpp>
#include <itpp/base/math/min_max.h>
#include <itpp/base/math/misc.h>
#include <itpp/base/math/misc.cpp>
#include <itpp/base/converters.h>
#include <itpp/base/converters.cpp>
#include <itpp/base/copy_vector.h>
#include <itpp/base/copy_vector.cpp>
#include <itpp/base/factory.h>
#include <itpp/base/help_functions.h>
#include <itpp/base/help_functions.cpp>
#include <itpp/base/itassert.h>
#include <itpp/base/itassert.cpp>
#include <itpp/base/mat.h>
#include <itpp/base/mat.cpp>
#include <itpp/base/matfunc.h>
#include <itpp/base/matfunc.cpp>
#include <itpp/base/operators.h>
#include <itpp/base/operators.cpp>
#include <itpp/base/random_dsfmt.h>
#include <itpp/base/random.h>
#include <itpp/base/random.cpp>
#include <itpp/base/sort.h>
#include <itpp/base/specmat.h>
#include <itpp/base/specmat.cpp>
#include <itpp/base/vec.h>
#include <itpp/base/vec.cpp>
#include <itpp/comm/crc.h>
#include <itpp/comm/crc.cpp>
#endif // #ifndef ITBASE_H
| 26.632353 | 76 | 0.700718 | [
"vector"
] |
c85ea17a35ab544b593b987aba865dbd6d5221fe | 183,420 | c | C | thirdparties/libfort/fort.c | ALGSS/ntrip_caster | 9dbfc35adaac87c40b380fa177878721ddf18032 | [
"BSD-3-Clause"
] | 23 | 2020-03-31T11:41:17.000Z | 2022-03-23T02:42:10.000Z | thirdparties/libfort/fort.c | ALGSS/ntrip_caster | 9dbfc35adaac87c40b380fa177878721ddf18032 | [
"BSD-3-Clause"
] | null | null | null | thirdparties/libfort/fort.c | ALGSS/ntrip_caster | 9dbfc35adaac87c40b380fa177878721ddf18032 | [
"BSD-3-Clause"
] | 12 | 2020-04-09T07:08:47.000Z | 2021-11-01T05:17:54.000Z | /*
libfort
MIT License
Copyright (c) 2017 - 2019 Seleznev Anton
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.
*/
/* The file was GENERATED by an amalgamation script.*/
/* DO NOT EDIT BY HAND!!! */
#define FT_AMALGAMED_SOURCE /* Macros to make internal libfort functions static */
/********************************************************
Begin of file "fort_utils.h"
********************************************************/
#ifndef FORT_IMPL_H
#define FORT_IMPL_H
#if defined(_MSC_VER)
#define _CRT_SECURE_NO_WARNINGS /* To disable warnings for unsafe functions */
#endif
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include "fort.h"
/* Define FT_INTERNAL to make internal libfort functions static
* in the result amalgamed source file.
*/
#ifdef FT_AMALGAMED_SOURCE
#define FT_INTERNAL static
#else
#define FT_INTERNAL
#endif /* FT_AMALGAMED_SORCE */
#define FORT_DEFAULT_COL_SEPARATOR '|'
extern char g_col_separator;
#define FORT_COL_SEPARATOR_LENGTH 1
#define FORT_UNUSED __attribute__((unused))
#define F_MALLOC fort_malloc
#define F_FREE fort_free
#define F_CALLOC fort_calloc
#define F_REALLOC fort_realloc
#define F_STRDUP fort_strdup
#define F_WCSDUP fort_wcsdup
#define F_CREATE(type) ((type *)F_CALLOC(sizeof(type), 1))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
enum PolicyOnNull {
Create,
DoNotCreate
};
enum F_BOOL {
F_FALSE = 0,
F_TRUE = 1
};
#define FT_STR_2_CAT_(arg1, arg2) \
arg1##arg2
#define FT_STR_2_CAT(arg1, arg2) \
FT_STR_2_CAT_(arg1, arg2)
#define UNIQUE_NAME_(prefix) \
FT_STR_2_CAT(prefix,__COUNTER__)
#define UNIQUE_NAME(prefix) \
UNIQUE_NAME_(prefix)
/*****************************************************************************
* LOGGER
*****************************************************************************/
#define SYS_LOG_ERROR(...)
/*****************************************************************************
* DEFAULT_SIZES
* ***************************************************************************/
#define DEFAULT_STR_BUF_SIZE 1024
#define DEFAULT_VECTOR_CAPACITY 10
struct fort_table_properties;
struct fort_column_properties;
struct fort_row;
struct vector;
struct fort_cell;
struct string_buffer;
struct separator {
int enabled;
};
typedef struct fort_table_properties fort_table_properties_t;
struct fort_context {
fort_table_properties_t *table_properties;
size_t row;
size_t column;
};
typedef struct fort_context context_t;
typedef struct fort_column_properties fort_column_properties_t;
typedef struct vector vector_t;
typedef struct fort_cell fort_cell_t;
typedef struct string_buffer string_buffer_t;
typedef struct fort_row fort_row_t;
/*typedef struct ft_table ft_table_t;*/
typedef struct separator separator_t;
enum CellType {
CommonCell,
GroupMasterCell,
GroupSlaveCell
};
enum request_geom_type {
VISIBLE_GEOMETRY,
INTERN_REPR_GEOMETRY
};
/*****************************************************************************
* LIBFORT helpers
*****************************************************************************/
extern void *(*fort_malloc)(size_t size);
extern void (*fort_free)(void *ptr);
extern void *(*fort_calloc)(size_t nmemb, size_t size);
extern void *(*fort_realloc)(void *ptr, size_t size);
FT_INTERNAL
void set_memory_funcs(void *(*f_malloc)(size_t size), void (*f_free)(void *ptr));
FT_INTERNAL
char *fort_strdup(const char *str);
FT_INTERNAL
size_t number_of_columns_in_format_string(const char *fmt);
#if defined(FT_HAVE_WCHAR)
FT_INTERNAL
wchar_t *fort_wcsdup(const wchar_t *str);
FT_INTERNAL
size_t number_of_columns_in_format_wstring(const wchar_t *fmt);
#endif
FT_INTERNAL
int snprint_n_strings(char *buf, size_t length, size_t n, const char *str);
#if defined(FT_HAVE_WCHAR)
FT_INTERNAL
int wsnprint_n_string(wchar_t *buf, size_t length, size_t n, const char *str);
#endif
#define CHCK_RSLT_ADD_TO_WRITTEN(statement) \
do { \
tmp = statement; \
if (tmp < 0) {\
goto clear; \
} \
written += (size_t)tmp; \
} while(0)
#define CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(statement) \
do { \
tmp = statement; \
if (tmp < 0) {\
goto clear; \
} \
invisible_written += (size_t)tmp; \
} while(0)
#define CHECK_NOT_NEGATIVE(x) \
do { if ((x) < 0) goto fort_fail; } while (0)
#endif /* FORT_IMPL_H */
/********************************************************
End of file "fort_utils.h"
********************************************************/
/********************************************************
Begin of file "vector.h"
********************************************************/
#ifndef VECTOR_H
#define VECTOR_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
#define INVALID_VEC_INDEX ((size_t) -1)
FT_INTERNAL
vector_t *create_vector(size_t item_size, size_t capacity);
FT_INTERNAL
void destroy_vector(vector_t *);
FT_INTERNAL
size_t vector_size(const vector_t *);
FT_INTERNAL
size_t vector_capacity(const vector_t *);
FT_INTERNAL
int vector_push(vector_t *, const void *item);
FT_INTERNAL
const void *vector_at_c(const vector_t *vector, size_t index);
FT_INTERNAL
void *vector_at(vector_t *, size_t index);
FT_INTERNAL
fort_status_t vector_swap(vector_t *cur_vec, vector_t *mv_vec, size_t pos);
/*
#define FOR_EACH_(type, item, vector, index_name) \
size_t index_name = 0; \
for (index_name = 0; (index_name < vector_size(vector)) ? ((item = *(type*)vector_at(vector, index_name)), 1) : 0; ++index_name)
#define FOR_EACH(type, item, vector) \
FOR_EACH_(type, item, vector, UNIQUE_NAME(i))
*/
#ifdef FT_TEST_BUILD
vector_t *copy_vector(vector_t *);
size_t vector_index_of(const vector_t *, const void *item);
int vector_erase(vector_t *, size_t index);
void vector_clear(vector_t *);
#endif
#endif /* VECTOR_H */
/********************************************************
End of file "vector.h"
********************************************************/
/********************************************************
Begin of file "wcwidth.h"
********************************************************/
#ifndef WCWIDTH_H
#define WCWIDTH_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
#ifdef FT_HAVE_WCHAR
#include <wchar.h>
FT_INTERNAL
int mk_wcswidth(const wchar_t *pwcs, size_t n);
#endif /* FT_HAVE_WCHAR */
#endif /* WCWIDTH_H */
/********************************************************
End of file "wcwidth.h"
********************************************************/
/********************************************************
Begin of file "string_buffer.h"
********************************************************/
#ifndef STRING_BUFFER_H
#define STRING_BUFFER_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
/*****************************************************************************
* STRING BUFFER
* ***************************************************************************/
enum str_buf_type {
CharBuf,
#ifdef FT_HAVE_WCHAR
WCharBuf
#endif /* FT_HAVE_WCHAR */
};
struct string_buffer {
union {
char *cstr;
wchar_t *wstr;
void *data;
} str;
size_t data_sz;
enum str_buf_type type;
};
FT_INTERNAL
string_buffer_t *create_string_buffer(size_t number_of_chars, enum str_buf_type type);
FT_INTERNAL
void destroy_string_buffer(string_buffer_t *buffer);
FT_INTERNAL
string_buffer_t *copy_string_buffer(const string_buffer_t *buffer);
FT_INTERNAL
fort_status_t realloc_string_buffer_without_copy(string_buffer_t *buffer);
FT_INTERNAL
fort_status_t fill_buffer_from_string(string_buffer_t *buffer, const char *str);
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
fort_status_t fill_buffer_from_wstring(string_buffer_t *buffer, const wchar_t *str);
#endif /* FT_HAVE_WCHAR */
FT_INTERNAL
size_t buffer_text_height(const string_buffer_t *buffer);
FT_INTERNAL
size_t string_buffer_capacity(const string_buffer_t *buffer);
FT_INTERNAL
void *buffer_get_data(string_buffer_t *buffer);
FT_INTERNAL
size_t buffer_text_width(const string_buffer_t *buffer);
FT_INTERNAL
int buffer_printf(string_buffer_t *buffer, size_t buffer_row, char *buf, size_t total_buf_len,
const context_t *context, const char *content_style_tag, const char *reset_content_style_tag);
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
int buffer_wprintf(string_buffer_t *buffer, size_t buffer_row, wchar_t *buf, size_t total_buf_len,
const context_t *context, const char *content_style_tag, const char *reset_content_style_tag);
#endif /* FT_HAVE_WCHAR */
#endif /* STRING_BUFFER_H */
/********************************************************
End of file "string_buffer.h"
********************************************************/
/********************************************************
Begin of file "properties.h"
********************************************************/
#ifndef PROPERTIES_H
#define PROPERTIES_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
#include <stdint.h>
#include <limits.h>
#define PROP_IS_SET(ft_props, property) ((ft_props) & (property))
#define PROP_SET(ft_props, property) ((ft_props) |=(property))
#define PROP_UNSET(ft_props, property) ((ft_props) &= ~((uint32_t)(property)))
#define TEXT_STYLE_TAG_MAX_SIZE (64 * 2)
FT_INTERNAL
void get_style_tag_for_cell(const fort_table_properties_t *props,
size_t row, size_t col, char *style_tag, size_t sz);
FT_INTERNAL
void get_reset_style_tag_for_cell(const fort_table_properties_t *props,
size_t row, size_t col, char *style_tag, size_t sz);
FT_INTERNAL
void get_style_tag_for_content(const fort_table_properties_t *props,
size_t row, size_t col, char *style_tag, size_t sz);
FT_INTERNAL
void get_reset_style_tag_for_content(const fort_table_properties_t *props,
size_t row, size_t col, char *style_tag, size_t sz);
struct fort_cell_props {
size_t cell_row;
size_t cell_col;
uint32_t properties_flags;
unsigned int col_min_width;
enum ft_text_alignment align;
unsigned int cell_padding_top;
unsigned int cell_padding_bottom;
unsigned int cell_padding_left;
unsigned int cell_padding_right;
unsigned int cell_empty_string_height;
enum ft_row_type row_type;
unsigned int content_fg_color_number;
unsigned int content_bg_color_number;
unsigned int cell_bg_color_number;
enum ft_text_style cell_text_style;
enum ft_text_style content_text_style;
};
typedef struct fort_cell_props fort_cell_props_t;
typedef vector_t fort_cell_prop_container_t;
FT_INTERNAL
fort_cell_prop_container_t *create_cell_prop_container(void);
FT_INTERNAL
void destroy_cell_prop_container(fort_cell_prop_container_t *cont);
FT_INTERNAL
const fort_cell_props_t *cget_cell_prop(const fort_cell_prop_container_t *cont, size_t row, size_t col);
FT_INTERNAL
fort_cell_props_t *get_cell_prop_and_create_if_not_exists(fort_cell_prop_container_t *cont, size_t row, size_t col);
FT_INTERNAL
fort_status_t set_cell_property(fort_cell_prop_container_t *cont, size_t row, size_t col, uint32_t property, int value);
FT_INTERNAL
int get_cell_property_value_hierarcial(const fort_table_properties_t *properties, size_t row, size_t column, uint32_t property);
FT_INTERNAL
fort_status_t set_default_cell_property(uint32_t property, int value);
/* TABLE BORDER DESСRIPTION
*
*
* TL TT TT TT TV TT TT TT TT TT TT TT TR
* LL IV RR
* LL IV RR
* LH IH IH IH II IH IH IH TI IH IH IH RH
* LL IV IV RR
* LL IV IV RR
* LL LI IH IH IH RI RH
* LL IV IV RR
* LL IV IV RR
* LH IH IH IH BI IH IH IH II IH IH IH RH
* LL IV RR
* LL IV RR
* BL BB BB BB BV BB BB BB BV BB BB BB BR
*/
/* HORIZONTAL SEPARATOR DESCRIPTION
*
*
* TL TT TT TT TV TT TT TT TV TT TT TT TR <----- TopSeparator
* LL IV IV RR
* LH IH IH IH II IH IH IH II IH IH IH RH <----- InsideSeparator
* LL IV IV RR
* BL BB BB BB BV BB BB BB BV BB BB BB BR <----- BottomSeparator
*/
enum HorSeparatorPos {
TopSeparator,
InsideSeparator,
BottomSeparator
};
enum BorderItemPos {
TL_bip = 0,
TT_bip = 1,
TV_bip = 2,
TR_bip = 3,
LL_bip = 4,
IV_bip = 5,
RR_bip = 6,
LH_bip = 7,
IH_bip = 8,
II_bip = 9,
RH_bip = 10,
BL_bip = 11,
BB_bip = 12,
BV_bip = 13,
BR_bip = 14,
LI_bip = 15,
TI_bip = 16,
RI_bip = 17,
BI_bip = 18,
BorderItemPosSize
};
enum SeparatorItemPos {
LH_sip = 0,
IH_sip = 1,
II_sip = 2,
RH_sip = 3,
TI_sip = 4,
BI_sip = 5,
SepratorItemPosSize
};
struct fort_border_style {
const char *border_chars[BorderItemPosSize];
const char *header_border_chars[BorderItemPosSize];
const char *separator_chars[SepratorItemPosSize];
};
extern struct fort_border_style FORT_BASIC_STYLE;
extern struct fort_border_style FORT_BASIC2_STYLE;
extern struct fort_border_style FORT_SIMPLE_STYLE;
extern struct fort_border_style FORT_PLAIN_STYLE;
extern struct fort_border_style FORT_DOT_STYLE;
extern struct fort_border_style FORT_EMPTY_STYLE;
extern struct fort_border_style FORT_EMPTY2_STYLE;
extern struct fort_border_style FORT_SOLID_STYLE;
extern struct fort_border_style FORT_SOLID_ROUND_STYLE;
extern struct fort_border_style FORT_NICE_STYLE;
extern struct fort_border_style FORT_DOUBLE_STYLE;
extern struct fort_border_style FORT_DOUBLE2_STYLE;
extern struct fort_border_style FORT_BOLD_STYLE;
extern struct fort_border_style FORT_BOLD2_STYLE;
extern struct fort_border_style FORT_FRAME_STYLE;
struct fort_entire_table_properties {
unsigned int left_margin;
unsigned int top_margin;
unsigned int right_margin;
unsigned int bottom_margin;
};
typedef struct fort_entire_table_properties fort_entire_table_properties_t;
extern fort_entire_table_properties_t g_entire_table_properties;
FT_INTERNAL
fort_status_t set_entire_table_property(fort_table_properties_t *table_properties, uint32_t property, int value);
FT_INTERNAL
fort_status_t set_default_entire_table_property(uint32_t property, int value);
struct fort_table_properties {
struct fort_border_style border_style;
fort_cell_prop_container_t *cell_properties;
fort_entire_table_properties_t entire_table_properties;
};
extern fort_table_properties_t g_table_properties;
FT_INTERNAL
size_t max_border_elem_strlen(struct fort_table_properties *);
FT_INTERNAL
fort_table_properties_t *create_table_properties(void);
FT_INTERNAL
void destroy_table_properties(fort_table_properties_t *properties);
FT_INTERNAL
fort_table_properties_t *copy_table_properties(const fort_table_properties_t *property);
#endif /* PROPERTIES_H */
/********************************************************
End of file "properties.h"
********************************************************/
/********************************************************
Begin of file "cell.h"
********************************************************/
#ifndef CELL_H
#define CELL_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
FT_INTERNAL
fort_cell_t *create_cell(void);
FT_INTERNAL
void destroy_cell(fort_cell_t *cell);
FT_INTERNAL
fort_cell_t *copy_cell(fort_cell_t *cell);
FT_INTERNAL
size_t hint_width_cell(const fort_cell_t *cell, const context_t *context, enum request_geom_type geom);
FT_INTERNAL
size_t hint_height_cell(const fort_cell_t *cell, const context_t *context);
FT_INTERNAL
void set_cell_type(fort_cell_t *cell, enum CellType type);
FT_INTERNAL
enum CellType get_cell_type(const fort_cell_t *cell);
FT_INTERNAL
int cell_printf(fort_cell_t *cell, size_t row, char *buf, size_t buf_len, const context_t *context);
FT_INTERNAL
fort_status_t fill_cell_from_string(fort_cell_t *cell, const char *str);
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
int cell_wprintf(fort_cell_t *cell, size_t row, wchar_t *buf, size_t buf_len, const context_t *context);
FT_INTERNAL
fort_status_t fill_cell_from_wstring(fort_cell_t *cell, const wchar_t *str);
#endif
FT_INTERNAL
string_buffer_t *cell_get_string_buffer(fort_cell_t *cell);
#endif /* CELL_H */
/********************************************************
End of file "cell.h"
********************************************************/
/********************************************************
Begin of file "row.h"
********************************************************/
#ifndef ROW_H
#define ROW_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
#include "fort.h"
#include <stdarg.h>
/* #include "properties.h" */ /* Commented by amalgamation script */
#ifdef FT_HAVE_WCHAR
#include <wchar.h>
#endif
FT_INTERNAL
fort_row_t *create_row(void);
FT_INTERNAL
void destroy_row(fort_row_t *row);
FT_INTERNAL
fort_row_t *copy_row(fort_row_t *row);
FT_INTERNAL
fort_row_t *create_row_from_string(const char *str);
FT_PRINTF_ATTRIBUTE_FORMAT(1, 0)
FT_INTERNAL
fort_row_t *create_row_from_fmt_string(const char *fmt, va_list *va_args);
FT_INTERNAL
size_t columns_in_row(const fort_row_t *row);
FT_INTERNAL
fort_cell_t *get_cell(fort_row_t *row, size_t col);
FT_INTERNAL
const fort_cell_t *get_cell_c(const fort_row_t *row, size_t col);
FT_INTERNAL
fort_cell_t *get_cell_and_create_if_not_exists(fort_row_t *row, size_t col);
FT_INTERNAL
fort_status_t swap_row(fort_row_t *cur_row, fort_row_t *ins_row, size_t pos);
FT_INTERNAL
size_t group_cell_number(const fort_row_t *row, size_t master_cell_col);
FT_INTERNAL
int get_row_cell_types(const fort_row_t *row, enum CellType *types, size_t types_sz);
FT_INTERNAL
fort_status_t row_set_cell_span(fort_row_t *row, size_t cell_column, size_t hor_span);
FT_INTERNAL
int print_row_separator(char *buffer, size_t buffer_sz,
const size_t *col_width_arr, size_t cols,
const fort_row_t *upper_row, const fort_row_t *lower_row,
enum HorSeparatorPos separatorPos, const separator_t *sep,
const context_t *context);
FT_INTERNAL
int snprintf_row(const fort_row_t *row, char *buffer, size_t buf_sz, size_t *col_width_arr, size_t col_width_arr_sz,
size_t row_height, const context_t *context);
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
fort_row_t *create_row_from_wstring(const wchar_t *str);
FT_INTERNAL
fort_row_t *create_row_from_fmt_wstring(const wchar_t *fmt, va_list *va_args);
FT_INTERNAL
int wprint_row_separator(wchar_t *buffer, size_t buffer_sz,
const size_t *col_width_arr, size_t cols,
const fort_row_t *upper_row, const fort_row_t *lower_row,
enum HorSeparatorPos separatorPos, const separator_t *sep,
const context_t *context);
FT_INTERNAL
int wsnprintf_row(const fort_row_t *row, wchar_t *buffer, size_t buf_sz, size_t *col_width_arr, size_t col_width_arr_sz,
size_t row_height, const context_t *context);
#endif
#endif /* ROW_H */
/********************************************************
End of file "row.h"
********************************************************/
/********************************************************
Begin of file "table.h"
********************************************************/
#ifndef TABLE_H
#define TABLE_H
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
struct ft_table {
vector_t *rows;
fort_table_properties_t *properties;
string_buffer_t *conv_buffer;
size_t cur_row;
size_t cur_col;
vector_t *separators;
};
FT_INTERNAL
separator_t *create_separator(int enabled);
FT_INTERNAL
void destroy_separator(separator_t *sep);
FT_INTERNAL
separator_t *copy_separator(separator_t *sep);
FT_INTERNAL
fort_status_t get_table_sizes(const ft_table_t *table, size_t *rows, size_t *cols);
FT_INTERNAL
fort_row_t *get_row(ft_table_t *table, size_t row);
FT_INTERNAL
const fort_row_t *get_row_c(const ft_table_t *table, size_t row);
FT_INTERNAL
fort_row_t *get_row_and_create_if_not_exists(ft_table_t *table, size_t row);
FT_INTERNAL
string_buffer_t *get_cur_str_buffer_and_create_if_not_exists(ft_table_t *table);
FT_INTERNAL
fort_status_t table_rows_and_cols_geometry(const ft_table_t *table,
size_t **col_width_arr_p, size_t *col_width_arr_sz,
size_t **row_height_arr_p, size_t *row_height_arr_sz,
enum request_geom_type geom);
FT_INTERNAL
fort_status_t table_geometry(const ft_table_t *table, size_t *height, size_t *width);
#endif /* TABLE_H */
/********************************************************
End of file "table.h"
********************************************************/
/********************************************************
Begin of file "cell.c"
********************************************************/
/* #include "cell.h" */ /* Commented by amalgamation script */
/* #include "properties.h" */ /* Commented by amalgamation script */
/* #include "string_buffer.h" */ /* Commented by amalgamation script */
#include <assert.h>
struct fort_cell {
string_buffer_t *str_buffer;
enum CellType cell_type;
};
FT_INTERNAL
fort_cell_t *create_cell(void)
{
fort_cell_t *cell = (fort_cell_t *)F_CALLOC(sizeof(fort_cell_t), 1);
if (cell == NULL)
return NULL;
cell->str_buffer = create_string_buffer(DEFAULT_STR_BUF_SIZE, CharBuf);
if (cell->str_buffer == NULL) {
F_FREE(cell);
return NULL;
}
cell->cell_type = CommonCell;
return cell;
}
FT_INTERNAL
void destroy_cell(fort_cell_t *cell)
{
if (cell == NULL)
return;
destroy_string_buffer(cell->str_buffer);
F_FREE(cell);
}
FT_INTERNAL
fort_cell_t *copy_cell(fort_cell_t *cell)
{
assert(cell);
fort_cell_t *result = create_cell();
if (result == NULL)
return NULL;
destroy_string_buffer(result->str_buffer);
result->str_buffer = copy_string_buffer(cell->str_buffer);
if (result->str_buffer == NULL) {
destroy_cell(result);
return NULL;
}
result->cell_type = cell->cell_type;
return result;
}
FT_INTERNAL
void set_cell_type(fort_cell_t *cell, enum CellType type)
{
assert(cell);
cell->cell_type = type;
}
FT_INTERNAL
enum CellType get_cell_type(const fort_cell_t *cell)
{
assert(cell);
return cell->cell_type;
}
FT_INTERNAL
size_t hint_width_cell(const fort_cell_t *cell, const context_t *context, enum request_geom_type geom)
{
/* todo:
* At the moment min width includes paddings. Maybe it is better that min width weren't include
* paddings but be min width of the cell content without padding
*/
assert(cell);
assert(context);
size_t cell_padding_left = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_LEFT_PADDING);
size_t cell_padding_right = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_RIGHT_PADDING);
size_t result = cell_padding_left + cell_padding_right;
if (cell->str_buffer && cell->str_buffer->str.data) {
result += buffer_text_width(cell->str_buffer);
}
result = MAX(result, (size_t)get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_MIN_WIDTH));
if (geom == INTERN_REPR_GEOMETRY) {
char cell_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_style_tag_for_cell(context->table_properties, context->row, context->column, cell_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
result += strlen(cell_style_tag);
char reset_cell_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_reset_style_tag_for_cell(context->table_properties, context->row, context->column, reset_cell_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
result += strlen(reset_cell_style_tag);
char content_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_style_tag_for_content(context->table_properties, context->row, context->column, content_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
result += strlen(content_style_tag);
char reset_content_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_reset_style_tag_for_content(context->table_properties, context->row, context->column, reset_content_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
result += strlen(reset_content_style_tag);
}
return result;
}
FT_INTERNAL
size_t hint_height_cell(const fort_cell_t *cell, const context_t *context)
{
assert(cell);
assert(context);
size_t cell_padding_top = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_TOP_PADDING);
size_t cell_padding_bottom = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_BOTTOM_PADDING);
size_t cell_empty_string_height = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_EMPTY_STR_HEIGHT);
size_t result = cell_padding_top + cell_padding_bottom;
if (cell->str_buffer && cell->str_buffer->str.data) {
size_t text_height = buffer_text_height(cell->str_buffer);
result += text_height == 0 ? cell_empty_string_height : text_height;
}
return result;
}
FT_INTERNAL
int cell_printf(fort_cell_t *cell, size_t row, char *buf, size_t buf_len, const context_t *context)
{
const char *space_char = " ";
int (*buffer_printf_)(string_buffer_t *, size_t, char *, size_t, const context_t *, const char *, const char *) = buffer_printf;
int (*snprint_n_strings_)(char *, size_t, size_t, const char *) = snprint_n_strings;
if (cell == NULL || buf_len == 0
|| (buf_len <= hint_width_cell(cell, context, VISIBLE_GEOMETRY))) {
return -1;
}
unsigned int cell_padding_top = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_TOP_PADDING);
unsigned int cell_padding_left = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_LEFT_PADDING);
unsigned int cell_padding_right = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_RIGHT_PADDING);
size_t written = 0;
size_t invisible_written = 0;
int tmp = 0;
/* todo: Dirty hack with changing buf_len! need refactoring. */
/* Also maybe it is better to move all struff with colors to buffers? */
char cell_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_style_tag_for_cell(context->table_properties, context->row, context->column, cell_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(cell_style_tag);
char reset_cell_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_reset_style_tag_for_cell(context->table_properties, context->row, context->column, reset_cell_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(reset_cell_style_tag);
char content_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_style_tag_for_content(context->table_properties, context->row, context->column, content_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(content_style_tag);
char reset_content_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_reset_style_tag_for_content(context->table_properties, context->row, context->column, reset_content_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(reset_content_style_tag);
/* CELL_STYLE_T LEFT_PADDING CONTENT_STYLE_T CONTENT RESET_CONTENT_STYLE_T RIGHT_PADDING RESET_CELL_STYLE_T
* | | | | | | | |
* L1 R1
* L2 R2
* L3 R3
*/
size_t L2 = cell_padding_left;
size_t R2 = cell_padding_right;
size_t R3 = strlen(reset_cell_style_tag);
#define TOTAL_WRITTEN (written + invisible_written)
#define RIGHT (cell_padding_right + extra_right)
#define WRITE_CELL_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, cell_style_tag))
#define WRITE_RESET_CELL_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, reset_cell_style_tag))
#define WRITE_CONTENT_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, content_style_tag))
#define WRITE_RESET_CONTENT_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, reset_content_style_tag))
if (row >= hint_height_cell(cell, context)
|| row < cell_padding_top
|| row >= (cell_padding_top + buffer_text_height(cell->str_buffer))) {
WRITE_CELL_STYLE_TAG;
WRITE_CONTENT_STYLE_TAG;
WRITE_RESET_CONTENT_STYLE_TAG;
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len, buf_len - 1 - TOTAL_WRITTEN - R3, space_char));
WRITE_RESET_CELL_STYLE_TAG;
return (int)TOTAL_WRITTEN;
}
WRITE_CELL_STYLE_TAG;
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, L2, space_char));
if (cell->str_buffer) {
CHCK_RSLT_ADD_TO_WRITTEN(buffer_printf_(cell->str_buffer, row - cell_padding_top, buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN - R2 - R3, context, content_style_tag, reset_content_style_tag));
} else {
WRITE_CONTENT_STYLE_TAG;
WRITE_RESET_CONTENT_STYLE_TAG;
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN - R2 - R3, space_char));
}
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, R2, space_char));
WRITE_RESET_CELL_STYLE_TAG;
return (int)TOTAL_WRITTEN;
clear:
return -1;
#undef WRITE_CELL_STYLE_TAG
#undef WRITE_RESET_CELL_STYLE_TAG
#undef WRITE_CONTENT_STYLE_TAG
#undef WRITE_RESET_CONTENT_STYLE_TAG
#undef TOTAL_WRITTEN
#undef RIGHT
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
int cell_wprintf(fort_cell_t *cell, size_t row, wchar_t *buf, size_t buf_len, const context_t *context)
{
const char *space_char = " ";
int (*buffer_printf_)(string_buffer_t *, size_t, wchar_t *, size_t, const context_t *, const char *, const char *) = buffer_wprintf;
int (*snprint_n_strings_)(wchar_t *, size_t, size_t, const char *) = wsnprint_n_string;
if (cell == NULL || buf_len == 0
|| (buf_len <= hint_width_cell(cell, context, VISIBLE_GEOMETRY))) {
return -1;
}
unsigned int cell_padding_top = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_TOP_PADDING);
unsigned int cell_padding_left = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_LEFT_PADDING);
unsigned int cell_padding_right = get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_RIGHT_PADDING);
size_t written = 0;
size_t invisible_written = 0;
int tmp = 0;
/* todo: Dirty hack with changing buf_len! need refactoring. */
/* Also maybe it is better to move all struff with colors to buffers? */
char cell_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_style_tag_for_cell(context->table_properties, context->row, context->column, cell_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(cell_style_tag);
char reset_cell_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_reset_style_tag_for_cell(context->table_properties, context->row, context->column, reset_cell_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(reset_cell_style_tag);
char content_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_style_tag_for_content(context->table_properties, context->row, context->column, content_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(content_style_tag);
char reset_content_style_tag[TEXT_STYLE_TAG_MAX_SIZE];
get_reset_style_tag_for_content(context->table_properties, context->row, context->column, reset_content_style_tag, TEXT_STYLE_TAG_MAX_SIZE);
buf_len += strlen(reset_content_style_tag);
/* CELL_STYLE_T LEFT_PADDING CONTENT_STYLE_T CONTENT RESET_CONTENT_STYLE_T RIGHT_PADDING RESET_CELL_STYLE_T
* | | | | | | | |
* L1 R1
* L2 R2
* L3 R3
*/
size_t L2 = cell_padding_left;
size_t R2 = cell_padding_right;
size_t R3 = strlen(reset_cell_style_tag);
#define TOTAL_WRITTEN (written + invisible_written)
#define RIGHT (right + extra_right)
#define WRITE_CELL_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, cell_style_tag))
#define WRITE_RESET_CELL_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, reset_cell_style_tag))
#define WRITE_CONTENT_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, content_style_tag))
#define WRITE_RESET_CONTENT_STYLE_TAG CHCK_RSLT_ADD_TO_INVISIBLE_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, 1, reset_content_style_tag))
if (row >= hint_height_cell(cell, context)
|| row < cell_padding_top
|| row >= (cell_padding_top + buffer_text_height(cell->str_buffer))) {
WRITE_CELL_STYLE_TAG;
WRITE_CONTENT_STYLE_TAG;
WRITE_RESET_CONTENT_STYLE_TAG;
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len, buf_len - 1 - TOTAL_WRITTEN - R3, space_char));
WRITE_RESET_CELL_STYLE_TAG;
return (int)TOTAL_WRITTEN;
}
WRITE_CELL_STYLE_TAG;
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, L2, space_char));
if (cell->str_buffer) {
CHCK_RSLT_ADD_TO_WRITTEN(buffer_printf_(cell->str_buffer, row - cell_padding_top, buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN - R2 - R3, context, content_style_tag, reset_content_style_tag));
} else {
WRITE_CONTENT_STYLE_TAG;
WRITE_RESET_CONTENT_STYLE_TAG;
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN - R2 - R3, space_char));
}
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buf + TOTAL_WRITTEN, buf_len - TOTAL_WRITTEN, R2, space_char));
WRITE_RESET_CELL_STYLE_TAG;
return (int)TOTAL_WRITTEN;
clear:
return -1;
#undef WRITE_CELL_STYLE_TAG
#undef WRITE_RESET_CELL_STYLE_TAG
#undef WRITE_CONTENT_STYLE_TAG
#undef WRITE_RESET_CONTENT_STYLE_TAG
#undef TOTAL_WRITTEN
#undef RIGHT
}
#endif
FT_INTERNAL
fort_status_t fill_cell_from_string(fort_cell_t *cell, const char *str)
{
assert(str);
assert(cell);
return fill_buffer_from_string(cell->str_buffer, str);
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
fort_status_t fill_cell_from_wstring(fort_cell_t *cell, const wchar_t *str)
{
assert(str);
assert(cell);
return fill_buffer_from_wstring(cell->str_buffer, str);
}
#endif
FT_INTERNAL
string_buffer_t *cell_get_string_buffer(fort_cell_t *cell)
{
assert(cell);
assert(cell->str_buffer);
return cell->str_buffer;
}
/********************************************************
End of file "cell.c"
********************************************************/
/********************************************************
Begin of file "fort_impl.c"
********************************************************/
/*
libfort
MIT License
Copyright (c) 2017 - 2018 Seleznev Anton
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 <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include "fort.h"
#include <assert.h>
#include <string.h>
#include <wchar.h>
#include <ctype.h>
/* #include "vector.h" */ /* Commented by amalgamation script */
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
/* #include "string_buffer.h" */ /* Commented by amalgamation script */
/* #include "table.h" */ /* Commented by amalgamation script */
/* #include "row.h" */ /* Commented by amalgamation script */
/* #include "properties.h" */ /* Commented by amalgamation script */
ft_table_t *ft_create_table(void)
{
ft_table_t *result = (ft_table_t *)F_CALLOC(1, sizeof(ft_table_t));
if (result == NULL)
return NULL;
result->rows = create_vector(sizeof(fort_row_t *), DEFAULT_VECTOR_CAPACITY);
if (result->rows == NULL) {
F_FREE(result);
return NULL;
}
result->separators = create_vector(sizeof(separator_t *), DEFAULT_VECTOR_CAPACITY);
if (result->separators == NULL) {
destroy_vector(result->rows);
F_FREE(result);
return NULL;
}
result->properties = NULL;
result->conv_buffer = NULL;
result->cur_row = 0;
result->cur_col = 0;
return result;
}
void ft_destroy_table(ft_table_t *table)
{
size_t i = 0;
if (table == NULL)
return;
if (table->rows) {
size_t row_n = vector_size(table->rows);
for (i = 0; i < row_n; ++i) {
destroy_row(*(fort_row_t **)vector_at(table->rows, i));
}
destroy_vector(table->rows);
}
if (table->separators) {
size_t row_n = vector_size(table->separators);
for (i = 0; i < row_n; ++i) {
destroy_separator(*(separator_t **)vector_at(table->separators, i));
}
destroy_vector(table->separators);
}
destroy_table_properties(table->properties);
destroy_string_buffer(table->conv_buffer);
F_FREE(table);
}
ft_table_t *ft_copy_table(ft_table_t *table)
{
if (table == NULL)
return NULL;
ft_table_t *result = ft_create_table();
if (result == NULL)
return NULL;
size_t i = 0;
size_t rows_n = vector_size(table->rows);
for (i = 0; i < rows_n; ++i) {
fort_row_t *row = *(fort_row_t **)vector_at(table->rows, i);
fort_row_t *new_row = copy_row(row);
if (new_row == NULL) {
ft_destroy_table(result);
return NULL;
}
vector_push(result->rows, &new_row);
}
size_t sep_sz = vector_size(table->separators);
for (i = 0; i < sep_sz; ++i) {
separator_t *sep = *(separator_t **)vector_at(table->separators, i);
separator_t *new_sep = copy_separator(sep);
if (new_sep == NULL) {
ft_destroy_table(result);
return NULL;
}
vector_push(result->separators, &new_sep);
}
result->properties = copy_table_properties(table->properties);
if (result->properties == NULL) {
ft_destroy_table(result);
return NULL;
}
/* todo: copy conv_buffer ?? */
result->cur_row = table->cur_row;
result->cur_col = table->cur_col;
return result;
}
void ft_ln(ft_table_t *table)
{
assert(table);
table->cur_col = 0;
table->cur_row++;
}
size_t ft_cur_row(ft_table_t *table)
{
assert(table);
return table->cur_row;
}
size_t ft_cur_col(ft_table_t *table)
{
assert(table);
return table->cur_col;
}
void ft_set_cur_cell(ft_table_t *table, size_t row, size_t col)
{
assert(table);
table->cur_row = row;
table->cur_col = col;
}
FT_PRINTF_ATTRIBUTE_FORMAT(3, 0)
static int ft_row_printf_impl(ft_table_t *table, size_t row, const char *fmt, va_list *va)
{
#define CREATE_ROW_FROM_FMT_STRING create_row_from_fmt_string
size_t i = 0;
size_t new_cols = 0;
if (table == NULL)
return -1;
fort_row_t *new_row = CREATE_ROW_FROM_FMT_STRING(fmt, va);
if (new_row == NULL) {
return -1;
}
fort_row_t **cur_row_p = NULL;
size_t sz = vector_size(table->rows);
if (row >= sz) {
size_t push_n = row - sz + 1;
for (i = 0; i < push_n; ++i) {
fort_row_t *padding_row = create_row();
if (padding_row == NULL)
goto clear;
if (FT_IS_ERROR(vector_push(table->rows, &padding_row))) {
destroy_row(padding_row);
goto clear;
}
}
}
/* todo: clearing pushed items in case of error ?? */
new_cols = columns_in_row(new_row);
cur_row_p = (fort_row_t **)vector_at(table->rows, row);
swap_row(*cur_row_p, new_row, table->cur_col);
table->cur_col += new_cols;
destroy_row(new_row);
return (int)new_cols;
clear:
destroy_row(new_row);
return -1;
#undef CREATE_ROW_FROM_FMT_STRING
}
#ifdef FT_HAVE_WCHAR
static int ft_row_wprintf_impl(ft_table_t *table, size_t row, const wchar_t *fmt, va_list *va)
{
#define CREATE_ROW_FROM_FMT_STRING create_row_from_fmt_wstring
size_t i = 0;
size_t new_cols = 0;
if (table == NULL)
return -1;
fort_row_t *new_row = CREATE_ROW_FROM_FMT_STRING(fmt, va);
if (new_row == NULL) {
return -1;
}
fort_row_t **cur_row_p = NULL;
size_t sz = vector_size(table->rows);
if (row >= sz) {
size_t push_n = row - sz + 1;
for (i = 0; i < push_n; ++i) {
fort_row_t *padding_row = create_row();
if (padding_row == NULL)
goto clear;
if (FT_IS_ERROR(vector_push(table->rows, &padding_row))) {
destroy_row(padding_row);
goto clear;
}
}
}
/* todo: clearing pushed items in case of error ?? */
new_cols = columns_in_row(new_row);
cur_row_p = (fort_row_t **)vector_at(table->rows, row);
swap_row(*cur_row_p, new_row, table->cur_col);
table->cur_col += new_cols;
destroy_row(new_row);
return (int)new_cols;
clear:
destroy_row(new_row);
return -1;
#undef CREATE_ROW_FROM_FMT_STRING
}
#endif
#if defined(FT_CLANG_COMPILER) || defined(FT_GCC_COMPILER)
#define FT_PRINTF ft_printf
#define FT_PRINTF_LN ft_printf_ln
#else
#define FT_PRINTF ft_printf_impl
#define FT_PRINTF_LN ft_printf_ln_impl
#endif
int FT_PRINTF(ft_table_t *table, const char *fmt, ...)
{
assert(table);
va_list va;
va_start(va, fmt);
int result = ft_row_printf_impl(table, table->cur_row, fmt, &va);
va_end(va);
return result;
}
int FT_PRINTF_LN(ft_table_t *table, const char *fmt, ...)
{
assert(table);
va_list va;
va_start(va, fmt);
int result = ft_row_printf_impl(table, table->cur_row, fmt, &va);
if (result >= 0) {
ft_ln(table);
}
va_end(va);
return result;
}
#undef FT_PRINTF
#undef FT_PRINTF_LN
#undef FT_HDR_PRINTF
#undef FT_HDR_PRINTF_LN
#ifdef FT_HAVE_WCHAR
int ft_wprintf(ft_table_t *table, const wchar_t *fmt, ...)
{
assert(table);
va_list va;
va_start(va, fmt);
int result = ft_row_wprintf_impl(table, table->cur_row, fmt, &va);
va_end(va);
return result;
}
int ft_wprintf_ln(ft_table_t *table, const wchar_t *fmt, ...)
{
assert(table);
va_list va;
va_start(va, fmt);
int result = ft_row_wprintf_impl(table, table->cur_row, fmt, &va);
if (result >= 0) {
ft_ln(table);
}
va_end(va);
return result;
}
#endif
void ft_set_default_printf_field_separator(char separator)
{
g_col_separator = separator;
}
static int ft_write_impl(ft_table_t *table, const char *cell_content)
{
assert(table);
string_buffer_t *str_buffer = get_cur_str_buffer_and_create_if_not_exists(table);
if (str_buffer == NULL)
return FT_ERROR;
int status = fill_buffer_from_string(str_buffer, cell_content);
if (FT_IS_SUCCESS(status)) {
table->cur_col++;
}
return status;
}
#ifdef FT_HAVE_WCHAR
static int ft_wwrite_impl(ft_table_t *table, const wchar_t *cell_content)
{
assert(table);
string_buffer_t *str_buffer = get_cur_str_buffer_and_create_if_not_exists(table);
if (str_buffer == NULL)
return FT_ERROR;
int status = fill_buffer_from_wstring(str_buffer, cell_content);
if (FT_IS_SUCCESS(status)) {
table->cur_col++;
}
return status;
}
#endif
int ft_nwrite(ft_table_t *table, size_t count, const char *cell_content, ...)
{
size_t i = 0;
assert(table);
int status = ft_write_impl(table, cell_content);
if (FT_IS_ERROR(status))
return status;
va_list va;
va_start(va, cell_content);
--count;
for (i = 0; i < count; ++i) {
const char *cell = va_arg(va, const char *);
status = ft_write_impl(table, cell);
if (FT_IS_ERROR(status)) {
va_end(va);
return status;
}
}
va_end(va);
return status;
}
int ft_nwrite_ln(ft_table_t *table, size_t count, const char *cell_content, ...)
{
size_t i = 0;
assert(table);
int status = ft_write_impl(table, cell_content);
if (FT_IS_ERROR(status))
return status;
va_list va;
va_start(va, cell_content);
--count;
for (i = 0; i < count; ++i) {
const char *cell = va_arg(va, const char *);
status = ft_write_impl(table, cell);
if (FT_IS_ERROR(status)) {
va_end(va);
return status;
}
}
va_end(va);
ft_ln(table);
return status;
}
#ifdef FT_HAVE_WCHAR
int ft_nwwrite(ft_table_t *table, size_t n, const wchar_t *cell_content, ...)
{
size_t i = 0;
assert(table);
int status = ft_wwrite_impl(table, cell_content);
if (FT_IS_ERROR(status))
return status;
va_list va;
va_start(va, cell_content);
--n;
for (i = 0; i < n; ++i) {
const wchar_t *cell = va_arg(va, const wchar_t *);
status = ft_wwrite_impl(table, cell);
if (FT_IS_ERROR(status)) {
va_end(va);
return status;
}
}
va_end(va);
return status;
}
int ft_nwwrite_ln(ft_table_t *table, size_t n, const wchar_t *cell_content, ...)
{
size_t i = 0;
assert(table);
int status = ft_wwrite_impl(table, cell_content);
if (FT_IS_ERROR(status))
return status;
va_list va;
va_start(va, cell_content);
--n;
for (i = 0; i < n; ++i) {
const wchar_t *cell = va_arg(va, const wchar_t *);
status = ft_wwrite_impl(table, cell);
if (FT_IS_ERROR(status)) {
va_end(va);
return status;
}
}
va_end(va);
ft_ln(table);
return status;
}
#endif
int ft_row_write(ft_table_t *table, size_t cols, const char *cells[])
{
size_t i = 0;
assert(table);
for (i = 0; i < cols; ++i) {
int status = ft_write_impl(table, cells[i]);
if (FT_IS_ERROR(status)) {
/* todo: maybe current pos in case of error should be equal to the one before function call? */
return status;
}
}
return FT_SUCCESS;
}
int ft_row_write_ln(ft_table_t *table, size_t cols, const char *cells[])
{
assert(table);
int status = ft_row_write(table, cols, cells);
if (FT_IS_SUCCESS(status)) {
ft_ln(table);
}
return status;
}
#ifdef FT_HAVE_WCHAR
int ft_row_wwrite(ft_table_t *table, size_t cols, const wchar_t *cells[])
{
size_t i = 0;
assert(table);
for (i = 0; i < cols; ++i) {
int status = ft_wwrite_impl(table, cells[i]);
if (FT_IS_ERROR(status)) {
/* todo: maybe current pos in case of error should be equal
* to the one before function call?
*/
return status;
}
}
return FT_SUCCESS;
}
int ft_row_wwrite_ln(ft_table_t *table, size_t cols, const wchar_t *cells[])
{
assert(table);
int status = ft_row_wwrite(table, cols, cells);
if (FT_IS_SUCCESS(status)) {
ft_ln(table);
}
return status;
}
#endif
int ft_table_write(ft_table_t *table, size_t rows, size_t cols, const char *table_cells[])
{
size_t i = 0;
assert(table);
for (i = 0; i < rows; ++i) {
int status = ft_row_write(table, cols, (const char **)&table_cells[i * cols]);
if (FT_IS_ERROR(status)) {
/* todo: maybe current pos in case of error should be equal
* to the one before function call?
*/
return status;
}
if (i != rows - 1)
ft_ln(table);
}
return FT_SUCCESS;
}
int ft_table_write_ln(ft_table_t *table, size_t rows, size_t cols, const char *table_cells[])
{
assert(table);
int status = ft_table_write(table, rows, cols, table_cells);
if (FT_IS_SUCCESS(status)) {
ft_ln(table);
}
return status;
}
#ifdef FT_HAVE_WCHAR
int ft_table_wwrite(ft_table_t *table, size_t rows, size_t cols, const wchar_t *table_cells[])
{
size_t i = 0;
assert(table);
for (i = 0; i < rows; ++i) {
int status = ft_row_wwrite(table, cols, (const wchar_t **)&table_cells[i * cols]);
if (FT_IS_ERROR(status)) {
/* todo: maybe current pos in case of error should be equal
* to the one before function call?
*/
return status;
}
if (i != rows - 1)
ft_ln(table);
}
return FT_SUCCESS;
}
int ft_table_wwrite_ln(ft_table_t *table, size_t rows, size_t cols, const wchar_t *table_cells[])
{
assert(table);
int status = ft_table_wwrite(table, rows, cols, table_cells);
if (FT_IS_SUCCESS(status)) {
ft_ln(table);
}
return status;
}
#endif
const char *ft_to_string(const ft_table_t *table)
{
typedef char char_type;
const enum str_buf_type buf_type = CharBuf;
const char *space_char = " ";
const char *new_line_char = "\n";
#define EMPTY_STRING ""
int (*snprintf_row_)(const fort_row_t *, char *, size_t, size_t *, size_t, size_t, const context_t *) = snprintf_row;
int (*print_row_separator_)(char *, size_t,
const size_t *, size_t,
const fort_row_t *, const fort_row_t *,
enum HorSeparatorPos, const separator_t *,
const context_t *) = print_row_separator;
int (*snprint_n_strings_)(char *, size_t, size_t, const char *) = snprint_n_strings;
assert(table);
/* Determing size of table string representation */
size_t height = 0;
size_t width = 0;
int status = table_geometry(table, &height, &width);
if (FT_IS_ERROR(status)) {
return NULL;
}
size_t sz = height * width + 1;
/* Allocate string buffer for string representation */
if (table->conv_buffer == NULL) {
((ft_table_t *)table)->conv_buffer = create_string_buffer(sz, buf_type);
if (table->conv_buffer == NULL)
return NULL;
}
while (string_buffer_capacity(table->conv_buffer) < sz) {
if (FT_IS_ERROR(realloc_string_buffer_without_copy(table->conv_buffer))) {
return NULL;
}
}
char_type *buffer = (char_type *)buffer_get_data(table->conv_buffer);
size_t cols = 0;
size_t rows = 0;
size_t *col_width_arr = NULL;
size_t *row_height_arr = NULL;
status = table_rows_and_cols_geometry(table, &col_width_arr, &cols, &row_height_arr, &rows, VISIBLE_GEOMETRY);
if (FT_IS_ERROR(status))
return NULL;
if (rows == 0)
return EMPTY_STRING;
size_t written = 0;
int tmp = 0;
size_t i = 0;
context_t context;
context.table_properties = (table->properties ? table->properties : &g_table_properties);
fort_row_t *prev_row = NULL;
fort_row_t *cur_row = NULL;
separator_t *cur_sep = NULL;
size_t sep_size = vector_size(table->separators);
/* Print top margin */
for (i = 0; i < context.table_properties->entire_table_properties.top_margin; ++i) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, width - 1/* minus new_line*/, space_char));
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, 1, new_line_char));
}
for (i = 0; i < rows; ++i) {
cur_sep = (i < sep_size) ? (*(separator_t **)vector_at(table->separators, i)) : NULL;
cur_row = *(fort_row_t **)vector_at(table->rows, i);
enum HorSeparatorPos separatorPos = (i == 0) ? TopSeparator : InsideSeparator;
context.row = i;
CHCK_RSLT_ADD_TO_WRITTEN(print_row_separator_(buffer + written, sz - written, col_width_arr, cols, prev_row, cur_row, separatorPos, cur_sep, &context));
CHCK_RSLT_ADD_TO_WRITTEN(snprintf_row_(cur_row, buffer + written, sz - written, col_width_arr, cols, row_height_arr[i], &context));
prev_row = cur_row;
}
cur_row = NULL;
cur_sep = (i < sep_size) ? (*(separator_t **)vector_at(table->separators, i)) : NULL;
context.row = i;
CHCK_RSLT_ADD_TO_WRITTEN(print_row_separator_(buffer + written, sz - written, col_width_arr, cols, prev_row, cur_row, BottomSeparator, cur_sep, &context));
/* Print bottom margin */
for (i = 0; i < context.table_properties->entire_table_properties.bottom_margin; ++i) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, width - 1/* minus new_line*/, space_char));
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, 1, new_line_char));
}
F_FREE(col_width_arr);
F_FREE(row_height_arr);
return buffer;
clear:
F_FREE(col_width_arr);
F_FREE(row_height_arr);
return NULL;
#undef EMPTY_STRING
}
#ifdef FT_HAVE_WCHAR
const wchar_t *ft_to_wstring(const ft_table_t *table)
{
typedef wchar_t char_type;
const enum str_buf_type buf_type = WCharBuf;
const char *space_char = " ";
const char *new_line_char = "\n";
#define EMPTY_STRING L""
int (*snprintf_row_)(const fort_row_t *, wchar_t *, size_t, size_t *, size_t, size_t, const context_t *) = wsnprintf_row;
int (*print_row_separator_)(wchar_t *, size_t,
const size_t *, size_t,
const fort_row_t *, const fort_row_t *,
enum HorSeparatorPos, const separator_t *,
const context_t *) = wprint_row_separator;
int (*snprint_n_strings_)(wchar_t *, size_t, size_t, const char *) = wsnprint_n_string;
assert(table);
/* Determing size of table string representation */
size_t height = 0;
size_t width = 0;
int status = table_geometry(table, &height, &width);
if (FT_IS_ERROR(status)) {
return NULL;
}
size_t sz = height * width + 1;
/* Allocate string buffer for string representation */
if (table->conv_buffer == NULL) {
((ft_table_t *)table)->conv_buffer = create_string_buffer(sz, buf_type);
if (table->conv_buffer == NULL)
return NULL;
}
while (string_buffer_capacity(table->conv_buffer) < sz) {
if (FT_IS_ERROR(realloc_string_buffer_without_copy(table->conv_buffer))) {
return NULL;
}
}
char_type *buffer = (char_type *)buffer_get_data(table->conv_buffer);
size_t cols = 0;
size_t rows = 0;
size_t *col_width_arr = NULL;
size_t *row_height_arr = NULL;
status = table_rows_and_cols_geometry(table, &col_width_arr, &cols, &row_height_arr, &rows, VISIBLE_GEOMETRY);
if (rows == 0)
return EMPTY_STRING;
if (FT_IS_ERROR(status))
return NULL;
size_t written = 0;
int tmp = 0;
size_t i = 0;
context_t context;
context.table_properties = (table->properties ? table->properties : &g_table_properties);
fort_row_t *prev_row = NULL;
fort_row_t *cur_row = NULL;
separator_t *cur_sep = NULL;
size_t sep_size = vector_size(table->separators);
/* Print top margin */
for (i = 0; i < context.table_properties->entire_table_properties.top_margin; ++i) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, width - 1/* minus new_line*/, space_char));
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, 1, new_line_char));
}
for (i = 0; i < rows; ++i) {
cur_sep = (i < sep_size) ? (*(separator_t **)vector_at(table->separators, i)) : NULL;
cur_row = *(fort_row_t **)vector_at(table->rows, i);
enum HorSeparatorPos separatorPos = (i == 0) ? TopSeparator : InsideSeparator;
context.row = i;
CHCK_RSLT_ADD_TO_WRITTEN(print_row_separator_(buffer + written, sz - written, col_width_arr, cols, prev_row, cur_row, separatorPos, cur_sep, &context));
CHCK_RSLT_ADD_TO_WRITTEN(snprintf_row_(cur_row, buffer + written, sz - written, col_width_arr, cols, row_height_arr[i], &context));
prev_row = cur_row;
}
cur_row = NULL;
cur_sep = (i < sep_size) ? (*(separator_t **)vector_at(table->separators, i)) : NULL;
context.row = i;
CHCK_RSLT_ADD_TO_WRITTEN(print_row_separator_(buffer + written, sz - written, col_width_arr, cols, prev_row, cur_row, BottomSeparator, cur_sep, &context));
/* Print bottom margin */
for (i = 0; i < context.table_properties->entire_table_properties.bottom_margin; ++i) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, width - 1/* minus new_line*/, space_char));
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, sz - written, 1, new_line_char));
}
F_FREE(col_width_arr);
F_FREE(row_height_arr);
return buffer;
clear:
F_FREE(col_width_arr);
F_FREE(row_height_arr);
return NULL;
#undef EMPTY_STRING
}
#endif
int ft_add_separator(ft_table_t *table)
{
assert(table);
assert(table->separators);
while (vector_size(table->separators) <= table->cur_row) {
separator_t *sep_p = create_separator(F_FALSE);
if (sep_p == NULL)
return FT_MEMORY_ERROR;
int status = vector_push(table->separators, &sep_p);
if (FT_IS_ERROR(status))
return status;
}
separator_t **sep_p = (separator_t **)vector_at(table->separators, table->cur_row);
if (*sep_p == NULL)
*sep_p = create_separator(F_TRUE);
else
(*sep_p)->enabled = F_TRUE;
if (*sep_p == NULL)
return FT_ERROR;
return FT_SUCCESS;
}
static const struct fort_border_style *built_in_styles[] = {
&FORT_BASIC_STYLE,
&FORT_BASIC2_STYLE,
&FORT_SIMPLE_STYLE,
&FORT_PLAIN_STYLE,
&FORT_DOT_STYLE,
&FORT_EMPTY_STYLE,
&FORT_EMPTY2_STYLE,
&FORT_SOLID_STYLE,
&FORT_SOLID_ROUND_STYLE,
&FORT_NICE_STYLE,
&FORT_DOUBLE_STYLE,
&FORT_DOUBLE2_STYLE,
&FORT_BOLD_STYLE,
&FORT_BOLD2_STYLE,
&FORT_FRAME_STYLE,
};
#define BUILT_IN_STYLES_SZ (sizeof(built_in_styles) / sizeof(built_in_styles[0]))
/* todo: remove this stupid and dangerous code */
static const struct ft_border_style built_in_external_styles[BUILT_IN_STYLES_SZ] = {
{
{"", "", "", "", "", ""},
{"", "", "", "", "", ""},
""
}
};
const struct ft_border_style *const FT_BASIC_STYLE = &built_in_external_styles[0];
const struct ft_border_style *const FT_BASIC2_STYLE = &built_in_external_styles[1];
const struct ft_border_style *const FT_SIMPLE_STYLE = &built_in_external_styles[2];
const struct ft_border_style *const FT_PLAIN_STYLE = &built_in_external_styles[3];
const struct ft_border_style *const FT_DOT_STYLE = &built_in_external_styles[4];
const struct ft_border_style *const FT_EMPTY_STYLE = &built_in_external_styles[5];
const struct ft_border_style *const FT_EMPTY2_STYLE = &built_in_external_styles[6];
const struct ft_border_style *const FT_SOLID_STYLE = &built_in_external_styles[7];
const struct ft_border_style *const FT_SOLID_ROUND_STYLE = &built_in_external_styles[8];
const struct ft_border_style *const FT_NICE_STYLE = &built_in_external_styles[9];
const struct ft_border_style *const FT_DOUBLE_STYLE = &built_in_external_styles[10];
const struct ft_border_style *const FT_DOUBLE2_STYLE = &built_in_external_styles[11];
const struct ft_border_style *const FT_BOLD_STYLE = &built_in_external_styles[12];
const struct ft_border_style *const FT_BOLD2_STYLE = &built_in_external_styles[13];
const struct ft_border_style *const FT_FRAME_STYLE = &built_in_external_styles[14];
static void set_border_props_for_props(fort_table_properties_t *properties, const struct ft_border_style *style)
{
if (style >= built_in_external_styles && style < (built_in_external_styles + BUILT_IN_STYLES_SZ)) {
size_t pos = (size_t)(style - built_in_external_styles);
memcpy(&(properties->border_style), built_in_styles[pos], sizeof(struct fort_border_style));
return;
}
const struct ft_border_chars *border_chs = &(style->border_chs);
const struct ft_border_chars *header_border_chs = &(style->header_border_chs);
#define BOR_CHARS properties->border_style.border_chars
#define H_BOR_CHARS properties->border_style.header_border_chars
#define SEP_CHARS properties->border_style.separator_chars
BOR_CHARS[TT_bip] = border_chs->top_border_ch;
BOR_CHARS[IH_bip] = border_chs->separator_ch;
BOR_CHARS[BB_bip] = border_chs->bottom_border_ch;
BOR_CHARS[LL_bip] = BOR_CHARS[IV_bip] = BOR_CHARS[RR_bip] = border_chs->side_border_ch;
BOR_CHARS[TL_bip] = BOR_CHARS[TV_bip] = BOR_CHARS[TR_bip] = border_chs->out_intersect_ch;
BOR_CHARS[LH_bip] = BOR_CHARS[RH_bip] = border_chs->out_intersect_ch;
BOR_CHARS[BL_bip] = BOR_CHARS[BV_bip] = BOR_CHARS[BR_bip] = border_chs->out_intersect_ch;
BOR_CHARS[II_bip] = border_chs->in_intersect_ch;
BOR_CHARS[LI_bip] = BOR_CHARS[TI_bip] = BOR_CHARS[RI_bip] = BOR_CHARS[BI_bip] = border_chs->in_intersect_ch;
if (strlen(border_chs->separator_ch) == 0 && strlen(border_chs->in_intersect_ch) == 0) {
BOR_CHARS[LH_bip] = BOR_CHARS[RH_bip] = "\0";
}
H_BOR_CHARS[TT_bip] = header_border_chs->top_border_ch;
H_BOR_CHARS[IH_bip] = header_border_chs->separator_ch;
H_BOR_CHARS[BB_bip] = header_border_chs->bottom_border_ch;
H_BOR_CHARS[LL_bip] = H_BOR_CHARS[IV_bip] = H_BOR_CHARS[RR_bip] = header_border_chs->side_border_ch;
H_BOR_CHARS[TL_bip] = H_BOR_CHARS[TV_bip] = H_BOR_CHARS[TR_bip] = header_border_chs->out_intersect_ch;
H_BOR_CHARS[LH_bip] = H_BOR_CHARS[RH_bip] = header_border_chs->out_intersect_ch;
H_BOR_CHARS[BL_bip] = H_BOR_CHARS[BV_bip] = H_BOR_CHARS[BR_bip] = header_border_chs->out_intersect_ch;
H_BOR_CHARS[II_bip] = header_border_chs->in_intersect_ch;
H_BOR_CHARS[LI_bip] = H_BOR_CHARS[TI_bip] = H_BOR_CHARS[RI_bip] = H_BOR_CHARS[BI_bip] = header_border_chs->in_intersect_ch;
if (strlen(header_border_chs->separator_ch) == 0 && strlen(header_border_chs->in_intersect_ch) == 0) {
BOR_CHARS[LH_bip] = BOR_CHARS[RH_bip] = "\0";
}
SEP_CHARS[LH_sip] = SEP_CHARS[RH_sip] = SEP_CHARS[II_sip] = header_border_chs->out_intersect_ch;
SEP_CHARS[TI_sip] = SEP_CHARS[BI_sip] = header_border_chs->out_intersect_ch;
SEP_CHARS[IH_sip] = style->hor_separator_char;
#undef BOR_CHARS
#undef H_BOR_CHARS
#undef SEP_CHARS
}
int ft_set_default_border_style(const struct ft_border_style *style)
{
set_border_props_for_props(&g_table_properties, style);
return FT_SUCCESS;
}
int ft_set_border_style(ft_table_t *table, const struct ft_border_style *style)
{
assert(table);
if (table->properties == NULL) {
table->properties = create_table_properties();
if (table->properties == NULL)
return FT_MEMORY_ERROR;
}
set_border_props_for_props(table->properties, style);
return FT_SUCCESS;
}
int ft_set_cell_prop(ft_table_t *table, size_t row, size_t col, uint32_t property, int value)
{
assert(table);
if (table->properties == NULL) {
table->properties = create_table_properties();
if (table->properties == NULL)
return FT_MEMORY_ERROR;
}
if (table->properties->cell_properties == NULL) {
table->properties->cell_properties = create_cell_prop_container();
if (table->properties->cell_properties == NULL) {
return FT_ERROR;
}
}
if (row == FT_CUR_ROW)
row = table->cur_row;
if (row == FT_CUR_COLUMN)
col = table->cur_col;
return set_cell_property(table->properties->cell_properties, row, col, property, value);
}
int ft_set_default_cell_prop(uint32_t property, int value)
{
return set_default_cell_property(property, value);
}
int ft_set_default_tbl_prop(uint32_t property, int value)
{
return set_default_entire_table_property(property, value);
}
int ft_set_tbl_prop(ft_table_t *table, uint32_t property, int value)
{
assert(table);
if (table->properties == NULL) {
table->properties = create_table_properties();
if (table->properties == NULL)
return FT_MEMORY_ERROR;
}
return set_entire_table_property(table->properties, property, value);
}
void ft_set_memory_funcs(void *(*f_malloc)(size_t size), void (*f_free)(void *ptr))
{
set_memory_funcs(f_malloc, f_free);
}
int ft_set_cell_span(ft_table_t *table, size_t row, size_t col, size_t hor_span)
{
assert(table);
if (hor_span < 2)
return FT_EINVAL;
if (row == FT_CUR_ROW)
row = table->cur_row;
if (row == FT_CUR_COLUMN)
col = table->cur_col;
fort_row_t *row_p = get_row_and_create_if_not_exists(table, row);
if (row_p == NULL)
return FT_ERROR;
return row_set_cell_span(row_p, col, hor_span);
}
/********************************************************
End of file "fort_impl.c"
********************************************************/
/********************************************************
Begin of file "fort_utils.c"
********************************************************/
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
#ifdef FT_HAVE_WCHAR
#include <wchar.h>
#endif
char g_col_separator = FORT_DEFAULT_COL_SEPARATOR;
/*****************************************************************************
* LIBFORT helpers
*****************************************************************************/
#ifndef FT_MICROSOFT_COMPILER
void *(*fort_malloc)(size_t size) = &malloc;
void (*fort_free)(void *ptr) = &free;
void *(*fort_calloc)(size_t nmemb, size_t size) = &calloc;
void *(*fort_realloc)(void *ptr, size_t size) = &realloc;
#else
static void *local_malloc(size_t size)
{
return malloc(size);
}
static void local_free(void *ptr)
{
free(ptr);
}
static void *local_calloc(size_t nmemb, size_t size)
{
return calloc(nmemb, size);
}
static void *local_realloc(void *ptr, size_t size)
{
return realloc(ptr, size);
}
void *(*fort_malloc)(size_t size) = &local_malloc;
void (*fort_free)(void *ptr) = &local_free;
void *(*fort_calloc)(size_t nmemb, size_t size) = &local_calloc;
void *(*fort_realloc)(void *ptr, size_t size) = &local_realloc;
#endif
static void *custom_fort_calloc(size_t nmemb, size_t size)
{
size_t total_size = nmemb * size;
void *result = F_MALLOC(total_size);
if (result != NULL)
memset(result, 0, total_size);
return result;
}
static void *custom_fort_realloc(void *ptr, size_t size)
{
if (ptr == NULL)
return F_MALLOC(size);
if (size == 0) {
F_FREE(ptr);
return NULL;
}
void *new_chunk = F_MALLOC(size);
if (new_chunk == NULL)
return NULL;
/*
* In theory we should copy MIN(size, size allocated for ptr) bytes,
* but this is rather dummy implementation so we don't care about it
*/
memcpy(new_chunk, ptr, size);
F_FREE(ptr);
return new_chunk;
}
FT_INTERNAL
void set_memory_funcs(void *(*f_malloc)(size_t size), void (*f_free)(void *ptr))
{
assert((f_malloc == NULL && f_free == NULL) /* Use std functions */
|| (f_malloc != NULL && f_free != NULL) /* Use custom functions */);
if (f_malloc == NULL && f_free == NULL) {
#ifndef FT_MICROSOFT_COMPILER
fort_malloc = &malloc;
fort_free = &free;
fort_calloc = &calloc;
fort_realloc = &realloc;
#else
fort_malloc = &local_malloc;
fort_free = &local_free;
fort_calloc = &local_calloc;
fort_realloc = &local_realloc;
#endif
} else {
fort_malloc = f_malloc;
fort_free = f_free;
fort_calloc = &custom_fort_calloc;
fort_realloc = &custom_fort_realloc;
}
}
FT_INTERNAL
char *fort_strdup(const char *str)
{
if (str == NULL)
return NULL;
size_t sz = strlen(str);
char *str_copy = (char *)F_MALLOC((sz + 1) * sizeof(char));
if (str_copy == NULL)
return NULL;
strcpy(str_copy, str);
return str_copy;
}
#if defined(FT_HAVE_WCHAR)
FT_INTERNAL
wchar_t *fort_wcsdup(const wchar_t *str)
{
if (str == NULL)
return NULL;
size_t sz = wcslen(str);
wchar_t *str_copy = (wchar_t *)F_MALLOC((sz + 1) * sizeof(wchar_t));
if (str_copy == NULL)
return NULL;
wcscpy(str_copy, str);
return str_copy;
}
#endif
FT_INTERNAL
size_t number_of_columns_in_format_string(const char *fmt)
{
size_t separator_counter = 0;
const char *pos = fmt;
while (1) {
pos = strchr(pos, g_col_separator);
if (pos == NULL)
break;
separator_counter++;
++pos;
}
return separator_counter + 1;
}
#if defined(FT_HAVE_WCHAR)
FT_INTERNAL
size_t number_of_columns_in_format_wstring(const wchar_t *fmt)
{
size_t separator_counter = 0;
const wchar_t *pos = fmt;
while (1) {
pos = wcschr(pos, g_col_separator);
if (pos == NULL)
break;
separator_counter++;
++pos;
}
return separator_counter + 1;
}
#endif
FT_INTERNAL
int snprint_n_strings(char *buf, size_t length, size_t n, const char *str)
{
size_t str_len = strlen(str);
if (length <= n * str_len)
return -1;
if (n == 0)
return 0;
/* To ensure valid return value it is safely not print such big strings */
if (n * str_len > INT_MAX)
return -1;
if (str_len == 0)
return 0;
int status = snprintf(buf, length, "%0*d", (int)(n * str_len), 0);
if (status < 0)
return status;
size_t i = 0;
for (i = 0; i < n; ++i) {
const char *str_p = str;
while (*str_p)
*(buf++) = *(str_p++);
}
return (int)(n * str_len);
}
#if defined(FT_HAVE_WCHAR)
#define WCS_SIZE 64
FT_INTERNAL
int wsnprint_n_string(wchar_t *buf, size_t length, size_t n, const char *str)
{
size_t str_len = strlen(str);
/* note: baybe it's, better to return -1 in case of multibyte character
* strings (not sure this case is done correctly).
*/
if (str_len > 1) {
const unsigned char *p = (const unsigned char *)str;
while (*p) {
if (*p <= 127)
p++;
else {
wchar_t wcs[WCS_SIZE];
const char *ptr = str;
size_t wcs_len;
mbstate_t mbst;
memset(&mbst, 0, sizeof(mbst));
wcs_len = mbsrtowcs(wcs, (const char **)&ptr, WCS_SIZE, &mbst);
/* for simplicity */
if ((wcs_len == (size_t) - 1) || wcs_len > 1) {
return -1;
} else {
wcs[wcs_len] = L'\0';
size_t k = n;
while (k) {
*buf = *wcs;
++buf;
--k;
}
buf[n] = L'\0';
return (int)n;
}
}
}
}
if (length <= n * str_len)
return -1;
if (n == 0)
return 0;
/* To ensure valid return value it is safely not print such big strings */
if (n * str_len > INT_MAX)
return -1;
if (str_len == 0)
return 0;
int status = swprintf(buf, length, L"%0*d", (int)(n * str_len), 0);
if (status < 0)
return status;
size_t i = 0;
for (i = 0; i < n; ++i) {
const char *str_p = str;
while (*str_p)
*(buf++) = (wchar_t) * (str_p++);
}
return (int)(n * str_len);
}
#endif
/********************************************************
End of file "fort_utils.c"
********************************************************/
/********************************************************
Begin of file "properties.c"
********************************************************/
/* #include "fort_utils.h" */ /* Commented by amalgamation script */
#include <assert.h>
/* #include "properties.h" */ /* Commented by amalgamation script */
/* #include "vector.h" */ /* Commented by amalgamation script */
#define FT_RESET_COLOR "\033[0m"
static const char *fg_colors[] = {
"",
"\033[30m",
"\033[31m",
"\033[32m",
"\033[33m",
"\033[34m",
"\033[35m",
"\033[36m",
"\033[37m",
"\033[90m",
"\033[91m",
"\033[92m",
"\033[93m",
"\033[94m",
"\033[95m",
"\033[96m",
"\033[97m",
};
static const char *bg_colors[] = {
"",
"\033[40m",
"\033[41m",
"\033[42m",
"\033[43m",
"\033[44m",
"\033[45m",
"\033[46m",
"\033[47m",
"\033[100m",
"\033[101m",
"\033[102m",
"\033[103m",
"\033[104m",
"\033[105m",
"\033[106m",
"\033[107m",
};
static const char *text_styles[] = {
"",
"\033[1m",
"\033[2m",
"\033[3m",
"\033[4m",
"\033[5m",
"\033[7m",
"\033[8m",
};
#define UNIVERSAL_RESET_TAG "\033[0m"
static const size_t n_fg_colors = sizeof(fg_colors) / sizeof(fg_colors[0]);
static const size_t n_bg_colors = sizeof(bg_colors) / sizeof(bg_colors[0]);
static const size_t n_styles = sizeof(text_styles) / sizeof(text_styles[0]);
void get_style_tag_for_cell(const fort_table_properties_t *props,
size_t row, size_t col, char *style_tag, size_t sz)
{
(void)sz;
size_t i = 0;
unsigned bg_color_number = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CELL_BG_COLOR);
unsigned text_style = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CELL_TEXT_STYLE);
style_tag[0] = '\0';
if (text_style < (1U << n_styles)) {
for (i = 0; i < n_styles; ++i) {
if (text_style & (1 << i)) {
strcat(style_tag, text_styles[i]);
}
}
} else {
goto error;
}
if (bg_color_number < n_bg_colors) {
strcat(style_tag, bg_colors[bg_color_number]);
} else {
goto error;
}
return;
error:
/* shouldn't be here */
assert(0);
style_tag[0] = '\0';
return;
}
void get_reset_style_tag_for_cell(const fort_table_properties_t *props,
size_t row, size_t col, char *reset_style_tag, size_t sz)
{
(void)sz;
size_t i = 0;
unsigned bg_color_number = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CELL_BG_COLOR);
unsigned text_style = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CELL_TEXT_STYLE);
reset_style_tag[0] = '\0';
if (text_style < (1U << n_styles)) {
for (i = 0; i < n_styles; ++i) {
if (text_style & (1 << i)) {
if (i != 0) // FT_TSTYLE_DEFAULT
goto reset_style;
}
}
} else {
goto error;
}
if (bg_color_number < n_bg_colors) {
if (bg_color_number)
goto reset_style;
} else {
goto error;
}
return;
reset_style:
strcat(reset_style_tag, UNIVERSAL_RESET_TAG);
return;
error:
/* shouldn't be here */
assert(0);
reset_style_tag[0] = '\0';
return;
}
void get_style_tag_for_content(const fort_table_properties_t *props,
size_t row, size_t col, char *style_tag, size_t sz)
{
(void)sz;
size_t i = 0;
unsigned text_style = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CONT_TEXT_STYLE);
unsigned fg_color_number = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CONT_FG_COLOR);
unsigned bg_color_number = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CONT_BG_COLOR);
style_tag[0] = '\0';
if (text_style < (1U << n_styles)) {
for (i = 0; i < n_styles; ++i) {
if (text_style & (1 << i)) {
strcat(style_tag, text_styles[i]);
}
}
} else {
goto error;
}
if (fg_color_number < n_fg_colors) {
if (fg_color_number)
strcat(style_tag, fg_colors[fg_color_number]);
} else {
goto error;
}
if (bg_color_number < n_bg_colors) {
strcat(style_tag, bg_colors[bg_color_number]);
} else {
goto error;
}
return;
error:
/* shouldn't be here */
assert(0);
style_tag[0] = '\0';
return;
}
void get_reset_style_tag_for_content(const fort_table_properties_t *props,
size_t row, size_t col, char *reset_style_tag, size_t sz)
{
(void)sz;
size_t i = 0;
size_t len = 0;
unsigned text_style = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CONT_TEXT_STYLE);
unsigned fg_color_number = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CONT_FG_COLOR);
unsigned bg_color_number = get_cell_property_value_hierarcial(props, row, col, FT_CPROP_CONT_BG_COLOR);
reset_style_tag[0] = '\0';
if (text_style < (1U << n_styles)) {
for (i = 0; i < n_styles; ++i) {
if (text_style & (1 << i)) {
if (i != 0) // FT_TSTYLE_DEFAULT
goto reset_style;
}
}
} else {
goto error;
}
if (fg_color_number < n_fg_colors) {
if (fg_color_number)
goto reset_style;
} else {
goto error;
}
if (bg_color_number < n_bg_colors) {
if (bg_color_number)
goto reset_style;
} else {
goto error;
}
return;
reset_style:
strcat(reset_style_tag, UNIVERSAL_RESET_TAG);
len = strlen(reset_style_tag);
get_style_tag_for_cell(props, row, col, reset_style_tag + len, sz - len);
return;
error:
/* shouldn't be here */
assert(0);
reset_style_tag[0] = '\0';
return;
}
static struct fort_cell_props g_default_cell_properties = {
FT_ANY_ROW, /* cell_row */
FT_ANY_COLUMN, /* cell_col */
/* properties_flags */
FT_CPROP_MIN_WIDTH | FT_CPROP_TEXT_ALIGN | FT_CPROP_TOP_PADDING
| FT_CPROP_BOTTOM_PADDING | FT_CPROP_LEFT_PADDING | FT_CPROP_RIGHT_PADDING
| FT_CPROP_EMPTY_STR_HEIGHT | FT_CPROP_CONT_FG_COLOR | FT_CPROP_CELL_BG_COLOR
| FT_CPROP_CONT_BG_COLOR | FT_CPROP_CELL_TEXT_STYLE | FT_CPROP_CONT_TEXT_STYLE,
0, /* col_min_width */
FT_ALIGNED_LEFT, /* align */
0, /* cell_padding_top */
0, /* cell_padding_bottom */
1, /* cell_padding_left */
1, /* cell_padding_right */
1, /* cell_empty_string_height */
FT_ROW_COMMON, /* row_type */
FT_COLOR_DEFAULT, /* content_fg_color_number */
FT_COLOR_DEFAULT, /* content_bg_color_number */
FT_COLOR_DEFAULT, /* cell_bg_color_number */
FT_TSTYLE_DEFAULT, /* cell_text_style */
FT_TSTYLE_DEFAULT, /* content_text_style */
};
static int get_prop_value_if_exists_otherwise_default(const struct fort_cell_props *cell_opts, uint32_t property)
{
if (cell_opts == NULL || !PROP_IS_SET(cell_opts->properties_flags, property)) {
cell_opts = &g_default_cell_properties;
}
switch (property) {
case FT_CPROP_MIN_WIDTH:
return cell_opts->col_min_width;
case FT_CPROP_TEXT_ALIGN:
return cell_opts->align;
case FT_CPROP_TOP_PADDING:
return cell_opts->cell_padding_top;
case FT_CPROP_BOTTOM_PADDING:
return cell_opts->cell_padding_bottom;
case FT_CPROP_LEFT_PADDING:
return cell_opts->cell_padding_left;
case FT_CPROP_RIGHT_PADDING:
return cell_opts->cell_padding_right;
case FT_CPROP_EMPTY_STR_HEIGHT:
return cell_opts->cell_empty_string_height;
case FT_CPROP_ROW_TYPE:
return cell_opts->row_type;
case FT_CPROP_CONT_FG_COLOR:
return cell_opts->content_fg_color_number;
case FT_CPROP_CONT_BG_COLOR:
return cell_opts->content_bg_color_number;
case FT_CPROP_CELL_BG_COLOR:
return cell_opts->cell_bg_color_number;
case FT_CPROP_CELL_TEXT_STYLE:
return cell_opts->cell_text_style;
case FT_CPROP_CONT_TEXT_STYLE:
return cell_opts->content_text_style;
default:
/* todo: implement later */
exit(333);
}
}
FT_INTERNAL
fort_cell_prop_container_t *create_cell_prop_container(void)
{
fort_cell_prop_container_t *ret = create_vector(sizeof(fort_cell_props_t), DEFAULT_VECTOR_CAPACITY);
return ret;
}
FT_INTERNAL
void destroy_cell_prop_container(fort_cell_prop_container_t *cont)
{
if (cont)
destroy_vector(cont);
}
FT_INTERNAL
const fort_cell_props_t *cget_cell_prop(const fort_cell_prop_container_t *cont, size_t row, size_t col)
{
assert(cont);
size_t sz = vector_size(cont);
size_t i = 0;
for (i = 0; i < sz; ++i) {
const fort_cell_props_t *opt = (const fort_cell_props_t *)vector_at_c(cont, i);
if (opt->cell_row == row && opt->cell_col == col)
return opt;
}
return NULL;
}
FT_INTERNAL
fort_cell_props_t *get_cell_prop_and_create_if_not_exists(fort_cell_prop_container_t *cont, size_t row, size_t col)
{
assert(cont);
size_t sz = vector_size(cont);
size_t i = 0;
for (i = 0; i < sz; ++i) {
fort_cell_props_t *opt = (fort_cell_props_t *)vector_at(cont, i);
if (opt->cell_row == row && opt->cell_col == col)
return opt;
}
fort_cell_props_t opt;
if (row == FT_ANY_ROW && col == FT_ANY_COLUMN)
memcpy(&opt, &g_default_cell_properties, sizeof(fort_cell_props_t));
else
memset(&opt, 0, sizeof(fort_cell_props_t));
opt.cell_row = row;
opt.cell_col = col;
if (FT_IS_SUCCESS(vector_push(cont, &opt))) {
return (fort_cell_props_t *)vector_at(cont, sz);
}
return NULL;
}
FT_INTERNAL
int get_cell_property_value_hierarcial(const fort_table_properties_t *propertiess, size_t row, size_t column, uint32_t property)
{
assert(propertiess);
size_t row_origin = row;
const fort_cell_props_t *opt = NULL;
if (propertiess->cell_properties != NULL) {
while (1) {
opt = cget_cell_prop(propertiess->cell_properties, row, column);
if (opt != NULL && PROP_IS_SET(opt->properties_flags, property))
break;
if (row != FT_ANY_ROW && column != FT_ANY_COLUMN) {
row = FT_ANY_ROW;
continue;
} else if (row == FT_ANY_ROW && column != FT_ANY_COLUMN) {
row = row_origin;
column = FT_ANY_COLUMN;
continue;
} else if (row != FT_ANY_ROW && column == FT_ANY_COLUMN) {
row = FT_ANY_ROW;
column = FT_ANY_COLUMN;
continue;
}
opt = NULL;
break;
}
}
return get_prop_value_if_exists_otherwise_default(opt, property);
}
static fort_status_t set_cell_property_impl(fort_cell_props_t *opt, uint32_t property, int value)
{
assert(opt);
PROP_SET(opt->properties_flags, property);
if (PROP_IS_SET(property, FT_CPROP_MIN_WIDTH)) {
CHECK_NOT_NEGATIVE(value);
opt->col_min_width = value;
} else if (PROP_IS_SET(property, FT_CPROP_TEXT_ALIGN)) {
opt->align = (enum ft_text_alignment)value;
} else if (PROP_IS_SET(property, FT_CPROP_TOP_PADDING)) {
CHECK_NOT_NEGATIVE(value);
opt->cell_padding_top = value;
} else if (PROP_IS_SET(property, FT_CPROP_BOTTOM_PADDING)) {
CHECK_NOT_NEGATIVE(value);
opt->cell_padding_bottom = value;
} else if (PROP_IS_SET(property, FT_CPROP_LEFT_PADDING)) {
CHECK_NOT_NEGATIVE(value);
opt->cell_padding_left = value;
} else if (PROP_IS_SET(property, FT_CPROP_RIGHT_PADDING)) {
CHECK_NOT_NEGATIVE(value);
opt->cell_padding_right = value;
} else if (PROP_IS_SET(property, FT_CPROP_EMPTY_STR_HEIGHT)) {
CHECK_NOT_NEGATIVE(value);
opt->cell_empty_string_height = value;
} else if (PROP_IS_SET(property, FT_CPROP_ROW_TYPE)) {
opt->row_type = (enum ft_row_type)value;
} else if (PROP_IS_SET(property, FT_CPROP_CONT_FG_COLOR)) {
opt->content_fg_color_number = value;
} else if (PROP_IS_SET(property, FT_CPROP_CONT_BG_COLOR)) {
opt->content_bg_color_number = value;
} else if (PROP_IS_SET(property, FT_CPROP_CELL_BG_COLOR)) {
opt->cell_bg_color_number = value;
} else if (PROP_IS_SET(property, FT_CPROP_CELL_TEXT_STYLE)) {
enum ft_text_style v = (enum ft_text_style)value;
if (v == FT_TSTYLE_DEFAULT) {
opt->cell_text_style = FT_TSTYLE_DEFAULT;
} else {
opt->cell_text_style = (enum ft_text_style)(opt->cell_text_style | v);
}
} else if (PROP_IS_SET(property, FT_CPROP_CONT_TEXT_STYLE)) {
enum ft_text_style v = (enum ft_text_style)value;
if (v == FT_TSTYLE_DEFAULT) {
opt->content_text_style = v;
} else {
opt->content_text_style = (enum ft_text_style)(opt->content_text_style | v);
}
}
return FT_SUCCESS;
fort_fail:
return FT_EINVAL;
}
FT_INTERNAL
fort_status_t set_cell_property(fort_cell_prop_container_t *cont, size_t row, size_t col, uint32_t property, int value)
{
fort_cell_props_t *opt = get_cell_prop_and_create_if_not_exists(cont, row, col);
if (opt == NULL)
return FT_ERROR;
return set_cell_property_impl(opt, property, value);
/*
PROP_SET(opt->propertiess, property);
if (PROP_IS_SET(property, FT_CPROP_MIN_WIDTH)) {
opt->col_min_width = value;
} else if (PROP_IS_SET(property, FT_CPROP_TEXT_ALIGN)) {
opt->align = value;
}
return FT_SUCCESS;
*/
}
FT_INTERNAL
fort_status_t set_default_cell_property(uint32_t property, int value)
{
return set_cell_property_impl(&g_default_cell_properties, property, value);
}
#define BASIC_STYLE { \
/* border_chars */ \
{ \
"+", "-", "+", "+", \
"|", "|", "|", \
"\0", "\0", "\0", "\0", \
"+", "-", "+", "+", \
"+", "+", "+", "+", \
}, \
/* header_border_chars */ \
{ \
"+", "-", "+", "+", \
"|", "|", "|", \
"+", "-", "+", "+", \
"+", "-", "+", "+", \
"+", "+", "+", "+", \
}, \
/* separator_chars */ \
{ \
"+", "-", "+", "+", \
"+", "+", \
}, \
}
#define BASIC2_STYLE { \
/* border_chars */ \
{ \
"+", "-", "+", "+", \
"|", "|", "|", \
"+", "-", "+", "+", \
"+", "-", "+", "+", \
"+", "+", "+", "+", \
}, \
/* header_border_chars */ \
{ \
"+", "-", "+", "+", \
"|", "|", "|", \
"+", "-", "+", "+", \
"+", "-", "+", "+", \
"+", "+", "+", "+", \
}, \
/* separator_chars */ \
{ \
"+", "-", "+", "+", \
"+", "+", \
}, \
}
#define SIMPLE_STYLE { \
/* border_chars */ \
{ \
"\0", "\0", "\0", "\0", \
"\0", " ", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
}, \
/* header_border_chars */ \
{ \
"\0", "\0", "\0", "\0", \
"\0", " ", "\0", \
"\0", "-", " ", "\0", \
"\0", " ", " ", "\0", \
" ", "-", " ", "-", \
}, \
/* separator_chars */ \
{ \
"\0", "-", " ", "\0", \
" ", " ", \
}, \
}
#define PLAIN_STYLE { \
/* border_chars */ \
{ \
"\0", "\0", "\0", "\0", \
"\0", " ", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
}, \
/* header_border_chars */ \
{ \
"\0", "-", "-", "\0", \
"\0", " ", "\0", \
"\0", "-", "-", "\0", \
"\0", "-", "-", "\0", \
" ", "-", " ", "-", \
}, \
/* separator_chars */ \
{ \
"\0", "-", "-", "\0", \
"-", "-", \
}, \
}
#define DOT_STYLE { \
/* border_chars */ \
{ \
".", ".", ".", ".", \
":", ":", ":", \
"\0", "\0", "\0", "\0", \
":", ".", ":", ":", \
"+", ":", "+", ":", \
}, \
/* header_border_chars */ \
{ \
".", ".", ".", ".", \
":", ":", ":", \
":", ".", ":", ":", \
":", ".", ":", ":", \
"+", ".", "+", ".", \
}, \
/* separator_chars */ \
{ \
":", ".", ":", ":", \
":", ":", \
}, \
}
#define EMPTY_STYLE { \
/* border_chars */ \
{ \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
}, \
/* header_border_chars */ \
{ \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
"\0", "\0", "\0", "\0", \
}, \
/* separator_chars */ \
{ \
"\0", " ", "\0 ", "\0", \
"\0", "\0", \
}, \
}
#define EMPTY2_STYLE { \
/* border_chars */ \
{ \
" ", " ", " ", " ", \
" ", " ", " ", \
"\0", "\0", "\0", "\0", \
" ", " ", " ", " ", \
" ", " ", " ", " ", \
}, \
/* header_border_chars */ \
{ \
" ", " ", " ", " ", \
" ", " ", " ", \
"\0", "\0", "\0", "\0", \
" ", " ", " ", " ", \
" ", " ", " ", " ", \
}, \
/* separator_chars */ \
{ \
" ", " ", " ", " ", \
" ", " ", \
}, \
}
#define SOLID_STYLE { \
/* border_chars */ \
{ \
"┌", "─", "┬", "┐", \
"│", "│", "│", \
"", "", "", "", \
"└", "─", "┴", "╯", \
"│", "─", "│", "─", \
}, \
/* header_border_chars */ \
{ \
"┌", "─", "┬", "┐", \
"│", "│", "│", \
"├", "─", "┼", "┤", \
"└", "─", "┴", "┘", \
"┼", "┬", "┼", "┴", \
}, \
/* separator_chars */ \
{ \
"├", "─", "┼", "┤", \
"┬", "┴", \
}, \
}
#define SOLID_ROUND_STYLE { \
/* border_chars */ \
{ \
"╭", "─", "┬", "╮", \
"│", "│", "│", \
"", "", "", "", \
"╰", "─", "┴", "╯", \
"│", "─", "│", "─", \
}, \
/* header_border_chars */ \
{ \
"╭", "─", "┬", "╮", \
"│", "│", "│", \
"├", "─", "┼", "┤", \
"╰", "─", "┴", "╯", \
"┼", "┬", "┼", "┴", \
}, \
/* separator_chars */ \
{ \
"├", "─", "┼", "┤", \
"┬", "┴", \
}, \
}
#define NICE_STYLE { \
/* border_chars */ \
{ \
"╔", "═", "╦", "╗", \
"║", "║", "║", \
"", "", "", "", \
"╚", "═", "╩", "╝", \
"┣", "┻", "┣", "┳", \
}, \
/* header_border_chars */ \
{ \
"╔", "═", "╦", "╗", \
"║", "║", "║", \
"╠", "═", "╬", "╣", \
"╚", "═", "╩", "╝", \
"┣", "╦", "┣", "╩", \
}, \
/* separator_chars */ \
{ \
"╟", "─", "╫", "╢", \
"╥", "╨", \
}, \
}
#define DOUBLE_STYLE { \
/* border_chars */ \
{ \
"╔", "═", "╦", "╗", \
"║", "║", "║", \
"", "", "", "", \
"╚", "═", "╩", "╝", \
"┣", "┻", "┣", "┳", \
}, \
/* header_border_chars */ \
{ \
"╔", "═", "╦", "╗", \
"║", "║", "║", \
"╠", "═", "╬", "╣", \
"╚", "═", "╩", "╝", \
"┣", "╦", "┣", "╩", \
}, \
/* separator_chars */ \
{ \
"╠", "═", "╬", "╣", \
"╦", "╩", \
}, \
}
#define DOUBLE2_STYLE { \
/* border_chars */ \
{ \
"╔", "═", "╤", "╗", \
"║", "│", "║", \
"╟", "─", "┼", "╢", \
"╚", "═", "╧", "╝", \
"├", "┬", "┤", "┴", \
}, \
/* header_border_chars */ \
{ \
"╔", "═", "╤", "╗", \
"║", "│", "║", \
"╠", "═", "╪", "╣", \
"╚", "═", "╧", "╝", \
"├", "╤", "┤", "╧", \
}, \
/* separator_chars */ \
{ \
"╠", "═", "╪", "╣", \
"╤", "╧", \
}, \
}
#define BOLD_STYLE { \
/* border_chars */ \
{ \
"┏", "━", "┳", "┓", \
"┃", "┃", "┃", \
"", "", "", "", \
"┗", "━", "┻", "┛", \
"┣", "┻", "┣", "┳", \
}, \
/* header_border_chars */ \
{ \
"┏", "━", "┳", "┓", \
"┃", "┃", "┃", \
"┣", "━", "╋", "┫", \
"┗", "━", "┻", "┛", \
"┣", "┳", "┣", "┻", \
}, \
/* separator_chars */ \
{ \
"┣", "━", "╋", "┫", \
"┳", "┻", \
}, \
}
#define BOLD2_STYLE { \
/* border_chars */ \
{ \
"┏", "━", "┯", "┓", \
"┃", "│", "┃", \
"┠", "─", "┼", "┨", \
"┗", "━", "┷", "┛", \
"┣", "┬", "┣", "┴", \
}, \
/* header_border_chars */ \
{ \
"┏", "━", "┯", "┓", \
"┃", "│", "┃", \
"┣", "━", "┿", "┫", \
"┗", "━", "┷", "┛", \
"┣", "┯", "┣", "┷", \
}, \
/* separator_chars */ \
{ \
"┣", "━", "┿", "┫", \
"┯", "┷", \
}, \
}
#define FRAME_STYLE { \
/* border_chars */ \
{ \
"▛", "▀", "▀", "▜", \
"▌", "┃", "▐", \
"", "", "", "", \
"▙", "▄", "▄", "▟", \
"┣", "━", "┣", "━" \
}, \
/* header_border_chars */ \
{ \
"▛", "▀", "▀", "▜", \
"▌", "┃", "▐", \
"▌", "━", "╋", "▐", \
"▙", "▄", "▄", "▟", \
"┣", "━", "┣", "━", \
}, \
/* separator_chars */ \
{ \
"▌", "━", "╋", "▐", \
"╋", "╋", \
}, \
}
struct fort_border_style FORT_BASIC_STYLE = BASIC_STYLE;
struct fort_border_style FORT_BASIC2_STYLE = BASIC2_STYLE;
struct fort_border_style FORT_SIMPLE_STYLE = SIMPLE_STYLE;
struct fort_border_style FORT_PLAIN_STYLE = PLAIN_STYLE;
struct fort_border_style FORT_DOT_STYLE = DOT_STYLE;
struct fort_border_style FORT_EMPTY_STYLE = EMPTY_STYLE;
struct fort_border_style FORT_EMPTY2_STYLE = EMPTY2_STYLE;
struct fort_border_style FORT_SOLID_STYLE = SOLID_STYLE;
struct fort_border_style FORT_SOLID_ROUND_STYLE = SOLID_ROUND_STYLE;
struct fort_border_style FORT_NICE_STYLE = NICE_STYLE;
struct fort_border_style FORT_DOUBLE_STYLE = DOUBLE_STYLE;
struct fort_border_style FORT_DOUBLE2_STYLE = DOUBLE2_STYLE;
struct fort_border_style FORT_BOLD_STYLE = BOLD_STYLE;
struct fort_border_style FORT_BOLD2_STYLE = BOLD2_STYLE;
struct fort_border_style FORT_FRAME_STYLE = FRAME_STYLE;
fort_entire_table_properties_t g_entire_table_properties = {
0, /* left_margin */
0, /* top_margin */
0, /* right_margin */
0, /* bottom_margin */
};
static fort_status_t set_entire_table_property_internal(fort_entire_table_properties_t *properties, uint32_t property, int value)
{
assert(properties);
CHECK_NOT_NEGATIVE(value);
if (PROP_IS_SET(property, FT_TPROP_LEFT_MARGIN)) {
properties->left_margin = value;
} else if (PROP_IS_SET(property, FT_TPROP_TOP_MARGIN)) {
properties->top_margin = value;
} else if (PROP_IS_SET(property, FT_TPROP_RIGHT_MARGIN)) {
properties->right_margin = value;
} else if (PROP_IS_SET(property, FT_TPROP_BOTTOM_MARGIN)) {
properties->bottom_margin = value;
} else {
return FT_EINVAL;
}
return FT_SUCCESS;
fort_fail:
return FT_EINVAL;
}
FT_INTERNAL
fort_status_t set_entire_table_property(fort_table_properties_t *table_properties, uint32_t property, int value)
{
assert(table_properties);
return set_entire_table_property_internal(&table_properties->entire_table_properties, property, value);
}
FT_INTERNAL
fort_status_t set_default_entire_table_property(uint32_t property, int value)
{
return set_entire_table_property_internal(&g_entire_table_properties, property, value);
}
FT_INTERNAL
size_t max_border_elem_strlen(struct fort_table_properties *properties)
{
assert(properties);
size_t result = 1;
int i = 0;
for (i = 0; i < BorderItemPosSize; ++i) {
result = MAX(result, strlen(properties->border_style.border_chars[i]));
}
for (i = 0; i < BorderItemPosSize; ++i) {
result = MAX(result, strlen(properties->border_style.header_border_chars[i]));
}
for (i = 0; i < SepratorItemPosSize; ++i) {
result = MAX(result, strlen(properties->border_style.separator_chars[i]));
}
return result;
}
fort_table_properties_t g_table_properties = {
/* border_style */
BASIC_STYLE,
NULL, /* cell_properties */
/* entire_table_properties */
{
0, /* left_margin */
0, /* top_margin */
0, /* right_margin */
0 /* bottom_margin */
}
};
FT_INTERNAL
fort_table_properties_t *create_table_properties(void)
{
fort_table_properties_t *properties = (fort_table_properties_t *)F_CALLOC(sizeof(fort_table_properties_t), 1);
if (properties == NULL) {
return NULL;
}
memcpy(properties, &g_table_properties, sizeof(fort_table_properties_t));
properties->cell_properties = create_cell_prop_container();
if (properties->cell_properties == NULL) {
destroy_table_properties(properties);
return NULL;
}
memcpy(&properties->entire_table_properties, &g_entire_table_properties, sizeof(fort_entire_table_properties_t));
return properties;
}
FT_INTERNAL
void destroy_table_properties(fort_table_properties_t *properties)
{
if (properties == NULL)
return;
if (properties->cell_properties != NULL) {
destroy_cell_prop_container(properties->cell_properties);
}
F_FREE(properties);
}
static
fort_cell_prop_container_t *copy_cell_properties(fort_cell_prop_container_t *cont)
{
fort_cell_prop_container_t *result = create_cell_prop_container();
if (result == NULL)
return NULL;
size_t i = 0;
size_t sz = vector_size(cont);
for (i = 0; i < sz; ++i) {
fort_cell_props_t *opt = (fort_cell_props_t *)vector_at(cont, i);
if (FT_IS_ERROR(vector_push(result, opt))) {
destroy_cell_prop_container(result);
return NULL;
}
}
return result;
}
FT_INTERNAL
fort_table_properties_t *copy_table_properties(const fort_table_properties_t *properties)
{
fort_table_properties_t *new_opt = create_table_properties();
if (new_opt == NULL)
return NULL;
destroy_vector(new_opt->cell_properties);
new_opt->cell_properties = copy_cell_properties(properties->cell_properties);
if (new_opt->cell_properties == NULL) {
destroy_table_properties(new_opt);
return NULL;
}
memcpy(&new_opt->border_style, &properties->border_style, sizeof(struct fort_border_style));
memcpy(&new_opt->entire_table_properties,
&properties->entire_table_properties, sizeof(fort_entire_table_properties_t));
return new_opt;
}
/********************************************************
End of file "properties.c"
********************************************************/
/********************************************************
Begin of file "row.c"
********************************************************/
#include <assert.h>
#include <ctype.h>
/* #include "row.h" */ /* Commented by amalgamation script */
/* #include "cell.h" */ /* Commented by amalgamation script */
/* #include "string_buffer.h" */ /* Commented by amalgamation script */
/* #include "vector.h" */ /* Commented by amalgamation script */
struct fort_row {
vector_t *cells;
/*enum ft_row_type type;*/
};
FT_INTERNAL
fort_row_t *create_row(void)
{
fort_row_t *row = (fort_row_t *)F_CALLOC(sizeof(fort_row_t), 1);
if (row == NULL)
return NULL;
row->cells = create_vector(sizeof(fort_cell_t *), DEFAULT_VECTOR_CAPACITY);
if (row->cells == NULL) {
F_FREE(row);
return NULL;
}
/*
row->is_header = F_FALSE;
row->type = FT_ROW_COMMON;
*/
return row;
}
FT_INTERNAL
void destroy_row(fort_row_t *row)
{
if (row == NULL)
return;
if (row->cells) {
size_t i = 0;
size_t cells_n = vector_size(row->cells);
for (i = 0; i < cells_n; ++i) {
fort_cell_t *cell = *(fort_cell_t **)vector_at(row->cells, i);
destroy_cell(cell);
}
destroy_vector(row->cells);
}
F_FREE(row);
}
FT_INTERNAL
fort_row_t *copy_row(fort_row_t *row)
{
assert(row);
fort_row_t *result = create_row();
if (result == NULL)
return NULL;
size_t i = 0;
size_t cols_n = vector_size(row->cells);
for (i = 0; i < cols_n; ++i) {
fort_cell_t *cell = *(fort_cell_t **)vector_at(row->cells, i);
fort_cell_t *new_cell = copy_cell(cell);
if (new_cell == NULL) {
destroy_row(result);
return NULL;
}
vector_push(result->cells, &new_cell);
}
return result;
}
FT_INTERNAL
size_t columns_in_row(const fort_row_t *row)
{
if (row == NULL || row->cells == NULL)
return 0;
return vector_size(row->cells);
}
static
fort_cell_t *get_cell_implementation(fort_row_t *row, size_t col, enum PolicyOnNull policy)
{
if (row == NULL || row->cells == NULL) {
return NULL;
}
switch (policy) {
case DoNotCreate:
if (col < columns_in_row(row)) {
return *(fort_cell_t **)vector_at(row->cells, col);
}
return NULL;
case Create:
while (col >= columns_in_row(row)) {
fort_cell_t *new_cell = create_cell();
if (new_cell == NULL)
return NULL;
if (FT_IS_ERROR(vector_push(row->cells, &new_cell))) {
destroy_cell(new_cell);
return NULL;
}
}
return *(fort_cell_t **)vector_at(row->cells, col);
}
assert(0 && "Shouldn't be here!");
return NULL;
}
FT_INTERNAL
fort_cell_t *get_cell(fort_row_t *row, size_t col)
{
return get_cell_implementation(row, col, DoNotCreate);
}
FT_INTERNAL
const fort_cell_t *get_cell_c(const fort_row_t *row, size_t col)
{
return get_cell((fort_row_t *)row, col);
}
FT_INTERNAL
fort_cell_t *get_cell_and_create_if_not_exists(fort_row_t *row, size_t col)
{
return get_cell_implementation(row, col, Create);
}
FT_INTERNAL
fort_status_t swap_row(fort_row_t *cur_row, fort_row_t *ins_row, size_t pos)
{
assert(cur_row);
assert(ins_row);
size_t cur_sz = vector_size(cur_row->cells);
if (cur_sz == 0 && pos == 0) {
fort_row_t tmp;
memcpy(&tmp, cur_row, sizeof(fort_row_t));
memcpy(cur_row, ins_row, sizeof(fort_row_t));
memcpy(ins_row, &tmp, sizeof(fort_row_t));
return FT_SUCCESS;
}
return vector_swap(cur_row->cells, ins_row->cells, pos);
}
FT_INTERNAL
size_t group_cell_number(const fort_row_t *row, size_t master_cell_col)
{
assert(row);
const fort_cell_t *master_cell = get_cell_c(row, master_cell_col);
if (master_cell == NULL)
return 0;
if (get_cell_type(master_cell) != GroupMasterCell)
return 1;
size_t total_cols = vector_size(row->cells);
size_t slave_col = master_cell_col + 1;
while (slave_col < total_cols) {
const fort_cell_t *cell = get_cell_c(row, slave_col);
if (cell && get_cell_type(cell) == GroupSlaveCell) {
++slave_col;
} else {
break;
}
}
return slave_col - master_cell_col;
}
FT_INTERNAL
int get_row_cell_types(const fort_row_t *row, enum CellType *types, size_t types_sz)
{
assert(row);
assert(types);
size_t i = 0;
for (i = 0; i < types_sz; ++i) {
const fort_cell_t *cell = get_cell_c(row, i);
if (cell) {
types[i] = get_cell_type(cell);
} else {
types[i] = CommonCell;
}
}
return FT_SUCCESS;
}
FT_INTERNAL
fort_status_t row_set_cell_span(fort_row_t *row, size_t cell_column, size_t hor_span)
{
assert(row);
if (hor_span < 2)
return FT_EINVAL;
fort_cell_t *main_cell = get_cell_and_create_if_not_exists(row, cell_column);
if (main_cell == NULL) {
return FT_ERROR;
}
set_cell_type(main_cell, GroupMasterCell);
--hor_span;
++cell_column;
while (hor_span) {
fort_cell_t *slave_cell = get_cell_and_create_if_not_exists(row, cell_column);
if (slave_cell == NULL) {
return FT_ERROR;
}
set_cell_type(slave_cell, GroupSlaveCell);
--hor_span;
++cell_column;
}
return FT_SUCCESS;
}
FT_INTERNAL
int print_row_separator(char *buffer, size_t buffer_sz,
const size_t *col_width_arr, size_t cols,
const fort_row_t *upper_row, const fort_row_t *lower_row,
enum HorSeparatorPos separatorPos,
const separator_t *sep, const context_t *context)
{
int (*snprint_n_strings_)(char *, size_t, size_t, const char *) = snprint_n_strings;
assert(buffer);
assert(context);
const char *space_char = " ";
int status = -1;
/* Get cell types
*
* Regions above top row and below bottom row areconsidered full of virtual
* GroupSlaveCell cells
*/
enum CellType *top_row_types = (enum CellType *)F_MALLOC(sizeof(enum CellType) * cols * 2);
if (top_row_types == NULL) {
return FT_MEMORY_ERROR;
}
enum CellType *bottom_row_types = top_row_types + cols;
if (upper_row) {
get_row_cell_types(upper_row, top_row_types, cols);
} else {
size_t i = 0;
for (i = 0; i < cols; ++i)
top_row_types[i] = GroupSlaveCell;
}
if (lower_row) {
get_row_cell_types(lower_row, bottom_row_types, cols);
} else {
size_t i = 0;
for (i = 0; i < cols; ++i)
bottom_row_types[i] = GroupSlaveCell;
}
size_t written = 0;
int tmp = 0;
enum ft_row_type lower_row_type = FT_ROW_COMMON;
if (lower_row != NULL) {
lower_row_type = (enum ft_row_type)get_cell_property_value_hierarcial(context->table_properties, context->row, FT_ANY_COLUMN, FT_CPROP_ROW_TYPE);
}
enum ft_row_type upper_row_type = FT_ROW_COMMON;
if (upper_row != NULL) {
upper_row_type = (enum ft_row_type)get_cell_property_value_hierarcial(context->table_properties, context->row - 1, FT_ANY_COLUMN, FT_CPROP_ROW_TYPE);
}
/* Row separator anatomy
*
* | C11 | C12 C13 | C14 C15 |
* L I I I IV I I IT I I I IB I I II I I R
* | C21 | C22 | C23 C24 C25 |
*/
const char **L = NULL;
const char **I = NULL;
const char **IV = NULL;
const char **R = NULL;
const char **IT = NULL;
const char **IB = NULL;
const char **II = NULL;
typedef const char *(*border_chars_point_t)[BorderItemPosSize];
const char *(*border_chars)[BorderItemPosSize] = NULL;
border_chars = (border_chars_point_t)&context->table_properties->border_style.border_chars;
if (upper_row_type == FT_ROW_HEADER || lower_row_type == FT_ROW_HEADER) {
border_chars = (border_chars_point_t)&context->table_properties->border_style.header_border_chars;
}
if (sep && sep->enabled) {
L = &(context->table_properties->border_style.separator_chars[LH_sip]);
I = &(context->table_properties->border_style.separator_chars[IH_sip]);
IV = &(context->table_properties->border_style.separator_chars[II_sip]);
R = &(context->table_properties->border_style.separator_chars[RH_sip]);
IT = &(context->table_properties->border_style.separator_chars[TI_sip]);
IB = &(context->table_properties->border_style.separator_chars[BI_sip]);
II = &(context->table_properties->border_style.separator_chars[IH_sip]);
if (lower_row == NULL) {
L = &(*border_chars)[BL_bip];
R = &(*border_chars)[BR_bip];
} else if (upper_row == NULL) {
L = &(*border_chars)[TL_bip];
R = &(*border_chars)[TR_bip];
}
} else {
switch (separatorPos) {
case TopSeparator:
L = &(*border_chars)[TL_bip];
I = &(*border_chars)[TT_bip];
IV = &(*border_chars)[TV_bip];
R = &(*border_chars)[TR_bip];
IT = &(*border_chars)[TV_bip];
IB = &(*border_chars)[TV_bip];
II = &(*border_chars)[TT_bip];
break;
case InsideSeparator:
L = &(*border_chars)[LH_bip];
I = &(*border_chars)[IH_bip];
IV = &(*border_chars)[II_bip];
R = &(*border_chars)[RH_bip];
/*
IT = &(*border_chars)[TV_bip];
IB = &(*border_chars)[BV_bip];
*/
IT = &(*border_chars)[TI_bip];
IB = &(*border_chars)[BI_bip];
II = &(*border_chars)[IH_bip];
break;
case BottomSeparator:
L = &(*border_chars)[BL_bip];
I = &(*border_chars)[BB_bip];
IV = &(*border_chars)[BV_bip];
R = &(*border_chars)[BR_bip];
IT = &(*border_chars)[BV_bip];
IB = &(*border_chars)[BV_bip];
II = &(*border_chars)[BB_bip];
break;
default:
break;
}
}
size_t i = 0;
/* If all chars are not printable, skip line separator */
/* todo: add processing for wchar_t */
/*
if (!isprint(*L) && !isprint(*I) && !isprint(*IV) && !isprint(*R)) {
status = 0;
goto clear;
}
*/
if ((strlen(*L) == 0 || (strlen(*L) == 1 && !isprint(**L)))
&& (strlen(*I) == 0 || (strlen(*I) == 1 && !isprint(**I)))
&& (strlen(*IV) == 0 || (strlen(*IV) == 1 && !isprint(**IV)))
&& (strlen(*R) == 0 || (strlen(*R) == 1 && !isprint(**R)))) {
status = 0;
goto clear;
}
/* Print left margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, context->table_properties->entire_table_properties.left_margin, space_char));
for (i = 0; i < cols; ++i) {
if (i == 0) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *L));
} else {
if ((top_row_types[i] == CommonCell || top_row_types[i] == GroupMasterCell)
&& (bottom_row_types[i] == CommonCell || bottom_row_types[i] == GroupMasterCell)) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *IV));
} else if (top_row_types[i] == GroupSlaveCell && bottom_row_types[i] == GroupSlaveCell) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *II));
} else if (top_row_types[i] == GroupSlaveCell) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *IT));
} else {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *IB));
}
}
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, col_width_arr[i], *I));
}
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *R));
/* Print right margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, context->table_properties->entire_table_properties.right_margin, space_char));
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, "\n"));
status = (int)written;
clear:
F_FREE(top_row_types);
return status;
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
int wprint_row_separator(wchar_t *buffer, size_t buffer_sz,
const size_t *col_width_arr, size_t cols,
const fort_row_t *upper_row, const fort_row_t *lower_row,
enum HorSeparatorPos separatorPos, const separator_t *sep,
const context_t *context)
{
int (*snprint_n_strings_)(wchar_t *, size_t, size_t, const char *) = wsnprint_n_string;
assert(buffer);
assert(context);
const char *space_char = " ";
int status = -1;
/* Get cell types
*
* Regions above top row and below bottom row areconsidered full of virtual
* GroupSlaveCell cells
*/
enum CellType *top_row_types = (enum CellType *)F_MALLOC(sizeof(enum CellType) * cols * 2);
if (top_row_types == NULL) {
return FT_MEMORY_ERROR;
}
enum CellType *bottom_row_types = top_row_types + cols;
if (upper_row) {
get_row_cell_types(upper_row, top_row_types, cols);
} else {
size_t i = 0;
for (i = 0; i < cols; ++i)
top_row_types[i] = GroupSlaveCell;
}
if (lower_row) {
get_row_cell_types(lower_row, bottom_row_types, cols);
} else {
size_t i = 0;
for (i = 0; i < cols; ++i)
bottom_row_types[i] = GroupSlaveCell;
}
size_t written = 0;
int tmp = 0;
enum ft_row_type lower_row_type = FT_ROW_COMMON;
if (lower_row != NULL) {
lower_row_type = (enum ft_row_type)get_cell_property_value_hierarcial(context->table_properties, context->row, FT_ANY_COLUMN, FT_CPROP_ROW_TYPE);
}
enum ft_row_type upper_row_type = FT_ROW_COMMON;
if (upper_row != NULL) {
upper_row_type = (enum ft_row_type)get_cell_property_value_hierarcial(context->table_properties, context->row - 1, FT_ANY_COLUMN, FT_CPROP_ROW_TYPE);
}
/* Row separator anatomy
*
* | C11 | C12 C13 | C14 C15 |
* L I I I IV I I IT I I I IB I I II I I R
* | C21 | C22 | C23 C24 C25 |
*/
const char **L = NULL;
const char **I = NULL;
const char **IV = NULL;
const char **R = NULL;
const char **IT = NULL;
const char **IB = NULL;
const char **II = NULL;
typedef const char *(*border_chars_point_t)[BorderItemPosSize];
const char *(*border_chars)[BorderItemPosSize] = NULL;
border_chars = (border_chars_point_t)&context->table_properties->border_style.border_chars;
if (upper_row_type == FT_ROW_HEADER || lower_row_type == FT_ROW_HEADER) {
border_chars = (border_chars_point_t)&context->table_properties->border_style.header_border_chars;
}
if (sep && sep->enabled) {
L = &(context->table_properties->border_style.separator_chars[LH_sip]);
I = &(context->table_properties->border_style.separator_chars[IH_sip]);
IV = &(context->table_properties->border_style.separator_chars[II_sip]);
R = &(context->table_properties->border_style.separator_chars[RH_sip]);
IT = &(context->table_properties->border_style.separator_chars[TI_sip]);
IB = &(context->table_properties->border_style.separator_chars[BI_sip]);
II = &(context->table_properties->border_style.separator_chars[IH_sip]);
if (lower_row == NULL) {
L = &(*border_chars)[BL_bip];
R = &(*border_chars)[BR_bip];
} else if (upper_row == NULL) {
L = &(*border_chars)[TL_bip];
R = &(*border_chars)[TR_bip];
}
} else {
switch (separatorPos) {
case TopSeparator:
L = &(*border_chars)[TL_bip];
I = &(*border_chars)[TT_bip];
IV = &(*border_chars)[TV_bip];
R = &(*border_chars)[TR_bip];
IT = &(*border_chars)[TV_bip];
IB = &(*border_chars)[TV_bip];
II = &(*border_chars)[TT_bip];
break;
case InsideSeparator:
L = &(*border_chars)[LH_bip];
I = &(*border_chars)[IH_bip];
IV = &(*border_chars)[II_bip];
R = &(*border_chars)[RH_bip];
/*
IT = &(*border_chars)[TV_bip];
IB = &(*border_chars)[BV_bip];
*/
IT = &(*border_chars)[TI_bip];
IB = &(*border_chars)[BI_bip];
II = &(*border_chars)[IH_bip];
break;
case BottomSeparator:
L = &(*border_chars)[BL_bip];
I = &(*border_chars)[BB_bip];
IV = &(*border_chars)[BV_bip];
R = &(*border_chars)[BR_bip];
IT = &(*border_chars)[BV_bip];
IB = &(*border_chars)[BV_bip];
II = &(*border_chars)[BB_bip];
break;
default:
break;
}
}
size_t i = 0;
/* If all chars are not printable, skip line separator */
/* todo: add processing for wchar_t */
/*
if (!isprint(*L) && !isprint(*I) && !isprint(*IV) && !isprint(*R)) {
status = 0;
goto clear;
}
*/
if ((strlen(*L) == 0 || (strlen(*L) == 1 && !isprint(**L)))
&& (strlen(*I) == 0 || (strlen(*I) == 1 && !isprint(**I)))
&& (strlen(*IV) == 0 || (strlen(*IV) == 1 && !isprint(**IV)))
&& (strlen(*R) == 0 || (strlen(*R) == 1 && !isprint(**R)))) {
status = 0;
goto clear;
}
/* Print left margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, context->table_properties->entire_table_properties.left_margin, space_char));
for (i = 0; i < cols; ++i) {
if (i == 0) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *L));
} else {
if ((top_row_types[i] == CommonCell || top_row_types[i] == GroupMasterCell)
&& (bottom_row_types[i] == CommonCell || bottom_row_types[i] == GroupMasterCell)) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *IV));
} else if (top_row_types[i] == GroupSlaveCell && bottom_row_types[i] == GroupSlaveCell) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *II));
} else if (top_row_types[i] == GroupSlaveCell) {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *IT));
} else {
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *IB));
}
}
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, col_width_arr[i], *I));
}
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, *R));
/* Print right margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, context->table_properties->entire_table_properties.right_margin, space_char));
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buffer_sz - written, 1, "\n"));
status = (int)written;
clear:
F_FREE(top_row_types);
return status;
}
#endif
FT_INTERNAL
fort_row_t *create_row_from_string(const char *str)
{
typedef char char_type;
char_type *(*strdup_)(const char_type * str) = F_STRDUP;
const char_type zero_char = '\0';
fort_status_t (*fill_cell_from_string_)(fort_cell_t *cell, const char *str) = fill_cell_from_string;
const char_type *const zero_string = "";
#define STRCHR strchr
char_type *pos = NULL;
char_type *base_pos = NULL;
size_t number_of_separators = 0;
fort_row_t *row = create_row();
if (row == NULL)
return NULL;
if (str == NULL)
return row;
char_type *str_copy = strdup_(str);
if (str_copy == NULL)
goto clear;
pos = str_copy;
base_pos = str_copy;
number_of_separators = 0;
while (*pos) {
pos = STRCHR(pos, g_col_separator);
if (pos != NULL) {
*(pos) = zero_char;
++pos;
number_of_separators++;
}
fort_cell_t *cell = create_cell();
if (cell == NULL)
goto clear;
int status = fill_cell_from_string_(cell, base_pos);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
status = vector_push(row->cells, &cell);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
if (pos == NULL)
break;
base_pos = pos;
}
/* special case if in format string last cell is empty */
while (vector_size(row->cells) < (number_of_separators + 1)) {
fort_cell_t *cell = create_cell();
if (cell == NULL)
goto clear;
int status = fill_cell_from_string_(cell, zero_string);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
status = vector_push(row->cells, &cell);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
}
F_FREE(str_copy);
return row;
clear:
destroy_row(row);
F_FREE(str_copy);
return NULL;
#undef STRCHR
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
fort_row_t *create_row_from_wstring(const wchar_t *str)
{
typedef wchar_t char_type;
char_type *(*strdup_)(const char_type * str) = F_WCSDUP;
const char_type zero_char = L'\0';
fort_status_t (*fill_cell_from_string_)(fort_cell_t *cell, const wchar_t *str) = fill_cell_from_wstring;
const char_type *const zero_string = L"";
#define STRCHR wcschr
char_type *pos = NULL;
char_type *base_pos = NULL;
size_t number_of_separators = 0;
fort_row_t *row = create_row();
if (row == NULL)
return NULL;
if (str == NULL)
return row;
char_type *str_copy = strdup_(str);
if (str_copy == NULL)
goto clear;
pos = str_copy;
base_pos = str_copy;
number_of_separators = 0;
while (*pos) {
pos = STRCHR(pos, g_col_separator);
if (pos != NULL) {
*(pos) = zero_char;
++pos;
number_of_separators++;
}
fort_cell_t *cell = create_cell();
if (cell == NULL)
goto clear;
int status = fill_cell_from_string_(cell, base_pos);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
status = vector_push(row->cells, &cell);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
if (pos == NULL)
break;
base_pos = pos;
}
/* special case if in format string last cell is empty */
while (vector_size(row->cells) < (number_of_separators + 1)) {
fort_cell_t *cell = create_cell();
if (cell == NULL)
goto clear;
int status = fill_cell_from_string_(cell, zero_string);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
status = vector_push(row->cells, &cell);
if (FT_IS_ERROR(status)) {
destroy_cell(cell);
goto clear;
}
}
F_FREE(str_copy);
return row;
clear:
destroy_row(row);
F_FREE(str_copy);
return NULL;
#undef STRCHR
}
#endif
FT_INTERNAL
fort_row_t *create_row_from_fmt_string(const char *fmt, va_list *va_args)
{
#define VSNPRINTF vsnprintf
#define STR_FILED cstr
#define CREATE_ROW_FROM_STRING create_row_from_string
#define NUMBER_OF_COLUMNS_IN_FORMAT_STRING number_of_columns_in_format_string
#define FILL_CELL_FROM_STRING fill_cell_from_string
#define STR_BUF_TYPE CharBuf
string_buffer_t *buffer = create_string_buffer(DEFAULT_STR_BUF_SIZE, STR_BUF_TYPE);
if (buffer == NULL)
return NULL;
size_t cols_origin = NUMBER_OF_COLUMNS_IN_FORMAT_STRING(fmt);
size_t cols = 0;
while (1) {
va_list va;
va_copy(va, *va_args);
int virtual_sz = VSNPRINTF(buffer->str.STR_FILED, string_buffer_capacity(buffer), fmt, va);
va_end(va);
/* If error encountered */
if (virtual_sz < 0)
goto clear;
/* Successful write */
if ((size_t)virtual_sz < string_buffer_capacity(buffer))
break;
/* Otherwise buffer was too small, so incr. buffer size ant try again. */
if (!FT_IS_SUCCESS(realloc_string_buffer_without_copy(buffer)))
goto clear;
}
cols = NUMBER_OF_COLUMNS_IN_FORMAT_STRING(buffer->str.STR_FILED);
if (cols == cols_origin) {
fort_row_t *row = CREATE_ROW_FROM_STRING(buffer->str.STR_FILED);
if (row == NULL) {
goto clear;
}
destroy_string_buffer(buffer);
return row;
}
if (cols_origin == 1) {
fort_row_t *row = create_row();
if (row == NULL) {
goto clear;
}
fort_cell_t *cell = get_cell_and_create_if_not_exists(row, 0);
if (cell == NULL) {
destroy_row(row);
goto clear;
}
fort_status_t result = FILL_CELL_FROM_STRING(cell, buffer->str.STR_FILED);
if (FT_IS_ERROR(result)) {
destroy_row(row);
goto clear;
}
destroy_string_buffer(buffer);
return row;
}
/*
* todo: add processing of cols != cols_origin in a general way
* (when cols_origin != 1).
*/
clear:
destroy_string_buffer(buffer);
return NULL;
#undef VSNPRINTF
#undef STR_FILED
#undef CREATE_ROW_FROM_STRING
#undef NUMBER_OF_COLUMNS_IN_FORMAT_STRING
#undef FILL_CELL_FROM_STRING
#undef STR_BUF_TYPE
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
fort_row_t *create_row_from_fmt_wstring(const wchar_t *fmt, va_list *va_args)
{
#define VSNPRINTF vswprintf
#define STR_FILED wstr
#define CREATE_ROW_FROM_STRING create_row_from_wstring
#define NUMBER_OF_COLUMNS_IN_FORMAT_STRING number_of_columns_in_format_wstring
#define FILL_CELL_FROM_STRING fill_cell_from_wstring
#define STR_BUF_TYPE WCharBuf
string_buffer_t *buffer = create_string_buffer(DEFAULT_STR_BUF_SIZE, STR_BUF_TYPE);
if (buffer == NULL)
return NULL;
size_t cols_origin = NUMBER_OF_COLUMNS_IN_FORMAT_STRING(fmt);
size_t cols = 0;
while (1) {
va_list va;
va_copy(va, *va_args);
int virtual_sz = VSNPRINTF(buffer->str.STR_FILED, string_buffer_capacity(buffer), fmt, va);
va_end(va);
/* If error encountered */
if (virtual_sz < 0)
goto clear;
/* Successful write */
if ((size_t)virtual_sz < string_buffer_capacity(buffer))
break;
/* Otherwise buffer was too small, so incr. buffer size ant try again. */
if (!FT_IS_SUCCESS(realloc_string_buffer_without_copy(buffer)))
goto clear;
}
cols = NUMBER_OF_COLUMNS_IN_FORMAT_STRING(buffer->str.STR_FILED);
if (cols == cols_origin) {
fort_row_t *row = CREATE_ROW_FROM_STRING(buffer->str.STR_FILED);
if (row == NULL) {
goto clear;
}
destroy_string_buffer(buffer);
return row;
}
if (cols_origin == 1) {
fort_row_t *row = create_row();
if (row == NULL) {
goto clear;
}
fort_cell_t *cell = get_cell_and_create_if_not_exists(row, 0);
if (cell == NULL) {
destroy_row(row);
goto clear;
}
fort_status_t result = FILL_CELL_FROM_STRING(cell, buffer->str.STR_FILED);
if (FT_IS_ERROR(result)) {
destroy_row(row);
goto clear;
}
destroy_string_buffer(buffer);
return row;
}
/*
* todo: add processing of cols != cols_origin in a general way
* (when cols_origin != 1).
*/
clear:
destroy_string_buffer(buffer);
return NULL;
#undef VSNPRINTF
#undef STR_FILED
#undef CREATE_ROW_FROM_STRING
#undef NUMBER_OF_COLUMNS_IN_FORMAT_STRING
#undef FILL_CELL_FROM_STRING
#undef STR_BUF_TYPE
}
#endif
FT_INTERNAL
int snprintf_row(const fort_row_t *row, char *buffer, size_t buf_sz, size_t *col_width_arr, size_t col_width_arr_sz,
size_t row_height, const context_t *context)
{
int (*snprint_n_strings_)(char *, size_t, size_t, const char *) = snprint_n_strings;
int (*cell_printf_)(fort_cell_t *, size_t, char *, size_t, const context_t *) = cell_printf;
assert(context);
const char *space_char = " ";
const char *new_line_char = "\n";
if (row == NULL)
return -1;
size_t cols_in_row = columns_in_row(row);
if (cols_in_row > col_width_arr_sz)
return -1;
/* Row separator anatomy
*
* L data IV data IV data R
*/
typedef const char *(*border_chars_point_t)[BorderItemPosSize];
enum ft_row_type row_type = (enum ft_row_type)get_cell_property_value_hierarcial(context->table_properties, context->row, FT_ANY_COLUMN, FT_CPROP_ROW_TYPE);
const char *(*bord_chars)[BorderItemPosSize] = (row_type == FT_ROW_HEADER)
? (border_chars_point_t)(&context->table_properties->border_style.header_border_chars)
: (border_chars_point_t)(&context->table_properties->border_style.border_chars);
const char **L = &(*bord_chars)[LL_bip];
const char **IV = &(*bord_chars)[IV_bip];
const char **R = &(*bord_chars)[RR_bip];
size_t written = 0;
int tmp = 0;
size_t i = 0;
for (i = 0; i < row_height; ++i) {
/* Print left margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, context->table_properties->entire_table_properties.left_margin, space_char));
/* Print left table boundary */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, *L));
size_t j = 0;
while (j < col_width_arr_sz) {
if (j < cols_in_row) {
((context_t *)context)->column = j;
fort_cell_t *cell = *(fort_cell_t **)vector_at(row->cells, j);
size_t cell_width = 0;
size_t group_slave_sz = group_cell_number(row, j);
cell_width = col_width_arr[j];
size_t slave_j = 0;
size_t master_j = j;
for (slave_j = master_j + 1; slave_j < (master_j + group_slave_sz); ++slave_j) {
cell_width += col_width_arr[slave_j] + FORT_COL_SEPARATOR_LENGTH;
++j;
}
CHCK_RSLT_ADD_TO_WRITTEN(cell_printf_(cell, i, buffer + written, cell_width + 1, context));
} else {
/* Print empty cell */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, col_width_arr[j], space_char));
}
/* Print boundary between cells */
if (j < col_width_arr_sz - 1)
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, *IV));
++j;
}
/* Print right table boundary */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, *R));
/* Print right margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, context->table_properties->entire_table_properties.right_margin, space_char));
/* Print new line character */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, new_line_char));
}
return (int)written;
clear:
return -1;
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
int wsnprintf_row(const fort_row_t *row, wchar_t *buffer, size_t buf_sz, size_t *col_width_arr, size_t col_width_arr_sz,
size_t row_height, const context_t *context)
{
int (*snprint_n_strings_)(wchar_t *, size_t, size_t, const char *) = wsnprint_n_string;
int (*cell_printf_)(fort_cell_t *, size_t, wchar_t *, size_t, const context_t *) = cell_wprintf;
assert(context);
const char *space_char = " ";
const char *new_line_char = "\n";
if (row == NULL)
return -1;
size_t cols_in_row = columns_in_row(row);
if (cols_in_row > col_width_arr_sz)
return -1;
/* Row separator anatomy
*
* L data IV data IV data R
*/
typedef const char *(*border_chars_point_t)[BorderItemPosSize];
enum ft_row_type row_type = (enum ft_row_type)get_cell_property_value_hierarcial(context->table_properties, context->row, FT_ANY_COLUMN, FT_CPROP_ROW_TYPE);
const char *(*bord_chars)[BorderItemPosSize] = (row_type == FT_ROW_HEADER)
? (border_chars_point_t)(&context->table_properties->border_style.header_border_chars)
: (border_chars_point_t)(&context->table_properties->border_style.border_chars);
const char **L = &(*bord_chars)[LL_bip];
const char **IV = &(*bord_chars)[IV_bip];
const char **R = &(*bord_chars)[RR_bip];
size_t written = 0;
int tmp = 0;
size_t i = 0;
for (i = 0; i < row_height; ++i) {
/* Print left margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, context->table_properties->entire_table_properties.left_margin, space_char));
/* Print left table boundary */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, *L));
size_t j = 0;
while (j < col_width_arr_sz) {
if (j < cols_in_row) {
((context_t *)context)->column = j;
fort_cell_t *cell = *(fort_cell_t **)vector_at(row->cells, j);
size_t cell_width = 0;
size_t group_slave_sz = group_cell_number(row, j);
cell_width = col_width_arr[j];
size_t slave_j = 0;
size_t master_j = j;
for (slave_j = master_j + 1; slave_j < (master_j + group_slave_sz); ++slave_j) {
cell_width += col_width_arr[slave_j] + FORT_COL_SEPARATOR_LENGTH;
++j;
}
CHCK_RSLT_ADD_TO_WRITTEN(cell_printf_(cell, i, buffer + written, cell_width + 1, context));
} else {
/* Print empty cell */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, col_width_arr[j], space_char));
}
/* Print boundary between cells */
if (j < col_width_arr_sz - 1)
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, *IV));
++j;
}
/* Print right table boundary */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, *R));
/* Print right margin */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, context->table_properties->entire_table_properties.right_margin, space_char));
/* Print new line character */
CHCK_RSLT_ADD_TO_WRITTEN(snprint_n_strings_(buffer + written, buf_sz - written, 1, new_line_char));
}
return (int)written;
clear:
return -1;
}
#endif
/********************************************************
End of file "row.c"
********************************************************/
/********************************************************
Begin of file "string_buffer.c"
********************************************************/
/* #include "string_buffer.h" */ /* Commented by amalgamation script */
/* #include "properties.h" */ /* Commented by amalgamation script */
/* #include "wcwidth.h" */ /* Commented by amalgamation script */
#include <assert.h>
#include <stddef.h>
#include <wchar.h>
static ptrdiff_t str_iter_width(const char *beg, const char *end)
{
assert(end >= beg);
return (end - beg);
}
#ifdef FT_HAVE_WCHAR
static ptrdiff_t wcs_iter_width(const wchar_t *beg, const wchar_t *end)
{
assert(end >= beg);
return mk_wcswidth(beg, (size_t)(end - beg));
}
#endif /* FT_HAVE_WCHAR */
static size_t buf_str_len(const string_buffer_t *buf)
{
assert(buf);
if (buf->type == CharBuf) {
return strlen(buf->str.cstr);
} else {
return wcslen(buf->str.wstr);
}
}
FT_INTERNAL
size_t strchr_count(const char *str, char ch)
{
if (str == NULL)
return 0;
size_t count = 0;
str = strchr(str, ch);
while (str) {
count++;
str++;
str = strchr(str, ch);
}
return count;
}
FT_INTERNAL
size_t wstrchr_count(const wchar_t *str, wchar_t ch)
{
if (str == NULL)
return 0;
size_t count = 0;
str = wcschr(str, ch);
while (str) {
count++;
str++;
str = wcschr(str, ch);
}
return count;
}
FT_INTERNAL
const char *str_n_substring_beg(const char *str, char ch_separator, size_t n)
{
if (str == NULL)
return NULL;
if (n == 0)
return str;
str = strchr(str, ch_separator);
--n;
while (n > 0) {
if (str == NULL)
return NULL;
--n;
str++;
str = strchr(str, ch_separator);
}
return str ? (str + 1) : NULL;
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
const wchar_t *wstr_n_substring_beg(const wchar_t *str, wchar_t ch_separator, size_t n)
{
if (str == NULL)
return NULL;
if (n == 0)
return str;
str = wcschr(str, ch_separator);
--n;
while (n > 0) {
if (str == NULL)
return NULL;
--n;
str++;
str = wcschr(str, ch_separator);
}
return str ? (str + 1) : NULL;
}
#endif /* FT_HAVE_WCHAR */
FT_INTERNAL
void str_n_substring(const char *str, char ch_separator, size_t n, const char **begin, const char **end)
{
const char *beg = str_n_substring_beg(str, ch_separator, n);
if (beg == NULL) {
*begin = NULL;
*end = NULL;
return;
}
const char *en = strchr(beg, ch_separator);
if (en == NULL) {
en = str + strlen(str);
}
*begin = beg;
*end = en;
return;
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
void wstr_n_substring(const wchar_t *str, wchar_t ch_separator, size_t n, const wchar_t **begin, const wchar_t **end)
{
const wchar_t *beg = wstr_n_substring_beg(str, ch_separator, n);
if (beg == NULL) {
*begin = NULL;
*end = NULL;
return;
}
const wchar_t *en = wcschr(beg, ch_separator);
if (en == NULL) {
en = str + wcslen(str);
}
*begin = beg;
*end = en;
return;
}
#endif /* FT_HAVE_WCHAR */
FT_INTERNAL
string_buffer_t *create_string_buffer(size_t number_of_chars, enum str_buf_type type)
{
size_t sz = (number_of_chars) * (type == CharBuf ? sizeof(char) : sizeof(wchar_t));
string_buffer_t *result = (string_buffer_t *)F_MALLOC(sizeof(string_buffer_t));
if (result == NULL)
return NULL;
result->str.data = F_MALLOC(sz);
if (result->str.data == NULL) {
F_FREE(result);
return NULL;
}
result->data_sz = sz;
result->type = type;
if (sz && type == CharBuf) {
result->str.cstr[0] = '\0';
#ifdef FT_HAVE_WCHAR
} else if (sz && type == WCharBuf) {
result->str.wstr[0] = L'\0';
#endif /* FT_HAVE_WCHAR */
}
return result;
}
FT_INTERNAL
void destroy_string_buffer(string_buffer_t *buffer)
{
if (buffer == NULL)
return;
F_FREE(buffer->str.data);
buffer->str.data = NULL;
F_FREE(buffer);
}
FT_INTERNAL
string_buffer_t *copy_string_buffer(const string_buffer_t *buffer)
{
assert(buffer);
string_buffer_t *result = create_string_buffer(buffer->data_sz, buffer->type);
if (result == NULL)
return NULL;
switch (buffer->type) {
case CharBuf:
if (FT_IS_ERROR(fill_buffer_from_string(result, buffer->str.cstr))) {
destroy_string_buffer(result);
return NULL;
}
break;
#ifdef FT_HAVE_WCHAR
case WCharBuf:
if (FT_IS_ERROR(fill_buffer_from_wstring(result, buffer->str.wstr))) {
destroy_string_buffer(result);
return NULL;
}
break;
#endif /* FT_HAVE_WCHAR */
default:
destroy_string_buffer(result);
return NULL;
}
return result;
}
FT_INTERNAL
fort_status_t realloc_string_buffer_without_copy(string_buffer_t *buffer)
{
assert(buffer);
char *new_str = (char *)F_MALLOC(buffer->data_sz * 2);
if (new_str == NULL) {
return FT_MEMORY_ERROR;
}
F_FREE(buffer->str.data);
buffer->str.data = new_str;
buffer->data_sz *= 2;
return FT_SUCCESS;
}
FT_INTERNAL
fort_status_t fill_buffer_from_string(string_buffer_t *buffer, const char *str)
{
assert(buffer);
assert(str);
char *copy = F_STRDUP(str);
if (copy == NULL)
return FT_MEMORY_ERROR;
F_FREE(buffer->str.data);
buffer->str.cstr = copy;
buffer->type = CharBuf;
return FT_SUCCESS;
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
fort_status_t fill_buffer_from_wstring(string_buffer_t *buffer, const wchar_t *str)
{
assert(buffer);
assert(str);
wchar_t *copy = F_WCSDUP(str);
if (copy == NULL)
return FT_MEMORY_ERROR;
F_FREE(buffer->str.data);
buffer->str.wstr = copy;
buffer->type = WCharBuf;
return FT_SUCCESS;
}
#endif /* FT_HAVE_WCHAR */
FT_INTERNAL
size_t buffer_text_height(const string_buffer_t *buffer)
{
if (buffer == NULL || buffer->str.data == NULL || buf_str_len(buffer) == 0) {
return 0;
}
if (buffer->type == CharBuf)
return 1 + strchr_count(buffer->str.cstr, '\n');
else
return 1 + wstrchr_count(buffer->str.wstr, L'\n');
}
FT_INTERNAL
size_t buffer_text_width(const string_buffer_t *buffer)
{
size_t max_length = 0;
if (buffer->type == CharBuf) {
size_t n = 0;
while (1) {
const char *beg = NULL;
const char *end = NULL;
str_n_substring(buffer->str.cstr, '\n', n, &beg, &end);
if (beg == NULL || end == NULL)
return max_length;
max_length = MAX(max_length, (size_t)(end - beg));
++n;
}
#ifdef FT_HAVE_WCHAR
} else {
size_t n = 0;
while (1) {
const wchar_t *beg = NULL;
const wchar_t *end = NULL;
wstr_n_substring(buffer->str.wstr, L'\n', n, &beg, &end);
if (beg == NULL || end == NULL)
return max_length;
int line_width = mk_wcswidth(beg, (size_t)(end - beg));
if (line_width < 0) /* For safety */
line_width = 0;
max_length = MAX(max_length, (size_t)line_width);
++n;
}
#endif /* FT_HAVE_WCHAR */
}
return max_length; /* shouldn't be here */
}
FT_INTERNAL
int buffer_printf(string_buffer_t *buffer, size_t buffer_row, char *buf, size_t total_buf_len,
const context_t *context, const char *content_style_tag, const char *reset_content_style_tag)
{
#define CHAR_TYPE char
#define NULL_CHAR '\0'
#define NEWLINE_CHAR '\n'
#define SPACE_CHAR " "
#define SNPRINTF_FMT_STR "%*s"
#define SNPRINTF snprintf
#define BUFFER_STR str.cstr
#define SNPRINT_N_STRINGS snprint_n_strings
#define STR_N_SUBSTRING str_n_substring
#define STR_ITER_WIDTH str_iter_width
size_t buf_len = total_buf_len - strlen(content_style_tag) - strlen(reset_content_style_tag);
if (buffer == NULL || buffer->str.data == NULL
|| buffer_row >= buffer_text_height(buffer) || buf_len == 0) {
return -1;
}
size_t content_width = buffer_text_width(buffer);
if ((buf_len - 1) < content_width)
return -1;
size_t left = 0;
size_t right = 0;
switch (get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_TEXT_ALIGN)) {
case FT_ALIGNED_LEFT:
left = 0;
right = (buf_len - 1) - content_width;
break;
case FT_ALIGNED_CENTER:
left = ((buf_len - 1) - content_width) / 2;
right = ((buf_len - 1) - content_width) - left;
break;
case FT_ALIGNED_RIGHT:
left = (buf_len - 1) - content_width;
right = 0;
break;
default:
assert(0);
break;
}
int set_old_value = 0;
size_t written = 0;
int tmp = 0;
ptrdiff_t str_it_width = 0;
const CHAR_TYPE *beg = NULL;
const CHAR_TYPE *end = NULL;
CHAR_TYPE old_value = (CHAR_TYPE)0;
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, left, SPACE_CHAR));
STR_N_SUBSTRING(buffer->BUFFER_STR, NEWLINE_CHAR, buffer_row, &beg, &end);
if (beg == NULL || end == NULL)
return -1;
old_value = *end;
*(CHAR_TYPE *)end = NULL_CHAR;
set_old_value = 1;
str_it_width = STR_ITER_WIDTH(beg, end);
if (str_it_width < 0 || content_width < (size_t)str_it_width)
goto clear;
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, 1, content_style_tag));
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINTF(buf + written, total_buf_len - written, SNPRINTF_FMT_STR, (int)(end - beg), beg));
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, 1, reset_content_style_tag));
*(CHAR_TYPE *)end = old_value;
set_old_value = 0;
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, (content_width - (size_t)str_it_width), SPACE_CHAR));
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, right, SPACE_CHAR));
return (int)written;
clear:
if (set_old_value)
*(CHAR_TYPE *)end = old_value;
return -1;
#undef CHAR_TYPE
#undef NULL_CHAR
#undef NEWLINE_CHAR
#undef SPACE_CHAR
#undef SNPRINTF_FMT_STR
#undef SNPRINTF
#undef BUFFER_STR
#undef SNPRINT_N_STRINGS
#undef STR_N_SUBSTRING
#undef STR_ITER_WIDTH
}
#ifdef FT_HAVE_WCHAR
FT_INTERNAL
int buffer_wprintf(string_buffer_t *buffer, size_t buffer_row, wchar_t *buf, size_t total_buf_len,
const context_t *context, const char *content_style_tag, const char *reset_content_style_tag)
{
#define CHAR_TYPE wchar_t
#define NULL_CHAR L'\0'
#define NEWLINE_CHAR L'\n'
#define SPACE_CHAR " "
#define SNPRINTF_FMT_STR L"%*ls"
#define SNPRINTF swprintf
#define BUFFER_STR str.wstr
#define SNPRINT_N_STRINGS wsnprint_n_string
#define STR_N_SUBSTRING wstr_n_substring
#define STR_ITER_WIDTH wcs_iter_width
size_t buf_len = total_buf_len - strlen(content_style_tag) - strlen(reset_content_style_tag);
if (buffer == NULL || buffer->str.data == NULL
|| buffer_row >= buffer_text_height(buffer) || buf_len == 0) {
return -1;
}
size_t content_width = buffer_text_width(buffer);
if ((buf_len - 1) < content_width)
return -1;
size_t left = 0;
size_t right = 0;
switch (get_cell_property_value_hierarcial(context->table_properties, context->row, context->column, FT_CPROP_TEXT_ALIGN)) {
case FT_ALIGNED_LEFT:
left = 0;
right = (buf_len - 1) - content_width;
break;
case FT_ALIGNED_CENTER:
left = ((buf_len - 1) - content_width) / 2;
right = ((buf_len - 1) - content_width) - left;
break;
case FT_ALIGNED_RIGHT:
left = (buf_len - 1) - content_width;
right = 0;
break;
default:
assert(0);
break;
}
int set_old_value = 0;
size_t written = 0;
int tmp = 0;
ptrdiff_t str_it_width = 0;
const CHAR_TYPE *beg = NULL;
const CHAR_TYPE *end = NULL;
CHAR_TYPE old_value = (CHAR_TYPE)0;
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, left, SPACE_CHAR));
STR_N_SUBSTRING(buffer->BUFFER_STR, NEWLINE_CHAR, buffer_row, &beg, &end);
if (beg == NULL || end == NULL)
return -1;
old_value = *end;
*(CHAR_TYPE *)end = NULL_CHAR;
set_old_value = 1;
str_it_width = STR_ITER_WIDTH(beg, end);
if (str_it_width < 0 || content_width < (size_t)str_it_width)
goto clear;
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, 1, content_style_tag));
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINTF(buf + written, total_buf_len - written, SNPRINTF_FMT_STR, (int)(end - beg), beg));
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, 1, reset_content_style_tag));
*(CHAR_TYPE *)end = old_value;
set_old_value = 0;
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, (content_width - (size_t)str_it_width), SPACE_CHAR));
CHCK_RSLT_ADD_TO_WRITTEN(SNPRINT_N_STRINGS(buf + written, total_buf_len - written, right, SPACE_CHAR));
return (int)written;
clear:
if (set_old_value)
*(CHAR_TYPE *)end = old_value;
return -1;
#undef CHAR_TYPE
#undef NULL_CHAR
#undef NEWLINE_CHAR
#undef SPACE_CHAR
#undef SNPRINTF_FMT_STR
#undef SNPRINTF
#undef BUFFER_STR
#undef SNPRINT_N_STRINGS
#undef STR_N_SUBSTRING
#undef STR_ITER_WIDTH
}
#endif /* FT_HAVE_WCHAR */
FT_INTERNAL
size_t string_buffer_capacity(const string_buffer_t *buffer)
{
assert(buffer);
if (buffer->type == CharBuf)
return buffer->data_sz;
else
return buffer->data_sz / sizeof(wchar_t);
}
FT_INTERNAL
void *buffer_get_data(string_buffer_t *buffer)
{
assert(buffer);
return buffer->str.data;
}
/********************************************************
End of file "string_buffer.c"
********************************************************/
/********************************************************
Begin of file "table.c"
********************************************************/
/* #include "table.h" */ /* Commented by amalgamation script */
/* #include "string_buffer.h" */ /* Commented by amalgamation script */
/* #include "cell.h" */ /* Commented by amalgamation script */
/* #include "vector.h" */ /* Commented by amalgamation script */
/* #include "row.h" */ /* Commented by amalgamation script */
FT_INTERNAL
separator_t *create_separator(int enabled)
{
separator_t *res = (separator_t *)F_CALLOC(1, sizeof(separator_t));
if (res == NULL)
return NULL;
res->enabled = enabled;
return res;
}
FT_INTERNAL
void destroy_separator(separator_t *sep)
{
F_FREE(sep);
}
FT_INTERNAL
separator_t *copy_separator(separator_t *sep)
{
assert(sep);
return create_separator(sep->enabled);
}
static
fort_row_t *get_row_implementation(ft_table_t *table, size_t row, enum PolicyOnNull policy)
{
if (table == NULL || table->rows == NULL) {
return NULL;
}
switch (policy) {
case DoNotCreate:
if (row < vector_size(table->rows)) {
return *(fort_row_t **)vector_at(table->rows, row);
}
return NULL;
case Create:
while (row >= vector_size(table->rows)) {
fort_row_t *new_row = create_row();
if (new_row == NULL)
return NULL;
if (FT_IS_ERROR(vector_push(table->rows, &new_row))) {
destroy_row(new_row);
return NULL;
}
}
return *(fort_row_t **)vector_at(table->rows, row);
}
assert(0 && "Shouldn't be here!");
return NULL;
}
FT_INTERNAL
fort_row_t *get_row(ft_table_t *table, size_t row)
{
return get_row_implementation(table, row, DoNotCreate);
}
FT_INTERNAL
const fort_row_t *get_row_c(const ft_table_t *table, size_t row)
{
return get_row((ft_table_t *)table, row);
}
FT_INTERNAL
fort_row_t *get_row_and_create_if_not_exists(ft_table_t *table, size_t row)
{
return get_row_implementation(table, row, Create);
}
FT_INTERNAL
string_buffer_t *get_cur_str_buffer_and_create_if_not_exists(ft_table_t *table)
{
assert(table);
fort_row_t *row = get_row_and_create_if_not_exists(table, table->cur_row);
if (row == NULL)
return NULL;
fort_cell_t *cell = get_cell_and_create_if_not_exists(row, table->cur_col);
if (cell == NULL)
return NULL;
return cell_get_string_buffer(cell);
}
/*
* Returns number of cells (rows * cols)
*/
FT_INTERNAL
fort_status_t get_table_sizes(const ft_table_t *table, size_t *rows, size_t *cols)
{
*rows = 0;
*cols = 0;
if (table && table->rows) {
*rows = vector_size(table->rows);
/*
fort_row_t *row = NULL;
FOR_EACH(fort_row_t *, row, table->rows) {
(void)i0;
size_t cols_in_row = columns_in_row(row);
if (cols_in_row > *cols)
*cols = cols_in_row;
}
*/
size_t row_index = 0;
for (row_index = 0; row_index < vector_size(table->rows); ++row_index) {
fort_row_t *row = *(fort_row_t **)vector_at(table->rows, row_index);
size_t cols_in_row = columns_in_row(row);
if (cols_in_row > *cols)
*cols = cols_in_row;
}
}
return FT_SUCCESS;
}
FT_INTERNAL
fort_status_t table_rows_and_cols_geometry(const ft_table_t *table,
size_t **col_width_arr_p, size_t *col_width_arr_sz,
size_t **row_height_arr_p, size_t *row_height_arr_sz,
enum request_geom_type geom)
{
if (table == NULL) {
return FT_ERROR;
}
size_t cols = 0;
size_t rows = 0;
int status = get_table_sizes(table, &rows, &cols);
if (FT_IS_ERROR(status))
return status;
size_t *col_width_arr = (size_t *)F_CALLOC(sizeof(size_t), cols);
size_t *row_height_arr = (size_t *)F_CALLOC(sizeof(size_t), rows);
if (col_width_arr == NULL || row_height_arr == NULL) {
F_FREE(col_width_arr);
F_FREE(row_height_arr);
return FT_ERROR;
}
int combined_cells_found = 0;
context_t context;
context.table_properties = (table->properties ? table->properties : &g_table_properties);
size_t col = 0;
for (col = 0; col < cols; ++col) {
col_width_arr[col] = 0;
size_t row = 0;
for (row = 0; row < rows; ++row) {
const fort_row_t *row_p = get_row_c(table, row);
const fort_cell_t *cell = get_cell_c(row_p, col);
context.column = col;
context.row = row;
if (cell) {
switch (get_cell_type(cell)) {
case CommonCell:
col_width_arr[col] = MAX(col_width_arr[col], hint_width_cell(cell, &context, geom));
break;
case GroupMasterCell:
combined_cells_found = 1;
break;
case GroupSlaveCell:
; /* Do nothing */
break;
}
row_height_arr[row] = MAX(row_height_arr[row], hint_height_cell(cell, &context));
} else {
size_t cell_empty_string_height = get_cell_property_value_hierarcial(context.table_properties, context.row, context.column, FT_CPROP_EMPTY_STR_HEIGHT);
if (cell_empty_string_height) {
size_t cell_top_padding = get_cell_property_value_hierarcial(context.table_properties, context.row, context.column, FT_CPROP_TOP_PADDING);
size_t cell_bottom_padding = get_cell_property_value_hierarcial(context.table_properties, context.row, context.column, FT_CPROP_BOTTOM_PADDING);
row_height_arr[row] = MAX(row_height_arr[row], cell_empty_string_height + cell_top_padding + cell_bottom_padding);
}
}
}
}
if (combined_cells_found) {
for (col = 0; col < cols; ++col) {
size_t row = 0;
for (row = 0; row < rows; ++row) {
const fort_row_t *row_p = get_row_c(table, row);
const fort_cell_t *cell = get_cell_c(row_p, col);
context.column = col;
context.row = row;
if (cell) {
if (get_cell_type(cell) == GroupMasterCell) {
size_t hint_width = hint_width_cell(cell, &context, geom);
size_t slave_col = col + group_cell_number(row_p, col);
size_t cur_adj_col = col;
size_t group_width = col_width_arr[col];
size_t i;
for (i = col + 1; i < slave_col; ++i)
group_width += col_width_arr[i] + FORT_COL_SEPARATOR_LENGTH;
/* adjust col. widths */
while (1) {
if (group_width >= hint_width)
break;
col_width_arr[cur_adj_col] += 1;
group_width++;
cur_adj_col++;
if (cur_adj_col == slave_col)
cur_adj_col = col;
}
}
}
}
}
}
/* todo: Maybe it is better to move min width checking to a particular cell width checking.
* At the moment min width includes paddings. Maybe it is better that min width weren't include
* paddings but be min width of the cell content without padding
*/
/*
if (table->properties) {
for (size_t i = 0; i < cols; ++i) {
col_width_arr[i] = MAX((int)col_width_arr[i], fort_props_column_width(table->properties, i));
}
}
*/
*col_width_arr_p = col_width_arr;
*col_width_arr_sz = cols;
*row_height_arr_p = row_height_arr;
*row_height_arr_sz = rows;
return FT_SUCCESS;
}
/*
* Returns geometry in characters
*/
FT_INTERNAL
fort_status_t table_geometry(const ft_table_t *table, size_t *height, size_t *width)
{
if (table == NULL)
return FT_ERROR;
*height = 0;
*width = 0;
size_t cols = 0;
size_t rows = 0;
size_t *col_width_arr = NULL;
size_t *row_height_arr = NULL;
int status = table_rows_and_cols_geometry(table, &col_width_arr, &cols, &row_height_arr, &rows, INTERN_REPR_GEOMETRY);
if (FT_IS_ERROR(status))
return status;
*width = 1 + (cols == 0 ? 1 : cols) + 1; /* for boundaries (that take 1 symbol) + newline */
size_t i = 0;
for (i = 0; i < cols; ++i) {
*width += col_width_arr[i];
}
/* todo: add check for non printable horizontal row separators */
*height = 1 + (rows == 0 ? 1 : rows); /* for boundaries (that take 1 symbol) */
for (i = 0; i < rows; ++i) {
*height += row_height_arr[i];
}
F_FREE(col_width_arr);
F_FREE(row_height_arr);
if (table->properties) {
*height += table->properties->entire_table_properties.top_margin;
*height += table->properties->entire_table_properties.bottom_margin;
*width += table->properties->entire_table_properties.left_margin;
*width += table->properties->entire_table_properties.right_margin;
}
/* Take into account that border elements can be more than one byte long */
fort_table_properties_t *table_properties = table->properties ? table->properties : &g_table_properties;
size_t max_border_elem_len = max_border_elem_strlen(table_properties);
*width *= max_border_elem_len;
return FT_SUCCESS;
}
/********************************************************
End of file "table.c"
********************************************************/
/********************************************************
Begin of file "vector.c"
********************************************************/
/* #include "vector.h" */ /* Commented by amalgamation script */
#include <assert.h>
#include <string.h>
struct vector {
size_t m_size;
void *m_data;
size_t m_capacity;
size_t m_item_size;
};
static int vector_reallocate_(vector_t *vector, size_t new_capacity)
{
assert(vector);
assert(new_capacity > vector->m_capacity);
size_t new_size = new_capacity * vector->m_item_size;
vector->m_data = F_REALLOC(vector->m_data, new_size);
if (vector->m_data == NULL)
return -1;
return 0;
}
FT_INTERNAL
vector_t *create_vector(size_t item_size, size_t capacity)
{
vector_t *vector = (vector_t *)F_MALLOC(sizeof(vector_t));
if (vector == NULL) {
SYS_LOG_ERROR("Failed to allocate memory for asock vector");
return NULL;
}
size_t init_size = MAX(item_size * capacity, 1);
vector->m_data = F_MALLOC(init_size);
if (vector->m_data == NULL) {
SYS_LOG_ERROR("Failed to allocate memory for asock vector inern. buffer");
F_FREE(vector);
return NULL;
}
vector->m_size = 0;
vector->m_capacity = capacity;
vector->m_item_size = item_size;
return vector;
}
FT_INTERNAL
void destroy_vector(vector_t *vector)
{
assert(vector);
F_FREE(vector->m_data);
F_FREE(vector);
}
FT_INTERNAL
size_t vector_size(const vector_t *vector)
{
assert(vector);
return vector->m_size;
}
FT_INTERNAL
size_t vector_capacity(const vector_t *vector)
{
assert(vector);
return vector->m_capacity;
}
FT_INTERNAL
int vector_push(vector_t *vector, const void *item)
{
assert(vector);
assert(item);
if (vector->m_size == vector->m_capacity) {
if (vector_reallocate_(vector, vector->m_capacity * 2) == -1)
return FT_ERROR;
vector->m_capacity = vector->m_capacity * 2;
}
size_t offset = vector->m_size * vector->m_item_size;
memcpy((char *)vector->m_data + offset, item, vector->m_item_size);
++(vector->m_size);
return FT_SUCCESS;
}
FT_INTERNAL
const void *vector_at_c(const vector_t *vector, size_t index)
{
if (index >= vector->m_size)
return NULL;
return (char *)vector->m_data + index * vector->m_item_size;
}
FT_INTERNAL
void *vector_at(vector_t *vector, size_t index)
{
if (index >= vector->m_size)
return NULL;
return (char *)vector->m_data + index * vector->m_item_size;
}
FT_INTERNAL
fort_status_t vector_swap(vector_t *cur_vec, vector_t *mv_vec, size_t pos)
{
assert(cur_vec);
assert(mv_vec);
assert(cur_vec != mv_vec);
assert(cur_vec->m_item_size == mv_vec->m_item_size);
size_t cur_sz = vector_size(cur_vec);
size_t mv_sz = vector_size(mv_vec);
if (mv_sz == 0) {
return FT_SUCCESS;
}
size_t min_targ_size = pos + mv_sz;
if (vector_capacity(cur_vec) < min_targ_size) {
if (vector_reallocate_(cur_vec, min_targ_size) == -1)
return FT_ERROR;
cur_vec->m_capacity = min_targ_size;
}
size_t offset = pos * cur_vec->m_item_size;
void *tmp = NULL;
size_t new_mv_sz = 0;
if (cur_sz > pos) {
new_mv_sz = MIN(cur_sz - pos, mv_sz);
tmp = F_MALLOC(cur_vec->m_item_size * new_mv_sz);
if (tmp == NULL) {
return FT_MEMORY_ERROR;
}
}
if (tmp) {
memcpy(tmp,
(char *)cur_vec->m_data + offset,
cur_vec->m_item_size * new_mv_sz);
}
memcpy((char *)cur_vec->m_data + offset,
mv_vec->m_data,
cur_vec->m_item_size * mv_sz);
if (tmp) {
memcpy(mv_vec->m_data,
tmp,
cur_vec->m_item_size * new_mv_sz);
}
cur_vec->m_size = MAX(cur_vec->m_size, min_targ_size);
mv_vec->m_size = new_mv_sz;
F_FREE(tmp);
return FT_SUCCESS;
}
#ifdef FT_TEST_BUILD
vector_t *copy_vector(vector_t *v)
{
if (v == NULL)
return NULL;
vector_t *new_vector = create_vector(v->m_item_size, v->m_capacity);
if (new_vector == NULL)
return NULL;
memcpy(new_vector->m_data, v->m_data, v->m_item_size * v->m_size);
new_vector->m_size = v->m_size ;
new_vector->m_item_size = v->m_item_size ;
return new_vector;
}
size_t vector_index_of(const vector_t *vector, const void *item)
{
assert(vector);
assert(item);
size_t i = 0;
for (i = 0; i < vector->m_size; ++i) {
void *data_pos = (char *)vector->m_data + i * vector->m_item_size;
if (memcmp(data_pos, item, vector->m_item_size) == 0) {
return i;
}
}
return INVALID_VEC_INDEX;
}
int vector_erase(vector_t *vector, size_t index)
{
assert(vector);
if (vector->m_size == 0 || index >= vector->m_size)
return FT_ERROR;
memmove((char *)vector->m_data + vector->m_item_size * index,
(char *)vector->m_data + vector->m_item_size * (index + 1),
(vector->m_size - 1 - index) * vector->m_item_size);
vector->m_size--;
return FT_SUCCESS;
}
void vector_clear(vector_t *vector)
{
vector->m_size = 0;
}
#endif
/********************************************************
End of file "vector.c"
********************************************************/
/********************************************************
Begin of file "wcwidth.c"
********************************************************/
/*
* This is an implementation of wcwidth() and wcswidth() (defined in
* IEEE Std 1002.1-2001) for Unicode.
*
* http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html
* http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html
*
* In fixed-width output devices, Latin characters all occupy a single
* "cell" position of equal width, whereas ideographic CJK characters
* occupy two such cells. Interoperability between terminal-line
* applications and (teletype-style) character terminals using the
* UTF-8 encoding requires agreement on which character should advance
* the cursor by how many cell positions. No established formal
* standards exist at present on which Unicode character shall occupy
* how many cell positions on character terminals. These routines are
* a first attempt of defining such behavior based on simple rules
* applied to data provided by the Unicode Consortium.
*
* For some graphical characters, the Unicode standard explicitly
* defines a character-cell width via the definition of the East Asian
* FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes.
* In all these cases, there is no ambiguity about which width a
* terminal shall use. For characters in the East Asian Ambiguous (A)
* class, the width choice depends purely on a preference of backward
* compatibility with either historic CJK or Western practice.
* Choosing single-width for these characters is easy to justify as
* the appropriate long-term solution, as the CJK practice of
* displaying these characters as double-width comes from historic
* implementation simplicity (8-bit encoded characters were displayed
* single-width and 16-bit ones double-width, even for Greek,
* Cyrillic, etc.) and not any typographic considerations.
*
* Much less clear is the choice of width for the Not East Asian
* (Neutral) class. Existing practice does not dictate a width for any
* of these characters. It would nevertheless make sense
* typographically to allocate two character cells to characters such
* as for instance EM SPACE or VOLUME INTEGRAL, which cannot be
* represented adequately with a single-width glyph. The following
* routines at present merely assign a single-cell width to all
* neutral characters, in the interest of simplicity. This is not
* entirely satisfactory and should be reconsidered before
* establishing a formal standard in this area. At the moment, the
* decision which Not East Asian (Neutral) characters should be
* represented by double-width glyphs cannot yet be answered by
* applying a simple rule from the Unicode database content. Setting
* up a proper standard for the behavior of UTF-8 character terminals
* will require a careful analysis not only of each Unicode character,
* but also of each presentation form, something the author of these
* routines has avoided to do so far.
*
* http://www.unicode.org/unicode/reports/tr11/
*
* Markus Kuhn -- 2007-05-26 (Unicode 5.0)
*
* Permission to use, copy, modify, and distribute this software
* for any purpose and without fee is hereby granted. The author
* disclaims all warranties with regard to this software.
*
* Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
*/
/* #include "wcwidth.h" */ /* Commented by amalgamation script */
#ifdef FT_HAVE_WCHAR
struct interval {
wchar_t first;
wchar_t last;
};
/* auxiliary function for binary search in interval table */
static int bisearch(wchar_t ucs, const struct interval *table, int max)
{
int min = 0;
if (ucs < table[0].first || ucs > table[max].last)
return 0;
while (max >= min) {
int mid = (min + max) / 2;
if (ucs > table[mid].last)
min = mid + 1;
else if (ucs < table[mid].first)
max = mid - 1;
else
return 1;
}
return 0;
}
/* The following two functions define the column width of an ISO 10646
* character as follows:
*
* - The null character (U+0000) has a column width of 0.
*
* - Other C0/C1 control characters and DEL will lead to a return
* value of -1.
*
* - Non-spacing and enclosing combining characters (general
* category code Mn or Me in the Unicode database) have a
* column width of 0.
*
* - SOFT HYPHEN (U+00AD) has a column width of 1.
*
* - Other format characters (general category code Cf in the Unicode
* database) and ZERO WIDTH SPACE (U+200B) have a column width of 0.
*
* - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
* have a column width of 0.
*
* - Spacing characters in the East Asian Wide (W) or East Asian
* Full-width (F) category as defined in Unicode Technical
* Report #11 have a column width of 2.
*
* - All remaining characters (including all printable
* ISO 8859-1 and WGL4 characters, Unicode control characters,
* etc.) have a column width of 1.
*
* This implementation assumes that wchar_t characters are encoded
* in ISO 10646.
*/
static int mk_wcwidth(wchar_t ucs)
{
/* sorted list of non-overlapping intervals of non-spacing characters */
/* generated by "uniset +cat=Me +cat=Mn +cat=Cf -00AD +1160-11FF +200B c" */
static const struct interval combining[] = {
{ 0x0300, 0x036F }, { 0x0483, 0x0486 }, { 0x0488, 0x0489 },
{ 0x0591, 0x05BD }, { 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 },
{ 0x05C4, 0x05C5 }, { 0x05C7, 0x05C7 }, { 0x0600, 0x0603 },
{ 0x0610, 0x0615 }, { 0x064B, 0x065E }, { 0x0670, 0x0670 },
{ 0x06D6, 0x06E4 }, { 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED },
{ 0x070F, 0x070F }, { 0x0711, 0x0711 }, { 0x0730, 0x074A },
{ 0x07A6, 0x07B0 }, { 0x07EB, 0x07F3 }, { 0x0901, 0x0902 },
{ 0x093C, 0x093C }, { 0x0941, 0x0948 }, { 0x094D, 0x094D },
{ 0x0951, 0x0954 }, { 0x0962, 0x0963 }, { 0x0981, 0x0981 },
{ 0x09BC, 0x09BC }, { 0x09C1, 0x09C4 }, { 0x09CD, 0x09CD },
{ 0x09E2, 0x09E3 }, { 0x0A01, 0x0A02 }, { 0x0A3C, 0x0A3C },
{ 0x0A41, 0x0A42 }, { 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D },
{ 0x0A70, 0x0A71 }, { 0x0A81, 0x0A82 }, { 0x0ABC, 0x0ABC },
{ 0x0AC1, 0x0AC5 }, { 0x0AC7, 0x0AC8 }, { 0x0ACD, 0x0ACD },
{ 0x0AE2, 0x0AE3 }, { 0x0B01, 0x0B01 }, { 0x0B3C, 0x0B3C },
{ 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B43 }, { 0x0B4D, 0x0B4D },
{ 0x0B56, 0x0B56 }, { 0x0B82, 0x0B82 }, { 0x0BC0, 0x0BC0 },
{ 0x0BCD, 0x0BCD }, { 0x0C3E, 0x0C40 }, { 0x0C46, 0x0C48 },
{ 0x0C4A, 0x0C4D }, { 0x0C55, 0x0C56 }, { 0x0CBC, 0x0CBC },
{ 0x0CBF, 0x0CBF }, { 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD },
{ 0x0CE2, 0x0CE3 }, { 0x0D41, 0x0D43 }, { 0x0D4D, 0x0D4D },
{ 0x0DCA, 0x0DCA }, { 0x0DD2, 0x0DD4 }, { 0x0DD6, 0x0DD6 },
{ 0x0E31, 0x0E31 }, { 0x0E34, 0x0E3A }, { 0x0E47, 0x0E4E },
{ 0x0EB1, 0x0EB1 }, { 0x0EB4, 0x0EB9 }, { 0x0EBB, 0x0EBC },
{ 0x0EC8, 0x0ECD }, { 0x0F18, 0x0F19 }, { 0x0F35, 0x0F35 },
{ 0x0F37, 0x0F37 }, { 0x0F39, 0x0F39 }, { 0x0F71, 0x0F7E },
{ 0x0F80, 0x0F84 }, { 0x0F86, 0x0F87 }, { 0x0F90, 0x0F97 },
{ 0x0F99, 0x0FBC }, { 0x0FC6, 0x0FC6 }, { 0x102D, 0x1030 },
{ 0x1032, 0x1032 }, { 0x1036, 0x1037 }, { 0x1039, 0x1039 },
{ 0x1058, 0x1059 }, { 0x1160, 0x11FF }, { 0x135F, 0x135F },
{ 0x1712, 0x1714 }, { 0x1732, 0x1734 }, { 0x1752, 0x1753 },
{ 0x1772, 0x1773 }, { 0x17B4, 0x17B5 }, { 0x17B7, 0x17BD },
{ 0x17C6, 0x17C6 }, { 0x17C9, 0x17D3 }, { 0x17DD, 0x17DD },
{ 0x180B, 0x180D }, { 0x18A9, 0x18A9 }, { 0x1920, 0x1922 },
{ 0x1927, 0x1928 }, { 0x1932, 0x1932 }, { 0x1939, 0x193B },
{ 0x1A17, 0x1A18 }, { 0x1B00, 0x1B03 }, { 0x1B34, 0x1B34 },
{ 0x1B36, 0x1B3A }, { 0x1B3C, 0x1B3C }, { 0x1B42, 0x1B42 },
{ 0x1B6B, 0x1B73 }, { 0x1DC0, 0x1DCA }, { 0x1DFE, 0x1DFF },
{ 0x200B, 0x200F }, { 0x202A, 0x202E }, { 0x2060, 0x2063 },
{ 0x206A, 0x206F }, { 0x20D0, 0x20EF }, { 0x302A, 0x302F },
{ 0x3099, 0x309A }, { 0xA806, 0xA806 }, { 0xA80B, 0xA80B },
{ 0xA825, 0xA826 }, { 0xFB1E, 0xFB1E }, { 0xFE00, 0xFE0F },
{ 0xFE20, 0xFE23 }, { 0xFEFF, 0xFEFF }, { 0xFFF9, 0xFFFB },
{ 0x10A01, 0x10A03 }, { 0x10A05, 0x10A06 }, { 0x10A0C, 0x10A0F },
{ 0x10A38, 0x10A3A }, { 0x10A3F, 0x10A3F }, { 0x1D167, 0x1D169 },
{ 0x1D173, 0x1D182 }, { 0x1D185, 0x1D18B }, { 0x1D1AA, 0x1D1AD },
{ 0x1D242, 0x1D244 }, { 0xE0001, 0xE0001 }, { 0xE0020, 0xE007F },
{ 0xE0100, 0xE01EF }
};
/* test for 8-bit control characters */
if (ucs == 0)
return 0;
if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0))
return -1;
/* binary search in table of non-spacing characters */
if (bisearch(ucs, combining,
sizeof(combining) / sizeof(struct interval) - 1))
return 0;
/* if we arrive here, ucs is not a combining or C0/C1 control character */
return 1 +
(ucs >= 0x1100 &&
(ucs <= 0x115f || /* Hangul Jamo init. consonants */
ucs == 0x2329 || ucs == 0x232a ||
(ucs >= 0x2e80 && ucs <= 0xa4cf &&
ucs != 0x303f) || /* CJK ... Yi */
(ucs >= 0xac00 && ucs <= 0xd7a3) || /* Hangul Syllables */
(ucs >= 0xf900 && ucs <= 0xfaff) || /* CJK Compatibility Ideographs */
(ucs >= 0xfe10 && ucs <= 0xfe19) || /* Vertical forms */
(ucs >= 0xfe30 && ucs <= 0xfe6f) || /* CJK Compatibility Forms */
(ucs >= 0xff00 && ucs <= 0xff60) || /* Fullwidth Forms */
(ucs >= 0xffe0 && ucs <= 0xffe6) ||
(ucs >= 0x20000 && ucs <= 0x2fffd) ||
(ucs >= 0x30000 && ucs <= 0x3fffd)));
}
FT_INTERNAL
int mk_wcswidth(const wchar_t *pwcs, size_t n)
{
int width = 0;
for (; *pwcs && n-- > 0; pwcs++) {
int w;
if ((w = mk_wcwidth(*pwcs)) < 0)
return -1;
else
width += w;
}
return width;
}
#endif /* FT_HAVE_WCHAR */
/********************************************************
End of file "wcwidth.c"
********************************************************/
| 30.868394 | 200 | 0.591822 | [
"geometry",
"vector"
] |
c871c3942a97662ab5f307784e859bd75a9c8290 | 2,268 | h | C | libit-0.2.3/include/it/hmmalgo.h | xiao00li/Undergraduate-Dissertation | b2866956bb1af869d888a2c354d9e425dcac6b44 | [
"MIT"
] | 1 | 2021-02-21T20:30:09.000Z | 2021-02-21T20:30:09.000Z | libit-0.2.3/include/it/hmmalgo.h | xiao00li/Undergraduate-Dissertation | b2866956bb1af869d888a2c354d9e425dcac6b44 | [
"MIT"
] | null | null | null | libit-0.2.3/include/it/hmmalgo.h | xiao00li/Undergraduate-Dissertation | b2866956bb1af869d888a2c354d9e425dcac6b44 | [
"MIT"
] | 2 | 2019-05-08T06:32:33.000Z | 2019-08-27T14:01:30.000Z | /*
libit - Library for basic source and channel coding functions
Copyright (C) 2005-2008 Francois Cayre, Vivien Chappelier, Herve Jegou
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Hidden Markov Model related algorithms
Copyright (C) 2005 Herve Jegou
*/
#ifndef __it_hhmalgo_h
#define __it_hhmalgo_h
#include <it/vec.h>
#include <it/mat.h>
#ifndef DUMM_NODE
#define DUMM_NODE (NULL_INDEX)
#endif
/*-----------------------------------------------------------------------------*/
/*! \defgroup hmm Hidden Markov Model */
/* @{ */
/*-----------------------------------------------------------------------------*/
/* The BCJR algorithm. Generic version. */
mat bcjr (mat x, imat next_state, mat next_state_pt,
vec alpha_0, vec beta_end);
/* The Viterbi algorithm. Generic version. */
ivec viterbi (mat x, imat next_state, mat next_state_pt,
vec alpha_0, vec beta_end);
/* The Viterbi algorithm using logprobabilities. Generic version. */
ivec logviterbi (mat logx, imat next_state, mat next_state_logpt,
vec logalpha_0, vec logbeta_end);
/* The viterbi algorithm that exploit side information on states at the decoder */
ivec viterbi_side (mat x, imat next_state, mat next_state_pt,
vec alpha_0, ivec sideinfo_pos, mat sideinfo);
/* The BCJR algorithm with additional side information on states at the decoder. */
mat bcjr_side (mat x, imat next_state, mat next_state_pt,
vec alpha_0, ivec sideinfo_pos, mat sideinfo);
/* @} */
#endif
| 35.4375 | 83 | 0.65388 | [
"model"
] |
c8749b9198d195c0ec01d5a60a58ebaadd5042f9 | 8,980 | c | C | c_src/utils.c | wandsdn/ofequivalence | bbf233a7cdbe0b86d896082fff58088957d063e6 | [
"Apache-2.0"
] | 4 | 2019-04-04T21:06:11.000Z | 2021-07-10T16:45:43.000Z | c_src/utils.c | wandsdn/ofequivalence | bbf233a7cdbe0b86d896082fff58088957d063e6 | [
"Apache-2.0"
] | null | null | null | c_src/utils.c | wandsdn/ofequivalence | bbf233a7cdbe0b86d896082fff58088957d063e6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Richard Sanger, Wand Network Research Group
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Python.h>
#include <longintrepr.h>
#include <longobject.h>
#include <stdio.h>
#include <x86intrin.h>
#define MODULE_NAME _utils
#define _STRINGIZE(a) #a
#define STRINGIZE(a) _STRINGIZE(a)
#define MODULE_NAME_S STRINGIZE(MODULE_NAME)
#ifndef Py_UNUSED /* This is already defined for Python 3.4 onwards */
#ifdef __GNUC__
#define Py_UNUSED(name) _unused_##name __attribute__((unused))
#else
#define Py_UNUSED(name) _unused_##name
#endif
#endif
#if PyLong_SHIFT % 2 != 0
#error "This code assumes PyLong_SHIFT is even (likely = 30), but it is " PyLong_SHIFT
#endif
#define PyLong_NumBits(num) _PyLong_NumBits((PyObject *)num)
/*
* Casts a Python object to an PyLong
* Returns a new reference which should be freed, this
* may point to the original object if already a PyLong.
*/
static PyLongObject *num_to_py_long(PyObject *num) {
PyLongObject *lnum = NULL;
if (PyLong_Check(num)) {
Py_INCREF(num);
lnum = (PyLongObject *)num;
} else {
PyObject *args;
if (!(args = Py_BuildValue("(O)", num))) {
return NULL;
}
lnum = (PyLongObject *)PyObject_CallObject((PyObject *)&PyLong_Type, args);
Py_DECREF(args);
}
return lnum;
}
static PyObject *morton_number_pdep32(PyObject *Py_UNUSED(self),
PyObject *args) {
PyObject *a = NULL, *b = NULL;
PyLongObject *la = NULL, *lb = NULL;
if (!PyArg_ParseTuple(args, "OO", &a, &b))
return NULL;
la = num_to_py_long(a);
if (!(lb = num_to_py_long(b))) {
Py_DECREF(la);
return NULL;
}
int a_bits = PyLong_NumBits(la);
int b_bits = PyLong_NumBits(lb);
int bits_to_read = a_bits > b_bits ? a_bits : b_bits;
int words = (bits_to_read / 16) + 1;
uint16_t a_b[words];
uint16_t b_b[words];
uint32_t r_b[words];
if (_PyLong_AsByteArray(la, (unsigned char *)a_b, sizeof(a_b), 1, 0) != 0) {
Py_DECREF(la);
Py_DECREF(lb);
return NULL;
}
if (_PyLong_AsByteArray(lb, (unsigned char *)b_b, sizeof(b_b), 1, 0) != 0) {
Py_DECREF(la);
Py_DECREF(lb);
return NULL;
}
for (int i = 0; i < words; i++) {
r_b[i] = _pdep_u32((uint32_t)a_b[i], 0x55555555);
r_b[i] |= _pdep_u32((uint32_t)b_b[i], 0xAAAAAAAA);
}
PyObject *res =
_PyLong_FromByteArray((unsigned char *)r_b, sizeof(r_b), 1, 0);
Py_DECREF(la);
Py_DECREF(lb);
return res;
}
static PyObject *morton_number_pdep64(PyObject *Py_UNUSED(self),
PyObject *args) {
PyObject *a = NULL, *b = NULL;
PyLongObject *la = NULL, *lb = NULL;
if (!PyArg_ParseTuple(args, "OO", &a, &b))
return NULL;
la = num_to_py_long(a);
if (!(lb = num_to_py_long(b))) {
Py_DECREF(la);
return NULL;
}
int a_bits = PyLong_NumBits(la);
int b_bits = PyLong_NumBits(lb);
int bits_to_read = a_bits > b_bits ? a_bits : b_bits;
int words = (bits_to_read / 32) + 1;
uint32_t a_b[words];
uint32_t b_b[words];
uint64_t r_b[words];
if (_PyLong_AsByteArray(la, (unsigned char *)a_b, sizeof(a_b), 1, 0) != 0) {
Py_DECREF(la);
Py_DECREF(lb);
return NULL;
}
if (_PyLong_AsByteArray(lb, (unsigned char *)b_b, sizeof(b_b), 1, 0) != 0) {
Py_DECREF(la);
Py_DECREF(lb);
return NULL;
}
for (int i = 0; i < words; i++) {
r_b[i] = _pdep_u64((uint64_t)a_b[i], 0x5555555555555555);
r_b[i] |= _pdep_u64((uint64_t)b_b[i], 0xAAAAAAAAAAAAAAAA);
}
Py_DECREF(la);
Py_DECREF(lb);
PyObject *res =
_PyLong_FromByteArray((unsigned char *)r_b, sizeof(r_b), 1, 0);
return res;
}
static const uint16_t MortonTable256[] = {
0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015, 0x0040,
0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055, 0x0100, 0x0101,
0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115, 0x0140, 0x0141, 0x0144,
0x0145, 0x0150, 0x0151, 0x0154, 0x0155, 0x0400, 0x0401, 0x0404, 0x0405,
0x0410, 0x0411, 0x0414, 0x0415, 0x0440, 0x0441, 0x0444, 0x0445, 0x0450,
0x0451, 0x0454, 0x0455, 0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511,
0x0514, 0x0515, 0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554,
0x0555, 0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015,
0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055, 0x1100,
0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115, 0x1140, 0x1141,
0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155, 0x1400, 0x1401, 0x1404,
0x1405, 0x1410, 0x1411, 0x1414, 0x1415, 0x1440, 0x1441, 0x1444, 0x1445,
0x1450, 0x1451, 0x1454, 0x1455, 0x1500, 0x1501, 0x1504, 0x1505, 0x1510,
0x1511, 0x1514, 0x1515, 0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551,
0x1554, 0x1555, 0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014,
0x4015, 0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055,
0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115, 0x4140,
0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155, 0x4400, 0x4401,
0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415, 0x4440, 0x4441, 0x4444,
0x4445, 0x4450, 0x4451, 0x4454, 0x4455, 0x4500, 0x4501, 0x4504, 0x4505,
0x4510, 0x4511, 0x4514, 0x4515, 0x4540, 0x4541, 0x4544, 0x4545, 0x4550,
0x4551, 0x4554, 0x4555, 0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011,
0x5014, 0x5015, 0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054,
0x5055, 0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115,
0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155, 0x5400,
0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415, 0x5440, 0x5441,
0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455, 0x5500, 0x5501, 0x5504,
0x5505, 0x5510, 0x5511, 0x5514, 0x5515, 0x5540, 0x5541, 0x5544, 0x5545,
0x5550, 0x5551, 0x5554, 0x5555};
static PyObject *morton_number_lut(PyObject *Py_UNUSED(self), PyObject *args) {
PyObject *a = NULL, *b = NULL;
PyLongObject *la = NULL, *lb = NULL;
if (!PyArg_ParseTuple(args, "OO", &a, &b))
return NULL;
la = num_to_py_long(a);
if (!(lb = num_to_py_long(b))) {
Py_DECREF(la);
return NULL;
}
int a_bits = PyLong_NumBits(la);
int b_bits = PyLong_NumBits(lb);
int bits_to_read = a_bits > b_bits ? a_bits : b_bits;
int words = (bits_to_read / 8) + 1;
uint8_t a_b[words];
uint8_t b_b[words];
uint16_t r_b[words];
if (_PyLong_AsByteArray(la, (unsigned char *)a_b, sizeof(a_b), 1, 0) != 0) {
Py_DECREF(la);
Py_DECREF(lb);
return NULL;
}
if (_PyLong_AsByteArray(lb, (unsigned char *)b_b, sizeof(b_b), 1, 0) != 0) {
Py_DECREF(la);
Py_DECREF(lb);
return NULL;
}
for (int i = 0; i < words; i++) {
r_b[i] =
(MortonTable256[b_b[i] & 0xFF] << 1) | MortonTable256[a_b[i] & 0xFF];
}
Py_DECREF(la);
Py_DECREF(lb);
PyObject *res =
_PyLong_FromByteArray((unsigned char *)r_b, sizeof(r_b), 1, 0);
return res;
}
static PyMethodDef utilMethods[] = {
{"morton_number", morton_number_pdep64, METH_VARARGS,
"Interleave two long integers into a morton number, using the fastest "
"method avaliable"},
{"morton_number_pdep32", morton_number_pdep32, METH_VARARGS,
"Interleave two long integers into a morton number, using the pdep32 "
"instruction"},
{"morton_number_pdep64", morton_number_pdep64, METH_VARARGS,
"Interleave two long integers into a morton number, using the pdep64 "
"instruction"},
{"morton_number_lut", morton_number_lut, METH_VARARGS,
"Interleave two long integers into a morton number, using a lookup table"},
{}};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
MODULE_NAME_S,
NULL,
-1, // Per module state
utilMethods,
// NULL,
// myextension_traverse,
// myextension_clear,
// NULL
};
#endif
#define G_HELPER(x, y) x##y
#define GLUE(x, y) G_HELPER(x, y)
static PyObject *moduleinit(void) {
PyObject *m;
if (!__builtin_cpu_supports("bmi2")) {
// Make sure the default doesn't use a missing instruction
utilMethods[0].ml_meth = morton_number_lut;
}
/* Init the global methods */
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule(MODULE_NAME_S, utilMethods);
#endif
return m;
}
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC GLUE(PyInit_, MODULE_NAME)(void) { return moduleinit(); }
#else
PyMODINIT_FUNC GLUE(init, MODULE_NAME)(void) { moduleinit(); }
#endif
| 33.136531 | 86 | 0.673831 | [
"object"
] |
c87781c696e6c343af4e39f2965c78e4e700e25f | 1,325 | h | C | src/vocabulary-rocksdb/src/native/vocabulary/PersistentVocabulary.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | src/vocabulary-rocksdb/src/native/vocabulary/PersistentVocabulary.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | src/vocabulary-rocksdb/src/native/vocabulary/PersistentVocabulary.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | //
// Created by Davide Caroselli on 17/08/16.
//
#ifndef MMTCORE_PERSISTENTVOCABULARY_H
#define MMTCORE_PERSISTENTVOCABULARY_H
#include <mmt/vocabulary/Vocabulary.h>
#include <string>
#include <rocksdb/db.h>
#include <unordered_set>
#include "IdGenerator.h"
using namespace std;
namespace mmt {
namespace vocabulary {
class PersistentVocabulary : public Vocabulary {
public:
PersistentVocabulary(string path, bool prepareForBulkLoad = false);
virtual ~PersistentVocabulary() override;
virtual wid_t Lookup(const string &word, bool putIfAbsent) override;
virtual void
Lookup(const vector<vector<string>> &buffer, vector<vector<wid_t>> *output, bool putIfAbsent) override;
virtual const bool ReverseLookup(wid_t id, string *output) override;
virtual const bool ReverseLookup(const vector<vector<wid_t>> &buffer, vector<vector<string>> &output) override;
void Put(const string &word, const wid_t id);
void ForceCompaction();
void ResetId(wid_t id);
private:
string idGeneratorPath;
IdGenerator idGenerator;
rocksdb::DB* directDb;
rocksdb::DB* reverseDb;
};
}
}
#endif //MMTCORE_PERSISTENTVOCABULARY_H
| 25.480769 | 123 | 0.660377 | [
"vector"
] |
c87fbfa0c426805561993a066beb54044e284892 | 10,816 | h | C | include/csys/autocomplete.h | alisenai/imgui-console | 7840945b5a20ea9f4e83f98d1ad3d9379aede3ed | [
"MIT"
] | 11 | 2020-07-09T06:57:44.000Z | 2022-02-13T04:56:55.000Z | include/csys/autocomplete.h | alisenai/imgui-console | 7840945b5a20ea9f4e83f98d1ad3d9379aede3ed | [
"MIT"
] | 1 | 2021-03-06T09:54:57.000Z | 2021-03-06T09:54:57.000Z | include/csys/autocomplete.h | alisenai/imgui-console | 7840945b5a20ea9f4e83f98d1ad3d9379aede3ed | [
"MIT"
] | 3 | 2021-09-13T05:57:09.000Z | 2022-02-26T05:05:41.000Z | // Copyright (c) 2020-present, Roland Munguia & Tristan Florian Bouchard.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#ifndef CSYS_AUTOCOMPLETE_H
#define CSYS_AUTOCOMPLETE_H
#pragma once
#include "csys/api.h"
#include <vector>
#include <string>
#include <memory>
namespace csys
{
// TODO: Check how to add support for UTF Encoding.
// TODO: Todo add max word suggestion depth.
// TODO: Only use "const char *" or "std::string" in csys. (On stl containers use iterators - SLOW). (Need to add std::string version)
//!< Auto complete ternary search tree.
class CSYS_API AutoComplete
{
public:
// Type definitions.
using r_sVector = std::vector<std::string> &;
using sVector = std::vector<std::string>;
//!< Autocomplete node.
struct ACNode
{
explicit ACNode(const char data, bool isWord = false) : m_Data(data), m_IsWord(isWord), m_Less(nullptr), m_Equal(nullptr), m_Greater(nullptr)
{};
explicit ACNode(const char &&data, bool isWord = false) : m_Data(data), m_IsWord(isWord), m_Less(nullptr), m_Equal(nullptr), m_Greater(nullptr)
{};
~ACNode()
{
delete m_Less;
delete m_Equal;
delete m_Greater;
};
char m_Data; //!< Node data.
bool m_IsWord; //!< Flag to determine if node is the end of a word.
ACNode *m_Less; //!< Left pointer.
ACNode *m_Equal; //!< Middle pointer.
ACNode *m_Greater; //!< Right pointer.
};
/*!
* \brief Default Constructor
*/
AutoComplete() = default;
/*!
* \brief
* Copy constructor
* \param tree
* Tree to be copied
*/
AutoComplete(const AutoComplete &tree);
/*!
* \brief
* Move constructor
* \param rhs
* Tree to be copied
*/
AutoComplete(AutoComplete &&rhs) = default;
/*!
* \brief
* Assignment operator
* \param rhs
* Source tree
* \return
* Self
*/
AutoComplete &operator=(const AutoComplete &rhs);
/*!
* \brief
* Move assignment operator
* \param rhs
* Source tree
* \return
* Self
*/
AutoComplete& operator=(AutoComplete&& rhs) = default;
/*!
*
* \tparam inputType
* String input type
* \param[in] il
* List of string from which TST will be constructed
*/
template<typename inputType>
AutoComplete(std::initializer_list<inputType> il)
{
for (const auto &item : il)
{
Insert(item);
}
}
/*!
*
* \tparam T
* Container type
* \param[in] items
* Arbitrary container of strings
*/
template<typename T>
explicit AutoComplete(const T &items)
{
for (const auto &item : items)
{
Insert(item);
}
}
/*!
* /brief
* Destructor
*/
~AutoComplete();
/*!
* \brief
* Get tree node count
* \return
* Tree node count
*/
[[nodiscard]] size_t Size() const;
/*!
* \brief
* Get tree word count
* \return
* Word count
*/
[[nodiscard]] size_t Count() const;
/*!
* \brief
* Search if the given word is in the tree
* \param[in] word
* Word to search
* \return
* Found word
*/
bool Search(const char *word);
/*!
* \brief
* Insert word into tree
* \param[in] word
* Word to be inserted
*/
void Insert(const char *word);
/*!
* \brief
* Insert word into tree
* \param[in] word
* Word to be inserted
*/
void Insert(const std::string &word);
/*!
* \brief
* Insert word into tree
* \tparam strType
* String type to be inserted
* \param[in] word
* Word to be inserted
*/
template<typename strType>
void Insert(const strType &word)
{
ACNode **ptr = &m_Root;
++m_Count;
while (*word != '\0')
{
// Insert char into tree.
if (*ptr == nullptr)
{
*ptr = new ACNode(*word);
++m_Size;
}
// Traverse tree.
if (*word < (*ptr)->m_Data)
{
ptr = &(*ptr)->m_Less;
}
else if (*word == (*ptr)->m_Data)
{
// String is already in tree, therefore only mark as word.
if (*(word + 1) == '\0')
{
if ((*ptr)->m_IsWord)
--m_Count;
(*ptr)->m_IsWord = true;
}
// Advance.
ptr = &(*ptr)->m_Equal;
++word;
}
else
{
ptr = &(*ptr)->m_Greater;
}
}
}
/*!
* \brief
* Removes a word from the tree if found
* \param[in] word
* String to be removed
*/
void Remove(const std::string &word);
/*!
* \brief
* Retrieve suggestions that match the given prefix
* \tparam strType
* Prefix string type
* \param[in] prefix
* Prefix to use for suggestion lookup
* \param[out] ac_options
* Vector of found suggestions
*/
template<typename strType>
void Suggestions(const strType &prefix, r_sVector ac_options)
{
ACNode *ptr = m_Root;
auto temp = prefix;
// Traverse tree and check if prefix exists.
while (ptr)
{
if (*prefix < ptr->m_Data)
{
ptr = ptr->m_Less;
}
else if (*prefix == ptr->m_Data)
{
// Prefix exists in tree.
if (*(prefix + 1) == '\0')
break;
ptr = ptr->m_Equal;
++prefix;
}
else
{
ptr = ptr->m_Greater;
}
}
// Already a word. (No need to auto complete).
if (ptr && ptr->m_IsWord) return;
// Prefix is not in tree.
if (!ptr) return;
// Retrieve auto complete options.
SuggestionsAux(ptr->m_Equal, ac_options, temp);
}
/*!
* \brief
* Retrieve suggestions that match the given prefix
* \param[in] prefix
* Prefix to use for suggestion lookup
* \param[out] ac_options
* Vector of found suggestions
*/
void Suggestions(const char *prefix, r_sVector ac_options);
/*!
* \brief
* Store suggestions that match prefix in ac_options and return partially completed prefix if possible.
* \param[in] prefix
* Prefix to use for suggestion lookup
* \param[out] ac_options
* Vector of found suggestions
* \return
* Partially completed prefix
*/
std::string Suggestions(const std::string &prefix, r_sVector ac_options);
/*!
* \brief
* Retrieve suggestions that match the given prefix
* \param[in/out] prefix
* Prefix to use for suggestion lookup, will be partially completed if flag partial_complete is on
* \param[out] ac_options
* Vector of found suggestions
* \param[in] partial_complete
* Flag to determine if prefix string will be partially completed
*/
void Suggestions(std::string &prefix, r_sVector ac_options, bool partial_complete);
/*!
* \brief
* Retrieve suggestions that match the given prefix
* \tparam strType
* Prefix string type
* \param[in] prefix
* Prefix to use for suggestion lookup
* \return
* Vector of found suggestions
*/
template<typename strType>
std::unique_ptr<sVector> Suggestions(const strType &prefix)
{
auto temp = std::make_unique<sVector>();
Suggestions(prefix, *temp);
return temp;
}
/*!
* \brief
* Retrieve suggestions that match the given prefix
* \param[in] prefix
* Prefix to use for suggestion lookup
* \return
* Vector of found suggestions
*/
std::unique_ptr<sVector> Suggestions(const char *prefix);
protected:
/*!
* \param[in] root
* Permutation root
* \param[out] ac_options
* Vector of found suggestions
* \param[in] buffer
* Prefix buffer
*/
void SuggestionsAux(ACNode *root, r_sVector ac_options, std::string buffer);
/*!
* \brief
* Remove word auxiliary function
* \param[in] root
* Current node to process
* \param[in] word
* String to look for and remove
* \return
* If node is word
*/
bool RemoveAux(ACNode *root, const char *word);
/*!
* \brief
* Clone acNode and all its children
* \param src
* Node to copy from
* \param dest
* Where new node will be stored
*/
void DeepClone(ACNode *src, ACNode *&dest);
ACNode *m_Root = nullptr; //!< Ternary Search Tree Root node
size_t m_Size = 0; //!< Node count
size_t m_Count = 0; //!< Word count
};
}
#ifdef CSYS_HEADER_ONLY
#include "csys/autocomplete.inl"
#endif
#endif //CSYS_AUTOCOMPLETE_H
| 27.94832 | 155 | 0.459135 | [
"vector"
] |
c881e26af691e62f45db2ba056fc352bea7bf4dd | 2,175 | h | C | include/dogecoin/vector.h | SparrowTek/libdogecoin | ca63b528aff21711063fbbaa75d1607cf44e5cd4 | [
"MIT"
] | 1 | 2022-02-09T01:55:51.000Z | 2022-02-09T01:55:51.000Z | include/dogecoin/vector.h | SparrowTek/libdogecoin | ca63b528aff21711063fbbaa75d1607cf44e5cd4 | [
"MIT"
] | null | null | null | include/dogecoin/vector.h | SparrowTek/libdogecoin | ca63b528aff21711063fbbaa75d1607cf44e5cd4 | [
"MIT"
] | 4 | 2022-02-03T19:02:07.000Z | 2022-02-17T22:57:36.000Z | /*
The MIT License (MIT)
Copyright (c) 2015 Jonas Schnelli
Copyright (c) 2022 bluezr
Copyright (c) 2022 The Dogecoin Foundation
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 __LIBDOGECOIN_VECTOR_H__
#define __LIBDOGECOIN_VECTOR_H__
#include <dogecoin/dogecoin.h>
LIBDOGECOIN_BEGIN_DECL
typedef struct vector {
void** data; /* array of pointers */
size_t len; /* array element count */
size_t alloc; /* allocated array elements */
void (*elem_free_f)(void*);
} vector;
LIBDOGECOIN_API vector* vector_new(size_t res, void (*free_f)(void*));
LIBDOGECOIN_API void vector_free(vector* vec, dogecoin_bool free_array);
LIBDOGECOIN_API dogecoin_bool vector_add(vector* vec, void* data);
LIBDOGECOIN_API dogecoin_bool vector_remove(vector* vec, void* data);
LIBDOGECOIN_API void vector_remove_idx(vector* vec, size_t idx);
LIBDOGECOIN_API void vector_remove_range(vector* vec, size_t idx, size_t len);
LIBDOGECOIN_API dogecoin_bool vector_resize(vector* vec, size_t newsz);
LIBDOGECOIN_API ssize_t vector_find(vector* vec, void* data);
#define vector_idx(vec, idx) ((vec)->data[(idx)])
LIBDOGECOIN_END_DECL
#endif // __LIBDOGECOIN_VECTOR_H__
| 36.25 | 78 | 0.77977 | [
"vector"
] |
c88435aec9033a6c54758d0fc606ca5941bd2c60 | 41,389 | c | C | src/nq/pr_cmds.c | luaman/twilight | b4853f3e0c828a5aaff23e44c17d70410f7781c1 | [
"MIT"
] | 3 | 2018-01-14T10:43:27.000Z | 2020-03-02T08:38:23.000Z | src/nq/pr_cmds.c | luaman/twilight | b4853f3e0c828a5aaff23e44c17d70410f7781c1 | [
"MIT"
] | null | null | null | src/nq/pr_cmds.c | luaman/twilight | b4853f3e0c828a5aaff23e44c17d70410f7781c1 | [
"MIT"
] | null | null | null | /*
$RCSfile$
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to:
Free Software Foundation, Inc.
59 Temple Place - Suite 330
Boston, MA 02111-1307, USA
*/
static const char rcsid[] =
"$Id$";
#include "twiconfig.h"
#include <stdio.h>
#include "quakedef.h"
#include "cmd.h"
#include "cvar.h"
#include "model.h"
#include "host.h"
#include "mathlib.h"
#include "server.h"
#include "strlib.h"
#include "sys.h"
#include "world.h"
// LordHavoc: added this to semi-fix the problem of using many ftos calls in a print
#define STRINGTEMP_BUFFERS 16
#define STRINGTEMP_LENGTH 4096
static char pr_string_temp[STRINGTEMP_BUFFERS][STRINGTEMP_LENGTH];
static int pr_string_tempindex = 0;
static char *PR_GetTempString(void)
{
char *s;
s = pr_string_temp[pr_string_tempindex];
pr_string_tempindex = (pr_string_tempindex + 1) % STRINGTEMP_BUFFERS;
return s;
}
#define RETURN_EDICT(e) (((int *)pr_globals)[OFS_RETURN] = EDICT_TO_PROG(e))
Uint8 checkpvs[MAX_MAP_LEAFS / 8];
#define MAX_CHECK 16
static int c_invis, c_notvis;
#define MSG_BROADCAST 0 // unreliable to all
#define MSG_ONE 1 // reliable to one (msg_entity)
#define MSG_ALL 2 // reliable to all
#define MSG_INIT 3 // write to the init string
static char engine_extensions[] =
"DP_QC_CHANGEPITCH "
"DP_QC_COPYENTITY "
"DP_QC_ETOS "
"DP_QC_FINDCHAIN "
"DP_QC_FINDCHAINFLOAT "
"DP_QC_FINDFLOAT "
// "DP_QC_GETSURFACE "
"DP_QC_MINMAXBOUND "
"DP_QC_RANDOMVEC "
"DP_QC_SINCOSSQRTPOW "
"DP_QC_TRACEBOX "
"DP_QC_TRACETOSS "
"DP_QC_VECTORVECTORS "
"DP_REGISTERCVAR "
"DP_SV_SETCOLOR "
"TW_SV_STEPCONTROLS ";
/*
===============================================================================
BUILT-IN FUNCTIONS
===============================================================================
*/
static char *
PF_VarString (Uint first)
{
Uint i;
static char out[256];
out[0] = 0;
for (i = first; i < pr_argc; i++)
strlcat_s (out, G_STRING ((OFS_PARM0 + i * 3)));
return out;
}
/*
=================
This is a TERMINAL error, which will kill off the entire server.
Dumps self.
error(value)
=================
*/
static void
PF_error (void)
{
char *s;
edict_t *ed;
s = PF_VarString (0);
Com_Printf ("======SERVER ERROR in %s:\n%s\n",
PRVM_GetString (pr_xfunction->s_name), s);
ed = PROG_TO_EDICT (pr_global_struct->self);
ED_Print (ed);
Host_Error ("Program error");
}
/*
=================
Dumps out self, then an error message. The program is aborted and self is
removed, but the level can continue.
objerror(value)
=================
*/
static void
PF_objerror (void)
{
char *s;
edict_t *ed;
s = PF_VarString (0);
Com_Printf ("======OBJECT ERROR in %s:\n%s\n",
PRVM_GetString (pr_xfunction->s_name), s);
ed = PROG_TO_EDICT (pr_global_struct->self);
ED_Print (ed);
ED_Free (ed);
Host_Error ("Program error");
}
/*
==============
Writes new values for v_forward, v_up, and v_right based on angles
makevectors(vector)
==============
*/
static void
PF_makevectors (void)
{
AngleVectors (G_VECTOR (OFS_PARM0), pr_global_struct->v_forward,
pr_global_struct->v_right, pr_global_struct->v_up);
}
/*
* ==============
Writes new values for v_forward, v_up, and v_right based on the given
forward vector
vectorvectors(vector, vector)
==============
*/
static void
PF_vectorvectors (void)
{
VectorNormalize2(G_VECTOR(OFS_PARM0), pr_global_struct->v_forward);
VectorVectors(pr_global_struct->v_forward, pr_global_struct->v_right,
pr_global_struct->v_up);
}
/*
=================
This is the only valid way to move an object without using the physics of the
world (setting velocity and waiting). Directly changing origin will not set
internal links correctly, so clipping would be messed up. This should be
called when an object is spawned, and then only if it is teleported.
setorigin (entity, origin)
=================
*/
static void
PF_setorigin (void)
{
edict_t *e;
float *org;
e = G_EDICT (OFS_PARM0);
org = G_VECTOR (OFS_PARM1);
VectorCopy (org, e->v.origin);
SV_LinkEdict (e, false);
}
static void
SetMinMaxSize (edict_t *e, float *min, float *max)
{
int i;
for (i = 0; i < 3; i++)
if (min[i] > max[i])
PR_RunError ("backwards mins/maxs");
// set derived values
VectorCopy (min, e->v.mins);
VectorCopy (max, e->v.maxs);
VectorSubtract (max, min, e->v.size);
SV_LinkEdict (e, false);
}
/*
=================
the size box is rotated by the current angle
setsize (entity, minvector, maxvector)
=================
*/
static void
PF_setsize (void)
{
edict_t *e;
float *min, *max;
e = G_EDICT (OFS_PARM0);
min = G_VECTOR (OFS_PARM1);
max = G_VECTOR (OFS_PARM2);
SetMinMaxSize (e, min, max);
}
/*
=================
setmodel(entity, model)
=================
*/
static void
PF_setmodel (void)
{
edict_t *e;
char *m;
int i;
e = G_EDICT (OFS_PARM0);
m = G_STRING (OFS_PARM1);
// check to see if model was properly precached
for (i = 0; i < MAX_MODELS && sv.model_precache[i]; i++)
if (!strcmp (sv.model_precache[i], m))
break;
if (!sv.model_precache[i])
PR_RunError ("no precache: %s\n", m);
e->v.model = PRVM_SetEngineString(sv.model_precache[i]);
e->v.modelindex = i; // SV_ModelIndex (m);
if (m[0] == '*' || !strcmp(COM_FileExtension(m), "bsp"))
{
model_t *mod;
if (ccls.state == ca_dedicated)
mod = Mod_ForName (m, FLAG_CRASH);
else
mod = Mod_ForName (m, FLAG_RENDER | FLAG_CRASH);
SetMinMaxSize (e, mod->normalmins, mod->normalmaxs);
VectorSubtract (mod->normalmaxs, mod->normalmins, e->v.size);
SV_LinkEdict (e, false);
}
}
/*
=================
broadcast print to everyone on server
bprint(value)
=================
*/
static void
PF_bprint (void)
{
char *s;
s = PF_VarString (0);
SV_BroadcastPrintf ("%s", s);
}
/*
=================
single print to a specific client
sprint(clientent, value)
=================
*/
static void
PF_sprint (void)
{
char *s;
client_t *client;
Uint32 entnum;
entnum = G_EDICTNUM (OFS_PARM0);
s = PF_VarString (1);
if (entnum < 1 || entnum > svs.maxclients)
{
Com_Printf ("tried to sprint to a non-client\n");
return;
}
client = &svs.clients[entnum - 1];
MSG_WriteChar (&client->message, svc_print);
MSG_WriteString (&client->message, s);
}
/*
=================
single print to a specific client
centerprint(clientent, value)
=================
*/
static void
PF_centerprint (void)
{
char *s;
client_t *client;
Uint32 entnum;
entnum = G_EDICTNUM (OFS_PARM0);
s = PF_VarString (1);
if (entnum < 1 || entnum > svs.maxclients)
{
Com_Printf ("tried to sprint to a non-client\n");
return;
}
client = &svs.clients[entnum - 1];
MSG_WriteChar (&client->message, svc_centerprint);
MSG_WriteString (&client->message, s);
}
/*
=================
vector normalize(vector)
=================
*/
static void
PF_normalize (void)
{
float *value1;
vec3_t newvalue;
float new;
value1 = G_VECTOR (OFS_PARM0);
new = DotProduct(value1,value1);
if (new == 0)
VectorSet (newvalue, 0, 0, 0);
else
{
new = Q_sqrt (new);
new = 1 / new;
newvalue[0] = value1[0] * new;
newvalue[1] = value1[1] * new;
newvalue[2] = value1[2] * new;
}
VectorCopy (newvalue, G_VECTOR (OFS_RETURN));
}
/*
=================
scalar vlen(vector)
=================
*/
static void
PF_vlen (void)
{
float *value1;
float new;
value1 = G_VECTOR (OFS_PARM0);
new = DotProduct(value1,value1);
G_FLOAT (OFS_RETURN) = (new) ? Q_sqrt (new) : 0;
}
/*
=================
float vectoyaw(vector)
=================
*/
static void
PF_vectoyaw (void)
{
float *value1;
float yaw;
value1 = G_VECTOR (OFS_PARM0);
if (value1[1] == 0 && value1[0] == 0)
yaw = 0;
else
{
yaw = Q_atan2 (value1[1], value1[0]) * 180 / M_PI;
if (yaw < 0)
yaw += 360;
}
G_FLOAT (OFS_RETURN) = yaw;
}
/*
=================
vector vectoangles(vector)
=================
*/
static void
PF_vectoangles (void)
{
float *value1 = G_VECTOR (OFS_PARM0);
vec3_t v;
Vector2Angles (value1, v);
G_FLOAT (OFS_RETURN + 0) = v[0];
G_FLOAT (OFS_RETURN + 1) = v[1];
G_FLOAT (OFS_RETURN + 2) = v[2];
}
/*
=================
Returns a number from 0<= num < 1
random()
=================
*/
static void
PF_random (void)
{
float num;
num = (rand () & 0x7fff) / ((float) 0x7fff);
G_FLOAT (OFS_RETURN) = num;
}
/*
=================
particle(origin, color, count)
=================
*/
static void
PF_particle (void)
{
float *org, *dir;
float color;
float count;
org = G_VECTOR (OFS_PARM0);
dir = G_VECTOR (OFS_PARM1);
color = G_FLOAT (OFS_PARM2);
count = G_FLOAT (OFS_PARM3);
SV_StartParticle (org, dir, color, count);
}
static void
PF_ambientsound (void)
{
char *samp;
float *pos;
float vol, attenuation;
int i, soundnum;
pos = G_VECTOR (OFS_PARM0);
samp = G_STRING (OFS_PARM1);
vol = G_FLOAT (OFS_PARM2);
attenuation = G_FLOAT (OFS_PARM3);
// check to see if samp was properly precached
for (soundnum = 0; soundnum < MAX_SOUNDS && sv.sound_precache[soundnum]; soundnum++)
if (!strcmp (sv.sound_precache[soundnum], samp))
break;
if (!sv.sound_precache[soundnum]) {
Com_Printf ("no precache: %s\n", samp);
return;
}
// add an svc_spawnambient command to the level signon packet
MSG_WriteByte (&sv.signon, svc_spawnstaticsound);
for (i = 0; i < 3; i++)
MSG_WriteCoord (&sv.signon, pos[i]);
MSG_WriteByte (&sv.signon, soundnum);
MSG_WriteByte (&sv.signon, vol * 255);
MSG_WriteByte (&sv.signon, attenuation * 64);
}
/*
=================
Each entity can have eight independant sound sources, like voice,
weapon, feet, etc.
Channel 0 is an auto-allocate channel, the others override anything
already running on that entity/channel pair.
An attenuation of 0 will play full volume everywhere in the level.
Larger attenuations will drop off.
=================
*/
static void
PF_sound (void)
{
char *sample;
int channel;
edict_t *entity;
int volume;
float attenuation;
entity = G_EDICT (OFS_PARM0);
channel = G_FLOAT (OFS_PARM1);
sample = G_STRING (OFS_PARM2);
volume = G_FLOAT (OFS_PARM3) * 255;
attenuation = G_FLOAT (OFS_PARM4);
if (volume < 0 || volume > 255)
Sys_Error ("SV_StartSound: volume = %i", volume);
if (attenuation < 0 || attenuation > 4)
Sys_Error ("SV_StartSound: attenuation = %f", attenuation);
if (channel < 0 || channel > 7)
Sys_Error ("SV_StartSound: channel = %i", channel);
SV_StartSound (entity, channel, sample, volume, attenuation);
}
/*
=================
break()
=================
*/
static void
PF_break (void)
{
Com_Printf ("break statement\n");
*(int *) -4 = 0; // dump to debugger
}
/*
=================
Used for use tracing and shot targeting
Traces are blocked by bbox and exact bsp entityes, and also slide box entities
if the tryents flag is set.
traceline (vector1, vector2, tryents)
=================
*/
static void
PF_traceline (void)
{
float *v1, *v2;
trace_t trace;
int nomonsters;
edict_t *ent;
v1 = G_VECTOR (OFS_PARM0);
v2 = G_VECTOR (OFS_PARM1);
nomonsters = G_FLOAT (OFS_PARM2);
ent = G_EDICT (OFS_PARM3);
trace = SV_Move (v1, vec3_origin, vec3_origin, v2, nomonsters, ent);
pr_global_struct->trace_allsolid = trace.allsolid;
pr_global_struct->trace_startsolid = trace.startsolid;
pr_global_struct->trace_fraction = trace.fraction;
pr_global_struct->trace_inwater = trace.inwater;
pr_global_struct->trace_inopen = trace.inopen;
VectorCopy (trace.endpos, pr_global_struct->trace_endpos);
VectorCopy (trace.plane.normal, pr_global_struct->trace_plane_normal);
pr_global_struct->trace_plane_dist = trace.plane.dist;
if (trace.ent)
pr_global_struct->trace_ent = EDICT_TO_PROG (trace.ent);
else
pr_global_struct->trace_ent = EDICT_TO_PROG (sv.edicts);
}
/*
=================
Used for use tracing and shot targeting
Traces are blocked by bbox and exact bsp entityes, and also slide box entities
if the tryents flag is set.
tracebox (vector1, vector mins, vector maxs, vector2, tryents)
=================
*/
static void
PF_tracebox (void)
{
float *v1, *v2, *m1, *m2;
trace_t trace;
int nomonsters;
edict_t *ent;
v1 = G_VECTOR(OFS_PARM0);
m1 = G_VECTOR(OFS_PARM1);
m2 = G_VECTOR(OFS_PARM2);
v2 = G_VECTOR(OFS_PARM3);
nomonsters = G_FLOAT(OFS_PARM4);
ent = G_EDICT(OFS_PARM5);
trace = SV_Move (v1, m1, m2, v2,
nomonsters ? MOVE_NOMONSTERS : MOVE_NORMAL, ent);
pr_global_struct->trace_allsolid = trace.allsolid;
pr_global_struct->trace_startsolid = trace.startsolid;
pr_global_struct->trace_fraction = trace.fraction;
pr_global_struct->trace_inwater = trace.inwater;
pr_global_struct->trace_inopen = trace.inopen;
VectorCopy (trace.endpos, pr_global_struct->trace_endpos);
VectorCopy (trace.plane.normal, pr_global_struct->trace_plane_normal);
pr_global_struct->trace_plane_dist = trace.plane.dist;
if (trace.ent)
pr_global_struct->trace_ent = EDICT_TO_PROG(trace.ent);
else
pr_global_struct->trace_ent = EDICT_TO_PROG(sv.edicts);
}
static void
PF_tracetoss (void)
{
trace_t trace;
edict_t *ent;
edict_t *ignore;
// We don't profile yet...
// pr_xfunction->builtinsprofile += 600;
ent = G_EDICT(OFS_PARM0);
ignore = G_EDICT(OFS_PARM1);
trace = SV_Trace_Toss (ent, ignore);
pr_global_struct->trace_allsolid = trace.allsolid;
pr_global_struct->trace_startsolid = trace.startsolid;
pr_global_struct->trace_fraction = trace.fraction;
pr_global_struct->trace_inwater = trace.inwater;
pr_global_struct->trace_inopen = trace.inopen;
VectorCopy (trace.endpos, pr_global_struct->trace_endpos);
VectorCopy (trace.plane.normal, pr_global_struct->trace_plane_normal);
pr_global_struct->trace_plane_dist = trace.plane.dist;
if (trace.ent)
pr_global_struct->trace_ent = EDICT_TO_PROG(trace.ent);
else
pr_global_struct->trace_ent = EDICT_TO_PROG(sv.edicts);
}
//============================================================================
static int
PF_newcheckclient (Uint32 check)
{
Uint32 i;
Uint8 *pvs;
edict_t *ent;
mleaf_t *leaf;
vec3_t org;
// cycle to the next one
if (check < 1)
check = 1;
if (check > svs.maxclients)
check = svs.maxclients;
if (check == svs.maxclients)
i = 1;
else
i = check + 1;
for (;; i++) {
if (i == svs.maxclients + 1)
i = 1;
ent = EDICT_NUM (i);
if (i == check)
// didn't find anything else
break;
if (ent->free)
continue;
if (ent->v.health <= 0)
continue;
if ((int) ent->v.flags & FL_NOTARGET)
continue;
// anything that is a client, or has a client as an enemy
break;
}
// get the PVS for the entity
VectorAdd (ent->v.origin, ent->v.view_ofs, org);
leaf = Mod_PointInLeaf (org, sv.worldmodel);
pvs = Mod_LeafPVS (leaf, sv.worldmodel);
memcpy (checkpvs, pvs, (sv.worldmodel->brush->numleafs + 7) >> 3);
return i;
}
/*
=================
Returns a client (or object that has a client enemy) that would be a
valid target.
If there are more than one valid options, they are cycled each frame
If (self.origin + self.viewofs) is not in the PVS of the current target,
it is not returned at all.
name checkclient ()
=================
*/
static void
PF_checkclient (void)
{
edict_t *ent, *self;
mleaf_t *leaf;
int l;
vec3_t view;
// find a new check if on a new frame
if (sv.time - sv.lastchecktime >= 0.1)
{
sv.lastcheck = PF_newcheckclient (sv.lastcheck);
sv.lastchecktime = sv.time;
}
// return check if it might be visible
ent = EDICT_NUM (sv.lastcheck);
if (ent->free || ent->v.health <= 0)
{
RETURN_EDICT (sv.edicts);
return;
}
// if current entity can't possibly see the check entity, return 0
self = PROG_TO_EDICT (pr_global_struct->self);
VectorAdd (self->v.origin, self->v.view_ofs, view);
leaf = Mod_PointInLeaf (view, sv.worldmodel);
l = (leaf - sv.worldmodel->brush->leafs) - 1;
if ((l < 0) || !(checkpvs[l >> 3] & (1 << (l & 7))))
{
c_notvis++;
RETURN_EDICT (sv.edicts);
return;
}
// might be able to see it
c_invis++;
RETURN_EDICT (ent);
}
//============================================================================
/*
=================
Sends text over to the client's execution buffer
stuffcmd (clientent, value)
=================
*/
static void
PF_stuffcmd (void)
{
Uint32 entnum;
char *str;
client_t *old;
entnum = G_EDICTNUM (OFS_PARM0);
if (entnum < 1 || entnum > svs.maxclients)
PR_RunError ("Parm 0 not a client");
str = G_STRING (OFS_PARM1);
old = host_client;
host_client = &svs.clients[entnum - 1];
Host_ClientCommands ("%s", str);
host_client = old;
}
/*
=================
Sends text over to the client's execution buffer
localcmd (string)
=================
*/
static void
PF_localcmd (void)
{
char *str;
str = G_STRING (OFS_PARM0);
Cbuf_AddText (str);
}
/*
=================
float cvar (string)
=================
*/
static void
PF_cvar (void)
{
char *str;
cvar_t *var;
str = G_STRING (OFS_PARM0);
var = Cvar_Find (str);
if (!var)
var=Cvar_CreateTemp (str, "0");
G_FLOAT (OFS_RETURN) = var->fvalue;
}
/*
=================
float cvar (string)
=================
*/
static void
PF_cvar_set (void)
{
char *name, *val;
cvar_t *var;
name = G_STRING (OFS_PARM0);
val = G_STRING (OFS_PARM1);
var = Cvar_Find (name);
if (!var)
Cvar_CreateTemp (name, val);
else
Cvar_Set (var, val);
}
/*
=================
Returns a chain of entities that have origins within a spherical area
findradius (origin, radius)
=================
*/
static void
PF_findradius (void)
{
edict_t *ent, *chain;
float rad, *org;
vec3_t eorg;
Uint32 i, j;
chain = (edict_t *) sv.edicts;
org = G_VECTOR (OFS_PARM0);
rad = G_FLOAT (OFS_PARM1);
ent = NEXT_EDICT (sv.edicts);
for (i = 1; i < sv.num_edicts; i++, ent = NEXT_EDICT (ent))
{
if (ent->free)
continue;
if (ent->v.solid == SOLID_NOT)
continue;
for (j = 0; j < 3; j++)
eorg[j] = org[j] - (ent->v.origin[j] + (ent->v.mins[j]
+ ent->v.maxs[j]) * 0.5);
if (DotProduct(eorg,eorg) > rad*rad)
continue;
ent->v.chain = EDICT_TO_PROG (chain);
chain = ent;
}
RETURN_EDICT (chain);
}
static void
PF_dprint (void)
{
Com_DPrintf ("%s", PF_VarString (0));
}
static void
PF_ftos (void)
{
float v;
char *s;
v = G_FLOAT (OFS_PARM0);
s = PR_GetTempString ();
if (v == (int) v)
sprintf (s, "%d", (int) v);
else
sprintf (s, "%5.1f", v);
G_INT (OFS_RETURN) = PRVM_SetEngineString (s);
}
static void
PF_fabs (void)
{
float v;
v = G_FLOAT (OFS_PARM0);
G_FLOAT (OFS_RETURN) = fabs (v);
}
static void
PF_vtos (void)
{
char *s = PR_GetTempString ();
sprintf (s, "'%5.1f %5.1f %5.1f'",
G_VECTOR (OFS_PARM0)[0], G_VECTOR (OFS_PARM0)[1],
G_VECTOR (OFS_PARM0)[2]);
G_INT (OFS_RETURN) = PRVM_SetEngineString (s);
}
static void
PF_etos (void)
{
char *s = PR_GetTempString ();
sprintf (s, "entity %i",
G_EDICTNUM(OFS_PARM0));
G_INT (OFS_RETURN) = PRVM_SetEngineString(s);
}
static void
PF_Spawn (void)
{
edict_t *ed;
ed = ED_Alloc ();
RETURN_EDICT (ed);
}
static void
PF_Remove (void)
{
edict_t *ed;
ed = G_EDICT (OFS_PARM0);
ED_Free (ed);
}
// entity (entity start, .string field, string match) find = #5;
static void
PF_Find (void)
{
Uint32 e;
int f;
char *s, *t;
edict_t *ed;
e = G_EDICTNUM (OFS_PARM0);
f = G_INT (OFS_PARM1);
s = G_STRING (OFS_PARM2);
if (!s)
PR_RunError ("PF_Find: bad search string");
if (!*s)
{
RETURN_EDICT (sv.edicts);
return;
}
for (e++; e < sv.num_edicts; e++)
{
ed = EDICT_NUM (e);
if (ed->free)
continue;
t = E_STRING (ed, f);
if (!t)
continue;
if (!strcmp (t, s))
{
RETURN_EDICT (ed);
return;
}
}
RETURN_EDICT (sv.edicts);
}
static void
PR_CheckEmptyString (char *s)
{
if (s[0] <= ' ')
PR_RunError ("Bad string");
}
static void
PF_precache_file (void)
{
// precache_file is only used to copy files with qcc, it does nothing
G_INT (OFS_RETURN) = G_INT (OFS_PARM0);
}
static void
PF_precache_sound (void)
{
char *s;
int i;
if (sv.state != ss_loading)
PR_RunError
("PF_Precache_*: Precache can only be done in spawn functions");
s = G_STRING (OFS_PARM0);
G_INT (OFS_RETURN) = G_INT (OFS_PARM0);
PR_CheckEmptyString (s);
for (i = 0; i < MAX_SOUNDS; i++)
{
if (!sv.sound_precache[i][0])
{
strlcpy_s(sv.sound_precache[i], s);
return;
}
if (!strcmp (sv.sound_precache[i], s))
return;
}
PR_RunError ("PF_precache_sound: overflow");
}
static void
PF_precache_model (void)
{
char *s;
int i;
if (sv.state != ss_loading)
PR_RunError
("PF_Precache_*: Precache can only be done in spawn functions");
s = G_STRING (OFS_PARM0);
G_INT (OFS_RETURN) = G_INT (OFS_PARM0);
PR_CheckEmptyString (s);
for (i = 1; i < MAX_MODELS; i++)
{
if (!sv.model_precache[i][0])
{
strlcpy_s(sv.model_precache[i], s);
if (ccls.state == ca_dedicated)
sv.models[i] = Mod_ForName (s, FLAG_CRASH);
else
sv.models[i] = Mod_ForName (s, FLAG_RENDER | FLAG_CRASH);
return;
}
if (!strcmp (sv.model_precache[i], s))
return;
}
PR_RunError ("PF_precache_model: overflow");
}
static void
PF_coredump (void)
{
ED_PrintEdicts ();
}
static void
PF_traceon (void)
{
pr_trace = true;
}
static void
PF_traceoff (void)
{
pr_trace = false;
}
static void
PF_eprint (void)
{
ED_PrintNum (G_EDICTNUM (OFS_PARM0));
}
/*
===============
float(float yaw, float dist) walkmove
===============
*/
static void
PF_walkmove (void)
{
edict_t *ent;
float yaw, dist;
vec3_t move;
dfunction_t *oldf;
int oldself;
ent = PROG_TO_EDICT (pr_global_struct->self);
yaw = G_FLOAT (OFS_PARM0);
dist = G_FLOAT (OFS_PARM1);
if (!((int) ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM)))
{
G_FLOAT (OFS_RETURN) = 0;
return;
}
yaw = yaw * M_PI * 2 / 360;
move[0] = Q_cos (yaw) * dist;
move[1] = Q_sin (yaw) * dist;
move[2] = 0;
// save program state, because SV_movestep may call other progs
oldf = pr_xfunction;
oldself = pr_global_struct->self;
G_FLOAT (OFS_RETURN) = SV_movestep (ent, move, true);
// restore program state
pr_xfunction = oldf;
pr_global_struct->self = oldself;
}
/*
===============
void() droptofloor
===============
*/
static void
PF_droptofloor (void)
{
edict_t *ent;
vec3_t end;
trace_t trace;
ent = PROG_TO_EDICT (pr_global_struct->self);
VectorCopy (ent->v.origin, end);
end[2] -= 256;
trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent);
if (trace.fraction == 1 || trace.allsolid)
G_FLOAT (OFS_RETURN) = 0;
else
{
VectorCopy (trace.endpos, ent->v.origin);
SV_LinkEdict (ent, false);
ent->v.flags = (int) ent->v.flags | FL_ONGROUND;
ent->v.groundentity = EDICT_TO_PROG (trace.ent);
G_FLOAT (OFS_RETURN) = 1;
}
}
/*
===============
void(float style, string value) lightstyle
===============
*/
static void
PF_lightstyle (void)
{
int style;
char *val;
client_t *client;
Uint32 j;
style = G_FLOAT (OFS_PARM0);
val = G_STRING (OFS_PARM1);
// change the string in sv
strlcpy_s (sv.lightstyles[style], val);
// send message to all clients on this server
if (sv.state != ss_active)
return;
for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++)
if (client->active || client->spawned)
{
MSG_WriteChar (&client->message, svc_lightstyle);
MSG_WriteChar (&client->message, style);
MSG_WriteString (&client->message, val);
}
}
static void
PF_rint (void)
{
float f;
f = G_FLOAT (OFS_PARM0);
if (f > 0)
G_FLOAT (OFS_RETURN) = (int) (f + 0.5);
else
G_FLOAT (OFS_RETURN) = (int) (f - 0.5);
}
static void
PF_floor (void)
{
G_FLOAT (OFS_RETURN) = floor (G_FLOAT (OFS_PARM0));
}
static void
PF_ceil (void)
{
G_FLOAT (OFS_RETURN) = ceil (G_FLOAT (OFS_PARM0));
}
static void
PF_checkbottom (void)
{
edict_t *ent;
ent = G_EDICT (OFS_PARM0);
G_FLOAT (OFS_RETURN) = SV_CheckBottom (ent);
}
static void
PF_pointcontents (void)
{
float *v;
v = G_VECTOR (OFS_PARM0);
G_FLOAT (OFS_RETURN) = SV_PointContents (v);
}
/*
=============
entity nextent(entity)
=============
*/
static void
PF_nextent (void)
{
Uint32 i;
edict_t *ent;
i = G_EDICTNUM (OFS_PARM0);
while (1)
{
i++;
if (i == sv.num_edicts)
{
RETURN_EDICT (sv.edicts);
return;
}
ent = EDICT_NUM (i);
if (!ent->free)
{
RETURN_EDICT (ent);
return;
}
}
}
/*
=============
Pick a vector for the player to shoot along
vector aim(entity, missilespeed)
=============
*/
static void
PF_aim (void)
{
edict_t *ent, *check, *bestent;
vec3_t start, dir, end, bestdir;
Uint32 i, j;
trace_t tr;
float dist, bestdist, speed;
ent = G_EDICT (OFS_PARM0);
speed = G_FLOAT (OFS_PARM1);
VectorCopy (ent->v.origin, start);
start[2] += 20;
// try sending a trace straight
VectorCopy (pr_global_struct->v_forward, dir);
VectorMA (start, 2048, dir, end);
tr = SV_Move (start, vec3_origin, vec3_origin, end, false, ent);
if (tr.ent && ((edict_t *) tr.ent)->v.takedamage == DAMAGE_AIM
&& (!teamplay->ivalue || ent->v.team <= 0
|| ent->v.team != ((edict_t *) tr.ent)->v.team))
{
VectorCopy (pr_global_struct->v_forward, G_VECTOR (OFS_RETURN));
return;
}
// try all possible entities
VectorCopy (dir, bestdir);
bestdist = sv_aim->fvalue;
bestent = NULL;
check = NEXT_EDICT (sv.edicts);
for (i = 1; i < sv.num_edicts; i++, check = NEXT_EDICT (check))
{
if (check->v.takedamage != DAMAGE_AIM)
continue;
if (check == ent)
continue;
if (teamplay->ivalue && ent->v.team > 0
&& ent->v.team == check->v.team)
// don't aim at teammate
continue;
for (j = 0; j < 3; j++)
end[j] = check->v.origin[j] + 0.5
* (check->v.mins[j] + check->v.maxs[j]);
VectorSubtract (end, start, dir);
VectorNormalizeFast (dir);
dist = DotProduct (dir, pr_global_struct->v_forward);
if (dist < bestdist)
// to far to turn
continue;
tr = SV_Move (start, vec3_origin, vec3_origin, end, false, ent);
if (tr.ent == check)
{
// can shoot at this one
bestdist = dist;
bestent = check;
}
}
if (bestent)
{
VectorSubtract (bestent->v.origin, ent->v.origin, dir);
dist = DotProduct (dir, pr_global_struct->v_forward);
VectorScale (pr_global_struct->v_forward, dist, end);
end[2] = dir[2];
VectorNormalizeFast (end);
VectorCopy (end, G_VECTOR (OFS_RETURN));
}
else
VectorCopy (bestdir, G_VECTOR (OFS_RETURN));
}
/*
==============
This was a major timewaster in progs, so it was converted to C
==============
*/
void
PF_changeyaw (void)
{
edict_t *ent;
float ideal, current, move, speed;
ent = PROG_TO_EDICT (pr_global_struct->self);
current = ANGLEMOD (ent->v.angles[1]);
ideal = ent->v.ideal_yaw;
speed = ent->v.yaw_speed;
if (current == ideal)
return;
move = ideal - current;
if (ideal > current)
{
if (move >= 180)
move = move - 360;
}
else
{
if (move <= -180)
move = move + 360;
}
if (move > 0)
{
if (move > speed)
move = speed;
}
else
{
if (move < -speed)
move = -speed;
}
ent->v.angles[1] = ANGLEMOD (current + move);
}
/*
==============
LordHavoc
==============
*/
static void
PF_changepitch (void)
{
edict_t *ent;
eval_t *val;
float ideal, current, move, speed;
ent = G_EDICT(OFS_PARM0);
current = ANGLEMOD ( ent->v.angles[0] );
if ((val = GETEDICTFIELDVALUE (ent, eval_idealpitch)))
ideal = val->_float;
else
{
PR_RunError ("PF_changepitch: .float idealpitch and .float "
"pitch_speed must be defined to use changepitch");
return;
}
if ((val = GETEDICTFIELDVALUE (ent, eval_pitch_speed)))
speed = val->_float;
else
{
PR_RunError ("PF_changepitch: .float idealpitch and .float "
"pitch_speed must be defined to use changepitch");
return;
}
if (current == ideal)
return;
move = ideal - current;
if (ideal > current)
{
if (move >= 180)
move = move - 360;
}
else
{
if (move <= -180)
move = move + 360;
}
if (move > 0)
{
if (move > speed)
move = speed;
}
else
{
if (move < -speed)
move = -speed;
}
ent->v.angles[0] = ANGLEMOD (current + move);
}
/*
===============================================================================
MESSAGE WRITING
===============================================================================
*/
static sizebuf_t *
WriteDest (void)
{
Uint entnum;
int dest;
edict_t *ent;
dest = G_FLOAT (OFS_PARM0);
switch (dest)
{
case MSG_BROADCAST:
return &sv.datagram;
case MSG_ONE:
ent = PROG_TO_EDICT (pr_global_struct->msg_entity);
entnum = NUM_FOR_EDICT (ent, __FILE__, __LINE__);
if (entnum < 1 || entnum > svs.maxclients)
PR_RunError ("WriteDest: not a client");
return &svs.clients[entnum - 1].message;
case MSG_ALL:
return &sv.reliable_datagram;
case MSG_INIT:
return &sv.signon;
default:
PR_RunError ("WriteDest: bad destination");
break;
}
return NULL;
}
static void
PF_WriteByte (void)
{
MSG_WriteByte (WriteDest (), G_FLOAT (OFS_PARM1));
}
static void
PF_WriteChar (void)
{
MSG_WriteChar (WriteDest (), G_FLOAT (OFS_PARM1));
}
static void
PF_WriteShort (void)
{
MSG_WriteShort (WriteDest (), G_FLOAT (OFS_PARM1));
}
static void
PF_WriteLong (void)
{
MSG_WriteLong (WriteDest (), G_FLOAT (OFS_PARM1));
}
static void
PF_WriteAngle (void)
{
MSG_WriteAngle (WriteDest (), G_FLOAT (OFS_PARM1));
}
static void
PF_WriteCoord (void)
{
MSG_WriteCoord (WriteDest (), G_FLOAT (OFS_PARM1));
}
static void
PF_WriteString (void)
{
MSG_WriteString (WriteDest (), G_STRING (OFS_PARM1));
}
static void
PF_WriteEntity (void)
{
MSG_WriteShort (WriteDest (), G_EDICTNUM (OFS_PARM1));
}
//=============================================================================
static void
PF_makestatic (void)
{
edict_t *ent;
Uint i;
ent = G_EDICT (OFS_PARM0);
MSG_WriteByte (&sv.signon, svc_spawnstatic);
MSG_WriteByte (&sv.signon, SV_ModelIndex (PRVM_GetString (ent->v.model)));
MSG_WriteByte (&sv.signon, ent->v.frame);
MSG_WriteByte (&sv.signon, ent->v.colormap);
MSG_WriteByte (&sv.signon, ent->v.skin);
for (i = 0; i < 3; i++)
{
MSG_WriteCoord (&sv.signon, ent->v.origin[i]);
MSG_WriteAngle (&sv.signon, ent->v.angles[i]);
}
// throw the entity away now
ED_Free (ent);
}
//=============================================================================
static void
PF_setspawnparms (void)
{
edict_t *ent;
Uint i;
client_t *client;
ent = G_EDICT (OFS_PARM0);
i = NUM_FOR_EDICT (ent, __FILE__, __LINE__);
if (i < 1 || i > svs.maxclients)
PR_RunError ("Entity is not a client");
// copy spawn parms out of the client_t
client = svs.clients + (i - 1);
for (i = 0; i < NUM_SPAWN_PARMS; i++)
(&pr_global_struct->parm1)[i] = client->spawn_parms[i];
}
static void
PF_changelevel (void)
{
char *s;
// make sure we don't issue two changelevels
if (svs.changelevel_issued)
return;
svs.changelevel_issued = true;
s = G_STRING (OFS_PARM0);
Cbuf_AddText (va ("changelevel %s\n", s));
}
static void
PF_sin (void)
{
G_FLOAT(OFS_RETURN) = sin(G_FLOAT(OFS_PARM0));
}
static void
PF_cos (void)
{
G_FLOAT(OFS_RETURN) = cos(G_FLOAT(OFS_PARM0));
}
static void
PF_sqrt (void)
{
G_FLOAT(OFS_RETURN) = sqrt(G_FLOAT(OFS_PARM0));
}
static void
PF_randomvec (void)
{
vec3_t temp;
do
{
temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
}
while (DotProduct(temp, temp) >= 1);
VectorCopy (temp, G_VECTOR(OFS_RETURN));
}
static void
PF_registercvar (void)
{
char *name, *value;
name = G_STRING(OFS_PARM0);
value = G_STRING(OFS_PARM1);
G_FLOAT(OFS_RETURN) = 0;
// Do nothing if Cvar already exists
if (Cvar_Find (name))
return;
// Don't create a Cvar which overlaps a command
if (Cmd_Exists (name))
{
Com_Printf ("PF_registercvar: %s is a command\n", name);
return;
}
if (!Cvar_Get (name, value, CVAR_TEMP, NULL))
{
Com_Printf ("PF_registercvar: %s could not be created\n", name);
return;
}
G_FLOAT(OFS_RETURN) = 1;
}
/*
=================
returns the minimum of two or more supplied floats
=================
*/
static void
PF_min (void)
{
Uint i;
float f;
if (pr_argc == 2)
G_FLOAT(OFS_RETURN) = min(G_FLOAT(OFS_PARM0), G_FLOAT(OFS_PARM1));
else if (pr_argc > 2)
{
f = G_FLOAT(OFS_PARM0);
for (i = 1; i < pr_argc; i++)
if (G_FLOAT((OFS_PARM0+i*3)) < f)
f = G_FLOAT((OFS_PARM0+i*3));
G_FLOAT(OFS_RETURN) = f;
}
else
PR_RunError ("min: must supply at least 2 floats\n");
}
/*
=================
returns the maximum of two or more supplied floats
=================
*/
static void
PF_max (void)
{
Uint i;
float f;
if (pr_argc == 2)
G_FLOAT(OFS_RETURN) = max(G_FLOAT(OFS_PARM0), G_FLOAT(OFS_PARM1));
else if (pr_argc >= 3)
{
f = G_FLOAT(OFS_PARM0);
for (i = 1;i < pr_argc;i++)
if (G_FLOAT((OFS_PARM0+i*3)) > f)
f = G_FLOAT((OFS_PARM0+i*3));
G_FLOAT(OFS_RETURN) = f;
}
else
PR_RunError("max: must supply at least 2 floats\n");
}
/*
=================
returns float bounded within a supplied range
=================
*/
static void
PF_bound (void)
{
G_FLOAT(OFS_RETURN) = bound(G_FLOAT(OFS_PARM0), G_FLOAT(OFS_PARM1), G_FLOAT(OFS_PARM2));
}
/*
=================
returns x raised to the y power
=================
*/
static void
PF_pow (void)
{
G_FLOAT(OFS_RETURN) = pow(G_FLOAT(OFS_PARM0), G_FLOAT(OFS_PARM1));
}
/*
=================
copies data from one entity to another
copyentity(src, dst)
=================
*/
static void
PF_copyentity (void)
{
edict_t *in, *out;
in = G_EDICT(OFS_PARM0);
out = G_EDICT(OFS_PARM1);
memcpy(&(out->v), &(in->v), progs->entityfields * 4);
}
/*
=================
sets the color of a client and broadcasts the update to all connected
clients
setcolor(clientent, value)
=================
*/
static void
PF_setcolor (void)
{
client_t *client;
Uint entnum, i;
entnum = G_EDICTNUM(OFS_PARM0);
i = G_FLOAT(OFS_PARM1);
if (entnum < 1 || entnum > svs.maxclients)
{
Sys_Printf ("tried to setcolor a non-client\n");
return;
}
client = &svs.clients[entnum-1];
client->colors = i;
client->edict->v.team = (i & 15) + 1;
MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
MSG_WriteByte (&sv.reliable_datagram, entnum - 1);
MSG_WriteByte (&sv.reliable_datagram, i);
}
static void
PF_findfloat (void)
{
Uint e;
int f;
float s;
edict_t *ed;
e = G_EDICTNUM(OFS_PARM0);
f = G_INT(OFS_PARM1);
s = G_FLOAT(OFS_PARM2);
for (e++; e < sv.num_edicts; e++)
{
ed = EDICT_NUM(e);
if (ed->free)
continue;
if (E_FLOAT(ed,f) == s)
{
RETURN_EDICT(ed);
return;
}
}
RETURN_EDICT(sv.edicts);
}
// chained search for strings in entity fields
// entity(.string field, string match) findchain = #402;
static void
PF_findchain (void)
{
Uint i;
int f;
char *s, *t;
edict_t *ent, *chain;
chain = (edict_t *)sv.edicts;
f = G_INT(OFS_PARM0);
s = G_STRING(OFS_PARM1);
if (!s || !s[0])
{
RETURN_EDICT(sv.edicts);
return;
}
ent = NEXT_EDICT(sv.edicts);
for (i = 1;i < sv.num_edicts;i++, ent = NEXT_EDICT(ent))
{
// We don't (yet) profile QC
// pr_xfunction->builtinsprofile++;
if (ent->free)
continue;
t = E_STRING(ent,f);
if (!t)
continue;
if (strcmp(t,s))
continue;
ent->v.chain = EDICT_TO_PROG(chain);
chain = ent;
}
RETURN_EDICT(chain);
}
// LordHavoc: chained search for float, int, and entity reference fields
// entity(.string field, float match) findchainfloat = #403;
static void
PF_findchainfloat (void)
{
Uint i;
int f;
float s;
edict_t *ent, *chain;
chain = (edict_t *)sv.edicts;
f = G_INT(OFS_PARM0);
s = G_FLOAT(OFS_PARM1);
ent = NEXT_EDICT(sv.edicts);
for (i = 1;i < sv.num_edicts;i++, ent = NEXT_EDICT(ent))
{
// We do not (yet) profile QC
// pr_xfunction->builtinsprofile++;
if (ent->free)
continue;
if (E_FLOAT(ent,f) != s)
continue;
ent->v.chain = EDICT_TO_PROG(chain);
chain = ent;
}
RETURN_EDICT(chain);
}
static void
PF_checkextension (void)
{
int len;
char *name, *e, *start;
name = G_STRING(OFS_PARM0);
len = strlen(name);
for (e = engine_extensions; *e; e++)
{
while (*e == ' ')
e++;
if (!*e)
break;
start = e;
while (*e && *e != ' ')
e++;
if (e - start == len)
if (!strncasecmp (start, name, len))
{
G_FLOAT(OFS_RETURN) = true;
return;
}
}
G_FLOAT(OFS_RETURN) = false;
}
#define NULL10 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
#define NULL100 NULL10, NULL10, NULL10, NULL10, NULL10, NULL10, NULL10, \
NULL10, NULL10, NULL10
static builtin_t pr_builtin[] =
{
NULL, // #000 runtime error
PF_makevectors, // #001
PF_setorigin, // #002
PF_setmodel, // #003
PF_setsize, // #004
NULL, // #005 setabssize (never implemented)
PF_break, // #006
PF_random, // #007
PF_sound, // #008
PF_normalize, // #009
PF_error, // #010
PF_objerror, // #011
PF_vlen, // #012
PF_vectoyaw, // #013
PF_Spawn, // #014
PF_Remove, // #015
PF_traceline, // #016
PF_checkclient, // #017
PF_Find, // #018
PF_precache_sound, // #019
PF_precache_model, // #020
PF_stuffcmd, // #021
PF_findradius, // #022
PF_bprint, // #023
PF_sprint, // #024
PF_dprint, // #025
PF_ftos, // #026
PF_vtos, // #027
PF_coredump, // #028
PF_traceon, // #029
PF_traceoff, // #030
PF_eprint, // #031
PF_walkmove, // #032
NULL, // #033 ???
PF_droptofloor, // #034
PF_lightstyle, // #035
PF_rint, // #036
PF_floor, // #037
PF_ceil, // #038
NULL, // #039
PF_checkbottom, // #040
PF_pointcontents, // #041
NULL, // #042
PF_fabs, // #043
PF_aim, // #044
PF_cvar, // #045
PF_localcmd, // #046
PF_nextent, // #047
PF_particle, // #048
PF_changeyaw, // #049
NULL, // #050
PF_vectoangles, // #051
PF_WriteByte, // #052
PF_WriteChar, // #053
PF_WriteShort, // #054
PF_WriteLong, // #055
PF_WriteCoord, // #056
PF_WriteAngle, // #057
PF_WriteString, // #058
PF_WriteEntity, // #059
PF_sin, // #060 Q2: DP_QC_SINCOSSQRTPOW
PF_cos, // #061 Q2: DP_QC_SINCOSSQRTPOW
PF_sqrt, // #062 Q2: DP_QC_SINCOSSQRTPOW
PF_changepitch, // #063 Q2: DP_QC_CHANGEPITCH
PF_tracetoss, // #064 Q2: DP_QC_TRACETOSS
PF_etos, // #065 Q2: DP_QC_ETOS
NULL, // #066 Q2: PF_watermove (don't implement)
SV_MoveToGoal, // #067
PF_precache_file, // #068
PF_makestatic, // #069
PF_changelevel, // #070
NULL, // #071
PF_cvar_set, // #072
PF_centerprint, // #073
PF_ambientsound, // #074
PF_precache_model, // #075
PF_precache_sound, // #076
PF_precache_file, // #077
PF_setspawnparms, // #078
// Used by various QSG "tutorials" (overlap with QW)
NULL, // #079
NULL, // #080
NULL, // #081
NULL, // #082
// Used by various QSG "tutorials"
NULL, // #083
NULL, // #084
NULL, // #085
NULL, // #086
NULL, // #087
NULL, // #088
NULL, // #089
// DarkPlaces extensions (1)
PF_tracebox, // #090 DP: DP_QC_TRACEBOX
PF_randomvec, // #091 DP: DP_QC_RANDOMVEC
NULL, // #092 DP: PF_getlight (don't implement)
PF_registercvar, // #093 DP: DP_REGISTERCVAR
PF_min, // #094 DP: DP_QC_MINMAXBOUND
PF_max, // #095 DP: DP_QC_MINMAXBOUND
PF_bound, // #096 DP: DP_QC_MINMAXBOUND
PF_pow, // #097 DP: DP_QC_SINCOSSQRTPOW
PF_findfloat, // #098 DP: DP_QC_FINDFLOAT
PF_checkextension, // #099 DP/TQ: checkextension
// Used by someone for something probably...
NULL100, // #100 - 199
NULL100, // #200 - 299
NULL100, // #300 - 399
// DarkPlaces extensions (2)
PF_copyentity, // #400 DP: DP_QC_COPYENTITY
PF_setcolor, // #401 DP: DP_SV_SETCOLOR
PF_findchain, // #401 DP: DP_QC_FINDCHAIN
PF_findchainfloat, // #403 DP: DP_QC_FINDCHAINFLOAT
NULL, // #404 PF_effect
NULL, // #405 PF_te_blood
NULL, // #406 PF_te_bloodshower
NULL, // #407 PF_te_explosionrgb
NULL, // #408 PF_te_particlecube
NULL, // #409 PF_te_particlerain
NULL, // #410 PF_te_particlesnow
NULL, // #411 PF_te_spark
NULL, // #412 PF_te_gunshotquad
NULL, // #413 PF_te_spikequad
NULL, // #414 PF_te_superspikequad
NULL, // #415 PF_te_explosionquad
NULL, // #416 PF_te_smallflash
NULL, // #417 PF_te_customflash
NULL, // #418 PF_te_gunshot
NULL, // #419 PF_te_spike
NULL, // #420 PF_te_superspike
NULL, // #421 PF_te_explosion
NULL, // #422 PF_te_tarexplosion
NULL, // #423 PF_te_wizspike
NULL, // #424 PF_te_knightspike
NULL, // #425 PF_te_lavasplash
NULL, // #426 PF_te_teleport
NULL, // #427 PF_te_explosion2
NULL, // #428 PF_te_lightning1
NULL, // #429 PF_te_lightning2
NULL, // #430 PF_te_lightning3
NULL, // #431 PF_te_beam
PF_vectorvectors, // #432 DP_QC_VECTORVECTORS
NULL, // #433 PF_te_plasmaburn
};
builtin_t *pr_builtins = pr_builtin;
Uint pr_numbuiltins = sizeof (pr_builtin) / sizeof (pr_builtin[0]);
| 19.541549 | 93 | 0.630095 | [
"object",
"vector",
"model",
"solid"
] |
c88757579959f898bda7c820bbfc5bd9f22c60b8 | 2,877 | h | C | code/steps/header/model/wtg_models/wt_turbine_model/wt3t1.h | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | 1 | 2021-01-21T13:10:40.000Z | 2021-01-21T13:10:40.000Z | code/steps/header/model/wtg_models/wt_turbine_model/wt3t1.h | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | null | null | null | code/steps/header/model/wtg_models/wt_turbine_model/wt3t1.h | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | 1 | 2020-10-01T03:48:38.000Z | 2020-10-01T03:48:38.000Z | #ifndef WT3T1_H
#define WT3T1_H
#include "header/model/wtg_models/wt_turbine_model/wt_turbine_model.h"
#include "header/block/integral_block.h"
class WT3T1 : public WT_TURBINE_MODEL
{
public:
WT3T1(STEPS& toolkit);
WT3T1(const WT3T1&model);
virtual ~WT3T1();
virtual WT3T1& operator=(const WT3T1& model);
public: // specific model level
virtual string get_model_name() const;
void set_Htotal_in_s(double H);
void set_Damp_in_pu(double D);
void set_Kaero(double K);
void set_Theta2_in_deg(double theta);
void set_Htfrac_in_pu(double frac);
void set_Freq1_in_Hz(double f);
void set_Dshaft_in_pu(double D);
double get_Htotal_in_s() const;
double get_Damp_in_pu() const;
double get_Kaero() const;
double get_Theta2_in_deg() const;
double get_Htfrac_in_pu() const;
double get_Freq1_in_Hz() const;
double get_Dshaft_in_pu() const;
public:
virtual bool setup_model_with_steps_string_vector(vector<string>& data);
virtual bool setup_model_with_psse_string(string data);
virtual bool setup_model_with_bpa_string(string data);
virtual void prepare_model_data_table();
virtual void prepare_model_internal_variable_table();
virtual void initialize();
virtual void run(DYNAMIC_MODE mode);
virtual double get_wind_turbine_mechanical_power_in_pu_based_on_mbase() const;
virtual double get_wind_turbine_generator_speed_reference_in_pu() const;
virtual double get_wind_turbine_generator_speed_in_pu() const;
virtual double get_wind_turbine_generator_rotor_angle_in_deg() const;
virtual double get_wind_turbine_generator_rotor_angle_in_rad() const;
virtual void check();
virtual void clear();
virtual void report();
virtual void save();
virtual string get_standard_psse_string() const;
virtual double get_model_data_with_name(string par_name) const;
virtual void set_model_data_with_name(string par_name, double value);
virtual double get_minimum_nonzero_time_constant_in_s();
virtual double get_model_internal_variable_with_name(string var_name);
virtual string get_dynamic_data_in_psse_format() const;
virtual string get_dynamic_data_in_bpa_format() const;
virtual string get_dynamic_data_in_steps_format() const;
private:
void copy_from_const_model(const WT3T1& model);
INTEGRAL_BLOCK shaft_twist;
INTEGRAL_BLOCK turbine_inertia;
INTEGRAL_BLOCK generator_inertia;
INTEGRAL_BLOCK generator_rotor_angle;
double Htotal;
double Damp;
double Kaero;
double Theta2;
double Htfrac;
double Freq1;
double Dshaft;
};
#endif // WT3T1_H
| 35.9625 | 86 | 0.704206 | [
"vector",
"model"
] |
c88df22b0da93966861bb38929d2383db6d8153a | 1,525 | h | C | DashWallet/Sources/UI/DashPay/Contacts/Models/DWBaseContactsModel.h | magicwave/dashwallet-ios | 57ca6d4cc2cd8ea699f294580e6e3f62d25c3f22 | [
"MIT"
] | 51 | 2016-01-19T12:01:58.000Z | 2019-02-03T19:46:24.000Z | DashWallet/Sources/UI/DashPay/Contacts/Models/DWBaseContactsModel.h | magicwave/dashwallet-ios | 57ca6d4cc2cd8ea699f294580e6e3f62d25c3f22 | [
"MIT"
] | 32 | 2015-10-31T07:01:03.000Z | 2019-01-09T15:48:54.000Z | DashWallet/Sources/UI/DashPay/Contacts/Models/DWBaseContactsModel.h | magicwave/dashwallet-ios | 57ca6d4cc2cd8ea699f294580e6e3f62d25c3f22 | [
"MIT"
] | 38 | 2015-09-17T00:35:53.000Z | 2021-04-29T06:08:40.000Z | //
// Created by Andrew Podkovyrin
// Copyright © 2020 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// 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.
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
#import "DWContactsDataSource.h"
#import "DWContactsSortModeProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@class DWBaseContactsModel;
@protocol DWContactsModelDelegate <NSObject>
- (void)contactsModelDidUpdate:(DWBaseContactsModel *)model;
@end
@interface DWBaseContactsModel : NSObject <DWContactsSortModeProtocol>
@property (readonly, nonatomic, assign) BOOL hasBlockchainIdentity;
@property (readonly, nonatomic, strong) id<DWContactsDataSource> dataSource;
@property (nullable, nonatomic, weak) id<DWContactsModelDelegate> delegate;
@property (nonatomic, assign) DWContactsSortMode sortMode;
- (void)start;
- (void)stop;
- (void)acceptContactRequest:(id<DWDPBasicUserItem>)item;
- (void)declineContactRequest:(id<DWDPBasicUserItem>)item;
- (void)searchWithQuery:(NSString *)searchQuery;
@end
NS_ASSUME_NONNULL_END
| 28.773585 | 76 | 0.775738 | [
"model"
] |
c8954913ae7bec3caa79170d05f121b04af2f367 | 26,918 | c | C | bootloader/src/thc_apple_events.c | synominit/pyinstaller | dd4dec9b1b748860773ad6f230bcedee9e6f0510 | [
"Apache-2.0"
] | null | null | null | bootloader/src/thc_apple_events.c | synominit/pyinstaller | dd4dec9b1b748860773ad6f230bcedee9e6f0510 | [
"Apache-2.0"
] | null | null | null | bootloader/src/thc_apple_events.c | synominit/pyinstaller | dd4dec9b1b748860773ad6f230bcedee9e6f0510 | [
"Apache-2.0"
] | null | null | null | /*
* ****************************************************************************
* Copyright (c) 2013-2021, PyInstaller Development Team.
*
* Distributed under the terms of the GNU General Public License (version 2
* or later) with exception for distributing the bootloader.
*
* The full license is in the file COPYING.txt, distributed with this software.
*
* SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
* ****************************************************************************
*/
/*
* Handling of Apple Events in macOS windowed (app bundle) mode:
* - argv emulation
* - event forwarding to child process
*/
#if defined(__APPLE__) && defined(WINDOWED)
#include <Carbon/Carbon.h> /* AppleEventsT */
#include <ApplicationServices/ApplicationServices.h> /* GetProcessForPID, etc */
#include "thc_global.h"
#include "thc_utils.h"
/* Not declared in modern headers but exists in Carbon libs since time immemorial
* See: https://applescriptlibrary.files.wordpress.com/2013/11/apple-events-programming-guide.pdf */
extern Boolean ConvertEventRefToEventRecord(EventRef inEvent, EventRecord *outEvent);
/*
* On Mac OS X this converts events from kAEOpenDocuments and kAEGetURL into sys.argv.
* After startup, it also forwards kAEOpenDocuments and KAEGetURL events at runtime to the child process.
*
* TODO: The below can be simplified considerably if re-written in Objective C (e.g. put into pyi_utils_osx.m).
*/
/* Static context structure for keeping track of data */
static struct AppleEventHandlerContext
{
/* Event handlers for argv-emu / event forwarding */
Boolean installed; /* Are handlers installed? */
EventHandlerUPP upp_handler; /* UPP for event handler callback */
AEEventHandlerUPP upp_handler_ae; /* UPP for AppleEvent handler callback */
EventHandlerRef handler_ref; /* Reference to installer event handler */
} _ae_ctx = {
false, /* installed */
NULL, /* handler */
NULL, /* handler_ae */
NULL, /* handler_ref */
};
/* Event types list: used to register handler and to listen for events */
static const EventTypeSpec event_types_ae[] = {
{ kEventClassAppleEvent, kEventAppleEvent },
};
/* Convert a FourCharCode into a string (useful for debug). Returned buffer is a static buffer, so subsequent calls
* may overwrite the same buffer. */
static const char *CC2Str(FourCharCode code) {
/* support up to 3 calls on the same debug print line */
static char bufs[3][5];
static unsigned int bufsidx = 0;
char *buf = bufs[bufsidx++ % 3u];
snprintf(buf, 5, "%c%c%c%c", (code >> 24) & 0xFF, (code >> 16) & 0xFF, (code >> 8) & 0xFF, code & 0xFF);
/* buffer is guaranteed to be nul terminated here */
return buf;
}
/* Generic event forwarder -- forwards an event destined for this process to the child process,
* copying its param object, if any. Parameter `theAppleEvent` may be NULL, in which case a new
* event is created with the specified class and id (containing 0 params / no param object). */
static OSErr generic_forward_apple_event(const AppleEvent *const theAppleEvent /* NULL ok */,
const AEEventClass eventClass, const AEEventID evtID,
const char *const descStr)
{
const FourCharCode evtCode = (FourCharCode)evtID;
OSErr err;
AppleEvent childEvent;
AEAddressDesc target;
DescType actualType = 0, typeCode = typeWildCard;
char *buf = NULL; /* dynamic buffer to hold copied event param data */
Size bufSize = 0, actualSize = 0;
pid_t child_pid;
VS("LOADER [AppleEvent]: Forwarder called for \"%s\".\n", descStr);
child_pid = pyi_utils_get_child_pid();
if (!child_pid) {
/* Child not up yet -- there is no way to "forward" this before child started!. */
VS("LOADER [AppleEvent]: Child not up yet (child_pid is 0)\n");
return errAEEventNotHandled;
}
VS("LOADER [AppleEvent]: Forwarding '%s' event.\n", CC2Str(evtCode));
err = AECreateDesc(typeKernelProcessID, &child_pid, sizeof(child_pid), &target);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create AEAddressDesc: %d\n", (int)err);
goto out;
}
VS("LOADER [AppleEvent]: Created AEAddressDesc.\n");
err = AECreateAppleEvent(eventClass, evtID, &target, kAutoGenerateReturnID, kAnyTransactionID,
&childEvent);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create event copy: %d\n", (int)err);
goto release_desc;
}
VS("LOADER [AppleEvent]: Created AppleEvent instance for child process.\n");
if (!theAppleEvent) {
/* Calling code wants a new event created from scratch, we do so
* here and it will have 0 params. Assumption: caller knows that
* the event type in question normally has 0 params. */
VS("LOADER [AppleEvent]: New AppleEvent class: '%s' code: '%s'\n",
CC2Str((FourCharCode)eventClass), CC2Str((FourCharCode)evtID));
} else {
err = AESizeOfParam(theAppleEvent, keyDirectObject, &typeCode, &bufSize);
if (err != noErr) {
/* No params for this event */
VS("LOADER [AppleEvent]: Failed to get size of param (error=%d) -- event '%s' may lack params.\n",
(int)err, CC2Str(evtCode));
} else {
/* This event has a param object, copy it. */
VS("LOADER [AppleEvent]: Got size of param: %ld\n", (long)bufSize);
buf = malloc(bufSize);
if (!buf) {
/* Failed to allocate buffer! */
OTHERERROR("LOADER [AppleEvent]: Failed to allocate buffer of size %ld: %s\n",
(long)bufSize, strerror(errno));
goto release_evt;
}
VS("LOADER [AppleEvent]: Allocated buffer of size: %ld\n", (long)bufSize);
VS("LOADER [AppleEvent]: Getting param.\n");
err = AEGetParamPtr(theAppleEvent, keyDirectObject, typeWildCard,
&actualType, buf, bufSize, &actualSize);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to get param data.\n");
goto release_evt;
}
if (actualSize > bufSize) {
/* From reading the Apple API docs, this should never happen, but it pays
* to program defensively here. */
OTHERERROR("LOADER [AppleEvent]: Got param size=%ld > bufSize=%ld, error!\n",
(long)actualSize, (long)bufSize);
goto release_evt;
}
VS("LOADER [AppleEvent]: Got param type=%x ('%s') size=%ld\n",
(UInt32)actualType, CC2Str((FourCharCode)actualType), (long)actualSize);
VS("LOADER [AppleEvent]: Putting param.\n");
err = AEPutParamPtr(&childEvent, keyDirectObject, actualType, buf, actualSize);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to put param data.\n");
goto release_evt;
}
}
}
VS("LOADER [AppleEvent]: Sending message...\n");
err = AESendMessage(&childEvent, NULL, kAENoReply, kAEDefaultTimeout);
VS("LOADER [AppleEvent]: Handler sent \"%s\" message to child pid %ld.\n", descStr, (long)child_pid);
/* In onefile build, we may encounter a race condition between parent
* and child process, because child_pid becomes valid immediately after
* fork, but the child process may not be able to receive the events yet.
* In such cases, AESendMessage fails with procNotFound (-600). Accommodate
* such cases with 10 retries, spaced 0.5 second apart (for 5 seconds
* of total retry time) */
if (err == procNotFound) {
int retry = 0;
while (err == procNotFound && retry++ < 5) {
VS("LOADER [AppleEvent]: Sending failed with procNotFound; re-trying in 1 second (attempt %d)\n", retry);
usleep(500000); /* sleep 0.5 second (kAENoReply = no timeout) */
err = AESendMessage(&childEvent, NULL, kAENoReply, kAEDefaultTimeout);
}
}
release_evt:
free(buf);
AEDisposeDesc(&childEvent);
release_desc:
AEDisposeDesc(&target);
out:
return err;
}
static Boolean realloc_checked(void **bufptr, Size size)
{
void *tmp = realloc(*bufptr, size);
if (!tmp) {
OTHERERROR("LOADER [AppleEvents]: Failed to allocate a buffer of size %ld.\n", (long)size);
return false;
}
VS("LOADER [AppleEvents]: (re)allocated a buffer of size %ld\n", (long)size);
*bufptr = tmp;
return true;
}
/* Handles apple events 'odoc' and 'GURL', both before and after the child_pid is up, Copying them to argv if child
* not up yet, or otherwise forwarding them to the child if the child is started. */
static OSErr handle_odoc_GURL_events(const AppleEvent *theAppleEvent, const AEEventID evtID)
{
const FourCharCode evtCode = (FourCharCode)evtID;
const Boolean apple_event_is_open_doc = evtID == kAEOpenDocuments;
const char *const descStr = apple_event_is_open_doc ? "OpenDoc" : "GetURL";
VS("LOADER [AppleEvent]: %s handler called.\n", descStr);
if (!pyi_utils_get_child_pid()) {
/* Child process is not up yet -- so we pick up kAEOpen and/or kAEGetURL events and append them to argv. */
AEDescList docList;
OSErr err;
long index;
long count = 0;
char *buf = NULL; /* Dynamic buffer for URL/file path data -- gets realloc'd as we iterate */
VS("LOADER [AppleEvent ARGV_EMU]: Processing args for forward...\n");
err = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
if (err != noErr) return err;
err = AECountItems(&docList, &count);
if (err != noErr) return err;
for (index = 1; index <= count; ++index) /* AppleEvent lists are 1-indexed (I guess because of Pascal?) */
{
DescType returnedType;
AEKeyword keywd;
Size actualSize = 0, bufSize = 0;
DescType typeCode = typeWildCard;
err = AESizeOfNthItem(&docList, index, &typeCode, &bufSize);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent ARGV_EMU]: Failed to get size of Nth item %ld, error: %d\n",
index, (int)err);
continue;
}
if (!realloc_checked((void **)&buf, bufSize+1)) {
/* Not enough memory -- very unlikely but if so keep going */
OTHERERROR("LOADER [AppleEvent ARGV_EMU]: Not enough memory for Nth item %ld, skipping%d\n", index);
continue;
}
err = AEGetNthPtr(&docList, index, apple_event_is_open_doc ? typeFileURL : typeUTF8Text, &keywd,
&returnedType, buf, bufSize, &actualSize);
if (err != noErr) {
VS("LOADER [AppleEvent ARGV_EMU]: err[%ld] = %d\n", index-1L, (int)err);
} else if (actualSize > bufSize) {
/* This should never happen but is here for thoroughness */
VS("LOADER [AppleEvent ARGV_EMU]: err[%ld]: not enough space in buffer (%ld > %ld)\n",
index-1L, (long)actualSize, (long)bufSize);
} else {
/* Copied data to buf, now ensure data is a simple file path and then append it to argv_pyi */
char *tmp_str = NULL;
Boolean ok;
buf[actualSize] = 0; /* Ensure NUL-char termination. */
if (apple_event_is_open_doc) {
/* Now, convert file:/// style URLs to an actual filesystem path for argv emu. */
CFURLRef url = CFURLCreateWithBytes(NULL, (UInt8 *)buf, actualSize, kCFStringEncodingUTF8,
NULL);
if (url) {
CFStringRef path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
ok = false;
if (path) {
const Size newLen = (Size)CFStringGetMaximumSizeOfFileSystemRepresentation(path);
if (realloc_checked((void **)&buf, newLen+1)) {
bufSize = newLen;
ok = CFStringGetFileSystemRepresentation(path, buf, bufSize);
buf[bufSize] = 0; /* Ensure NUL termination */
}
CFRelease(path); /* free */
}
CFRelease(url); /* free */
if (!ok) {
VS("LOADER [AppleEvent ARGV_EMU]: "
"Failed to convert file:/// path to POSIX filesystem representation for arg %ld!\n",
index);
continue;
}
}
}
/* Append URL to argv_pyi array, reallocating as necessary */
VS("LOADER [AppleEvent ARGV_EMU]: appending '%s' to argv_pyi\n", buf);
if (pyi_utils_append_to_args(buf) < 0) {
OTHERERROR("LOADER [AppleEvent ARGV_EMU]: failed to append to argv_pyi: %s\n",
buf, strerror(errno));
} else {
VS("LOADER [AppleEvent ARGV_EMU]: argv entry appended.\n");
}
}
}
free(buf); /* free of possible-NULL ok */
err = AEDisposeDesc(&docList);
return err;
} /* else ... */
/* The child process exists.. so we forward events to it */
return generic_forward_apple_event(theAppleEvent,
apple_event_is_open_doc ? kCoreEventClass : kInternetEventClass,
evtID,
descStr);
}
/* This brings the child process's windows to the foreground when the user double-clicks the
* app's icon again in the macOS UI. 'rapp' is accepted by us only when the child is
* already running. */
static OSErr handle_rapp_event(const AppleEvent *const theAppleEvent, const AEEventID evtID)
{
OSErr err;
VS("LOADER [AppleEvent]: ReopenApp handler called.\n");
/* First, forward the 'rapp' event to the child */
err = generic_forward_apple_event(theAppleEvent, kCoreEventClass, evtID, "ReopenApp");
if (err == noErr) {
/* Next, create a new activate ('actv') event. We never receive this event because
* we have no window, but if we did this event would come next. So we synthesize an
* event that should normally come for a windowed app, so that the child process
* is brought to the foreground properly. */
generic_forward_apple_event(NULL /* create new event with 0 params */,
kAEMiscStandards, kAEActivate, "Activate");
}
return err;
}
/* Top-level event handler -- dispatches 'odoc', 'GURL', 'rapp', or 'actv' events. */
static pascal OSErr handle_apple_event(const AppleEvent *theAppleEvent, AppleEvent *reply, SRefCon handlerRefCon)
{
const FourCharCode evtCode = (FourCharCode)(intptr_t)handlerRefCon;
const AEEventID evtID = (AEEventID)(intptr_t)handlerRefCon;
(void)reply; /* unused */
VS("LOADER [AppleEvent]: %s called with code '%s'.\n", __FUNCTION__, CC2Str(evtCode));
switch(evtID) {
case kAEOpenApplication:
/* Nothing to do here, just make sure we report event as handled. */
return noErr;
case kAEOpenDocuments:
case kAEGetURL:
return handle_odoc_GURL_events(theAppleEvent, evtID);
case kAEReopenApplication:
return handle_rapp_event(theAppleEvent, evtID);
case kAEActivate:
/* This is not normally reached since the bootloader process lacks a window, and it
* turns out macOS never sends this event to processes lacking a window. However,
* since the Apple API docs are very sparse, this has been left-in here just in case. */
return generic_forward_apple_event(theAppleEvent, kAEMiscStandards, evtID, "Activate");
default:
/* Not 'GURL', 'odoc', 'rapp', or 'actv' -- this is not reached unless there is a
* programming error in the code that sets up the handler(s) in pyi_process_apple_events. */
OTHERERROR("LOADER [AppleEvent]: %s called with unexpected event type '%s'!\n",
__FUNCTION__, CC2Str(evtCode));
return errAEEventNotHandled;
}
}
/* This function gets installed as the process-wide UPP event handler.
* It is responsible for dequeuing events and telling Carbon to forward
* them to our installed handlers. */
static OSStatus evt_handler_proc(EventHandlerCallRef href, EventRef eref, void *data) {
VS("LOADER [AppleEvent]: App event handler proc called.\n");
Boolean release = false;
EventRecord eventRecord;
OSStatus err;
/* Events of type kEventAppleEvent must be removed from the queue
* before being passed to AEProcessAppleEvent. */
if (IsEventInQueue(GetMainEventQueue(), eref)) {
/* RemoveEventFromQueue will release the event, which will
* destroy it if we don't retain it first. */
VS("LOADER [AppleEvent]: Event was in queue, will release.\n");
RetainEvent(eref);
release = true;
RemoveEventFromQueue(GetMainEventQueue(), eref);
}
/* Convert the event ref to the type AEProcessAppleEvent expects. */
ConvertEventRefToEventRecord(eref, &eventRecord);
VS("LOADER [AppleEvent]: what=%hu message=%lx ('%s') modifiers=%hu\n",
eventRecord.what, eventRecord.message, CC2Str((FourCharCode)eventRecord.message), eventRecord.modifiers);
/* This will end up calling one of the callback functions
* that we installed in pyi_process_apple_events() */
err = AEProcessAppleEvent(&eventRecord);
if (err == errAEEventNotHandled) {
VS("LOADER [AppleEvent]: Ignored event.\n");
} else if (err != noErr) {
VS("LOADER [AppleEvent]: Error processing event: %d\n", (int)err);
}
if (release) {
ReleaseEvent(eref);
}
return noErr;
}
/*
* Install Apple Event handlers. The handlers must be install prior to
* calling pyi_apple_process_events().
*/
int pyi_apple_install_event_handlers()
{
OSStatus err;
/* Already installed; nothing to do */
if (_ae_ctx.installed) {
return 0;
}
VS("LOADER [AppleEvent]: Installing event handlers...\n");
/* Allocate UPP (universal procedure pointer) for handler functions */
_ae_ctx.upp_handler = NewEventHandlerUPP(evt_handler_proc);
_ae_ctx.upp_handler_ae = NewAEEventHandlerUPP(handle_apple_event);
/* Register Apple Event handlers */
/* 'oapp' (open application) */
err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, _ae_ctx.upp_handler_ae, (SRefCon)kAEOpenApplication, false);
if (err != noErr) {
goto end;
}
/* 'odoc' (open document) */
err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, _ae_ctx.upp_handler_ae, (SRefCon)kAEOpenDocuments, false);
if (err != noErr) {
goto end;
}
/* 'GURL' (open url) */
err = AEInstallEventHandler(kInternetEventClass, kAEGetURL, _ae_ctx.upp_handler_ae, (SRefCon)kAEGetURL, false);
if (err != noErr) {
goto end;
}
/* 'rapp' (re-open application) */
err = AEInstallEventHandler(kCoreEventClass, kAEReopenApplication, _ae_ctx.upp_handler_ae, (SRefCon)kAEReopenApplication, false);
if (err != noErr) {
goto end;
}
/* register 'actv' (activate) */
err = AEInstallEventHandler(kAEMiscStandards, kAEActivate, _ae_ctx.upp_handler_ae, (SRefCon)kAEActivate, false);
if (err != noErr) {
goto end;
}
/* Install application event handler */
err = InstallApplicationEventHandler(_ae_ctx.upp_handler, 1, event_types_ae, NULL, &_ae_ctx.handler_ref);
end:
if (err != noErr) {
/* Failed to install one of AE handlers or application event handler.
* Remove everything. */
AERemoveEventHandler(kAEMiscStandards, kAEActivate, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEReopenApplication, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kInternetEventClass, kAEGetURL, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenApplication, _ae_ctx.upp_handler_ae, false);
DisposeEventHandlerUPP(_ae_ctx.upp_handler);
DisposeAEEventHandlerUPP(_ae_ctx.upp_handler_ae);
OTHERERROR("LOADER [AppleEvent]: Failed to install event handlers!\n");
return -1;
}
VS("LOADER [AppleEvent]: Installed event handlers.\n");
_ae_ctx.installed = true;
return 0;
}
/*
* Uninstall Apple Event handlers.
*/
int pyi_apple_uninstall_event_handlers()
{
/* Not installed; nothing to do */
if (!_ae_ctx.installed) {
return 0;
}
VS("LOADER [AppleEvent]: Uninstalling event handlers...\n");
/* Remove application event handler */
RemoveEventHandler(_ae_ctx.handler_ref);
_ae_ctx.handler_ref = NULL;
/* Remove Apple Event handlers */
AERemoveEventHandler(kAEMiscStandards, kAEActivate, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEReopenApplication, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kInternetEventClass, kAEGetURL, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenApplication, _ae_ctx.upp_handler_ae, false);
/* Cleanup UPPs */
DisposeEventHandlerUPP(_ae_ctx.upp_handler);
DisposeAEEventHandlerUPP(_ae_ctx.upp_handler_ae);
_ae_ctx.upp_handler = NULL;
_ae_ctx.upp_handler_ae = NULL;
_ae_ctx.installed = false;
VS("LOADER [AppleEvent]: Uninstalled event handlers.\n");
return 0;
}
/*
* Apple event message pump; retrieves and processes Apple Events until
* the specified timeout (in seconds) or an error is reached.
*/
void pyi_apple_process_events(float timeout)
{
/* No-op if we failed to install event handlers */
if (!_ae_ctx.installed) {
return;
}
VS("LOADER [AppleEvent]: Processing Apple Events...\n");
/* Event pump: process events until timeout (in seconds) or error */
for (;;) {
OSStatus status;
EventRef event_ref; /* Event that caused ReceiveNextEvent to return. */
VS("LOADER [AppleEvent]: Calling ReceiveNextEvent\n");
status = ReceiveNextEvent(1, event_types_ae, timeout, kEventRemoveFromQueue, &event_ref);
if (status == eventLoopTimedOutErr) {
VS("LOADER [AppleEvent]: ReceiveNextEvent timed out\n");
break;
} else if (status != 0) {
VS("LOADER [AppleEvent]: ReceiveNextEvent fetching events failed\n");
break;
} else {
/* We actually pulled an event off the queue, so process it.
We now 'own' the event_ref and must release it. */
VS("LOADER [AppleEvent]: ReceiveNextEvent got an EVENT\n");
VS("LOADER [AppleEvent]: Dispatching event...\n");
status = SendEventToEventTarget(event_ref, GetEventDispatcherTarget());
ReleaseEvent(event_ref);
event_ref = NULL;
if (status != 0) {
VS("LOADER [AppleEvent]: processing events failed\n");
break;
}
}
}
VS("LOADER [AppleEvent]: Out of the event loop.\n");
}
/*
* Submit oapp (open application) event to ourselves. This is an attempt
* to mitigate the issues with some UI frameworks (Tcl/Tk, in particular)
* that are causes by argv-emu being enabled in onedir mode. In this case,
* argv-emu swallows initial activation event (usually oapp; or odoc/GURL
* if launched via file/url open request). This function attempts to
* mitigate that by submitting a manual oapp event to itself so that the
* UI framework finds the activation even in the event queue, as if no
* Apple Event processing took place in the bootloader.
*/
void pyi_apple_submit_oapp_event()
{
AppleEvent event = {typeNull, nil};
AEAddressDesc target = {typeNull, nil};
EventRef event_ref;
ProcessSerialNumber psn;
OSErr err;
VS("LOADER [AppleEvent]: Submitting 'oapp' event...\n");
// Get PSN via GetCurrentProcess. This function is deprecated, but
// we cannot use {0, kCurrentProcess} because we need our event
// to be queued.
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
err = GetCurrentProcess(&psn);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to obtain PSN: %d\n", (int)err);
goto cleanup;
}
// Create target address using the PSN, ...
err = AECreateDesc(typeProcessSerialNumber, &psn, sizeof(psn), &target);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create AEAddressDesc: %d\n", (int)err);
goto cleanup;
}
// ... create OAPP event, ...
err = AECreateAppleEvent(kCoreEventClass, kAEOpenApplication, &target, kAutoGenerateReturnID, kAnyTransactionID, &event);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create OAPP event: %d\n", (int)err);
goto cleanup;
}
// ... and send it
err = AESendMessage(&event, NULL, kAENoReply, 60 /* 60 = about 1.0 seconds timeout */);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to send event: %d\n", (int)err);
goto cleanup;
} else {
VS("LOADER [AppleEvent]: Submitted 'oapp' event.\n");
}
// Now wait for the event to show up in event queue (this implicitly
// assumes that no other activation event shows up, but those would
// also solve the problem we are trying to mitigate).
VS("LOADER [AppleEvent]: Waiting for 'oapp' event to show up in queue...\n");
err = ReceiveNextEvent(1, event_types_ae, 10.0, kEventLeaveInQueue, &event_ref);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Timed out while waiting for submitted 'oapp' event to show up in queue!\n");
} else {
VS("LOADER [AppleEvent]: Submitted 'oapp' event is available in the queue.\n");
}
cleanup:
AEDisposeDesc(&event);
AEDisposeDesc(&target);
return;
}
#endif /* if defined(__APPLE__) && defined(WINDOWED) */
| 41.668731 | 133 | 0.628316 | [
"object"
] |
c897825cf5cccf5c6c6e97b41463f3e51f27bc58 | 10,784 | c | C | workspace/stm32apps/src/lcd_usd/main.c | URSec/Silhouette-Evaluation | e0d4a764b0b5cab02bfc499ba66162787c82d379 | [
"Apache-2.0"
] | 1 | 2021-11-04T19:59:42.000Z | 2021-11-04T19:59:42.000Z | workspace/stm32apps/src/lcd_usd/main.c | URSec/Silhouette-Evaluation | e0d4a764b0b5cab02bfc499ba66162787c82d379 | [
"Apache-2.0"
] | null | null | null | workspace/stm32apps/src/lcd_usd/main.c | URSec/Silhouette-Evaluation | e0d4a764b0b5cab02bfc499ba66162787c82d379 | [
"Apache-2.0"
] | null | null | null | /**
******************************************************************************
* @file Display/LCD_PicturesFromSDCard/Src/main.c
* @author MCD Application Team
* @brief This file provides main program functions
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.</center></h2>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/** @addtogroup STM32F4xx_HAL_Applications
* @{
*/
/** @addtogroup LCD_PicturesFromSDCard
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
FATFS SD_FatFs; /* File system object for SD card logical drive */
char SD_Path[4]; /* SD card logical drive path */
char* pDirectoryFiles[MAX_BMP_FILES];
uint8_t ubNumberOfFiles = 0;
uint32_t uwBmplen = 0;
/* Internal Buffer defined in SDRAM memory */
uint8_t *uwInternalBuffer;
/* Private function prototypes -----------------------------------------------*/
static void LCD_Config(void);
static void Error_Handler(void);
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
int main(void)
{
uint32_t counter = 0, transparency = 0;
uint8_t str[30];
uint32_t t;
printf("Start to run %s\n", BENCHMARK_NAME);
t = HAL_GetTick();
uwInternalBuffer = (uint8_t *)INTERNAL_BUFFER_START_ADDRESS;
/* Configure LED3 */
BSP_LED_Init(LED3);
/*##-1- Configure LCD ######################################################*/
LCD_Config();
/*##-2- Link the SD Card disk I/O driver ###################################*/
if(FATFS_LinkDriver(&SD_Driver, SD_Path) == 0)
{
/*##-3- Initialize the Directory Files pointers (heap) ###################*/
for (counter = 0; counter < MAX_BMP_FILES; counter++)
{
pDirectoryFiles[counter] = malloc(MAX_BMP_FILE_NAME);
if(pDirectoryFiles[counter] == NULL)
{
/* Set the Text Color */
BSP_LCD_SetTextColor(LCD_COLOR_RED);
BSP_LCD_DisplayStringAtLine(8, (uint8_t*)" Cannot allocate memory ");
Error_Handler();
}
}
/* Get the BMP file names on root directory */
ubNumberOfFiles = Storage_GetDirectoryBitmapFiles("/Media", pDirectoryFiles);
if (ubNumberOfFiles == 0)
{
for (counter = 0; counter < MAX_BMP_FILES; counter++)
{
free(pDirectoryFiles[counter]);
}
BSP_LCD_DisplayStringAtLine(8, (uint8_t*)" No Bitmap files... ");
Error_Handler();
}
}
else
{
/* FatFs Initialization Error */
Error_Handler();
}
/* Main infinite loop */
while(1)
{
counter = 0;
while ((counter) < ubNumberOfFiles)
{
/* Step1 : Display on Foreground layer -------------------------------*/
/* Format the string */
sprintf ((char*)str, "Media/%-11.11s", pDirectoryFiles[counter]);
if (Storage_CheckBitmapFile((const char*)str, &uwBmplen) == 0)
{
/* Format the string */
sprintf ((char*)str, "Media/%-11.11s", pDirectoryFiles[counter]);
/* Set LCD foreground Layer */
BSP_LCD_SelectLayer(LTDC_ACTIVE_LAYER_FOREGROUND);
/* Open a file and copy its content to an internal buffer */
Storage_OpenReadFile(uwInternalBuffer, (const char*)str);
/* Write bmp file on LCD frame buffer */
BSP_LCD_DrawBitmap(0, 0, uwInternalBuffer);
/* Configure the transparency for background layer : Increase the transparency */
for (transparency = 0; transparency < 255; (transparency++))
{
BSP_LCD_SetTransparency(LTDC_ACTIVE_LAYER_FOREGROUND, transparency);
/* Insert a delay of display */
HAL_Delay(10);
}
/* Configure the transparency for foreground layer : decrease the transparency */
for (transparency = 255; transparency > 0; transparency--)
{
BSP_LCD_SetTransparency(LTDC_ACTIVE_LAYER_FOREGROUND, transparency);
/* Insert a delay of display */
HAL_Delay(10);
}
HAL_Delay(1000);
/* Clear the Foreground Layer */
BSP_LCD_Clear(LCD_COLOR_BLACK);
/* Jump to the next image */
counter++;
/* Step2 : Display on Background layer -----------------------------*/
/* Format the string */
sprintf ((char*)str, "Media/%-11.11s", pDirectoryFiles[counter]);
if ((Storage_CheckBitmapFile((const char*)str, &uwBmplen) == 0) || (counter < (ubNumberOfFiles)))
{
/* Connect the Output Buffer to LCD Background Layer */
BSP_LCD_SelectLayer(LTDC_ACTIVE_LAYER_BACKGROUND);
/* Format the string */
sprintf ((char*)str, "Media/%-11.11s", pDirectoryFiles[counter]);
/* Open a file and copy its content to an internal buffer */
Storage_OpenReadFile(uwInternalBuffer, (const char*)str);
/* Write bmp file on LCD frame buffer */
BSP_LCD_DrawBitmap(0, 0, uwInternalBuffer);
/* Configure the transparency for background layer : decrease the transparency */
for (transparency = 0; transparency < 255; (transparency++))
{
BSP_LCD_SetTransparency(LTDC_ACTIVE_LAYER_BACKGROUND, transparency);
/* Insert a delay of display */
HAL_Delay(10);
}
HAL_Delay(1000);
/* Step3 : -------------------------------------------------------*/
/* Configure the transparency for background layer : Increase the transparency */
for (transparency = 255; transparency > 0; transparency--)
{
BSP_LCD_SetTransparency(LTDC_ACTIVE_LAYER_BACKGROUND, transparency);
/* Insert a delay of display */
HAL_Delay(10);
}
HAL_Delay(1000);
/* Clear the Background Layer */
BSP_LCD_Clear(LCD_COLOR_BLACK);
counter++;
}
else if (Storage_CheckBitmapFile((const char*)str, &uwBmplen) == 0)
{
/* Set the Text Color */
BSP_LCD_SetTextColor(LCD_COLOR_RED);
BSP_LCD_DisplayStringAtLine(7, (uint8_t *) str);
BSP_LCD_DisplayStringAtLine(8, (uint8_t*)" File type not supported. ");
Error_Handler();
}
}
}
t = HAL_GetTick() - t;
printf("Elapsed time: %u ms\n", t);
break;
}
}
/**
* @brief LCD configuration
* @param None
* @retval None
*/
static void LCD_Config(void)
{
uint8_t lcd_status = LCD_OK;
/* LCD DSI initialization in mode Video Burst */
/* Initialize DSI LCD */
BSP_LCD_Init();
while(lcd_status != LCD_OK);
BSP_LCD_LayerDefaultInit(LTDC_ACTIVE_LAYER_BACKGROUND, LCD_FB_START_ADDRESS);
/* Select the LCD Background Layer */
BSP_LCD_SelectLayer(LTDC_ACTIVE_LAYER_BACKGROUND);
/* Clear the Background Layer */
BSP_LCD_Clear(LCD_COLOR_BLACK);
BSP_LCD_LayerDefaultInit(LTDC_ACTIVE_LAYER_FOREGROUND, LCD_BG_LAYER_ADDRESS);
/* Select the LCD Foreground Layer */
BSP_LCD_SelectLayer(LTDC_ACTIVE_LAYER_FOREGROUND);
/* Clear the Foreground Layer */
BSP_LCD_Clear(LCD_COLOR_BLACK);
/* Configure the transparency for foreground and background :
Increase the transparency */
BSP_LCD_SetTransparency(LTDC_ACTIVE_LAYER_BACKGROUND, 0);
BSP_LCD_SetTransparency(LTDC_ACTIVE_LAYER_FOREGROUND, 100);
}
/**
* @brief This function is executed in case of error occurrence.
* @param None
* @retval None
*/
static void Error_Handler(void)
{
/* Turn LED3 on */
BSP_LED_On(LED3);
while(1)
{
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 32.878049 | 105 | 0.606639 | [
"object"
] |
c89c327678bd4a60bd56fa9dc663901334ffa089 | 30,615 | c | C | targets/TARGET_Atmel/TARGET_SAM_CortexM0P/i2c_api.c | pradeep-gr/mbed-os5-onsemi | 576d096f2d9933c39b8a220f486e9756d89173f2 | [
"Apache-2.0"
] | 7 | 2017-01-15T16:37:41.000Z | 2021-08-10T02:14:04.000Z | targets/TARGET_Atmel/TARGET_SAM_CortexM0P/i2c_api.c | pradeep-gr/mbed-os5-onsemi | 576d096f2d9933c39b8a220f486e9756d89173f2 | [
"Apache-2.0"
] | 1 | 2017-02-20T10:48:02.000Z | 2017-02-21T11:34:16.000Z | targets/TARGET_Atmel/TARGET_SAM_CortexM0P/i2c_api.c | pradeep-gr/mbed-os5-onsemi | 576d096f2d9933c39b8a220f486e9756d89173f2 | [
"Apache-2.0"
] | 10 | 2018-02-05T03:24:55.000Z | 2021-07-04T00:31:30.000Z | /* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed_assert.h"
#include "i2c_api.h"
#include <math.h>
#include "cmsis.h"
#include "pinmap.h"
#include "sercom.h"
#include "i2c_master.h"
#include "i2c_slave.h"
#include "pinmap_function.h"
#if DEVICE_I2C_ASYNCH
#include "i2c_master_interrupt.h"
#endif
#if DEVICE_I2C_ASYNCH
#define pI2C_S(obj) (&obj->i2c)
#else
#define pI2C_S(obj) obj
#endif
#define I2C_MASTER_DEFAULT_BAUD 100000
/**
* \brief I2C modes enum
*
* I2C mode selection.
*/
enum i2c_mode {
/** Master mode. */
I2C_MODE_MASTER = 0x5,
/** Slave mode. */
I2C_MODE_SLAVE = 0x4,
};
/* Extern Variables */
extern uint8_t g_sys_init;
typedef void (*I2CHandler)(void);
#if DEVICE_I2C_ASYNCH
#define _SERCOM_INTERRUPT_HANDLERS(n, unused) (uint32_t)SERCOM##n##_Handler,
/* To save the i2c objects */
static uint32_t i2c_instances[SERCOM_INST_NUM] = {0};
const uint32_t sercom_irq_handlers[SERCOM_INST_NUM] = {
MREPEAT(SERCOM_INST_NUM, _SERCOM_INTERRUPT_HANDLERS, ~)
};
#endif
/* Forward declaration */
enum status_code _i2c_master_wait_for_bus(
struct i2c_master_module *const module);
enum status_code _i2c_master_address_response(
struct i2c_master_module *const module);
enum status_code _i2c_master_send_hs_master_code(
struct i2c_master_module *const module,
uint8_t hs_master_code);
/* Adding function from ASF for compatibility */
static enum status_code _i2c_slave_wait_for_bus(
struct i2c_slave_module *const module)
{
/* Sanity check arguments. */
MBED_ASSERT(module);
MBED_ASSERT(module->hw);
SercomI2cs *const i2c_hw = &(module->hw->I2CS);
/* Wait for reply. */
uint16_t timeout_counter = 0;
while ((!(i2c_hw->INTFLAG.reg & SERCOM_I2CS_INTFLAG_DRDY)) &&
(!(i2c_hw->INTFLAG.reg & SERCOM_I2CS_INTFLAG_PREC)) &&
(!(i2c_hw->INTFLAG.reg & SERCOM_I2CS_INTFLAG_AMATCH))) {
/* Check timeout condition. */
if (++timeout_counter >= module->buffer_timeout) {
return STATUS_ERR_TIMEOUT;
}
}
return STATUS_OK;
}
/** Initialize the I2C peripheral
*
* Configures the pins used by I2C, sets a default format and frequency, and enables the peripheral
* @param[out] obj The I2C object to initialize
* @param[in] sda The pin to use for SDA
* @param[in] scl The pin to use for SCL
* @return void
*/
void i2c_init(i2c_t *obj, PinName sda, PinName scl)
{
Sercom* hw;
uint32_t mux_func;
struct i2c_master_config config_i2c_master;
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(sda != NC);
MBED_ASSERT(scl != NC);
if (g_sys_init == 0) {
system_init();
g_sys_init = 1;
}
pI2C_S(obj)->pins[0] = sda;
pI2C_S(obj)->pins[1] = scl;
/* Calculate SERCOM instance from pins */
uint32_t sercom_index = pinmap_merge_sercom(sda, scl);
if (sercom_index == (uint32_t)NC) {
return;
}
hw = (Sercom*)pinmap_peripheral_sercom(NC, sercom_index);
i2c_master_get_config_defaults(&config_i2c_master);
/* SERCOM PAD0 - SDA */
mux_func = pinmap_function_sercom(sda, sercom_index);
if (mux_func == (uint32_t)NC) return;
config_i2c_master.pinmux_pad0 = (sda << 16) | (mux_func & 0xFFFF);
/* SERCOM PAD1 - SCL */
mux_func = pinmap_function_sercom(scl, sercom_index);
if (mux_func == (uint32_t)NC) return;
config_i2c_master.pinmux_pad1 = (scl << 16) | (mux_func & 0xFFFF);
/* Default baud rate is set to 100kHz */
pI2C_S(obj)->baud_rate = I2C_MASTER_DEFAULT_BAUD;
config_i2c_master.baud_rate = pI2C_S(obj)->baud_rate / 1000;
while(i2c_master_init(&pI2C_S(obj)->master, hw, &config_i2c_master) != STATUS_OK);
pI2C_S(obj)->mode = I2C_MODE_MASTER;
#if DEVICE_I2C_ASYNCH
/* Save the i2c object */
i2c_instances[sercom_index] = (uint32_t)obj;
#endif
i2c_master_enable(&pI2C_S(obj)->master);
}
/** Configure the I2C frequency.
* @param obj The i2c object
* @param hz Frequency in Hz
*/
void i2c_frequency(i2c_t *obj, int hz)
{
/* Temporary variables. */
int32_t baud_rate;
int32_t tmp_baud;
int32_t tmp_baud_hs;
enum status_code tmp_status_code;
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
/* Return if in Slave mode, slave do not have any baud to set */
if (pI2C_S(obj)->mode != I2C_MODE_MASTER) return;
SercomI2cm *const i2c_module = &(pI2C_S(obj)->master.hw->I2CM);
/* Disable I2C Module */
i2c_master_disable(&pI2C_S(obj)->master);
baud_rate = hz / 1000; /* To kHz */
/* Give a dummy supported value */
pI2C_S(obj)->baud_rate_high_speed = I2C_MASTER_BAUD_RATE_3400KHZ;
uint32_t sercom_index = _sercom_get_sercom_inst_index(pI2C_S(obj)->master.hw);
/* Find and set baudrate. */
tmp_baud = (int32_t)(div_ceil(
system_gclk_chan_get_hz(SERCOM0_GCLK_ID_CORE + sercom_index), (2000*(baud_rate))) - 5);
/* Check that baudrate is supported at current speed. */
if (tmp_baud > 255 || tmp_baud < 0) {
/* Baud rate not supported. */
tmp_status_code = STATUS_ERR_BAUDRATE_UNAVAILABLE;
} else {
/* Find baudrate for high speed */
tmp_baud_hs = (int32_t)(div_ceil(
system_gclk_chan_get_hz(SERCOM0_GCLK_ID_CORE + sercom_index),
(2000*(pI2C_S(obj)->baud_rate_high_speed))) - 1);
/* Check that baudrate is supported at current speed. */
if (tmp_baud_hs > 255 || tmp_baud_hs < 0) {
/* Baud rate not supported. */
tmp_status_code = STATUS_ERR_BAUDRATE_UNAVAILABLE;
}
}
if (tmp_status_code != STATUS_ERR_BAUDRATE_UNAVAILABLE) {
/* Baud rate acceptable. */
i2c_module->BAUD.reg = SERCOM_I2CM_BAUD_BAUD(tmp_baud) | SERCOM_I2CM_BAUD_HSBAUD(tmp_baud_hs);
pI2C_S(obj)->baud_rate = hz;
}
/* Enable back the I2C Module */
i2c_master_enable(&pI2C_S(obj)->master);
}
/** Send START command.
* @param obj The i2c object
*/
int i2c_start(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
if (pI2C_S(obj)->mode == I2C_MODE_MASTER) {
pI2C_S(obj)->start_pending = 1;
}
return 0;
}
/** Send STOP command.
* @param obj The i2c object
*/
int i2c_stop(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
if (pI2C_S(obj)->mode == I2C_MODE_MASTER) {
/* Send STOP command */
i2c_master_send_stop(&pI2C_S(obj)->master);
} else {
SercomI2cs *const i2c_hw = &(pI2C_S(obj)->slave.hw->I2CS);
/* Release line and wait for next start condition */
i2c_hw->CTRLB.reg |= SERCOM_I2CS_CTRLB_CMD(0x2);
}
pI2C_S(obj)->start_pending = 0;
/* TODO: Wait till STOP is send */
return 0;
}
/** Blocking reading data.
* @param obj The i2c object
* @param address 7-bit address (last bit is 1)
* @param data The buffer for receiving
* @param length Number of bytes to read
* @param stop Stop to be generated after the transfer is done
* @return Number of read bytes
*/
int i2c_read(i2c_t *obj, int address, char *data, int length, int stop)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
enum status_code tmp_status;
#if DEVICE_I2C_ASYNCH
if (i2c_active(obj)) {
/* I2C is busy with a job */
return 0;
}
#endif
struct i2c_master_packet packet;
packet.address = (address & 0xFF) >> 1;
packet.data_length = length;
packet.data = (uint8_t*)data;
packet.ten_bit_address = false;
packet.high_speed = false;
if (stop) {
tmp_status = i2c_master_read_packet_wait(&pI2C_S(obj)->master, &packet);
} else {
tmp_status = i2c_master_read_packet_wait_no_stop(&pI2C_S(obj)->master, &packet);
}
if (tmp_status == STATUS_OK) {
return length;
} else {
/* Currently, no way to track no of bytes received, so return 0 if fail */
return 0;
}
}
/** Blocking sending data.
* @param obj The i2c object
* @param address 7-bit address (last bit is 0)
* @param data The buffer for sending
* @param length Number of bytes to write
* @param stop Stop to be generated after the transfer is done
* @return Number of written bytes
*/
int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
enum status_code tmp_status;
#if DEVICE_I2C_ASYNCH
if (i2c_active(obj)) {
/* I2C is busy with a job */
return 0;
}
#endif
struct i2c_master_packet packet;
packet.address = (address & 0xFF) >> 1;
packet.data_length = length;
packet.data = (uint8_t *)data;
packet.ten_bit_address = false;
packet.high_speed = false;
if (stop) {
tmp_status = i2c_master_write_packet_wait(&pI2C_S(obj)->master, &packet);
} else {
tmp_status = i2c_master_write_packet_wait_no_stop(&pI2C_S(obj)->master, &packet);
}
if (tmp_status == STATUS_OK) {
return length;
} else {
/* Currently, no way to track no of bytes transmitted, so return 0 if fail */
return 0;
}
}
/** Reset I2C peripheral.
* @param obj The i2c object
*/
void i2c_reset(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
/* Send STOP */
i2c_stop(obj);
pI2C_S(obj)->start_pending = 0;
}
/** Write address preceded by START condition.
* @param obj The i2c object
* @param address Address to be placed
* @param rw_flag read or write flag
* @return 1 if NAK was received, 0 if ACK was received, 2 for timeout.
*/
int i2c_write_address(i2c_t *obj, int address, int rw_flag)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
enum status_code tmp_status;
SercomI2cm *const i2c_module = &(pI2C_S(obj)->master.hw->I2CM);
_i2c_master_wait_for_sync(&pI2C_S(obj)->master);
/* Set action to ACK. */
i2c_module->CTRLB.reg &= ~SERCOM_I2CM_CTRLB_ACKACT;
/* Write 7-bit address + read/write flag */
i2c_module->ADDR.reg = ((address & 0x7F) << 1) | (rw_flag & 0x01) | (0 << SERCOM_I2CM_ADDR_HS_Pos);
/* Wait for response on bus. */
tmp_status = _i2c_master_wait_for_bus(&pI2C_S(obj)->master);
/* Check for error. */
if (tmp_status != STATUS_OK) {
return I2C_ERROR_BUS_BUSY;
}
/* Check for address response error unless previous error is detected. */
tmp_status = _i2c_master_address_response(&pI2C_S(obj)->master);
if (tmp_status != STATUS_OK) {
return I2C_ERROR_NO_SLAVE;
}
return 0;
}
/** Read one byte.
* @param obj The i2c object
* @param last Acknowledge
* @return The read byte
*/
int i2c_byte_read(i2c_t *obj, int last)
{
int data = -1;
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
enum status_code tmp_status;
if (pI2C_S(obj)->mode == I2C_MODE_MASTER) {
SercomI2cm *const i2c_module = &(pI2C_S(obj)->master.hw->I2CM);
if (last) {
/* Set action to nack. */
i2c_module->CTRLB.reg |= SERCOM_I2CM_CTRLB_ACKACT;
} else {
/* Set action to ack. */
i2c_module->CTRLB.reg &= ~SERCOM_I2CM_CTRLB_ACKACT;
}
/* Check that bus ownership is not lost. */
if (!(i2c_module->STATUS.reg & SERCOM_I2CM_STATUS_BUSSTATE(2))) {
return -1; /* Return invalid data*/
}
/* Save data to buffer. */
_i2c_master_wait_for_sync(&pI2C_S(obj)->master);
data = i2c_module->DATA.reg;
/* Wait for response. */
tmp_status = _i2c_master_wait_for_bus(&pI2C_S(obj)->master);
/* Check for error. */
if (tmp_status != STATUS_OK) {
return -1; /* Return invalid data*/
}
} else {
#if DEVICE_I2CSLAVE
SercomI2cs *const i2c_hw = &(pI2C_S(obj)->slave.hw->I2CS);
/* Check direction */
if (i2c_hw->STATUS.reg & SERCOM_I2CS_STATUS_DIR) {
/* Write request from master, send NACK and return */
i2c_hw->CTRLB.reg |= SERCOM_I2CS_CTRLB_ACKACT;
i2c_hw->CTRLB.reg |= SERCOM_I2CS_CTRLB_CMD(0x3);
return -1; /* Return invalid data*/
}
if (i2c_hw->INTFLAG.reg & SERCOM_I2CS_INTFLAG_AMATCH) {
/* Request from master, Address not yet acknowledged */
i2c_hw->CTRLB.reg &= ~SERCOM_I2CS_CTRLB_ACKACT;
i2c_hw->CTRLB.reg |= SERCOM_I2CS_CTRLB_CMD(0x3);
i2c_hw->INTFLAG.reg = SERCOM_I2CS_INTFLAG_AMATCH;
}
if (last) {
/* Set action to nack. */
i2c_hw->CTRLB.reg |= SERCOM_I2CM_CTRLB_ACKACT;
} else {
/* Set action to ack. */
i2c_hw->CTRLB.reg &= ~SERCOM_I2CM_CTRLB_ACKACT;
}
/* Wait for next byte or stop condition */
tmp_status = _i2c_slave_wait_for_bus(&pI2C_S(obj)->slave);
if (tmp_status != STATUS_OK) {
/* Timeout, return */
return -1;
}
if (i2c_hw->INTFLAG.reg & SERCOM_I2CS_INTFLAG_PREC) {
/* Master sent stop condition, or repeated start, read done */
/* Clear stop flag */
i2c_hw->INTFLAG.reg = SERCOM_I2CS_INTFLAG_PREC;
return -1;
}
/* Read data */
_i2c_slave_wait_for_sync(&pI2C_S(obj)->slave);
data = i2c_hw->DATA.reg;
#endif
}
return data;
}
/** Write one byte.
* @param obj The i2c object
* @param data Byte to be written
* @return 1 if NAK was received, 0 if ACK was received, 2 for timeout.
*/
int i2c_byte_write(i2c_t *obj, int data)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
enum status_code tmp_status;
data = data & 0xFF;
if (pI2C_S(obj)->mode == I2C_MODE_MASTER) {
SercomI2cm *const i2c_module = &(pI2C_S(obj)->master.hw->I2CM);
if (pI2C_S(obj)->start_pending) {
pI2C_S(obj)->start_pending = 0;
/* Write address */
return i2c_write_address(obj, (data >> 1), (data & 0x01));
} else {
/* Write data */
/* Check that bus ownership is not lost. */
if (!(i2c_module->STATUS.reg & SERCOM_I2CM_STATUS_BUSSTATE(2))) {
return I2C_ERROR_NO_SLAVE;
}
/* Write byte to slave. */
_i2c_master_wait_for_sync(&pI2C_S(obj)->master);
i2c_module->DATA.reg = data;
/* Wait for response. */
tmp_status = _i2c_master_wait_for_bus(&pI2C_S(obj)->master);
/* Check for error. */
if (tmp_status != STATUS_OK) {
return I2C_ERROR_BUS_BUSY;
}
/* Check for NACK from slave. */
if (i2c_module->STATUS.reg & SERCOM_I2CM_STATUS_RXNACK) {
/* Return bad data value. */
return I2C_ERROR_NO_SLAVE;
}
}
} else {
#if DEVICE_I2CSLAVE
SercomI2cs *const i2c_hw = &(pI2C_S(obj)->slave.hw->I2CS);
if (i2c_hw->INTFLAG.reg & SERCOM_I2CS_INTFLAG_AMATCH) {
/* Read request from master, Address not yet acknowledged */
i2c_hw->CTRLB.reg &= ~SERCOM_I2CS_CTRLB_ACKACT;
i2c_hw->CTRLB.reg |= SERCOM_I2CS_CTRLB_CMD(0x3);
i2c_hw->INTFLAG.reg = SERCOM_I2CS_INTFLAG_AMATCH;
}
/* Write data */
_i2c_slave_wait_for_sync(&pI2C_S(obj)->slave);
i2c_hw->DATA.reg = data;
/* Wait for response from master */
tmp_status = _i2c_slave_wait_for_bus(&pI2C_S(obj)->slave);
if (tmp_status != STATUS_OK) {
/* Timeout, return */
return I2C_ERROR_BUS_BUSY;
}
if (i2c_hw->STATUS.reg & SERCOM_I2CS_STATUS_RXNACK) {
/* NACK from master, abort */
/* Release line */
i2c_hw->CTRLB.reg |= SERCOM_I2CS_CTRLB_CMD(0x02);
return I2C_ERROR_NO_SLAVE;
}
#endif
}
return 0;
}
#if DEVICE_I2CSLAVE
/**
* \defgroup SynchI2C Synchronous I2C Hardware Abstraction Layer for slave
* @{
*/
/** Configure I2C as slave or master.
* @param obj The I2C object
* @param enable_slave configure I2C in slave mode or not
* @return void
*/
void i2c_slave_mode(i2c_t *obj, int enable_slave)
{
int i;
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
uint32_t mux_func[2];
uint32_t sercom_index = _sercom_get_sercom_inst_index(pI2C_S(obj)->master.hw);
for (i=0; i<2; i++) {
mux_func[i] = pinmap_function_sercom(pI2C_S(obj)->pins[0], sercom_index);
if (mux_func[i] == (uint32_t)NC) return;
}
if (enable_slave) {
/* Disable I2C Master module if active */
i2c_master_disable(&pI2C_S(obj)->master);
struct i2c_slave_config config_i2c_slave;
i2c_slave_get_config_defaults(&config_i2c_slave);
/* SERCOM PAD0 - SDA */
config_i2c_slave.pinmux_pad0 = (pI2C_S(obj)->pins[0] << 16) | (mux_func[0] & 0xFFFF);
/* SERCOM PAD1 - SCL */
config_i2c_slave.pinmux_pad1 = (pI2C_S(obj)->pins[1] << 16) | (mux_func[1] & 0xFFFF);
i2c_slave_init(&pI2C_S(obj)->slave, pI2C_S(obj)->master.hw, &config_i2c_slave);
pI2C_S(obj)->mode = I2C_MODE_SLAVE;
i2c_slave_enable(&pI2C_S(obj)->slave);
} else {
if ((pI2C_S(obj)->master.hw) && (pI2C_S(obj)->mode == I2C_MODE_MASTER)) {
/* Already configured, enable and return */
i2c_master_enable(&pI2C_S(obj)->master);
return;
} else if ((pI2C_S(obj)->slave.hw) && (pI2C_S(obj)->mode == I2C_MODE_SLAVE)) {
/* Disable slave */
i2c_slave_disable(&pI2C_S(obj)->slave);
}
struct i2c_master_config config_i2c_master;
/* SERCOM PAD0 - SDA */
config_i2c_master.pinmux_pad0 = (pI2C_S(obj)->pins[0] << 16) | (mux_func[0] & 0xFFFF);
/* SERCOM PAD1 - SCL */
config_i2c_master.pinmux_pad1 = (pI2C_S(obj)->pins[1] << 16) | (mux_func[1] & 0xFFFF);
/* Baud rate */
config_i2c_master.baud_rate = pI2C_S(obj)->baud_rate / 1000;
while(i2c_master_init(&pI2C_S(obj)->master, pI2C_S(obj)->master.hw, &config_i2c_master) != STATUS_OK);
pI2C_S(obj)->mode = I2C_MODE_MASTER;
i2c_master_enable(&pI2C_S(obj)->master);
}
}
/** Check to see if the I2C slave has been addressed.
* @param obj The I2C object
* @return The status - 1 - read addresses, 2 - write to all slaves,
* 3 write addressed, 0 - the slave has not been addressed
*/
int i2c_slave_receive(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->slave.hw);
SercomI2cs *const i2c_module = &(pI2C_S(obj)->slave.hw->I2CS);
if (i2c_module->INTFLAG.reg & SERCOM_I2CS_INTFLAG_AMATCH) {
if (i2c_module->STATUS.reg & SERCOM_I2CS_STATUS_DIR) {
/* Slave is read addressed */
return 1;
} else {
if (!(i2c_module->DATA.reg & 0xFF)) {
/* General call address detected */
return 2;
} else {
/* Slave is write addressed */
return 3;
}
}
}
return 0;
}
/** Blocking reading data.
* @param obj The i2c slave object
* @param data The buffer for receiving
* @param length Number of bytes to read
* @return Number of read bytes
*/
int i2c_slave_read(i2c_t *obj, char *data, int length)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->slave.hw);
if (!data || !length) return 0;
enum status_code tmp_status;
struct i2c_slave_packet packet;
packet.data_length = length;
packet.data = (uint8_t*)data;
tmp_status = i2c_slave_read_packet_wait(&pI2C_S(obj)->slave, &packet);
if (tmp_status == STATUS_OK) {
return length;
} else {
/* Currently, no way to track no of bytes transmitted, so return 0 */
return 0;
}
}
/** Blocking writing data.
* @param obj The i2c slave object
* @param data The buffer for transmitting
* @param length Number of bytes to write
* @return Number of bytes written
*/
int i2c_slave_write(i2c_t *obj, const char *data, int length)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->slave.hw);
if (!data || !length) return 0;
enum status_code tmp_status;
struct i2c_slave_packet packet;
packet.data_length = length;
packet.data = (uint8_t *)data;
tmp_status = i2c_slave_write_packet_wait(&pI2C_S(obj)->slave, &packet);
if (tmp_status == STATUS_OK) {
return length;
} else {
/* Currently, no way to track no of bytes transmitted, so return 0 */
return 0;
}
}
/** Configure I2C slave address.
* @param obj The I2C object
* @param idx Currently not used
* @param address The address to be set
* @param mask Currently not used
*/
void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->slave.hw);
/* Disable I2C Module */
i2c_slave_disable(&pI2C_S(obj)->slave);
SercomI2cs *const i2c_hw = &(pI2C_S(obj)->slave.hw->I2CS);
address = (address & 0xFF) >> 1;
if (!mask) {
mask = (0xFE >> 1);
}
/* Set the address and address mask */
i2c_hw->ADDR.reg = (address << SERCOM_I2CS_ADDR_ADDR_Pos) |
(mask << SERCOM_I2CS_ADDR_ADDRMASK_Pos) |
(0 << SERCOM_I2CS_ADDR_TENBITEN_Pos) |
(1 << SERCOM_I2CS_ADDR_GENCEN_Pos);
/* Enable I2C Module */
i2c_slave_enable(&pI2C_S(obj)->slave);
}
#endif /* DEVICE_I2CSLAVE */
/**@}*/
#if DEVICE_I2C_ASYNCH
/**
* \defgroup AsynchI2C Asynchronous I2C Hardware Abstraction Layer
* @{
*/
/**
* \internal
* Callback for transfer finish.
*
* \param[in,out] module Pointer to SPI software instance struct
*/
void i2c_transfer_complete_callback(struct i2c_master_module *const module)
{
uint32_t sercom_index = _sercom_get_sercom_inst_index(module->hw);
if (sercom_index >= SERCOM_INST_NUM) {
/* TODO: Abort operation */
return;
}
i2c_t *obj = (i2c_t*)i2c_instances[sercom_index];
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_WRITE_COMPLETE);
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_READ_COMPLETE);
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_ERROR);
/* Call the handler function */
if (pI2C_S(obj)->handler) {
((I2CHandler)pI2C_S(obj)->handler)();
}
}
/**
* \internal
* Callback for write complete. Initiate read from here.
*
* \param[in,out] module Pointer to SPI software instance struct
*/
void i2c_write_complete_callback(struct i2c_master_module *const module)
{
uint32_t sercom_index = _sercom_get_sercom_inst_index(module->hw);
if (sercom_index >= SERCOM_INST_NUM) {
/* TODO: Abort operation */
return;
}
i2c_t *obj = (i2c_t*)i2c_instances[sercom_index];
if (!(pI2C_S(obj)->rd_packet.data) || (pI2C_S(obj)->rd_packet.data_length == 0)) {
/* Call the handler function */
i2c_transfer_complete_callback(module);
} else {
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_WRITE_COMPLETE);
/* Register read complete callback */
i2c_master_register_callback(&pI2C_S(obj)->master, i2c_transfer_complete_callback, I2C_MASTER_CALLBACK_READ_COMPLETE);
i2c_master_enable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_READ_COMPLETE);
/* Initiate read operation */
if (pI2C_S(obj)->master.send_stop) {
i2c_master_read_packet_job(&pI2C_S(obj)->master,&pI2C_S(obj)->rd_packet);
} else {
i2c_master_read_packet_job_no_stop(&pI2C_S(obj)->master, &pI2C_S(obj)->rd_packet);
}
}
}
/** Start i2c asynchronous transfer.
* @param obj The I2C object
* @param tx The buffer to send
* @param tx_length The number of words to transmit
* @param rx The buffer to receive
* @param rx_length The number of words to receive
* @param address The address to be set - 7bit or 9 bit
* @param stop If true, stop will be generated after the transfer is done
* @param handler The I2C IRQ handler to be set
* @param hint DMA hint usage
*/
void i2c_transfer_asynch(i2c_t *obj, const void *tx, size_t tx_length, void *rx, size_t rx_length, uint32_t address, uint32_t stop, uint32_t handler, uint32_t event, DMAUsage hint)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
/* Return if in Slave mode */
if (pI2C_S(obj)->mode != I2C_MODE_MASTER) return;
uint32_t sercom_index = _sercom_get_sercom_inst_index(pI2C_S(obj)->master.hw);
/* Init i2c packet. */
pI2C_S(obj)->wr_packet.address = address >> 1;
pI2C_S(obj)->wr_packet.data_length = tx_length;
pI2C_S(obj)->wr_packet.data = (uint8_t *)tx;
pI2C_S(obj)->rd_packet.address = address >> 1;
pI2C_S(obj)->rd_packet.data_length = rx_length;
pI2C_S(obj)->rd_packet.data = rx;
/* Save event mask and handler function pointer */
pI2C_S(obj)->events = event;
pI2C_S(obj)->handler = handler;
/* TODO: Current implementation is interrupt based only */
/* Set interrupt handler to default handler of ASF */
/* Enable interrupt */
NVIC_SetVector((IRQn_Type)((uint32_t)SERCOM0_IRQn + sercom_index), sercom_irq_handlers[sercom_index]);
NVIC_EnableIRQ((IRQn_Type)((uint32_t)SERCOM0_IRQn + sercom_index));
/* Register callbacks */
i2c_master_register_callback(&pI2C_S(obj)->master, i2c_transfer_complete_callback, I2C_MASTER_CALLBACK_ERROR);
i2c_master_enable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_ERROR);
if (tx && tx_length) {
i2c_master_register_callback(&pI2C_S(obj)->master, i2c_write_complete_callback, I2C_MASTER_CALLBACK_WRITE_COMPLETE);
i2c_master_enable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_WRITE_COMPLETE);
/* Start I2C write */
if (stop) {
i2c_master_write_packet_job(&pI2C_S(obj)->master, &pI2C_S(obj)->wr_packet);
} else {
i2c_master_write_packet_job_no_stop(&pI2C_S(obj)->master, &pI2C_S(obj)->wr_packet);
}
} else if (rx && rx_length) {
i2c_master_register_callback(&pI2C_S(obj)->master, i2c_transfer_complete_callback, I2C_MASTER_CALLBACK_READ_COMPLETE);
i2c_master_enable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_READ_COMPLETE);
/* Start I2C read */
if (stop) {
i2c_master_read_packet_job(&pI2C_S(obj)->master,&pI2C_S(obj)->rd_packet);
} else {
i2c_master_read_packet_job_no_stop(&pI2C_S(obj)->master, &pI2C_S(obj)->rd_packet);
}
} else {
/* Nothing to transfer, invoke callback */
i2c_transfer_complete_callback(&pI2C_S(obj)->master);
}
}
/** The asynchronous IRQ handler
* @param obj The I2C object which holds the transfer information
* @return event flags if a transfer termination condition was met or 0 otherwise.
*/
uint32_t i2c_irq_handler_asynch(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
uint32_t event_mask = pI2C_S(obj)->events;
/* TODO: Current implementation is interrupt based only */
switch (pI2C_S(obj)->master.status) {
case STATUS_OK:
/* Transfer is complete */
return (I2C_EVENT_TRANSFER_COMPLETE & event_mask);
case STATUS_ERR_BAD_ADDRESS:
/* Received a NACK */
return (I2C_EVENT_ERROR_NO_SLAVE & event_mask);
case STATUS_ERR_PACKET_COLLISION:
/* An error occurred in between transfer */
return (I2C_EVENT_ERROR & event_mask);
default:
return 0;
}
//return 0;
}
/** Attempts to determine if I2C peripheral is already in use.
* @param obj The I2C object
* @return non-zero if the I2C module is active or zero if it is not
*/
uint8_t i2c_active(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
return (pI2C_S(obj)->master.status == STATUS_BUSY);
}
/** Abort ongoing asynchronous transaction.
* @param obj The I2C object
*/
void i2c_abort_asynch(i2c_t *obj)
{
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(pI2C_S(obj)->master.hw);
/* Pointer to the hardware module instance */
SercomI2cm *const i2c_module = &(pI2C_S(obj)->master.hw->I2CM);
/* Abort ongoing job */
/* Stop packet operation */
i2c_module->INTENCLR.reg = SERCOM_I2CM_INTENCLR_MB | SERCOM_I2CM_INTENCLR_SB;
pI2C_S(obj)->master.buffer_length = 0;
pI2C_S(obj)->master.buffer_remaining = 0;
/* Send nack and stop command unless arbitration is lost */
if ((pI2C_S(obj)->master.status != STATUS_ERR_PACKET_COLLISION) && pI2C_S(obj)->master.send_stop) {
_i2c_master_wait_for_sync(&pI2C_S(obj)->master);
i2c_module->CTRLB.reg |= SERCOM_I2CM_CTRLB_ACKACT | SERCOM_I2CM_CTRLB_CMD(3);
}
/* Disable any registered callback */
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_WRITE_COMPLETE);
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_READ_COMPLETE);
i2c_master_disable_callback(&pI2C_S(obj)->master, I2C_MASTER_CALLBACK_ERROR);
pI2C_S(obj)->master.status = STATUS_ABORTED;
}
#endif
| 30.737952 | 180 | 0.638837 | [
"object"
] |
c89d8515bbed0f45ca68fad7887b333e5941e2da | 89,002 | c | C | libraries/mpu9250/rc_mpu9250.c | tkurbad/Robotics_Cape_Installer | 1dfcf302a5f76e68dc005673d411002181b73ce9 | [
"MIT"
] | 1 | 2017-11-07T19:12:33.000Z | 2017-11-07T19:12:33.000Z | libraries/mpu9250/rc_mpu9250.c | glebshendrik/Robotics_Cape_Installer | 1dfcf302a5f76e68dc005673d411002181b73ce9 | [
"MIT"
] | null | null | null | libraries/mpu9250/rc_mpu9250.c | glebshendrik/Robotics_Cape_Installer | 1dfcf302a5f76e68dc005673d411002181b73ce9 | [
"MIT"
] | null | null | null | /*******************************************************************************
* mpu9250.c
*
* This is a collection of high-level functions to control the
* MPU9250 from a BeagleBone Black as configured on the Robotics Cape.
* Credit to Kris Winer most of the framework and register definitions.
*******************************************************************************/
#define _GNU_SOURCE
#include "../rc_defs.h"
#include "../roboticscape.h"
#include "../preprocessor_macros.h"
#include "rc_mpu9250_defs.h"
#include "dmp_firmware.h"
#include "dmpKey.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
// macros
#define ARRAY_SIZE(array) sizeof(array)/sizeof(array[0])
#define min(a, b) ((a < b) ? a : b)
#define DEG_TO_RAD 0.0174532925199
#define RAD_TO_DEG 57.295779513
#define PI M_PI
#define TWO_PI (2.0 * M_PI)
// there should be 28 or 35 bytes in the FIFO if the magnetometer is disabled
// or enabled.
#define FIFO_LEN_NO_MAG 28
#define FIFO_LEN_MAG 35
// error threshold checks
#define QUAT_ERROR_THRESH (1L<<16) // very precise threshold
#define QUAT_MAG_SQ_NORMALIZED (1L<<28)
#define QUAT_MAG_SQ_MIN (QUAT_MAG_SQ_NORMALIZED - QUAT_ERROR_THRESH)
#define QUAT_MAG_SQ_MAX (QUAT_MAG_SQ_NORMALIZED + QUAT_ERROR_THRESH)
#define GYRO_CAL_THRESH 50
#define GYRO_OFFSET_THRESH 500
// Thread control
pthread_mutex_t rc_imu_read_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t rc_imu_read_condition = PTHREAD_COND_INITIALIZER;
/*******************************************************************************
* Local variables
*******************************************************************************/
rc_imu_config_t config;
int bypass_en;
int dmp_en;
int packet_len;
pthread_t imu_interrupt_thread;
int thread_running_flag;
struct sched_param params;
void (*imu_interrupt_func)(); // pointer to user's interrupt function
int interrupt_func_set;
float mag_factory_adjust[3];
float mag_offsets[3];
float mag_scales[3];
int last_read_successful;
uint64_t last_interrupt_timestamp_nanos;
rc_imu_data_t* data_ptr;
int shutdown_interrupt_thread = 0;
// for magnetometer Yaw filtering
rc_filter_t low_pass, high_pass;
/*******************************************************************************
* config functions for internal use only
*******************************************************************************/
int reset_mpu9250();
int set_gyro_fsr(rc_gyro_fsr_t fsr, rc_imu_data_t* data);
int set_accel_fsr(rc_accel_fsr_t, rc_imu_data_t* data);
int set_gyro_dlpf(rc_gyro_dlpf_t);
int set_accel_dlpf(rc_accel_dlpf_t);
int initialize_magnetometer();
int power_down_magnetometer();
int mpu_set_bypass(unsigned char bypass_on);
int mpu_write_mem(unsigned short mem_addr, unsigned short length,\
unsigned char *data);
int mpu_read_mem(unsigned short mem_addr, unsigned short length,\
unsigned char *data);
int dmp_load_motion_driver_firmware();
int dmp_set_orientation(unsigned short orient);
int dmp_enable_gyro_cal(unsigned char enable);
int dmp_enable_lp_quat(unsigned char enable);
int dmp_enable_6x_lp_quat(unsigned char enable);
int mpu_reset_fifo(void);
int mpu_set_sample_rate(int rate);
int dmp_set_fifo_rate(unsigned short rate);
int dmp_enable_feature(unsigned short mask);
int mpu_set_dmp_state(unsigned char enable);
int set_int_enable(unsigned char enable);
int dmp_set_interrupt_mode(unsigned char mode);
int read_dmp_fifo(rc_imu_data_t* data);
int data_fusion(rc_imu_data_t* data);
int load_gyro_offets();
int load_mag_calibration();
int write_mag_cal_to_disk(float offsets[3], float scale[3]);
void* imu_interrupt_handler(void* ptr);
int check_quaternion_validity(unsigned char* raw, int i);
/*******************************************************************************
* rc_imu_config_t rc_default_imu_config()
*
* returns reasonable default configuration values
*******************************************************************************/
rc_imu_config_t rc_default_imu_config(){
rc_imu_config_t conf;
// general stuff
conf.accel_fsr = A_FSR_4G;
conf.gyro_fsr = G_FSR_1000DPS;
conf.gyro_dlpf = GYRO_DLPF_92;
conf.accel_dlpf = ACCEL_DLPF_92;
conf.enable_magnetometer = 0;
// DMP stuff
conf.dmp_sample_rate = 100;
conf.orientation = ORIENTATION_Z_UP;
conf.compass_time_constant = 5.0;
conf.dmp_interrupt_priority = sched_get_priority_max(SCHED_FIFO)-1;
conf.show_warnings = 0;
return conf;
}
/*******************************************************************************
* int rc_set_imu_config_to_defaults(*rc_imu_config_t);
*
* resets an rc_imu_config_t struct to default values
*******************************************************************************/
int rc_set_imu_config_to_defaults(rc_imu_config_t *conf){
*conf = rc_default_imu_config();
return 0;
}
/*******************************************************************************
* int rc_initialize_imu(rc_imu_config_t conf)
*
* Set up the imu for one-shot sampling of sensor data by user
*******************************************************************************/
int rc_initialize_imu(rc_imu_data_t *data, rc_imu_config_t conf){
uint8_t c;
// make sure the bus is not currently in use by another thread
// do not proceed to prevent interfering with that process
if(rc_i2c_get_in_use_state(IMU_BUS)){
printf("i2c bus claimed by another process\n");
printf("Continuing with rc_initialize_imu() anyway.\n");
}
// if it is not claimed, start the i2c bus
if(rc_i2c_init(IMU_BUS, IMU_ADDR)<0){
fprintf(stderr,"failed to initialize i2c bus\n");
return -1;
}
// claiming the bus does no guarantee other code will not interfere
// with this process, but best to claim it so other code can check
// like we did above
rc_i2c_claim_bus(IMU_BUS);
// update local copy of config struct with new values
config=conf;
// restart the device so we start with clean registers
if(reset_mpu9250()<0){
fprintf(stderr,"ERROR: failed to reset_mpu9250\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
//check the who am i register to make sure the chip is alive
if(rc_i2c_read_byte(IMU_BUS, WHO_AM_I_MPU9250, &c)<0){
fprintf(stderr,"Reading WHO_AM_I_MPU9250 register failed\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(c!=0x71){
fprintf(stderr,"mpu9250 WHO AM I register should return 0x71\n");
fprintf(stderr,"WHO AM I returned: 0x%x\n", c);
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// load in gyro calibration offsets from disk
if(load_gyro_offets()<0){
fprintf(stderr,"ERROR: failed to load gyro calibration offsets\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// Set sample rate = 1000/(1 + SMPLRT_DIV)
// here we use a divider of 0 for 1khz sample
if(rc_i2c_write_byte(IMU_BUS, SMPLRT_DIV, 0x00)){
fprintf(stderr,"I2C bus write error\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// set full scale ranges and filter constants
if(set_gyro_fsr(conf.gyro_fsr, data)){
fprintf(stderr,"failed to set gyro fsr\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(set_accel_fsr(conf.accel_fsr, data)){
fprintf(stderr,"failed to set accel fsr\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(set_gyro_dlpf(conf.gyro_dlpf)){
fprintf(stderr,"failed to set gyro dlpf\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(set_accel_dlpf(conf.accel_dlpf)){
fprintf(stderr,"failed to set accel_dlpf\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// initialize the magnetometer too if requested in config
if(conf.enable_magnetometer){
if(initialize_magnetometer()){
fprintf(stderr,"failed to initialize magnetometer\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
}
else power_down_magnetometer();
// all done!!
rc_i2c_release_bus(IMU_BUS);
return 0;
}
/*******************************************************************************
* int rc_read_accel_data(rc_imu_data_t* data)
*
* Always reads in latest accelerometer values. The sensor
* self-samples at 1khz and this retrieves the latest data.
*******************************************************************************/
int rc_read_accel_data(rc_imu_data_t *data){
// new register data stored here
uint8_t raw[6];
// set the device address
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// Read the six raw data registers into data array
if(rc_i2c_read_bytes(IMU_BUS, ACCEL_XOUT_H, 6, &raw[0])<0){
return -1;
}
// Turn the MSB and LSB into a signed 16-bit value
data->raw_accel[0] = (int16_t)(((uint16_t)raw[0]<<8)|raw[1]);
data->raw_accel[1] = (int16_t)(((uint16_t)raw[2]<<8)|raw[3]);
data->raw_accel[2] = (int16_t)(((uint16_t)raw[4]<<8)|raw[5]);
// Fill in real unit values
data->accel[0] = data->raw_accel[0] * data->accel_to_ms2;
data->accel[1] = data->raw_accel[1] * data->accel_to_ms2;
data->accel[2] = data->raw_accel[2] * data->accel_to_ms2;
return 0;
}
/*******************************************************************************
* int rc_read_gyro_data(rc_imu_data_t* data)
*
* Always reads in latest gyroscope values. The sensor self-samples
* at 1khz and this retrieves the latest data.
*******************************************************************************/
int rc_read_gyro_data(rc_imu_data_t *data){
// new register data stored here
uint8_t raw[6];
// set the device address
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// Read the six raw data registers into data array
if(rc_i2c_read_bytes(IMU_BUS, GYRO_XOUT_H, 6, &raw[0])<0){
return -1;
}
// Turn the MSB and LSB into a signed 16-bit value
data->raw_gyro[0] = (int16_t)(((int16_t)raw[0]<<8)|raw[1]);
data->raw_gyro[1] = (int16_t)(((int16_t)raw[2]<<8)|raw[3]);
data->raw_gyro[2] = (int16_t)(((int16_t)raw[4]<<8)|raw[5]);
// Fill in real unit values
data->gyro[0] = data->raw_gyro[0] * data->gyro_to_degs;
data->gyro[1] = data->raw_gyro[1] * data->gyro_to_degs;
data->gyro[2] = data->raw_gyro[2] * data->gyro_to_degs;
return 0;
}
/*******************************************************************************
* int rc_read_mag_data(rc_imu_data_t* data)
*
* Checks if there is new magnetometer data and reads it in if true.
* Magnetometer only updates at 100hz, if there is no new data then
* the values in rc_imu_data_t struct are left alone.
*******************************************************************************/
int rc_read_mag_data(rc_imu_data_t* data){
uint8_t st1;
uint8_t raw[7];
int16_t adc[3];
float factory_cal_data[3];
if(config.enable_magnetometer==0){
fprintf(stderr,"ERROR: can't read magnetometer unless it is enabled in \n");
fprintf(stderr,"rc_imu_config_t struct before calling rc_initialize_imu\n");
return -1;
}
// magnetometer is actually a separate device with its
// own address inside the mpu9250
// MPU9250 was put into passthrough mode
rc_i2c_set_device_address(IMU_BUS, AK8963_ADDR);
// read the data ready bit to see if there is new data
if(rc_i2c_read_byte(IMU_BUS, AK8963_ST1, &st1)<0){
fprintf(stderr,"ERROR reading Magnetometer, i2c_bypass is probably not set\n");
return -1;
}
#ifdef DEBUG
printf("st1: %d", st1);
#endif
if(!(st1&MAG_DATA_READY)){
#ifdef DEBUG
printf("no new data\n");
#endif
return 0;
}
// Read the six raw data regs into data array
if(rc_i2c_read_bytes(IMU_BUS,AK8963_XOUT_L,7,&raw[0])<0){
printf("rc_read_mag_data failed\n");
return -1;
}
// check if the readings saturated such as because
// of a local field source, discard data if so
if(raw[6]&MAGNETOMETER_SATURATION){
fprintf(stderr,"ERROR: magnetometer saturated\n");
return -1;
}
// Turn the MSB and LSB into a signed 16-bit value
// Data stored as little Endian
adc[0] = (int16_t)(((int16_t)raw[1]<<8) | raw[0]);
adc[1] = (int16_t)(((int16_t)raw[3]<<8) | raw[2]);
adc[2] = (int16_t)(((int16_t)raw[5]<<8) | raw[4]);
#ifdef DEBUG
printf("raw mag:%d %d %d\n", adc[0], adc[1], adc[2]);
#endif
// multiply by the sensitivity adjustment and convert to units of uT micro
// Teslas. Also correct the coordinate system as someone in invensense
// thought it would be bright idea to have the magnetometer coordiate
// system aligned differently than the accelerometer and gyro.... -__-
factory_cal_data[0] = adc[1] * mag_factory_adjust[1] * MAG_RAW_TO_uT;
factory_cal_data[1] = adc[0] * mag_factory_adjust[0] * MAG_RAW_TO_uT;
factory_cal_data[2] = -adc[2] * mag_factory_adjust[2] * MAG_RAW_TO_uT;
// now apply out own calibration, but first make sure we don't accidentally
// multiply by zero in case of uninitialized scale factors
if(mag_scales[0]==0.0) mag_scales[0]=1.0;
if(mag_scales[1]==0.0) mag_scales[1]=1.0;
if(mag_scales[2]==0.0) mag_scales[2]=1.0;
data->mag[0] = (factory_cal_data[0]-mag_offsets[0])*mag_scales[0];
data->mag[1] = (factory_cal_data[1]-mag_offsets[1])*mag_scales[1];
data->mag[2] = (factory_cal_data[2]-mag_offsets[2])*mag_scales[2];
return 0;
}
/*******************************************************************************
* int rc_read_imu_temp(rc_imu_data_t* data)
*
* reads the latest temperature of the imu.
*******************************************************************************/
int rc_read_imu_temp(rc_imu_data_t* data){
uint16_t adc;
// set device address
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// Read the two raw data registers
if(rc_i2c_read_word(IMU_BUS, TEMP_OUT_H, &adc)<0){
fprintf(stderr,"failed to read IMU temperature registers\n");
return -1;
}
// convert to real units
data->temp = 21.0 + adc/TEMP_SENSITIVITY;
return 0;
}
/*******************************************************************************
* int reset_mpu9250()
*
* sets the reset bit in the power management register which restores
* the device to defualt settings. a 0.1 second wait is also included
* to let the device compelete the reset process.
*******************************************************************************/
int reset_mpu9250(){
// disable the interrupt to prevent it from doing things while we reset
shutdown_interrupt_thread = 1;
// set the device address
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// write the reset bit
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, H_RESET)){
// wait and try again
rc_usleep(10000);
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, H_RESET)){
fprintf(stderr,"I2C write to MPU9250 Failed\n");
return -1;
}
}
// make sure all other power management features are off
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, 0)){
// wait and try again
rc_usleep(10000);
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, 0)){
fprintf(stderr,"I2C write to MPU9250 Failed\n");
return -1;
}
}
rc_usleep(100000);
return 0;
}
/*******************************************************************************
* int set_gyro_fsr(rc_gyro_fsr_t fsr, rc_imu_data_t* data)
*
* set gyro full scale range and update conversion ratio
*******************************************************************************/
int set_gyro_fsr(rc_gyro_fsr_t fsr, rc_imu_data_t* data){
uint8_t c;
switch(fsr){
case G_FSR_250DPS:
c = GYRO_FSR_CFG_250 | FCHOICE_B_DLPF_EN;
data->gyro_to_degs = 250.0/32768.0;
break;
case G_FSR_500DPS:
c = GYRO_FSR_CFG_500 | FCHOICE_B_DLPF_EN;
data->gyro_to_degs = 500.0/32768.0;
break;
case G_FSR_1000DPS:
c = GYRO_FSR_CFG_1000 | FCHOICE_B_DLPF_EN;
data->gyro_to_degs = 1000.0/32768.0;
break;
case G_FSR_2000DPS:
c = GYRO_FSR_CFG_2000 | FCHOICE_B_DLPF_EN;
data->gyro_to_degs = 2000.0/32768.0;
break;
default:
fprintf(stderr,"invalid gyro fsr\n");
return -1;
}
return rc_i2c_write_byte(IMU_BUS, GYRO_CONFIG, c);
}
/*******************************************************************************
* int set_accel_fsr(rc_accel_fsr_t fsr, rc_imu_data_t* data)
*
* set accelerometer full scale range and update conversion ratio
*******************************************************************************/
int set_accel_fsr(rc_accel_fsr_t fsr, rc_imu_data_t* data){
uint8_t c;
switch(fsr){
case A_FSR_2G:
c = ACCEL_FSR_CFG_2G;
data->accel_to_ms2 = 9.80665*2.0/32768.0;
break;
case A_FSR_4G:
c = ACCEL_FSR_CFG_4G;
data->accel_to_ms2 = 9.80665*4.0/32768.0;
break;
case A_FSR_8G:
c = ACCEL_FSR_CFG_8G;
data->accel_to_ms2 = 9.80665*8.0/32768.0;
break;
case A_FSR_16G:
c = ACCEL_FSR_CFG_16G;
data->accel_to_ms2 = 9.80665*16.0/32768.0;
break;
default:
fprintf(stderr,"invalid accel fsr\n");
return -1;
}
return rc_i2c_write_byte(IMU_BUS, ACCEL_CONFIG, c);
}
/*******************************************************************************
* int set_gyro_dlpf(rc_gyro_dlpf_t dlpf)
*
* Set GYRO low pass filter constants. This is the same register as
* the fifo overflow mode so we set it to keep the newest data too.
*******************************************************************************/
int set_gyro_dlpf(rc_gyro_dlpf_t dlpf){
uint8_t c = FIFO_MODE_REPLACE_OLD;
switch(dlpf){
case GYRO_DLPF_OFF:
c |= 1;
break;
case GYRO_DLPF_184:
c |= 1;
break;
case GYRO_DLPF_92:
c |= 2;
break;
case GYRO_DLPF_41:
c |= 3;
break;
case GYRO_DLPF_20:
c |= 4;
break;
case GYRO_DLPF_10:
c |= 5;
break;
case GYRO_DLPF_5:
c |= 6;
break;
default:
fprintf(stderr,"invalid gyro_dlpf\n");
return -1;
}
return rc_i2c_write_byte(IMU_BUS, CONFIG, c);
}
/*******************************************************************************
* int set_accel_dlpf(rc_accel_dlpf_t dlpf)
*
* Set accel low pass filter constants. This is the same register as
* the sample rate. We set it at 1khz as 4khz is unnecessary.
*******************************************************************************/
int set_accel_dlpf(rc_accel_dlpf_t dlpf){
uint8_t c = ACCEL_FCHOICE_1KHZ | BIT_FIFO_SIZE_1024;
switch(dlpf){
case ACCEL_DLPF_OFF:
c |= 7;
break;
case ACCEL_DLPF_184:
c |= 1;
break;
case ACCEL_DLPF_92:
c |= 2;
break;
case ACCEL_DLPF_41:
c |= 3;
break;
case ACCEL_DLPF_20:
c |= 4;
break;
case ACCEL_DLPF_10:
c |= 5;
break;
case ACCEL_DLPF_5:
c |= 6;
break;
default:
fprintf(stderr,"invalid gyro_dlpf\n");
return -1;
}
return rc_i2c_write_byte(IMU_BUS, ACCEL_CONFIG_2, c);
}
/*******************************************************************************
* int initialize_magnetometer()
*
* configure the magnetometer for 100hz reads, also reads in the factory
* sensitivity values into the global variables;
*******************************************************************************/
int initialize_magnetometer(){
uint8_t raw[3]; // calibration data stored here
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// Enable i2c bypass to allow talking to magnetometer
if(mpu_set_bypass(1)){
fprintf(stderr,"failed to set mpu9250 into bypass i2c mode\n");
return -1;
}
// magnetometer is actually a separate device with its
// own address inside the mpu9250
rc_i2c_set_device_address(IMU_BUS, AK8963_ADDR);
// Power down magnetometer
rc_i2c_write_byte(IMU_BUS, AK8963_CNTL, MAG_POWER_DN);
rc_usleep(1000);
// Enter Fuse ROM access mode
rc_i2c_write_byte(IMU_BUS, AK8963_CNTL, MAG_FUSE_ROM);
rc_usleep(1000);
// Read the xyz sensitivity adjustment values
if(rc_i2c_read_bytes(IMU_BUS, AK8963_ASAX, 3, &raw[0])<0){
fprintf(stderr,"failed to read magnetometer adjustment register\n");
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
mpu_set_bypass(0);
return -1;
}
// Return sensitivity adjustment values
mag_factory_adjust[0] = (raw[0]-128)/256.0 + 1.0;
mag_factory_adjust[1] = (raw[1]-128)/256.0 + 1.0;
mag_factory_adjust[2] = (raw[2]-128)/256.0 + 1.0;
// Power down magnetometer again
rc_i2c_write_byte(IMU_BUS, AK8963_CNTL, MAG_POWER_DN);
rc_usleep(100);
// Configure the magnetometer for 16 bit resolution
// and continuous sampling mode 2 (100hz)
uint8_t c = MSCALE_16|MAG_CONT_MES_2;
rc_i2c_write_byte(IMU_BUS, AK8963_CNTL, c);
rc_usleep(100);
// go back to configuring the IMU, leave bypass on
rc_i2c_set_device_address(IMU_BUS,IMU_ADDR);
// load in magnetometer calibration
load_mag_calibration();
return 0;
}
/*******************************************************************************
* int power_down_magnetometer()
*
* Make sure the magnetometer is off.
*******************************************************************************/
int power_down_magnetometer(){
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// Enable i2c bypass to allow talking to magnetometer
if(mpu_set_bypass(1)){
fprintf(stderr,"failed to set mpu9250 into bypass i2c mode\n");
return -1;
}
// magnetometer is actually a separate device with its
// own address inside the mpu9250
rc_i2c_set_device_address(IMU_BUS, AK8963_ADDR);
// Power down magnetometer
if(rc_i2c_write_byte(IMU_BUS, AK8963_CNTL, MAG_POWER_DN)<0){
fprintf(stderr,"failed to write to magnetometer\n");
return -1;
}
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// Enable i2c bypass to allow talking to magnetometer
if(mpu_set_bypass(0)){
fprintf(stderr,"failed to set mpu9250 into bypass i2c mode\n");
return -1;
}
return 0;
}
/*******************************************************************************
* Power down the IMU
*******************************************************************************/
int rc_power_off_imu(){
shutdown_interrupt_thread = 1;
// set the device address
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// write the reset bit
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, H_RESET)){
//wait and try again
rc_usleep(1000);
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, H_RESET)){
fprintf(stderr,"I2C write to MPU9250 Failed\n");
return -1;
}
}
// write the sleep bit
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, MPU_SLEEP)){
//wait and try again
rc_usleep(1000);
if(rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, MPU_SLEEP)){
fprintf(stderr,"I2C write to MPU9250 Failed\n");
return -1;
}
}
// wait for the interrupt thread to exit if it hasn't already
//allow up to 1 second for thread cleanup
if(thread_running_flag){
struct timespec thread_timeout;
clock_gettime(CLOCK_REALTIME, &thread_timeout);
thread_timeout.tv_sec += 1;
int thread_err = 0;
thread_err = pthread_timedjoin_np(imu_interrupt_thread, NULL, \
&thread_timeout);
if(thread_err == ETIMEDOUT){
fprintf(stderr,"WARNING: imu_interrupt_thread exit timeout\n");
}
}
return 0;
}
/*******************************************************************************
* Set up the IMU for DMP accelerated filtering and interrupts
*******************************************************************************/
int rc_initialize_imu_dmp(rc_imu_data_t *data, rc_imu_config_t conf){
uint8_t c;
// range check
if(conf.dmp_sample_rate>DMP_MAX_RATE || conf.dmp_sample_rate<DMP_MIN_RATE){
fprintf(stderr,"ERROR:dmp_sample_rate must be between %d & %d\n", \
DMP_MIN_RATE, DMP_MAX_RATE);
return -1;
}
// make sure the sample rate is a divisor so we can find a neat rate divider
if(DMP_MAX_RATE%conf.dmp_sample_rate != 0){
fprintf(stderr,"DMP sample rate must be a divisor of 200\n");
fprintf(stderr,"acceptable values: 200,100,50,40,25,20,10,8,5,4 (HZ)\n");
return -1;
}
// make sure the compass filter time constant is valid
if(conf.enable_magnetometer && conf.compass_time_constant<=0.1){
fprintf(stderr,"ERROR: compass time constant must be greater than 0.1\n");
return -1;
}
// make sure the bus is not currently in use by another thread
// do not proceed to prevent interfering with that process
if(rc_i2c_get_in_use_state(IMU_BUS)){
fprintf(stderr,"WARNING: i2c bus claimed by another process\n");
fprintf(stderr,"Continuing with rc_initialize_imu_dmp() anyway\n");
}
// start the i2c bus
if(rc_i2c_init(IMU_BUS, IMU_ADDR)){
fprintf(stderr,"rc_initialize_imu_dmp failed at rc_i2c_init\n");
return -1;
}
// configure the gpio interrupt pin
if(rc_gpio_export(IMU_INTERRUPT_PIN)<0){
fprintf(stderr,"ERROR: failed to export GPIO %d", IMU_INTERRUPT_PIN);
return -1;
}
if(rc_gpio_set_dir(IMU_INTERRUPT_PIN, INPUT_PIN)<0){
fprintf(stderr,"ERROR: failed to configure GPIO %d", IMU_INTERRUPT_PIN);
return -1;
}
if(rc_gpio_set_edge(IMU_INTERRUPT_PIN, EDGE_FALLING)<0){
fprintf(stderr,"ERROR: failed to configure GPIO %d", IMU_INTERRUPT_PIN);
return -1;
}
// claiming the bus does no guarantee other code will not interfere
// with this process, but best to claim it so other code can check
// like we did above
rc_i2c_claim_bus(IMU_BUS);
// restart the device so we start with clean registers
if(reset_mpu9250()<0){
fprintf(stderr,"failed to reset_mpu9250()\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
//check the who am i register to make sure the chip is alive
if(rc_i2c_read_byte(IMU_BUS, WHO_AM_I_MPU9250, &c)<0){
fprintf(stderr,"i2c_read_byte failed reading who_am_i register\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
} if(c!=0x71){
fprintf(stderr,"mpu9250 WHO AM I register should return 0x71\n");
fprintf(stderr,"WHO AM I returned: 0x%x\n", c);
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// load in gyro calibration offsets from disk
if(load_gyro_offets()<0){
fprintf(stderr,"ERROR: failed to load gyro calibration offsets\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// log locally that the dmp will be running
dmp_en = 1;
// update local copy of config and data struct with new values
config = conf;
data_ptr = data;
// Set sensor sample rate to 200hz which is max the dmp can do.
// DMP will divide this frequency down further itself
if(mpu_set_sample_rate(200)<0){
fprintf(stderr,"ERROR: setting IMU sample rate\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// initialize the magnetometer too if requested in config
if(conf.enable_magnetometer){
if(initialize_magnetometer()){
fprintf(stderr,"ERROR: failed to initialize_magnetometer\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
}
else power_down_magnetometer();
// set full scale ranges. It seems the DMP only scales the gyro properly
// at 2000DPS. I'll assume the same is true for accel and use 2G like their
// example
set_gyro_fsr(G_FSR_2000DPS, data_ptr);
set_accel_fsr(A_FSR_2G, data_ptr);
// set the user-configurable DLPF
set_gyro_dlpf(config.gyro_dlpf);
set_accel_dlpf(config.accel_dlpf);
// set up the DMP
if(dmp_load_motion_driver_firmware()<0){
fprintf(stderr,"failed to load DMP motion driver\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(dmp_set_fifo_rate(config.dmp_sample_rate)<0){
fprintf(stderr,"ERROR: failed to set DMP fifo rate\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// Set fifo/sensor sample rate. Will have to set the DMP sample
// rate to match this shortly.
if(dmp_set_orientation((unsigned short)conf.orientation)<0){
fprintf(stderr,"ERROR: failed to set dmp orientation\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(dmp_enable_feature(DMP_FEATURE_6X_LP_QUAT|DMP_FEATURE_SEND_RAW_ACCEL| \
DMP_FEATURE_SEND_RAW_GYRO)<0){
fprintf(stderr,"ERROR: failed to enable DMP features\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(dmp_set_interrupt_mode(DMP_INT_CONTINUOUS)<0){
fprintf(stderr,"ERROR: failed to set DMP interrupt mode to continuous\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if (mpu_set_dmp_state(1)<0) {
fprintf(stderr,"ERROR: mpu_set_dmp_state(1) failed\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// set up the IMU to put magnetometer data in the fifo too if enabled
if(conf.enable_magnetometer){
// enable slave 0 (mag) in fifo
rc_i2c_write_byte(IMU_BUS,FIFO_EN, FIFO_SLV0_EN);
// enable master, and clock speed
rc_i2c_write_byte(IMU_BUS,I2C_MST_CTRL, 0x8D);
// set slave 0 address to magnetometer address
rc_i2c_write_byte(IMU_BUS,I2C_SLV0_ADDR, 0X8C);
// set mag data register to read from
rc_i2c_write_byte(IMU_BUS,I2C_SLV0_REG, AK8963_XOUT_L);
// set slave 0 to read 7 bytes
rc_i2c_write_byte(IMU_BUS,I2C_SLV0_CTRL, 0x87);
packet_len += 7; // add 7 more bytes to the fifo reads
}
// done with I2C for now
rc_i2c_release_bus(IMU_BUS);
#ifdef DEBUG
printf("packet_len: %d\n", packet_len);
#endif
// start the interrupt handler thread
interrupt_func_set = 1;
shutdown_interrupt_thread = 0;
rc_set_imu_interrupt_func(&rc_null_func);
pthread_create(&imu_interrupt_thread, NULL, \
imu_interrupt_handler, (void*) NULL);
params.sched_priority = config.dmp_interrupt_priority;
pthread_setschedparam(imu_interrupt_thread, SCHED_FIFO, ¶ms);
thread_running_flag = 1;
rc_usleep(1000);
#ifdef DEBUG
int policy;
struct sched_param params_tmp;
pthread_getschedparam(imu_interrupt_thread, &policy, ¶ms_tmp);
printf("new policy: %d, fifo: %d, prio: %d\n", policy, SCHED_FIFO, params_tmp.sched_priority);
#endif
return 0;
}
/*******************************************************************************
* @brief Write to the DMP memory.
* This function prevents I2C writes past the bank boundaries. The DMP memory
* is only accessible when the chip is awake.
* @param[in] mem_addr Memory location (bank << 8 | start address)
* @param[in] length Number of bytes to write.
* @param[in] data Bytes to write to memory.
* @return 0 if successful.
*******************************************************************************/
int mpu_write_mem(unsigned short mem_addr, unsigned short length,\
unsigned char *data){
unsigned char tmp[2];
if (!data){
fprintf(stderr,"ERROR: in mpu_write_mem, NULL pointer\n");
return -1;
}
tmp[0] = (unsigned char)(mem_addr >> 8);
tmp[1] = (unsigned char)(mem_addr & 0xFF);
// Check bank boundaries.
if (tmp[1] + length > MPU6500_BANK_SIZE){
fprintf(stderr,"mpu_write_mem exceeds bank size\n");
return -1;
}
if (rc_i2c_write_bytes(IMU_BUS,MPU6500_BANK_SEL, 2, tmp))
return -1;
if (rc_i2c_write_bytes(IMU_BUS,MPU6500_MEM_R_W, length, data))
return -1;
return 0;
}
/*******************************************************************************
* @brief Read from the DMP memory.
* This function prevents I2C reads past the bank boundaries. The DMP memory
* is only accessible when the chip is awake.
* @param[in] mem_addr Memory location (bank << 8 | start address)
* @param[in] length Number of bytes to read.
* @param[out] data Bytes read from memory.
* @return 0 if successful.
*******************************************************************************/
int mpu_read_mem(unsigned short mem_addr, unsigned short length,\
unsigned char *data){
unsigned char tmp[2];
if (!data){
fprintf(stderr,"ERROR: in mpu_write_mem, NULL pointer\n");
return -1;
}
tmp[0] = (unsigned char)(mem_addr >> 8);
tmp[1] = (unsigned char)(mem_addr & 0xFF);
// Check bank boundaries.
if (tmp[1] + length > MPU6500_BANK_SIZE){
printf("mpu_read_mem exceeds bank size\n");
return -1;
}
if (rc_i2c_write_bytes(IMU_BUS,MPU6500_BANK_SEL, 2, tmp))
return -1;
if (rc_i2c_read_bytes(IMU_BUS,MPU6500_MEM_R_W, length, data)!=length)
return -1;
return 0;
}
/*******************************************************************************
* int dmp_load_motion_driver_firmware()
*
* loads pre-compiled firmware binary from invensense onto dmp
*******************************************************************************/
int dmp_load_motion_driver_firmware(){
unsigned short ii;
unsigned short this_write;
// Must divide evenly into st.hw->bank_size to avoid bank crossings.
unsigned char cur[DMP_LOAD_CHUNK], tmp[2];
// make sure the address is set correctly
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
// loop through 16 bytes at a time and check each write for corruption
for (ii=0; ii<DMP_CODE_SIZE; ii+=this_write) {
this_write = min(DMP_LOAD_CHUNK, DMP_CODE_SIZE - ii);
if (mpu_write_mem(ii, this_write, (uint8_t*)&dmp_firmware[ii])){
fprintf(stderr,"dmp firmware write failed\n");
return -1;
}
if (mpu_read_mem(ii, this_write, cur)){
fprintf(stderr,"dmp firmware read failed\n");
return -1;
}
if (memcmp(dmp_firmware+ii, cur, this_write)){
fprintf(stderr,"dmp firmware write corrupted\n");
return -2;
}
}
// Set program start address.
tmp[0] = dmp_start_addr >> 8;
tmp[1] = dmp_start_addr & 0xFF;
if (rc_i2c_write_bytes(IMU_BUS, MPU6500_PRGM_START_H, 2, tmp)){
fprintf(stderr,"ERROR writing to MPU6500_PRGM_START register\n");
return -1;
}
return 0;
}
/*******************************************************************************
* @brief Push gyro and accel orientation to the DMP.
* The orientation is represented here as the output of
* @e inv_orientation_matrix_to_scalar.
* @param[in] orient Gyro and accel orientation in body frame.
* @return 0 if successful.
*******************************************************************************/
int dmp_set_orientation(unsigned short orient){
unsigned char gyro_regs[3], accel_regs[3];
const unsigned char gyro_axes[3] = {DINA4C, DINACD, DINA6C};
const unsigned char accel_axes[3] = {DINA0C, DINAC9, DINA2C};
const unsigned char gyro_sign[3] = {DINA36, DINA56, DINA76};
const unsigned char accel_sign[3] = {DINA26, DINA46, DINA66};
// populate fata to be written
gyro_regs[0] = gyro_axes[orient & 3];
gyro_regs[1] = gyro_axes[(orient >> 3) & 3];
gyro_regs[2] = gyro_axes[(orient >> 6) & 3];
accel_regs[0] = accel_axes[orient & 3];
accel_regs[1] = accel_axes[(orient >> 3) & 3];
accel_regs[2] = accel_axes[(orient >> 6) & 3];
// Chip-to-body, axes only.
if (mpu_write_mem(FCFG_1, 3, gyro_regs)){
fprintf(stderr, "ERROR: in dmp_set_orientation, failed to write dmp mem\n");
return -1;
}
if (mpu_write_mem(FCFG_2, 3, accel_regs)){
fprintf(stderr, "ERROR: in dmp_set_orientation, failed to write dmp mem\n");
return -1;
}
memcpy(gyro_regs, gyro_sign, 3);
memcpy(accel_regs, accel_sign, 3);
if (orient & 4) {
gyro_regs[0] |= 1;
accel_regs[0] |= 1;
}
if (orient & 0x20) {
gyro_regs[1] |= 1;
accel_regs[1] |= 1;
}
if (orient & 0x100) {
gyro_regs[2] |= 1;
accel_regs[2] |= 1;
}
// Chip-to-body, sign only.
if(mpu_write_mem(FCFG_3, 3, gyro_regs)){
fprintf(stderr, "ERROR: in dmp_set_orientation, failed to write dmp mem\n");
return -1;
}
if(mpu_write_mem(FCFG_7, 3, accel_regs)){
fprintf(stderr, "ERROR: in dmp_set_orientation, failed to write dmp mem\n");
return -1;
}
return 0;
}
/*******************************************************************************
* @brief Set DMP output rate.
* Only used when DMP is on.
* @param[in] rate Desired fifo rate (Hz).
* @return 0 if successful.
*******************************************************************************/
int dmp_set_fifo_rate(unsigned short rate){
const unsigned char regs_end[12] = {DINAFE, DINAF2, DINAAB,
0xc4, DINAAA, DINAF1, DINADF, DINADF, 0xBB, 0xAF, DINADF, DINADF};
unsigned short div;
unsigned char tmp[8];
if (rate > DMP_MAX_RATE){
return -1;
}
// set the DMP scaling factors
div = DMP_MAX_RATE / rate - 1;
tmp[0] = (unsigned char)((div >> 8) & 0xFF);
tmp[1] = (unsigned char)(div & 0xFF);
if (mpu_write_mem(D_0_22, 2, tmp)){
fprintf(stderr,"ERROR: writing dmp sample rate reg");
return -1;
}
if (mpu_write_mem(CFG_6, 12, (unsigned char*)regs_end)){
fprintf(stderr,"ERROR: writing dmp regs_end");
return -1;
}
return 0;
}
/*******************************************************************************
* int mpu_set_bypass(unsigned char bypass_on)
*
* configures the USER_CTRL and INT_PIN_CFG registers to turn on and off the
* i2c bypass mode for talking to the magnetometer. In random read mode this
* is used to turn on the bypass and left as is. In DMP mode bypass is turned
* off after configuration and the MPU fetches magnetometer data automatically.
* USER_CTRL - based on global variable dsp_en
* INT_PIN_CFG based on requested bypass state
*******************************************************************************/
int mpu_set_bypass(uint8_t bypass_on){
uint8_t tmp = 0;
// set up USER_CTRL first
if(dmp_en){
tmp |= FIFO_EN_BIT; // enable fifo for dsp mode
}
if(!bypass_on){
tmp |= I2C_MST_EN; // i2c master mode when not in bypass
}
if (rc_i2c_write_byte(IMU_BUS, USER_CTRL, tmp)){
fprintf(stderr,"ERROR in mpu_set_bypass, failed to write USER_CTRL register\n");
return -1;
}
rc_usleep(3000);
// INT_PIN_CFG settings
tmp = LATCH_INT_EN | INT_ANYRD_CLEAR | ACTL_ACTIVE_LOW;
tmp = ACTL_ACTIVE_LOW;
if(bypass_on)
tmp |= BYPASS_EN;
if (rc_i2c_write_byte(IMU_BUS, INT_PIN_CFG, tmp)){
fprintf(stderr,"ERROR in mpu_set_bypass, failed to write INT_PIN_CFG register\n");
return -1;
}
if(bypass_on){
bypass_en = 1;
}
else{
bypass_en = 0;
}
return 0;
}
/*******************************************************************************
* int dmp_enable_feature(unsigned short mask)
*
* This is mostly taken from the Invensense DMP code and serves to turn on and
* off DMP features based on the feature mask. We modified to remove some
* irrelevant features and set our own fifo-length variable. This probably
* isn't necessary to remain in its current form as rc_initialize_imu_dmp uses
* a fixed set of features but we keep it as is since it works fine.
*******************************************************************************/
int dmp_enable_feature(unsigned short mask){
unsigned char tmp[10];
// Set integration scale factor.
tmp[0] = (unsigned char)((GYRO_SF >> 24) & 0xFF);
tmp[1] = (unsigned char)((GYRO_SF >> 16) & 0xFF);
tmp[2] = (unsigned char)((GYRO_SF >> 8) & 0xFF);
tmp[3] = (unsigned char)(GYRO_SF & 0xFF);
if(mpu_write_mem(D_0_104, 4, tmp)<0){
fprintf(stderr, "ERROR: in dmp_enable_feature, failed to write mpu mem\n");
return -1;
}
// Send sensor data to the FIFO.
tmp[0] = 0xA3;
if (mask & DMP_FEATURE_SEND_RAW_ACCEL) {
tmp[1] = 0xC0;
tmp[2] = 0xC8;
tmp[3] = 0xC2;
} else {
tmp[1] = 0xA3;
tmp[2] = 0xA3;
tmp[3] = 0xA3;
}
if (mask & DMP_FEATURE_SEND_ANY_GYRO) {
tmp[4] = 0xC4;
tmp[5] = 0xCC;
tmp[6] = 0xC6;
} else {
tmp[4] = 0xA3;
tmp[5] = 0xA3;
tmp[6] = 0xA3;
}
tmp[7] = 0xA3;
tmp[8] = 0xA3;
tmp[9] = 0xA3;
if(mpu_write_mem(CFG_15,10,tmp)<0){
fprintf(stderr, "ERROR: in dmp_enable_feature, failed to write mpu mem\n");
return -1;
}
// Send gesture data to the FIFO.
if (mask & (DMP_FEATURE_TAP | DMP_FEATURE_ANDROID_ORIENT)){
tmp[0] = DINA20;
}
else{
tmp[0] = 0xD8;
}
if(mpu_write_mem(CFG_27,1,tmp)){
fprintf(stderr, "ERROR: in dmp_enable_feature, failed to write mpu mem\n");
return -1;
}
if(mask & DMP_FEATURE_GYRO_CAL){
dmp_enable_gyro_cal(1);
}
else{
dmp_enable_gyro_cal(0);
}
if (mask & DMP_FEATURE_SEND_ANY_GYRO) {
if (mask & DMP_FEATURE_SEND_CAL_GYRO) {
tmp[0] = 0xB2;
tmp[1] = 0x8B;
tmp[2] = 0xB6;
tmp[3] = 0x9B;
} else {
tmp[0] = DINAC0;
tmp[1] = DINA80;
tmp[2] = DINAC2;
tmp[3] = DINA90;
}
mpu_write_mem(CFG_GYRO_RAW_DATA, 4, tmp);
}
// disable tap feature
tmp[0] = 0xD8;
mpu_write_mem(CFG_20, 1, tmp);
// disable orientation feature
tmp[0] = 0xD8;
mpu_write_mem(CFG_ANDROID_ORIENT_INT, 1, tmp);
if (mask & DMP_FEATURE_LP_QUAT){
dmp_enable_lp_quat(1);
}
else{
dmp_enable_lp_quat(0);
}
if (mask & DMP_FEATURE_6X_LP_QUAT){
dmp_enable_6x_lp_quat(1);
}
else{
dmp_enable_6x_lp_quat(0);
}
mpu_reset_fifo();
packet_len = 0;
if(mask & DMP_FEATURE_SEND_RAW_ACCEL){
packet_len += 6;
}
if(mask & DMP_FEATURE_SEND_ANY_GYRO){
packet_len += 6;
}
if(mask & (DMP_FEATURE_LP_QUAT | DMP_FEATURE_6X_LP_QUAT)){
packet_len += 16;
}
return 0;
}
/*******************************************************************************
* int dmp_enable_gyro_cal(unsigned char enable)
*
* Taken straight from the Invensense DMP code. This enabled the automatic gyro
* calibration feature in the DMP. This this feature is fine for cell phones
* but annoying in control systems we do not use it here and instead ask users
* to run our own gyro_calibration routine.
*******************************************************************************/
int dmp_enable_gyro_cal(unsigned char enable){
if(enable){
unsigned char regs[9] = {0xb8, 0xaa, 0xb3, 0x8d, 0xb4, 0x98, 0x0d, 0x35, 0x5d};
return mpu_write_mem(CFG_MOTION_BIAS, 9, regs);
}
else{
unsigned char regs[9] = {0xb8, 0xaa, 0xaa, 0xaa, 0xb0, 0x88, 0xc3, 0xc5, 0xc7};
return mpu_write_mem(CFG_MOTION_BIAS, 9, regs);
}
}
/*******************************************************************************
* int dmp_enable_6x_lp_quat(unsigned char enable)
*
* Taken straight from the Invensense DMP code. This enabled quaternion filtering
* with accelerometer and gyro filtering.
*******************************************************************************/
int dmp_enable_6x_lp_quat(unsigned char enable){
unsigned char regs[4];
if(enable){
regs[0] = DINA20;
regs[1] = DINA28;
regs[2] = DINA30;
regs[3] = DINA38;
}
else{
memset(regs, 0xA3, 4);
}
mpu_write_mem(CFG_8, 4, regs);
return 0;
}
/*******************************************************************************
* int dmp_enable_lp_quat(unsigned char enable)
*
* sets the DMP to do gyro-only quaternion filtering. This is not actually used
* here but remains as a vestige of the Invensense DMP code.
*******************************************************************************/
int dmp_enable_lp_quat(unsigned char enable){
unsigned char regs[4];
if(enable){
regs[0] = DINBC0;
regs[1] = DINBC2;
regs[2] = DINBC4;
regs[3] = DINBC6;
}
else{
memset(regs, 0x8B, 4);
}
mpu_write_mem(CFG_LP_QUAT, 4, regs);
return 0;
}
/*******************************************************************************
* int mpu_reset_fifo()
*
* This is mostly from the Invensense open source codebase but modified to also
* allow magnetometer data to come in through the FIFO. This just turns off the
* interrupt, resets fifo and DMP, then starts them again. Used once while
* initializing (probably no necessary) then again if the fifo gets too full.
*******************************************************************************/
int mpu_reset_fifo(void){
uint8_t data;
// make sure the i2c address is set correctly.
// this shouldn't take any time at all if already set
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
data = 0;
if (rc_i2c_write_byte(IMU_BUS, INT_ENABLE, data)) return -1;
if (rc_i2c_write_byte(IMU_BUS, FIFO_EN, data)) return -1;
//if (rc_i2c_write_byte(IMU_BUS, USER_CTRL, data)) return -1;
data = BIT_FIFO_RST | BIT_DMP_RST;
if (rc_i2c_write_byte(IMU_BUS, USER_CTRL, data)) return -1;
rc_usleep(1000);
data = BIT_DMP_EN | BIT_FIFO_EN;
if(config.enable_magnetometer){
data |= I2C_MST_EN;
}
if(rc_i2c_write_byte(IMU_BUS, USER_CTRL, data)){
return -1;
}
if(config.enable_magnetometer){
rc_i2c_write_byte(IMU_BUS, FIFO_EN, FIFO_SLV0_EN);
}
else{
rc_i2c_write_byte(IMU_BUS, FIFO_EN, 0);
}
if(dmp_en){
rc_i2c_write_byte(IMU_BUS, INT_ENABLE, BIT_DMP_INT_EN);
}
else{
rc_i2c_write_byte(IMU_BUS, INT_ENABLE, 0);
}
return 0;
}
/*******************************************************************************
* int dmp_set_interrupt_mode(unsigned char mode)
*
* This is from the Invensense open source DMP code. It configures the DMP
* to trigger an interrupt either every sample or only on gestures. Here we
* only ever configure for continuous sampling.
*******************************************************************************/
int dmp_set_interrupt_mode(unsigned char mode){
const unsigned char regs_continuous[11] =
{0xd8, 0xb1, 0xb9, 0xf3, 0x8b, 0xa3, 0x91, 0xb6, 0x09, 0xb4, 0xd9};
const unsigned char regs_gesture[11] =
{0xda, 0xb1, 0xb9, 0xf3, 0x8b, 0xa3, 0x91, 0xb6, 0xda, 0xb4, 0xda};
switch(mode){
case DMP_INT_CONTINUOUS:
return mpu_write_mem(CFG_FIFO_ON_EVENT, 11, (unsigned char*)regs_continuous);
case DMP_INT_GESTURE:
return mpu_write_mem(CFG_FIFO_ON_EVENT, 11, (unsigned char*)regs_gesture);
default:
return -1;
}
}
/*******************************************************************************
* int set_int_enable(unsigned char enable)
*
* This is a vestige of the invensense mpu open source code and is probably
* not necessary but remains here anyway.
*******************************************************************************/
int set_int_enable(unsigned char enable){
unsigned char tmp;
if (enable){
tmp = BIT_DMP_INT_EN;
}
else{
tmp = 0x00;
}
if(rc_i2c_write_byte(IMU_BUS, INT_ENABLE, tmp)){
fprintf(stderr, "ERROR: in set_int_enable, failed to write INT_ENABLE register\n");
return -1;
}
// disable all other FIFO features leaving just DMP
if (rc_i2c_write_byte(IMU_BUS, FIFO_EN, 0)){
fprintf(stderr, "ERROR: in set_int_enable, failed to write FIFO_EN register\n");
return -1;
}
return 0;
}
/*******************************************************************************
int mpu_set_sample_rate(int rate)
Sets the clock rate divider for sensor sampling
*******************************************************************************/
int mpu_set_sample_rate(int rate){
if(rate>1000 || rate<4){
fprintf(stderr,"ERROR: sample rate must be between 4 & 1000\n");
return -1;
}
/* Keep constant sample rate, FIFO rate controlled by DMP. */
uint8_t div = (1000/rate) - 1;
#ifdef DEBUG
printf("setting divider to %d\n", div);
#endif
if(rc_i2c_write_byte(IMU_BUS, SMPLRT_DIV, div)){
fprintf(stderr,"ERROR: in mpu_set_sample_rate, failed to write SMPLRT_DIV register\n");
return -1;
}
return 0;
}
/*******************************************************************************
* int mpu_set_dmp_state(unsigned char enable)
*
* This turns on and off the DMP interrupt and resets the FIFO. This probably
* isn't necessary as rc_initialize_imu_dmp sets these registers but it remains
* here as a vestige of the invensense open source dmp code.
*******************************************************************************/
int mpu_set_dmp_state(unsigned char enable){
if (enable) {
// Disable data ready interrupt.
set_int_enable(0);
// Disable bypass mode.
mpu_set_bypass(0);
// Remove FIFO elements.
rc_i2c_write_byte(IMU_BUS, FIFO_EN , 0);
// Enable DMP interrupt.
set_int_enable(1);
mpu_reset_fifo();
}
else {
// Disable DMP interrupt.
set_int_enable(0);
// Restore FIFO settings.
rc_i2c_write_byte(IMU_BUS, FIFO_EN , 0);
mpu_reset_fifo();
}
return 0;
}
/*******************************************************************************
* void* imu_interrupt_handler(void* ptr)
*
* Here is where the magic happens. This function runs as its own thread and
* monitors the gpio pin IMU_INTERRUPT_PIN with the blocking function call
* poll(). If a valid interrupt is received from the IMU then mark the timestamp,
* read in the IMU data, and call the user-defined interrupt function if set.
*******************************************************************************/
void* imu_interrupt_handler( __unused void* ptr){
struct pollfd fdset[1];
int ret;
char buf[64];
int first_run = 1;
int imu_gpio_fd = rc_gpio_fd_open(IMU_INTERRUPT_PIN);
if(imu_gpio_fd == -1){
fprintf(stderr,"ERROR: can't open IMU_INTERRUPT_PIN gpio fd\n");
fprintf(stderr,"aborting imu_interrupt_handler\n");
return NULL;
}
fdset[0].fd = imu_gpio_fd;
fdset[0].events = POLLPRI;
// keep running until the program closes
mpu_reset_fifo();
while(rc_get_state()!=EXITING && shutdown_interrupt_thread!=1) {
// system hangs here until IMU FIFO interrupt
poll(fdset, 1, IMU_POLL_TIMEOUT);
if(rc_get_state()==EXITING || shutdown_interrupt_thread==1){
break;
}
else if (fdset[0].revents & POLLPRI) {
lseek(fdset[0].fd, 0, SEEK_SET);
read(fdset[0].fd, buf, 64);
// interrupt received, mark the timestamp
last_interrupt_timestamp_nanos = rc_nanos_since_epoch();
// try to load fifo no matter the claim bus state
if(rc_i2c_get_in_use_state(IMU_BUS)){
fprintf(stderr,"WARNING: Something has claimed the I2C bus when an\n");
fprintf(stderr,"IMU interrupt was received. Reading IMU anyway.\n");
}
// aquires bus
rc_i2c_claim_bus(IMU_BUS);
// aquires mutex
pthread_mutex_lock( &rc_imu_read_mutex );
// read data
ret = read_dmp_fifo(data_ptr);
// record if it was successful or not
if (ret==0) {
last_read_successful=1;
// signals that a measurement is available
pthread_cond_broadcast( &rc_imu_read_condition );
}
else
last_read_successful=0;
// releases mutex
pthread_mutex_unlock( &rc_imu_read_mutex );
// releases bus
rc_i2c_release_bus(IMU_BUS);
// call the user function if not the first run
if(first_run == 1){
first_run = 0;
}
else if(interrupt_func_set && last_read_successful){
imu_interrupt_func();
}
}
}
// aquires mutex
pthread_mutex_lock( &rc_imu_read_mutex );
// /releases other threads
pthread_cond_broadcast( &rc_imu_read_condition );
// releases mutex
pthread_mutex_unlock( &rc_imu_read_mutex );
rc_gpio_fd_close(imu_gpio_fd);
thread_running_flag = 0;
return 0;
}
/*******************************************************************************
* int rc_set_imu_interrupt_func(void (*func)(void))
*
* sets a user function to be called when new data is read
*******************************************************************************/
int rc_set_imu_interrupt_func(void (*func)(void)){
if(func==NULL){
fprintf(stderr,"ERROR: trying to assign NULL pointer to imu_interrupt_func\n");
return -1;
}
imu_interrupt_func = func;
interrupt_func_set = 1;
return 0;
}
/*******************************************************************************
* int rc_stop_imu_interrupt_func()
*
* stops the user function from being called when new data is available
*******************************************************************************/
int rc_stop_imu_interrupt_func(){
interrupt_func_set = 0;
return 0;
}
/*******************************************************************************
* int read_dmp_fifo(rc_imu_data_t* data)
*
* Reads the FIFO buffer and populates the data struct. Here is where we see
* bad/empty/double packets due to i2c bus errors and the IMU failing to have
* data ready in time. enabling warnings in the config struct will let this
* function print out warnings when these conditions are detected. If write
* errors are detected then this function tries some i2c transfers a second time.
*******************************************************************************/
int read_dmp_fifo(rc_imu_data_t* data){
unsigned char raw[MAX_FIFO_BUFFER];
long quat[4];
int16_t mag_adc[3];
uint16_t fifo_count;
int ret, mag_data_available, dmp_data_available;
int i = 0; // position of beginning of mag data
int j = 0; // position of beginning of dmp data
static int first_run = 1; // set to 0 after first call
float factory_cal_data[3]; // just temp holder for mag data
double q_tmp[4];
double sum,qlen;
if(!dmp_en){
printf("only use mpu_read_fifo in dmp mode\n");
return -1;
}
// if the fifo packet_len variable not set up yet, this function must
// have been called prematurely
if(packet_len!=FIFO_LEN_NO_MAG && packet_len!=FIFO_LEN_MAG){
fprintf(stderr,"ERROR: packet_len is set incorrectly for read_dmp_fifo\n");
return -1;
}
// make sure the i2c address is set correctly.
// this shouldn't take any time at all if already set
rc_i2c_set_device_address(IMU_BUS, IMU_ADDR);
int is_new_dmp_data = 0;
// check fifo count register to make sure new data is there
if(rc_i2c_read_word(IMU_BUS, FIFO_COUNTH, &fifo_count)<0){
if(config.show_warnings){
printf("fifo_count i2c error: %s\n",strerror(errno));
}
return -1;
}
#ifdef DEBUG
printf("fifo_count: %d\n", fifo_count);
#endif
/***************************************************************************
* now that we see how many values are in the buffer, we have a long list of
* checks to determine what should be done
***************************************************************************/
mag_data_available=0;
dmp_data_available=0;
// empty FIFO, just return, nothing else to do
if(fifo_count==0){
// if(config.show_warnings&& first_run!=1){
// printf("WARNING: empty fifo\n");
// }
return -1;
}
// one packet, perfect!
if(fifo_count==FIFO_LEN_NO_MAG){
i = 0; // set offset to 0
mag_data_available=0;
dmp_data_available=1;
goto READ_FIFO;
}
if(fifo_count==FIFO_LEN_MAG){
i = 0; // set offset to 0
mag_data_available=1;
dmp_data_available=1;
goto READ_FIFO;
}
// these numbers pop up under high stress and represent uneven
// combinations of magnetometer and DMP data
if(fifo_count==42){
if(config.show_warnings&& first_run!=1){
printf("warning: packet count 42\n");
}
i = 7; // set offset to 7
mag_data_available=0;
dmp_data_available=1;
goto READ_FIFO;
}
if(fifo_count==63){
if(config.show_warnings&& first_run!=1){
printf("warning: packet count 63\n");
}
i = 28; // set offset to 7
mag_data_available=0;
dmp_data_available=1;
goto READ_FIFO;
}
if(fifo_count==77){
if(config.show_warnings&& first_run!=1){
printf("warning: packet count 77\n");
}
i = 42; // set offset to 7
mag_data_available=0;
dmp_data_available=1;
goto READ_FIFO;
}
// if exactly 2 packets are there we just missed one (whoops)
// read both in and set the offset i to one packet length
// the last packet data will be read normally
if(fifo_count==2*FIFO_LEN_NO_MAG){
if(config.show_warnings&& first_run!=1){
printf("warning: imu fifo contains two packets\n");
}
i = FIFO_LEN_NO_MAG; // set offset to beginning of second packet
mag_data_available=0;
dmp_data_available=1;
goto READ_FIFO;
}
if(fifo_count==2*FIFO_LEN_MAG){
if(config.show_warnings&& first_run!=1){
printf("warning: imu fifo contains two packets\n");
}
i = FIFO_LEN_MAG; // set offset to beginning of second packet
mag_data_available=1;
dmp_data_available=1;
goto READ_FIFO;
}
// if there are exactly 7 14, or 21 bytes available, there must be magnetometer
// data but nothing else. read it in anyway
if(fifo_count==7 || fifo_count==14 || fifo_count==21){
i = fifo_count - 7;
mag_data_available = 1;
dmp_data_available = 0;
goto READ_FIFO;
}
// finally, if we got a weird packet length, reset the fifo
if(config.show_warnings&& first_run!=1){
printf("warning: %d bytes in FIFO, expected %d\n", fifo_count,packet_len);
}
mpu_reset_fifo();
return -1;
/***************************************************************************
* now we get to the reading section. Here we also have logic to determine
* the order of the data in the packet as magnetometer data may come before
* or after the DMP data
***************************************************************************/
READ_FIFO:
memset(raw,0,MAX_FIFO_BUFFER);
// read it in!
ret = rc_i2c_read_bytes(IMU_BUS, FIFO_R_W, fifo_count, &raw[0]);
if(ret<0){
// if i2c_read returned -1 there was an error, try again
ret = rc_i2c_read_bytes(IMU_BUS, FIFO_R_W, fifo_count, &raw[0]);
}
if(ret!=fifo_count){
if(config.show_warnings){
fprintf(stderr,"ERROR: failed to read fifo buffer register\n");
printf("read %d bytes, expected %d\n", ret, packet_len);
}
return -1;
}
// if dmp data is available we must figure out if it's before or
// after the magnetometer data. Usually before.
if(dmp_data_available){
if(config.enable_magnetometer && check_quaternion_validity(raw,i+7)){
j=i+7; // 7 mag bytes before dmp data
}
else if(check_quaternion_validity(raw,i)){
// printf("after\n");
j=i; // 7 mag bytes after dmp data
i=i+FIFO_LEN_NO_MAG; // update mag data offset
}
else{
if(config.show_warnings){
printf("warning: Quaternion out of bounds\n");
printf("fifo_count: %d\n", fifo_count);
}
mpu_reset_fifo();
return -1;
}
// now we can read the quaternion
// parse the quaternion data from the buffer
quat[0] = ((long)raw[j+0] << 24) | ((long)raw[j+1] << 16) |
((long)raw[j+2] << 8) | raw[j+3];
quat[1] = ((long)raw[j+4] << 24) | ((long)raw[j+5] << 16) |
((long)raw[j+6] << 8) | raw[j+7];
quat[2] = ((long)raw[j+8] << 24) | ((long)raw[j+9] << 16) |
((long)raw[j+10] << 8) | raw[j+11];
quat[3] = ((long)raw[j+12] << 24) | ((long)raw[j+13] << 16) |
((long)raw[j+14] << 8) | raw[j+15];
// do double-precision quaternion normalization since the numbers
// in raw format are huge
for(i=0;i<4;i++) q_tmp[i]=(double)quat[i];
sum = 0.0;
for(i=0;i<4;i++) sum+=q_tmp[i]*q_tmp[i];
qlen=sqrt(sum);
for(i=0;i<4;i++) q_tmp[i]/=qlen;
// make floating point and put in output
for(i=0;i<4;i++) data->dmp_quat[i]=(float)q_tmp[i];
// fill in tait-bryan angles to the data struct
rc_quaternion_to_tb_array(data->dmp_quat, data->dmp_TaitBryan);
j+=16; // increase offset by 16 which was the quaternion size
// Read Accel values and load into imu_data struct
// Turn the MSB and LSB into a signed 16-bit value
data->raw_accel[0] = (int16_t)(((uint16_t)raw[j+0]<<8)|raw[j+1]);
data->raw_accel[1] = (int16_t)(((uint16_t)raw[j+2]<<8)|raw[j+3]);
data->raw_accel[2] = (int16_t)(((uint16_t)raw[j+4]<<8)|raw[j+5]);
// Fill in real unit values
data->accel[0] = data->raw_accel[0] * data->accel_to_ms2;
data->accel[1] = data->raw_accel[1] * data->accel_to_ms2;
data->accel[2] = data->raw_accel[2] * data->accel_to_ms2;
j+=6;
// Read gyro values and load into imu_data struct
// Turn the MSB and LSB into a signed 16-bit value
data->raw_gyro[0] = (int16_t)(((int16_t)raw[0+j]<<8)|raw[1+j]);
data->raw_gyro[1] = (int16_t)(((int16_t)raw[2+j]<<8)|raw[3+j]);
data->raw_gyro[2] = (int16_t)(((int16_t)raw[4+j]<<8)|raw[5+j]);
// Fill in real unit values
data->gyro[0] = data->raw_gyro[0] * data->gyro_to_degs;
data->gyro[1] = data->raw_gyro[1] * data->gyro_to_degs;
data->gyro[2] = data->raw_gyro[2] * data->gyro_to_degs;
is_new_dmp_data = 1;
}
// if there was magnetometer data try to read it
if(mag_data_available){
// Turn the MSB and LSB into a signed 16-bit value
// Data stored as little Endian
mag_adc[0] = (int16_t)(((int16_t)raw[i+1]<<8) | raw[i+0]);
mag_adc[1] = (int16_t)(((int16_t)raw[i+3]<<8) | raw[i+2]);
mag_adc[2] = (int16_t)(((int16_t)raw[i+5]<<8) | raw[i+4]);
// if the data is non-zero, save it
// multiply by the sensitivity adjustment and convert to units of
// uT micro Teslas. Also correct the coordinate system as someone
// in invensense thought it would be bright idea to have the
// magnetometer coordiate system aligned differently than the
// accelerometer and gyro.... -__-
if(mag_adc[0]!=0 || mag_adc[1]!=0 || mag_adc[2]!=0){
// multiply by the sensitivity adjustment and convert to units of uT
// Also correct the coordinate system as someone in invensense
// thought it would be a bright idea to have the magnetometer coordiate
// system aligned differently than the accelerometer and gyro.... -__-
factory_cal_data[0] = mag_adc[1]*mag_factory_adjust[1] * MAG_RAW_TO_uT;
factory_cal_data[1] = mag_adc[0]*mag_factory_adjust[0] * MAG_RAW_TO_uT;
factory_cal_data[2] = -mag_adc[2]*mag_factory_adjust[2] * MAG_RAW_TO_uT;
// now apply out own calibration, but first make sure we don't
// accidentally multiply by zero in case of uninitialized scale factors
if(mag_scales[0]==0.0) mag_scales[0]=1.0;
if(mag_scales[1]==0.0) mag_scales[1]=1.0;
if(mag_scales[2]==0.0) mag_scales[2]=1.0;
data->mag[0] = (factory_cal_data[0]-mag_offsets[0])*mag_scales[0];
data->mag[1] = (factory_cal_data[1]-mag_offsets[1])*mag_scales[1];
data->mag[2] = (factory_cal_data[2]-mag_offsets[2])*mag_scales[2];
}
}
// run data_fusion to filter yaw with compass if new mag data came in
if(is_new_dmp_data && config.enable_magnetometer){
#ifdef DEBUG
printf("running data_fusion\n");
#endif
data_fusion(data);
}
// if we finally got dmp data, turn off the first run flag
if(is_new_dmp_data) first_run=0;
// finally, our return value is based on the presence of DMP data only
// even if new magnetometer data was read, the expected timing must come
// from the DMP samples only
if(is_new_dmp_data) return 0;
else return -1;
}
/*******************************************************************************
* We can detect a corrupted FIFO by monitoring the quaternion data and
* ensuring that the magnitude is always normalized to one. This
* shouldn't happen in normal operation, but if an I2C error occurs,
* the FIFO reads might become misaligned.
*
* Let's start by scaling down the quaternion data to avoid long long
* math.
*******************************************************************************/
int check_quaternion_validity(unsigned char* raw, int i){
long quat_q14[4], quat[4], quat_mag_sq;
// parse the quaternion data from the buffer
quat[0] = ((long)raw[i+0] << 24) | ((long)raw[i+1] << 16) |
((long)raw[i+2] << 8) | raw[i+3];
quat[1] = ((long)raw[i+4] << 24) | ((long)raw[i+5] << 16) |
((long)raw[i+6] << 8) | raw[i+7];
quat[2] = ((long)raw[i+8] << 24) | ((long)raw[i+9] << 16) |
((long)raw[i+10] << 8) | raw[i+11];
quat[3] = ((long)raw[i+12] << 24) | ((long)raw[i+13] << 16) |
((long)raw[i+14] << 8) | raw[i+15];
quat_q14[0] = quat[0] >> 16;
quat_q14[1] = quat[1] >> 16;
quat_q14[2] = quat[2] >> 16;
quat_q14[3] = quat[3] >> 16;
quat_mag_sq = quat_q14[0] * quat_q14[0] + quat_q14[1] * quat_q14[1] +
quat_q14[2] * quat_q14[2] + quat_q14[3] * quat_q14[3];
if ((quat_mag_sq < QUAT_MAG_SQ_MIN) ||(quat_mag_sq > QUAT_MAG_SQ_MAX)){
return 0;
}
if ((quat_mag_sq < QUAT_MAG_SQ_MIN) ||(quat_mag_sq > QUAT_MAG_SQ_MAX)){
return 0;
}
return 1;
}
/*******************************************************************************
* int data_fusion(rc_imu_data_t* data)
*
* This fuses the magnetometer data with the quaternion straight from the DMP
* to correct the yaw heading to a compass heading. Much thanks to Pansenti for
* open sourcing this routine. In addition to the Pansenti implementation I also
* correct the magnetometer data for DMP orientation, initialize yaw with the
* magnetometer to prevent initial rise time, and correct the yaw_mixing_factor
* with the sample rate so the filter rise time remains constant with different
* sample rates.
*******************************************************************************/
int data_fusion(rc_imu_data_t* data){
float tilt_tb[3], tilt_q[4], mag_vec[3];
static float newMagYaw = 0;
static float newDMPYaw = 0;
float lastDMPYaw, lastMagYaw, newYaw;
static int dmp_spin_counter = 0;
static int mag_spin_counter = 0;
static int first_run = 1; // set to 0 after first call to this function
// start by filling in the roll/pitch components of the fused euler
// angles from the DMP generated angles. Ignore yaw for now, we have to
// filter that later.
tilt_tb[0] = data->dmp_TaitBryan[TB_PITCH_X];
tilt_tb[1] = data->dmp_TaitBryan[TB_ROLL_Y];
tilt_tb[2] = 0.0f;
// generate a quaternion rotation of just roll/pitch
rc_tb_to_quaternion_array(tilt_tb,tilt_q);
// create a quaternion vector from the current magnetic field vector
// in IMU body coordinate frame. Since the DMP quaternion is aligned with
// a particular orientation, we must be careful to orient the magnetometer
// data to match.
switch(config.orientation){
case ORIENTATION_Z_UP:
mag_vec[0] = data->mag[TB_PITCH_X];
mag_vec[1] = data->mag[TB_ROLL_Y];
mag_vec[2] = data->mag[TB_YAW_Z];
break;
case ORIENTATION_Z_DOWN:
mag_vec[0] = -data->mag[TB_PITCH_X];
mag_vec[1] = data->mag[TB_ROLL_Y];
mag_vec[2] = -data->mag[TB_YAW_Z];
break;
case ORIENTATION_X_UP:
mag_vec[0] = data->mag[TB_YAW_Z];
mag_vec[1] = data->mag[TB_ROLL_Y];
mag_vec[2] = data->mag[TB_PITCH_X];
break;
case ORIENTATION_X_DOWN:
mag_vec[0] = -data->mag[TB_YAW_Z];
mag_vec[1] = data->mag[TB_ROLL_Y];
mag_vec[2] = -data->mag[TB_PITCH_X];
break;
case ORIENTATION_Y_UP:
mag_vec[0] = data->mag[TB_PITCH_X];
mag_vec[1] = -data->mag[TB_YAW_Z];
mag_vec[2] = data->mag[TB_ROLL_Y];
break;
case ORIENTATION_Y_DOWN:
mag_vec[0] = data->mag[TB_PITCH_X];
mag_vec[1] = data->mag[TB_YAW_Z];
mag_vec[2] = -data->mag[TB_ROLL_Y];
break;
case ORIENTATION_X_FORWARD:
mag_vec[0] = data->mag[TB_ROLL_Y];
mag_vec[1] = -data->mag[TB_PITCH_X];
mag_vec[2] = data->mag[TB_YAW_Z];
break;
case ORIENTATION_X_BACK:
mag_vec[0] = -data->mag[TB_ROLL_Y];
mag_vec[1] = data->mag[TB_PITCH_X];
mag_vec[2] = data->mag[TB_YAW_Z];
break;
default:
fprintf(stderr,"ERROR: invalid orientation\n");
return -1;
}
// tilt that vector by the roll/pitch of the IMU to align magnetic field
// vector such that Z points vertically
rc_quaternion_rotate_vector_array(mag_vec,tilt_q);
// from the aligned magnetic field vector, find a yaw heading
// check for validity and make sure the heading is positive
lastMagYaw = newMagYaw; // save from last loop
newMagYaw = -atan2(mag_vec[1], mag_vec[0]);
if (newMagYaw != newMagYaw) {
#ifdef WARNINGS
printf("newMagYaw NAN\n");
#endif
return -1;
}
data->compass_heading_raw = newMagYaw;
// save DMP last from time and record newDMPYaw for this time
lastDMPYaw = newDMPYaw;
newDMPYaw = data->dmp_TaitBryan[TB_YAW_Z];
// the outputs from atan2 and dmp are between -PI and PI.
// for our filters to run smoothly, we can't have them jump between -PI
// to PI when doing a complete spin. Therefore we check for a skip and
// increment or decrement the spin counter
if(newMagYaw-lastMagYaw < -PI) mag_spin_counter++;
else if (newMagYaw-lastMagYaw > PI) mag_spin_counter--;
if(newDMPYaw-lastDMPYaw < -PI) dmp_spin_counter++;
else if (newDMPYaw-lastDMPYaw > PI) dmp_spin_counter--;
// if this is the first run, set up filters
if(first_run){
lastMagYaw = newMagYaw;
lastDMPYaw = newDMPYaw;
mag_spin_counter = 0;
dmp_spin_counter = 0;
// generate complementary filters
float dt = 1.0/config.dmp_sample_rate;
rc_first_order_lowpass(&low_pass,dt,config.compass_time_constant);
rc_first_order_highpass(&high_pass,dt,config.compass_time_constant);
rc_prefill_filter_inputs(&low_pass,newMagYaw);
rc_prefill_filter_outputs(&low_pass,newMagYaw);
rc_prefill_filter_inputs(&high_pass,newDMPYaw);
rc_prefill_filter_outputs(&high_pass,0);
first_run = 0;
}
// new Yaw is the sum of low and high pass complementary filters.
newYaw = rc_march_filter(&low_pass,newMagYaw+(TWO_PI*mag_spin_counter)) \
+ rc_march_filter(&high_pass,newDMPYaw+(TWO_PI*dmp_spin_counter));
newYaw = fmod(newYaw,TWO_PI); // remove the effect of the spins
if (newYaw > PI) newYaw -= TWO_PI; // bound between +- PI
else if (newYaw < -PI) newYaw += TWO_PI; // bound between +- PI
// TB angles expect a yaw between -pi to pi so slide it again and
// store in the user-accessible fused tb angle
data->compass_heading = newYaw;
data->fused_TaitBryan[2] = newYaw;
data->fused_TaitBryan[0] = data->dmp_TaitBryan[0];
data->fused_TaitBryan[1] = data->dmp_TaitBryan[1];
// Also generate a new quaternion from the filtered tb angles
rc_tb_to_quaternion_array(data->fused_TaitBryan, data->fused_quat);
return 0;
}
/*******************************************************************************
* int write_gyro_offsets_to_disk(int16_t offsets[3])
*
* Reads steady state gyro offsets from the disk and puts them in the IMU's
* gyro offset register. If no calibration file exists then make a new one.
*******************************************************************************/
int write_gyro_offets_to_disk(int16_t offsets[3]){
FILE *cal;
char file_path[100];
// construct a new file path string and open for writing
strcpy(file_path, CONFIG_DIRECTORY);
strcat(file_path, GYRO_CAL_FILE);
cal = fopen(file_path, "w+");
// if opening for writing failed, the directory may not exist yet
if (cal == 0) {
mkdir(CONFIG_DIRECTORY, 0777);
cal = fopen(file_path, "w+");
if (cal == 0){
fprintf(stderr,"could not open config directory\n");
fprintf(stderr,CONFIG_DIRECTORY);
fprintf(stderr,"\n");
return -1;
}
}
// write to the file, close, and exit
if(fprintf(cal,"%d\n%d\n%d\n", offsets[0],offsets[1],offsets[2])<0){
printf("Failed to write gyro offsets to file\n");
fclose(cal);
return -1;
}
fclose(cal);
return 0;
}
/*******************************************************************************
* int load_gyro_offsets()
*
* Loads steady state gyro offsets from the disk and puts them in the IMU's
* gyro offset register. If no calibration file exists then make a new one.
*******************************************************************************/
int load_gyro_offets(){
FILE *cal;
char file_path[100];
uint8_t data[6];
int x,y,z;
// construct a new file path string and open for reading
strcpy (file_path, CONFIG_DIRECTORY);
strcat (file_path, GYRO_CAL_FILE);
cal = fopen(file_path, "r");
if (cal == 0) {
// calibration file doesn't exist yet
fprintf(stderr,"WARNING: no gyro calibration data found\n");
fprintf(stderr,"Please run rc_calibrate_gyro\n\n");
// use zero offsets
x = 0;
y = 0;
z = 0;
}
else {
// read in data
fscanf(cal,"%d\n%d\n%d\n", &x,&y,&z);
fclose(cal);
}
#ifdef DEBUG
printf("offsets: %d %d %d\n", x, y, z);
#endif
// Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input
// format. also make negative since we wish to subtract out the steady
// state offset
data[0] = (-x/4 >> 8) & 0xFF;
data[1] = (-x/4) & 0xFF;
data[2] = (-y/4 >> 8) & 0xFF;
data[3] = (-y/4) & 0xFF;
data[4] = (-z/4 >> 8) & 0xFF;
data[5] = (-z/4) & 0xFF;
// Push gyro biases to hardware registers
if(rc_i2c_write_bytes(IMU_BUS, XG_OFFSET_H, 6, &data[0])){
fprintf(stderr,"ERROR: failed to load gyro offsets into IMU register\n");
return -1;
}
return 0;
}
/*******************************************************************************
* int rc_calibrate_gyro_routine()
*
* Initializes the IMU and samples the gyro for a short period to get steady
* state gyro offsets. These offsets are then saved to disk for later use.
*******************************************************************************/
int rc_calibrate_gyro_routine(){
uint8_t c, data[6];
int32_t gyro_sum[3] = {0, 0, 0};
int16_t offsets[3];
int was_last_steady = 1;
// make sure the bus is not currently in use by another thread
// do not proceed to prevent interfering with that process
if(rc_i2c_get_in_use_state(IMU_BUS)){
fprintf(stderr,"i2c bus claimed by another process\n");
fprintf(stderr,"aborting gyro calibration()\n");
return -1;
}
// if it is not claimed, start the i2c bus
if(rc_i2c_init(IMU_BUS, IMU_ADDR)){
fprintf(stderr,"rc_initialize_imu_dmp failed at rc_i2c_init\n");
return -1;
}
// claiming the bus does no guarantee other code will not interfere
// with this process, but best to claim it so other code can check
// like we did above
rc_i2c_claim_bus(IMU_BUS);
// reset device, reset all registers
if(reset_mpu9250()<0){
fprintf(stderr,"ERROR: failed to reset MPU9250\n");
return -1;
}
// set up the IMU specifically for calibration.
rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, 0x01);
rc_i2c_write_byte(IMU_BUS, PWR_MGMT_2, 0x00);
rc_usleep(200000);
// // set bias registers to 0
// // Push gyro biases to hardware registers
// uint8_t zeros[] = {0,0,0,0,0,0};
// if(rc_i2c_write_bytes(IMU_BUS, XG_OFFSET_H, 6, zeros)){
// fprintf(stderr,"ERROR: failed to load gyro offsets into IMU register\n");
// return -1;
// }
rc_i2c_write_byte(IMU_BUS, INT_ENABLE, 0x00); // Disable all interrupts
rc_i2c_write_byte(IMU_BUS, FIFO_EN, 0x00); // Disable FIFO
rc_i2c_write_byte(IMU_BUS, PWR_MGMT_1, 0x00); // Turn on internal clock source
rc_i2c_write_byte(IMU_BUS, I2C_MST_CTRL, 0x00);// Disable I2C master
rc_i2c_write_byte(IMU_BUS, USER_CTRL, 0x00); // Disable FIFO and I2C master
rc_i2c_write_byte(IMU_BUS, USER_CTRL, 0x0C); // Reset FIFO and DMP
rc_usleep(15000);
// Configure MPU9250 gyro and accelerometer for bias calculation
rc_i2c_write_byte(IMU_BUS, CONFIG, 0x01); // Set low-pass filter to 188 Hz
rc_i2c_write_byte(IMU_BUS, SMPLRT_DIV, 0x04); // Set sample rate to 200hz
// Set gyro full-scale to 250 degrees per second, maximum sensitivity
rc_i2c_write_byte(IMU_BUS, GYRO_CONFIG, 0x00);
// Set accelerometer full-scale to 2 g, maximum sensitivity
rc_i2c_write_byte(IMU_BUS, ACCEL_CONFIG, 0x00);
COLLECT_DATA:
if(rc_get_state()==EXITING){
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// Configure FIFO to capture gyro data for bias calculation
rc_i2c_write_byte(IMU_BUS, USER_CTRL, 0x40); // Enable FIFO
// Enable gyro sensors for FIFO (max size 512 bytes in MPU-9250)
c = FIFO_GYRO_X_EN|FIFO_GYRO_Y_EN|FIFO_GYRO_Z_EN;
rc_i2c_write_byte(IMU_BUS, FIFO_EN, c);
// 6 bytes per sample. 200hz. wait 0.4 seconds
rc_usleep(400000);
// At end of sample accumulation, turn off FIFO sensor read
rc_i2c_write_byte(IMU_BUS, FIFO_EN, 0x00);
// read FIFO sample count and log number of samples
rc_i2c_read_bytes(IMU_BUS, FIFO_COUNTH, 2, &data[0]);
int16_t fifo_count = ((uint16_t)data[0] << 8) | data[1];
int samples = fifo_count/6;
#ifdef DEBUG
printf("calibration samples: %d\n", samples);
#endif
int i;
int16_t x,y,z;
rc_vector_t vx = rc_empty_vector();
rc_vector_t vy = rc_empty_vector();
rc_vector_t vz = rc_empty_vector();
rc_alloc_vector(&vx,samples);
rc_alloc_vector(&vy,samples);
rc_alloc_vector(&vz,samples);
float dev_x, dev_y, dev_z;
gyro_sum[0] = 0;
gyro_sum[1] = 0;
gyro_sum[2] = 0;
for (i=0; i<samples; i++) {
// read data for averaging
if(rc_i2c_read_bytes(IMU_BUS, FIFO_R_W, 6, data)<0){
fprintf(stderr,"ERROR: failed to read FIFO\n");
return -1;
}
x = (int16_t)(((int16_t)data[0] << 8) | data[1]) ;
y = (int16_t)(((int16_t)data[2] << 8) | data[3]) ;
z = (int16_t)(((int16_t)data[4] << 8) | data[5]) ;
gyro_sum[0] += (int32_t) x;
gyro_sum[1] += (int32_t) y;
gyro_sum[2] += (int32_t) z;
vx.d[i] = (float)x;
vy.d[i] = (float)y;
vz.d[i] = (float)z;
}
dev_x = rc_std_dev(vx);
dev_y = rc_std_dev(vy);
dev_z = rc_std_dev(vz);
rc_free_vector(&vx);
rc_free_vector(&vy);
rc_free_vector(&vz);
#ifdef DEBUG
printf("gyro sums: %d %d %d\n", gyro_sum[0], gyro_sum[1], gyro_sum[2]);
printf("std_deviation: %6.2f %6.2f %6.2f\n", dev_x, dev_y, dev_z);
#endif
// try again is standard deviation is too high
if(dev_x>GYRO_CAL_THRESH||dev_y>GYRO_CAL_THRESH||dev_z>GYRO_CAL_THRESH){
printf("Gyro data too noisy, put me down on a solid surface!\n");
printf("trying again\n");
was_last_steady = 0;
goto COLLECT_DATA;
}
// this skips the first steady reading after a noisy reading
// to make sure IMU has settled after being picked up.
if(was_last_steady == 0){
was_last_steady = 1;
goto COLLECT_DATA;
}
// average out the samples
offsets[0] = (int16_t) (gyro_sum[0]/(int32_t)samples);
offsets[1] = (int16_t) (gyro_sum[1]/(int32_t)samples);
offsets[2] = (int16_t) (gyro_sum[2]/(int32_t)samples);
// also check for values that are way out of bounds
if(abs(offsets[0])>GYRO_OFFSET_THRESH || abs(offsets[1])>GYRO_OFFSET_THRESH \
|| abs(offsets[2])>GYRO_OFFSET_THRESH){
printf("Gyro data out of bounds, put me down on a solid surface!\n");
printf("trying again\n");
goto COLLECT_DATA;
}
// done with I2C for now
rc_i2c_release_bus(IMU_BUS);
#ifdef DEBUG
printf("offsets: %d %d %d\n", offsets[0], offsets[1], offsets[2]);
#endif
// write to disk
if(write_gyro_offets_to_disk(offsets)<0){
fprintf(stderr,"ERROR in rc_calibrate_gyro_routine, failed to write to disk\n");
return -1;
}
return 0;
}
/*******************************************************************************
* unsigned short inv_row_2_scale(signed char row[])
*
* takes a single row on a rotation matrix and returns the associated scalar
* for use by inv_orientation_matrix_to_scalar.
*******************************************************************************/
unsigned short inv_row_2_scale(signed char row[]){
unsigned short b;
if (row[0] > 0)
b = 0;
else if (row[0] < 0)
b = 4;
else if (row[1] > 0)
b = 1;
else if (row[1] < 0)
b = 5;
else if (row[2] > 0)
b = 2;
else if (row[2] < 0)
b = 6;
else
b = 7; // error
return b;
}
/*******************************************************************************
* unsigned short inv_orientation_matrix_to_scalar(signed char mtx[])
*
* This take in a rotation matrix and returns the corresponding 16 bit short
* which is sent to the DMP to set the orientation. This function is actually
* not used in normal operation and only served to retrieve the orientation
* scalars once to populate the rc_imu_orientation_t enum during development.
*******************************************************************************/
unsigned short inv_orientation_matrix_to_scalar(signed char mtx[]){
unsigned short scalar;
scalar = inv_row_2_scale(mtx);
scalar |= inv_row_2_scale(mtx + 3) << 3;
scalar |= inv_row_2_scale(mtx + 6) << 6;
return scalar;
}
/*******************************************************************************
* void print_orientation_info()
*
* this function purely serves to print out orientation values and rotation
* matrices which form the rc_imu_orientation_t enum. This is not called inside
* this C file and is not exposed to the user.
*******************************************************************************/
void print_orientation_info(){
printf("\n");
//char mtx[9];
unsigned short orient;
// Z-UP (identity matrix)
signed char zup[] = {1,0,0, 0,1,0, 0,0,1};
orient = inv_orientation_matrix_to_scalar(zup);
printf("Z-UP: %d\n", orient);
// Z-down
signed char zdown[] = {-1,0,0, 0,1,0, 0,0,-1};
orient = inv_orientation_matrix_to_scalar(zdown);
printf("Z-down: %d\n", orient);
// X-up
signed char xup[] = {0,0,-1, 0,1,0, 1,0,0};
orient = inv_orientation_matrix_to_scalar(xup);
printf("x-up: %d\n", orient);
// X-down
signed char xdown[] = {0,0,1, 0,1,0, -1,0,0};
orient = inv_orientation_matrix_to_scalar(xdown);
printf("x-down: %d\n", orient);
// Y-up
signed char yup[] = {1,0,0, 0,0,-1, 0,1,0};
orient = inv_orientation_matrix_to_scalar(yup);
printf("y-up: %d\n", orient);
// Y-down
signed char ydown[] = {1,0,0, 0,0,1, 0,-1,0};
orient = inv_orientation_matrix_to_scalar(ydown);
printf("y-down: %d\n", orient);
// X-forward
signed char xforward[] = {0,-1,0, 1,0,0, 0,0,1};
orient = inv_orientation_matrix_to_scalar(xforward);
printf("x-forward: %d\n", orient);
// X-back
signed char xback[] = {0,1,0, -1,0,0, 0,0,1};
orient = inv_orientation_matrix_to_scalar(xback);
printf("yx-back: %d\n", orient);
}
/*******************************************************************************
* int rc_was_last_imu_read_successful()
*
* Occasionally bad data is read from the IMU, but the user's imu interrupt
* function is always called on every interrupt to keep discrete filters
* running at a steady clock. In the event of a bad read, old data is always
* available in the user's rc_imu_data_t struct and the user can call
* rc_was_last_imu_read_successful() to see if the data was updated or not.
*******************************************************************************/
int rc_was_last_imu_read_successful(){
return last_read_successful;
}
/*******************************************************************************
* uint64_t rc_nanos_since_last_imu_interrupt()
*
* Immediately after the IMU triggers an interrupt saying new data is ready,
* a timestamp is logged in microseconds. The user's imu_interrupt_function
* will be called after all data has been read in through the I2C bus and
* the user's rc_imu_data_t struct has been populated. If the user wishes to see
* how long it has been since that interrupt was received they may use this
* function.
*******************************************************************************/
uint64_t rc_nanos_since_last_imu_interrupt(){
return rc_nanos_since_epoch() - last_interrupt_timestamp_nanos;
}
/*******************************************************************************
* int write_mag_cal_to_disk(float offsets[3], float scale[3])
*
* Reads steady state gyro offsets from the disk and puts them in the IMU's
* gyro offset register. If no calibration file exists then make a new one.
*******************************************************************************/
int write_mag_cal_to_disk(float offsets[3], float scale[3]){
FILE *cal;
char file_path[100];
int ret;
// construct a new file path string and open for writing
strcpy(file_path, CONFIG_DIRECTORY);
strcat(file_path, MAG_CAL_FILE);
cal = fopen(file_path, "w+");
// if opening for writing failed, the directory may not exist yet
if (cal == 0) {
mkdir(CONFIG_DIRECTORY, 0777);
cal = fopen(file_path, "w+");
if (cal == 0){
fprintf(stderr,"could not open config directory\n");
fprintf(stderr, CONFIG_DIRECTORY);
fprintf(stderr,"\n");
return -1;
}
}
// write to the file, close, and exit
ret = fprintf(cal,"%f\n%f\n%f\n%f\n%f\n%f\n", offsets[0],\
offsets[1],\
offsets[2],\
scale[0],\
scale[1],\
scale[2]);
if(ret<0){
fprintf(stderr,"Failed to write mag calibration to file\n");
fclose(cal);
return -1;
}
fclose(cal);
return 0;
}
/*******************************************************************************
* int load_mag_calibration()
*
* Loads steady state magnetometer offsets and scale from the disk into global
* variables for correction later by read_magnetometer and FIFO read functions
*******************************************************************************/
int load_mag_calibration(){
FILE *cal;
char file_path[100];
float x,y,z,sx,sy,sz;
// construct a new file path string and open for reading
strcpy (file_path, CONFIG_DIRECTORY);
strcat (file_path, MAG_CAL_FILE);
cal = fopen(file_path, "r");
if (cal == 0) {
// calibration file doesn't exist yet
fprintf(stderr,"WARNING: no magnetometer calibration data found\n");
fprintf(stderr,"Please run rc_calibrate_mag\n\n");
mag_offsets[0]=0.0;
mag_offsets[1]=0.0;
mag_offsets[2]=0.0;
mag_scales[0]=1.0;
mag_scales[1]=1.0;
mag_scales[2]=1.0;
return -1;
}
// read in data
fscanf(cal,"%f\n%f\n%f\n%f\n%f\n%f\n", &x,&y,&z,&sx,&sy,&sz);
#ifdef DEBUG
printf("magcal: %f %f %f %f %f %f\n", x,y,z,sx,sy,sz);
#endif
// write to global variables fo use by rc_read_mag_data
mag_offsets[0]=x;
mag_offsets[1]=y;
mag_offsets[2]=z;
mag_scales[0]=sx;
mag_scales[1]=sy;
mag_scales[2]=sz;
fclose(cal);
return 0;
}
/*******************************************************************************
* int rc_calibrate_mag_routine()
*
* Initializes the IMU and samples the magnetometer until sufficient samples
* have been collected from each octant. From there, fit an ellipse to the data
* and save the correct offsets and scales to the disk which will later be
* applied to correct the uncalibrated magnetometer data to map calibrated
* field vectors to a sphere.
*******************************************************************************/
int rc_calibrate_mag_routine(){
const int samples = 200;
const int sample_rate_hz = 15;
int i;
uint8_t c;
float new_scale[3];
rc_matrix_t A = rc_empty_matrix();
rc_vector_t center = rc_empty_vector();
rc_vector_t lengths = rc_empty_vector();
rc_imu_data_t imu_data; // to collect magnetometer data
config = rc_default_imu_config();
config.enable_magnetometer = 1;
// make sure the bus is not currently in use by another thread
// do not proceed to prevent interfering with that process
if(rc_i2c_get_in_use_state(IMU_BUS)){
fprintf(stderr,"i2c bus claimed by another process\n");
fprintf(stderr,"aborting gyro calibration()\n");
return -1;
}
// if it is not claimed, start the i2c bus
if(rc_i2c_init(IMU_BUS, IMU_ADDR)){
fprintf(stderr,"rc_initialize_imu_dmp failed at rc_i2c_init\n");
return -1;
}
// claiming the bus does no guarantee other code will not interfere
// with this process, but best to claim it so other code can check
// like we did above
rc_i2c_claim_bus(IMU_BUS);
// reset device, reset all registers
if(reset_mpu9250()<0){
fprintf(stderr,"ERROR: failed to reset MPU9250\n");
return -1;
}
//check the who am i register to make sure the chip is alive
if(rc_i2c_read_byte(IMU_BUS, WHO_AM_I_MPU9250, &c)<0){
fprintf(stderr,"Reading WHO_AM_I_MPU9250 register failed\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(c!=0x71){
fprintf(stderr,"mpu9250 WHO AM I register should return 0x71\n");
fprintf(stderr,"WHO AM I returned: 0x%x\n", c);
rc_i2c_release_bus(IMU_BUS);
return -1;
}
if(initialize_magnetometer()){
fprintf(stderr,"ERROR: failed to initialize_magnetometer\n");
rc_i2c_release_bus(IMU_BUS);
return -1;
}
// set local calibration to initial values and prepare variables
mag_offsets[0] = 0.0;
mag_offsets[1] = 0.0;
mag_offsets[2] = 0.0;
mag_scales[0] = 1.0;
mag_scales[1] = 1.0;
mag_scales[2] = 1.0;
rc_alloc_matrix(&A,samples,3);
i = 0;
// sample data
while(i<samples && rc_get_state()!=EXITING){
if(rc_read_mag_data(&imu_data)<0){
fprintf(stderr,"ERROR: failed to read magnetometer\n");
break;
}
// make sure the data is non-zero
if(imu_data.mag[0]==0 && imu_data.mag[1]==0 && imu_data.mag[2]==0){
fprintf(stderr,"ERROR: retreived all zeros from magnetometer\n");
break;
}
// save data to matrix for ellipse fitting
A.d[i][0] = imu_data.mag[0];
A.d[i][1] = imu_data.mag[1];
A.d[i][2] = imu_data.mag[2];
i++;
// print "keep going" every 4 seconds
if(i%(sample_rate_hz*4) == sample_rate_hz*2){
printf("keep spinning\n");
}
// print "you're doing great" every 4 seconds
if(i%(sample_rate_hz*4) == 0){
printf("you're doing great\n");
}
rc_usleep(1000000/sample_rate_hz);
}
// done with I2C for now
rc_power_off_imu();
rc_i2c_release_bus(IMU_BUS);
printf("\n\nOkay Stop!\n");
printf("Calculating calibration constants.....\n");
fflush(stdout);
// if data collection loop exited without getting enough data, warn the
// user and return -1, otherwise keep going normally
if(i<samples){
printf("exiting rc_calibrate_mag_routine without saving new data\n");
return -1;
}
// make empty vectors for ellipsoid fitting to populate
if(rc_fit_ellipsoid(A,¢er,&lengths)<0){
fprintf(stderr,"failed to fit ellipsoid to magnetometer data\n");
rc_free_matrix(&A);
return -1;
}
// empty memory, we are done with A
rc_free_matrix(&A);
// do some sanity checks to make sure data is reasonable
if(fabs(center.d[0])>200 || fabs(center.d[1])>200 || \
fabs(center.d[2])>200){
fprintf(stderr,"ERROR: center of fitted ellipsoid out of bounds\n");
rc_free_vector(¢er);
rc_free_vector(&lengths);
return -1;
}
if( lengths.d[0]>200 || lengths.d[0]<5 || \
lengths.d[1]>200 || lengths.d[1]<5 || \
lengths.d[2]>200 || lengths.d[2]<5){
fprintf(stderr,"ERROR: length of fitted ellipsoid out of bounds\n");
//rc_free_vector(¢er);
//rc_free_vector(&lengths);
//return -1;
}
// all seems well, calculate scaling factors to map ellipse lengths to
// a sphere of radius 70uT, this scale will later be multiplied by the
// factory corrected data
new_scale[0] = 70.0f/lengths.d[0];
new_scale[1] = 70.0f/lengths.d[1];
new_scale[2] = 70.0f/lengths.d[2];
// print results
printf("\n");
printf("Offsets X: %7.3f Y: %7.3f Z: %7.3f\n", center.d[0],\
center.d[1],\
center.d[2]);
printf("Scales X: %7.3f Y: %7.3f Z: %7.3f\n", new_scale[0],\
new_scale[1],\
new_scale[2]);
// write to disk
if(write_mag_cal_to_disk(center.d,new_scale)<0){
rc_free_vector(¢er);
rc_free_vector(&lengths);
return -1;
}
rc_free_vector(¢er);
rc_free_vector(&lengths);
return 0;
}
/*******************************************************************************
* int rc_is_gyro_calibrated()
*
* return 1 is a gyro calibration file exists, otherwise 0
*******************************************************************************/
int rc_is_gyro_calibrated(){
char file_path[100];
strcpy (file_path, CONFIG_DIRECTORY);
strcat (file_path, GYRO_CAL_FILE);
if(!access(file_path, F_OK)) return 1;
else return 0;
}
/*******************************************************************************
* int rc_is_mag_calibrated()
*
* return 1 is a magnetometer calibration file exists, otherwise 0
*******************************************************************************/
int rc_is_mag_calibrated(){
char file_path[100];
strcpy (file_path, CONFIG_DIRECTORY);
strcat (file_path, MAG_CAL_FILE);
if(!access(file_path, F_OK)) return 1;
else return 0;
}
// Phew, that was a lot of code....
| 33.712879 | 95 | 0.640682 | [
"vector",
"solid"
] |
c89dcadabe266340f5ade5366078a36398a30a0c | 1,262 | c | C | projects/tests/mcp/mcp.c | ithinuel/elib | 0d343e62d350708d0a5f1f6b926462a66549437e | [
"Apache-2.0"
] | null | null | null | projects/tests/mcp/mcp.c | ithinuel/elib | 0d343e62d350708d0a5f1f6b926462a66549437e | [
"Apache-2.0"
] | null | null | null | projects/tests/mcp/mcp.c | ithinuel/elib | 0d343e62d350708d0a5f1f6b926462a66549437e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014 Chauveau Wilfried
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdlib.h>
#include <stdbool.h>
#include "unity_fixture.h"
#include "mcp/mcp.h"
static void mcp_entry(void);
system_entry_t g_mcp_entry =
{
.entry = mcp_entry,
.stack_size = 512,
.priority = 1
};
static void runAllTests()
{
RUN_TEST_GROUP(chunk_mock);
RUN_TEST_GROUP(memmgr_mock);
RUN_TEST_GROUP(task_mock);
RUN_TEST_GROUP(mm_chunk);
RUN_TEST_GROUP(memmgr);
RUN_TEST_GROUP(cstring);
RUN_TEST_GROUP(cexcept);
RUN_TEST_GROUP(object);
RUN_TEST_GROUP(mutex);
RUN_TEST_GROUP(spinlock);
RUN_TEST_GROUP(stream);
RUN_TEST_GROUP(task);
RUN_TEST_GROUP(list);
}
static void mcp_entry(void)
{
char *argv[2] = { "unit test", NULL };
UnityMain(1, argv, runAllTests);
}
| 22.945455 | 73 | 0.757528 | [
"object"
] |
c8a0ee24ee9192a432dd3dbb5506a0a23c7587f2 | 653 | h | C | Circular_kernel_3/doc/Circular_kernel_3/Concepts/AlgebraicKernelForSpheres--CompareY.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Circular_kernel_3/doc/Circular_kernel_3/Concepts/AlgebraicKernelForSpheres--CompareY.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Circular_kernel_3/doc/Circular_kernel_3/Concepts/AlgebraicKernelForSpheres--CompareY.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z |
/*!
\ingroup PkgCircularKernel3AlgebraicConcepts
\cgalConcept
\sa `AlgebraicKernelForSpheres::CompareX`
\sa `AlgebraicKernelForSpheres::CompareZ`
\sa `AlgebraicKernelForSpheres::CompareXY`
\sa `AlgebraicKernelForSpheres::CompareXYZ`
*/
class AlgebraicKernelForSpheres::CompareY {
public:
/// \name Operations
/// A model of this concept must provide:
/// @{
/*!
Compares the `y` (second) variables of two `Root_for_spheres_2_3`.
*/
CGAL::Comparison_result
operator()(const AlgebraicKernelForSpheres::Root_for_spheres_2_3 & r1,
const AlgebraicKernelForSpheres::Root_for_spheres_2_3 & r2);
/// @}
}; /* end AlgebraicKernelForSpheres::CompareY */
| 21.064516 | 70 | 0.773354 | [
"model"
] |
c8a7b1deabaebe83e3735a137dec4d55f784b84c | 22,731 | h | C | src/vpic/vpic.h | pdlfs/vpic | c2e9be14ef22b03b8feba2a69fab9e13db5262fc | [
"Unlicense"
] | 2 | 2017-04-21T00:33:05.000Z | 2021-02-13T06:06:53.000Z | src/vpic/vpic.h | pdlfs/vpic | c2e9be14ef22b03b8feba2a69fab9e13db5262fc | [
"Unlicense"
] | null | null | null | src/vpic/vpic.h | pdlfs/vpic | c2e9be14ef22b03b8feba2a69fab9e13db5262fc | [
"Unlicense"
] | null | null | null | /*
* Written by:
* Kevin J. Bowers, Ph.D.
* Plasma Physics Group (X-1)
* Applied Physics Division
* Los Alamos National Lab
* March/April 2004 - Heavily revised and extended from earlier V4PIC versions
*
* snell - revised to add new dumps, 20080310
*
*/
#ifndef vpic_h
#define vpic_h
#include <vector>
#include <cmath>
#include "../boundary/boundary.h"
#include "../collision/collision.h"
#include "../emitter/emitter.h"
// FIXME: INCLUDES ONCE ALL IS CLEANED UP
#include "../util/io/FileIO.h"
#include "../util/bitfield.h"
#include "../util/checksum.h"
#include "../util/system.h"
#ifndef USER_GLOBAL_SIZE
#define USER_GLOBAL_SIZE 16384
#endif
#ifndef NVARHISMX
#define NVARHISMX 250
#endif
// #include "dumpvars.h"
typedef FileIO FILETYPE;
const uint32_t all (0xffffffff);
const uint32_t electric (1<<0 | 1<<1 | 1<<2);
const uint32_t div_e_err (1<<3);
const uint32_t magnetic (1<<4 | 1<<5 | 1<<6);
const uint32_t div_b_err (1<<7);
const uint32_t tca (1<<8 | 1<<9 | 1<<10);
const uint32_t rhob (1<<11);
const uint32_t current (1<<12 | 1<<13 | 1<<14);
const uint32_t rhof (1<<15);
const uint32_t emat (1<<16 | 1<<17 | 1<<18);
const uint32_t nmat (1<<19);
const uint32_t fmat (1<<20 | 1<<21 | 1<<22);
const uint32_t cmat (1<<23);
const size_t total_field_variables(24);
const size_t total_field_groups(12); // this counts vectors, tensors etc...
// These bits will be tested to determine which variables to output
const size_t field_indeces[12] = { 0, 3, 4, 7, 8, 11, 12, 15, 16, 19, 20, 23 };
struct FieldInfo {
char name[128];
char degree[128];
char elements[128];
char type[128];
size_t size;
}; // struct FieldInfo
const uint32_t current_density (1<<0 | 1<<1 | 1<<2);
const uint32_t charge_density (1<<3);
const uint32_t momentum_density (1<<4 | 1<<5 | 1<<6);
const uint32_t ke_density (1<<7);
const uint32_t stress_tensor (1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12 | 1<<13);
/* May want to use these instead
const uint32_t stress_diagonal (1<<8 | 1<<9 | 1<<10);
const uint32_t stress_offdiagonal (1<<11 | 1<<12 | 1<<13);
*/
const size_t total_hydro_variables(14);
const size_t total_hydro_groups(5); // this counts vectors, tensors etc...
// These bits will be tested to determine which variables to output
const size_t hydro_indeces[5] = { 0, 3, 4, 7, 8 };
struct HydroInfo {
char name[128];
char degree[128];
char elements[128];
char type[128];
size_t size;
}; // struct FieldInfo
/*----------------------------------------------------------------------------
* DumpFormat Enumeration
----------------------------------------------------------------------------*/
enum DumpFormat {
band = 0,
band_interleave = 1
}; // enum DumpFormat
/*----------------------------------------------------------------------------
* DumpParameters Struct
----------------------------------------------------------------------------*/
struct DumpParameters {
void output_variables(uint32_t mask) {
output_vars.set(mask);
} // output_variables
BitField output_vars;
size_t stride_x;
size_t stride_y;
size_t stride_z;
DumpFormat format;
char name[128];
char baseDir[128];
char baseFileName[128];
}; // struct DumpParameters
class vpic_simulation {
public:
vpic_simulation();
~vpic_simulation();
void initialize( int argc, char **argv );
void modify( const char *fname );
int advance( void );
void finalize( void );
private:
// Directly initialized by user
int verbose; // Should system be verbose
int num_step; // Number of steps to take
int num_comm_round; // Num comm round
int status_interval; // How often to print status messages
int clean_div_e_interval; // How often to clean div e
int num_div_e_round; // How many clean div e rounds per div e interval
int clean_div_b_interval; // How often to clean div b
int num_div_b_round; // How many clean div b rounds per div b interval
int sync_shared_interval; // How often to synchronize shared faces
// FIXME: THESE INTERVALS SHOULDN'T BE PART OF vpic_simulation
// THE BIG LIST FOLLOWING IT SHOULD BE CLEANED UP TOO
double quota;
int checkpt_interval;
int hydro_interval;
int field_interval;
int particle_interval;
size_t nxout, nyout, nzout;
size_t px, py, pz;
float dxout, dyout, dzout;
int ndfld;
int ndhyd;
int ndpar;
int ndhis;
int ndgrd;
int head_option;
int istride;
int jstride;
int kstride;
int stride_option;
int pstride;
int nprobe;
int ijkprobe[NVARHISMX][4];
float xyzprobe[NVARHISMX][3];
int block_dump;
int stepdigit;
int rankdigit;
int ifenergies;
// Helper initialized by user
/* There are enough synchronous and local random number generators
to permit the host thread plus all the pipeline threads for one
dispatcher to simultaneously produce both synchronous and local
random numbers. Keeping the synchronous generators in sync is
the generator users responsibility. */
rng_pool_t * entropy; // Local entropy pool
rng_pool_t * sync_entropy; // Synchronous entropy pool
grid_t * grid; // define_*_grid et al
material_t * material_list; // define_material
field_array_t * field_array; // define_field_array
interpolator_array_t * interpolator_array; // define_interpolator_array
accumulator_array_t * accumulator_array; // define_accumulator_array
hydro_array_t * hydro_array; // define_hydro_array
species_t * species_list; // define_species /
// species helpers
particle_bc_t * particle_bc_list; // define_particle_bc /
// boundary helpers
emitter_t * emitter_list; // define_emitter /
// emitter helpers
collision_op_t * collision_op_list; // collision helpers
// User defined checkpt preserved variables
// Note: user_global is aliased with user_global_t (see deck_wrapper.cxx)
char user_global[USER_GLOBAL_SIZE];
/*----------------------------------------------------------------------------
* Diagnostics
---------------------------------------------------------------------------*/
double poynting_flux(double e0);
/*----------------------------------------------------------------------------
* Check Sums
---------------------------------------------------------------------------*/
#if defined(ENABLE_OPENSSL)
void output_checksum_fields();
void checksum_fields(CheckSum & cs);
void output_checksum_species(const char * species);
void checksum_species(const char * species, CheckSum & cs);
#endif // ENABLE_OPENSSL
void print_available_ram() {
SystemRAM::print_available();
} // print_available_ram
///////////////
// Dump helpers
int dump_mkdir(const char * dname);
int dump_cwd(char * dname, size_t size);
// Text dumps
void dump_energies( const char *fname, int append = 1 );
void dump_materials( const char *fname );
void dump_species( const char *fname );
// Binary dumps
void dump_grid( const char *fbase );
void dump_fields( const char *fbase, int fname_tag = 1 );
void dump_hydro( const char *sp_name, const char *fbase,
int fname_tag = 1 );
void dump_particles( const char *sp_name, const char *fbase,
int fname_tag = 1 );
// convenience functions for simlog output
void create_field_list(char * strlist, DumpParameters & dumpParams);
void create_hydro_list(char * strlist, DumpParameters & dumpParams);
void print_hashed_comment(FileIO & fileIO, const char * comment);
void global_header(const char * base,
std::vector<DumpParameters *> dumpParams);
void field_header(const char * fbase, DumpParameters & dumpParams);
void hydro_header(const char * speciesname, const char * hbase,
DumpParameters & dumpParams);
void field_dump(DumpParameters & dumpParams);
void hydro_dump(const char * speciesname, DumpParameters & dumpParams);
///////////////////
// Useful accessors
inline int
rank() { return world_rank; }
inline int
nproc() { return world_size; }
inline void
barrier() { mp_barrier(); }
inline double
time() {
return grid->t0 + (double)grid->dt*(double)grid->step;
}
inline int64_t &
step() {
return grid->step;
}
inline field_t &
field( const int v ) {
return field_array->f[ v ];
}
inline int
voxel( const int ix, const int iy, const int iz ) {
return ix + grid->sy*iy + grid->sz*iz;
}
inline field_t &
field( const int ix, const int iy, const int iz ) {
return field_array->f[ voxel(ix,iy,iz) ];
}
inline interpolator_t &
interpolator( const int v ) {
return interpolator_array->i[ v ];
}
inline interpolator_t &
interpolator( const int ix, const int iy, const int iz ) {
return interpolator_array->i[ voxel(ix,iy,iz) ];
}
inline hydro_t &
hydro( const int v ) {
return hydro_array->h[ v ];
}
inline hydro_t &
hydro( const int ix, const int iy, const int iz ) {
return hydro_array->h[ voxel(ix,iy,iz) ];
}
inline rng_t *
rng( const int n ) {
return entropy->rng[n];
}
inline rng_t *
sync_rng( const int n ) {
return sync_entropy->rng[n];
}
///////////////
// Grid helpers
inline void
define_units( float cvac,
float eps0 ) {
grid->cvac = cvac;
grid->eps0 = eps0;
}
inline void
define_timestep( float dt, double t0 = 0, int64_t step = 0 ) {
grid->t0 = t0;
grid->dt = (float)dt;
grid->step = step;
}
// The below functions automatically create partition simple grids with
// simple boundary conditions on the edges.
inline void
define_periodic_grid( double xl, double yl, double zl,
double xh, double yh, double zh,
double gnx, double gny, double gnz,
double gpx, double gpy, double gpz ) {
px = size_t(gpx); py = size_t(gpy); pz = size_t(gpz);
partition_periodic_box( grid, xl, yl, zl, xh, yh, zh,
(int)gnx, (int)gny, (int)gnz,
(int)gpx, (int)gpy, (int)gpz );
}
inline void
define_absorbing_grid( double xl, double yl, double zl,
double xh, double yh, double zh,
double gnx, double gny, double gnz,
double gpx, double gpy, double gpz, int pbc ) {
px = size_t(gpx); py = size_t(gpy); pz = size_t(gpz);
partition_absorbing_box( grid, xl, yl, zl, xh, yh, zh,
(int)gnx, (int)gny, (int)gnz,
(int)gpx, (int)gpy, (int)gpz,
pbc );
}
inline void
define_reflecting_grid( double xl, double yl, double zl,
double xh, double yh, double zh,
double gnx, double gny, double gnz,
double gpx, double gpy, double gpz ) {
px = size_t(gpx); py = size_t(gpy); pz = size_t(gpz);
partition_metal_box( grid, xl, yl, zl, xh, yh, zh,
(int)gnx, (int)gny, (int)gnz,
(int)gpx, (int)gpy, (int)gpz );
}
// The below macros allow custom domains to be created
// Creates a particle reflecting metal box in the local domain
inline void
size_domain( double lnx, double lny, double lnz ) {
size_grid(grid,(int)lnx,(int)lny,(int)lnz);
}
// Attaches a local domain boundary to another domain
inline void join_domain( int boundary, double rank ) {
join_grid( grid, boundary, (int)rank );
}
// Sets the field boundary condition of a local domain boundary
inline void set_domain_field_bc( int boundary, int fbc ) {
set_fbc( grid, boundary, fbc );
}
// Sets the particle boundary condition of a local domain boundary
inline void set_domain_particle_bc( int boundary, int pbc ) {
set_pbc( grid, boundary, pbc );
}
///////////////////
// Material helpers
inline material_t *
define_material( const char * name,
double eps,
double mu = 1,
double sigma = 0,
double zeta = 0 ) {
return append_material( material( name,
eps, eps, eps,
mu, mu, mu,
sigma, sigma, sigma,
zeta, zeta, zeta ), &material_list );
}
inline material_t *
define_material( const char * name,
double epsx, double epsy, double epsz,
double mux, double muy, double muz,
double sigmax, double sigmay, double sigmaz,
double zetax = 0 , double zetay = 0, double zetaz = 0 ) {
return append_material( material( name,
epsx, epsy, epsz,
mux, muy, muz,
sigmax, sigmay, sigmaz,
zetax, zetay, zetaz ), &material_list );
}
inline material_t *
lookup_material( const char * name ) {
return find_material_name( name, material_list );
}
inline material_t *
lookup_material( material_id id ) {
return find_material_id( id, material_list );
}
//////////////////////
// Field array helpers
// If fa is provided, define_field_advance will use it (and take ownership
// of the it). Otherwise the standard field array will be used with the
// optionally provided radition damping parameter.
inline void
define_field_array( field_array_t * fa = NULL, double damp = 0 ) {
int nx1 = grid->nx + 1, ny1 = grid->ny+1, nz1 = grid->nz+1;
if( grid->nx<1 || grid->ny<1 || grid->nz<1 )
ERROR(( "Define your grid before defining the field array" ));
if( !material_list )
ERROR(( "Define your materials before defining the field array" ));
field_array = fa ? fa :
new_standard_field_array( grid, material_list, damp );
interpolator_array = new_interpolator_array( grid );
accumulator_array = new_accumulator_array( grid );
hydro_array = new_hydro_array( grid );
// Pre-size communications buffers. This is done to get most memory
// allocation over with before the simulation starts running
mp_size_recv_buffer(grid->mp,BOUNDARY(-1, 0, 0),ny1*nz1*sizeof(hydro_t));
mp_size_recv_buffer(grid->mp,BOUNDARY( 1, 0, 0),ny1*nz1*sizeof(hydro_t));
mp_size_recv_buffer(grid->mp,BOUNDARY( 0,-1, 0),nz1*nx1*sizeof(hydro_t));
mp_size_recv_buffer(grid->mp,BOUNDARY( 0, 1, 0),nz1*nx1*sizeof(hydro_t));
mp_size_recv_buffer(grid->mp,BOUNDARY( 0, 0,-1),nx1*ny1*sizeof(hydro_t));
mp_size_recv_buffer(grid->mp,BOUNDARY( 0, 0, 1),nx1*ny1*sizeof(hydro_t));
mp_size_send_buffer(grid->mp,BOUNDARY(-1, 0, 0),ny1*nz1*sizeof(hydro_t));
mp_size_send_buffer(grid->mp,BOUNDARY( 1, 0, 0),ny1*nz1*sizeof(hydro_t));
mp_size_send_buffer(grid->mp,BOUNDARY( 0,-1, 0),nz1*nx1*sizeof(hydro_t));
mp_size_send_buffer(grid->mp,BOUNDARY( 0, 1, 0),nz1*nx1*sizeof(hydro_t));
mp_size_send_buffer(grid->mp,BOUNDARY( 0, 0,-1),nx1*ny1*sizeof(hydro_t));
mp_size_send_buffer(grid->mp,BOUNDARY( 0, 0, 1),nx1*ny1*sizeof(hydro_t));
}
// Other field helpers are provided by macros in deck_wrapper.cxx
//////////////////
// Species helpers
// FIXME: SILLY PROMOTIONS
inline species_t *
define_species( const char *name,
double q,
double m,
double max_local_np,
double max_local_nm,
double sort_interval,
double sort_out_of_place ) {
// Compute a reasonble number of movers if user did not specify
// Based on the twice the number of particles expected to hit the boundary
// of a wpdt=0.2 / dx=lambda species in a 3x3x3 domain
if( max_local_nm<0 ) {
max_local_nm = 2*max_local_np/25;
if( max_local_nm<16*(MAX_PIPELINE+1) )
max_local_nm = 16*(MAX_PIPELINE+1);
}
return append_species( species( name, (float)q, (float)m,
(size_t)max_local_np, (size_t)max_local_nm,
(int)sort_interval, (int)sort_out_of_place,
grid ), &species_list );
}
inline species_t *
find_species( const char *name ) {
return find_species_name( name, species_list );
}
inline species_t *
find_species( int32_t id ) {
return find_species_id( id, species_list );
}
///////////////////
// Particle helpers
// Note: Don't use injection with aging during initialization
// Defaults in the declaration below enable backwards compatibility.
void
inject_particle( species_t * sp,
double x, double y, double z,
double ux, double uy, double uz,
double w, double age = 0, int update_rhob = 1,
int64_t tag = 0 );
// Inject particle raw is for power users!
// No nannyism _at_ _all_:
// - Availability of free stoarge is _not_ checked.
// - Particle displacements and voxel index are _not_ for validity.
// - The rhob field is _not_ updated.
// - Injection with displacment may use up movers (i.e. don't use
// injection with displacement during initialization).
// This injection is _ultra_ _fast_.
inline void
inject_particle_raw( species_t * RESTRICT sp,
float dx, float dy, float dz, int32_t i,
float ux, float uy, float uz, float w,
int64_t tag = 0 ) {
particle_t * RESTRICT p = sp->p + (sp->np++);
p->dx = dx; p->dy = dy; p->dz = dz; p->i = i;
p->ux = ux; p->uy = uy; p->uz = uz; p->w = w;
#ifdef ENABLE_PARTICLE_TAG
p->tag = tag;
#endif
}
// This variant does a raw inject and moves the particles
inline void
inject_particle_raw( species_t * RESTRICT sp,
float dx, float dy, float dz, int32_t i,
float ux, float uy, float uz, float w,
float dispx, float dispy, float dispz,
int update_rhob, int64_t tag = 0 ) {
particle_t * RESTRICT p = sp->p + (sp->np++);
particle_mover_t * RESTRICT pm = sp->pm + sp->nm;
p->dx = dx; p->dy = dy; p->dz = dz; p->i = i;
p->ux = ux; p->uy = uy; p->uz = uz; p->w = w;
#ifdef ENABLE_PARTICLE_TAG
p->tag = tag;
#endif
pm->dispx = dispx; pm->dispy = dispy; pm->dispz = dispz; pm->i = sp->np-1;
if( update_rhob ) accumulate_rhob( field_array->f, p, grid, -sp->q );
sp->nm += move_p( sp->p, pm, accumulator_array->a, grid, sp->q );
}
//////////////////////////////////
// Random number generator helpers
// seed_rand seed the all the random number generators. The seed
// used for the individual generators is based off the user provided
// seed such each local generator in each process (rng[0:r-1]) gets
// a unique seed. Each synchronous generator (sync_rng[0:r-1]) gets a
// unique seed that does not overlap with the local generators
// (common across each process). Lastly, all these seeds are such
// that, no individual generator seeds are reused across different
// user seeds.
// FIXME: MTRAND DESPERATELY NEEDS A LARGER SEED SPACE!
inline void seed_entropy( int base ) {
seed_rng_pool( entropy, base, 0 );
seed_rng_pool( sync_entropy, base, 1 );
}
// Uniform random number on (low,high) (open interval)
// FIXME: IS THE INTERVAL STILL OPEN IN FINITE PRECISION
// AND IS THE OPEN INTERVAL REALLY WHAT USERS WANT??
inline double uniform( rng_t * rng, double low, double high ) {
double dx = drand( rng );
return low*(1-dx) + high*dx;
}
// Normal random number with mean mu and standard deviation sigma
inline double normal( rng_t * rng, double mu, double sigma ) {
return mu + sigma*drandn( rng );
}
/////////////////////////////////
// Emitter and particle bc helpers
// Note that append_emitter is hacked to silently returne if the
// emitter is already in the list. This allows things like:
//
// define_surface_emitter( my_emitter( ... ), rgn )
// ... or ...
// my_emit_t * e = my_emit( ... )
// define_surface_emitter( e, rgn )
// ... or ...
// my_emit_t * e = define_emitter( my_emit( ... ) )
// define_surface_emitter( e, rng )
// ...
// All to work. (Nominally, would like define_surface_emitter
// to evaluate to the value of e. But, alas, the way
// define_surface_emitter works and language limitations of
// strict C++ prevent this.)
inline emitter_t *
define_emitter( emitter_t * e ) {
return append_emitter( e, &emitter_list );
}
inline particle_bc_t *
define_particle_bc( particle_bc_t * pbc ) {
return append_particle_bc( pbc, &particle_bc_list );
}
inline collision_op_t *
define_collision_op( collision_op_t * cop ) {
return append_collision_op( cop, &collision_op_list );
}
////////////////////////
// Miscellaneous helpers
inline void abort( double code ) {
nanodelay(2000000000); mp_abort((((int)code)<<17)+1);
}
// Truncate "a" to the nearest integer multiple of "b"
inline double trunc_granular( double a, double b ) { return b*int(a/b); }
// Compute the remainder of a/b
inline double remainder( double a, double b ) { return std::remainder(a,b); }
// remainder(a,b);
// Compute the Courant length on a regular mesh
inline double courant_length( double lx, double ly, double lz,
double nx, double ny, double nz ) {
double w0, w1 = 0;
if( nx>1 ) w0 = nx/lx, w1 += w0*w0;
if( ny>1 ) w0 = ny/ly, w1 += w0*w0;
if( nz>1 ) w0 = nz/lz, w1 += w0*w0;
return sqrt(1/w1);
}
//////////////////////////////////////////////////////////
// These friends are used by the checkpt / restore service
friend void checkpt_vpic_simulation( const vpic_simulation * vpic );
friend vpic_simulation * restore_vpic_simulation( void );
friend void reanimate_vpic_simulation( vpic_simulation * vpic );
////////////////////////////////////////////////////////////
// User input deck provided functions (see deck_wrapper.cxx)
void user_initialization( int argc, char **argv );
void user_particle_injection(void);
void user_current_injection(void);
void user_field_injection(void);
void user_diagnostics(void);
void user_particle_collisions(void);
};
#endif // vpic_h
| 33.329912 | 80 | 0.602833 | [
"mesh",
"vector"
] |
c8afbe3d10106f835dc78485a1d416d9219fea7d | 5,233 | h | C | components/nmsis/dsp/inc/dsp/basic_math_functions_f16.h | HuakeZhBo/bl_mcu_sdk | a6a7f077e5dd535419d1741e4c2f5215eebb699d | [
"Apache-2.0"
] | 93 | 2021-04-27T07:34:49.000Z | 2022-03-22T08:43:44.000Z | components/nmsis/dsp/inc/dsp/basic_math_functions_f16.h | HuakeZhBo/bl_mcu_sdk | a6a7f077e5dd535419d1741e4c2f5215eebb699d | [
"Apache-2.0"
] | 28 | 2020-01-19T09:23:43.000Z | 2022-03-31T10:21:30.000Z | components/nmsis/dsp/inc/dsp/basic_math_functions_f16.h | HuakeZhBo/bl_mcu_sdk | a6a7f077e5dd535419d1741e4c2f5215eebb699d | [
"Apache-2.0"
] | 33 | 2021-04-27T07:46:50.000Z | 2022-02-27T05:45:19.000Z | /******************************************************************************
* @file basic_math_functions_f16.h
* @brief Public header file for NMSIS DSP Library
* @version V1.9.0
* @date 23 April 2021
* Target Processor: RISC-V Cores
******************************************************************************/
/*
* Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
* Copyright (c) 2019 Nuclei Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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 _BASIC_MATH_FUNCTIONS_F16_H_
#define _BASIC_MATH_FUNCTIONS_F16_H_
#ifdef __cplusplus
extern "C"
{
#endif
#include "riscv_math_types_f16.h"
#include "riscv_math_memory.h"
#include "dsp/none.h"
#include "dsp/utils.h"
#if defined(RISCV_FLOAT16_SUPPORTED)
/**
* @brief Floating-point vector addition.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void riscv_add_f16(
const float16_t * pSrcA,
const float16_t * pSrcB,
float16_t * pDst,
uint32_t blockSize);
/**
* @brief Floating-point vector subtraction.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void riscv_sub_f16(
const float16_t * pSrcA,
const float16_t * pSrcB,
float16_t * pDst,
uint32_t blockSize);
/**
* @brief Multiplies a floating-point vector by a scalar.
* @param[in] pSrc points to the input vector
* @param[in] scale scale factor to be applied
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void riscv_scale_f16(
const float16_t * pSrc,
float16_t scale,
float16_t * pDst,
uint32_t blockSize);
/**
* @brief Floating-point vector absolute value.
* @param[in] pSrc points to the input buffer
* @param[out] pDst points to the output buffer
* @param[in] blockSize number of samples in each vector
*/
void riscv_abs_f16(
const float16_t * pSrc,
float16_t * pDst,
uint32_t blockSize);
/**
* @brief Adds a constant offset to a floating-point vector.
* @param[in] pSrc points to the input vector
* @param[in] offset is the offset to be added
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void riscv_offset_f16(
const float16_t * pSrc,
float16_t offset,
float16_t * pDst,
uint32_t blockSize);
/**
* @brief Dot product of floating-point vectors.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[in] blockSize number of samples in each vector
* @param[out] result output result returned here
*/
void riscv_dot_prod_f16(
const float16_t * pSrcA,
const float16_t * pSrcB,
uint32_t blockSize,
float16_t * result);
/**
* @brief Floating-point vector multiplication.
* @param[in] pSrcA points to the first input vector
* @param[in] pSrcB points to the second input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in each vector
*/
void riscv_mult_f16(
const float16_t * pSrcA,
const float16_t * pSrcB,
float16_t * pDst,
uint32_t blockSize);
/**
* @brief Negates the elements of a floating-point vector.
* @param[in] pSrc points to the input vector
* @param[out] pDst points to the output vector
* @param[in] blockSize number of samples in the vector
*/
void riscv_negate_f16(
const float16_t * pSrc,
float16_t * pDst,
uint32_t blockSize);
/**
@brief Elementwise floating-point clipping
@param[in] pSrc points to input values
@param[out] pDst points to output clipped values
@param[in] low lower bound
@param[in] high higher bound
@param[in] numSamples number of samples to clip
@return none
*/
void riscv_clip_f16(const float16_t * pSrc,
float16_t * pDst,
float16_t low,
float16_t high,
uint32_t numSamples);
#endif /* defined(RISCV_FLOAT16_SUPPORTED)*/
#ifdef __cplusplus
}
#endif
#endif /* ifndef _BASIC_MATH_FUNCTIONS_F16_H_ */
| 30.782353 | 80 | 0.641506 | [
"vector"
] |
c8b5acdceeb568b416f5bff64f57a9fa12543313 | 2,126 | h | C | MediaStreamItf.h | sdanny/libtgvoip | c4a48b3627f7d08c7be40dc63b84f8b16eaf281a | [
"Unlicense"
] | 69 | 2017-05-10T09:50:26.000Z | 2022-03-31T08:14:32.000Z | MediaStreamItf.h | sdanny/libtgvoip | c4a48b3627f7d08c7be40dc63b84f8b16eaf281a | [
"Unlicense"
] | 15 | 2019-12-04T13:18:04.000Z | 2022-01-02T09:24:14.000Z | MediaStreamItf.h | sdanny/libtgvoip | c4a48b3627f7d08c7be40dc63b84f8b16eaf281a | [
"Unlicense"
] | 50 | 2017-05-18T12:42:46.000Z | 2022-03-20T10:23:57.000Z | //
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#ifndef LIBTGVOIP_MEDIASTREAMINPUT_H
#define LIBTGVOIP_MEDIASTREAMINPUT_H
#include <string.h>
#include <vector>
#include <memory>
#include <stdint.h>
#include "threading.h"
#include "BlockingQueue.h"
#include "Buffers.h"
namespace tgvoip{
class EchoCanceller;
class MediaStreamItf{
public:
virtual void Start()=0;
virtual void Stop()=0;
void SetCallback(size_t (*f)(unsigned char*, size_t, void*), void* param);
//protected:
size_t InvokeCallback(unsigned char* data, size_t length);
private:
size_t (*callback)(unsigned char*, size_t, void*)=NULL;
void* callbackParam;
};
class AudioMixer : public MediaStreamItf{
public:
AudioMixer();
virtual ~AudioMixer();
void SetOutput(MediaStreamItf* output);
virtual void Start();
virtual void Stop();
void AddInput(std::shared_ptr<MediaStreamItf> input);
void RemoveInput(std::shared_ptr<MediaStreamItf> input);
void SetInputVolume(std::shared_ptr<MediaStreamItf> input, float volumeDB);
void SetEchoCanceller(EchoCanceller* aec);
private:
void RunThread();
struct MixerInput{
std::shared_ptr<MediaStreamItf> source;
float multiplier;
};
Mutex inputsMutex;
void DoCallback(unsigned char* data, size_t length);
static size_t OutputCallback(unsigned char* data, size_t length, void* arg);
std::vector<MixerInput> inputs;
Thread* thread;
BufferPool bufferPool;
BlockingQueue<unsigned char*> processedQueue;
Semaphore semaphore;
EchoCanceller* echoCanceller;
bool running;
};
class CallbackWrapper : public MediaStreamItf{
public:
CallbackWrapper(){};
virtual ~CallbackWrapper(){};
virtual void Start(){};
virtual void Stop(){};
};
class AudioLevelMeter{
public:
AudioLevelMeter();
float GetLevel();
void Update(int16_t* samples, size_t count);
private:
int16_t absMax;
int16_t count;
int8_t currentLevel;
int16_t currentLevelFullRange;
};
};
#endif //LIBTGVOIP_MEDIASTREAMINPUT_H
| 23.88764 | 78 | 0.746002 | [
"vector"
] |
c8baf0259848ea39eb6340d8082902fce249b307 | 5,760 | c | C | libs/qmlglsink/gst-plugins-good/gst/goom2k1/gstgoom.c | ant-nihil/routen-qgroundcontrol | 0868aa1d6aba3f066dbaa55c53c943fc77eb8ff7 | [
"Apache-2.0"
] | 2 | 2021-05-24T14:18:37.000Z | 2022-03-04T06:59:42.000Z | libs/qmlglsink/gst-plugins-good/gst/goom2k1/gstgoom.c | ant-nihil/routen-qgroundcontrol | 0868aa1d6aba3f066dbaa55c53c943fc77eb8ff7 | [
"Apache-2.0"
] | null | null | null | libs/qmlglsink/gst-plugins-good/gst/goom2k1/gstgoom.c | ant-nihil/routen-qgroundcontrol | 0868aa1d6aba3f066dbaa55c53c943fc77eb8ff7 | [
"Apache-2.0"
] | null | null | null | /* gstgoom.c: implementation of goom drawing element
* Copyright (C) <2001> Richard Boulton <richard@tartarus.org>
* (C) <2006> Wim Taymans <wim at fluendo dot com>
* (C) <2015> Luis de Bethencourt <luis@debethencourt.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/**
* SECTION:element-goom2k1
* @title: goom2k1
* @see_also: goom, synaesthesia
*
* Goom2k1 is an audio visualisation element. It creates warping structures
* based on the incoming audio signal. Goom2k1 is the older version of the
* visualisation. Also available is goom2k4, with a different look.
*
* ## Example launch line
* |[
* gst-launch-1.0 -v audiotestsrc ! goom2k1 ! videoconvert ! xvimagesink
* ]|
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include "gstgoom.h"
#include "goom_core.h"
GST_DEBUG_CATEGORY_STATIC (goom2k1_debug);
#define GST_CAT_DEFAULT goom2k1_debug
#define DEFAULT_WIDTH 320
#define DEFAULT_HEIGHT 240
#define DEFAULT_FPS_N 25
#define DEFAULT_FPS_D 1
#if G_BYTE_ORDER == G_BIG_ENDIAN
#define RGB_ORDER "xRGB"
#else
#define RGB_ORDER "BGRx"
#endif
static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (RGB_ORDER))
);
static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink", /* the name of the pads */
GST_PAD_SINK, /* type of the pad */
GST_PAD_ALWAYS, /* ALWAYS/SOMETIMES */
GST_STATIC_CAPS ("audio/x-raw, "
"format = (string) " GST_AUDIO_NE (S16) ", "
"rate = (int) [ 8000, 96000 ], "
"channels = (int) 1, "
"layout = (string) interleaved; "
"audio/x-raw, "
"format = (string) " GST_AUDIO_NE (S16) ", "
"rate = (int) [ 8000, 96000 ], "
"channels = (int) 2, "
"channel-mask = (bitmask) 0x3, " "layout = (string) interleaved")
);
static void gst_goom2k1_finalize (GObject * object);
static gboolean gst_goom2k1_setup (GstAudioVisualizer * base);
static gboolean gst_goom2k1_render (GstAudioVisualizer * base,
GstBuffer * audio, GstVideoFrame * video);
G_DEFINE_TYPE (GstGoom2k1, gst_goom2k1, GST_TYPE_AUDIO_VISUALIZER);
static void
gst_goom2k1_class_init (GstGoom2k1Class * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
GstAudioVisualizerClass *visualizer_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
visualizer_class = (GstAudioVisualizerClass *) klass;
gobject_class->finalize = gst_goom2k1_finalize;
gst_element_class_set_static_metadata (gstelement_class,
"GOOM: what a GOOM! 2k1 edition", "Visualization",
"Takes frames of data and outputs video frames using the GOOM 2k1 filter",
"Wim Taymans <wim@fluendo.com>");
gst_element_class_add_static_pad_template (gstelement_class, &sink_template);
gst_element_class_add_static_pad_template (gstelement_class, &src_template);
GST_DEBUG_CATEGORY_INIT (goom2k1_debug, "goom2k1", 0,
"goom2k1 visualisation element");
visualizer_class->setup = GST_DEBUG_FUNCPTR (gst_goom2k1_setup);
visualizer_class->render = GST_DEBUG_FUNCPTR (gst_goom2k1_render);
}
static void
gst_goom2k1_init (GstGoom2k1 * goom)
{
goom->width = DEFAULT_WIDTH;
goom->height = DEFAULT_HEIGHT;
goom->channels = 0;
goom_init (&(goom->goomdata), goom->width, goom->height);
}
static void
gst_goom2k1_finalize (GObject * object)
{
GstGoom2k1 *goom = GST_GOOM2K1 (object);
goom_close (&(goom->goomdata));
G_OBJECT_CLASS (gst_goom2k1_parent_class)->finalize (object);
}
static gboolean
gst_goom2k1_setup (GstAudioVisualizer * base)
{
GstGoom2k1 *goom = GST_GOOM2K1 (base);
goom->width = GST_VIDEO_INFO_WIDTH (&base->vinfo);
goom->height = GST_VIDEO_INFO_HEIGHT (&base->vinfo);
goom_set_resolution (&(goom->goomdata), goom->width, goom->height);
return TRUE;
}
static gboolean
gst_goom2k1_render (GstAudioVisualizer * base, GstBuffer * audio,
GstVideoFrame * video)
{
GstGoom2k1 *goom = GST_GOOM2K1 (base);
GstMapInfo amap;
gint16 datain[2][GOOM2K1_SAMPLES];
gint16 *adata;
gint i;
/* get next GOOM2K1_SAMPLES, we have at least this amount of samples */
gst_buffer_map (audio, &amap, GST_MAP_READ);
adata = (gint16 *) amap.data;
if (goom->channels == 2) {
for (i = 0; i < GOOM2K1_SAMPLES; i++) {
datain[0][i] = *adata++;
datain[1][i] = *adata++;
}
} else {
for (i = 0; i < GOOM2K1_SAMPLES; i++) {
datain[0][i] = *adata;
datain[1][i] = *adata++;
}
}
video->data[0] = goom_update (&(goom->goomdata), datain);
gst_buffer_unmap (audio, &amap);
return TRUE;
}
static gboolean
plugin_init (GstPlugin * plugin)
{
return gst_element_register (plugin, "goom2k1", GST_RANK_NONE,
GST_TYPE_GOOM2K1);
}
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
goom2k1,
"GOOM 2k1 visualization filter",
plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)
| 29.690722 | 106 | 0.70816 | [
"render",
"object"
] |
c8c1e3c029a0de43f9b6c1edbff4ed9e207247e4 | 1,248 | h | C | Game/Client/WXCore/Core/WXSceneInfo.h | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/Client/WXCore/Core/WXSceneInfo.h | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/Client/WXCore/Core/WXSceneInfo.h | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | #ifndef __FAIRYSCENEINFO_H__
#define __FAIRYSCENEINFO_H__
#include "WXScene.h"
namespace WX
{
class XMLParser;
class XMLWriter;
class System;
class Terrain;
class TerrainData;
class IncrementalSceneBuilder;
class SceneInfo : public Scene
{
protected:
Terrain* mTerrain;
TerrainData* mTerrainData;
IncrementalSceneBuilder* mIncrementalSceneBuilder;
public:
SceneInfo(void);
~SceneInfo();
Terrain* getTerrain(void) const
{
return mTerrain;
}
TerrainData* getTerrainData(void) const
{
return mTerrainData;
}
void load(XMLParser* parser, const String& filename, const String& groupName, bool completely);
void save(XMLWriter* writer, const String& filename);
/** Destroys all the created render instance state (reverse of initialise).
@remarks
You can call initialise() again after this.
*/
void destroy(void);
/** Clears any of the objects added to this scene and
destroys anything which has already been initialised.
*/
void reset(void);
/** Initialise the scene.
*/
void initialise(System* system);
};
}
#endif
| 21.517241 | 103 | 0.635417 | [
"render"
] |
c8c303394049df94a68c248953da928b57a6b5d3 | 4,301 | c | C | software/tcl_auto/ds9tools/ast/sla/refz.c | MMTObservatory/SAOguider | e528d35d63876e2db066bef43cfcabd6946bc986 | [
"BSD-3-Clause"
] | null | null | null | software/tcl_auto/ds9tools/ast/sla/refz.c | MMTObservatory/SAOguider | e528d35d63876e2db066bef43cfcabd6946bc986 | [
"BSD-3-Clause"
] | null | null | null | software/tcl_auto/ds9tools/ast/sla/refz.c | MMTObservatory/SAOguider | e528d35d63876e2db066bef43cfcabd6946bc986 | [
"BSD-3-Clause"
] | null | null | null | #include "slalib.h"
#include "slamac.h"
void slaRefz ( double zu, double refa, double refb, double *zr )
/*
** - - - - - - - -
** s l a R e f z
** - - - - - - - -
**
** Adjust an unrefracted zenith distance to include the effect of
** atmospheric refraction, using the simple A tan z + B tan^3 z
** model.
**
** Given:
** zu double unrefracted zenith distance of the source (radian)
** refa double A: tan z coefficient (radian)
** refb double B: tan^3 z coefficient (radian)
**
** Returned:
** *zr double refracted zenith distance (radian)
**
** Notes:
**
** 1 This routine applies the adjustment for refraction in the
** opposite sense to the usual one - it takes an unrefracted
** (in vacuo) position and produces an observed (refracted)
** position, whereas the A tan Z + B tan^3 Z model strictly
** applies to the case where an observed position is to have the
** refraction removed. The unrefracted to refracted case is
** harder, and requires an inverted form of the text-book
** refraction models; the formula used here is based on the
** Newton-Raphson method. For the utmost numerical consistency
** with the refracted to unrefracted model, two iterations are
** carried out, achieving agreement at the 1D-11 arcseconds level
** for a ZD of 80 degrees. The inherent accuracy of the model
** is, of course, far worse than this - see the documentation for
** slaRefco for more information.
**
** 2 At ZD 83 degrees, the rapidly-worsening A tan Z + B tan^3 Z
** model is abandoned and an empirical formula takes over. Over a
** wide range of observer heights and corresponding temperatures and
** pressures, the following levels of accuracy (arcsec) are achieved,
** relative to numerical integration through a model atmosphere:
**
** ZR error
**
** 80 0.4
** 81 0.8
** 82 1.5
** 83 3.2
** 84 4.9
** 85 5.8
** 86 6.1
** 87 7.1
** 88 10
** 89 20
** 90 40
** 91 100 } relevant only to
** 92 200 } high-elevation sites
**
** The high-ZD model is scaled to match the normal model at the
** transition point; there is no glitch.
**
**
** 3 Beyond 93 deg zenith distance, the refraction is held at its
** 93 deg value.
**
** 4 See also the routine slaRefv, which performs the adjustment in
** Cartesian Az/El coordinates, and with the emphasis on speed
** rather than numerical accuracy.
**
** Defined in slamac.h: DR2D
**
** Last revision: 4 June 1997
**
** Copyright P.T.Wallace. All rights reserved.
*/
{
double zu1, zl, s, c, t, tsq, tcu, ref, e, e2;
/* Coefficients for high ZD model (used beyond ZD 83 deg */
const double c1 = 0.55445,
c2 = -0.01133,
c3 = 0.00202,
c4 = 0.28385,
c5 = 0.02390;
/* Largest usable ZD (deg) */
const double z93 = 93.0;
/* ZD at which one model hands over to the other (radians) */
const double z83 = 83.0 / DR2D;
/* High-ZD-model prediction (deg) for that point */
const double ref83 = ( c1 + c2 * 7.0 + c3 * 49.0 ) /
( 1.0 + c4 * 7.0 + c5 * 49.0 );
/* Perform calculations for zu or 83 deg, whichever is smaller */
zu1 = gmin ( zu, z83 );
/* Functions of ZD */
zl = zu1;
s = sin ( zl );
c = cos ( zl );
t = s / c;
tsq = t * t;
tcu = t * tsq;
/* Refracted ZD (mathematically to better than 1mas at 70 deg) */
zl -= ( refa * t + refb * tcu )
/ ( 1.0 + ( refa + 3.0 * refb * tsq ) / ( c * c ) );
/* Further iteration */
s = sin ( zl );
c = cos ( zl );
t = s / c;
tsq = t * t;
tcu = t * tsq;
ref = zu1 - zl + ( zl - zu1 + refa * t + refb * tcu )
/ ( 1.0 + ( refa + 3.0 * refb * tsq ) / ( c * c ) );
/* Special handling for large zu */
if ( zu > zu1 ) {
e = 90.0 - gmin ( z93, zu * DR2D );
e2 = e * e;
ref = ( ref / ref83 ) * ( c1 + c2 * e + c3 * e2 ) /
( 1.0 + c4 * e + c5 * e2 );
}
/* Refracted ZD */
*zr = zu - ref;
}
| 32.338346 | 73 | 0.548245 | [
"model"
] |
c8cc693f99aa481b08f63085f068fa311a416dc4 | 23,512 | h | C | be/src/olap/olap_engine.h | crazyleeyang/incubator-doris | 85b4619d54ca109a6c6d49dd10541d660ad8058c | [
"Apache-2.0"
] | 2 | 2019-06-06T08:05:59.000Z | 2019-06-06T08:06:04.000Z | be/src/olap/olap_engine.h | LiangchangZ/incubator-doris | cb91e15f1e96ade86c909b90456b02977e6cbf56 | [
"Apache-2.0"
] | 10 | 2020-03-04T23:28:37.000Z | 2021-12-14T21:33:14.000Z | be/src/olap/olap_engine.h | LiangchangZ/incubator-doris | cb91e15f1e96ade86c909b90456b02977e6cbf56 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#ifndef DORIS_BE_SRC_OLAP_OLAP_ENGINE_H
#define DORIS_BE_SRC_OLAP_OLAP_ENGINE_H
#include <ctime>
#include <list>
#include <map>
#include <mutex>
#include <condition_variable>
#include <set>
#include <string>
#include <vector>
#include <thread>
#include <rapidjson/document.h>
#include <pthread.h>
#include "agent/status.h"
#include "common/status.h"
#include "gen_cpp/AgentService_types.h"
#include "gen_cpp/BackendService_types.h"
#include "gen_cpp/MasterService_types.h"
#include "olap/atomic.h"
#include "olap/lru_cache.h"
#include "olap/olap_common.h"
#include "olap/olap_define.h"
#include "olap/olap_table.h"
#include "olap/olap_meta.h"
#include "olap/options.h"
namespace doris {
class OLAPTable;
class OlapStore;
struct RootPathInfo {
RootPathInfo():
capacity(1),
available(0),
data_used_capacity(0),
is_used(false) { }
std::string path;
int64_t path_hash;
int64_t capacity; // 总空间,单位字节
int64_t available; // 可用空间,单位字节
int64_t data_used_capacity;
bool is_used; // 是否可用标识
TStorageMedium::type storage_medium; // 存储介质类型:SSD|HDD
};
// OLAPEngine singleton to manage all Table pointers.
// Providing add/drop/get operations.
// OLAPEngine instance doesn't own the Table resources, just hold the pointer,
// allocation/deallocation must be done outside.
class OLAPEngine {
public:
OLAPEngine() { }
OLAPEngine(const EngineOptions& options);
~OLAPEngine();
static Status open(const EngineOptions& options, OLAPEngine** engine_ptr);
static void set_instance(OLAPEngine* engine) {
_s_instance = engine;
}
static OLAPEngine *get_instance() {
return _s_instance;
}
// Get table pointer
// TODO(cmy): I think it is better to return Status instead of OLAPTablePtr,
// so that the caller can decide what to do next based on Status.
// Currently, I just add a new parameter 'err' to save the error msg.
// This should be redesigned later.
OLAPTablePtr get_table(TTabletId tablet_id, SchemaHash schema_hash, bool load_table = true, std::string* err = nullptr);
OLAPStatus get_tables_by_id(TTabletId tablet_id, std::list<OLAPTablePtr>* table_list);
bool check_tablet_id_exist(TTabletId tablet_id);
OLAPStatus create_table(const TCreateTabletReq& request);
// Create new table for OLAPEngine
//
// Return OLAPTable * succeeded; Otherwise, return NULL if failed
OLAPTablePtr create_table(const TCreateTabletReq& request,
const std::string* ref_root_path,
const bool is_schema_change_table,
const OLAPTablePtr ref_olap_table);
// Add a table pointer to OLAPEngine
// If force, drop the existing table add this new one
//
// Return OLAP_SUCCESS, if run ok
// OLAP_ERR_TABLE_INSERT_DUPLICATION_ERROR, if find duplication
// OLAP_ERR_NOT_INITED, if not inited
OLAPStatus add_table(TTabletId tablet_id, SchemaHash schema_hash,
const OLAPTablePtr& table, bool force = false);
OLAPStatus add_transaction(TPartitionId partition_id, TTransactionId transaction_id,
TTabletId tablet_id, SchemaHash schema_hash,
const PUniqueId& load_id);
void delete_transaction(TPartitionId partition_id, TTransactionId transaction_id,
TTabletId tablet_id, SchemaHash schema_hash,
bool delete_from_tablet = true);
void get_transactions_by_tablet(OLAPTablePtr tablet, int64_t* partition_id,
std::set<int64_t>* transaction_ids);
bool has_transaction(TPartitionId partition_id, TTransactionId transaction_id,
TTabletId tablet_id, SchemaHash schema_hash);
OLAPStatus publish_version(const TPublishVersionRequest& publish_version_req,
std::vector<TTabletId>* error_tablet_ids);
void clear_transaction_task(const TTransactionId transaction_id,
const std::vector<TPartitionId> partition_ids);
OLAPStatus clone_incremental_data(OLAPTablePtr tablet, OLAPHeader& clone_header,
int64_t committed_version);
OLAPStatus clone_full_data(OLAPTablePtr tablet, OLAPHeader& clone_header);
// Add empty data for OLAPTable
//
// Return OLAP_SUCCESS, if run ok
OLAPStatus create_init_version(
TTabletId tablet_id, SchemaHash schema_hash,
Version version, VersionHash version_hash);
// Drop a table by description
// If set keep_files == true, files will NOT be deleted when deconstruction.
// Return OLAP_SUCCESS, if run ok
// OLAP_ERR_TABLE_DELETE_NOEXIST_ERROR, if table not exist
// OLAP_ERR_NOT_INITED, if not inited
OLAPStatus drop_table(
TTabletId tablet_id, SchemaHash schema_hash, bool keep_files = false);
// Drop table directly with check schema change info.
OLAPStatus _drop_table_directly(TTabletId tablet_id, TSchemaHash schema_hash, bool keep_files = false);
OLAPStatus _drop_table_directly_unlocked(TTabletId tablet_id, TSchemaHash schema_hash, bool keep_files = false);
OLAPStatus drop_tables_on_error_root_path(const std::vector<TabletInfo>& tablet_info_vec);
// Prevent schema change executed concurrently.
bool try_schema_change_lock(TTabletId tablet_id);
void release_schema_change_lock(TTabletId tablet_id);
// 获取所有tables的名字
//
// Return OLAP_SUCCESS, if run ok
// OLAP_ERR_INPUT_PARAMETER_ERROR, if tables is null
OLAPStatus report_tablet_info(TTabletInfo* tablet_info);
OLAPStatus report_all_tablets_info(std::map<TTabletId, TTablet>* tablets_info);
void get_tablet_stat(TTabletStatResult& result);
// Instance should be inited from create_instance
// MUST NOT be called in other circumstances.
OLAPStatus open();
// Clear status(tables, ...)
OLAPStatus clear();
void start_clean_fd_cache();
void perform_cumulative_compaction(OlapStore* store);
void perform_base_compaction(OlapStore* store);
// 获取cache的使用情况信息
void get_cache_status(rapidjson::Document* document) const;
void check_none_row_oriented_table(const std::vector<OlapStore*>& stores);
OLAPStatus check_none_row_oriented_table_in_path(
OlapStore* store, TTabletId tablet_id,
SchemaHash schema_hash, const std::string& schema_hash_path);
OLAPStatus _check_none_row_oriented_table_in_store(OlapStore* store);
// Note: 这里只能reload原先已经存在的root path,即re-load启动时就登记的root path
// 是允许的,但re-load全新的path是不允许的,因为此处没有彻底更新ce调度器信息
void load_stores(const std::vector<OlapStore*>& stores);
OLAPStatus load_one_tablet(OlapStore* store,
TTabletId tablet_id,
SchemaHash schema_hash,
const std::string& schema_hash_path,
bool force = false);
Cache* index_stream_lru_cache() {
return _index_stream_lru_cache;
}
// 清理trash和snapshot文件,返回清理后的磁盘使用量
OLAPStatus start_trash_sweep(double *usage);
template<bool include_unused = false>
std::vector<OlapStore*> get_stores();
Status set_cluster_id(int32_t cluster_id);
// @brief 设置root_path是否可用
void set_store_used_flag(const std::string& root_path, bool is_used);
// @brief 获取所有root_path信息
OLAPStatus get_all_root_path_info(std::vector<RootPathInfo>* root_paths_info);
void get_all_available_root_path(std::vector<std::string>* available_paths);
OLAPStatus register_table_into_root_path(OLAPTable* olap_table);
// 磁盘状态监测。监测unused_flag路劲新的对应root_path unused标识位,
// 当检测到有unused标识时,从内存中删除对应表信息,磁盘数据不动。
// 当磁盘状态为不可用,但未检测到unused标识时,需要从root_path上
// 重新加载数据。
void start_disk_stat_monitor();
// get root path for creating table. The returned vector of root path should be random,
// for avoiding that all the table would be deployed one disk.
std::vector<OlapStore*> get_stores_for_create_table(
TStorageMedium::type storage_medium);
OlapStore* get_store(const std::string& path);
OlapStore* get_store(int64_t path_hash);
uint32_t available_storage_medium_type_count() {
return _available_storage_medium_type_count;
}
int32_t effective_cluster_id() const {
return _effective_cluster_id;
}
uint32_t get_file_system_count() {
return _store_map.size();
}
// @brief 创建snapshot
// @param tablet_id [in] 原表的id
// @param schema_hash [in] 原表的schema,与tablet_id参数合起来唯一确定一张表
// @param snapshot_path [out] 新生成的snapshot的路径
OLAPStatus make_snapshot(
const TSnapshotRequest& request,
std::string* snapshot_path);
// @brief 释放snapshot
// @param snapshot_path [in] 要被释放的snapshot的路径,只包含到ID
OLAPStatus release_snapshot(const std::string& snapshot_path);
// @brief 迁移数据,从一种存储介质到另一种存储介质
OLAPStatus storage_medium_migrate(
TTabletId tablet_id,
TSchemaHash schema_hash,
TStorageMedium::type storage_medium);
void start_delete_unused_index();
void add_unused_index(SegmentGroup* olap_index);
// check whether files are in gc's unused files
// revoke them from the unused files if they exists
void revoke_files_from_gc(const std::vector<std::string>& files_to_check);
// ######################### ALTER TABLE BEGIN #########################
// The following interfaces are all about alter tablet operation,
// the main logical is that generating a new tablet with different
// schema on base tablet.
// Create rollup tablet on base tablet, after create_rollup_table,
// both base tablet and new tablet is effective.
//
// @param [in] request specify base tablet, new tablet and its schema
// @return OLAP_SUCCESS if submit success
OLAPStatus create_rollup_table(const TAlterTabletReq& request);
// Do schema change on tablet, OLAPEngine support
// add column, drop column, alter column type and order,
// after schema_change, base tablet is abandoned.
// Note that the two tablets has same tablet_id but different schema_hash
//
// @param [in] request specify base tablet, new tablet and its schema
// @return OLAP_SUCCESS if submit success
OLAPStatus schema_change(const TAlterTabletReq& request);
// Show status of all alter table operation.
//
// @param [in] tablet_id & schema_hash specify a tablet
// @return alter table status
AlterTableStatus show_alter_table_status(TTabletId tablet_id, TSchemaHash schema_hash);
OLAPStatus compute_checksum(
TTabletId tablet_id,
TSchemaHash schema_hash,
TVersion version,
TVersionHash version_hash,
uint32_t* checksum);
OLAPStatus cancel_delete(const TCancelDeleteDataReq& request);
// Delete data of specified tablet according to delete conditions,
// once delete_data command submit success, deleted data is not visible,
// but not actually deleted util delay_delete_time run out.
//
// @param [in] request specify tablet and delete conditions
// @param [out] tablet_info_vec return tablet lastest status, which
// include version info, row count, data size, etc
// @return OLAP_SUCCESS if submit delete_data success
virtual OLAPStatus delete_data(
const TPushReq& request,
std::vector<TTabletInfo>* tablet_info_vec);
OLAPStatus recover_tablet_until_specfic_version(
const TRecoverTabletReq& recover_tablet_req);
// before doing incremental clone,
// need to calculate tablet's download dir and tablet's missing versions
virtual std::string get_info_before_incremental_clone(OLAPTablePtr tablet,
int64_t committed_version, std::vector<Version>* missing_versions);
virtual OLAPStatus finish_clone(OLAPTablePtr tablet, const std::string& clone_dir,
int64_t committed_version, bool is_incremental_clone);
// Obtain the path by specified path hash
virtual OLAPStatus obtain_shard_path_by_hash(
int64_t path_hash,
std::string* shared_path,
OlapStore** store);
// Obtain shard path for new tablet.
//
// @param [out] shard_path choose an available root_path to clone new tablet
// @return error code
virtual OLAPStatus obtain_shard_path(
TStorageMedium::type storage_medium,
std::string* shared_path,
OlapStore** store);
// Load new tablet to make it effective.
//
// @param [in] root_path specify root path of new tablet
// @param [in] request specify new tablet info
// @return OLAP_SUCCESS if load tablet success
virtual OLAPStatus load_header(
const std::string& shard_path, const TCloneReq& request);
virtual OLAPStatus load_header(
OlapStore* store,
const std::string& shard_path,
TTabletId tablet_id,
TSchemaHash schema_hash);
OLAPStatus clear_alter_task(const TTabletId tablet_id,
const TSchemaHash schema_hash);
OLAPStatus push(
const TPushReq& request,
std::vector<TTabletInfo>* tablet_info_vec);
// call this if you want to trigger a disk and tablet report
void report_notify(bool is_all) {
is_all ? _report_cv.notify_all() : _report_cv.notify_one();
}
// call this to wait a report notification until timeout
void wait_for_report_notify(int64_t timeout_sec, bool is_tablet_report) {
std::unique_lock<std::mutex> lk(_report_mtx);
auto cv_status = _report_cv.wait_for(lk, std::chrono::seconds(timeout_sec));
if (cv_status == std::cv_status::no_timeout) {
is_tablet_report ? _is_report_olap_table_already = true :
_is_report_disk_state_already = true;
}
}
private:
OLAPStatus check_all_root_path_cluster_id();
bool _used_disk_not_enough(uint32_t unused_num, uint32_t total_num);
OLAPStatus _get_path_available_capacity(
const std::string& root_path,
int64_t* disk_available);
OLAPStatus _config_root_path_unused_flag_file(
const std::string& root_path,
std::string* unused_flag_file);
void _delete_tables_on_unused_root_path();
void _update_storage_medium_type_count();
OLAPStatus _judge_and_update_effective_cluster_id(int32_t cluster_id);
OLAPStatus _calc_snapshot_id_path(
const OLAPTablePtr& olap_table,
std::string* out_path);
std::string _get_schema_hash_full_path(
const OLAPTablePtr& ref_olap_table,
const std::string& location) const;
std::string _get_header_full_path(
const OLAPTablePtr& ref_olap_table,
const std::string& schema_hash_path) const;
void _update_header_file_info(
const std::vector<VersionEntity>& shortest_version_entity,
OLAPHeader* header);
OLAPStatus _link_index_and_data_files(
const std::string& header_path,
const OLAPTablePtr& ref_olap_table,
const std::vector<VersionEntity>& version_entity_vec);
OLAPStatus _copy_index_and_data_files(
const std::string& header_path,
const OLAPTablePtr& ref_olap_table,
std::vector<VersionEntity>& version_entity_vec);
OLAPStatus _create_snapshot_files(
const OLAPTablePtr& ref_olap_table,
const TSnapshotRequest& request,
std::string* snapshot_path);
OLAPStatus _create_incremental_snapshot_files(
const OLAPTablePtr& ref_olap_table,
const TSnapshotRequest& request,
std::string* snapshot_path);
OLAPStatus _prepare_snapshot_dir(const OLAPTablePtr& ref_olap_table,
std::string* snapshot_id_path);
OLAPStatus _append_single_delta(
const TSnapshotRequest& request,
OlapStore* store);
std::string _construct_index_file_path(
const std::string& tablet_path_prefix,
const Version& version,
VersionHash version_hash,
int32_t segment_group_id, int32_t segment) const;
std::string _construct_data_file_path(
const std::string& tablet_path_prefix,
const Version& version,
VersionHash version_hash,
int32_t segment_group_id, int32_t segment) const;
OLAPStatus _generate_new_header(
OlapStore* store,
const uint64_t new_shard,
const OLAPTablePtr& tablet,
const std::vector<VersionEntity>& version_entity_vec, OLAPHeader* new_olap_header);
OLAPStatus _create_hard_link(const std::string& from_path, const std::string& to_path);
OLAPStatus _start_bg_worker();
OLAPStatus _create_init_version(OLAPTablePtr olap_table, const TCreateTabletReq& request);
private:
struct TableInstances {
Mutex schema_change_lock;
std::list<OLAPTablePtr> table_arr;
};
enum CompactionType {
BASE_COMPACTION = 1,
CUMULATIVE_COMPACTION = 2
};
struct CompactionCandidate {
CompactionCandidate(uint32_t nicumulative_compaction_, int64_t tablet_id_, uint32_t index_) :
nice(nicumulative_compaction_), tablet_id(tablet_id_), disk_index(index_) {}
uint32_t nice; // 优先度
int64_t tablet_id;
uint32_t disk_index = -1;
};
struct CompactionCandidateComparator {
bool operator()(const CompactionCandidate& a, const CompactionCandidate& b) {
return a.nice > b.nice;
}
};
struct CompactionDiskStat {
CompactionDiskStat(std::string path, uint32_t index, bool used) :
storage_path(path),
disk_index(index),
task_running(0),
task_remaining(0),
is_used(used){}
const std::string storage_path;
const uint32_t disk_index;
uint32_t task_running;
uint32_t task_remaining;
bool is_used;
};
typedef std::map<int64_t, TableInstances> tablet_map_t;
typedef std::map<std::string, uint32_t> file_system_task_count_t;
OLAPTablePtr _get_table_with_no_lock(TTabletId tablet_id, SchemaHash schema_hash);
// 遍历root所指定目录, 通过dirs返回此目录下所有有文件夹的名字, files返回所有文件的名字
OLAPStatus _dir_walk(const std::string& root,
std::set<std::string>* dirs,
std::set<std::string>* files);
// 扫描目录, 加载表
OLAPStatus _load_store(OlapStore* store);
OLAPStatus _create_new_table_header(const TCreateTabletReq& request,
OlapStore* store,
const bool is_schema_change_table,
const OLAPTablePtr ref_olap_table,
OLAPHeader* header);
OLAPStatus _check_existed_or_else_create_dir(const std::string& path);
OLAPTablePtr _find_best_tablet_to_compaction(CompactionType compaction_type, OlapStore* store);
bool _can_do_compaction(OLAPTablePtr table);
void _cancel_unfinished_schema_change();
OLAPStatus _do_sweep(
const std::string& scan_root, const time_t& local_tm_now, const uint32_t expire);
void _build_tablet_info(OLAPTablePtr olap_table, TTabletInfo* tablet_info);
void _build_tablet_stat();
EngineOptions _options;
std::mutex _store_lock;
std::map<std::string, OlapStore*> _store_map;
uint32_t _available_storage_medium_type_count;
int32_t _effective_cluster_id;
bool _is_all_cluster_id_exist;
bool _is_drop_tables;
// 错误磁盘所在百分比,超过设定的值,则engine需要退出运行
uint32_t _min_percentage_of_error_disk;
RWMutex _tablet_map_lock;
tablet_map_t _tablet_map;
RWMutex _transaction_tablet_map_lock;
using TxnKey = std::pair<int64_t, int64_t>; // partition_id, transaction_id;
std::map<TxnKey, std::map<TabletInfo, std::vector<PUniqueId>>> _transaction_tablet_map;
size_t _global_table_id;
Cache* _file_descriptor_lru_cache;
Cache* _index_stream_lru_cache;
uint32_t _max_base_compaction_task_per_disk;
uint32_t _max_cumulative_compaction_task_per_disk;
Mutex _fs_task_mutex;
file_system_task_count_t _fs_base_compaction_task_num_map;
std::vector<CompactionCandidate> _cumulative_compaction_candidate;
// cache to save tablets' statistics, such as data size and row
// TODO(cmy): for now, this is a naive implementation
std::map<int64_t, TTabletStat> _tablet_stat_cache;
std::mutex _tablet_stat_mutex;
// last update time of tablet stat cache
int64_t _tablet_stat_cache_update_time_ms;
static OLAPEngine* _s_instance;
// snapshot
Mutex _snapshot_mutex;
uint64_t _snapshot_base_id;
std::unordered_map<SegmentGroup*, std::vector<std::string>> _gc_files;
Mutex _gc_mutex;
// Thread functions
// base compaction thread process function
void* _base_compaction_thread_callback(void* arg, OlapStore* store);
// garbage sweep thread process function. clear snapshot and trash folder
void* _garbage_sweeper_thread_callback(void* arg);
// delete table with io error process function
void* _disk_stat_monitor_thread_callback(void* arg);
// unused index process function
void* _unused_index_thread_callback(void* arg);
// cumulative process function
void* _cumulative_compaction_thread_callback(void* arg, OlapStore* store);
// clean file descriptors cache
void* _fd_cache_clean_callback(void* arg);
// thread to monitor snapshot expiry
std::thread _garbage_sweeper_thread;
// thread to monitor disk stat
std::thread _disk_stat_monitor_thread;
// thread to monitor unused index
std::thread _unused_index_thread;
// thread to run base compaction
std::vector<std::thread> _base_compaction_threads;
// thread to check cumulative
std::vector<std::thread> _cumulative_compaction_threads;
std::thread _fd_cache_clean_thread;
static atomic_t _s_request_number;
// for tablet and disk report
std::mutex _report_mtx;
std::condition_variable _report_cv;
std::atomic_bool _is_report_disk_state_already;
std::atomic_bool _is_report_olap_table_already;
};
} // namespace doris
#endif // DORIS_BE_SRC_OLAP_OLAP_ENGINE_H
| 36.910518 | 124 | 0.69305 | [
"vector"
] |
c8ce52433d2be51ac9b1f06a3b317f8c32037ae1 | 793 | h | C | libgo/netio/unix/reactor.h | sunny-shu/libgo | 948e34f31d3a5335aeab19e82ade8776fcbb6478 | [
"MIT"
] | 2,831 | 2015-12-24T03:21:07.000Z | 2022-03-31T18:37:29.000Z | libgo/netio/unix/reactor.h | sunny-shu/libgo | 948e34f31d3a5335aeab19e82ade8776fcbb6478 | [
"MIT"
] | 238 | 2016-01-26T03:35:35.000Z | 2022-03-18T11:17:00.000Z | libgo/netio/unix/reactor.h | sunny-shu/libgo | 948e34f31d3a5335aeab19e82ade8776fcbb6478 | [
"MIT"
] | 781 | 2015-12-24T04:28:34.000Z | 2022-03-26T05:23:12.000Z | #pragma once
#include "../../common/config.h"
#include "reactor_element.h"
namespace co {
class Reactor
{
public:
static Reactor& Select(int fd);
// @returns: ignore
static int InitializeReactorCount(uint8_t n);
static int GetReactorThreadCount();
public:
typedef ReactorElement::Entry Entry;
Reactor();
bool Add(int fd, short int pollEvent, Entry const& entry);
virtual void Run() = 0;
// ---------- call by element
virtual bool AddEvent(int fd, short int addEvent, short int promiseEvent) = 0;
virtual bool DelEvent(int fd, short int delEvent, short int promiseEvent) = 0;
protected:
void InitLoopThread();
private:
static std::vector<Reactor*> sReactors_;
static std::atomic<uint8_t> sReactorCount_;
};
} // namespace co
| 19.825 | 82 | 0.679697 | [
"vector"
] |
c8db91f2b8f877481335cdf8a73d931a10d8185b | 33,083 | c | C | 2-dev-env-docker/2-tool/files/app/emacs/src/ralloc.c | jiftle/dev-docker | 078e4d3c05e4df06f4f8bff7a03ce4b6de902b08 | [
"MIT"
] | null | null | null | 2-dev-env-docker/2-tool/files/app/emacs/src/ralloc.c | jiftle/dev-docker | 078e4d3c05e4df06f4f8bff7a03ce4b6de902b08 | [
"MIT"
] | null | null | null | 2-dev-env-docker/2-tool/files/app/emacs/src/ralloc.c | jiftle/dev-docker | 078e4d3c05e4df06f4f8bff7a03ce4b6de902b08 | [
"MIT"
] | null | null | null | /* Block-relocating memory allocator.
Copyright (C) 1993, 1995, 2000-2019 Free Software Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
/* NOTES:
Only relocate the blocs necessary for SIZE in r_alloc_sbrk,
rather than all of them. This means allowing for a possible
hole between the first bloc and the end of malloc storage. */
#include <config.h>
#include <stddef.h>
#ifdef emacs
# include "lisp.h"
# include "blockinput.h"
# include <unistd.h>
#endif
#include "getpagesize.h"
/* A flag to indicate whether we have initialized ralloc yet. For
Emacs's sake, please do not make this local to malloc_init; on some
machines, the dumping procedure makes all static variables
read-only. On these machines, the word static is #defined to be
the empty string, meaning that r_alloc_initialized becomes an
automatic variable, and loses its value each time Emacs is started
up. */
static int r_alloc_initialized = 0;
static void r_alloc_init (void);
/* Declarations for working with the malloc, ralloc, and system breaks. */
/* Function to set the real break value. */
void *(*real_morecore) (ptrdiff_t);
/* The break value, as seen by malloc. */
static void *virtual_break_value;
/* The address of the end of the last data in use by ralloc,
including relocatable blocs as well as malloc data. */
static void *break_value;
/* This is the size of a page. We round memory requests to this boundary. */
static int page_size;
/* Whenever we get memory from the system, get this many extra bytes. This
must be a multiple of page_size. */
static int extra_bytes;
/* Macros for rounding. Note that rounding to any value is possible
by changing the definition of PAGE. */
#define PAGE (getpagesize ())
#define PAGE_ROUNDUP(size) (((size_t) (size) + page_size - 1) \
& ~((size_t) (page_size - 1)))
#define MEM_ALIGN sizeof (double)
#define MEM_ROUNDUP(addr) (((size_t) (addr) + MEM_ALIGN - 1) \
& ~(MEM_ALIGN - 1))
/* The hook `malloc' uses for the function which gets more space
from the system. */
#ifdef HAVE_MALLOC_H
# include <malloc.h>
#endif
#ifndef DOUG_LEA_MALLOC
extern void *(*__morecore) (ptrdiff_t);
#endif
/***********************************************************************
Implementation using sbrk
***********************************************************************/
/* Data structures of heaps and blocs. */
/* The relocatable objects, or blocs, and the malloc data
both reside within one or more heaps.
Each heap contains malloc data, running from `start' to `bloc_start',
and relocatable objects, running from `bloc_start' to `free'.
Relocatable objects may relocate within the same heap
or may move into another heap; the heaps themselves may grow
but they never move.
We try to make just one heap and make it larger as necessary.
But sometimes we can't do that, because we can't get contiguous
space to add onto the heap. When that happens, we start a new heap. */
typedef struct heap
{
struct heap *next;
struct heap *prev;
/* Start of memory range of this heap. */
void *start;
/* End of memory range of this heap. */
void *end;
/* Start of relocatable data in this heap. */
void *bloc_start;
/* Start of unused space in this heap. */
void *free;
/* First bloc in this heap. */
struct bp *first_bloc;
/* Last bloc in this heap. */
struct bp *last_bloc;
} *heap_ptr;
#define NIL_HEAP ((heap_ptr) 0)
/* This is the first heap object.
If we need additional heap objects, each one resides at the beginning of
the space it covers. */
static struct heap heap_base;
/* Head and tail of the list of heaps. */
static heap_ptr first_heap, last_heap;
/* These structures are allocated in the malloc arena.
The linked list is kept in order of increasing '.data' members.
The data blocks abut each other; if b->next is non-nil, then
b->data + b->size == b->next->data.
An element with variable==NULL denotes a freed block, which has not yet
been collected. They may only appear while r_alloc_freeze_level > 0,
and will be freed when the arena is thawed. Currently, these blocs are
not reusable, while the arena is frozen. Very inefficient. */
typedef struct bp
{
struct bp *next;
struct bp *prev;
void **variable;
void *data;
size_t size;
void *new_data; /* temporarily used for relocation */
struct heap *heap; /* Heap this bloc is in. */
} *bloc_ptr;
#define NIL_BLOC ((bloc_ptr) 0)
#define BLOC_PTR_SIZE (sizeof (struct bp))
/* Head and tail of the list of relocatable blocs. */
static bloc_ptr first_bloc, last_bloc;
static int use_relocatable_buffers;
/* If >0, no relocation whatsoever takes place. */
static int r_alloc_freeze_level;
/* Functions to get and return memory from the system. */
/* Find the heap that ADDRESS falls within. */
static heap_ptr
find_heap (void *address)
{
heap_ptr heap;
for (heap = last_heap; heap; heap = heap->prev)
{
if (heap->start <= address && address <= heap->end)
return heap;
}
return NIL_HEAP;
}
/* Find SIZE bytes of space in a heap.
Try to get them at ADDRESS (which must fall within some heap's range)
if we can get that many within one heap.
If enough space is not presently available in our reserve, this means
getting more page-aligned space from the system. If the returned space
is not contiguous to the last heap, allocate a new heap, and append it
to the heap list.
obtain does not try to keep track of whether space is in use or not
in use. It just returns the address of SIZE bytes that fall within a
single heap. If you call obtain twice in a row with the same arguments,
you typically get the same value. It's the caller's responsibility to
keep track of what space is in use.
Return the address of the space if all went well, or zero if we couldn't
allocate the memory. */
static void *
obtain (void *address, size_t size)
{
heap_ptr heap;
size_t already_available;
/* Find the heap that ADDRESS falls within. */
for (heap = last_heap; heap; heap = heap->prev)
{
if (heap->start <= address && address <= heap->end)
break;
}
if (! heap)
emacs_abort ();
/* If we can't fit SIZE bytes in that heap,
try successive later heaps. */
while (heap && (char *) address + size > (char *) heap->end)
{
heap = heap->next;
if (heap == NIL_HEAP)
break;
address = heap->bloc_start;
}
/* If we can't fit them within any existing heap,
get more space. */
if (heap == NIL_HEAP)
{
void *new = real_morecore (0);
size_t get;
already_available = (char *) last_heap->end - (char *) address;
if (new != last_heap->end)
{
/* Someone else called sbrk. Make a new heap. */
heap_ptr new_heap = (heap_ptr) MEM_ROUNDUP (new);
void *bloc_start = (void *) MEM_ROUNDUP ((void *) (new_heap + 1));
if (real_morecore ((char *) bloc_start - (char *) new) != new)
return 0;
new_heap->start = new;
new_heap->end = bloc_start;
new_heap->bloc_start = bloc_start;
new_heap->free = bloc_start;
new_heap->next = NIL_HEAP;
new_heap->prev = last_heap;
new_heap->first_bloc = NIL_BLOC;
new_heap->last_bloc = NIL_BLOC;
last_heap->next = new_heap;
last_heap = new_heap;
address = bloc_start;
already_available = 0;
}
/* Add space to the last heap (which we may have just created).
Get some extra, so we can come here less often. */
get = size + extra_bytes - already_available;
get = (char *) PAGE_ROUNDUP ((char *) last_heap->end + get)
- (char *) last_heap->end;
if (real_morecore (get) != last_heap->end)
return 0;
last_heap->end = (char *) last_heap->end + get;
}
return address;
}
/* Return unused heap space to the system
if there is a lot of unused space now.
This can make the last heap smaller;
it can also eliminate the last heap entirely. */
static void
relinquish (void)
{
register heap_ptr h;
ptrdiff_t excess = 0;
/* Add the amount of space beyond break_value
in all heaps which have extend beyond break_value at all. */
for (h = last_heap; h && break_value < h->end; h = h->prev)
{
excess += (char *) h->end - (char *) ((break_value < h->bloc_start)
? h->bloc_start : break_value);
}
if (excess > extra_bytes * 2 && real_morecore (0) == last_heap->end)
{
/* Keep extra_bytes worth of empty space.
And don't free anything unless we can free at least extra_bytes. */
excess -= extra_bytes;
if ((char *) last_heap->end - (char *) last_heap->bloc_start <= excess)
{
heap_ptr lh_prev;
/* This heap should have no blocs in it. If it does, we
cannot return it to the system. */
if (last_heap->first_bloc != NIL_BLOC
|| last_heap->last_bloc != NIL_BLOC)
return;
/* Return the last heap, with its header, to the system. */
excess = (char *) last_heap->end - (char *) last_heap->start;
lh_prev = last_heap->prev;
/* If the system doesn't want that much memory back, leave
last_heap unaltered to reflect that. This can occur if
break_value is still within the original data segment. */
if (real_morecore (- excess) != 0)
{
last_heap = lh_prev;
last_heap->next = NIL_HEAP;
}
}
else
{
excess = ((char *) last_heap->end
- (char *) PAGE_ROUNDUP ((char *) last_heap->end - excess));
/* If the system doesn't want that much memory back, leave
the end of the last heap unchanged to reflect that. This
can occur if break_value is still within the original
data segment. */
if (real_morecore (- excess) != 0)
last_heap->end = (char *) last_heap->end - excess;
}
}
}
/* The meat - allocating, freeing, and relocating blocs. */
/* Find the bloc referenced by the address in PTR. Returns a pointer
to that block. */
static bloc_ptr
find_bloc (void **ptr)
{
bloc_ptr p = first_bloc;
while (p != NIL_BLOC)
{
/* Consistency check. Don't return inconsistent blocs.
Don't abort here, as callers might be expecting this, but
callers that always expect a bloc to be returned should abort
if one isn't to avoid a memory corruption bug that is
difficult to track down. */
if (p->variable == ptr && p->data == *ptr)
return p;
p = p->next;
}
return p;
}
/* Allocate a bloc of SIZE bytes and append it to the chain of blocs.
Returns a pointer to the new bloc, or zero if we couldn't allocate
memory for the new block. */
static bloc_ptr
get_bloc (size_t size)
{
bloc_ptr new_bloc;
heap_ptr heap;
if (! (new_bloc = malloc (BLOC_PTR_SIZE))
|| ! (new_bloc->data = obtain (break_value, size)))
{
free (new_bloc);
return 0;
}
break_value = (char *) new_bloc->data + size;
new_bloc->size = size;
new_bloc->next = NIL_BLOC;
new_bloc->variable = NULL;
new_bloc->new_data = 0;
/* Record in the heap that this space is in use. */
heap = find_heap (new_bloc->data);
heap->free = break_value;
/* Maintain the correspondence between heaps and blocs. */
new_bloc->heap = heap;
heap->last_bloc = new_bloc;
if (heap->first_bloc == NIL_BLOC)
heap->first_bloc = new_bloc;
/* Put this bloc on the doubly-linked list of blocs. */
if (first_bloc)
{
new_bloc->prev = last_bloc;
last_bloc->next = new_bloc;
last_bloc = new_bloc;
}
else
{
first_bloc = last_bloc = new_bloc;
new_bloc->prev = NIL_BLOC;
}
return new_bloc;
}
/* Calculate new locations of blocs in the list beginning with BLOC,
relocating it to start at ADDRESS, in heap HEAP. If enough space is
not presently available in our reserve, call obtain for
more space.
Store the new location of each bloc in its new_data field.
Do not touch the contents of blocs or break_value. */
static int
relocate_blocs (bloc_ptr bloc, heap_ptr heap, void *address)
{
bloc_ptr b = bloc;
/* No need to ever call this if arena is frozen, bug somewhere! */
if (r_alloc_freeze_level)
emacs_abort ();
while (b)
{
/* If bloc B won't fit within HEAP,
move to the next heap and try again. */
while (heap && (char *) address + b->size > (char *) heap->end)
{
heap = heap->next;
if (heap == NIL_HEAP)
break;
address = heap->bloc_start;
}
/* If BLOC won't fit in any heap,
get enough new space to hold BLOC and all following blocs. */
if (heap == NIL_HEAP)
{
bloc_ptr tb = b;
size_t s = 0;
/* Add up the size of all the following blocs. */
while (tb != NIL_BLOC)
{
if (tb->variable)
s += tb->size;
tb = tb->next;
}
/* Get that space. */
address = obtain (address, s);
if (address == 0)
return 0;
heap = last_heap;
}
/* Record the new address of this bloc
and update where the next bloc can start. */
b->new_data = address;
if (b->variable)
address = (char *) address + b->size;
b = b->next;
}
return 1;
}
/* Update the records of which heaps contain which blocs, starting
with heap HEAP and bloc BLOC. */
static void
update_heap_bloc_correspondence (bloc_ptr bloc, heap_ptr heap)
{
register bloc_ptr b;
/* Initialize HEAP's status to reflect blocs before BLOC. */
if (bloc != NIL_BLOC && bloc->prev != NIL_BLOC && bloc->prev->heap == heap)
{
/* The previous bloc is in HEAP. */
heap->last_bloc = bloc->prev;
heap->free = (char *) bloc->prev->data + bloc->prev->size;
}
else
{
/* HEAP contains no blocs before BLOC. */
heap->first_bloc = NIL_BLOC;
heap->last_bloc = NIL_BLOC;
heap->free = heap->bloc_start;
}
/* Advance through blocs one by one. */
for (b = bloc; b != NIL_BLOC; b = b->next)
{
/* Advance through heaps, marking them empty,
till we get to the one that B is in. */
while (heap)
{
if (heap->bloc_start <= b->data && b->data <= heap->end)
break;
heap = heap->next;
/* We know HEAP is not null now,
because there has to be space for bloc B. */
heap->first_bloc = NIL_BLOC;
heap->last_bloc = NIL_BLOC;
heap->free = heap->bloc_start;
}
/* Update HEAP's status for bloc B. */
heap->free = (char *) b->data + b->size;
heap->last_bloc = b;
if (heap->first_bloc == NIL_BLOC)
heap->first_bloc = b;
/* Record that B is in HEAP. */
b->heap = heap;
}
/* If there are any remaining heaps and no blocs left,
mark those heaps as empty. */
heap = heap->next;
while (heap)
{
heap->first_bloc = NIL_BLOC;
heap->last_bloc = NIL_BLOC;
heap->free = heap->bloc_start;
heap = heap->next;
}
}
/* Resize BLOC to SIZE bytes. This relocates the blocs
that come after BLOC in memory. */
static int
resize_bloc (bloc_ptr bloc, size_t size)
{
bloc_ptr b;
heap_ptr heap;
void *address;
size_t old_size;
/* No need to ever call this if arena is frozen, bug somewhere! */
if (r_alloc_freeze_level)
emacs_abort ();
if (bloc == NIL_BLOC || size == bloc->size)
return 1;
for (heap = first_heap; heap != NIL_HEAP; heap = heap->next)
{
if (heap->bloc_start <= bloc->data && bloc->data <= heap->end)
break;
}
if (heap == NIL_HEAP)
emacs_abort ();
old_size = bloc->size;
bloc->size = size;
/* Note that bloc could be moved into the previous heap. */
address = (bloc->prev ? (char *) bloc->prev->data + bloc->prev->size
: (char *) first_heap->bloc_start);
while (heap)
{
if (heap->bloc_start <= address && address <= heap->end)
break;
heap = heap->prev;
}
if (! relocate_blocs (bloc, heap, address))
{
bloc->size = old_size;
return 0;
}
if (size > old_size)
{
for (b = last_bloc; b != bloc; b = b->prev)
{
if (!b->variable)
{
b->size = 0;
b->data = b->new_data;
}
else
{
if (b->new_data != b->data)
memmove (b->new_data, b->data, b->size);
*b->variable = b->data = b->new_data;
}
}
if (!bloc->variable)
{
bloc->size = 0;
bloc->data = bloc->new_data;
}
else
{
if (bloc->new_data != bloc->data)
memmove (bloc->new_data, bloc->data, old_size);
memset ((char *) bloc->new_data + old_size, 0, size - old_size);
*bloc->variable = bloc->data = bloc->new_data;
}
}
else
{
for (b = bloc; b != NIL_BLOC; b = b->next)
{
if (!b->variable)
{
b->size = 0;
b->data = b->new_data;
}
else
{
if (b->new_data != b->data)
memmove (b->new_data, b->data, b->size);
*b->variable = b->data = b->new_data;
}
}
}
update_heap_bloc_correspondence (bloc, heap);
break_value = (last_bloc ? (char *) last_bloc->data + last_bloc->size
: (char *) first_heap->bloc_start);
return 1;
}
/* Free BLOC from the chain of blocs, relocating any blocs above it.
This may return space to the system. */
static void
free_bloc (bloc_ptr bloc)
{
heap_ptr heap = bloc->heap;
heap_ptr h;
if (r_alloc_freeze_level)
{
bloc->variable = NULL;
return;
}
resize_bloc (bloc, 0);
if (bloc == first_bloc && bloc == last_bloc)
{
first_bloc = last_bloc = NIL_BLOC;
}
else if (bloc == last_bloc)
{
last_bloc = bloc->prev;
last_bloc->next = NIL_BLOC;
}
else if (bloc == first_bloc)
{
first_bloc = bloc->next;
first_bloc->prev = NIL_BLOC;
}
else
{
bloc->next->prev = bloc->prev;
bloc->prev->next = bloc->next;
}
/* Sometimes, 'heap' obtained from bloc->heap above is not really a
'heap' structure. It can even be beyond the current break point,
which will cause crashes when we dereference it below (see
bug#12242). Evidently, the reason is bloc allocations done while
use_relocatable_buffers was non-positive, because additional
memory we get then is not recorded in the heaps we manage. If
bloc->heap records such a "heap", we cannot (and don't need to)
update its records. So we validate the 'heap' value by making
sure it is one of the heaps we manage via the heaps linked list,
and don't touch a 'heap' that isn't found there. This avoids
accessing memory we know nothing about. */
for (h = first_heap; h != NIL_HEAP; h = h->next)
if (heap == h)
break;
if (h)
{
/* Update the records of which blocs are in HEAP. */
if (heap->first_bloc == bloc)
{
if (bloc->next != 0 && bloc->next->heap == heap)
heap->first_bloc = bloc->next;
else
heap->first_bloc = heap->last_bloc = NIL_BLOC;
}
if (heap->last_bloc == bloc)
{
if (bloc->prev != 0 && bloc->prev->heap == heap)
heap->last_bloc = bloc->prev;
else
heap->first_bloc = heap->last_bloc = NIL_BLOC;
}
}
relinquish ();
free (bloc);
}
/* Interface routines. */
/* Obtain SIZE bytes of storage from the free pool, or the system, as
necessary. If relocatable blocs are in use, this means relocating
them. This function gets plugged into the GNU malloc's __morecore
hook.
We provide hysteresis, never relocating by less than extra_bytes.
If we're out of memory, we should return zero, to imitate the other
__morecore hook values - in particular, __default_morecore in the
GNU malloc package. */
static void *
r_alloc_sbrk (ptrdiff_t size)
{
bloc_ptr b;
void *address;
if (! r_alloc_initialized)
r_alloc_init ();
if (use_relocatable_buffers <= 0)
return real_morecore (size);
if (size == 0)
return virtual_break_value;
if (size > 0)
{
/* Allocate a page-aligned space. GNU malloc would reclaim an
extra space if we passed an unaligned one. But we could
not always find a space which is contiguous to the previous. */
void *new_bloc_start;
heap_ptr h = first_heap;
size_t get = PAGE_ROUNDUP (size);
address = (void *) PAGE_ROUNDUP (virtual_break_value);
/* Search the list upward for a heap which is large enough. */
while ((char *) h->end < (char *) MEM_ROUNDUP ((char *) address + get))
{
h = h->next;
if (h == NIL_HEAP)
break;
address = (void *) PAGE_ROUNDUP (h->start);
}
/* If not found, obtain more space. */
if (h == NIL_HEAP)
{
get += extra_bytes + page_size;
if (! obtain (address, get))
return 0;
if (first_heap == last_heap)
address = (void *) PAGE_ROUNDUP (virtual_break_value);
else
address = (void *) PAGE_ROUNDUP (last_heap->start);
h = last_heap;
}
new_bloc_start = (void *) MEM_ROUNDUP ((char *) address + get);
if (first_heap->bloc_start < new_bloc_start)
{
/* This is no clean solution - no idea how to do it better. */
if (r_alloc_freeze_level)
return NULL;
/* There is a bug here: if the above obtain call succeeded, but the
relocate_blocs call below does not succeed, we need to free
the memory that we got with obtain. */
/* Move all blocs upward. */
if (! relocate_blocs (first_bloc, h, new_bloc_start))
return 0;
/* Note that (char *) (h + 1) <= (char *) new_bloc_start since
get >= page_size, so the following does not destroy the heap
header. */
for (b = last_bloc; b != NIL_BLOC; b = b->prev)
{
if (b->new_data != b->data)
memmove (b->new_data, b->data, b->size);
*b->variable = b->data = b->new_data;
}
h->bloc_start = new_bloc_start;
update_heap_bloc_correspondence (first_bloc, h);
}
if (h != first_heap)
{
/* Give up managing heaps below the one the new
virtual_break_value points to. */
first_heap->prev = NIL_HEAP;
first_heap->next = h->next;
first_heap->start = h->start;
first_heap->end = h->end;
first_heap->free = h->free;
first_heap->first_bloc = h->first_bloc;
first_heap->last_bloc = h->last_bloc;
first_heap->bloc_start = h->bloc_start;
if (first_heap->next)
first_heap->next->prev = first_heap;
else
last_heap = first_heap;
}
memset (address, 0, size);
}
else /* size < 0 */
{
size_t excess = ((char *) first_heap->bloc_start
- ((char *) virtual_break_value + size));
address = virtual_break_value;
if (r_alloc_freeze_level == 0 && excess > 2 * extra_bytes)
{
excess -= extra_bytes;
first_heap->bloc_start
= (void *) MEM_ROUNDUP ((char *) first_heap->bloc_start - excess);
relocate_blocs (first_bloc, first_heap, first_heap->bloc_start);
for (b = first_bloc; b != NIL_BLOC; b = b->next)
{
if (b->new_data != b->data)
memmove (b->new_data, b->data, b->size);
*b->variable = b->data = b->new_data;
}
}
if ((char *) virtual_break_value + size < (char *) first_heap->start)
{
/* We found an additional space below the first heap */
first_heap->start = (void *) ((char *) virtual_break_value + size);
}
}
virtual_break_value = (void *) ((char *) address + size);
break_value = (last_bloc
? (char *) last_bloc->data + last_bloc->size
: (char *) first_heap->bloc_start);
if (size < 0)
relinquish ();
return address;
}
/* Allocate a relocatable bloc of storage of size SIZE. A pointer to
the data is returned in *PTR. PTR is thus the address of some variable
which will use the data area.
The allocation of 0 bytes is valid.
In case r_alloc_freeze_level is set, a best fit of unused blocs could be
done before allocating a new area. Not yet done.
If we can't allocate the necessary memory, set *PTR to zero, and
return zero. */
void *
r_alloc (void **ptr, size_t size)
{
bloc_ptr new_bloc;
if (! r_alloc_initialized)
r_alloc_init ();
new_bloc = get_bloc (MEM_ROUNDUP (size));
if (new_bloc)
{
new_bloc->variable = ptr;
*ptr = new_bloc->data;
}
else
*ptr = 0;
return *ptr;
}
/* Free a bloc of relocatable storage whose data is pointed to by PTR.
Store 0 in *PTR to show there's no block allocated. */
void
r_alloc_free (void **ptr)
{
bloc_ptr dead_bloc;
if (! r_alloc_initialized)
r_alloc_init ();
dead_bloc = find_bloc (ptr);
if (dead_bloc == NIL_BLOC)
emacs_abort (); /* Double free? PTR not originally used to allocate? */
free_bloc (dead_bloc);
*ptr = 0;
#ifdef emacs
refill_memory_reserve ();
#endif
}
/* Given a pointer at address PTR to relocatable data, resize it to SIZE.
Do this by shifting all blocks above this one up in memory, unless
SIZE is less than or equal to the current bloc size, in which case
do nothing.
In case r_alloc_freeze_level is set, a new bloc is allocated, and the
memory copied to it. Not very efficient. We could traverse the
bloc_list for a best fit of free blocs first.
Change *PTR to reflect the new bloc, and return this value.
If more memory cannot be allocated, then leave *PTR unchanged, and
return zero. */
void *
r_re_alloc (void **ptr, size_t size)
{
bloc_ptr bloc;
if (! r_alloc_initialized)
r_alloc_init ();
if (!*ptr)
return r_alloc (ptr, size);
if (!size)
{
r_alloc_free (ptr);
return r_alloc (ptr, 0);
}
bloc = find_bloc (ptr);
if (bloc == NIL_BLOC)
emacs_abort (); /* Already freed? PTR not originally used to allocate? */
if (size < bloc->size)
{
/* Wouldn't it be useful to actually resize the bloc here? */
/* I think so too, but not if it's too expensive... */
if ((bloc->size - MEM_ROUNDUP (size) >= page_size)
&& r_alloc_freeze_level == 0)
{
resize_bloc (bloc, MEM_ROUNDUP (size));
/* Never mind if this fails, just do nothing... */
/* It *should* be infallible! */
}
}
else if (size > bloc->size)
{
if (r_alloc_freeze_level)
{
bloc_ptr new_bloc;
new_bloc = get_bloc (MEM_ROUNDUP (size));
if (new_bloc)
{
new_bloc->variable = ptr;
*ptr = new_bloc->data;
bloc->variable = NULL;
}
else
return NULL;
}
else
{
if (! resize_bloc (bloc, MEM_ROUNDUP (size)))
return NULL;
}
}
return *ptr;
}
#if defined (emacs) && defined (DOUG_LEA_MALLOC)
/* Reinitialize the morecore hook variables after restarting a dumped
Emacs. This is needed when using Doug Lea's malloc from GNU libc. */
void
r_alloc_reinit (void)
{
/* Only do this if the hook has been reset, so that we don't get an
infinite loop, in case Emacs was linked statically. */
if (__morecore != r_alloc_sbrk)
{
real_morecore = __morecore;
__morecore = r_alloc_sbrk;
}
}
#endif /* emacs && DOUG_LEA_MALLOC */
#ifdef DEBUG
#include <assert.h>
void
r_alloc_check (void)
{
int found = 0;
heap_ptr h, ph = 0;
bloc_ptr b, pb = 0;
if (!r_alloc_initialized)
return;
assert (first_heap);
assert (last_heap->end <= (void *) sbrk (0));
assert ((void *) first_heap < first_heap->start);
assert (first_heap->start <= virtual_break_value);
assert (virtual_break_value <= first_heap->end);
for (h = first_heap; h; h = h->next)
{
assert (h->prev == ph);
assert ((void *) PAGE_ROUNDUP (h->end) == h->end);
#if 0 /* ??? The code in ralloc.c does not really try to ensure
the heap start has any sort of alignment.
Perhaps it should. */
assert ((void *) MEM_ROUNDUP (h->start) == h->start);
#endif
assert ((void *) MEM_ROUNDUP (h->bloc_start) == h->bloc_start);
assert (h->start <= h->bloc_start && h->bloc_start <= h->end);
if (ph)
{
assert (ph->end < h->start);
assert (h->start <= (void *) h && (void *) (h + 1) <= h->bloc_start);
}
if (h->bloc_start <= break_value && break_value <= h->end)
found = 1;
ph = h;
}
assert (found);
assert (last_heap == ph);
for (b = first_bloc; b; b = b->next)
{
assert (b->prev == pb);
assert ((void *) MEM_ROUNDUP (b->data) == b->data);
assert ((size_t) MEM_ROUNDUP (b->size) == b->size);
ph = 0;
for (h = first_heap; h; h = h->next)
{
if (h->bloc_start <= b->data && b->data + b->size <= h->end)
break;
ph = h;
}
assert (h);
if (pb && pb->data + pb->size != b->data)
{
assert (ph && b->data == h->bloc_start);
while (ph)
{
if (ph->bloc_start <= pb->data
&& pb->data + pb->size <= ph->end)
{
assert (pb->data + pb->size + b->size > ph->end);
break;
}
else
{
assert (ph->bloc_start + b->size > ph->end);
}
ph = ph->prev;
}
}
pb = b;
}
assert (last_bloc == pb);
if (last_bloc)
assert (last_bloc->data + last_bloc->size == break_value);
else
assert (first_heap->bloc_start == break_value);
}
#endif /* DEBUG */
/* Update the internal record of which variable points to some data to NEW.
Used by buffer-swap-text in Emacs to restore consistency after it
swaps the buffer text between two buffer objects. The OLD pointer
is checked to ensure that memory corruption does not occur due to
misuse. */
void
r_alloc_reset_variable (void **old, void **new)
{
bloc_ptr bloc = first_bloc;
/* Find the bloc that corresponds to the data pointed to by pointer.
find_bloc cannot be used, as it has internal consistency checks
which fail when the variable needs resetting. */
while (bloc != NIL_BLOC)
{
if (bloc->data == *new)
break;
bloc = bloc->next;
}
if (bloc == NIL_BLOC || bloc->variable != old)
emacs_abort (); /* Already freed? OLD not originally used to allocate? */
/* Update variable to point to the new location. */
bloc->variable = new;
}
void
r_alloc_inhibit_buffer_relocation (int inhibit)
{
if (use_relocatable_buffers > 1)
use_relocatable_buffers = 1;
if (inhibit)
use_relocatable_buffers--;
else if (use_relocatable_buffers < 1)
use_relocatable_buffers++;
}
/***********************************************************************
Initialization
***********************************************************************/
/* Initialize various things for memory allocation. */
static void
r_alloc_init (void)
{
if (r_alloc_initialized)
return;
r_alloc_initialized = 1;
page_size = PAGE;
#if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
real_morecore = __morecore;
__morecore = r_alloc_sbrk;
first_heap = last_heap = &heap_base;
first_heap->next = first_heap->prev = NIL_HEAP;
first_heap->start = first_heap->bloc_start
= virtual_break_value = break_value = real_morecore (0);
if (break_value == NULL)
emacs_abort ();
extra_bytes = PAGE_ROUNDUP (50000);
#endif
#ifdef DOUG_LEA_MALLOC
block_input ();
mallopt (M_TOP_PAD, 64 * 4096);
unblock_input ();
#else
#if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
/* Give GNU malloc's morecore some hysteresis so that we move all
the relocatable blocks much less often. The number used to be
64, but alloc.c would override that with 32 in code that was
removed when SYNC_INPUT became the only input handling mode.
That code was conditioned on !DOUG_LEA_MALLOC, so the call to
mallopt above is left unchanged. (Actually, I think there's no
system nowadays that uses DOUG_LEA_MALLOC and also uses
REL_ALLOC.) */
__malloc_extra_blocks = 32;
#endif
#endif
#if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
first_heap->end = (void *) PAGE_ROUNDUP (first_heap->start);
/* The extra call to real_morecore guarantees that the end of the
address space is a multiple of page_size, even if page_size is
not really the page size of the system running the binary in
which page_size is stored. This allows a binary to be built on a
system with one page size and run on a system with a smaller page
size. */
real_morecore ((char *) first_heap->end - (char *) first_heap->start);
/* Clear the rest of the last page; this memory is in our address space
even though it is after the sbrk value. */
/* Doubly true, with the additional call that explicitly adds the
rest of that page to the address space. */
memset (first_heap->start, 0,
(char *) first_heap->end - (char *) first_heap->start);
virtual_break_value = break_value = first_heap->bloc_start = first_heap->end;
#endif
use_relocatable_buffers = 1;
}
| 27.050695 | 79 | 0.635825 | [
"object"
] |
c8e57cd866db97bb472361021408219da42df8e0 | 2,537 | h | C | fuchsia/engine/test/web_engine_browser_test.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | fuchsia/engine/test/web_engine_browser_test.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | fuchsia/engine/test/web_engine_browser_test.h | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FUCHSIA_ENGINE_TEST_WEB_ENGINE_BROWSER_TEST_H_
#define FUCHSIA_ENGINE_TEST_WEB_ENGINE_BROWSER_TEST_H_
#include <lib/fidl/cpp/binding_set.h>
#include <memory>
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/optional.h"
#include "content/public/test/browser_test_base.h"
#include "fuchsia/engine/browser/context_impl.h"
namespace cr_fuchsia {
// Base test class used for testing the WebEngine Context FIDL service in
// integration.
class WebEngineBrowserTest : public content::BrowserTestBase {
public:
WebEngineBrowserTest();
~WebEngineBrowserTest() override;
// Sets the Context client channel which will be bound to a Context FIDL
// object by WebEngineBrowserTest.
static void SetContextClientChannel(zx::channel channel);
// Creates a Frame for this Context using default parameters.
// |listener|: If set, specifies the navigation listener for the Frame.
fuchsia::web::FramePtr CreateFrame(
fuchsia::web::NavigationEventListener* listener);
// Creates a Frame for this Context using non-default parameters.
// |listener|: If set, specifies the navigation listener for the Frame.
// |params|: The CreateFrameParams to use.
fuchsia::web::FramePtr CreateFrameWithParams(
fuchsia::web::NavigationEventListener* listener,
fuchsia::web::CreateFrameParams params);
// Gets the client object for the Context service.
fuchsia::web::ContextPtr& context() { return context_; }
// Gets the underlying ContextImpl service instance.
ContextImpl* context_impl() const;
fidl::BindingSet<fuchsia::web::NavigationEventListener>&
navigation_listener_bindings() {
return navigation_listener_bindings_;
}
void SetHeadlessInCommandLine(base::CommandLine* command_line);
void set_test_server_root(const base::FilePath& path) {
test_server_root_ = path;
}
// content::BrowserTestBase implementation.
void SetUp() override;
void PreRunTestOnMainThread() override;
void PostRunTestOnMainThread() override;
void TearDownOnMainThread() override;
private:
base::FilePath test_server_root_;
fuchsia::web::ContextPtr context_;
fidl::BindingSet<fuchsia::web::NavigationEventListener>
navigation_listener_bindings_;
DISALLOW_COPY_AND_ASSIGN(WebEngineBrowserTest);
};
} // namespace cr_fuchsia
#endif // FUCHSIA_ENGINE_TEST_WEB_ENGINE_BROWSER_TEST_H_
| 32.948052 | 74 | 0.772566 | [
"object"
] |
c8ee17654a71e13a9bc1ba7e287a8defa3913e5e | 19,855 | h | C | pwiz_tools/Bumbershoot/freicore/ResidueMap.h | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 2 | 2019-12-28T21:24:36.000Z | 2020-04-18T03:52:05.000Z | pwiz_tools/Bumbershoot/freicore/ResidueMap.h | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | null | null | null | pwiz_tools/Bumbershoot/freicore/ResidueMap.h | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | null | null | null | //
// $Id: ResidueMap.h 8634 2015-06-30 16:34:24Z chambm $
//
// 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.
//
// The Original Code is the Bumbershoot core library.
//
// The Initial Developer of the Original Code is Matt Chambers.
//
// Copyright 2009 Vanderbilt University
//
// Contributor(s): Surendra Dasari
//
#ifndef _RESIDUEMAP_H
#define _RESIDUEMAP_H
#include "stdafx.h"
#include "shared_types.h"
namespace freicore
{
//typedef map< char, float > n2m_t;
typedef map< double, AminoAcidResidue > m2n_t;
//typedef vector< float > n2m_t;
typedef CharIndexedVector<double> n2m_t;
class ResidueMap
{
public:
ResidueMap()
{
isValid = false;
// Alanine
m_monoMassesToNamesMap[ AminoAcid::Info::record('A').residueFormula.monoisotopicMass() ] = 'A';
m_avgMassesToNamesMap[ AminoAcid::Info::record('A').residueFormula.molecularWeight() ] = 'A';
// Arginine
m_monoMassesToNamesMap[ AminoAcid::Info::record('R').residueFormula.monoisotopicMass() ] = 'R';
m_avgMassesToNamesMap[ AminoAcid::Info::record('R').residueFormula.molecularWeight() ] = 'R';
// Asparagine
m_monoMassesToNamesMap[ AminoAcid::Info::record('N').residueFormula.monoisotopicMass() ] = 'N';
m_avgMassesToNamesMap[ AminoAcid::Info::record('N').residueFormula.molecularWeight() ] = 'N';
// Aspartic acid
m_monoMassesToNamesMap[ AminoAcid::Info::record('D').residueFormula.monoisotopicMass() ] = 'D';
m_avgMassesToNamesMap[ AminoAcid::Info::record('D').residueFormula.molecularWeight() ] = 'D';
// Cysteine
m_monoMassesToNamesMap[ AminoAcid::Info::record('C').residueFormula.monoisotopicMass() ] = 'C';
m_avgMassesToNamesMap[ AminoAcid::Info::record('C').residueFormula.molecularWeight() ] = 'C';
// Glutamic acid
m_monoMassesToNamesMap[ AminoAcid::Info::record('E').residueFormula.monoisotopicMass() ] = 'E';
m_avgMassesToNamesMap[ AminoAcid::Info::record('E').residueFormula.molecularWeight() ] = 'E';
// Glutamine
m_monoMassesToNamesMap[ AminoAcid::Info::record('Q').residueFormula.monoisotopicMass() ] = 'Q';
m_avgMassesToNamesMap[ AminoAcid::Info::record('Q').residueFormula.molecularWeight() ] = 'Q';
// Glycine
m_monoMassesToNamesMap[ AminoAcid::Info::record('G').residueFormula.monoisotopicMass() ] = 'G';
m_avgMassesToNamesMap[ AminoAcid::Info::record('G').residueFormula.molecularWeight() ] = 'G';
// Histidine
m_monoMassesToNamesMap[ AminoAcid::Info::record('H').residueFormula.monoisotopicMass() ] = 'H';
m_avgMassesToNamesMap[ AminoAcid::Info::record('H').residueFormula.molecularWeight() ] = 'H';
// Isoleucine
m_monoMassesToNamesMap[ AminoAcid::Info::record('I').residueFormula.monoisotopicMass() ] = 'I';
m_avgMassesToNamesMap[ AminoAcid::Info::record('I').residueFormula.molecularWeight() ] = 'I';
// Lysine
m_monoMassesToNamesMap[ AminoAcid::Info::record('K').residueFormula.monoisotopicMass() ] = 'K';
m_avgMassesToNamesMap[ AminoAcid::Info::record('K').residueFormula.molecularWeight() ] = 'K';
// Methionine
m_monoMassesToNamesMap[ AminoAcid::Info::record('M').residueFormula.monoisotopicMass() ] = 'M';
m_avgMassesToNamesMap[ AminoAcid::Info::record('M').residueFormula.molecularWeight() ] = 'M';
// Phenylalanine
m_monoMassesToNamesMap[ AminoAcid::Info::record('F').residueFormula.monoisotopicMass() ] = 'F';
m_avgMassesToNamesMap[ AminoAcid::Info::record('F').residueFormula.molecularWeight() ] = 'F';
// Proline
m_monoMassesToNamesMap[ AminoAcid::Info::record('P').residueFormula.monoisotopicMass() ] = 'P';
m_avgMassesToNamesMap[ AminoAcid::Info::record('P').residueFormula.molecularWeight() ] = 'P';
// Serine
m_monoMassesToNamesMap[ AminoAcid::Info::record('S').residueFormula.monoisotopicMass() ] = 'S';
m_avgMassesToNamesMap[ AminoAcid::Info::record('S').residueFormula.molecularWeight() ] = 'S';
// Threonine
m_monoMassesToNamesMap[ AminoAcid::Info::record('T').residueFormula.monoisotopicMass() ] = 'T';
m_avgMassesToNamesMap[ AminoAcid::Info::record('T').residueFormula.molecularWeight() ] = 'T';
// Tryptophan
m_monoMassesToNamesMap[ AminoAcid::Info::record('W').residueFormula.monoisotopicMass() ] = 'W';
m_avgMassesToNamesMap[ AminoAcid::Info::record('W').residueFormula.molecularWeight() ] = 'W';
// Tyrosine
m_monoMassesToNamesMap[ AminoAcid::Info::record('Y').residueFormula.monoisotopicMass() ] = 'Y';
m_avgMassesToNamesMap[ AminoAcid::Info::record('Y').residueFormula.molecularWeight() ] = 'Y';
// Valine
m_monoMassesToNamesMap[ AminoAcid::Info::record('V').residueFormula.monoisotopicMass() ] = 'V';
m_avgMassesToNamesMap[ AminoAcid::Info::record('V').residueFormula.molecularWeight() ] = 'V';
for( m2n_t::iterator itr = m_monoMassesToNamesMap.begin(); itr != m_monoMassesToNamesMap.end(); ++itr )
{
m_defaultNamesToMonoMassesMap[ itr->second ] = itr->first;
m_defaultResidues.insert( itr->second );
}
for( m2n_t::iterator itr = m_avgMassesToNamesMap.begin(); itr != m_avgMassesToNamesMap.end(); ++itr )
m_defaultNamesToAvgMassesMap[ itr->second ] = itr->first;
Formula hydroxyl("O1H1");
Formula hydrogen("H1");
m_monoMassesToNamesMap[ hydroxyl.monoisotopicMass() ] = PEPTIDE_C_TERMINUS_SYMBOL;
m_avgMassesToNamesMap[ hydroxyl.molecularWeight() ] = PEPTIDE_C_TERMINUS_SYMBOL;
m_monoMassesToNamesMap[ hydrogen.monoisotopicMass() ] = PEPTIDE_N_TERMINUS_SYMBOL;
m_avgMassesToNamesMap[ hydrogen.molecularWeight() ] = PEPTIDE_N_TERMINUS_SYMBOL;
finalize();
}
bool initialized() { return isValid; }
int initializeFromFile( const string& residuesCfgFilename = "residue_masses.cfg" )
{
ifstream residuesCfgFile( residuesCfgFilename.c_str() );
if( residuesCfgFile.is_open() )
{
// clear old residues
m_residues.clear();
m_monoMassesToNamesMap.clear();
m_avgMassesToNamesMap.clear();
m_namesToMonoMassesMap.clear();
m_namesToAvgMassesMap.clear();
int cfgSize = (int) GetFileSize( residuesCfgFilename );
cfgStr.resize( cfgSize );
residuesCfgFile.read( &cfgStr[0], cfgSize );
int rv = initializeFromBuffer( cfgStr );
residuesCfgFile.close();
return rv;
} else
return 1;
}
int initializeFromBuffer( const string& cfgStr )
{
isValid = false;
stringstream cfgStream( cfgStr );
char r;
double mono, avg;
while( cfgStream >> r >> mono >> avg )
{
if( !m_defaultResidues.count(r) )
cerr << "Warning: residue map has been initialized with non-standard residue '" << r << "'!" << endl;
else
{
if( m_defaultNamesToMonoMassesMap[r] != mono )
cerr << "Warning: residue map has initialized standard residue '" << r << "' with non-standard monoisotopic mass!" << endl;
if( m_defaultNamesToAvgMassesMap[r] != avg )
cerr << "Warning: residue map has initialized standard residue '" << r << "' with non-standard average mass!" << endl;
}
m_monoMassesToNamesMap[ mono ] = r;
m_avgMassesToNamesMap[ avg ] = r;
}
if( m_monoMassesToNamesMap.empty() || m_avgMassesToNamesMap.empty() )
return 1;
finalize();
return 0;
}
void finalize()
{
for( m2n_t::iterator itr = m_monoMassesToNamesMap.begin(); itr != m_monoMassesToNamesMap.end(); ++itr )
{
m_namesToMonoMassesMap[ itr->second ] = itr->first;
m_residues.insert( itr->second );
}
for( m2n_t::iterator itr = m_avgMassesToNamesMap.begin(); itr != m_avgMassesToNamesMap.end(); ++itr )
m_namesToAvgMassesMap[ itr->second ] = itr->first;
if( m_namesToMonoMassesMap['I'] > 0 )
{
m_namesToMonoMassesMap['L'] = m_namesToMonoMassesMap['I'];
m_namesToAvgMassesMap['L'] = m_namesToAvgMassesMap['I'];
m_residues.insert('L');
} else if( m_namesToMonoMassesMap['L'] > 0 )
{
m_namesToMonoMassesMap['I'] = m_namesToMonoMassesMap['L'];
m_namesToAvgMassesMap['I'] = m_namesToAvgMassesMap['L'];
m_residues.insert('L');
}
m_residues.erase(PEPTIDE_N_TERMINUS_SYMBOL);
m_residues.erase(PEPTIDE_C_TERMINUS_SYMBOL);
isValid = true;
}
void addDynamicMod( const DynamicMod& mod )
{
if( !dynamicMods.count( mod ) )
{
dynamicMods.insert( mod );
m_monoMassesToNamesMap[ m_namesToMonoMassesMap[ mod.unmodChar ] + mod.modMass ] = mod.uniqueModChar;
m_avgMassesToNamesMap[ m_namesToAvgMassesMap[ mod.unmodChar ] + mod.modMass ] = mod.uniqueModChar;
m_namesToMonoMassesMap[ mod.uniqueModChar ] = m_namesToMonoMassesMap[ mod.unmodChar ] + mod.modMass;
m_namesToAvgMassesMap[ mod.uniqueModChar ] = m_namesToAvgMassesMap[ mod.unmodChar ] + mod.modMass;
}
}
void removeDynamicMod( const DynamicMod& mod )
{
if( dynamicMods.count( mod ) )
{
dynamicMods.erase( mod );
forceAddDynamicMod( mod );
}
}
void addStaticMod( const StaticMod& mod )
{
if( !staticMods.count( mod ) )
{
staticMods.insert( mod );
forceAddStaticMod( mod );
}
}
void clearDynamicMods()
{
for( DynamicModSet::iterator itr = dynamicMods.begin(); itr != dynamicMods.end(); ++itr )
{
m_monoMassesToNamesMap.erase( m_namesToMonoMassesMap[ itr->unmodChar ] + itr->modMass );
m_avgMassesToNamesMap.erase( m_namesToAvgMassesMap[ itr->unmodChar ] + itr->modMass );
m_namesToMonoMassesMap.erase( itr->uniqueModChar );
m_namesToAvgMassesMap.erase( itr->uniqueModChar );
}
dynamicMods.clear();
}
void clearStaticMods()
{
for( StaticModSet::iterator itr = staticMods.begin(); itr != staticMods.end(); ++itr )
{
double monoMass = m_namesToMonoMassesMap[ itr->name ];
double avgMass = m_namesToAvgMassesMap[ itr->name ];
m_monoMassesToNamesMap[ monoMass - itr->mass ] = itr->name;
m_avgMassesToNamesMap[ avgMass - itr->mass ] = itr->name;
m_monoMassesToNamesMap.erase( monoMass );
m_avgMassesToNamesMap.erase( avgMass );
m_namesToMonoMassesMap[ itr->name ] = monoMass - itr->mass;
m_namesToAvgMassesMap[ itr->name ] = avgMass - itr->mass;
}
staticMods.clear();
}
void setDynamicMods( const string& cfgStr )
{
clearDynamicMods();
if( cfgStr.empty() ) return;
DynamicModSet tmp( cfgStr );
for( DynamicModSet::iterator itr = tmp.begin(); itr != tmp.end(); ++itr )
addDynamicMod( *itr );
}
void setStaticMods( const string& cfgStr )
{
clearStaticMods();
if( cfgStr.empty() ) return;
StaticModSet tmp( cfgStr );
for( StaticModSet::iterator itr = tmp.begin(); itr != tmp.end(); ++itr )
addStaticMod( *itr );
}
const set<char>& getResidues() const { return m_residues; }
bool hasResidue( char r ) const { return m_namesToMonoMassesMap[r] > 0; }
double largestDynamicModMass() const { return ( dynamicMods.empty() ? 0 : dynamicMods.rbegin()->modMass ); }
double smallestDynamicModMass() const { return ( dynamicMods.empty() ? 0 : dynamicMods.begin()->modMass ); }
inline double GetMassOfResidues( const string::const_iterator& seqBegin, const string::const_iterator& seqEnd, bool useAvgMass = false ) const
{
double mass = 0.0;
if( useAvgMass )
{
for( string::const_iterator itr = seqBegin; itr != seqEnd; ++itr )
mass += getAvgMassByName( *itr );
} else
{
for( string::const_iterator itr = seqBegin; itr != seqEnd; ++itr )
mass += getMonoMassByName( *itr );
}
return mass;
}
inline double GetMassOfResidues( const string& residues, bool useAvgMass = false ) const
{
return GetMassOfResidues( residues.begin(), residues.end(), useAvgMass );
}
void dump() const
{
//cout << "Residue map size: " << m_namesToMonoMassesMap.size() << endl;
//for( n2m_t::iterator itr = m_namesToMonoMassesMap.begin(); itr != m_namesToMonoMassesMap.end(); ++itr )
// cout << itr->first << ": " << itr->second << " " << m_namesToAvgMassesMap[ itr->first ] << endl;
for( size_t i=0; i < 128; ++i )
if( m_namesToMonoMassesMap[i] > 0 )
cout << (char) i << ": " << m_namesToMonoMassesMap[i] << " " << m_namesToAvgMassesMap[i] << endl;
cout << dynamicMods.userToUniqueMap << endl << dynamicMods.uniqueToUserMap << endl;
}
size_t size() const { return m_namesToMonoMassesMap.size(); }
n2m_t::const_iterator beginMonoNames() const { return m_namesToMonoMassesMap.begin(); }
n2m_t::const_iterator endMonoNames() const { return m_namesToMonoMassesMap.end(); }
n2m_t::const_iterator beginAvgNames() const { return m_namesToAvgMassesMap.begin(); }
n2m_t::const_iterator endAvgNames() const { return m_namesToAvgMassesMap.end(); }
m2n_t::const_iterator beginMonoMasses() const { return m_monoMassesToNamesMap.begin(); }
m2n_t::const_iterator endMonoMasses() const { return m_monoMassesToNamesMap.end(); }
m2n_t::const_iterator beginAvgMasses() const { return m_avgMassesToNamesMap.begin(); }
m2n_t::const_iterator endAvgMasses() const { return m_avgMassesToNamesMap.end(); }
char getNameByMonoMass( double key ) const { return m_monoMassesToNamesMap.find( key )->second; }
char getNameByAvgMass( double key ) const { return m_avgMassesToNamesMap.find( key )->second; }
char getNameByMonoMass( double key, double epsilon ) const
{
if( epsilon > 0.0f )
{
m2n_t::const_iterator min, max, cur, best;
min = m_monoMassesToNamesMap.lower_bound( key - epsilon );
max = m_monoMassesToNamesMap.lower_bound( key + epsilon );
if( min == max )
throw runtime_error( string( "No residue matching mass " ) + lexical_cast<string>( key ) );
double minDelta = fabs( min->first - key );
for( best = cur = min; cur != max; ++cur )
{
double curDelta = fabs( cur->first - key );
if( curDelta < minDelta )
{
minDelta = curDelta;
best = cur;
}
}
return best->second;
} else
return getNameByMonoMass(key);
}
char getNameByAvgMass( double key, double epsilon ) const
{
if( epsilon > 0.0f )
{
m2n_t::const_iterator min, max, cur, best;
min = m_avgMassesToNamesMap.lower_bound( key - epsilon );
max = m_avgMassesToNamesMap.lower_bound( key + epsilon );
if( min == max )
throw runtime_error( string( "No residue matching mass " ) + lexical_cast<string>( key ) );
double minDelta = fabs( min->first - key );
for( best = cur = min; cur != max; ++cur )
{
double curDelta = fabs( cur->first - key );
if( curDelta < minDelta )
{
minDelta = curDelta;
best = cur;
}
}
return best->second;
} else
return getNameByAvgMass(key);
}
double getMonoMassByName( char key ) const { return m_namesToMonoMassesMap[ key ]; }
double getAvgMassByName( char key ) const { return m_namesToAvgMassesMap[ key ]; }
string cfgStr;
DynamicModSet dynamicMods;
StaticModSet staticMods;
bool isValid;
private:
void forceAddDynamicMod( const DynamicMod& mod )
{
m_monoMassesToNamesMap[ m_namesToMonoMassesMap[ mod.unmodChar ] + mod.modMass ] = mod.uniqueModChar;
m_avgMassesToNamesMap[ m_namesToAvgMassesMap[ mod.unmodChar ] + mod.modMass ] = mod.uniqueModChar;
m_namesToMonoMassesMap[ mod.uniqueModChar ] = m_namesToMonoMassesMap[ mod.unmodChar ] + mod.modMass;
m_namesToAvgMassesMap[ mod.uniqueModChar ] = m_namesToAvgMassesMap[ mod.unmodChar ] + mod.modMass;
}
void forceAddStaticMod( const StaticMod& mod )
{
double monoMass = m_namesToMonoMassesMap[ mod.name ];
double avgMass = m_namesToAvgMassesMap[ mod.name ];
m_monoMassesToNamesMap[ monoMass + mod.mass ] = mod.name;
m_avgMassesToNamesMap[ avgMass + mod.mass ] = mod.name;
m_monoMassesToNamesMap.erase( monoMass );
m_avgMassesToNamesMap.erase( avgMass );
m_namesToMonoMassesMap[ mod.name ] = monoMass + mod.mass;
m_namesToAvgMassesMap[ mod.name ] = avgMass + mod.mass;
}
n2m_t m_defaultNamesToMonoMassesMap;
n2m_t m_defaultNamesToAvgMassesMap;
set<char> m_defaultResidues;
n2m_t m_namesToMonoMassesMap;
n2m_t m_namesToAvgMassesMap;
m2n_t m_monoMassesToNamesMap;
m2n_t m_avgMassesToNamesMap;
set<char> m_residues;
};
}
#endif
| 46.607981 | 150 | 0.576631 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.