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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
320bf229c5064c7c04d4c8eeb65f9353a6392fe9 | 5,248 | h | C | applications/structural_application/custom_elements/beam_element.h | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 2 | 2020-04-30T19:13:08.000Z | 2021-04-14T19:40:47.000Z | applications/structural_application/custom_elements/beam_element.h | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 1 | 2020-04-30T19:19:09.000Z | 2020-05-02T14:22:36.000Z | applications/structural_application/custom_elements/beam_element.h | AndreaVoltan/MyKratos7.0 | e977752722e8ef1b606f25618c4bf8fd04c434cc | [
"BSD-4-Clause"
] | 1 | 2020-06-12T08:51:24.000Z | 2020-06-12T08:51:24.000Z |
// Project Name: Kratos
// Last Modified by: $Author: nelson $
// Date: $Date: 2008-12-10 11:10:16 $
// Revision: $Revision: 1.1 $
//
//
#if !defined(KRATOS_BEAM_ELEMENT_INCLUDED )
#define KRATOS_BEAM_ELEMENT_INCLUDED
// System includes
// External includes
#include "boost/smart_ptr.hpp"
// Project includes
#include "structural_application.h"
#include "includes/define.h"
#include "includes/serializer.h"
#include "includes/element.h"
#include "includes/ublas_interface.h"
#include "includes/variables.h"
#include "includes/constitutive_law.h"
namespace Kratos
{
class BeamElement
:public Element
{
typedef GeometryData::IntegrationMethod IntegrationMethod;
private:
///@name Static Member Variables
double mArea; // Area de la seccion tranversal de la viga.
double mInertia_x; // Momento de Inercia alredor del eje Ix local.
double mInertia_y; // Momento de Inercia alrededor del eje Iy local.
double mInertia_Polar; // Momento Polar de Inercia
double mlength; // Longitud del Elemento.
void CalculateSectionProperties();
void CalculateLocalMatrix(Matrix& LocalMatrix);
void CalculateTransformationMatrix(Matrix& Rotation);
void CalculateBodyForce(Matrix& Rotation, Vector& LocalBody, Vector& GlobalBody);
void CalculateLocalNodalStress(Vector& Stress);
double CalculateInternalAxil( const double& Ao, const double& Load, const double& X);
double CalculateInternalShear( const double& Vo, const double& Load, const double& X);
double CalculateInternalMoment( const double& Mo, const double& Vo, const double& Load, const double& X);
void CalculateDistrubuitedBodyForce(const int Direction, Vector& Load);
public:
KRATOS_CLASS_POINTER_DEFINITION(BeamElement);
/// Default constructor.
BeamElement(IndexType NewId, GeometryType::Pointer pGeometry);
BeamElement(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties);
/// Destructor.
virtual ~BeamElement();
Element::Pointer Create(IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties) const;
void Initialize();
void CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo);
void CalculateLeftHandSide(MatrixType& rLeftHandSideMatrix, ProcessInfo& rCurrentProcessInfo);
void CalculateRightHandSide(VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo);
void EquationIdVector(EquationIdVectorType& rResult, ProcessInfo& rCurrentProcessInfo);
void GetDofList(DofsVectorType& ElementalDofList,ProcessInfo& CurrentProcessInfo);
void InitializeSolutionStep(ProcessInfo& CurrentProcessInfo);
void FinalizeSolutionStep(ProcessInfo& CurrentProcessInfo);
void GetValuesVector(Vector& values, int Step);
void CalculateMassMatrix(MatrixType& rMassMatrix, ProcessInfo& rCurrentProcessInfo);
void CalculateRHS(Vector& rRightHandSideVector);
void CalculateLHS(Matrix& rLeftHandSideMatrix);
void CalculateAll(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector,
ProcessInfo& rCurrentProcessInfo,
bool CalculateStiffnessMatrixFlag,
bool CalculateResidualVectorFlag);
void GetFirstDerivativesVector(Vector& values, int Step);
void GetSecondDerivativesVector(Vector& values, int Step);
void CalculateOnIntegrationPoints( const Variable<array_1d<double,3> >& rVariable,
std::vector< array_1d<double,3> >& Output,
const ProcessInfo& rCurrentProcessInfo);
void GetValueOnIntegrationPoints( const Variable<array_1d<double,3> >& rVariable,
std::vector<array_1d<double,3> >& rValues,
const ProcessInfo& rCurrentProcessInfo);
IntegrationMethod GetIntegrationMethod() const;
//************************************************************************************
//************************************************************************************
/**
* This function provides the place to perform checks on the completeness of the input.
* 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 rCurrentProcessInfo
*/
int Check(const ProcessInfo& rCurrentProcessInfo);
///@}
///@name Serialization
///@{
friend class Serializer;
// A private default constructor necessary for serialization
BeamElement() {};
virtual void save(Serializer& rSerializer) const
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, Element );
}
virtual void load(Serializer& rSerializer)
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, Element );
}
}; // Class BeamElement
} // Namespace Kratos.
#endif
| 30.870588 | 131 | 0.672256 | [
"vector"
] |
321277fc9c52456032d868aa59ece7b76c53b4c2 | 11,169 | h | C | kernel/include/arch/arm/arch/object/structures.h | winksaville/sel4-min-sel4 | 2f2d88aa0f06b35f80c12bc06556100d44298c10 | [
"BSD-2-Clause"
] | 1 | 2016-09-09T13:53:10.000Z | 2016-09-09T13:53:10.000Z | kernel/include/arch/arm/arch/object/structures.h | winksaville/sel4-minimal-helloworld | 52900e395383af11f03dd3fe695fa677fc525f19 | [
"BSD-2-Clause"
] | null | null | null | kernel/include/arch/arm/arch/object/structures.h | winksaville/sel4-minimal-helloworld | 52900e395383af11f03dd3fe695fa677fc525f19 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2014, General Dynamics C4 Systems
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(GD_GPL)
*/
#ifndef __ARCH_OBJECT_STRUCTURES_H
#define __ARCH_OBJECT_STRUCTURES_H
#include <assert.h>
#include <util.h>
#include <api/types.h>
#include <arch/types.h>
#include <arch/object/structures_gen.h>
#include <arch/machine/hardware.h>
#include <arch/machine/registerset.h>
/* Object sizes */
#define EP_SIZE_BITS 4
#define AEP_SIZE_BITS 4
#define CTE_SIZE_BITS 4
#define TCB_BLOCK_SIZE_BITS (TCB_SIZE_BITS+1)
/* TCB CNode: size = 256 bytes */
/* typedef cte_t[16] tcb_cnode; */
/* TCB: size = 136 bytes, alignment = 256 bytes */
struct tcb {
/* Saved user-level context of thread, 72 bytes */
user_context_t tcbContext;
/* Thread state, 12 bytes */
thread_state_t tcbState;
/* Current fault, 8 bytes */
fault_t tcbFault;
/* Current lookup failure, 8 bytes */
lookup_fault_t tcbLookupFailure;
/* Domain, 1 byte, padded to 4 bytes */
dom_t tcbDomain;
/* Priority, 1 byte, padded to 4 bytes */
prio_t tcbPriority;
/* Timeslice remaining, 4 bytes */
uint32_t tcbTimeSlice;
/* Capability pointer to thread fault handler, 4 bytes */
cptr_t tcbFaultHandler;
/* Physical address of thread IPC buffer, 4 bytes */
word_t tcbIPCBuffer;
/* Previous and next pointers for endpoint & scheduler queues, 16 bytes */
struct tcb *tcbSchedNext, *tcbSchedPrev, *tcbEPNext, *tcbEPPrev;
#ifdef DEBUG
/* Use any remaining space for a thread name */
char tcbName[];
#endif
};
typedef struct tcb tcb_t;
/* ARM-specific object types */
enum vm_rights {
VMNoAccess = 0,
VMKernelOnly = 1,
VMReadOnly = 2,
VMReadWrite = 3
};
typedef uint32_t vm_rights_t;
#define PDE_SIZE_BITS 2
#define PDE_PTR(r) ((pde_t *)(r))
#define PDE_REF(p) ((unsigned int)p)
#define PDE_PTR_PTR(r) ((pde_t **)r)
#define PD_BITS 12
#define PD_SIZE_BITS (PD_BITS+PDE_SIZE_BITS)
#define PD_PTR(r) ((pde_t *)(r))
#define PD_REF(p) ((unsigned int)p)
/* Page directory entries (PDEs) */
enum pde_type {
PDEInvalid = 0,
PDECoarse = 1,
PDEMapping = 2
};
typedef uint32_t pde_type_t;
#define PTE_SIZE_BITS 2
#define PTE_PTR(r) ((pte_t *)r)
#define PTE_REF(p) ((unsigned int)p)
#define PT_BITS 8
#define PT_SIZE_BITS (PT_BITS+PTE_SIZE_BITS)
#define PT_PTR(r) ((pte_t *)r)
#define PT_REF(p) ((unsigned int)p)
#define WORD_SIZE_BITS 2
struct user_data {
word_t words[BIT(ARMSmallPageBits) / sizeof(word_t)];
};
typedef struct user_data user_data_t;
enum asidSizeConstants {
asidHighBits = 8,
asidLowBits = 10
};
struct asid_pool {
pde_t* array[BIT(asidLowBits)];
};
typedef struct asid_pool asid_pool_t;
#define ASID_POOL_PTR(r) ((asid_pool_t *)r)
#define ASID_POOL_REF(p) ((unsigned int)p)
#define HW_ASID_SIZE_BITS 1
#define ASID_POOL_BITS asidLowBits
#define ASID_POOL_SIZE_BITS (ASID_POOL_BITS+WORD_SIZE_BITS)
#define ASID_BITS (asidHighBits+asidLowBits)
#define nASIDPools BIT(asidHighBits)
#define ASID_LOW(a) (a & MASK(asidLowBits))
#define ASID_HIGH(a) ((a >> asidLowBits) & MASK(asidHighBits))
static inline cap_t CONST
cap_small_frame_cap_set_capFMappedASID(cap_t cap, word_t asid)
{
cap = cap_small_frame_cap_set_capFMappedASIDLow(cap,
asid & MASK(asidLowBits));
return cap_small_frame_cap_set_capFMappedASIDHigh(cap,
(asid >> asidLowBits) & MASK(asidHighBits));
}
static inline word_t CONST
cap_small_frame_cap_get_capFMappedASID(cap_t cap)
{
return (cap_small_frame_cap_get_capFMappedASIDHigh(cap) << asidLowBits) +
cap_small_frame_cap_get_capFMappedASIDLow(cap);
}
static inline cap_t CONST
cap_frame_cap_set_capFMappedASID(cap_t cap, word_t asid)
{
cap = cap_frame_cap_set_capFMappedASIDLow(cap,
asid & MASK(asidLowBits));
return cap_frame_cap_set_capFMappedASIDHigh(cap,
(asid >> asidLowBits) & MASK(asidHighBits));
}
static inline word_t CONST
cap_frame_cap_get_capFMappedASID(cap_t cap)
{
return (cap_frame_cap_get_capFMappedASIDHigh(cap) << asidLowBits) +
cap_frame_cap_get_capFMappedASIDLow(cap);
}
static inline word_t CONST
generic_frame_cap_get_capFMappedASID(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
assert(ctag == cap_small_frame_cap ||
ctag == cap_frame_cap);
if (ctag == cap_small_frame_cap) {
return cap_small_frame_cap_get_capFMappedASID(cap);
} else {
return cap_frame_cap_get_capFMappedASID(cap);
}
}
static inline cap_t CONST
generic_frame_cap_set_capFMappedAddress(cap_t cap, word_t asid, word_t addr)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
assert(ctag == cap_small_frame_cap ||
ctag == cap_frame_cap);
if (ctag == cap_small_frame_cap) {
cap = cap_small_frame_cap_set_capFMappedASID(cap, asid);
cap = cap_small_frame_cap_set_capFMappedAddress(cap, addr);
return cap;
} else {
cap = cap_frame_cap_set_capFMappedASID(cap, asid);
cap = cap_frame_cap_set_capFMappedAddress(cap, addr);
return cap;
}
}
static inline void
generic_frame_cap_ptr_set_capFMappedAddress(cap_t *cap_ptr, word_t asid,
word_t addr)
{
*cap_ptr = generic_frame_cap_set_capFMappedAddress(*cap_ptr, asid, addr);
}
static inline vm_rights_t CONST
generic_frame_cap_get_capFVMRights(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
assert(ctag == cap_small_frame_cap ||
ctag == cap_frame_cap);
switch (ctag) {
case cap_small_frame_cap:
return cap_small_frame_cap_get_capFVMRights(cap);
case cap_frame_cap:
return cap_frame_cap_get_capFVMRights(cap);
default:
return VMNoAccess;
}
}
static inline word_t CONST
generic_frame_cap_get_capFBasePtr(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
assert(ctag == cap_small_frame_cap ||
ctag == cap_frame_cap);
switch (ctag) {
case cap_small_frame_cap:
return cap_small_frame_cap_get_capFBasePtr(cap);
case cap_frame_cap:
return cap_frame_cap_get_capFBasePtr(cap);
default:
return 0;
}
}
static inline word_t CONST
generic_frame_cap_get_capFSize(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
assert(ctag == cap_small_frame_cap ||
ctag == cap_frame_cap);
switch (ctag) {
case cap_small_frame_cap:
return ARMSmallPage;
case cap_frame_cap:
return cap_frame_cap_get_capFSize(cap);
default:
return 0;
}
}
static inline word_t CONST
generic_frame_cap_get_capFIsMapped(cap_t cap)
{
return generic_frame_cap_get_capFMappedASID(cap) != 0;
}
static inline word_t CONST
generic_frame_cap_get_capFMappedAddress(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
assert(ctag == cap_small_frame_cap ||
ctag == cap_frame_cap);
if (ctag == cap_small_frame_cap) {
return cap_small_frame_cap_get_capFMappedAddress(cap);
} else {
return cap_frame_cap_get_capFMappedAddress(cap);
}
}
static inline unsigned int CONST
cap_get_capSizeBits(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
switch (ctag) {
case cap_untyped_cap:
return cap_untyped_cap_get_capBlockSize(cap);
case cap_endpoint_cap:
return EP_SIZE_BITS;
case cap_async_endpoint_cap:
return AEP_SIZE_BITS;
case cap_cnode_cap:
return cap_cnode_cap_get_capCNodeRadix(cap) + CTE_SIZE_BITS;
case cap_thread_cap:
return TCB_BLOCK_SIZE_BITS;
case cap_small_frame_cap:
case cap_frame_cap:
return pageBitsForSize(generic_frame_cap_get_capFSize(cap));
case cap_page_table_cap:
return PT_SIZE_BITS;
case cap_page_directory_cap:
return PD_SIZE_BITS;
case cap_asid_pool_cap:
return ASID_POOL_SIZE_BITS;
case cap_zombie_cap: {
uint32_t type = cap_zombie_cap_get_capZombieType(cap);
if (type == ZombieType_ZombieTCB) {
return TCB_BLOCK_SIZE_BITS;
}
return ZombieType_ZombieCNode(type) + CTE_SIZE_BITS;
}
case cap_null_cap:
case cap_domain_cap:
case cap_reply_cap:
case cap_irq_control_cap:
case cap_irq_handler_cap:
case cap_asid_control_cap:
return 0;
default:
/* Unreachable, but GCC can't figure that out */
return 0;
}
}
static inline void * CONST
cap_get_capPtr(cap_t cap)
{
cap_tag_t ctag;
ctag = cap_get_capType(cap);
switch (ctag) {
case cap_untyped_cap:
return WORD_PTR(cap_untyped_cap_get_capPtr(cap));
case cap_endpoint_cap:
return EP_PTR(cap_endpoint_cap_get_capEPPtr(cap));
case cap_async_endpoint_cap:
return AEP_PTR(cap_async_endpoint_cap_get_capAEPPtr(cap));
case cap_cnode_cap:
return CTE_PTR(cap_cnode_cap_get_capCNodePtr(cap));
case cap_thread_cap:
return TCB_PTR_CTE_PTR(cap_thread_cap_get_capTCBPtr(cap), 0);
case cap_small_frame_cap:
case cap_frame_cap:
return (void *)(generic_frame_cap_get_capFBasePtr(cap));
case cap_page_table_cap:
return PT_PTR(cap_page_table_cap_get_capPTBasePtr(cap));
case cap_page_directory_cap:
return PD_PTR(cap_page_directory_cap_get_capPDBasePtr(cap));
case cap_asid_pool_cap:
return ASID_POOL_PTR(cap_asid_pool_cap_get_capASIDPool(cap));
case cap_zombie_cap:
return CTE_PTR(cap_zombie_cap_get_capZombiePtr(cap));
case cap_null_cap:
case cap_domain_cap:
case cap_reply_cap:
case cap_irq_control_cap:
case cap_irq_handler_cap:
case cap_asid_control_cap:
return NULL;
default:
/* Unreachable, but GCC can't figure that out */
return NULL;
}
}
static inline word_t CONST
isArchCap(cap_t cap)
{
return (cap_get_capType(cap) % 2);
}
/* We need to supply different type getters for the bitfield generated PTE type
* because there is an implicit third type that PTEs can be. If the type bit is
* set but the reserved bit is not set, the type of the PTE is invalid, not a
* large PTE.
*/
enum { pte_pte_invalid = 2 };
static inline uint32_t __attribute__((__const__))
pte_get_pteType(pte_t pte)
{
if (pte_get_pteSize(pte) == pte_pte_small) {
return pte_pte_small;
} else if (pte_pte_large_get_reserved(pte) == 1) {
return pte_pte_large;
} else {
return pte_pte_invalid;
}
}
static inline uint32_t __attribute__((__pure__))
pte_ptr_get_pteType(pte_t *pte_ptr)
{
if (pte_ptr_get_pteSize(pte_ptr) == pte_pte_small) {
return pte_pte_small;
} else if (pte_pte_large_ptr_get_reserved(pte_ptr) == 1) {
return pte_pte_large;
} else {
return pte_pte_invalid;
}
}
#endif
| 24.710177 | 98 | 0.693795 | [
"object"
] |
32163b7104a9bada147ec831f06201947b6caf5d | 13,740 | h | C | src/OSSupport/Network.h | nickc01/cuberite | be818200a6567218ba99bb072e721c4b64b71d67 | [
"Apache-2.0"
] | 4,126 | 2015-06-12T21:56:49.000Z | 2022-03-31T06:33:12.000Z | src/OSSupport/Network.h | nickc01/cuberite | be818200a6567218ba99bb072e721c4b64b71d67 | [
"Apache-2.0"
] | 2,931 | 2015-06-11T17:13:15.000Z | 2022-03-31T22:46:31.000Z | src/OSSupport/Network.h | nickc01/cuberite | be818200a6567218ba99bb072e721c4b64b71d67 | [
"Apache-2.0"
] | 917 | 2015-06-11T21:47:41.000Z | 2022-03-30T10:32:55.000Z |
// Network.h
// Declares the classes used for the Network API
#pragma once
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
// fwd:
class cTCPLink;
typedef std::shared_ptr<cTCPLink> cTCPLinkPtr;
typedef std::vector<cTCPLinkPtr> cTCPLinkPtrs;
class cServerHandle;
typedef std::shared_ptr<cServerHandle> cServerHandlePtr;
typedef std::vector<cServerHandlePtr> cServerHandlePtrs;
class cCryptoKey;
typedef std::shared_ptr<cCryptoKey> cCryptoKeyPtr;
class cX509Cert;
typedef std::shared_ptr<cX509Cert> cX509CertPtr;
/** Interface that provides the methods available on a single TCP connection. */
class cTCPLink
{
friend class cNetwork;
public:
class cCallbacks
{
public:
// Force a virtual destructor for all descendants:
virtual ~cCallbacks() {}
/** Called when the cTCPLink for the connection is created.
The callback may store the cTCPLink instance for later use, but it should remove it in OnError(), OnRemoteClosed() or right after Close(). */
virtual void OnLinkCreated(cTCPLinkPtr a_Link) = 0;
/** Called when there's data incoming from the remote peer. */
virtual void OnReceivedData(const char * a_Data, size_t a_Length) = 0;
/** Called when the remote end closes the connection.
The link is still available for connection information query (IP / port).
Sending data on the link is not an error, but the data won't be delivered. */
virtual void OnRemoteClosed(void) = 0;
/** Called when the TLS handshake has been completed and communication can continue regularly.
Has an empty default implementation, so that link callback descendants don't need to specify TLS handlers when they don't use TLS at all. */
virtual void OnTlsHandshakeCompleted(void) {}
/** Called when an error is detected on the connection. */
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) = 0;
};
typedef std::shared_ptr<cCallbacks> cCallbacksPtr;
// Force a virtual destructor for all descendants:
virtual ~cTCPLink() {}
/** Queues the specified data for sending to the remote peer.
Returns true on success, false on failure. Note that this success or failure only reports the queue status, not the actual data delivery. */
virtual bool Send(const void * a_Data, size_t a_Length) = 0;
/** Queues the specified data for sending to the remote peer.
Returns true on success, false on failure. Note that this success or failure only reports the queue status, not the actual data delivery. */
bool Send(const AString & a_Data)
{
return Send(a_Data.data(), a_Data.size());
}
/** Returns the IP address of the local endpoint of the connection. */
virtual AString GetLocalIP(void) const = 0;
/** Returns the port used by the local endpoint of the connection. */
virtual UInt16 GetLocalPort(void) const = 0;
/** Returns the IP address of the remote endpoint of the connection. */
virtual AString GetRemoteIP(void) const = 0;
/** Returns the port used by the remote endpoint of the connection. */
virtual UInt16 GetRemotePort(void) const = 0;
/** Closes the link gracefully.
The link will send any queued outgoing data, then it will send the FIN packet.
The link will still receive incoming data from remote until the remote closes the connection. */
virtual void Shutdown(void) = 0;
/** Drops the connection without any more processing.
Sends the RST packet, queued outgoing and incoming data is lost. */
virtual void Close(void) = 0;
/** Starts a TLS handshake as a client connection.
If a client certificate should be used for the connection, set the certificate into a_OwnCertData and
its corresponding private key to a_OwnPrivKeyData. If both are empty, no client cert is presented.
a_OwnPrivKeyPassword is the password to be used for decoding PrivKey, empty if not passworded.
Returns empty string on success, non-empty error description on failure. */
virtual AString StartTLSClient(
cX509CertPtr a_OwnCert,
cCryptoKeyPtr a_OwnPrivKey
) = 0;
/** Starts a TLS handshake as a server connection.
Set the server certificate into a_CertData and its corresponding private key to a_OwnPrivKeyData.
a_OwnPrivKeyPassword is the password to be used for decoding PrivKey, empty if not passworded.
a_StartTLSData is any data that should be pushed into the TLS before reading more data from the remote.
This is used mainly for protocols starting TLS in the middle of communication, when the TLS start command
can be received together with the TLS Client Hello message in one OnReceivedData() call, to re-queue the
Client Hello message into the TLS handshake buffer.
Returns empty string on success, non-empty error description on failure. */
virtual AString StartTLSServer(
cX509CertPtr a_OwnCert,
cCryptoKeyPtr a_OwnPrivKey,
const AString & a_StartTLSData
) = 0;
/** Returns the callbacks that are used. */
cCallbacksPtr GetCallbacks(void) const { return m_Callbacks; }
protected:
/** Callbacks to be used for the various situations. */
cCallbacksPtr m_Callbacks;
/** Creates a new link, with the specified callbacks. */
cTCPLink(cCallbacksPtr a_Callbacks):
m_Callbacks(std::move(a_Callbacks))
{
}
};
/** Interface that provides the methods available on a listening server socket. */
class cServerHandle
{
friend class cNetwork;
public:
// Force a virtual destructor for all descendants:
virtual ~cServerHandle() {}
/** Stops the server, no more incoming connections will be accepted.
All current connections will be shut down (cTCPLink::Shutdown()). */
virtual void Close(void) = 0;
/** Returns true if the server has been started correctly and is currently listening for incoming connections. */
virtual bool IsListening(void) const = 0;
};
/** Interface that provides methods available on UDP communication endpoints. */
class cUDPEndpoint
{
public:
/** Interface for the callbacks for events that can happen on the endpoint. */
class cCallbacks
{
public:
// Force a virtual destructor in all descendants:
virtual ~cCallbacks() {}
/** Called when an error occurs on the endpoint. */
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) = 0;
/** Called when there is an incoming datagram from a remote host. */
virtual void OnReceivedData(const char * a_Data, size_t a_Size, const AString & a_RemoteHost, UInt16 a_RemotePort) = 0;
};
// Force a virtual destructor for all descendants:
virtual ~cUDPEndpoint() {}
/** Closes the underlying socket.
Note that there still might be callbacks in-flight after this method returns. */
virtual void Close(void) = 0;
/** Returns true if the endpoint is open. */
virtual bool IsOpen(void) const = 0;
/** Returns the local port to which the underlying socket is bound. */
virtual UInt16 GetPort(void) const = 0;
/** Sends the specified payload in a single UDP datagram to the specified host + port combination.
Note that in order to send to a broadcast address, you need to call EnableBroadcasts() first. */
virtual bool Send(const AString & a_Payload, const AString & a_Host, UInt16 a_Port) = 0;
/** Marks the socket as capable of sending broadcast, using whatever OS API is needed.
Without this call, sending to a broadcast address using Send() may fail. */
virtual void EnableBroadcasts(void) = 0;
protected:
/** The callbacks used for various events on the endpoint. */
cCallbacks & m_Callbacks;
/** Creates a new instance of an endpoint, with the specified callbacks. */
cUDPEndpoint(cCallbacks & a_Callbacks):
m_Callbacks(a_Callbacks)
{
}
};
typedef std::shared_ptr<cUDPEndpoint> cUDPEndpointPtr;
class cNetwork
{
public:
/** Callbacks used for connecting to other servers as a client. */
class cConnectCallbacks
{
public:
// Force a virtual destructor for all descendants:
virtual ~cConnectCallbacks() {}
/** Called when the Connect call succeeds.
Provides the newly created link that can be used for communication. */
virtual void OnConnected(cTCPLink & a_Link) = 0;
/** Called when the Connect call fails. */
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) = 0;
};
typedef std::shared_ptr<cConnectCallbacks> cConnectCallbacksPtr;
/** Callbacks used when listening for incoming connections as a server. */
class cListenCallbacks
{
public:
// Force a virtual destructor for all descendants:
virtual ~cListenCallbacks() {}
/** Called when the TCP server created with Listen() receives a new incoming connection.
Returns the link callbacks that the server should use for the newly created link.
If a nullptr is returned, the connection is dropped immediately;
otherwise a new cTCPLink instance is created and OnAccepted() is called. */
virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) = 0;
/** Called when the TCP server created with Listen() creates a new link for an incoming connection.
Provides the newly created Link that can be used for communication.
Called right after a successful OnIncomingConnection(). */
virtual void OnAccepted(cTCPLink & a_Link) = 0;
/** Called when the socket fails to listen on the specified port. */
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) = 0;
};
typedef std::shared_ptr<cListenCallbacks> cListenCallbacksPtr;
/** Callbacks used when resolving names to IPs. */
class cResolveNameCallbacks
{
public:
// Force a virtual destructor for all descendants:
virtual ~cResolveNameCallbacks() {}
/** Called when the hostname is successfully resolved into an IP address.
May be called multiple times if a name resolves to multiple addresses.
a_IP may be either an IPv4 or an IPv6 address with their proper formatting.
Each call to OnNameResolved() is preceded by a call to either OnNameResolvedV4() or OnNameResolvedV6(). */
virtual void OnNameResolved(const AString & a_Name, const AString & a_IP) = 0;
/** Called when the hostname is successfully resolved into an IPv4 address.
May be called multiple times if a name resolves to multiple addresses.
Each call to OnNameResolvedV4 is followed by OnNameResolved with the IP address serialized to a string.
If this callback returns false, the OnNameResolved() call is skipped for this address. */
virtual bool OnNameResolvedV4(const AString & a_Name, const sockaddr_in * a_IP) { return true; }
/** Called when the hostname is successfully resolved into an IPv6 address.
May be called multiple times if a name resolves to multiple addresses.
Each call to OnNameResolvedV4 is followed by OnNameResolved with the IP address serialized to a string.
If this callback returns false, the OnNameResolved() call is skipped for this address. */
virtual bool OnNameResolvedV6(const AString & a_Name, const sockaddr_in6 * a_IP) { return true; }
/** Called when an error is encountered while resolving.
If an error is reported, the OnFinished() callback is not called. */
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) = 0;
/** Called when all the addresses resolved have been reported via the OnNameResolved() callback.
Only called if there was no error reported. */
virtual void OnFinished(void) = 0;
};
typedef std::shared_ptr<cResolveNameCallbacks> cResolveNameCallbacksPtr;
/** Queues a TCP connection to be made to the specified host.
Calls one the connection callbacks (success, error) when the connection is successfully established, or upon failure.
The a_LinkCallbacks is passed to the newly created cTCPLink.
Returns true if queueing was successful, false on failure to queue.
Note that the return value doesn't report the success of the actual connection; the connection is established asynchronously in the background.
Implemented in TCPLinkImpl.cpp. */
static bool Connect(
const AString & a_Host,
UInt16 a_Port,
cConnectCallbacksPtr a_ConnectCallbacks,
cTCPLink::cCallbacksPtr a_LinkCallbacks
);
/** Opens up the specified port for incoming connections.
Calls an OnAccepted callback for each incoming connection.
A cTCPLink with the specified link callbacks is created for each connection.
Returns a cServerHandle that can be used to query the operation status and close the server.
Implemented in ServerHandleImpl.cpp. */
static cServerHandlePtr Listen(
UInt16 a_Port,
cListenCallbacksPtr a_ListenCallbacks
);
/** Queues a DNS query to resolve the specified hostname to IP address.
Calls one of the callbacks when the resolving succeeds, or when it fails.
Returns true if queueing was successful, false if not.
Note that the return value doesn't report the success of the actual lookup; the lookup happens asynchronously on the background.
Implemented in HostnameLookup.cpp. */
static bool HostnameToIP(
const AString & a_Hostname,
cResolveNameCallbacksPtr a_Callbacks
);
/** Queues a DNS query to resolve the specified IP address to a hostname.
Calls one of the callbacks when the resolving succeeds, or when it fails.
Returns true if queueing was successful, false if not.
Note that the return value doesn't report the success of the actual lookup; the lookup happens asynchronously on the background.
Implemented in IPLookup.cpp. */
static bool IPToHostName(
const AString & a_IP,
cResolveNameCallbacksPtr a_Callbacks
);
/** Opens up an UDP endpoint for sending and receiving UDP datagrams on the specified port.
If a_Port is 0, the OS is free to assign any port number it likes to the endpoint.
Returns the endpoint object that can be interacted with. */
static cUDPEndpointPtr CreateUDPEndpoint(UInt16 a_Port, cUDPEndpoint::cCallbacks & a_Callbacks);
/** Returns all local IP addresses for network interfaces currently available. */
static AStringVector EnumLocalIPAddresses(void);
};
| 37.336957 | 144 | 0.761063 | [
"object",
"vector"
] |
321b9b070ed56a2a06c1968217605175b73171e6 | 428 | h | C | src/Ball.h | Laefy/Brik | d8b93a1fca52fe3324e97500a4d20dcb3aeef06f | [
"MIT"
] | null | null | null | src/Ball.h | Laefy/Brik | d8b93a1fca52fe3324e97500a4d20dcb3aeef06f | [
"MIT"
] | null | null | null | src/Ball.h | Laefy/Brik | d8b93a1fca52fe3324e97500a4d20dcb3aeef06f | [
"MIT"
] | 1 | 2021-06-25T14:23:40.000Z | 2021-06-25T14:23:40.000Z | #pragma once
#include <SFML/System/Vector2.hpp>
class Map;
namespace sf {
class RenderTarget;
} // namespace sf
class Ball
{
public:
explicit Ball(const sf::Vector2f& position);
void Render(sf::RenderTarget& target) const;
void Update(float dt, Map& map);
private:
static constexpr float RADIUS = 0.05f;
sf::Vector2f m_position;
sf::Vector2f m_direction { 0.f, 1.f };
float m_speed = 1.f;
};
| 15.851852 | 48 | 0.672897 | [
"render"
] |
9a4ab68ef716cd9b9ac7b51e3aeb2ed81d08ad00 | 5,274 | h | C | src/plugcalc/newparse.h | FarPlugins/Calculator | 679cd57cfa223719e02dffd4a1b7876210a64e61 | [
"BSD-3-Clause"
] | 1 | 2021-12-16T14:26:23.000Z | 2021-12-16T14:26:23.000Z | src/plugcalc/newparse.h | FarPlugins/Calculator | 679cd57cfa223719e02dffd4a1b7876210a64e61 | [
"BSD-3-Clause"
] | 9 | 2021-01-06T07:25:00.000Z | 2021-10-04T16:45:05.000Z | src/plugcalc/newparse.h | FarPlugins/Calculator | 679cd57cfa223719e02dffd4a1b7876210a64e61 | [
"BSD-3-Clause"
] | 1 | 2021-05-30T19:00:49.000Z | 2021-05-30T19:00:49.000Z | //
// Copyright (c) uncle-vunkis 2009-2012 <uncle-vunkis@yandex.ru>
// You can use, modify, distribute this code or any other part
// of this program in sources or in binaries only according
// to License (see /doc/license.txt for more information).
//
#ifndef CALC_NEWPARSE_H
#define CALC_NEWPARSE_H
#include <sgml/sgml.h>
#include <unordered_map>
#undef min
#undef max
#include <mathexpression/MathExpressionBase.h>
#include "sarg.h"
#include "syntax.h"
enum CALC_ERROR
{
ERR_OK = 0,
ERR_ALL, ERR_EXPR, ERR_TYPE,
ERR_PARAM, ERR_BRACK, ERR_ZERO, ERR_FLOW, ERR_TOOLONG
};
enum CALC_CONV_TYPE
{
CALC_CONV_DECPT = -1,
CALC_CONV_DECEXP = -2,
CALC_CONV_ENTER = -3,
CALC_CONV_UNITS = -4,
};
class CalcAddonPart
{
public:
CalcAddonPart()
{
parser = nullptr;
}
CalcAddonPart(const CalcAddonPart & p);
~CalcAddonPart();
void Parse(bool no_args = false);
public:
friend class CalcParser;
std::wstring expr;
CalcParser *parser; /// pre-parsed pattern expression
int str_pos; /// abs. string position for replacement
};
class CalcAddon
{
public:
CalcAddon()
{
radix = 10;
flags = CALC_ADDON_FLAG_NONE;
}
public:
std::wstring name;
std::wstring expr;
int radix, flags;
std::vector<CalcAddonPart> parts;
};
struct SDialogElem
{
wchar_t Name[64];
int Type;
Big scale;
int addon_idx;
int column_idx;
CalcAddonPart *input, *scale_expr;
// PEditObject Edit;
SDialogElem *Next;
SDialogElem();
~SDialogElem();
};
typedef SDialogElem *PDialogElem;
struct SDialogData
{
wchar_t Name[64];
int num;
SDialogElem *Elem;
SDialogData *Next;
SDialogData();
~SDialogData();
};
typedef SDialogData *PDialogData;
class CalcParser : public MathExpressionBase<SArg>
{
typedef MathExpressionBase<SArg> mybase;
friend wchar_t *convertToString(SArg val, int type_idx, int num_lim, bool append_suffix, bool pad_zeroes, bool group_delim);
friend void print_repeating_decimal(std::wstring & s, SArg val, int num_lim, bool group_delim);
friend void print_continued_decimal(std::wstring & s, SArg val, int num_lim, bool group_delim);
friend int CalcMenu(int c);
friend void SetUnitsDialogDims();
friend void ShowUnitsDialog(int no);
friend struct SArg;
friend class CalcAddonPart;
public:
typedef SArg value_type;
CalcParser();
CalcParser(const CalcParser & p);
~CalcParser();
static bool InitTables(int rep_fraction_max_start, int rep_fraction_max_period, int cont_fraction_max);
static bool ProcessData(PSgmlEl BaseRc, bool case_sensitive);
static void FillDialogData(PSgmlEl Base, bool case_sensitive, const wchar_t *lang_name);
static bool SetDelims(wchar_t decimal, wchar_t args, wchar_t digit);
static bool ProcessAddons();
static bool ProcessDialogData();
static int GetNumDialogs();
/// Add all functs, ops, consts
static bool AddAll(bool add_user_ops_and_funcs = true);
static void GetFraction(Big b, BigInt *numer, BigInt *denom);
static void RoundUp(Big &b);
SArg Parse(const wchar_t* str, bool case_sensitive);
CALC_ERROR GetError();
public:
/// parsed addons
static std::vector<CalcAddon> addons;
static unsigned main_addons_num;
static wchar_t delim_decimal, delim_args, delim_digit;
static ttmath::Conv from_convs[17], to_convs[17];
protected:
bool parse_number(SArg *value, const wchar_t *curpos, wchar_t **endptr);
static bool FillSet(PSgmlEl set, bool case_sensitive);
static bool AddLexem(PSyntax &syntax, PSgmlEl Ch, PSgmlEl set, bool case_sensitive);
static int DelSpaces(wchar_t *str);
static std::wstring ReplaceDelims(const wchar_t *str);
bool SetVar(wchar_t *name, SArg value);
static PSyntax Consts;
static PSyntax Ops;
static PSyntax Functs;
static PSyntax Addons;
static PSyntax Numerals;
static PVars Vars;
protected:
static SArg builtin_binary_op(const SArg & op0, const SArg & op1);
static SArg builtin_unary_not(const SArg & op);
static SArg binary_op(const SArg & op0, const SArg & op1);
static SArg unary_op(const SArg & op0);
class UserFunctionList : public std::vector<CalcParser *>
{
public:
UserFunctionList() = default;
~UserFunctionList();
};
protected:
CALC_ERROR math_error;
string func_name;
static std::unordered_map<std::wstring, CalcParser *> user_bin_ops, user_un_ops;
protected:
static UserFunctionList *user_funcs;
static FunctionList allFunctions;
static NamedConstantList allNamedConstants;
static UnaryOperationTable allUnaryOpTable;
static BinaryOperationTable allBinaryOpTable;
static std::vector<BigInt> rep_fraction_coefs;
static std::vector<Big> rep_mul1, rep_mul2;
static Big rep_fraction_thr, rep_fraction_thr2;
static int rep_fraction_max_start, rep_fraction_max_period;
static int cont_fraction_max;
static PDialogData DialogData;
static int DialogsNum;
};
/// if type_idx >= 0 then it's index to addons, or type enum if < 0
wchar_t *convertToString(const SArg & val, int type_idx, int num_lim = 0, bool append_suffix = false, bool pad_zeroes = true, bool group_delim = true, CALC_ERROR *error_code = nullptr);
#endif // of CALC_NEWPARSE_H
| 24.64486 | 186 | 0.724308 | [
"vector"
] |
9a55fa44b7dfd4cde12625f850f5c9b5f11ab38a | 3,450 | h | C | src/components/autofill/browser/autocomplete_history_manager.h | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | components/autofill/browser/autocomplete_history_manager.h | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/browser/autocomplete_history_manager.h | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.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 COMPONENTS_AUTOFILL_BROWSER_AUTOCOMPLETE_HISTORY_MANAGER_H_
#define COMPONENTS_AUTOFILL_BROWSER_AUTOCOMPLETE_HISTORY_MANAGER_H_
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/prefs/pref_member.h"
#include "components/autofill/browser/webdata/autofill_webdata_service.h"
#include "components/webdata/common/web_data_service_consumer.h"
#include "content/public/browser/web_contents_observer.h"
namespace content {
class BrowserContext;
}
namespace autofill {
class AutofillExternalDelegate;
struct FormData;
// Per-tab Autocomplete history manager. Handles receiving form data
// from the renderer and the storing and retrieving of form data
// through WebDataServiceBase.
class AutocompleteHistoryManager : public content::WebContentsObserver,
public WebDataServiceConsumer {
public:
explicit AutocompleteHistoryManager(content::WebContents* web_contents);
virtual ~AutocompleteHistoryManager();
// content::WebContentsObserver implementation.
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
// WebDataServiceConsumer implementation.
virtual void OnWebDataServiceRequestDone(
WebDataServiceBase::Handle h,
const WDTypedResult* result) OVERRIDE;
// Pass-through functions that are called by AutofillManager, after it has
// dispatched a message.
void OnGetAutocompleteSuggestions(
int query_id,
const base::string16& name,
const base::string16& prefix,
const std::vector<base::string16>& autofill_values,
const std::vector<base::string16>& autofill_labels,
const std::vector<base::string16>& autofill_icons,
const std::vector<int>& autofill_unique_ids);
void OnFormSubmitted(const FormData& form);
// Must be public for the external delegate to use.
void OnRemoveAutocompleteEntry(const base::string16& name,
const base::string16& value);
// Sets our external delegate.
void SetExternalDelegate(AutofillExternalDelegate* delegate);
protected:
friend class AutofillManagerTest;
// Sends the given |suggestions| for display in the Autofill popup.
void SendSuggestions(const std::vector<base::string16>* suggestions);
private:
// Cancels the currently pending WebDataService query, if there is one.
void CancelPendingQuery();
content::BrowserContext* browser_context_;
scoped_refptr<AutofillWebDataService> autofill_data_;
BooleanPrefMember autofill_enabled_;
// When the manager makes a request from WebDataServiceBase, the database is
// queried on another thread, we record the query handle until we get called
// back. We also store the autofill results so we can send them together.
WebDataServiceBase::Handle pending_query_handle_;
int query_id_;
std::vector<base::string16> autofill_values_;
std::vector<base::string16> autofill_labels_;
std::vector<base::string16> autofill_icons_;
std::vector<int> autofill_unique_ids_;
// Delegate to perform external processing (display, selection) on
// our behalf. Weak.
AutofillExternalDelegate* external_delegate_;
DISALLOW_COPY_AND_ASSIGN(AutocompleteHistoryManager);
};
} // namespace autofill
#endif // COMPONENTS_AUTOFILL_BROWSER_AUTOCOMPLETE_HISTORY_MANAGER_H_
| 35.9375 | 78 | 0.771014 | [
"vector"
] |
9a573878ff189afdd06d9a3118d6c891b78aa932 | 393 | h | C | src/Cell.h | GuildMasterInfinite/GameOfLife | 2d320ff48a238fbf3c4ef6aed8a5959970dad9bf | [
"MIT"
] | null | null | null | src/Cell.h | GuildMasterInfinite/GameOfLife | 2d320ff48a238fbf3c4ef6aed8a5959970dad9bf | [
"MIT"
] | null | null | null | src/Cell.h | GuildMasterInfinite/GameOfLife | 2d320ff48a238fbf3c4ef6aed8a5959970dad9bf | [
"MIT"
] | null | null | null | #ifndef CELL_H
#define CELL_H
#include <SFML/Graphics.hpp>
class Cell
{
public:
static const int SIZE = 16;
Cell(int x, int y);
virtual ~Cell();
void render(sf::RenderWindow &w);
void setAlive(bool alive);
bool isAlive();
private:
const int x, y;
bool alive;
sf::RectangleShape shape;
};
#endif // CELL_H
| 14.555556 | 41 | 0.557252 | [
"render",
"shape"
] |
9a577b92971a8c00692a8face3ee02fcb1d2b535 | 20,725 | h | C | src/mnemonics/ukrainian.h | mygirl8893/evov3 | 3df817b5f5eeb15bf0dad84c3abfa24264c2ceab | [
"MIT"
] | null | null | null | src/mnemonics/ukrainian.h | mygirl8893/evov3 | 3df817b5f5eeb15bf0dad84c3abfa24264c2ceab | [
"MIT"
] | null | null | null | src/mnemonics/ukrainian.h | mygirl8893/evov3 | 3df817b5f5eeb15bf0dad84c3abfa24264c2ceab | [
"MIT"
] | 1 | 2018-06-04T08:50:33.000Z | 2018-06-04T08:50:33.000Z | // Copyright (c) 2017-2018, Karbo developers
/*!
* file Ukrainian.h
*
* Created by Karbovanets contributor Lastik, edited by Aiwe
* Based on 'Frequency list of Ukrainian language' by Volodymyr Vlad
* This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/.
* Copyright © 2013 Volodymyr Vlad
*
* brief Ukrainian word list.
*/
#pragma once
#include "language_base.h"
#include <vector>
#include <unordered_map>
#include <string>
namespace Language {
class Ukrainian : public Base
{
public:
const static std::string c_name;
Ukrainian() : Base(c_name, std::vector<std::string>({
"абат",
"абощо",
"абсурд",
"автор",
"агов",
"адепт",
"азарт",
"акцент",
"алея",
"альбом",
"альфа",
"амінь",
"ананас",
"ангар",
"анкета",
"апарат",
"арена",
"арешт",
"аркуш",
"армія",
"аромат",
"артист",
"артіль",
"арфа",
"аршин",
"атлас",
"атож",
"афіша",
"бабай",
"бабин",
"бавити",
"багач",
"бажати",
"балон",
"банан",
"банк",
"бариня",
"барліг",
"бармен",
"барон",
"бачити",
"баюра",
"береза",
"бидло",
"билина",
"бильце",
"битва",
"битий",
"бичок",
"благо",
"бланк",
"ближче",
"блиск",
"бляха",
"блідий",
"бодай",
"болото",
"болт",
"бомба",
"бора",
"борт",
"борщ",
"босий",
"боягуз",
"боязко",
"брань",
"браття",
"брижа",
"бритва",
"бронза",
"брук",
"брусок",
"бувало",
"будка",
"будяк",
"буква",
"букет",
"було",
"бурка",
"буряк",
"бути",
"буття",
"буфет",
"бухати",
"бюст",
"бігти",
"бігцем",
"бідняк",
"бізнес",
"бійка",
"білан",
"бісик",
"вабити",
"вада",
"вага",
"вадити",
"важіль",
"вазон",
"валер",
"валити",
"валун",
"вальс",
"валюта",
"валяти",
"валіза",
"вампір",
"вантаж",
"варкий",
"васал",
"ватага",
"вахтер",
"вбити",
"вбік",
"вверх",
"ввесь",
"вгорі",
"вдало",
"вдати",
"вдвох",
"вдень",
"вдова",
"вдома",
"вдягти",
"вельми",
"вепр",
"верета",
"версія",
"вертеп",
"вершок",
"весло",
"весна",
"вести",
"весь",
"вечеря",
"вжити",
"взвод",
"взимку",
"взнати",
"взятий",
"вибрик",
"вигляд",
"визиск",
"вийти",
"викрик",
"вилиця",
"вимити",
"винен",
"винний",
"вираз",
"вирій",
"витати",
"виток",
"вихід",
"вишити",
"вишкіл",
"вишня",
"вищати",
"вищий",
"вкрай",
"вкупі",
"вмерти",
"вміст",
"вміти",
"вниз",
"вовчий",
"вогкий",
"вогонь",
"вода",
"водний",
"вождь",
"возний",
"вокзал",
"волох",
"волхв",
"воля",
"ворог",
"воша",
"вперше",
"вплив",
"вправо",
"врешті",
"врожай",
"всього",
"всюди",
"всякий",
"втерти",
"втома",
"втрата",
"втіха",
"вузлик",
"вуйко",
"вулиця",
"вулкан",
"вусик",
"вчора",
"вщент",
"віват",
"відати",
"відлік",
"відсік",
"відхід",
"відьма",
"війна",
"вікно",
"вікінг",
"віник",
"вінок",
"віра",
"віршик",
"віск",
"вість",
"вісім",
"вітер",
"віхоть",
"вішати",
"віяти",
"гадати",
"гайда",
"галузь",
"ганити",
"гаплик",
"гаразд",
"гарба",
"гарно",
"гарт",
"гатити",
"гвинт",
"генрі",
"геолог",
"герб",
"герць",
"гиря",
"гладко",
"глас",
"глек",
"глечик",
"глузд",
"глухий",
"гнаний",
"гнида",
"гнилий",
"гнути",
"гнівно",
"гнідий",
"гніздо",
"гній",
"годен",
"година",
"голка",
"голота",
"голуб",
"гонець",
"гонор",
"гопак",
"гордий",
"горло",
"горня",
"горст",
"горщик",
"гостя",
"готово",
"градус",
"грань",
"грати",
"граф",
"грація",
"гребти",
"грек",
"грець",
"гречка",
"грубо",
"грудка",
"грюкіт",
"грітий",
"гріх",
"губка",
"гудок",
"гуляти",
"гумка",
"гурт",
"гусар",
"гуси",
"гусінь",
"гута",
"гуцул",
"гяур",
"гідний",
"гімн",
"гіпс",
"гіркий",
"гірше",
"давити",
"далеко",
"далі",
"дамба",
"дань",
"дарма",
"даром",
"дата",
"датися",
"датчик",
"дашок",
"дверці",
"двійка",
"двір",
"двічі",
"дедалі",
"декан",
"демон",
"депеша",
"дерево",
"дерти",
"десь",
"деякий",
"деінде",
"джаз",
"джинси",
"джип",
"дзьоб",
"дибати",
"дивина",
"дивний",
"дикий",
"димар",
"динька",
"дитя",
"днище",
"добро",
"добір",
"довбня",
"довго",
"доволі",
"довший",
"догляд",
"додати",
"додому",
"дожити",
"дозвіл",
"доки",
"докір",
"долати",
"долу",
"доля",
"дома",
"донизу",
"донька",
"доня",
"допіру",
"дорога",
"досвід",
"дослід",
"доста",
"досі",
"дотик",
"дотла",
"доторк",
"доцент",
"доїти",
"друг",
"друкар",
"дрібно",
"дуга",
"дуже",
"дужий",
"дукач",
"думка",
"дурно",
"дуріти",
"дути",
"душно",
"дюна",
"дядина",
"дятел",
"дідусь",
"дійти",
"ділити",
"діра",
"дірка",
"дітися",
"егоїзм",
"едем",
"екстаз",
"екіпаж",
"еліта",
"етап",
"етюд",
"ефект",
"ешелон",
"жадоба",
"жалоба",
"жаль",
"жанр",
"жахати",
"жахний",
"жваво",
"жереб",
"жертва",
"жест",
"живити",
"живо",
"жилка",
"житися",
"житло",
"житній",
"життя",
"жменя",
"жмут",
"жнець",
"жнива",
"жовнір",
"жовтий",
"жовч",
"жолоб",
"жолудь",
"жрець",
"жупан",
"журба",
"журнал",
"жучок",
"жінка",
"забити",
"завити",
"загал",
"загс",
"задати",
"задля",
"задній",
"задом",
"зажити",
"зайвий",
"закон",
"закрут",
"зала",
"замет",
"заміж",
"заново",
"заодно",
"заочно",
"запах",
"запона",
"засув",
"зась",
"затято",
"захист",
"зачати",
"зашити",
"заячий",
"заєць",
"збирач",
"збити",
"зблиск",
"збоку",
"зброя",
"збіжжя",
"збір",
"звання",
"звити",
"звичай",
"зворот",
"звідти",
"звір",
"згаяти",
"згоден",
"здати",
"здоров",
"земля",
"зигзаг",
"зима",
"зимний",
"зиск",
"зйомка",
"злам",
"злегка",
"злий",
"зліва",
"злізти",
"злість",
"зліт",
"змити",
"змога",
"змійка",
"зміст",
"знайда",
"знання",
"знову",
"знятий",
"зовні",
"зозуля",
"зойк",
"зонд",
"зорити",
"зоря",
"зоріти",
"зроду",
"зрідка",
"зубок",
"зуміти",
"зілля",
"ймення",
"йолоп",
"кабан",
"каблук",
"казан",
"казино",
"какао",
"кала",
"калина",
"калоша",
"калюжа",
"канава",
"канчук",
"капець",
"капище",
"капітан",
"карась",
"карета",
"карта",
"касета",
"касир",
"каска",
"катати",
"качан",
"каша",
"кашель",
"кашкет",
"каяття",
"каїн",
"квач",
"кваша",
"кволо",
"кедр",
"кейс",
"келих",
"кефір",
"кийок",
"килим",
"кирея",
"кирка",
"кисень",
"кисло",
"кисіль",
"киця",
"кишеня",
"кишка",
"кишіти",
"клепка",
"клин",
"клон",
"клоун",
"клубок",
"клунок",
"ключ",
"кліть",
"книжка",
"князь",
"кобура",
"коваль",
"ковила",
"ковпак",
"ковчег",
"кодекс",
"кожух",
"козеня",
"козир",
"козуб",
"коледж",
"колиба",
"колоти",
"коліно",
"комаха",
"комод",
"конати",
"конче",
"конюх",
"коняка",
"кора",
"коржик",
"корона",
"корпус",
"корчма",
"коса",
"косий",
"косяк",
"котел",
"котик",
"котрий",
"котяра",
"кофта",
"кохати",
"коцюба",
"кошик",
"кошт",
"крадій",
"краля",
"крам",
"кран",
"кратер",
"кращий",
"країна",
"кредит",
"крем",
"кривда",
"криза",
"крити",
"криця",
"кролик",
"кругом",
"крук",
"кряж",
"крісло",
"кубик",
"кубло",
"кузина",
"кузня",
"кукіль",
"культ",
"кума",
"куна",
"куняти",
"купе",
"купчик",
"курган",
"кури",
"курний",
"курява",
"кусник",
"кутик",
"кутя",
"кухоль",
"кушнір",
"кшталт",
"кілер",
"кіль",
"кінець",
"кінчик",
"кінь",
"кіоск",
"кіска",
"кістка",
"кітель",
"кішка",
"лабети",
"лава",
"лавиця",
"лагуна",
"ладо",
"лазити",
"лазня",
"ламати",
"лантух",
"лапа",
"лапка",
"ласка",
"ласощі",
"левада",
"легко",
"легіон",
"ледар",
"ледь",
"лежак",
"лезо",
"лекція",
"леле",
"лемент",
"летіти",
"лижа",
"линва",
"линути",
"липень",
"лисиця",
"лист",
"литвин",
"литися",
"лихий",
"лицар",
"лице",
"личина",
"личко",
"лишати",
"лишити",
"лобода",
"логіка",
"лоза",
"лозина",
"лозунг",
"лопух",
"лоро",
"лунати",
"лупати",
"луска",
"льон",
"любов",
"любчик",
"людний",
"люлька",
"люто",
"лягати",
"ляда",
"лячно",
"ліана",
"лігво",
"ліжко",
"ліки",
"лікоть",
"лілея",
"лінь",
"ліпити",
"ліпший",
"ліра",
"ліса",
"лісник",
"літати",
"літо",
"лічити",
"мабуть",
"магнат",
"мадам",
"мазепа",
"мазур",
"майдан",
"майже",
"майка",
"майно",
"майя",
"маклер",
"максим",
"макуха",
"мальва",
"малюк",
"маліти",
"мандри",
"маневр",
"мантія",
"мара",
"марка",
"мармур",
"марний",
"марс",
"марш",
"масаж",
"масний",
"масово",
"мастак",
"матка",
"матуся",
"мафія",
"махом",
"машина",
"маячня",
"маєток",
"медик",
"медуза",
"межа",
"менш",
"меню",
"мерщій",
"мести",
"месія",
"мета",
"метеор",
"меткий",
"метод",
"мечеть",
"минати",
"минути",
"мирний",
"миро",
"миска",
"мисль",
"мити",
"митра",
"миттю",
"миша",
"млин",
"млосно",
"мляво",
"мліти",
"мовби",
"мовний",
"могти",
"мода",
"модний",
"модуль",
"мокро",
"молоти",
"монгол",
"мораль",
"морг",
"морок",
"мотати",
"мотив",
"мотор",
"мотуз",
"мощі",
"мрець",
"мрія",
"мстити",
"мудро",
"мужньо",
"муляти",
"мураха",
"мутний",
"муха",
"мушка",
"мчати",
"мідь",
"мікроб",
"мілкий",
"міняти",
"міраж",
"місити",
"місток",
"міцний",
"набити",
"набік",
"навіщо",
"нагай",
"нагорі",
"надати",
"надмір",
"надпис",
"надути",
"наді",
"назад",
"наймит",
"налити",
"наліт",
"намір",
"напис",
"напрям",
"напій",
"наразі",
"нарком",
"наруга",
"насип",
"наскок",
"натовп",
"натура",
"нахил",
"нацист",
"начеб",
"неволя",
"негода",
"недруг",
"незле",
"нелюд",
"немає",
"неміч",
"неначе",
"ненка",
"нерв",
"нехай",
"нехотя",
"нижче",
"никати",
"нитка",
"нить",
"нишком",
"новак",
"новела",
"новина",
"ножик",
"носик",
"носок",
"носій",
"нота",
"нотка",
"нудний",
"нужда",
"нуль",
"нумо",
"ніжно",
"нізащо",
"нікуди",
"німб",
"німець",
"німота",
"нічого",
"ніяк",
"обабіч",
"обвал",
"обидва",
"обмаль",
"обмін",
"обняти",
"обоз",
"обора",
"обоє",
"обрис",
"обруч",
"обхід",
"обшир",
"обід",
"обіч",
"овал",
"овес",
"одежа",
"одинак",
"одійти",
"ожина",
"окань",
"окраса",
"окрім",
"олія",
"омар",
"онде",
"оний",
"опора",
"оправа",
"опікун",
"опір",
"оракул",
"орач",
"оргазм",
"особа",
"осокір",
"острів",
"осуд",
"осяяти",
"осінь",
"отак",
"отам",
"отвір",
"отим",
"отой",
"отрок",
"отрута",
"офіс",
"офіцер",
"охайно",
"охнути",
"охота",
"охочий",
"оцей",
"оцінка",
"очерет",
"очний",
"падати",
"падло",
"пазуха",
"пака",
"палата",
"палець",
"палити",
"палко",
"пальма",
"панель",
"панна",
"папаха",
"паркет",
"паста",
"патли",
"патрон",
"патьок",
"пафос",
"пацан",
"паче",
"пашіти",
"паща",
"певен",
"певне",
"педаль",
"пекуче",
"пелька",
"пенсне",
"пень",
"перина",
"перон",
"перст",
"перший",
"печаль",
"печеня",
"пилюка",
"пиляти",
"пиріг",
"писар",
"писк",
"писок",
"пиття",
"пиха",
"пищати",
"пияк",
"плазма",
"плай",
"план",
"пласт",
"плач",
"плесо",
"плече",
"плин",
"плугар",
"плюс",
"плямка",
"плівка",
"плід",
"плітка",
"побути",
"побіля",
"повз",
"повний",
"повіки",
"погано",
"погляд",
"погон",
"поезія",
"поет",
"пожежа",
"пожива",
"позад",
"позов",
"поки",
"покора",
"покров",
"полин",
"полк",
"полюс",
"поляк",
"політ",
"помалу",
"помста",
"поміж",
"понад",
"попадя",
"попіл",
"пора",
"порив",
"порода",
"портал",
"посаг",
"посол",
"потиск",
"потому",
"потуга",
"потіха",
"пошити",
"пояс",
"поїти",
"право",
"прадід",
"праска",
"присуд",
"притча",
"приціл",
"пробіл",
"провал",
"проект",
"пройти",
"прокоп",
"проміж",
"прорив",
"просо",
"протяг",
"прохід",
"прояв",
"пружно",
"прямий",
"прірва",
"псалом",
"птах",
"пташка",
"пузо",
"пульс",
"пункт",
"пусто",
"пуття",
"путь",
"пшоно",
"півень",
"півник",
"піджак",
"підло",
"підряд",
"підхід",
"піжама",
"пільга",
"піна",
"піонер",
"після",
"піст",
"пітон",
"піхва",
"пічка",
"рабиня",
"равлик",
"раджа",
"ради",
"радник",
"район",
"ракета",
"рама",
"рамено",
"ранг",
"ранець",
"ранити",
"ранком",
"рано",
"раніш",
"раптом",
"рать",
"рачки",
"ребро",
"рева",
"ревище",
"ревний",
"ревти",
"регіт",
"рейка",
"рейс",
"рекорд",
"ректор",
"ремінь",
"рента",
"рецепт",
"речник",
"ривок",
"ридати",
"ринути",
"риса",
"робити",
"рогоза",
"родити",
"роза",
"розбір",
"розкіш",
"розмір",
"розпад",
"розум",
"роман",
"ротик",
"рубати",
"рубець",
"руда",
"румун",
"рурка",
"русин",
"рухати",
"рученя",
"ручка",
"рушати",
"рушій",
"руїна",
"рядком",
"рядно",
"рядок",
"ряска",
"ряст",
"рівень",
"рідко",
"рідня",
"різкий",
"різник",
"рішати",
"рішучо",
"сага",
"садиба",
"садок",
"сакви",
"сало",
"салют",
"самець",
"самиця",
"сапер",
"сарана",
"сварка",
"сваха",
"свинка",
"свято",
"свіжо",
"світло",
"свіча",
"сейм",
"секрет",
"сектор",
"секція",
"селити",
"селюк",
"серб",
"сердюк",
"середа",
"серп",
"серія",
"сизий",
"синтез",
"синяк",
"синій",
"сириця",
"ситий",
"сичати",
"скала",
"скарб",
"скелет",
"склад",
"скніти",
"скоба",
"скорий",
"скраю",
"скриня",
"слабий",
"славка",
"слати",
"сливка",
"слимак",
"служба",
"сльота",
"сліпо",
"смерть",
"смик",
"сморід",
"смутно",
"сміло",
"снаряд",
"снасть",
"собака",
"собі",
"сокира",
"сокіл",
"солома",
"солід",
"соната",
"сонний",
"соня",
"сопка",
"сорт",
"сосна",
"сотка",
"соус",
"соціум",
"союз",
"спекти",
"сперма",
"спис",
"спрут",
"спів",
"став",
"старик",
"стаття",
"стегно",
"стеля",
"стен",
"стерня",
"стиль",
"стисло",
"стихія",
"стовп",
"стоячи",
"страта",
"стрий",
"строфа",
"струна",
"стріла",
"стукач",
"стулка",
"стусан",
"стягти",
"стіл",
"стінка",
"суворо",
"сувій",
"суглоб",
"суддя",
"судина",
"судно",
"судома",
"сукно",
"сумно",
"сунути",
"сутінь",
"сухар",
"сухо",
"сушити",
"сущий",
"суєта",
"схил",
"схов",
"схожий",
"схрон",
"схід",
"сюжет",
"сяючий",
"сяяти",
"сідати",
"сікач",
"сірко",
"сірник",
"сісти",
"сіяти",
"сіяч",
"табло",
"табу",
"тавро",
"така",
"талант",
"тандем",
"танк",
"танок",
"танути",
"тато",
"тахта",
"таїна",
"таїти",
"твань",
"твар",
"твердо",
"театр",
"теза",
"тема",
"темний",
"темп",
"темінь",
"тепер",
"тепло",
"терези",
"термос",
"терор",
"тертя",
"тесати",
"технік",
"течія",
"тигр",
"тикати",
"тисяча",
"титар",
"титул",
"тихо",
"тихцем",
"тиша",
"тлін",
"товща",
"того",
"толока",
"тонкий",
"тонший",
"тонус",
"тополя",
"торба",
"трава",
"тракт",
"транс",
"треба",
"тренер",
"тричі",
"трон",
"тропіки",
"троян",
"трудар",
"труна",
"трюк",
"трішки",
"туалет",
"тугий",
"тужний",
"туніка",
"тупати",
"тупий",
"турист",
"туча",
"тюрма",
"тяга",
"тягти",
"тяжко",
"тяжче",
"тяжіти",
"тяма",
"тятива",
"тіло",
"тільце",
"тітка",
"тітчин",
"тішити",
"убір",
"увесь",
"уголос",
"угору",
"удар",
"удача",
"удвічі",
"узвіз",
"узяти",
"укол",
"украй",
"улич",
"уміло",
"унизу",
"уночі",
"уніат",
"унітаз",
"унія",
"уперше",
"упир",
"упокій",
"ураз",
"уранці",
"урвище",
"уряд",
"услід",
"усміх",
"успіх",
"уста",
"усього",
"усякий",
"утроба",
"уява",
"уявити",
"файл",
"факт",
"фальш",
"фара",
"фарба",
"фарс",
"фасон",
"фата",
"фермер",
"флакон",
"флот",
"фляга",
"фокус",
"фонд",
"фора",
"фотель",
"фото",
"фрак",
"франк",
"фраза",
"фреска",
"футбол",
"фікція",
"філія",
"фірма",
"хабар",
"халат",
"халепа",
"халупа",
"хатка",
"хвала",
"хвіст",
"хижка",
"хитати",
"хиткий",
"хитро",
"хлоп",
"хмара",
"хмиз",
"ходити",
"хоча",
"хребет",
"хрест",
"хрипко",
"хропти",
"хруст",
"хрущ",
"хтось",
"хутір",
"хідник",
"хімія",
"царів",
"цвісти",
"цезар",
"центр",
"церква",
"циклон",
"цинізм",
"цить",
"цукор",
"цупкий",
"цівка",
"цікаво",
"цілий",
"чавун",
"чагар",
"чадо",
"чайка",
"чайник",
"чаклун",
"чапля",
"чарка",
"часник",
"часом",
"часто",
"чати",
"чаша",
"чашка",
"чвара",
"чекати",
"чемно",
"черва",
"через",
"черкас",
"черінь",
"чесати",
"честь",
"чийсь",
"чимало",
"чимраз",
"чинний",
"чирва",
"число",
"чисто",
"читач",
"член",
"човник",
"чоло",
"чорний",
"чорт",
"чота",
"чотири",
"чувати",
"чудно",
"чудо",
"чуже",
"чужий",
"чуйний",
"чума",
"чути",
"чутка",
"чітко",
"шакал",
"шалик",
"шаман",
"шанець",
"шати",
"шафа",
"шахтар",
"шашка",
"швачка",
"швед",
"швидко",
"шедевр",
"шейх",
"шеляг",
"шерех",
"шериф",
"шиба",
"шибка",
"ширити",
"широко",
"ширше",
"шитво",
"шити",
"шкала",
"шквал",
"шкода",
"шкіпер",
"шкірка",
"шлик",
"шлунок",
"шляхта",
"шовк",
"шолом",
"шофер",
"шпарко",
"шпигун",
"шпиль",
"шпичак",
"шрифт",
"штаб",
"штамп",
"штани",
"штахет",
"штик",
"штраф",
"шуба",
"шубка",
"шуліка",
"шурхіт",
"шхуна",
"щабель",
"щастя",
"щезати",
"щеня",
"щиро",
"щоби",
"щодень",
"щодня",
"щомиті",
"щораз",
"щосили",
"щічка",
"ювелір",
"ювілей",
"юнга",
"юрба",
"юрист",
"юрма",
"юрта",
"явити",
"явище",
"ягня",
"ягода",
"ягідка",
"якір",
"ямочка",
"ярина",
"ярка",
"ярмо",
"яруга",
"ясла",
"ясний",
"ясніше",
"ятаган",
"яхта",
"ячмінь",
"ящик",
"яєчня",
"євро",
"єдиний",
"єство",
"ідилія",
"іззаду",
"ікона",
"імла",
"індус",
"іноді",
"іній",
"іржа",
"іскра",
"іслам",
"істота",
"їжак",
"їжачок",
"їздити",
"їхній",
"ґанок",
"ґазда",
"ґвалт",
"ґрунт",
"ґуля"
}), 4)
{
populate_maps();
}
};
} //Language
| 12.477423 | 184 | 0.438649 | [
"vector"
] |
9a578369640d7cb654e6cb68853799c5bb7e499f | 1,701 | h | C | external/GTEngine/Include/Mathematics/GteVertexAttribute.h | yushuiqiang/geometry3cpp | 2727986b89da2d40ffbd0dddb6947183c8bf68b0 | [
"BSL-1.0"
] | 1 | 2021-02-18T10:25:42.000Z | 2021-02-18T10:25:42.000Z | external/GTEngine/Include/Mathematics/GteVertexAttribute.h | yushuiqiang/geometry3cpp | 2727986b89da2d40ffbd0dddb6947183c8bf68b0 | [
"BSL-1.0"
] | null | null | null | external/GTEngine/Include/Mathematics/GteVertexAttribute.h | yushuiqiang/geometry3cpp | 2727986b89da2d40ffbd0dddb6947183c8bf68b0 | [
"BSL-1.0"
] | null | null | null | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.3.0 (2016/08/29)
#pragma once
#include <GTEngineDEF.h>
#include <string>
namespace gte
{
struct VertexAttribute
{
inline VertexAttribute();
inline VertexAttribute(std::string const& inSemantic, void* inSource, size_t inStride);
// The 'semantic' string allows you to query for a specific vertex
// attribute and use the 'source' and 'stride' to access the data
// of the attribute. For example, you might use the semantics
// "position" (px,py,pz), "normal" (nx,ny,nz), "tcoord" (texture
// coordinates (u,v)), "dpdu" (derivative of position with respect
// to u), or "dpdv" (derivative of position with respect to v) for
// mesh vertices.
//
// The source pointer must be 4-byte aligned. The stride must be
// positive and a multiple of 4. The pointer alignment constraint is
// guaranteed on 32-bit and 64-bit architectures. The stride constraint
// is reasonable given that (usually) geometric attributes are usually
// arrays of 'float' or 'double'.
std::string semantic;
void* source;
size_t stride;
};
inline VertexAttribute::VertexAttribute()
:
semantic(""),
source(nullptr),
stride(0)
{
}
inline VertexAttribute::VertexAttribute(std::string const& inSemantic, void* inSource, size_t inStride)
:
semantic(inSemantic),
source(inSource),
stride(inStride)
{
}
}
| 29.842105 | 104 | 0.66843 | [
"mesh"
] |
9a5baa2398f8acf2f7914521c5b292948c3d01b9 | 12,812 | c | C | ext/db/builder/where.c | erikaaron/cphalcon7-1.3.3-Stable-0 | 5f8d996370449421317694534caa7285a286d0b4 | [
"BSD-3-Clause"
] | 1 | 2020-04-26T23:16:41.000Z | 2020-04-26T23:16:41.000Z | ext/db/builder/where.c | erikwang2013/cphalcon7-1.3.3-Stable-0 | 5f8d996370449421317694534caa7285a286d0b4 | [
"BSD-3-Clause"
] | null | null | null | ext/db/builder/where.c | erikwang2013/cphalcon7-1.3.3-Stable-0 | 5f8d996370449421317694534caa7285a286d0b4 | [
"BSD-3-Clause"
] | null | null | null | /*
+------------------------------------------------------------------------+
| Phalcon Framework |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file docs/LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to license@phalconphp.com so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Andres Gutierrez <andres@phalconphp.com> |
| Eduar Carvajal <eduar@phalconphp.com> |
| ZhuZongXin <dreamsxin@qq.com> |
+------------------------------------------------------------------------+
*/
#include "db/builder/where.h"
#include "db/builder.h"
#include "db/builder/exception.h"
#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/array.h"
#include "kernel/object.h"
#include "kernel/exception.h"
#include "kernel/fcall.h"
#include "kernel/concat.h"
#include "kernel/operators.h"
#include "kernel/string.h"
/**
* Phalcon\Db\Builder\Where
*
* Helps to create PHQL queries for WHERE statements
*/
zend_class_entry *phalcon_db_builder_where_ce;
PHP_METHOD(Phalcon_Db_Builder_Where, setConditions);
PHP_METHOD(Phalcon_Db_Builder_Where, getConditions);
PHP_METHOD(Phalcon_Db_Builder_Where, where);
PHP_METHOD(Phalcon_Db_Builder_Where, andWhere);
PHP_METHOD(Phalcon_Db_Builder_Where, orWhere);
PHP_METHOD(Phalcon_Db_Builder_Where, inWhere);
PHP_METHOD(Phalcon_Db_Builder_Where, notInWhere);
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_builder_where_setconditions, 0, 0, 1)
ZEND_ARG_INFO(0, conditions)
ZEND_ARG_TYPE_INFO(0, bindParams, IS_ARRAY, 1)
ZEND_ARG_TYPE_INFO(0, bindTypes, IS_ARRAY, 1)
ZEND_ARG_TYPE_INFO(0, bindParams, IS_ARRAY, 1)
ZEND_ARG_TYPE_INFO(0, type, _IS_BOOL, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_builder_where_where, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, conditions, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, bindParams, IS_ARRAY, 1)
ZEND_ARG_TYPE_INFO(0, bindTypes, IS_ARRAY, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_builder_where_andwhere, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, conditions, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, bindParams, IS_ARRAY, 1)
ZEND_ARG_TYPE_INFO(0, bindTypes, IS_ARRAY, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_builder_where_orwhere, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, conditions, IS_STRING, 0)
ZEND_ARG_INFO(0, bindParams)
ZEND_ARG_INFO(0, bindTypes)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_builder_where_inwhere, 0, 0, 2)
ZEND_ARG_TYPE_INFO(0, expr, IS_STRING, 0)
ZEND_ARG_INFO(0, values)
ZEND_ARG_INFO(0, useOrWhere)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_builder_where_notinwhere, 0, 0, 2)
ZEND_ARG_TYPE_INFO(0, expr, IS_STRING, 0)
ZEND_ARG_INFO(0, values)
ZEND_ARG_INFO(0, useOrWhere)
ZEND_END_ARG_INFO()
static const zend_function_entry phalcon_db_builder_where_method_entry[] = {
PHP_ME(Phalcon_Db_Builder_Where, setConditions, arginfo_phalcon_db_builder_where_setconditions, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Db_Builder_Where, getConditions, NULL, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Db_Builder_Where, where, arginfo_phalcon_db_builder_where_where, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Db_Builder_Where, andWhere, arginfo_phalcon_db_builder_where_andwhere, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Db_Builder_Where, orWhere, arginfo_phalcon_db_builder_where_orwhere, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Db_Builder_Where, inWhere, arginfo_phalcon_db_builder_where_inwhere, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Db_Builder_Where, notInWhere, arginfo_phalcon_db_builder_where_notinwhere, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/**
* Phalcon\Db\Builder initializer
*/
PHALCON_INIT_CLASS(Phalcon_Db_Builder_Where){
PHALCON_REGISTER_CLASS_EX(Phalcon\\Db\\Builder, Where, db_builder_where, phalcon_db_builder_ce, phalcon_db_builder_where_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS);
zend_declare_property_null(phalcon_db_builder_where_ce, SL("_conditions"), ZEND_ACC_PROTECTED);
return SUCCESS;
}
/**
* Return the conditions
*
* @return string
*/
PHP_METHOD(Phalcon_Db_Builder_Where, getConditions){
RETURN_MEMBER(getThis(), "_conditions");
}
/**
* Gets the type of PHQL queries
*
* @param string|array $conditions
* @param array $bindParams
* @param array $bindTypes
* @param boolean $type
* @param boolean $grouping
* @return int
*/
PHP_METHOD(Phalcon_Db_Builder_Where, setConditions){
zval *conditions, *bind_params = NULL, *bind_types = NULL, *type = NULL, *grouping = NULL, merge = {};
phalcon_fetch_params(0, 1, 4, &conditions, &bind_params, &bind_types, &type, &grouping);
if (!bind_params) {
bind_params = &PHALCON_GLOBAL(z_null);
}
if (!bind_types) {
bind_types = &PHALCON_GLOBAL(z_null);
}
if (!type) {
type = &PHALCON_GLOBAL(z_null);
}
ZVAL_BOOL(&merge, Z_TYPE_P(type) != IS_NULL ? 1 : 0);
PHALCON_CALL_METHOD(NULL, getThis(), "setbindparams", bind_params, &merge);
PHALCON_CALL_METHOD(NULL, getThis(), "setbindtypes", bind_types, &merge);
if (Z_TYPE_P(type) != IS_NULL) {
zval new_conditions = {}, current_conditions = {};
PHALCON_CALL_SELF(¤t_conditions, "getConditions");
if (zend_is_true(type)) {
/**
* Nest the condition to current ones or set as unique
*/
if (zend_is_true(¤t_conditions)) {
if (zend_is_true(grouping)) {
PHALCON_CONCAT_SVSVS(&new_conditions, "(", ¤t_conditions, ") AND (", conditions, ")");
} else {
PHALCON_CONCAT_VSV(&new_conditions, ¤t_conditions, " AND ", conditions);
}
} else {
ZVAL_COPY(&new_conditions, conditions);
}
} else {
if (zend_is_true(¤t_conditions)) {
if (zend_is_true(grouping)) {
PHALCON_CONCAT_SVSVS(&new_conditions, "(", ¤t_conditions, ") OR (", conditions, ")");
} else {
PHALCON_CONCAT_VSV(&new_conditions, ¤t_conditions, " OR ", conditions);
}
} else {
ZVAL_COPY(&new_conditions, conditions);
}
}
zval_ptr_dtor(¤t_conditions);
phalcon_update_property(getThis(), SL("_conditions"), &new_conditions);
zval_ptr_dtor(&new_conditions);
} else {
phalcon_update_property(getThis(), SL("_conditions"), conditions);
}
}
/**
* Sets the query conditions
*
*<code>
* $builder->where('name = "Peter"');
* $builder->where('name = :name AND id > :id', array('name' => 'Peter', 'id' => 100));
*</code>
*
* @param string $conditions
* @param array $bindParams
* @param array $bindTypes
* @param boolean $grouping
* @return Phalcon\Db\Builder
*/
PHP_METHOD(Phalcon_Db_Builder_Where, where){
zval *conditions, *bind_params = NULL, *bind_types = NULL;
phalcon_fetch_params(0, 1, 2, &conditions, &bind_params, &bind_types);
if (!bind_params) {
bind_params = &PHALCON_GLOBAL(z_null);
}
if (!bind_types) {
bind_types = &PHALCON_GLOBAL(z_null);
}
PHALCON_CALL_SELF(NULL, "setconditions", conditions, bind_params, bind_types);
RETURN_THIS();
}
/**
* Appends a condition to the current conditions using a AND operator
*
*<code>
* $builder->andWhere('name = "Peter"');
* $builder->andWhere('name = :name AND id > :id', array('name' => 'Peter', 'id' => 100));
*</code>
*
* @param string $conditions
* @param array $bindParams
* @param array $bindTypes
* @param boolean $grouping
* @return Phalcon\Db\Builder
*/
PHP_METHOD(Phalcon_Db_Builder_Where, andWhere){
zval *conditions, *bind_params = NULL, *bind_types = NULL, *grouping = NULL;
phalcon_fetch_params(0, 1, 3, &conditions, &bind_params, &bind_types, &grouping);
if (!bind_params) {
bind_params = &PHALCON_GLOBAL(z_null);
}
if (!bind_types) {
bind_types = &PHALCON_GLOBAL(z_null);
}
if (!grouping) {
grouping = &PHALCON_GLOBAL(z_true);
}
PHALCON_CALL_SELF(NULL, "setconditions", conditions, bind_params, bind_types, &PHALCON_GLOBAL(z_true), grouping);
RETURN_THIS();
}
/**
* Appends a condition to the current conditions using a OR operator
*
* @param string $conditions
* @param array $bindParams
* @param array $bindTypes
* @return Phalcon\Db\Builder
*/
PHP_METHOD(Phalcon_Db_Builder_Where, orWhere){
zval *conditions, *bind_params = NULL, *bind_types = NULL, *grouping = NULL;
phalcon_fetch_params(0, 1, 3, &conditions, &bind_params, &bind_types, &grouping);
if (!bind_params) {
bind_params = &PHALCON_GLOBAL(z_null);
}
if (!bind_types) {
bind_types = &PHALCON_GLOBAL(z_null);
}
if (!grouping) {
grouping = &PHALCON_GLOBAL(z_true);
}
PHALCON_CALL_SELF(NULL, "setconditions", conditions, bind_params, bind_types, &PHALCON_GLOBAL(z_false), grouping);
RETURN_THIS();
}
/**
* Appends an IN condition to the current conditions
*
* @param string $expr
* @param array $values
* @param boolean $useOrWhere
* @return Phalcon\Db\Builder
*/
PHP_METHOD(Phalcon_Db_Builder_Where, inWhere){
zval *expr, *values, *use_orwhere = NULL, hidden_param = {}, bind_params = {}, bind_keys = {}, *value, joined_keys = {}, conditions = {};
phalcon_fetch_params(0, 2, 1, &expr, &values, &use_orwhere);
if (!use_orwhere) {
use_orwhere = &PHALCON_GLOBAL(z_false);
}
phalcon_read_property(&hidden_param, getThis(), SL("_hiddenParamNumber"), PH_READONLY);
array_init(&bind_params);
array_init(&bind_keys);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(values), value) {
zval key = {}, query_key = {};
/**
* Key with auto bind-params
*/
PHALCON_CONCAT_SV(&key, "phi", &hidden_param);
PHALCON_CONCAT_SVS(&query_key, ":", &key, ":");
phalcon_array_append(&bind_keys, &query_key, 0);
phalcon_array_update(&bind_params, &key, value, PH_COPY);
zval_ptr_dtor(&key);
phalcon_increment(&hidden_param);
} ZEND_HASH_FOREACH_END();
phalcon_fast_join_str(&joined_keys, SL(", "), &bind_keys);
zval_ptr_dtor(&bind_keys);
/**
* Create a standard IN condition with bind params
*/
PHALCON_CONCAT_VSVS(&conditions, expr, " IN (", &joined_keys, ")");
zval_ptr_dtor(&joined_keys);
/**
* Append the IN to the current conditions using and 'and'
*/
if (zend_is_true(use_orwhere)) {
PHALCON_CALL_METHOD(NULL, getThis(), "orwhere", &conditions, &bind_params);
} else {
PHALCON_CALL_METHOD(NULL, getThis(), "andwhere", &conditions, &bind_params);
}
zval_ptr_dtor(&conditions);
zval_ptr_dtor(&bind_params);
phalcon_update_property(getThis(), SL("_hiddenParamNumber"), &hidden_param);
RETURN_THIS();
}
/**
* Appends a NOT IN condition to the current conditions
*
* @param string $expr
* @param array $values
* @param boolean $useOrWhere
* @return Phalcon\Db\Builder
*/
PHP_METHOD(Phalcon_Db_Builder_Where, notInWhere){
zval *expr, *values, *use_orwhere = NULL, hidden_param = {}, bind_params = {}, bind_keys = {}, *value, joined_keys = {}, conditions = {};
phalcon_fetch_params(0, 2, 1, &expr, &values, &use_orwhere);
if (!use_orwhere) {
use_orwhere = &PHALCON_GLOBAL(z_false);
}
if (Z_TYPE_P(values) != IS_ARRAY) {
PHALCON_THROW_EXCEPTION_STR(phalcon_db_builder_exception_ce, "Values must be an array");
return;
}
phalcon_read_property(&hidden_param, getThis(), SL("_hiddenParamNumber"), PH_NOISY|PH_READONLY);
array_init(&bind_params);
array_init(&bind_keys);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(values), value) {
zval key = {}, query_key = {};
/**
* Key with auto bind-params
*/
PHALCON_CONCAT_SV(&key, "phi", &hidden_param);
PHALCON_CONCAT_SVS(&query_key, ":", &key, ":");
phalcon_array_append(&bind_keys, &query_key, 0);
phalcon_array_update(&bind_params, &key, value, PH_COPY);
zval_ptr_dtor(&key);
phalcon_increment(&hidden_param);
} ZEND_HASH_FOREACH_END();
phalcon_fast_join_str(&joined_keys, SL(", "), &bind_keys);
zval_ptr_dtor(&bind_keys);
/**
* Create a standard IN condition with bind params
*/
PHALCON_CONCAT_VSVS(&conditions, expr, " NOT IN (", &joined_keys, ")");
zval_ptr_dtor(&joined_keys);
/**
* Append the IN to the current conditions using and 'and'
*/
if (zend_is_true(use_orwhere)) {
PHALCON_CALL_METHOD(NULL, getThis(), "orwhere", &conditions, &bind_params);
} else {
PHALCON_CALL_METHOD(NULL, getThis(), "andwhere", &conditions, &bind_params);
}
zval_ptr_dtor(&conditions);
zval_ptr_dtor(&bind_params);
phalcon_update_property(getThis(), SL("_hiddenParamNumber"), &hidden_param);
RETURN_THIS();
}
| 30.650718 | 170 | 0.695676 | [
"object"
] |
9a637c455660a058bdab318e14a3dfe52cbc4fda | 4,831 | h | C | src/RcsCore/Rcs_distanceWM5.h | famura/Rcs | 4f8b997d2649a2cd7a1945ea079e07a71ee215fc | [
"BSD-3-Clause"
] | 37 | 2018-03-20T12:28:45.000Z | 2022-02-28T08:39:32.000Z | src/RcsCore/Rcs_distanceWM5.h | famura/Rcs | 4f8b997d2649a2cd7a1945ea079e07a71ee215fc | [
"BSD-3-Clause"
] | 19 | 2018-04-19T08:49:53.000Z | 2021-06-11T09:47:09.000Z | src/RcsCore/Rcs_distanceWM5.h | famura/Rcs | 4f8b997d2649a2cd7a1945ea079e07a71ee215fc | [
"BSD-3-Clause"
] | 15 | 2018-03-28T11:52:39.000Z | 2022-02-04T19:34:01.000Z | /*******************************************************************************
Copyright (c) 2017, Honda Research Institute Europe GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#ifndef RCS_DISTANCEWM5_H
#define RCS_DISTANCEWM5_H
#include "Rcs_HTr.h"
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \defgroup DistanceFunctions Distance functions
*/
/*!
* \brief Returns true if the query point lies within the convex polygon (2D)
* \param pt Query point
* \param polygon Polygon vertices in ordered counter-clockwise
* \param N Number of polygon vertices
* \return
*/
bool Rcs_containedPoint2DConvexPolygon2D(const double pt[2],
const double polygon[][2],
unsigned int N);
/*!
* \ingroup DistanceFunctions
* \brief Returns the distance and closest points between a point and a convex
* polygon
* \param pt Query Point
* \param polygon Polygon vertices in ordered counter-clockwise
* \param N Number of polygon vertices
* \param cp0 Will be set to pt (can be NULL)
* \param cp1 Set to closest point, if query point is outside the polygon
* (can be NULL)
* \return
*
* Distance is positive if point is outside the polygon and negative if
* inside.
*/
double Rcs_distancePoint2DConvexPolygon2D(const double pt[2],
const double polygon[][2],
unsigned int N,
double cp0[2],
double cp1[2]);
/*!
* \ingroup DistanceFunctions
* \brief Returns the distance between a 3D point and a 2D convex polygon
* \param pt Query point (3D)
* \param polygon Polygon vertices in ordered counter-clockwise (2D)
* \param N Number of polygon vertices
* \param A Reference frame of the polygon
* \param cp0 Will be set to pt (can be NULL)
* \param cp1 Set to closest point, if query point is outside the polygon
* (can be NULL)
* \return
*/
double Rcs_distancePoint3DConvexPolygon2D(const double pt[3],
const double polygon[][2],
unsigned int N,
const HTr* A,
double cp0[3],
double cp1[3]);
/*! \ingroup DistanceFunctions
* \brief Computes the intersection between two planes. The planes are
* defined by a plane point p and a plane normal n. The function
* returns false if no intersection line could be found. In this
* case, origin and direction are unchanged. If an intersection line
* was found, vector origin will be a point on the intersection line,
* and direction will be a normalized direction vector.
*/
bool Rcs_computePlanePlaneIntersection(const double p1[3],
const double n1[3],
const double p2[3],
const double n2[3],
double origin[3],
double direction[3]);
#ifdef __cplusplus
}
#endif
#endif // RCS_DISTANCEWM5_H
| 37.449612 | 80 | 0.619333 | [
"vector",
"3d"
] |
9a67fa3389096efaaf4850b5eca0d5c5a20361c3 | 16,362 | h | C | src/client/game.h | Sposito/otclient | d3e12b5d44a3f801b0b24fcf25dfd811929e6ba4 | [
"MIT"
] | 518 | 2015-01-10T18:09:26.000Z | 2022-03-27T11:41:33.000Z | src/client/game.h | Sposito/otclient | d3e12b5d44a3f801b0b24fcf25dfd811929e6ba4 | [
"MIT"
] | 504 | 2015-01-01T17:34:59.000Z | 2022-03-25T18:27:37.000Z | src/client/game.h | Sposito/otclient | d3e12b5d44a3f801b0b24fcf25dfd811929e6ba4 | [
"MIT"
] | 545 | 2015-01-08T09:37:10.000Z | 2022-03-05T00:57:50.000Z | /*
* Copyright (c) 2010-2020 OTClient <https://github.com/edubart/otclient>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef GAME_H
#define GAME_H
#include "declarations.h"
#include "item.h"
#include "animatedtext.h"
#include "effect.h"
#include "creature.h"
#include "container.h"
#include "protocolgame.h"
#include "localplayer.h"
#include "outfit.h"
#include <framework/core/timer.h>
#include <bitset>
struct UnjustifiedPoints {
bool operator==(const UnjustifiedPoints& other) {
return killsDay == other.killsDay &&
killsDayRemaining == other.killsDayRemaining &&
killsWeek == other.killsWeek &&
killsWeekRemaining == other.killsWeekRemaining &&
killsMonth == other.killsMonth &&
killsMonthRemaining == other.killsMonthRemaining &&
skullTime == other.skullTime;
}
uint8 killsDay;
uint8 killsDayRemaining;
uint8 killsWeek;
uint8 killsWeekRemaining;
uint8 killsMonth;
uint8 killsMonthRemaining;
uint8 skullTime;
};
typedef std::tuple<std::string, uint, std::string, int, bool> Vip;
//@bindsingleton g_game
class Game
{
public:
Game();
void init();
void terminate();
private:
void resetGameStates();
protected:
void processConnectionError(const boost::system::error_code& ec);
void processDisconnect();
void processPing();
void processPingBack();
void processUpdateNeeded(const std::string& signature);
void processLoginError(const std::string& error);
void processLoginAdvice(const std::string& message);
void processLoginWait(const std::string& message, int time);
void processLoginToken(bool unknown);
void processLogin();
void processPendingGame();
void processEnterGame();
void processGameStart();
void processGameEnd();
void processDeath(int deathType, int penality);
void processGMActions(const std::vector<uint8>& actions);
void processInventoryChange(int slot, const ItemPtr& item);
void processAttackCancel(uint seq);
void processWalkCancel(Otc::Direction direction);
void processPlayerHelpers(int helpers);
void processPlayerModes(Otc::FightModes fightMode, Otc::ChaseModes chaseMode, bool safeMode, Otc::PVPModes pvpMode);
// message related
void processTextMessage(Otc::MessageMode mode, const std::string& text);
void processTalk(const std::string& name, int level, Otc::MessageMode mode, const std::string& text, int channelId, const Position& pos);
// container related
void processOpenContainer(int containerId, const ItemPtr& containerItem, const std::string& name, int capacity, bool hasParent, const std::vector<ItemPtr>& items, bool isUnlocked, bool hasPages, int containerSize, int firstIndex);
void processCloseContainer(int containerId);
void processContainerAddItem(int containerId, const ItemPtr& item, int slot);
void processContainerUpdateItem(int containerId, int slot, const ItemPtr& item);
void processContainerRemoveItem(int containerId, int slot, const ItemPtr& lastItem);
// channel related
void processChannelList(const std::vector<std::tuple<int, std::string> >& channelList);
void processOpenChannel(int channelId, const std::string& name);
void processOpenPrivateChannel(const std::string& name);
void processOpenOwnPrivateChannel(int channelId, const std::string& name);
void processCloseChannel(int channelId);
// rule violations
void processRuleViolationChannel(int channelId);
void processRuleViolationRemove(const std::string& name);
void processRuleViolationCancel(const std::string& name);
void processRuleViolationLock();
// vip related
void processVipAdd(uint id, const std::string& name, uint status, const std::string& description, int iconId, bool notifyLogin);
void processVipStateChange(uint id, uint status);
// tutorial hint
void processTutorialHint(int id);
void processAddAutomapFlag(const Position& pos, int icon, const std::string& message);
void processRemoveAutomapFlag(const Position& pos, int icon, const std::string& message);
// outfit
void processOpenOutfitWindow(const Outfit& currentOutfit, const std::vector<std::tuple<int, std::string, int> >& outfitList,
const std::vector<std::tuple<int, std::string> >& mountList);
// npc trade
void processOpenNpcTrade(const std::vector<std::tuple<ItemPtr, std::string, int, int, int> >& items);
void processPlayerGoods(int money, const std::vector<std::tuple<ItemPtr, int> >& goods);
void processCloseNpcTrade();
// player trade
void processOwnTrade(const std::string& name, const std::vector<ItemPtr>& items);
void processCounterTrade(const std::string& name, const std::vector<ItemPtr>& items);
void processCloseTrade();
// edit text/list
void processEditText(uint id, int itemId, int maxLength, const std::string& text, const std::string& writer, const std::string& date);
void processEditList(uint id, int doorId, const std::string& text);
// questlog
void processQuestLog(const std::vector<std::tuple<int, std::string, bool> >& questList);
void processQuestLine(int questId, const std::vector<std::tuple<std::string, std::string> >& questMissions);
// modal dialogs >= 970
void processModalDialog(uint32 id, std::string title, std::string message, std::vector<std::tuple<int, std::string> > buttonList, int enterButton, int escapeButton, std::vector<std::tuple<int, std::string> > choiceList, bool priority);
friend class ProtocolGame;
friend class Map;
public:
// login related
void loginWorld(const std::string& account, const std::string& password, const std::string& worldName, const std::string& worldHost, int worldPort, const std::string& characterName, const std::string& authenticatorToken, const std::string& sessionKey);
void cancelLogin();
void forceLogout();
void safeLogout();
// walk related
bool walk(Otc::Direction direction, bool dash = false);
bool dashWalk(Otc::Direction direction);
void autoWalk(std::vector<Otc::Direction> dirs);
void forceWalk(Otc::Direction direction);
void turn(Otc::Direction direction);
void stop();
// item related
void look(const ThingPtr& thing, bool isBattleList = false);
void move(const ThingPtr &thing, const Position& toPos, int count);
void moveToParentContainer(const ThingPtr& thing, int count);
void rotate(const ThingPtr& thing);
void use(const ThingPtr& thing);
void useWith(const ItemPtr& item, const ThingPtr& toThing);
void useInventoryItem(int itemId);
void useInventoryItemWith(int itemId, const ThingPtr& toThing);
ItemPtr findItemInContainers(uint itemId, int subType);
// container related
int open(const ItemPtr& item, const ContainerPtr& previousContainer);
void openParent(const ContainerPtr& container);
void close(const ContainerPtr& container);
void refreshContainer(const ContainerPtr& container);
// attack/follow related
void attack(CreaturePtr creature);
void cancelAttack() { attack(nullptr); }
void follow(CreaturePtr creature);
void cancelFollow() { follow(nullptr); }
void cancelAttackAndFollow();
// talk related
void talk(const std::string& message);
void talkChannel(Otc::MessageMode mode, int channelId, const std::string& message);
void talkPrivate(Otc::MessageMode mode, const std::string& receiver, const std::string& message);
// channel related
void openPrivateChannel(const std::string& receiver);
void requestChannels();
void joinChannel(int channelId);
void leaveChannel(int channelId);
void closeNpcChannel();
void openOwnChannel();
void inviteToOwnChannel(const std::string& name);
void excludeFromOwnChannel(const std::string& name);
// party related
void partyInvite(int creatureId);
void partyJoin(int creatureId);
void partyRevokeInvitation(int creatureId);
void partyPassLeadership(int creatureId);
void partyLeave();
void partyShareExperience(bool active);
// outfit related
void requestOutfit();
void changeOutfit(const Outfit& outfit);
// vip related
void addVip(const std::string& name);
void removeVip(int playerId);
void editVip(int playerId, const std::string& description, int iconId, bool notifyLogin);
// fight modes related
void setChaseMode(Otc::ChaseModes chaseMode);
void setFightMode(Otc::FightModes fightMode);
void setSafeFight(bool on);
void setPVPMode(Otc::PVPModes pvpMode);
Otc::ChaseModes getChaseMode() { return m_chaseMode; }
Otc::FightModes getFightMode() { return m_fightMode; }
bool isSafeFight() { return m_safeFight; }
Otc::PVPModes getPVPMode() { return m_pvpMode; }
// pvp related
void setUnjustifiedPoints(UnjustifiedPoints unjustifiedPoints);
UnjustifiedPoints getUnjustifiedPoints() { return m_unjustifiedPoints; };
void setOpenPvpSituations(int openPvpSituations);
int getOpenPvpSituations() { return m_openPvpSituations; }
// npc trade related
void inspectNpcTrade(const ItemPtr& item);
void buyItem(const ItemPtr& item, int amount, bool ignoreCapacity, bool buyWithBackpack);
void sellItem(const ItemPtr& item, int amount, bool ignoreEquipped);
void closeNpcTrade();
// player trade related
void requestTrade(const ItemPtr& item, const CreaturePtr& creature);
void inspectTrade(bool counterOffer, int index);
void acceptTrade();
void rejectTrade();
// house window and editable items related
void editText(uint id, const std::string& text);
void editList(uint id, int doorId, const std::string& text);
// rule violations (only gms)
void openRuleViolation(const std::string& reporter);
void closeRuleViolation(const std::string& reporter);
void cancelRuleViolation();
// reports
void reportBug(const std::string& comment);
void reportRuleViolation(const std::string& target, int reason, int action, const std::string& comment, const std::string& statement, int statementId, bool ipBanishment);
void debugReport(const std::string& a, const std::string& b, const std::string& c, const std::string& d);
// questlog related
void requestQuestLog();
void requestQuestLine(int questId);
// 870 only
void equipItem(const ItemPtr& item);
void mount(bool mount);
// 910 only
void requestItemInfo(const ItemPtr& item, int index);
// >= 970 modal dialog
void answerModalDialog(uint32 dialog, int button, int choice);
// >= 984 browse field
void browseField(const Position& position);
void seekInContainer(int cid, int index);
// >= 1080 ingame store
void buyStoreOffer(int offerId, int productType, const std::string& name = "");
void requestTransactionHistory(int page, int entriesPerPage);
void requestStoreOffers(const std::string& categoryName, int serviceType = 0);
void openStore(int serviceType = 0, const std::string& category = "");
void transferCoins(const std::string& recipient, int amount);
void openTransactionHistory(int entriesPerPage);
//void reportRuleViolation2();
void ping();
void setPingDelay(int delay) { m_pingDelay = delay; }
// otclient only
void changeMapAwareRange(int xrange, int yrange);
// dynamic support for game features
void enableFeature(Otc::GameFeature feature) { m_features.set(feature, true); }
void disableFeature(Otc::GameFeature feature) { m_features.set(feature, false); }
void setFeature(Otc::GameFeature feature, bool enabled) { m_features.set(feature, enabled); }
bool getFeature(Otc::GameFeature feature) { return m_features.test(feature); }
void setProtocolVersion(int version);
int getProtocolVersion() { return m_protocolVersion; }
void setClientVersion(int version);
int getClientVersion() { return m_clientVersion; }
void setCustomOs(int os) { m_clientCustomOs = os; }
int getOs();
bool canPerformGameAction();
bool checkBotProtection();
bool isOnline() { return m_online; }
bool isLogging() { return !m_online && m_protocolGame; }
bool isDead() { return m_dead; }
bool isAttacking() { return !!m_attackingCreature && !m_attackingCreature->isRemoved(); }
bool isFollowing() { return !!m_followingCreature && !m_followingCreature->isRemoved(); }
bool isConnectionOk() { return m_protocolGame && m_protocolGame->getElapsedTicksSinceLastRead() < 5000; }
int getPing() { return m_ping >= 0 ? std::max<int>(m_ping, m_pingTimer.elapsed_millis()) : -1; }
ContainerPtr getContainer(int index) { return m_containers[index]; }
std::map<int, ContainerPtr> getContainers() { return m_containers; }
std::map<int, Vip> getVips() { return m_vips; }
CreaturePtr getAttackingCreature() { return m_attackingCreature; }
CreaturePtr getFollowingCreature() { return m_followingCreature; }
void setServerBeat(int beat) { m_serverBeat = beat; }
int getServerBeat() { return m_serverBeat; }
void setCanReportBugs(bool enable) { m_canReportBugs = enable; }
bool canReportBugs() { return m_canReportBugs; }
void setExpertPvpMode(bool enable) { m_expertPvpMode = enable; }
bool getExpertPvpMode() { return m_expertPvpMode; }
LocalPlayerPtr getLocalPlayer() { return m_localPlayer; }
ProtocolGamePtr getProtocolGame() { return m_protocolGame; }
std::string getCharacterName() { return m_characterName; }
std::string getWorldName() { return m_worldName; }
std::vector<uint8> getGMActions() { return m_gmActions; }
bool isGM() { return !m_gmActions.empty(); }
Otc::Direction getLastWalkDir() { return m_lastWalkDir; }
std::string formatCreatureName(const std::string &name);
int findEmptyContainerId();
protected:
void enableBotCall() { m_denyBotCall = false; }
void disableBotCall() { m_denyBotCall = true; }
private:
void setAttackingCreature(const CreaturePtr& creature);
void setFollowingCreature(const CreaturePtr& creature);
LocalPlayerPtr m_localPlayer;
CreaturePtr m_attackingCreature;
CreaturePtr m_followingCreature;
ProtocolGamePtr m_protocolGame;
std::map<int, ContainerPtr> m_containers;
std::map<int, Vip> m_vips;
bool m_online;
bool m_denyBotCall;
bool m_dead;
bool m_expertPvpMode;
int m_serverBeat;
ticks_t m_ping;
uint m_pingSent;
uint m_pingReceived;
stdext::timer m_pingTimer;
Timer m_dashTimer;
uint m_seq;
int m_pingDelay;
Otc::FightModes m_fightMode;
Otc::ChaseModes m_chaseMode;
Otc::PVPModes m_pvpMode;
Otc::Direction m_lastWalkDir;
UnjustifiedPoints m_unjustifiedPoints;
int m_openPvpSituations;
bool m_safeFight;
bool m_canReportBugs;
std::vector<uint8> m_gmActions;
std::string m_characterName;
std::string m_worldName;
std::bitset<Otc::LastGameFeature> m_features;
ScheduledEventPtr m_pingEvent;
ScheduledEventPtr m_walkEvent;
ScheduledEventPtr m_checkConnectionEvent;
bool m_connectionFailWarned;
int m_protocolVersion;
int m_clientVersion;
std::string m_clientSignature;
int m_clientCustomOs;
};
extern Game g_game;
#endif
| 40.300493 | 256 | 0.721489 | [
"vector"
] |
9a6ab128fd99869c8a4f44740dedda158096b4e0 | 4,370 | h | C | VisualizationBase/src/declarative/NodeItemWrapperFormElement.h | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | VisualizationBase/src/declarative/NodeItemWrapperFormElement.h | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | VisualizationBase/src/declarative/NodeItemWrapperFormElement.h | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#pragma once
#include "ItemWrapperFormElement.h"
#include "ModelBase/src/nodes/Node.h"
#include "../renderer/ModelRenderer.h"
namespace Visualization {
/**
* This is an item wrapper element, with a specifiable node to create the item with.
*/
template <class ParentType>
class NodeItemWrapperFormElement : public ItemWrapperFormElement<ParentType> {
FLUENT_ELEMENT_INTERFACE(NodeItemWrapperFormElement);
public:
using ChildItem = typename ItemWrapperFormElement<ParentType>::ChildItem;
using GetNodeFunction = std::function<Model::Node* (ParentType* v)>;
NodeItemWrapperFormElement(ChildItem item, GetNodeFunction nodeGetter);
NodeItemWrapperFormElement() = delete;
NodeItemWrapperFormElement(const NodeItemWrapperFormElement<ParentType>&) = default;
NodeItemWrapperFormElement<ParentType>& operator=(const NodeItemWrapperFormElement<ParentType>&) = delete;
virtual ~NodeItemWrapperFormElement() {};
virtual NodeItemWrapperFormElement<ParentType>* clone() const override;
virtual void synchronizeWithItem(Item* item) override;
/**
* Sets if a wrapped item is created, even if there is no node to \a create. It is false by default.
*/
NodeItemWrapperFormElement<ParentType>* setCreateIfNoNode(bool create);
private:
// Do not forget to update the copy constructor if adding new members.
GetNodeFunction nodeGetter_{};
bool createIfNoNode_{false};
};
template <class ParentType>
NodeItemWrapperFormElement<ParentType>::NodeItemWrapperFormElement(ChildItem item, GetNodeFunction nodeGetter)
: ItemWrapperFormElement<ParentType>{item}, nodeGetter_{nodeGetter}
{}
template <class ParentType>
NodeItemWrapperFormElement<ParentType>* NodeItemWrapperFormElement<ParentType>::clone() const
{
return new NodeItemWrapperFormElement<ParentType>(*this);
}
template <class ParentType>
void NodeItemWrapperFormElement<ParentType>::synchronizeWithItem(Item* item)
{
auto& childItem = (static_cast<ParentType*>(item))->*this->item();
auto node = nodeGetter_(static_cast<ParentType*>(item));
if(childItem && childItem->node() != node)
{
SAFE_DELETE_ITEM(childItem);
item->setUpdateNeeded(Item::StandardUpdate);
}
if(!childItem && (node || createIfNoNode_))
{
childItem = item->renderer()->render(item, node);
item->setUpdateNeeded(Item::StandardUpdate);
}
}
template <class ParentType>
inline NodeItemWrapperFormElement<ParentType>* NodeItemWrapperFormElement<ParentType>::setCreateIfNoNode(bool create)
{
createIfNoNode_ = create;
return this;
}
} /* namespace Visualization */
| 40.841121 | 120 | 0.729519 | [
"render",
"model"
] |
9a70b6f7f93650dfc46b5f00d092cdeedd2d028b | 6,189 | h | C | win/devkit/plug-ins/AbcBullet/MayaUtility.h | leegoonz/Maya-devkit | b81fe799b58e854e4ef16435426d60446e975871 | [
"ADSL"
] | 10 | 2018-03-30T16:09:02.000Z | 2021-12-07T07:29:19.000Z | win/devkit/plug-ins/AbcBullet/MayaUtility.h | leegoonz/Maya-devkit | b81fe799b58e854e4ef16435426d60446e975871 | [
"ADSL"
] | null | null | null | win/devkit/plug-ins/AbcBullet/MayaUtility.h | leegoonz/Maya-devkit | b81fe799b58e854e4ef16435426d60446e975871 | [
"ADSL"
] | 9 | 2018-06-02T09:18:49.000Z | 2021-12-20T09:24:35.000Z | //-*****************************************************************************
//
// Copyright (c) 2009-2012,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// 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 Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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.
//
//-*****************************************************************************
#ifndef _AlembicExport_MayaUtility_h_
#define _AlembicExport_MayaUtility_h_
#include "Foundation.h"
#include <Alembic/Abc/OArrayProperty.h>
#include <Alembic/Abc/OScalarProperty.h>
namespace util
{
struct mObjectCmp
{
bool operator()(const MObject& o1, const MObject& o2) const
{
return strcmp(MFnDependencyNode(o1).name().asChar(), MFnDependencyNode(o2).name().asChar()) < 0;
}
};
typedef std::map <MObject, MSelectionList, mObjectCmp> GetMembersMap;
struct cmpDag
{
bool operator()( const MDagPath& lhs, const MDagPath& rhs )
{
std::string name1(lhs.fullPathName().asChar());
std::string name2(rhs.fullPathName().asChar());
return (name1.compare(name2) < 0);
}
};
typedef std::set< MDagPath, cmpDag > ShapeSet;
inline MStatus isFloat(MString str, const MString & usage)
{
MStatus status = MS::kSuccess;
if (!str.isFloat())
{
MGlobal::displayInfo(usage);
status = MS::kFailure;
}
return status;
}
inline MStatus isUnsigned(MString str, const MString & usage)
{
MStatus status = MS::kSuccess;
if (!str.isUnsigned())
{
MGlobal::displayInfo(usage);
status = MS::kFailure;
}
return status;
}
// safely inverse a scale component
inline double inverseScale(double scale)
{
const double kScaleEpsilon = 1.0e-12;
if (scale < kScaleEpsilon && scale >= 0.0)
return 1.0 / kScaleEpsilon;
else if (scale > -kScaleEpsilon && scale < 0.0)
return 1.0 / -kScaleEpsilon;
else
return 1.0 / scale;
}
// seconds per frame
double spf();
bool isAncestorDescendentRelationship(const MDagPath & path1,
const MDagPath & path2);
// returns 0 if static, 1 if sampled, and 2 if a curve
int getSampledType(const MPlug& iPlug);
// 0 dont write, 1 write static 0, 2 write anim 0, 3 write anim 1
int getVisibilityType(const MPlug & iPlug);
// determines what order we do the rotation in, returns false if iOrder is
// kInvalid or kLast
bool getRotOrder(MTransformationMatrix::RotationOrder iOrder,
unsigned int & oXAxis, unsigned int & oYAxis, unsigned int & oZAxis);
// determine if a Maya Object is animated or not
// copy from mayapit code (MayaPit.h .cpp)
bool isAnimated(MObject & object, bool checkParent = false);
// determine if a Maya Object is intermediate
bool isIntermediate(const MObject & object);
// returns true for visible and lod invisible and not templated objects
bool isRenderable(const MObject & object);
// strip iDepth namespaces from the node name, go from taco:foo:bar to bar
// for iDepth > 1
MString stripNamespaces(const MString & iNodeName, unsigned int iDepth);
// returns the Help string for AbcExport
MString getHelpText();
} // namespace util
struct PlugAndObjScalar
{
MPlug plug;
MObject obj;
Alembic::Abc::OScalarProperty prop;
};
struct PlugAndObjArray
{
MPlug plug;
MObject obj;
Alembic::Abc::OArrayProperty prop;
};
struct JobArgs
{
JobArgs()
{
excludeInvisible = false;
filterEulerRotations = false;
noNormals = false;
stripNamespace = 0;
useSelectionList = false;
worldSpace = false;
writeVisibility = false;
writeUVs = false;
writeColorSets = false;
writeFaceSets = false;
verbose = false;
}
bool excludeInvisible;
bool filterEulerRotations;
bool noNormals;
unsigned int stripNamespace;
bool useSelectionList;
bool worldSpace;
bool writeVisibility;
bool writeUVs;
bool writeColorSets;
bool writeFaceSets;
bool verbose;
std::string melPerFrameCallback;
std::string melPostCallback;
std::string pythonPerFrameCallback;
std::string pythonPostCallback;
// to put into .arbGeomParam
std::vector< std::string > prefixFilters;
std::set< std::string > attribs;
// to put into .userProperties
std::vector< std::string > userPrefixFilters;
std::set< std::string > userAttribs;
util::ShapeSet dagPaths;
};
#endif // _AlembicExport_MayaUtility_h_
| 30.638614 | 109 | 0.662627 | [
"object",
"vector"
] |
9a7299f4073df7f50ab7444588999cd4ffdc0be7 | 29,543 | h | C | source/serializer/tmfile/tm2_format.h | ddzhao91/Tengine | 3930387025675c7f4fb336f64617b719bc036d50 | [
"Apache-2.0"
] | null | null | null | source/serializer/tmfile/tm2_format.h | ddzhao91/Tengine | 3930387025675c7f4fb336f64617b719bc036d50 | [
"Apache-2.0"
] | null | null | null | source/serializer/tmfile/tm2_format.h | ddzhao91/Tengine | 3930387025675c7f4fb336f64617b719bc036d50 | [
"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.
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author: jingyou@openailab.com
*/
#ifndef __TM2_FORMAT_H__
#define __TM2_FORMAT_H__
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
#define TM2_FILE_VER_MAIN 2
#define TM2_FILE_VER_SUB 0
#define TM2_FILE_VER_COMPILE 0
#define TM2_OP_VER 1
#define TM2_NOT_SET 0x00
/* Type define */
typedef uint32_t tm_uoffset_t; /* offset is 4-byte unsigned integer */
typedef uint32_t tm_size_t; /* size is 4-byte unsigned integer */
typedef uint8_t tm_bool_t; /* bool is 1-byte unsigned integer */
/* Operator strings */
#define TM2_OPSTR_ACCURACY "Accuracy"
#define TM2_OPSTR_BATCHNORMALIZATION "BatchNormalization"
#define TM2_OPSTR_BILINEARRESIZE "Resize"
#define TM2_OPSTR_CONCAT "Concat"
#define TM2_OPSTR_CONST "Const"
#define TM2_OPSTR_CONVOLUTION "Convolution"
#define TM2_OPSTR_DECONVOLUTION "Deconvolution"
#define TM2_OPSTR_DETECTIONOUTPUT "DetectionOutput"
#define TM2_OPSTR_DROPOUT "Dropout"
#define TM2_OPSTR_ELTWISE "Eltwise"
#define TM2_OPSTR_FLATTEN "Flatten"
#define TM2_OPSTR_FULLYCONNECTED "FullyConnected"
#define TM2_OPSTR_INPUTOP "InputOp"
#define TM2_OPSTR_LRN "LRN"
#define TM2_OPSTR_NORMALIZE "Normalize"
#define TM2_OPSTR_PERMUTE "Permute"
#define TM2_OPSTR_POOLING "Pooling"
#define TM2_OPSTR_PRELU "PReLU"
#define TM2_OPSTR_PRIORBOX "PriorBox"
#define TM2_OPSTR_REGION "Region"
#define TM2_OPSTR_RELU "ReLu"
#define TM2_OPSTR_RELU6 "ReLu6"
#define TM2_OPSTR_REORG "Reorg"
#define TM2_OPSTR_RESHAPE "Reshape"
#define TM2_OPSTR_ROIPOOLING "ROIPooling"
#define TM2_OPSTR_RPN "RPN"
#define TM2_OPSTR_SCALE "Scale"
#define TM2_OPSTR_SLICE "Slice"
#define TM2_OPSTR_SOFTMAX "Softmax"
#define TM2_OPSTR_SPLIT "Split"
#define TM2_OPSTR_DETECTIONPOSTPROCESS "DetectionPostProcess"
#define TM2_OPSTR_GEMM "Gemm"
#define TM2_OPSTR_GENERIC "Generic"
#define TM2_OPSTR_LOGISTIC "Logistic"
#define TM2_OPSTR_LSTM "LSTM"
#define TM2_OPSTR_RNN "RNN"
#define TM2_OPSTR_TANH "Tanh"
#define TM2_OPSTR_SIGMOID "Sigmoid"
#define TM2_OPSTR_SQUEEZE "Squeeze"
#define TM2_OPSTR_PAD "Pad"
#define TM2_OPSTR_STRIDEDSLICE "StridedSlice"
#define TM2_OPSTR_REDUCTION "Reduction"
#define TM2_OPSTR_ARGMAX "ArgMax"
#define TM2_OPSTR_ARGMIN "ArgMin"
#define TM2_OPSTR_TOPKV2 "TopKV2"
#define TM2_OPSTR_MAX "Maximum"
#define TM2_OPSTR_MIN "Minimum"
#define TM2_OPSTR_ADDN "Addn"
#define TM2_OPSTR_SWAPAXIS "SwapAxis"
#define TM2_OPSTR_GRU "GRU"
#define TM2_OPSTR_FUSEDBNSCALERELU "Fused.BNScaleReLu"
#define TM2_OPSTR_UPSAMPLE "Upsample"
#define TM2_OPSTR_SHUFFLECHANNEL "ShuffleChannel"
#define TM2_OPSTR_RESIZE "Resize"
#define TM2_OPSTR_SPACETOBATCHND "SpaceToBatchND"
#define TM2_OPSTR_BATCHTOSPACEND "BatchToSpaceND"
#define TM2_OPSTR_CROP "Crop"
#define TM2_OPSTR_PSROIPOOLING "Psroipooling"
#define TM2_OPSTR_ROIALIGN "Roialign"
#define TM2_OPSTR_EXPANDDIMS "Expanddims"
#define TM2_OPSTR_UNARY "Unary"
#define TM2_OPSTR_BIAS "Bias"
#define TM2_OPSTR_NOOP "Noop"
#define TM2_OPSTR_THRESHOLD "Threshold"
#define TM2_OPSTR_HARDSIGMOID "Hardsigmoid"
#define TM2_OPSTR_EMBED "Embedding"
#define TM2_OPSTR_INSTANCENORM "InstanceNorm"
#define TM2_OPSTR_MVN "MVN"
#define TM2_OPSTR_ABSVAL "Absval"
#define TM2_OPSTR_CAST "Cast"
#define TM2_OPSTR_HARDSWISH "HardSwish"
#define TM2_OPSTR_INTERP "Interp"
#define TM2_OPSTR_SELU "Selu"
#define TM2_OPSTR_ELU "Elu"
#define TM2_OPSTR_BROADMUL "BroadMul"
#define TM2_OPSTR_LOGICAL "Logical"
#define TM2_OPSTR_GATHER "Gather"
#define TM2_OPSTR_TRANSPOSE "Transpose"
#define TM2_OPSTR_REVERSE "Reverse"
#define TM2_OPSTR_COMPARISON "Comparison"
#define TM2_OPSTR_SPACETODEPTH "SpaceToDepth"
#define TM2_OPSTR_DEPTHTOSPACE "DepthToSpace"
#define TM2_OPSTR_SQUAREDDIFFERENCE "SquaredDifference"
#define TM2_OPSTR_SPARSETODENSE "SparseToDense"
#define TM2_OPSTR_CEIL "Ceil"
#define TM2_OPSTR_ROUND "Round"
#define TM2_OPSTR_ZEROSLIKE "ZerosLike"
#define TM2_OPSTR_CLIP "Clip"
#define TM2_OPSTR_UNSQUEEZE "Unsqueeze"
#define TM2_OPSTR_REDUCEL2 "ReduceL2"
#define TM2_OPSTR_MEAN "Mean"
#define TM2_OPSTR_MATMUL "MatMul"
#define TM2_OPSTR_MISH "Mish"
#define TM2_OPSTR_L2NORMALIZATION "L2Normalization"
#define TM2_OPSTR_RELU1 "ReLU1"
#define TM2_OPSTR_SHAPE "Shape"
#define TM2_OPSTR_LOGSOFTMAX "LogSoftmax"
#define TM2_OPSTR_SCATTER "Scatter"
#define TM2_OPSTR_TILE "Tile"
#define TM2_OPSTR_L2POOL "L2Pool"
/* Operator types */
#define TM2_OPTYPE_ACCURACY 0 /* No Param */
#define TM2_OPTYPE_BATCHNORMALIZATION 1 /* TM2_BatchNormParam */
#define TM2_OPTYPE_BILINEARRESIZE 2 /* TM2_ResizeParam */
#define TM2_OPTYPE_CONCAT 3 /* TM2_ConcatParam */
#define TM2_OPTYPE_CONST 4 /* No Param */
#define TM2_OPTYPE_CONVOLUTION 5 /* TM2_ConvParam */
#define TM2_OPTYPE_DECONVOLUTION 6 /* TM2_DeconvParam */
#define TM2_OPTYPE_DETECTIONOUTPUT 7 /* TM2_DetectionOutputParam */
#define TM2_OPTYPE_DROPOUT 8 /* No Param */
#define TM2_OPTYPE_ELTWISE 9 /* TM2_EltwiseParam */
#define TM2_OPTYPE_FLATTEN 10 /* TM2_FlattenParam */
#define TM2_OPTYPE_FULLYCONNECTED 11 /* TM2_FCParam */
#define TM2_OPTYPE_INPUTOP 12 /* No Param */
#define TM2_OPTYPE_LRN 13 /* TM2_LRNParam */
#define TM2_OPTYPE_NORMALIZE 14 /* TM2_NormalizeParam */
#define TM2_OPTYPE_PERMUTE 15 /* TM2_PermuteParam */
#define TM2_OPTYPE_POOLING 16 /* TM2_PoolParam */
#define TM2_OPTYPE_PRELU 17 /* No Param */
#define TM2_OPTYPE_PRIORBOX 18 /* TM2_PriorBoxParam */
#define TM2_OPTYPE_REGION 19 /* TM2_RegionParam */
#define TM2_OPTYPE_RELU 20 /* TM2_ReLuParam */
#define TM2_OPTYPE_RELU6 21 /* No Param */
#define TM2_OPTYPE_REORG 22 /* TM2_ReorgParam */
#define TM2_OPTYPE_RESHAPE 23 /* TM2_ReshapeParam */
#define TM2_OPTYPE_ROIPOOLING 24 /* TM2_ROIPoolingParam */
#define TM2_OPTYPE_RPN 25 /* TM2_RPNParam */
#define TM2_OPTYPE_SCALE 26 /* TM2_ScaleParam */
#define TM2_OPTYPE_SLICE 27 /* TM2_SliceParam */
#define TM2_OPTYPE_SOFTMAX 28 /* TM2_SoftmaxParam */
#define TM2_OPTYPE_SPLIT 29 /* No Param */
#define TM2_OPTYPE_DETECTIONPOSTPROCESS 30 /* TM2_DetectionPostProcessParam */
#define TM2_OPTYPE_GEMM 31 /* TM2_GemmParam */
#define TM2_OPTYPE_GENERIC 32 /* TM2_GenericParam */
#define TM2_OPTYPE_LOGISTIC 33 /* No Param */
#define TM2_OPTYPE_LSTM 34 /* TM2_LstmParam */
#define TM2_OPTYPE_RNN 35 /* TM2_RnnParam */
#define TM2_OPTYPE_TANH 36 /* No Param */
#define TM2_OPTYPE_SIGMOID 37 /* No Param */
#define TM2_OPTYPE_SQUEEZE 38 /* TM2_SqueezeParam */
#define TM2_OPTYPE_FUSEDBNSCALERELU 39 /* No Param */
#define TM2_OPTYPE_PAD 40 /* TM2_PadParam */
#define TM2_OPTYPE_STRIDEDSLICE 41 /* TM2_StrideSliceParam */
#define TM2_OPTYPE_ARGMAX 42 /* TM2_ArgmaxParam */
#define TM2_OPTYPE_ARGMIN 43 /* TM2_ArgminParam */
#define TM2_OPTYPE_TOPKV2 44 /* TM2_TopkV2Param */
#define TM2_OPTYPE_REDUCTION 45 /* TM2_ReductionParam */
#define TM2_OPTYPE_MAX 46 /* No Param */
#define TM2_OPTYPE_MIN 47 /* No Param */
#define TM2_OPTYPE_GRU 48 /* TM2_GruParam */
#define TM2_OPTYPE_ADDN 49 /* TM2_AddNParam */
#define TM2_OPTYPE_SWAPAXIS 50 /* TM2_SwapAixsParam */
#define TM2_OPTYPE_UPSAMPLE 51 /* TM2_UpsampleParam */
#define TM2_OPTYPE_SPACETOBATCHND 52
#define TM2_OPTYPE_BATCHTOSPACEND 53
#define TM2_OPTYPE_RESIZE 54
#define TM2_OPTYPE_SHUFFLECHANNEL 55 /* TM2_ShuffleChannelPara */
#define TM2_OPTYPE_CROP 56 /* TM2_CropParam */
#define TM2_OPTYPE_ROIALIGN 57
#define TM2_OPTYPE_PSROIPOOLING 58
#define TM2_OPTYPE_UNARY 59
#define TM2_OPTYPE_EXPANDDIMS 60
#define TM2_OPTYPE_BIAS 61
#define TM2_OPTYPE_NOOP 62
#define TM2_OPTYPE_THRESHOLD 63
#define TM2_OPTYPE_HARDSIGMOID 64
#define TM2_OPTYPE_EMBED 65
#define TM2_OPTYPE_INSTANCENORM 66
#define TM2_OPTYPE_MVN 67
#define TM2_OPTYPE_ABSVAL 68
#define TM2_OPTYPE_CAST 69
#define TM2_OPTYPE_HARDSWISH 70
#define TM2_OPTYPE_INTERP 71
#define TM2_OPTYPE_SELU 72
#define TM2_OPTYPE_ELU 73
#define TM2_OPTYPE_BROADMUL 74
#define TM2_OPTYPE_LOGICAL 75
#define TM2_OPTYPE_GATHER 76
#define TM2_OPTYPE_TRANSPOSE 77
#define TM2_OPTYPE_COMPARISON 78
#define TM2_OPTYPE_SPACETODEPTH 79
#define TM2_OPTYPE_DEPTHTOSPACE 80
#define TM2_OPTYPE_REVERSE 81
#define TM2_OPTYPE_SPARSETODENSE 82
#define TM2_OPTYPE_CEIL 83
#define TM2_OPTYPE_SQUAREDDIFFERENCE 84
#define TM2_OPTYPE_ROUND 85
#define TM2_OPTYPE_ZEROSLIKE 86
#define TM2_OPTYPE_CLIP 87
#define TM2_OPTYPE_UNSQUEEZE 88
#define TM2_OPTYPE_REDUCEL2 89
#define TM2_OPTYPE_MEAN 90
#define TM2_OPTYPE_EXPAND 91
#define TM2_OPTYPE_MATMUL 92
#define TM2_OPTYPE_SCATTER 93
#define TM2_OPTYPE_SHAPE 94
#define TM2_OPTYPE_WHERE 95
#define TM2_OPTYPE_TILE 96
#define TM2_OPTYPE_MISH 97
#define TM2_OPTYPE_L2POOL 98
#define TM2_OPTYPE_LOGSOFTMAX 99
#define TM2_OPTYPE_RELU1 100
#define TM2_OPTYPE_L2NORMALIZATION 101
#define TM2_OPTYPE_NUM 102
/* --------------------- -------- TM objects -------------------------------- */
typedef struct
{
uint16_t ver_main; /* main version of Tengine model file format */
uint16_t ver_sub; /* sub version of Tengine model file format */
uint16_t ver_compile; /* compile version of Tengine model file format */
tm_uoffset_t offset_root; /* offset of root table (TM2_Model) */
} TM2_Header;
/* Root table of Tengine model */
typedef struct
{
int32_t orig_format; /* format of original model */
int32_t sub_format; /* sub format for DLA model */
tm_uoffset_t offset_vo_subgraphs; /* offset of TM2_Vector_offsets <offsets of subgraphs> */
tm_uoffset_t offset_s_mname; /* offset of string <model name> */
} TM2_Model;
/* Only 1 subgraph is supported currently */
typedef struct
{
uint32_t subgraph_id; /* subgraph id */
int32_t graph_layout; /* actual data layout */
int32_t model_layout; /* data layout of original model */
tm_uoffset_t offset_vi_input_indices; /* offset of TM2_Vector_indices <indices of input nodes> */
tm_uoffset_t offset_vi_output_indices; /* offset of TM2_Vector_indices <indices of output nodes> */
tm_uoffset_t offset_vo_seq_nodes; /* offset of TM2_Vector_offsets <nodes> */
tm_uoffset_t offset_vo_tensors; /* offset of TM2_Vector_offsets <tensors> */
tm_uoffset_t offset_vo_buffers; /* offset of TM2_Vector_offsets <buffers> */
tm_uoffset_t offset_s_sname; /* offset of string <subgraph name> */
tm_uoffset_t offset_vo_sub_info; /* offset of TM2_Vector_offsets <sub graph infomation> */
} TM2_Subgraph;
typedef struct
{
uint32_t subgraph_id; /* sub graph idx */
uint32_t input_wait_count; /* input wait count */
int32_t data_type; /* FP32 FP16 U8 INT8 */
tm_uoffset_t offset_vi_node_list; /* offset of TM2_Vector_indices <indices of node list> */
tm_uoffset_t offset_vi_input_tensor; /* offset of TM2_Vector_indices <indices of input node> */
tm_uoffset_t offset_vi_output_tensor; /* offset of TM2_Vector_indices <indices of output node> */
tm_uoffset_t offset_s_device_name; /* offset of string <device name> */
} TM2_Sub_Info;
typedef struct
{
tm_uoffset_t offset_s_attrname; /* offset of string <attr name> */
tm_uoffset_t offset_s_attrval; /* offset of string <attr value> */
int32_t attr_type;
} TM2_Attr;
typedef struct
{
uint32_t node_id; /* node id */
tm_uoffset_t offset_vi_input_tensors; /* offset of TM2_Vector_indices <indices of input tensors> */
tm_uoffset_t offset_vi_output_tensors; /* offset of TM2_Vector_indices <indices of output tensors> */
tm_uoffset_t offset_t_operator; /* offset of table <operator> */
tm_uoffset_t offset_s_nname; /* offset of string <node name> */
tm_uoffset_t offset_vo_attrs; /* offset of TM2_Vector_offsets <attrs> */
tm_bool_t dynamic_shape;
} TM2_Node;
typedef struct
{
uint32_t op_ver; /* version of operator */
uint32_t operator_type; /* operator type */
tm_uoffset_t offset_t_param; /* offset of table <operator param> */
} TM2_Operator;
typedef struct
{
int32_t zero_point;
float scale;
int32_t width;
} TM2_QuantParam;
typedef struct
{
uint32_t tensor_id;
uint32_t buffer_id;
tm_uoffset_t offset_vd_dims; /* offset of TM2_Vector_dims <dims> */
tm_uoffset_t offset_s_tname; /* offset of string <tensor name> */
tm_uoffset_t offect_vo_quantparams; /* offset of TM2_Vector_offsets <quant params> */
int32_t layout;
int32_t type;
int32_t data_type;
} TM2_Tensor;
typedef struct
{
tm_size_t size; /* buffer size */
tm_uoffset_t offset_data; /* offset of buffer data */
} TM2_Buffer;
typedef struct
{
tm_size_t size; /* string size */
tm_uoffset_t offset_data; /* offset of string data */
} TM2_String;
/* ------------------------ ------- Vectors --------------------------------- */
typedef struct
{
tm_size_t v_num; /* number of vector elements */
tm_uoffset_t offsets[0];
} TM2_Vector_offsets;
typedef struct
{
tm_size_t v_num; /* number of vector elements */
uint32_t indices[0];
} TM2_Vector_indices;
typedef struct
{
tm_size_t v_num; /* number of vector elements */
int32_t dims[0];
} TM2_Vector_dims;
typedef struct
{
tm_size_t v_num; /* number of vector elements */
float data[0];
} TM2_Vector_floats;
typedef struct
{
tm_size_t v_num; /* number of vector elements */
float data[0][4]; /* x0, y0, x1, y1 */
} TM2_Vector_anchors;
/* -------------------- ------- Operator params ----------------------------- */
typedef struct
{
int32_t max_input_num;
int32_t max_output_num;
tm_uoffset_t offset_s_opname; /* offset of string <op name> */
} TM2_GenericParam;
typedef struct
{
float rescale_factor;
float eps;
int32_t caffe_flavor;
} TM2_BatchNormParam;
typedef struct
{
int32_t axis;
} TM2_ConcatParam;
typedef struct
{
int32_t kernel_h;
int32_t kernel_w;
int32_t stride_h;
int32_t stride_w;
int32_t dilation_h;
int32_t dilation_w;
int32_t input_channel;
int32_t output_channel;
int32_t group;
int32_t activation;
int32_t pad_h0; /* top padding rows */
int32_t pad_w0; /* left padding columns */
int32_t pad_h1; /* bottom padding rows */
int32_t pad_w1; /* right padding columns */
} TM2_ConvParam;
typedef struct
{
int32_t num_output;
int32_t kernel_h;
int32_t kernel_w;
int32_t stride_h;
int32_t stride_w;
int32_t pad_w0;
int32_t pad_h0;
int32_t pad_w1;
int32_t pad_h1;
int32_t dilation_h;
int32_t dilation_w;
int32_t group;
int32_t activation;
int32_t output_pad_h0;
int32_t output_pad_w0;
} TM2_DeconvParam;
typedef struct
{
int32_t num_classes;
int32_t keep_top_k;
int32_t nms_top_k;
float confidence_threshold;
float nms_threshold;
} TM2_DetectionOutputParam;
typedef struct
{
uint32_t type;
int32_t caffe_flavor;
float shift;
float power;
float scale;
} TM2_EltwiseParam;
typedef struct
{
int32_t num_output;
} TM2_FCParam;
typedef struct
{
int32_t axis;
int32_t end_axis;
} TM2_FlattenParam;
typedef struct
{
int32_t local_size;
float alpha;
float beta;
int32_t norm_region;
float k;
float bias;
tm_bool_t is_onnx;
} TM2_LRNParam;
typedef struct
{
int32_t across_spatial;
int32_t channel_shared;
} TM2_NormalizeParam;
typedef struct
{
int32_t flag;
int32_t order0;
int32_t order1;
int32_t order2;
int32_t order3;
} TM2_PermuteParam;
typedef struct
{
uint32_t alg;
int32_t kernel_h;
int32_t kernel_w;
int32_t stride_h;
int32_t stride_w;
int32_t global;
int32_t caffe_flavor;
int32_t pad_h0; /* top padding rows */
int32_t pad_w0; /* left padding columns */
int32_t pad_h1; /* bottom padding rows */
int32_t pad_w1; /* right padding columns */
} TM2_PoolParam;
typedef struct
{
tm_uoffset_t offset_vf_min_size; /* offset of TM2_Vector_floats <min_sizes> */
tm_uoffset_t offset_vf_max_size; /* offset of TM2_Vector_floats <max_sizes> */
tm_uoffset_t offset_vf_variance; /* offset of TM2_Vector_floats <variances> */
tm_uoffset_t offset_vf_aspect_ratio; /* offset of TM2_Vector_floats <aspect_ratios> */
int32_t flip;
int32_t clip;
int32_t img_size;
int32_t img_h;
int32_t img_w;
float step_w;
float step_h;
float offset;
int32_t num_priors;
int32_t out_dim;
} TM2_PriorBoxParam;
typedef struct
{
int32_t num_classes;
int32_t side;
int32_t num_box;
int32_t coords;
float confidence_threshold;
float nms_threshold;
tm_uoffset_t offset_vf_biases; /* offset of TM2_Vector_floats <biases> */
} TM2_RegionParam;
typedef struct
{
float negative_slope;
} TM2_ReLuParam;
typedef struct
{
int32_t stride;
} TM2_ReorgParam;
typedef struct
{
int32_t is_mxnet;
int32_t reverse;
tm_uoffset_t offset_re_shape;
} TM2_ReshapeParam;
typedef struct
{
float scale_x;
float scale_y;
int type;
} TM2_ResizeParam;
typedef struct
{
int32_t pooled_h;
int32_t pooled_w;
float spatial_scale;
} TM2_ROIPoolingParam;
typedef struct
{
tm_uoffset_t offset_vf_ratios; /* pointer to TM2_Vector_floats <ratios> */
tm_uoffset_t offset_vf_anchor_scales; /* pointer to TM2_Vector_floats <anchor_scales> */
int32_t feat_stride;
int32_t basesize;
int32_t min_size;
int32_t per_nms_topn;
int32_t post_nms_topn;
float nms_thresh;
tm_uoffset_t offset_va_anchors; /* offset of TM2_Vector_anchors <anchors> */
} TM2_RPNParam;
typedef struct
{
int32_t axis;
int32_t num_axes;
int32_t bias_term;
} TM2_ScaleParam;
typedef struct
{
int32_t axis;
tm_uoffset_t offset_vi_slice_points; /* offset of TM2_Vector_dims <slice_points> */
tm_uoffset_t offset_vi_begins; /* offset of TM2_Vector_dims <begins> */
tm_uoffset_t offset_vi_sizes; /* offset of TM2_Vector_dims <sizes> */
int32_t iscaffe;
int32_t ismxnet;
int32_t isonnx;
int32_t begin;
int32_t end;
} TM2_SliceParam;
typedef struct
{
int32_t axis;
} TM2_SoftmaxParam;
typedef struct
{
int32_t max_detections;
int32_t max_classes_per_detection;
float nms_score_threshold;
float nms_iou_threshold;
int32_t num_classes;
tm_uoffset_t offset_vf_scales; /* y_scale, x_scale, h_scale, w_scale */
} TM2_DetectionPostProcessParam;
typedef struct
{
float alpha;
float beta;
int32_t transA;
int32_t transB;
} TM2_GemmParam;
typedef struct
{
float forget_bias;
float clip;
int32_t output_len;
int32_t sequence_len;
int32_t input_size;
int32_t hidden_size;
int32_t cell_size;
int32_t has_peephole;
int32_t has_projection;
int32_t has_clip;
int32_t has_bias;
int32_t has_init_state;
int32_t forget_act;
int32_t input_act;
int32_t output_act;
int32_t cellin_act;
int32_t cellout_act;
int32_t mxnet_flag;
} TM2_LstmParam;
typedef struct
{
float clip;
int32_t output_len;
int32_t sequence_len;
int32_t input_size;
int32_t hidden_size;
int32_t has_clip;
int32_t has_bias;
int32_t has_init_state;
int32_t activation;
} TM2_RnnParam;
typedef struct
{
int32_t dim_0;
int32_t dim_1;
int32_t dim_2;
int32_t dim_3;
} TM2_SqueezeParam;
typedef struct
{
int32_t axis;
int32_t keepdims;
} TM2_ArgMaxParam;
typedef struct
{
int32_t axis;
int32_t keepdims;
} TM2_ArgMinParam;
typedef struct
{
int32_t k;
int32_t sorted;
} TM2_TopKV2Param;
typedef struct
{
int32_t begin_n;
int32_t end_n;
int32_t stride_n;
int32_t begin_c;
int32_t end_c;
int32_t stride_c;
int32_t begin_h;
int32_t end_h;
int32_t stride_h;
int32_t begin_w;
int32_t end_w;
int32_t stride_w;
} TM2_StridedSliceParam;
typedef struct
{
int32_t pad_n_0;
int32_t pad_n_1;
int32_t pad_c_0;
int32_t pad_c_1;
int32_t pad_h_0;
int32_t pad_h_1;
int32_t pad_w_0;
int32_t pad_w_1;
int32_t mode;
float value;
} TM2_PadParam;
typedef struct
{
int32_t dim_0;
int32_t dim_1;
int32_t dim_2;
int32_t dim_3;
int32_t type;
int32_t keepdim;
} TM2_ReductionParam;
typedef struct
{
float clip;
int32_t output_len;
int32_t sequence_len;
int32_t input_size;
int32_t hidden_size;
int32_t has_clip;
int32_t has_gate_bias;
int32_t has_candidate_bias;
int32_t has_init_state;
int32_t mxnet_flag;
} TM2_GRUParam;
typedef struct
{
int32_t axis;
} TM2_AddnParam;
typedef struct
{
int32_t dim_0;
int32_t dim_1;
} TM2_SwapAxisParam;
typedef struct
{
int32_t axis;
int32_t split_dim;
// int32_t squeeze_axis;
tm_bool_t is_caffe;
tm_bool_t is_onnx;
tm_uoffset_t offset_split_sizes;
} TM2_SplitParam;
typedef struct
{
float scale;
} TM2_UpsampleParam;
typedef struct
{
int group;
} TM2_ShuffleChannelParam;
typedef struct
{
int32_t dilation_x;
int32_t dilation_y;
int32_t pad_top;
int32_t pad_bottom;
int32_t pad_left;
int32_t pad_right;
} TM2_SpaceToBatchNDParam;
typedef struct
{
int32_t dilation_x;
int32_t dilation_y;
int32_t crop_top;
int32_t crop_bottom;
int32_t crop_left;
int32_t crop_right;
} TM2_BatchToSpaceNDParam;
typedef struct
{
int32_t num_args;
int32_t offset_c;
int32_t offset_h;
int32_t offset_w;
int32_t crop_h;
int32_t crop_w;
bool center_crop;
int32_t axis;
int32_t flag;
} TM2_CropParam;
typedef struct
{
int32_t pooled_width;
int32_t pooled_height;
float spatial_scale;
} TM2_RoialignParam;
typedef struct
{
int32_t pooled_w;
int32_t pooled_h;
float spatial_scale;
int32_t output_dim;
} TM2_PsroipoolingParam;
typedef struct
{
int32_t axis;
} TM2_ExpanddimsParam;
typedef struct
{
int32_t type;
} TM2_UnaryParam;
typedef struct
{
int32_t bias_size;
} TM2_BiasParam;
typedef struct
{
float threshold;
} TM2_ThresholdParam;
typedef struct
{
float alpha;
float beta;
} TM2_HardsigmoidParam;
typedef struct
{
int32_t num_output;
int32_t input_dim;
int32_t bias_term;
int32_t weight_data_size;
} TM2_EmbedParam;
typedef struct
{
float eps;
} TM2_InstanceNormParam;
typedef struct
{
int32_t across_channels;
int32_t normalize_variance;
float eps;
} TM2_MVNParam;
typedef struct
{
int32_t type_from;
int32_t type_to;
} TM2_CastParam;
typedef struct
{
float alpha;
float beta;
} TM2_HardSwishParam;
typedef struct
{
int32_t resize_type; // 1=nearest 2=bilinear 3=bicubic
float width_scale;
float height_scale;
int32_t output_width;
int32_t output_height;
} TM2_InterpParam;
typedef struct
{
float alpha;
float lambda;
} TM2_SeluParam;
typedef struct
{
float alpha;
} TM2_EluParam;
typedef struct
{
uint32_t type;
} TM2_LogicalParam;
typedef struct
{
int32_t axis;
int32_t indices_num;
tm_bool_t is_onnx;
} TM2_GatherParam;
typedef struct
{
tm_uoffset_t offset_tr_shape;
} TM2_TransposeParam;
typedef struct
{
int32_t type;
} TM2_ComparisonParam;
typedef struct
{
int block_size;
} TM2_SpaceToDepthParam;
typedef struct
{
int block_size;
} TM2_DepthToSpaceParam;
typedef struct
{
int output_shape_size0;
int output_shape_size1;
int default_value;
} TM2_SparseToDenseParam;
typedef struct
{
float max;
float min;
} TM2_ClipParam;
typedef struct
{
tm_uoffset_t offset_vi_axises;
} TM2_UnsqueezeParam;
typedef struct
{
int32_t axis;
int32_t keepdim;
} TM2_ReduceL2Param;
typedef struct
{
int32_t axis;
} TM2_LogSoftmaxParam;
typedef struct
{
int32_t axis;
tm_bool_t is_onnx;
} TM2_ScatterParam;
typedef struct
{
int32_t paddingType;
int32_t kernel_h;
int32_t kernel_w;
int32_t stride_h;
int32_t stride_w;
} TM2_L2PoolParam;
typedef struct
{
int32_t frame_flag;
int32_t reps_size;
tm_uoffset_t offset_reps;
} TM2_TileParam;
#ifdef __cplusplus
}
#endif
#endif
| 29.811302 | 105 | 0.618928 | [
"shape",
"vector",
"model"
] |
9a76080762140ae9de15803ffeac30cb2f9a6420 | 21,080 | h | C | libraries/nacl_sdk/pepper_49/toolchain/win_pnacl/include/clang/AST/ExternalASTSource.h | Enime-Project/mpv.js | 5d80165419a043ac61c29567c58fcae6af3e1f1b | [
"CC0-1.0"
] | 1 | 2022-01-11T11:12:00.000Z | 2022-01-11T11:12:00.000Z | libraries/nacl_sdk/pepper_49/toolchain/win_pnacl/include/clang/AST/ExternalASTSource.h | Enime-Project/mpv.js | 5d80165419a043ac61c29567c58fcae6af3e1f1b | [
"CC0-1.0"
] | null | null | null | libraries/nacl_sdk/pepper_49/toolchain/win_pnacl/include/clang/AST/ExternalASTSource.h | Enime-Project/mpv.js | 5d80165419a043ac61c29567c58fcae6af3e1f1b | [
"CC0-1.0"
] | null | null | null | //===--- ExternalASTSource.h - Abstract External AST Interface --*- C++ -*-===//
//
// 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 ExternalASTSource interface, which enables
// construction of AST nodes from some external source.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_EXTERNALASTSOURCE_H
#define LLVM_CLANG_AST_EXTERNALASTSOURCE_H
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclBase.h"
#include "llvm/ADT/DenseMap.h"
namespace clang {
class ASTConsumer;
class CXXBaseSpecifier;
class CXXCtorInitializer;
class DeclarationName;
class ExternalSemaSource; // layering violation required for downcasting
class FieldDecl;
class Module;
class NamedDecl;
class RecordDecl;
class Selector;
class Stmt;
class TagDecl;
/// \brief Enumeration describing the result of loading information from
/// an external source.
enum ExternalLoadResult {
/// \brief Loading the external information has succeeded.
ELR_Success,
/// \brief Loading the external information has failed.
ELR_Failure,
/// \brief The external information has already been loaded, and therefore
/// no additional processing is required.
ELR_AlreadyLoaded
};
/// \brief Abstract interface for external sources of AST nodes.
///
/// External AST sources provide AST nodes constructed from some
/// external source, such as a precompiled header. External AST
/// sources can resolve types and declarations from abstract IDs into
/// actual type and declaration nodes, and read parts of declaration
/// contexts.
class ExternalASTSource : public RefCountedBase<ExternalASTSource> {
/// Generation number for this external AST source. Must be increased
/// whenever we might have added new redeclarations for existing decls.
uint32_t CurrentGeneration;
/// \brief Whether this AST source also provides information for
/// semantic analysis.
bool SemaSource;
friend class ExternalSemaSource;
public:
ExternalASTSource() : CurrentGeneration(0), SemaSource(false) { }
virtual ~ExternalASTSource();
/// \brief RAII class for safely pairing a StartedDeserializing call
/// with FinishedDeserializing.
class Deserializing {
ExternalASTSource *Source;
public:
explicit Deserializing(ExternalASTSource *source) : Source(source) {
assert(Source);
Source->StartedDeserializing();
}
~Deserializing() {
Source->FinishedDeserializing();
}
};
/// \brief Get the current generation of this AST source. This number
/// is incremented each time the AST source lazily extends an existing
/// entity.
uint32_t getGeneration() const { return CurrentGeneration; }
/// \brief Resolve a declaration ID into a declaration, potentially
/// building a new declaration.
///
/// This method only needs to be implemented if the AST source ever
/// passes back decl sets as VisibleDeclaration objects.
///
/// The default implementation of this method is a no-op.
virtual Decl *GetExternalDecl(uint32_t ID);
/// \brief Resolve a selector ID into a selector.
///
/// This operation only needs to be implemented if the AST source
/// returns non-zero for GetNumKnownSelectors().
///
/// The default implementation of this method is a no-op.
virtual Selector GetExternalSelector(uint32_t ID);
/// \brief Returns the number of selectors known to the external AST
/// source.
///
/// The default implementation of this method is a no-op.
virtual uint32_t GetNumExternalSelectors();
/// \brief Resolve the offset of a statement in the decl stream into
/// a statement.
///
/// This operation is meant to be used via a LazyOffsetPtr. It only
/// needs to be implemented if the AST source uses methods like
/// FunctionDecl::setLazyBody when building decls.
///
/// The default implementation of this method is a no-op.
virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
/// \brief Resolve the offset of a set of C++ constructor initializers in
/// the decl stream into an array of initializers.
///
/// The default implementation of this method is a no-op.
virtual CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset);
/// \brief Resolve the offset of a set of C++ base specifiers in the decl
/// stream into an array of specifiers.
///
/// The default implementation of this method is a no-op.
virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
/// \brief Update an out-of-date identifier.
virtual void updateOutOfDateIdentifier(IdentifierInfo &II) { }
/// \brief Find all declarations with the given name in the given context,
/// and add them to the context by calling SetExternalVisibleDeclsForName
/// or SetNoExternalVisibleDeclsForName.
/// \return \c true if any declarations might have been found, \c false if
/// we definitely have no declarations with tbis name.
///
/// The default implementation of this method is a no-op returning \c false.
virtual bool
FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name);
/// \brief Ensures that the table of all visible declarations inside this
/// context is up to date.
///
/// The default implementation of this function is a no-op.
virtual void completeVisibleDeclsMap(const DeclContext *DC);
/// \brief Retrieve the module that corresponds to the given module ID.
virtual Module *getModule(unsigned ID) { return nullptr; }
/// \brief Finds all declarations lexically contained within the given
/// DeclContext, after applying an optional filter predicate.
///
/// \param isKindWeWant a predicate function that returns true if the passed
/// declaration kind is one we are looking for. If NULL, all declarations
/// are returned.
///
/// \return an indication of whether the load succeeded or failed.
///
/// The default implementation of this method is a no-op.
virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
bool (*isKindWeWant)(Decl::Kind),
SmallVectorImpl<Decl*> &Result);
/// \brief Finds all declarations lexically contained within the given
/// DeclContext.
///
/// \return true if an error occurred
ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
SmallVectorImpl<Decl*> &Result) {
return FindExternalLexicalDecls(DC, nullptr, Result);
}
template <typename DeclTy>
ExternalLoadResult FindExternalLexicalDeclsBy(const DeclContext *DC,
SmallVectorImpl<Decl*> &Result) {
return FindExternalLexicalDecls(DC, DeclTy::classofKind, Result);
}
/// \brief Get the decls that are contained in a file in the Offset/Length
/// range. \p Length can be 0 to indicate a point at \p Offset instead of
/// a range.
virtual void FindFileRegionDecls(FileID File, unsigned Offset,
unsigned Length,
SmallVectorImpl<Decl *> &Decls);
/// \brief Gives the external AST source an opportunity to complete
/// the redeclaration chain for a declaration. Called each time we
/// need the most recent declaration of a declaration after the
/// generation count is incremented.
virtual void CompleteRedeclChain(const Decl *D);
/// \brief Gives the external AST source an opportunity to complete
/// an incomplete type.
virtual void CompleteType(TagDecl *Tag);
/// \brief Gives the external AST source an opportunity to complete an
/// incomplete Objective-C class.
///
/// This routine will only be invoked if the "externally completed" bit is
/// set on the ObjCInterfaceDecl via the function
/// \c ObjCInterfaceDecl::setExternallyCompleted().
virtual void CompleteType(ObjCInterfaceDecl *Class);
/// \brief Loads comment ranges.
virtual void ReadComments();
/// \brief Notify ExternalASTSource that we started deserialization of
/// a decl or type so until FinishedDeserializing is called there may be
/// decls that are initializing. Must be paired with FinishedDeserializing.
///
/// The default implementation of this method is a no-op.
virtual void StartedDeserializing();
/// \brief Notify ExternalASTSource that we finished the deserialization of
/// a decl or type. Must be paired with StartedDeserializing.
///
/// The default implementation of this method is a no-op.
virtual void FinishedDeserializing();
/// \brief Function that will be invoked when we begin parsing a new
/// translation unit involving this external AST source.
///
/// The default implementation of this method is a no-op.
virtual void StartTranslationUnit(ASTConsumer *Consumer);
/// \brief Print any statistics that have been gathered regarding
/// the external AST source.
///
/// The default implementation of this method is a no-op.
virtual void PrintStats();
/// \brief Perform layout on the given record.
///
/// This routine allows the external AST source to provide an specific
/// layout for a record, overriding the layout that would normally be
/// constructed. It is intended for clients who receive specific layout
/// details rather than source code (such as LLDB). The client is expected
/// to fill in the field offsets, base offsets, virtual base offsets, and
/// complete object size.
///
/// \param Record The record whose layout is being requested.
///
/// \param Size The final size of the record, in bits.
///
/// \param Alignment The final alignment of the record, in bits.
///
/// \param FieldOffsets The offset of each of the fields within the record,
/// expressed in bits. All of the fields must be provided with offsets.
///
/// \param BaseOffsets The offset of each of the direct, non-virtual base
/// classes. If any bases are not given offsets, the bases will be laid
/// out according to the ABI.
///
/// \param VirtualBaseOffsets The offset of each of the virtual base classes
/// (either direct or not). If any bases are not given offsets, the bases will be laid
/// out according to the ABI.
///
/// \returns true if the record layout was provided, false otherwise.
virtual bool layoutRecordType(
const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets,
llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets,
llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets);
//===--------------------------------------------------------------------===//
// Queries for performance analysis.
//===--------------------------------------------------------------------===//
struct MemoryBufferSizes {
size_t malloc_bytes;
size_t mmap_bytes;
MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
: malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
};
/// Return the amount of memory used by memory buffers, breaking down
/// by heap-backed versus mmap'ed memory.
MemoryBufferSizes getMemoryBufferSizes() const {
MemoryBufferSizes sizes(0, 0);
getMemoryBufferSizes(sizes);
return sizes;
}
virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
protected:
static DeclContextLookupResult
SetExternalVisibleDeclsForName(const DeclContext *DC,
DeclarationName Name,
ArrayRef<NamedDecl*> Decls);
static DeclContextLookupResult
SetNoExternalVisibleDeclsForName(const DeclContext *DC,
DeclarationName Name);
/// \brief Increment the current generation.
uint32_t incrementGeneration(ASTContext &C);
};
/// \brief A lazy pointer to an AST node (of base type T) that resides
/// within an external AST source.
///
/// The AST node is identified within the external AST source by a
/// 63-bit offset, and can be retrieved via an operation on the
/// external AST source itself.
template<typename T, typename OffsT, T* (ExternalASTSource::*Get)(OffsT Offset)>
struct LazyOffsetPtr {
/// \brief Either a pointer to an AST node or the offset within the
/// external AST source where the AST node can be found.
///
/// If the low bit is clear, a pointer to the AST node. If the low
/// bit is set, the upper 63 bits are the offset.
mutable uint64_t Ptr;
public:
LazyOffsetPtr() : Ptr(0) { }
explicit LazyOffsetPtr(T *Ptr) : Ptr(reinterpret_cast<uint64_t>(Ptr)) { }
explicit LazyOffsetPtr(uint64_t Offset) : Ptr((Offset << 1) | 0x01) {
assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
if (Offset == 0)
Ptr = 0;
}
LazyOffsetPtr &operator=(T *Ptr) {
this->Ptr = reinterpret_cast<uint64_t>(Ptr);
return *this;
}
LazyOffsetPtr &operator=(uint64_t Offset) {
assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
if (Offset == 0)
Ptr = 0;
else
Ptr = (Offset << 1) | 0x01;
return *this;
}
/// \brief Whether this pointer is non-NULL.
///
/// This operation does not require the AST node to be deserialized.
explicit operator bool() const { return Ptr != 0; }
/// \brief Whether this pointer is non-NULL.
///
/// This operation does not require the AST node to be deserialized.
bool isValid() const { return Ptr != 0; }
/// \brief Whether this pointer is currently stored as an offset.
bool isOffset() const { return Ptr & 0x01; }
/// \brief Retrieve the pointer to the AST node that this lazy pointer
///
/// \param Source the external AST source.
///
/// \returns a pointer to the AST node.
T* get(ExternalASTSource *Source) const {
if (isOffset()) {
assert(Source &&
"Cannot deserialize a lazy pointer without an AST source");
Ptr = reinterpret_cast<uint64_t>((Source->*Get)(Ptr >> 1));
}
return reinterpret_cast<T*>(Ptr);
}
};
/// \brief A lazy value (of type T) that is within an AST node of type Owner,
/// where the value might change in later generations of the external AST
/// source.
template<typename Owner, typename T, void (ExternalASTSource::*Update)(Owner)>
struct LazyGenerationalUpdatePtr {
/// A cache of the value of this pointer, in the most recent generation in
/// which we queried it.
struct LazyData {
LazyData(ExternalASTSource *Source, T Value)
: ExternalSource(Source), LastGeneration(0), LastValue(Value) {}
ExternalASTSource *ExternalSource;
uint32_t LastGeneration;
T LastValue;
};
// Our value is represented as simply T if there is no external AST source.
typedef llvm::PointerUnion<T, LazyData*> ValueType;
ValueType Value;
LazyGenerationalUpdatePtr(ValueType V) : Value(V) {}
// Defined in ASTContext.h
static ValueType makeValue(const ASTContext &Ctx, T Value);
public:
explicit LazyGenerationalUpdatePtr(const ASTContext &Ctx, T Value = T())
: Value(makeValue(Ctx, Value)) {}
/// Create a pointer that is not potentially updated by later generations of
/// the external AST source.
enum NotUpdatedTag { NotUpdated };
LazyGenerationalUpdatePtr(NotUpdatedTag, T Value = T())
: Value(Value) {}
/// Forcibly set this pointer (which must be lazy) as needing updates.
void markIncomplete() {
Value.template get<LazyData *>()->LastGeneration = 0;
}
/// Set the value of this pointer, in the current generation.
void set(T NewValue) {
if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>()) {
LazyVal->LastValue = NewValue;
return;
}
Value = NewValue;
}
/// Set the value of this pointer, for this and all future generations.
void setNotUpdated(T NewValue) { Value = NewValue; }
/// Get the value of this pointer, updating its owner if necessary.
T get(Owner O) {
if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>()) {
if (LazyVal->LastGeneration != LazyVal->ExternalSource->getGeneration()) {
LazyVal->LastGeneration = LazyVal->ExternalSource->getGeneration();
(LazyVal->ExternalSource->*Update)(O);
}
return LazyVal->LastValue;
}
return Value.template get<T>();
}
/// Get the most recently computed value of this pointer without updating it.
T getNotUpdated() const {
if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>())
return LazyVal->LastValue;
return Value.template get<T>();
}
void *getOpaqueValue() { return Value.getOpaqueValue(); }
static LazyGenerationalUpdatePtr getFromOpaqueValue(void *Ptr) {
return LazyGenerationalUpdatePtr(ValueType::getFromOpaqueValue(Ptr));
}
};
} // end namespace clang
/// Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be
/// placed into a PointerUnion.
namespace llvm {
template<typename Owner, typename T,
void (clang::ExternalASTSource::*Update)(Owner)>
struct PointerLikeTypeTraits<
clang::LazyGenerationalUpdatePtr<Owner, T, Update>> {
typedef clang::LazyGenerationalUpdatePtr<Owner, T, Update> Ptr;
static void *getAsVoidPointer(Ptr P) { return P.getOpaqueValue(); }
static Ptr getFromVoidPointer(void *P) { return Ptr::getFromOpaqueValue(P); }
enum {
NumLowBitsAvailable = PointerLikeTypeTraits<T>::NumLowBitsAvailable - 1
};
};
}
namespace clang {
/// \brief Represents a lazily-loaded vector of data.
///
/// The lazily-loaded vector of data contains data that is partially loaded
/// from an external source and partially added by local translation. The
/// items loaded from the external source are loaded lazily, when needed for
/// iteration over the complete vector.
template<typename T, typename Source,
void (Source::*Loader)(SmallVectorImpl<T>&),
unsigned LoadedStorage = 2, unsigned LocalStorage = 4>
class LazyVector {
SmallVector<T, LoadedStorage> Loaded;
SmallVector<T, LocalStorage> Local;
public:
/// Iteration over the elements in the vector.
///
/// In a complete iteration, the iterator walks the range [-M, N),
/// where negative values are used to indicate elements
/// loaded from the external source while non-negative values are used to
/// indicate elements added via \c push_back().
/// However, to provide iteration in source order (for, e.g., chained
/// precompiled headers), dereferencing the iterator flips the negative
/// values (corresponding to loaded entities), so that position -M
/// corresponds to element 0 in the loaded entities vector, position -M+1
/// corresponds to element 1 in the loaded entities vector, etc. This
/// gives us a reasonably efficient, source-order walk.
///
/// We define this as a wrapping iterator around an int. The
/// iterator_adaptor_base class forwards the iterator methods to basic integer
/// arithmetic.
class iterator : public llvm::iterator_adaptor_base<
iterator, int, std::random_access_iterator_tag, T, int> {
LazyVector *Self;
iterator(LazyVector *Self, int Position)
: iterator::iterator_adaptor_base(Position), Self(Self) {}
bool isLoaded() const { return this->I < 0; }
friend class LazyVector;
public:
iterator() : iterator(nullptr, 0) {}
typename iterator::reference operator*() const {
if (isLoaded())
return Self->Loaded.end()[this->I];
return Self->Local.begin()[this->I];
}
};
iterator begin(Source *source, bool LocalOnly = false) {
if (LocalOnly)
return iterator(this, 0);
if (source)
(source->*Loader)(Loaded);
return iterator(this, -(int)Loaded.size());
}
iterator end() {
return iterator(this, Local.size());
}
void push_back(const T& LocalValue) {
Local.push_back(LocalValue);
}
void erase(iterator From, iterator To) {
if (From.isLoaded() && To.isLoaded()) {
Loaded.erase(&*From, &*To);
return;
}
if (From.isLoaded()) {
Loaded.erase(&*From, Loaded.end());
From = begin(nullptr, true);
}
Local.erase(&*From, &*To);
}
};
/// \brief A lazy pointer to a statement.
typedef LazyOffsetPtr<Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt>
LazyDeclStmtPtr;
/// \brief A lazy pointer to a declaration.
typedef LazyOffsetPtr<Decl, uint32_t, &ExternalASTSource::GetExternalDecl>
LazyDeclPtr;
/// \brief A lazy pointer to a set of CXXCtorInitializers.
typedef LazyOffsetPtr<CXXCtorInitializer *, uint64_t,
&ExternalASTSource::GetExternalCXXCtorInitializers>
LazyCXXCtorInitializersPtr;
/// \brief A lazy pointer to a set of CXXBaseSpecifiers.
typedef LazyOffsetPtr<CXXBaseSpecifier, uint64_t,
&ExternalASTSource::GetExternalCXXBaseSpecifiers>
LazyCXXBaseSpecifiersPtr;
} // end namespace clang
#endif
| 36.597222 | 89 | 0.690702 | [
"object",
"vector"
] |
9a782368f0a6236a9e00aadec20ad4b775da501f | 66,472 | h | C | motr/client.h | rkothiya/cortx-motr | daf765c7bbeb1c405ec771d7ce7cf6f11ab5e583 | [
"Apache-2.0"
] | 2 | 2022-03-29T17:26:25.000Z | 2022-03-31T11:24:50.000Z | motr/client.h | ydb242/cortx-motr | 4de43b22b13c0d5e7de538bd5aa1a62cc7df6fa5 | [
"Apache-2.0"
] | null | null | null | motr/client.h | ydb242/cortx-motr | 4de43b22b13c0d5e7de538bd5aa1a62cc7df6fa5 | [
"Apache-2.0"
] | null | null | null | /* -*- C -*- */
/*
* Copyright (c) 2016-2020 Seagate Technology LLC and/or its Affiliates
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For any questions about this software or licensing,
* please email opensource@seagate.com or cortx-questions@seagate.com.
*
*/
#pragma once
#ifndef __MOTR_CLIENT_H__
#define __MOTR_CLIENT_H__
#include "lib/vec.h"
#include "lib/types.h"
#include "sm/sm.h" /* struct m0_sm */
#include "rpc/rpc_machine.h" /* M0_RPC_DEF_MAX_RPC_MSG_SIZE */
#include "fid/fid.h"
#include "lib/cookie.h"
#include "xcode/xcode_attr.h"
/**
* @defgroup client
*
* Overview
* --------
*
* Examples of Motr applications are:
*
* - Motr file system client (m0t1fs);
*
* - Lustre osd-motr module (part of LOMO);
*
* - Lustre HSM backend (part of Castor-A200);
*
* - SWIFT or S3 backend (part of WOMO);
*
* - Motr-based block device (part of BOMO);
*
* - exascale E10 stack (see eiow.org).
*
* Client interface is divided into the following sub-interfaces:
*
* - access sub-interface, which provides basic abstraction to build storage
* application;
*
* - management sub-interface, which provides methods for Motr cluster
* deployment, configuration, re-configuration and monitoring;
*
* - extension sub-interface, which allows applications to extend Motr
* functionality without modifying the core Motr.
*
* This header describes the access sub-interface of client, simply called
* "client interface" hereafter.
*
* In the following "an application" means a code invoking the client interface
* and "the implementation" refers to the implementation of the said interface.
*
* Client provides the following abstractions:
*
* - object (m0_obj) is an array of fixed-size blocks;
*
* - index (m0_idx) is a key-value store;
*
* - realm (m0_realm) is a spatial and temporal part of system with a
* prescribed access discipline. Objects, indices and operations live in
* realms;
*
* - operation (m0_op) is a process of querying or updating system
* state;
*
* Realms are further sub-divided in:
*
* - transaction (m0__dtx) is a collection of operations atomic in the
* face of failures;
*
* - epoch (m0_epoch) is a collection of operations done by an
* application, which moves the system from one application-consistent
* state to another;
*
* - container (m0_container) is a collection of objects used by a
* particular application or group of applications;
*
* - other types of realms, as can be added in the future.
*
* Object, index and realm are sub-types of entity (m0_entity). Entities
* provide state, interface and behavior shared by all sub-types.
*
* All client entry points, except for m0_op_wait(), are non-blocking.
* To perform a potentially lengthy activity, that might involve network
* communication (for example, read from an object), the client entry point
* (m0_obj_op() in the case of object read), sets up an operation
* (m0_ops) structure containing the parameters of the activity and
* immediately returns to the caller. The caller should explicitly launch a set
* of previously prepared operations by calling m0_op_launch().
* Separation of preparation and launch provides for more efficient network
* communication, where multiple operations are accumulated in the same network
* message.
*
* In-memory structures (m0_{obj,index,realm,...}) correspond to some
* storage entities maintained by the implementation. The implementation does
* not enforce this correspondence. If an application keeps multiple in-memory
* structures for the same storage entity (whether in the same process address
* space or not), it is up to the application to keep the structures coherent
* (the very notion of coherency, obviously, being application-dependent). At
* the one end of the spectrum, an application can employ a fully coherent,
* distributed cache for entities, providing strong consistency guarantees. On
* the other end, an application can tolerate multiple inconsistent views of the
* same storage entities, providing NFSv2-like semantics.
*
* Sub-typing
* ----------
*
* @verbatim
*
* entity (create, delete, open, close, fini) [abstract, no constructor]
* |
* |
* +---- object (init, read, write, alloc, free)
* |
* |
* +---- index (init, get, put, next)
* |
* |
* +---- realm () [abstract, no constructor]
* |
* |
* +---- container (init)
* |
* |
* +---- epoch (init)
* |
* |
* +---- dtx (init)
*
*
* op (init, wait, setup, launch, kick, free, fini)
* [has private sub-types in private.h]
*
* @endverbatim
*
* Identifiers
* -----------
*
* An entity exists in some realm and has a 128-bit identifier, unique within
* the cluster and never re-used. The high 8 bits of an identifier denote the
* entity type. Identifier management is up to the application, except that the
* single identifier M0_UBER_REALM is reserved for the "uber realm",
* representing the root of the realm hierarchy, and within each entity type,
* identifiers less than M0_ID_APP are reserved for the implementation's
* internal use.
*
* @todo A library on top of client for fast scalable identifier allocation will
* be provided as part of Motr.
*
* The implementation is free to reserve some 8-bit combinations for its
* internal use.
*
* @todo an interface to register 8-bit combinations for application use (to
* introduce application-specific "entity-like" things).
*
* Operations
* ----------
*
* An operation structure tracks the state of execution of a request made to the
* implementation.
*
* An operation structure is a state machine going through states described by
* enum m0_op_state:
*
* @verbatim
* (0)
* |
* |
* V
* +---------------INITIALISED
* | |
* | | m0_op_launch()
* V V
* FAILED<-------------LAUNCHED
* ^ |
* | |
* | V
* +----------------EXECUTED---------------->STABLE
* @endverbatim
*
* An operation in INITIALISED, FAILED or STABLE state is called "complete" and
* "outstanding" (or "in-progress") otherwise.
*
* An operation is in INITIALISED state after allocation. In this state, the
* operation processing is not yet started, the application is free to modify
* operation parameters with a call to m0_op_setup() or direct field
* access.
*
* Multiple initialised operation structures can be simultaneously moved to the
* LAUNCHED state, by a call to m0_op_launch(). This call starts actual
* operation processing. No changes to the operation structure are allowed by
* the application after this call is made and until the operation completes.
* To improve caching and utilisation of system resources, the implementation
* is free to delay any operation-related acitivities, such as sending network
* messages, for some time after the operation is launched. The value of
* m0_op::op_linger is an application-provided hint about the absolute
* time by which such delays should be limited.
*
* In case of successful execution, a launched operation structure eventually
* reaches EXECUTED state, meaning that the operation was executed at least in
* the volatile stores of the respective services. When the operation enters
* EXECUTED state, the m0_op_ops::oop_executed() call-back, if provided
* by the application, is invoked. By the time this state is entered, the
* operation return code is in m0_op::op_sm::sm_rc, and all return
* information (object data in case of READ, keys and values in case of GET and
* NEXT) are already placed in the application-supplied buffers.
*
* After an operation has been executed, it can still be lost due to a
* failure. The implementation continues to work toward making the operation
* stable. When this activity successfully terminates, the operation enters the
* STABLE state and the m0_op_ops::oop_stable() call-back is invoked, if
* provided. Once an operation is stable, the implementation guarantees that the
* operation would survive any "allowed failure", where allowed failures include
* at least transient service failures (crash and restart with volatile store
* loss), transient network failures and client failures.
*
* In case of a failure, the operation structure moves into FAILED state, the
* m0_op_ops::oop_failed() call-back is invoked, and no further state
* transitions will ensue.
*
* The implementation is free to add another states to the operation state
* machine.
*
* All operation structures embed "generic operation" m0_op as the first
* member.
*
* The application can track the state of the operation either synchronously, by
* waiting until the operation reaches a particular state (m0_op_wait()),
* or asynchronously by supplying (m0_op_setup()) a call-back to be
* called when the operation reaches a particular state.
*
* Operation structures are either pre-allocated by the application or allocated
* by the appropriate entry points, see the "op" parameter of m0_obj_op()
* for an example. When an operation structure is pre-allocated, the application
* must set m0_op::op_size to the size of the pre-allocated structure
* before passing it to a client entry point. This allows the implementation to
* check that the pre-allocated structure has enough room and return an error
* (-EMSGSIZE) otherwise.
*
* Operation errors are returned through m0_op::op_sm::sm_rc.
*
* Operations, common for all entity types are implemented at the entity level:
* m0_entity_create(), m0_entity_delete(),
* m0_entity_fini().
*
* A typical usage would involve initialisation of a concrete entity (e.g.,
* object), execution of some generic operations and then of some concrete
* operations, for example:
*
* @code
* m0_obj o;
* m0_op *ops[2] = {};
*
* // initialise object in-memory structure.
* m0_obj_init(&o, &container, &id, 0);
*
* // initiate object creation. m0_entity_create() allocated the
* // operation and stores the pointer to it in ops[0].
* m0_entity_create(NULL, &o.ob_entity, &ops[0]);
*
* // initiate write data in the object.
* result = m0_obj_op(&o, M0_OC_WRITE, ..., &ops[1]);
*
* // launch both operations (creation and write)
* m0_op_launch(ops, ARRAY_SIZE(ops));
*
* // wait until creation completes
* result = m0_op_wait(op[0], M0_BITS(M0_OS_STABLE,
* M0_OS_FAILED),
* M0_TIME_NEVER);
* // wait until write completes
* result = m0_op_wait(op[1], M0_BITS(M0_OS_STABLE,
* M0_OS_FAILED),
* M0_TIME_NEVER);
* // finalise the object
* m0_entity_fini(&o.ob_entity);
*
* // free the operations
* m0_op_free(op[0]);
* m0_op_free(op[1]);
* @endcode
*
* Object
* ------
*
* A client object is an array of blocks, which can be read from and written
* onto at the block granularity.
*
* Block size is a power of two bytes and is selected at the object creation
* time.
*
* An object has no traditional application-visible meta-data (in particular, it
* has no size). Instead it has meta-data, called "block attributes" associated
* with each block. Block attributes can be used to store check-sums, version
* numbers, hashes, etc. Because of the huge number of blocks in a typical
* system, the overhead of block attributes book-keeping must be kept at a
* minimum, which puts restrictions on the block attribute access interface
* (@todo to be described).
*
* There are 4 types of object operations, in addition to the common entity
* operations:
*
* - READ: transfer blocks and block attributes from an object to
* application buffers;
*
* - WRITE: transfer blocks and block attributes from application buffers to
* an object;
*
* - ALLOC: pre-allocate certain blocks in an implementation-dependent
* manner. This operation guarantees that consecutive WRITE onto
* pre-allocated blocks will not fail due to lack of storage space;
*
* - FREE: free storage resources used by specified object
* blocks. Consecutive reads from the blocks will return zeroes.
*
* READ and WRITE operations are fully scatter-gather-scatter: data are
* transferred between a sequence of object extents and a sequence of
* application buffers, the only restrictions being:
*
* - total lengths of the extents must be equal to the total size of the
* buffers, and
*
* - extents must be block-size aligned and sizes of extents and buffers
* must be multiples of block-size.
*
* Internally, the implementation stores an object according to the object
* layout (specified at the object creation time). The layout determines
* fault-tolerance and performance related characteristics of the
* object. Examples layouts are:
*
* - network striping with parity de-clustering. This is the default layout,
* it provides a flexible level of fault-tolerance, high availability in
* the face of permanent storage device failures and full utilisation of
* storage resources;
*
* - network striping without parity (raid0). This provides higher space
* utilisation and lower processor costs than parity de-clustering at the
* expense of fault-tolerance;
*
* - network mirroring (raid1). This provides high fault-tolerance and
* availability at the cost of storage space consumption;
*
* - de-dup, compression, encryption.
*
* Index
* -----
*
* A client index is a key-value store.
*
* An index stores records, each record consisting of a key and a value. Keys
* and values within the same index can be of variable size. Keys are ordered by
* the lexicographic ordering of their bit-level representation. Records are
* ordered by the key ordering. Keys are unique within an index.
*
* There are 4 types of index operations:
*
* - GET: given a set of keys, return the matching records from the index;
*
* - PUT: given a set of records, place them in the index, overwriting
* existing records if necessary, inserting new records otherwise;
*
* - DEL: given a set of keys, delete the matching records from the index;
*
* - NEXT: given a set of keys, return the records with the next (in the
* ascending key order) keys from the index.
*
* Indices are stored according to a layout, much like objects.
*
* Realm
* -----
*
* To define what a realm is, consider the entire history of a client storage
* system. In the history, each object and index is represented as a "world
* line" (https://en.wikipedia.org/wiki/World_line), which starts when the
* entity is created and ends when it is deleted. Points on the world line
* correspond to operations that update entity state.
*
* A realm is the union of some continuous portions of different world
* lines. That is, a realm is given by a collection of entities and, for each
* entity in the collection, a start and an end point (operations) on the
* entity world line. A realm can be visualised as a cylinder in the history.
*
* The restriction placed on realms is that each start point in a realm must
* either be the first point in a world line (i.e., the corresponding entity is
* created in the realm) or belong to the same realm, called the parent of the
* realm in question. This arranges realms in a tree.
*
* @note Realms are *not* necessarily disjoint.
*
* A realm can be in the following application-controllable states:
*
* - OPEN: in this state the realm can be extended by executing new
* operations against entities already in the realm or creating new
* entities in the realm;
*
* - CLOSED: in this state the realm can no longer be extended, but it is
* tracked by the system and maintains its identity. Entities in a closed
* realm can be located and read-only operations can be executed on them;
*
* - ABSORBED: in this state the realm is no longer tracked by the
* system. All the operations executed as part of the realm are by now
* stable and absorbed in the parent realm;
*
* - FAILED: an application aborted the realm or the implementation
* unilaterally decided to abort it. The operations executed in the realm
* are undone together with a transitive closure of dependent operations
* (the precise definition being left to the implementation
* discretion). Thus, failure of a realm can lead to cascading failures of
* other realms.
*
* Examples of realms are:
*
* - a container (m0_container) can be thought of as a "place" where
* a particular storage application lives. In a typical scenario, when an
* application is setup on a system, a new container, initially empty,
* will be created for the application. The application can create new
* entities in the container and manipulate them without risk of conflicts
* (e.g., for identifier allocation) with other applications. A container
* can be thought of as a virtualised storage system for an application. A
* container realm is open as long as application needs its persistent
* data. When the application is uninstalled, its realm is deleted;
*
* - a snapshot realm is created with a container as the parent and is
* immediately closed. From now on, the snapshot provides a read-only view
* of container objects at the moment of the snapshot creation. Finally,
* the snapshot is deleted. If a snapshot is not closed immediately, but
* remains open, it is a writeable snapshot (clone)---a separate branch in
* the container's history. A clone is eventually deleted without being
* absorbed in the parent container;
*
* - an epoch (m0_epoch) is a realm capturing part of the
* application's work-flow for resilience. Often an HPC application works
* by interspersing "compute phases", when actual data processing is done,
* with an "IO phase" when a checkpoint of application state is saved on
* the storage system for failure recovery purposes. A client application
* would, instead, keep an open "current" epoch realm, closed at the
* compute-IO phase transition, with the new epoch opened immediately. The
* realm tree for such application would look like
*
* @verbatim
*
* CONTAINER--->E--->E---...->E--->CURRENT
*
* @endverbatim
*
* Where all E epochs are closed and in the process of absorbtion, and all
* earlier epochs already absorbed in the container.
*
* If the application fails, it can restart either from the container or
* from any closed epoch, which are all guaranteed to be consistent, that
* is, reflect storage state at the boundry of a compute phase. The final
* CURRENT epoch is potentially inconsistent after a failure and should be
* deleted.
*
* - a distributed transaction (m0__dtx) is a group of operations,
* which must be atomic w.r.t. to failures.
*
* Ownership
* ---------
*
* client entity structures (realms, objects and indices) are allocated by the
* application. The application may free a structure after completing the
* corresponding finalisation call. The application must ensure that all
* outstanding operations on the entity are complete before finalisation.
*
* An operation structure allocated by the application, must remain allocated
* until the operation is complete. Before a complete operation structure can be
* re-used, it should be finalised by a call to m0_op_fini(). An
* operation structure allocated by the client implementation can be finalised
* and re-used as one allocated by the application, and must be eventually freed
* by the application (by calling m0_op_free()) some time after the
* operation completes.
*
* Data blocks used by scatter-gather-scatter lists and key-value records are
* allocated by the application. For read-only operations (M0_OC_READ,
* M0_IC_GET and M0_IC_NEXT) the application may free the data
* blocks as soon as the operation reaches EXECUTED or FAILED state. For
* updating operations, the data blocks must remain allocated until the
* operation stabilises.
*
* Concurrency
* -----------
*
* The client implementation guarantees that concurrent calls to the same index
* are linearizable.
*
* All other concurrency control, including ordering of reads and writes to a
* client object, and distributed transaction serializability, is up to the
* application.
*
* For documentation links, please refer to this file :
* doc/motr-design-doc-list.rst
*
* @todo entity type structures (to provide constructors, 8-bit identifier tags
* and an ability to register new entity types).
*
* @todo handling of extensible attributes (check-sums, version numbers, etc.),
* which require interaction with the implementation on the service side.
*
* @{
*/
/**
* Operation codes for entity, object and index.
*/
enum m0_entity_opcode {
M0_EO_INVALID, /* 0 */
M0_EO_CREATE, /* 1 */
M0_EO_DELETE, /* 2 */
M0_EO_SYNC, /* 3 */
M0_EO_OPEN, /* 4 */
M0_EO_GETATTR, /* 5 */
M0_EO_SETATTR, /* 6 */
M0_EO_LAYOUT_GET, /* 7 */
M0_EO_LAYOUT_SET, /* 8 */
M0_EO_NR /* 9 */
} M0_XCA_ENUM;
/** Object operation codes. */
enum m0_obj_opcode {
/** Read object data. */
M0_OC_READ = M0_EO_NR + 1, /* 10 */
/** Write object data. */
M0_OC_WRITE, /* 11 */
/** Pre-allocate space. */
M0_OC_ALLOC, /* 12 */
/** De-allocate space, consecutive reads will return 0s. */
M0_OC_FREE, /* 13 */
M0_OC_NR /* 14 */
} M0_XCA_ENUM;
/* Index operation codes. */
enum m0_idx_opcode {
/** Lookup a value with the given key. */
M0_IC_GET = M0_OC_NR + 1, /* 15 */
/** Insert or update the value, given a key. */
M0_IC_PUT, /* 16 */
/** Delete the value, if any, for the given key. */
M0_IC_DEL, /* 17 */
/** Given a key, return the next key and its value. */
M0_IC_NEXT, /* 18 */
/** Check an index for an existence. */
M0_IC_LOOKUP, /* 19 */
/** Given an index id, get the list of next indices. */
M0_IC_LIST, /* 20 */
M0_IC_NR /* 21 */
} M0_XCA_ENUM;
/**
* Flags passed to m0_obj_op() to specify object IO operation behaviour.
*/
enum m0_op_obj_flags {
/**
* Read operation should not see any holes. If a hole is met during
* read, return error instead.
*/
M0_OOF_NOHOLE = 1 << 0,
/**
* Write, alloc and free operations wait for the transaction to become
* persistent before returning.
*/
M0_OOF_SYNC = 1 << 1
} M0_XCA_ENUM;
/**
* Types of entities supported by client.
*/
enum m0_entity_type {
M0_ET_REALM,
M0_ET_OBJ,
M0_ET_IDX
} M0_XCA_ENUM;
/**
* Flags passed to m0_entitiy_create(), m0_entity_open() to specify
* application's behaviour.
*/
enum m0_entity_flags {
/**
* If motr client application has the capability to store object
* metadata by itself (such as pool version and layout, which can
* be stored by the application at motr distributed index, for example),
* it can use this flag to avoid sending additional metadata fops on
* such object operations as CREATE, OPEN, DELETE, GETATTR and, thus,
* improve its performance.
*
* Before calling m0_entity_create() or m0_entity_open(), application
* is expected to set obj->ob_entity->en_flags |= M0_ENF_META. When
* m0_entity_create() returns, the pool version and layout id will be
* available for the application at obj->ob_attr.oa_pver and
* obj->ob_attr.oa_lid respectively.
*
* For example, create workflow can look like this:
*
* obj->ob_entity.en_flags |= M0_ENF_META;
* m0_entity_create(NULL, &obj->ob_entity, &ops[0]);
* // Save the returned pool version and lid into app_meta_data
* app_meta_data.pver = obj->ob_attr.oa_pver;
* app_meta_data.lid = obj->ob_attr.oa_lid;
*
* And read workflow:
*
* obj->ob_entity.en_flags |= M0_ENF_META;
* // Set the pool version and lid from app_meta_data
* obj->ob_attr.oa_pver = app_meta_data.pver;
* obj->ob_attr.oa_lid = app_meta_data.lid;
* m0_entity_open(NULL, &obj->ob_entity, &ops[0]);
*/
M0_ENF_META = 1 << 0,
/**
* If this flags is set during entity_create() that means application
* do not support update operation. This flag is not in use yet.
*/
M0_ENF_NO_RMW = 1 << 1,
/**
* This flag is to enable data integrity.
*/
M0_ENF_DI = 1 << 2
} M0_XCA_ENUM;
/**
* Generic client operation structure.
*/
struct m0_op {
uint64_t op_magic;
/**
* Operation code.
*
* @see m0_entity_opcode, m0_realm_opcode
* @see m0_obj_opcode, m0_idx_opcode,
*/
unsigned int op_code;
/** Operation result code */
int32_t op_rc;
/** Each op has its own sm group. */
struct m0_sm_group op_sm_group;
/** Operation state machine. */
struct m0_sm op_sm;
/** Application-supplied call-backs. */
const struct m0_op_ops *op_cbs;
/** The entity this operation is on. */
struct m0_entity *op_entity;
/** Caching dead-line. */
m0_time_t op_linger; /* a town in Luxembourg. */
/** Size of the ambient operation structure. */
size_t op_size;
/** Part of a cookie (m0_cookie) used to identify this operation. */
uint64_t op_gen;
/**
* Back pointer to parent op and it is used to form an execution plan
* for a group of ops. An example: an composite layout IO op is divided
* into a few IO ops to sub-objects. Each sub-object IO op has an
* pointer to the composite IO op.
*/
struct m0_op *op_parent;
struct m0_sm_ast op_parent_ast;
/** list of pending transactions. */
struct m0_tl op_pending_tx;
struct m0_mutex op_pending_tx_lock;
/* Operation's private data, can be used as arguments for callbacks.*/
void *op_datum;
uint64_t op_count;
/**
* Private field, to be used by internal implementation.
*/
void *op_priv;
struct m0_mutex op_priv_lock;
};
/**
* Operation state, stored in m0_op::op_sm::sm_state.
*/
enum m0_op_state {
M0_OS_UNINITIALISED,
M0_OS_INITIALISED,
M0_OS_LAUNCHED,
M0_OS_EXECUTED,
M0_OS_STABLE,
M0_OS_FAILED,
M0_OS_NR
};
/**
* Common structure shared by objects, indices and realms.
*/
struct m0_entity {
/** Entity type. */
enum m0_entity_type en_type;
/** Globally unique, not re-usable entity identifier. */
struct m0_uint128 en_id;
/** Parent realm, this entity lives in. */
struct m0_realm *en_realm;
/**
* Entity state machine. Used internally by the implementation. For the
* reference, the state diagram is:
*
* @verbatim
* create
* CREATING<--------+
* | |
* | |
* | |
* | |
* +---------->INIT<----------------------CLOSING
* | | | ^
* | | | |
* | | | | close
* | | | |
* DELETING<--------+ +-------->OPENING-------->OPEN
* delete open
* @endverbatim
*
*/
struct m0_sm en_sm;
/** Each entity has its own sm group. */
struct m0_sm_group en_sm_group;
/** list of pending transactions. */
struct m0_tl en_pending_tx;
struct m0_mutex en_pending_tx_lock;
uint32_t en_flags;
};
/**
* Object attributes.
*
* This is supplied by an application when an object is created and returned by
* the implementation when an object is opened.
*/
struct m0_obj_attr {
/** Binary logarithm (bit-shift) of object minimal block size. */
m0_bcount_t oa_bshift;
/** Layout ID for an object. */
uint64_t oa_layout_id;
/**
* The pool this object stores data to. A pool can be selected when
* creating an object by specifying this field. A pool version matching
* the specified pool fid is then chosen for the object. The pool
* version is then stored as one of its attributes in service's backend.
*/
struct m0_fid oa_pool;
/** Pool version fid */
struct m0_fid oa_pver;
/**
* Buffer size for object IO. Set this before m0_obj_init() to generate
* optimal layout id during m0_entity_create().
*/
size_t oa_buf_size;
};
/**
* Layout is of an entity containing information to locate data
* (node, service, device). TODO: rewrite the definition.
*/
enum m0_client_layout_type {
M0_LT_PDCLUST = 0,
M0_LT_COMPOSITE,
M0_LT_CAPTURE,
M0_LT_NR
};
/**
* Object is an array of blocks. Each block has 64-bit index and a block
* attributes.
*/
struct m0_client_layout;
struct m0_obj {
struct m0_entity ob_entity;
struct m0_obj_attr ob_attr;
struct m0_client_layout *ob_layout;
/** Cookie associated with a RM context */
struct m0_cookie ob_cookie;
};
struct m0_client_layout {
struct m0_entity ml_entity;
enum m0_client_layout_type ml_type;
/* Back pointer to the object it belongs to. */
struct m0_obj *ml_obj;
const struct m0_client_layout_ops *ml_ops;
};
/**
* Index attributes.
*
* This is supplied by an application and return by the implementation
* when an index is created.
*
*/
struct m0_idx_attr {
/** DIX pool layout type. Please refer to enum dix_layout_type. */
uint32_t idx_layout_type;
/** DIX pool version. */
struct m0_fid idx_pver;
};
/**
* Index is an ordered key-value store.
*
* A record is a key-value pair. A new record can be inserted in an index,
* record with a given key can be looked for, updated or deleted.
*
* An index can be iterated starting from a given key. Keys are ordered in the
* lexicographical order of their bit-representations.
*
* Entity identifier in_entity::en_id format depends on index service type.
* M0_IDX_MOCK and M0_IDX_CASS services accept arbitrary
* identifiers. M0_IDX_DIX service supports two types of indices:
* - distributed index, which is identified by well-formed motr fid having
* m0_dix_fid_type type.
* - non-distributed index, which is identified by well-formed motr fid having
* m0_cas_index_fid_type type.
*/
struct m0_idx {
struct m0_entity in_entity;
struct m0_idx_attr in_attr;
};
#define M0_COMPOSITE_EXTENT_INF (0xffffffffffffffff)
struct m0_composite_layer_idx_key {
struct m0_uint128 cek_layer_id;
m0_bindex_t cek_off;
};
struct m0_composite_layer_idx_val {
m0_bcount_t cev_len;
};
enum m0_realm_type {
M0_ST_CONTAINER,
M0_ST_EPOCH,
M0_ST_DTX,
M0_ST_NR
};
/**
* Forward declaration: m0_client represents a client instance, a connection
* to a motr cluster.
*
* Defined in motr/client_internal.h
*/
struct m0_client;
/**
* Realm is where entities (including other realms) live.
*
* @see m0_container, m0_epoch, m0__dtx.
*/
struct m0_realm {
struct m0_entity re_entity;
enum m0_realm_type re_type;
struct m0_client *re_instance;
};
/**
* Container is a special type of realm, used to partition storage system among
* applications.
*/
struct m0_container {
struct m0_realm co_realm;
};
/**
* Epoch is a special type of realm, used by an application (or a
* collaborative set of applications) to partition their work in consistent
* portions.
*
* Epoch boundary should be a consistent (from application point of view) state
* of storage. By resuming from a given epoch, applications can implement a
* scalable failure recovery mechanism.
*/
struct m0_epoch {
struct m0_realm ep_realm;
};
/**
* Distributed transaction is a special type of realm, which is a group of
* operations atomic w.r.t. certain failures.
*/
struct m0__dtx {
struct m0_realm dt_realm;
};
/**
* Operation callbacks.
*/
struct m0_op_ops {
void (*oop_executed)(struct m0_op *op);
void (*oop_failed)(struct m0_op *op);
void (*oop_stable) (struct m0_op *op);
};
/**
* m0_config contains configuration parameters to setup an
* client instance.
*/
struct m0_config {
/** oostore mode is set when 'is_oostore' is TRUE. */
bool mc_is_oostore;
/**
* Flag for verify-on-read. Parity is checked when doing
* READ's if this flag is set.
*/
bool mc_is_read_verify;
/**
* Flag to enable/disable addb2 initialization
*/
bool mc_is_addb_init;
/** Local endpoint.*/
const char *mc_local_addr;
/** HA service's endpoint.*/
const char *mc_ha_addr;
/** Process fid for rmservice@client. */
const char *mc_process_fid;
const char *mc_profile;
/**
* The minimum length of the 'tm' receive queue,
* use M0_NET_TM_RECV_QUEUE_DEF_LEN if unsure.
*/
uint32_t mc_tm_recv_queue_min_len;
/**
* The maximum rpc message size, use M0_RPC_DEF_MAX_RPC_MSG_SIZE
* if unsure.
*/
uint32_t mc_max_rpc_msg_size;
/* TODO: This parameter is added for a temporary solution of
* layout selection for s3 team. This has to be removed when
* sophisticated solution is implemented.*/
uint32_t mc_layout_id;
int mc_idx_service_id;
void *mc_idx_service_conf;
/**
* ADDB size
*/
m0_bcount_t mc_addb_size;
};
/** The identifier of the root of realm hierarchy. */
extern const struct m0_uint128 M0_UBER_REALM;
/**
* First identifier that applications are free to use.
*
* It is guaranteed that M0_UBER_REALM falls into reserved extent.
* @invariant m0_uint128_cmp(&M0_UBER_REALM, &M0_ID_APP) < 0
*/
extern const struct m0_uint128 M0_ID_APP;
/**
* Resource Manager(RM) Object Locks
* ----------------------------------------------------------------------------
*
* Resource: is an entity in Motr for which a notion of ownership can be
* well-defined.
* Resource Manager: is a service which manages the granting and revocation
* of resources to and from clients and services.
* Objects: are resources for the Resource Manager(RM).
* Remote RM creditor: is the RM service running on a remote server.
* Borrowing: the rights to use the resource from remote RM,
* 'locks' the object.
* Relinquishing: the rights to use the resource to remote RM, 'unlocks'
* the object.
* Write Locks: behave like mutexes and maintain mutual exclusion.
* Read Locks: facilitate shared access to the object made by other requests.
* Lock conflict: When a request for lock has to wait for other lock request(s)
* to release the lock.
* Fairness: Object lock maintains fairness among lock requests by enforcing
* FCFS among lock requests (Note: fairness can be guaranteed if the
* clocks are synchronized among RM services).
*
* The object can be locked with exclusive access by using write
* locks and shared access by using read locks. An object locked with write
* lock cannot be locked by other lock requests and any subsequent requests
* for locks will conflict. An object locked with read lock will not conflict
* with other subsequest read locks.
*
* To maintain fairness and prevent writer starvation, any read lock requests
* made after the arrival of a write lock request, will wait and wont bypass
* FCFS ordering to acquire lock.
*
* @verbatim
* type of lock held | new request for lock | conflict?
* -------------------------+--------------------------+-----------------
* Write | Write | Yes
* Write | Read | Yes
* Read | Write | Yes
* Read | Read | No
* -------------------------+--------------------------+-----------------
* @endverbatim
*
* There is no restriction on the granularity of locks on application level.
*
* The RM context (represented by m0_rm_lock_ctx) holds information
* about the object which is needed by the RM to lock/unlock this object,
* and act as a local owner for the object.
*
* The RM context is cached in client instance to avoid multiple
* initializations. It is created and initialized on the first call
* of m0_obj_lock_init for a particular object and upon subsequent calls
* for the same object, it takes a reference of cached RM context and attaches
* it to the instance of the object.
*
* In single threaded environment, it's recommended that the object lock is
* initialized only once, followed by a sequence of lock and unlock before
* finalizing the lock.
*
* In multi-threaded environment, every in-memory instance of the same object
* should be initialised local to the thread. They will share the same instance
* of RM context which is cached in client instance. The usage is same as with
* single threaded environment after initialization.
* eg:
*
* @verbatim
* Thread 1 inst Thread 2
* ---------- --------------- ----------
* | | |
* | | |
* m0_obj_lock_init(ob) --> ref_cnt = 1 |
* | | |
* | | |
* | ref_cnt = 2 <-- m0_obj_lock_init(ob)
* m0_obj_lock_get(ob) | |
* | | m0_obj_lock_get(ob)
* | | (wait)
* | | (wait)
* m0_obj_lock_put(ob) | |
* | | |
* m0_obj_lock_fini(ob) --> ref_cnt = 1 |
* | | m0_obj_lock_put(ob)
* X | |
* ref_cnt = 0 <-- m0_obj_lock_fini(ob)
* | |
* | X
* @endverbatim
*
* Locks are shared among requests for objects in same group.
* Default groups:
* #m0_rm_group - part of client group.
* #m0_rm_no_group - part of no group.(stand-alone objects)
* #NULL - it is also treated as not part of any group.
*
* The application should implement mechanisms to properly handle sharing of
* locks among multiple threads.
*
* @code
* void *io_thread(void *)
* {
* m0_obj ob1;
* m0_rm_lock_req req;
* m0_uint128 rm_group1 = M0_UINT128(0, 1);
*
* m0_obj_lock_init(&ob1, &rm_group1);
* m0_obj_lock_get(&ob1, &req, &rm_group1);
* ...
* //Mechanism to handle lock sharing & do IO.
* ...
* m0_obj_lock_put(&req);
* m0_obj_lock_fini(&ob1);
* }
*
* void perform_mutiple_io(void)
* {
* pthread_t th1;
* pthread_t th2;
*
* pthread_create(&th1, NULL, io_thread, NULL);
* pthread_create(&th2, NULL, io_thread, NULL);
* pthread_join(th1, NULL);
* pthread_join(th2, NULL);
* }
* @endcode
*
* An object is 'locked' by requesting the RM creditor to borrow the rights to
* use a resource. When the request completes, a
* channel(m0_rm_lock_req::rlr_chan) is signalled
* and a callback is executed for the clink attached to the channel.
*/
/**
* Forward declaration: m0_rm_lock_req represents a request to
* borrow/relinquish rights to use a resource form remote RM creditor
* and lock/unlock the object.
*/
struct m0_rm_lock_req;
/**
* Initializes the RM object lock for this object and attaches a RM context
* with this object.
*
* @pre m0_obj_init()
* @param obj an instance of object.
* @param group group_id for the object.
* @retval 0 On success.
* @retval -ENOMEM when there is no memory for ctx or fid.
*/
int m0_obj_lock_init(struct m0_obj *obj);
/**
* Finalizes the object lock and decreased the rm_ctx::rmc_ref::ref_cnt.
* If the rm_ctx::rmc_ref::ref_cnt becomes 0, then finalize the
* cached RM context.
*
* @pre m0_obj_init()
* @pre m0_obj_lock_init()
* @param obj an instance of object.
*/
void m0_obj_lock_fini(struct m0_obj *obj);
/**
* Acquires the write lock for the object asynchronously.
* Recursive locking is not supported.
*
* This is a wrapper over m0_obj_lock_get();
*
* @pre m0_obj_init()
* @pre m0_obj_lock_init()
* @param obj a pointer to m0_obj.
* @param req representing a request to RM.
* @param clink a link which will listen on a channel for the signal of
* completion.
* @retval 0 On success.
*/
int m0_obj_write_lock_get(struct m0_obj *obj,
struct m0_rm_lock_req *req,
struct m0_clink *clink);
/**
* Acquires the write lock for the object.
* Recursive locking is not supported.
* This is a blocking function.
*
* This is a wrapper over m0_obj_lock_get_sync();
*
* @pre m0_obj_init()
* @pre m0_obj_lock_init()
* @param obj A pointer to m0_obj.
* @param req Representing a request to RM.
* @retval 0 On success.
*/
int m0_obj_write_lock_get_sync(struct m0_obj *obj,
struct m0_rm_lock_req *req);
/**
* Acquires the read lock for the object asynchronously.
* Recursive locking is not supported.
* Locks don't conflict among requests for read lock.
*
* This is a wrapper over m0_obj_lock_get();
*
* @pre m0_obj_init()
* @pre m0_obj_lock_init()
* @param obj A pointer to m0_obj.
* @param req Representing a request to RM.
* @param clink A link which will listen on m0_rm_lock_req::rlr_chan
* channel for the signal of completion.
* @retval 0 On success.
*/
int m0_obj_read_lock_get(struct m0_obj *obj,
struct m0_rm_lock_req *req,
struct m0_clink *clink);
/**
* Acquires the read lock for the object.
* Recursive locking is not supported.
* This is a blocking function.
* Locks don't conflict among requests for read lock.
*
* This is a wrapper over m0_obj_read_lock_get_sync();
*
* @pre m0_obj_init()
* @pre m0_obj_lock_init()
* @param obj A pointer to m0_obj.
* @param req Representing a request to RM.
* @retval 0 On success.
*/
int m0_obj_read_lock_get_sync(struct m0_obj *obj,
struct m0_rm_lock_req *req);
/**
* Releases the RM lock for the object.
*
* @param req Representing a request to RM.
*/
void m0_obj_lock_put(struct m0_rm_lock_req *req);
/**
* Sets application-manipulable operation parameters.
*
* @param op Operation to be setup with callback functions.
* @param cbs Callback functions.
* @param linger The absolute time by which delays should be limited.
* If linger < m0_time_now(), the op is executed as soon as possible.
*
* @pre op != NULL
* @pre op->op_sm.sm_state == M0_OS_INITIALISED
*/
void m0_op_setup(struct m0_op *op,
const struct m0_op_ops *cbs,
m0_time_t linger);
/**
* Launches a collection of operations. Operations must belong to the same
* m0_ instances.
*
* @note the launched operations may be in other states than
* M0_OS_LAUNCHED by the time this call returns.
*
* @param op Array of operations to be launched.
* @param nr Number of operations.
*
* @pre ergo(op != NULL)
* @pre m0_forall(i, nr, op[i] != NULL)
* @pre m0_forall(i, nr, op[i]->op_sm.sm_state == M0_OS_INITIALISED)
* @pre m0_forall(i, nr, m0_entity_type_is_valid(op[i]->op_entity))
* @post m0_forall(i, nr, op[i]->op_sm.sm_state >= M0_OS_LAUNCHED)
*/
void m0_op_launch(struct m0_op **op, uint32_t nr);
/**
* Waits until the operation reaches a desired state.
*
* @param bits Bitmask of states based on m0_op_state. M0_BITS() macro
* should be used to build a bitmask. *
* @param op Single operation to wait on.
* @param to Absolute timeout for the wait.
*
* @code
* // Wait until the operation completes, 10 seconds max.
* result = m0_op_wait(op, M0_BITS(M0_OS_STABLE,
* M0_OS_FAILED),
* m0_time_from_now(10, 0));
* if (result == -ETIMEDOUT)
* // Timed out.
* else if (result == 0) {
* // Wait completed in time.
* if (op->op_sm.sm_state == M0_OS_STABLE) {
* ...
* } else {
* M0_ASSERT(op->op_sm.sm_state == M0_OS_FAILED);
* ...
* }
* } else {
* // Some other error.
* }
* @endcode
*
* @pre op != NULL
* @pre bits != 0
* @pre (bits & ~M0_BITS(M0_OS_LAUNCHED, M0_OS_EXECUTED,
* M0_OS_STABLE, M0_OS_FAILED)) == 0
*/
int32_t m0_op_wait(struct m0_op *op, uint64_t bits, m0_time_t to);
/**
* Cancels client operations. Caller is expected to wait
* for operation to move to one of the terminal states. The process of
* cancellation does not guarantee restoring an object to any consistent
* state and is left to application. Eg. cancellation of "create" operation
* does not invoke "unlink" operation internally, and application shall
* restore the consistency by either "unlinking" the object or trying
* to recreate the same.
* @TODO: Revisit the logic once DTM0 lands into dev.
*
* @param op collection of operations to cancel.
*
* @pre op != NULL
* @pre cancellation callback is defined for every operation.
*/
void m0_op_cancel(struct m0_op **op, uint32_t nr);
/**
* Asks the implementation to speed up progress of this operation toward
* stability.
*
* The implementation is free to either honour this call by modifying various
* internal caching and queuing policies to process the operation with less
* delays, or to ignore this call altogether. This call may incur resource
* under-utilisation and other overheads.
*
* @param op Operation to be kicked.
*
* @pre op != NULL
* @pre op->op_sm.sm_state >= M0_OS_INITIALISED
*/
void m0_op_kick(struct m0_op *op);
/**
* An API to return the return code from an op.
*
* This is basically a function that abstracts the return code member access
* for applications using client.
*
* @param op Operation whose return code is to be accessed.
*
* @pre op != NULL
*/
int32_t m0_rc(const struct m0_op *op);
/**
* Finalises a complete operation. The state machine will be moved to
* M0_OS_UNINITIALISED.
*
* @param op Operation being finalised.
*
* @pre op != NULL
* @pre M0_IN(op->op_sm.sm_state, (M0_OS_INITIALISED,
* M0_OS_STABLE, M0_OS_FAILED))
*/
void m0_op_fini(struct m0_op *op);
/**
* Frees a complete operation, allocated by the implementation.
*
* @param op Operation being freed.
*
* @pre op != NULL
* pre op->op_sm.sm_state == M0_OS_UNINITIALISED
*/
void m0_op_free(struct m0_op *op);
void m0_container_init(struct m0_container *con,
struct m0_realm *parent,
const struct m0_uint128 *id,
struct m0_client *instance);
void m0_epoch_init (struct m0_epoch *epoch,
struct m0_realm *parent,
const struct m0_uint128 *id);
void m0__dtx_init (struct m0__dtx *dtx,
struct m0_realm *parent,
const struct m0_uint128 *id);
/**
* Initialises a client object so that it can be created or deleted, or have
* read, write, alloc and free operations executed on it.
*
* The size of data and parity buffer (m0_obj::ob_attr::oa_bshift) is
* set to default value 'M0_DEFAULT_BUF_SHIFT'.
*
* If layout_id == 0, then this object will be set with optimal layout id
* according to the object size set in m0_obj::ob_attr::oa_buf_size.
* If Object size is not set, then this object will be set with
* default layout id (See struct m0_obj_attr).
*
* @param obj The object to initialise.
* @param parent The realm operations on this object will be part of.
* @param id The identifier assigned by the application to this object.
* @param layout_id The layout id assigned by the application to this object.
*
* @pre obj != NULL
* @pre parent != NULL
* @pre id != NULL && m0_uint128_cmp(&M0_ID_APP, id) < 0
*/
void m0_obj_init(struct m0_obj *obj,
struct m0_realm *parent,
const struct m0_uint128 *id,
uint64_t layout_id);
/**
* Finalises an obj, leading to finilise entity and to free any additiona
* memory allocated to represent it.
*
* @param obj Pointer to the object to finalise.
*
* @pre obj != NULL
*/
void m0_obj_fini(struct m0_obj *obj);
/**
* Initialises the index corresponding to a given object.
*
* Keys in this index are 64-bit block offsets (in BE representation, with
* lexicographic ordering) and the values are battrs (and maybe data?) for the
* block.
*
* The index structure, initialised by this function, provides access to object
* data through client index interface.
*
* @post m0_uint128_eq(&idx->in_entity.en_id, &obj->ob_entity.en_id)
*/
void m0_obj_idx_init(struct m0_idx *idx,
const struct m0_obj *obj);
/**
* Initialises object operation.
*
* @param obj Object the operation is targeted to.
* @param opcode Operation code for the operation.
* @param ext Extents in the object, measured in blocks.
* @param data Application buffers for the operation.
* @param attr Application buffers for block attributes.
* @param mask Attribute mask.
* @param[in, out] op Pointer to the operation pointer. If the operation pointer
* is NULL, client will allocate one. Otherwise, client will
* check the operation and make sure it is reusable for this
* operation.
*
* @return 0 for successful initialisation of operation. Otherwise
* standard linux system error code.
*
* @remarks "data" defines buffers from which data are read on WRITE and
* written to on READ.
*
* @remarks "attr" and "mask" together define which block attributes are read
* or written.
*
* @remarks The application can provide a pre-allocated operation. Otherwise,
* a new operation is allocated by this entry point, which eventually must be
* explicitely freed by the app.
*
* @pre obj != NULL
* @pre M0_IN(opcode, (M0_OC_READ, M0_OC_WRITE,
* M0_OC_ALLOC, M0_OC_FREE))
* @pre ext != NULL
* @pre obj->ob_attr.oa_bshift >= M0_MIN_BUF_SHIFT
* @pre m0_vec_count(&ext->iv_vec) % (1ULL << obj->ob_attr.oa_bshift) == 0
* @pre op != NULL
* @pre ergo(M0_IN(opcode, (M0_OC_READ, M0_OC_WRITE)),
* data != NULL && attr != NULL &&
* m0_vec_count(&ext->iv_vec) == m0_vec_count(&data->ov_vec) &&
* m0_vec_count(&attr->ov_vec) == 8 * m0_no_of_bits_set(mask) *
* (m0_vec_count(&ext->iv_vec) >> obj->ob_attr.oa_bshift)
* @pre ergo(M0_IN(opcode, (M0_OC_ALLOC, M0_OC_FREE)),
* data == NULL && attr == NULL && mask == 0)
* @pre ergo(opcode == M0_OC_READ, M0_IN(flags, (0, M0_OOF_NOHOLE)))
* @pre ergo(opcode != M0_OC_READ, M0_IN(flags, (0, M0_OOF_SYNC)))
*
* @post ergo(*op != NULL, *op->op_code == opcode &&
* *op->op_sm.sm_state == M0_OS_INITIALISED)
*/
int m0_obj_op(struct m0_obj *obj,
enum m0_obj_opcode opcode,
struct m0_indexvec *ext,
struct m0_bufvec *data,
struct m0_bufvec *attr,
uint64_t mask,
uint32_t flags,
struct m0_op **op);
/**
* Initialises client index in a given realm.
*
* Notes for M0_IDX_DIX index service type:
* 'id' should be a valid motr fid of type 'x' (see m0_dix_fid_type). Zero fid
* container is reserved for distributed meta-indices and shouldn't be used for
* user indices, i.e. indices with M0_FID_TINIT('x', 0, *) fids are reserved.
*
* @code
* struct m0_fid fid = M0_FID_TINIT('x', 1, 1);
*
* m0_idx_init(&idx, &realm, (struct m0_uint128 *)&fid);
* @endcode
*
* Non-distributed indices (having fid type 'i') are going to be supported in
* future.
*/
void m0_idx_init(struct m0_idx *idx,
struct m0_realm *parent,
const struct m0_uint128 *id);
void m0_idx_fini(struct m0_idx *idx);
/**
* Initialises an index operation.
*
* For M0_IC_NEXT operation arguments should be as follows:
* - 'keys' buffer vector first element should contain a starting key and other
* elements should be set to NULL. Buffer vector size indicates number of
* records to return.
* Starting key can be NULL. In this case starting key is treated as the
* smallest possible key of the index. If starting key doesn't exist in the
* index, then retrieved records will start with the smallest key following
* the starting key. Otherwise, a record corresponding to the starting key
* will be included in a result.
* - 'vals' vector should be at least of the same size as 'keys' and should
* contain NULLs. After successful operation completion retrieved index
* records are stored in 'keys' and 'vals' buffer vectors. If some error
* occurred during i-th index record retrieval then rcs[i] != 0. -ENOENT error
* means that there are no more records to return.
*
* For M0_IC_GET operation arguments should be as follows:
* - 'keys' buffer vector should contain keys for records being requested.
* At least one key should be specified and no NULL keys are allowed.
* - 'vals' vector should be at least of the same size as 'keys' and should
* contain NULLs. After successful operation completion retrieved record
* values are stored in 'vals' buffer vector. If some value retrieval has
* failed, then corresponding element in 'rcs' array != 0.
*
* 'rcs' holds array of per-item return codes for the operation. It should be
* allocated by user with a size of at least 'keys->ov_vec.v_nr' elements. For
* example, 6 records with keys k0...k5 were requested through GET request with
* k3 being absent in the index. After operation completion rcs[3] will be
* -ENOENT and rcs[0,1,2,4,5] will be 0.
*
* Per-item return codes are more fine-grained than global operation return
* code (op->op_sm.sm_rc). On operation completion the global return code
* is set to negative value if it's impossible to process any item (invalid
* index fid, lost RPC connection, etc.).
* - If the operation global return code is 0, then user should check per-item
* return codes.
* - If the operation global return code is not 0, then per-item return codes
* are undefined.
*
* 'rcs' argument is mandatory for all operations except M0_IC_LOOKUP.
*
* For M0_CLOVIC_IC_PUT flags argument may be set.
* - 'flags' is a bit-mask of m0_op_idx_flags enum. M0_OIF_OVERWRITE and
* M0_OIF_SYNC_WAIT are supported for now.
* If M0_OIF_OVERWRITE flag is set then records with existing keys are
* overwritten, otherwise operation returns -EEXIST for existing keys.
* If M0_OIF_SYNC_WAIT flag is set then it ensures that reply would be sent
* only when transaction is persisted. This flag can only be used
* with M0_IC_PUT or M0_IC_DEL.
*
* @pre idx != NULL
* @pre M0_IN(opcode, (M0_IC_LOOKUP, M0_IC_LIST,
* M0_IC_GET, M0_IC_PUT,
* M0_IC_DEL, M0_IC_NEXT))
* @pre ergo(*op != NULL, *op->op_size >= sizeof **op)
* @pre ergo(opcode == M0_IC_LOOKUP, rcs != NULL)
* @pre ergo(opcode != M0_IC_LOOKUP, keys != NULL)
* @pre M0_IN(opcode, (M0_IC_DEL,
* M0_IC_LOOKUP,
* M0_IC_LIST)) == (vals == NULL)
* @pre ergo(opcode == M0_IC_LIST,
* m0_forall(i, keys->ov_vec.v_nr,
* keys->ov_vec.v_count[i] == sizeof(struct m0_uint128)))
* @pre ergo(opcode == M0_IC_GET, keys->ov_vec.v_nr != 0)
* @pre ergo(opcode == M0_IC_GET,
* m0_forall(i, keys->ov_vec.v_nr, keys->ov_buf[i] != NULL))
* @pre ergo(flags == M0_OIF_SYNC_WAIT,
* M0_IN(opcode, (M0_IC_PUT, M0_IC_DEL)))
* @pre ergo(vals != NULL, keys->ov_vec.v_nr == vals->ov_vec.v_nr)
* @post ergo(result == 0, *op != NULL && *op->op_code == opcode &&
* *op->op_sm.sm_state == M0_OS_INITIALISED)
*/
/**
* @todo For now 'rcs' may be NULL if index backend is not Motr KVS
* and operation code is not M0_IC_GET.
* All backends should be updated to fill 'rcs' for all operation codes.
*/
int m0_idx_op(struct m0_idx *idx,
enum m0_idx_opcode opcode,
struct m0_bufvec *keys,
struct m0_bufvec *vals,
int32_t *rcs,
uint32_t flags,
struct m0_op **op);
void m0_realm_create(struct m0_realm *realm,
uint64_t wcount, uint64_t rcount,
struct m0_op **op);
void m0_realm_open(struct m0_realm *realm,
uint64_t wcount, uint64_t rcount,
struct m0_op **op);
void m0_realm_close(struct m0_realm *realm,
uint64_t wcount, uint64_t rcount,
struct m0_op **op);
/**
* Sets an operation to create or delete an entity.
*
* @param pool Specify the pool to store the entity if it is not NULL,
* otherwise a pool selected by internal policy is used.
* @param entity In-memory representation of the entity that is to be created.
* @param[out] op Pointer to the operation. The operation can be pre-allocated
* by the application. Otherwise, this entry point will allocate it if succeed.
* @return 0 for success, (*op)->op_sm.sm_rc otherwise.
*
* @pre entity != NULL
* @pre op != NULL
*/
/**@{*/
int m0_entity_create(struct m0_fid *pool,
struct m0_entity *entity,
struct m0_op **op);
int m0_entity_delete(struct m0_entity *entity,
struct m0_op **op);
/**@}*/
/**
* Sets an operation to open an entity.
*
* @param entity The entity that needs to be opened.
* @param[out] op Pointer to the operation which can be pre-allocated by the
* application. Else, this entry point will allocate it if succeed.
* @return 0 for success, (*op)->op_sm.sm_rc otherwise
*
* @pre entity != NULL
* @pre op != NULL
*/
int m0_entity_open(struct m0_entity *entity,
struct m0_op **op);
/**
* Finalises an entity, freeing any additional memory allocated to represent it.
*
* @param entity Pointer to the entity to finalise.
*
* @pre entity != NULL
* @pre entity->en_sm.sm_state == M0_ES_INIT
*/
void m0_entity_fini(struct m0_entity *entity);
/**
* Returns the maximum size a client operation is expected to be.
* If pre-allocating 'struct m0_op's, allocations smaller than this
* size may be rejected with EMSGSIZE
*/
size_t m0_op_maxsize(void);
/**
* Initialises state machine types et al.
*
* @param m0c Where to store the allocated instance.
* @param conf client configuration parameters.
* @param init_m0 Indicate whether or not Motr needs to be initialised.
* @return 0 for success, anything else for an error.
*
* @pre m0c must point to a NULL struct m0_client *.
* @pre local_ep must not be NULL or the empty string.
*/
int m0_client_init(struct m0_client **m0c,
struct m0_config *conf,
bool init_m0);
/**
* Finalises client, finalise state machine group et al.
*
* @pre (m0c != NULL).
*/
void m0_client_fini(struct m0_client *m0c, bool fini_m0);
/**
* Returns the process fid of the motr instance.
*
* @param m0c The client instance being queried.
* @param proc_fid The returned process fid.
* @return 0 for success and valid process fid is stored in proc_fid,
* anything else for an error.
*/
void m0_process_fid(const struct m0_client *m0c,
struct m0_fid *proc_fid);
/**
* Allocates and initialises an SYNC operation.
*
* @param sop A new SYNC op is created, entities and ops can be added
* into this SYNC op once it's initialised.
* @return 0 for success, anything else for an error.
*/
int m0_sync_op_init(struct m0_op **sop);
/**
* Adds an entity to SYNC op.
*
* @param sop The SYNC op where an entity is added to.
* @param entity The entity to be SYNC-ed.
* @return 0 for success, anything else for an error.
*/
int m0_sync_entity_add(struct m0_op *sop,
struct m0_entity *ent);
/**
* Adds an `op` to SYNC op.
*
* @param sop The SYNC op where an entity is added to.
* @param op The operation to be SYNC-ed.
* @return 0 for success, anything else for an error.
*/
int m0_sync_op_add(struct m0_op *sop,
struct m0_op *op);
/**
* Blocking version of entity sync API, corresponding to m0t1fs_fsync()
* in m0t1fs.
*
* @param ent The object is going to be sync'ed.
* @return 0 for success, anything else for an error.
*/
int m0_entity_sync(struct m0_entity *ent);
/**
* Motr sync instance entry point, corresponding to m0t1fs_sync_fs()
* in m0t1fs.
*
* @param m0c The Motr instance is going to be sync'ed.
* @param wait Ask client to wait till pending tx's are done if set to
* be "ture".
* @return 0 for success, anything else for an error.
*/
int m0_sync(struct m0_client *m0c, bool wait);
/**
* Maps a unit size to a layout id defined in Motr.
*
* @param unit_size Parity group unit size set. Only those unit sizes defined
* in layout/layout_pver.c are valid.
* @return 0 for invalid unit sizes and layout id for valid unit sizes.
*
*/
uint64_t m0_obj_unit_size_to_layout_id(int unit_size);
/**
* Maps a layout id to unit size.
*
* @param layout_id The layout id to query. The layout_id must be one of the valid
* layout ids defined in Motr.
* @return The corresponding unit size of queried layout id.
*
*/
int m0_obj_layout_id_to_unit_size(uint64_t layout_id);
uint64_t m0_client_layout_id(const struct m0_client *instance);
/**
* Gets the layout type of an object.
*
* @param obj The object to query.
* @return The layout type of object in question.
*/
enum m0_client_layout_type m0_obj_layout_type(struct m0_obj *obj);
/**
* Add layer to the composite layout.
*
* @param layout The layout to add to.
* @param sub_obj The sub object corresponds to the new layer. The API requires
* object argument instead of its identifier as Motr
* internally requires some object attributes to construct
* the composite layout.
* @param priority The layer's priority which is used to select which layer an
* IO request goes to.
* @return 0 for success, anything else for an error.
*/
int m0_composite_layer_add(struct m0_client_layout *layout,
struct m0_obj *sub_obj, int priority);
/**
* Delete layer from the composite layout.
*
* @param layout The layout to delete from.
* @param subobj_id The id of the sub-object (layer) to delete.
*/
void m0_composite_layer_del(struct m0_client_layout *layout,
struct m0_uint128 subobj_id);
/**
* Returns an in-memory index representation for extents in a composite layer.
*
* @param layer_id The composite layer in question.
* @param write True for extents for WRITE, false for extents for READ.
* @param idx The returned index.
* @return 0 for success, anything else for an error.
*/
int m0_composite_layer_idx(struct m0_uint128 layer_id,
bool write, struct m0_idx *idx);
/**
* Helper APIs to copy and transform a layer key/value to/from buffer.
* m0_composite_layer_idx_key_to_buf() transforms original key
* to a representation in lexicographical order.
*/
int m0_composite_layer_idx_key_to_buf(
struct m0_composite_layer_idx_key *key,
void **out_kbuf, m0_bcount_t *out_klen);
void m0_composite_layer_idx_key_from_buf(
struct m0_composite_layer_idx_key *key,
void *kbuf);
int m0_composite_layer_idx_val_to_buf(
struct m0_composite_layer_idx_val *val,
void **out_vbuf, m0_bcount_t *out_vlen);
void m0_composite_layer_idx_val_from_buf(
struct m0_composite_layer_idx_val *val,
void *vbuf);
/**
* Initialises layout operation.
*
* @param obj The object which the layout is belong to.
* @param layout Layout the operation is targeted to.
* @param opcode Operation code for the operation.
* @param[out] op Pointer to the operation pointer. If the operation pointer is
* NULL, motr will allocate one. Otherwise, motr will check
* the operation and make sure it is reusable for this operation.
*/
int m0_client_layout_op(struct m0_obj *obj,
enum m0_entity_opcode opcode,
struct m0_client_layout *layout,
struct m0_op **op);
/**
* Note: current version only support capturing pdclust layout for an object.
*
* To capture the layout for an object, an application has to issue LAYOUT_GET
* op first to retrieve the object's layout.
*/
int m0_client_layout_capture(struct m0_client_layout *layout,
struct m0_obj *obj,
struct m0_client_layout **out);
/* Allocate/free in-memory layout data struct for an object. */
struct m0_client_layout*
m0_client_layout_alloc(enum m0_client_layout_type type);
void m0_client_layout_free(struct m0_client_layout *layout);
//** @} end of client group */
#include "motr/idx.h" /* export m0_idx operations and services to client. */
#include "cas/cas.h"
#endif /* __MOTR_CLIENT_H__ */
/*
* Local variables:
* c-indentation-style: "K&R"
* c-basic-offset: 8
* tab-width: 8
* fill-column: 80
* scroll-step: 1
* End:
*/
/*
* vim: tabstop=8 shiftwidth=8 noexpandtab textwidth=80 nowrap
*/
| 35.930811 | 82 | 0.665453 | [
"object",
"vector",
"transform"
] |
9a7c8929f0da680e73c5025a34dccb97a12c5634 | 620 | h | C | HongKZH_IOS/Classes/MyCircle/MyCircleView/MyCocleHeadView.h | wuruijie/LXZAPP | 15b8739bb4bee3f1665f0c841cce79bde0fe920e | [
"Apache-2.0"
] | 2 | 2019-05-09T18:32:14.000Z | 2020-04-23T08:38:58.000Z | HongKZH_IOS/Classes/MyCircle/MyCircleView/MyCocleHeadView.h | wuruijie/LXZAPP | 15b8739bb4bee3f1665f0c841cce79bde0fe920e | [
"Apache-2.0"
] | null | null | null | HongKZH_IOS/Classes/MyCircle/MyCircleView/MyCocleHeadView.h | wuruijie/LXZAPP | 15b8739bb4bee3f1665f0c841cce79bde0fe920e | [
"Apache-2.0"
] | 2 | 2019-05-27T15:47:28.000Z | 2019-08-23T06:43:01.000Z | //
// MyCocleHeadView.h
// HongKZH_IOS
//
// Created by wanghui on 2018/9/10.
// Copyright © 2018年 hkzh. All rights reserved.
//
#import <UIKit/UIKit.h>
@class HKMyCircleData;
@protocol MyCocleHeadViewDelegate <NSObject>
@optional
-(void)toVcheadBtnClick;
-(void)toAddGroup;
-(void)gotoShoppingVc:(NSInteger)tag;
-(void)swichSenderTag:(NSInteger)index;
-(void)pushTopPostWithPostId:(NSString *)postId;
-(void)pushNoticeWithPostId:(NSString *)postId;
@end
@interface MyCocleHeadView : UIView
@property (nonatomic, strong)HKMyCircleData *model;
@property (nonatomic,weak) id<MyCocleHeadViewDelegate> delegate;
@end
| 23.846154 | 64 | 0.766129 | [
"model"
] |
9a7e527079b222b8d5f91fcd602f480d277018b9 | 3,243 | h | C | src/card/base/CardConnectionWorker.h | Governikus/AusweisApp2-Omapi | 0d563e61cb385492cef96c2542d50a467e003259 | [
"Apache-2.0"
] | 1 | 2019-06-06T11:58:51.000Z | 2019-06-06T11:58:51.000Z | src/card/base/CardConnectionWorker.h | ckahlo/AusweisApp2-Omapi | 5141b82599f9f11ae32ff7221b6de3b885e6e5f9 | [
"Apache-2.0"
] | 1 | 2022-01-28T11:08:59.000Z | 2022-01-28T12:05:33.000Z | src/card/base/CardConnectionWorker.h | ckahlo/AusweisApp2-Omapi | 5141b82599f9f11ae32ff7221b6de3b885e6e5f9 | [
"Apache-2.0"
] | 3 | 2019-06-06T11:58:14.000Z | 2021-11-15T23:32:04.000Z | /*!
* \brief Worker for \ref CardConnection that will do the job in \ref ReaderManagerWorker
*
* \copyright Copyright (c) 2014-2019 Governikus GmbH & Co. KG, Germany
*/
#pragma once
#include "asn1/SecurityInfos.h"
#include "CardReturnCode.h"
#include "CommandApdu.h"
#include "Commands.h"
#include "EstablishPaceChannel.h"
#include "FileRef.h"
#include "pace/SecureMessaging.h"
#include "Reader.h"
#include "ResponseApdu.h"
#include "SmartCardDefinitions.h"
#include <QByteArray>
namespace governikus
{
/*!
* This class represents a connection to a smart card.
*/
class CardConnectionWorker
: public QObject
, public QEnableSharedFromThis<CardConnectionWorker>
{
private:
Q_OBJECT
/*!
* The connection talks to the Card held by the Reader
*/
QPointer<Reader> mReader;
/*!
* Object performing the cryptography needed by a secure messaging channel
*/
QScopedPointer<SecureMessaging> mSecureMessaging;
bool hasCard() const;
inline QSharedPointer<const EFCardAccess> getEfCardAccess() const;
private Q_SLOTS:
void onReaderInfoChanged(const QString& pReaderName);
protected:
/*!
* The Card hold by the Reader is expected to be connected.
* The connection is closed, when the CardConnection is destroyed.
*/
CardConnectionWorker(Reader* pReader);
/*!
* Destroys the CardConnection and disconnects from the card.
*/
virtual ~CardConnectionWorker();
public:
static QSharedPointer<CardConnectionWorker> create(Reader* pReader);
Q_INVOKABLE ReaderInfo getReaderInfo() const;
void setPukInoperative();
virtual CardReturnCode updateRetryCounter();
virtual CardReturnCode readFile(const FileRef& pFileRef, QByteArray& pFileContent);
virtual CardReturnCode transmit(const CommandApdu& pCommandApdu, ResponseApdu& pResponseApdu);
/*!
* Performs PACE and establishes a PACE channel.
* If the Reader is a basic reader and the PACE channel is successfully established, the subsequent transmits will be secured using, secure messaging.
* I. e., a secure messaging channel is established.
*/
virtual CardReturnCode establishPaceChannel(PacePasswordId pPasswordId,
const QString& pPasswordValue,
EstablishPaceChannelOutput& pChannelOutput);
/*!
* Performs PACE and establishes a PACE channel for later terminal authentication.
* If the Reader is a basic reader and the PACE channel is successfully established, the subsequent transmits will be secured using, secure messaging.
* I. e., a secure messaging channel is established.
*/
virtual CardReturnCode establishPaceChannel(PacePasswordId pPasswordId,
const QString& pPasswordValue,
const QByteArray& pChat,
const QByteArray& pCertificateDescription,
EstablishPaceChannelOutput& pChannelOutput);
/*!
* Destroys a previously established PACE channel.
*/
virtual CardReturnCode destroyPaceChannel();
/*!
* Destroys an established secure messaging channel, if there is one.
*/
Q_INVOKABLE virtual bool stopSecureMessaging();
virtual CardReturnCode setEidPin(const QString& pNewPin, quint8 pTimeoutSeconds, ResponseApdu& pResponseApdu);
Q_SIGNALS:
void fireReaderInfoChanged(const ReaderInfo& pReaderInfo);
};
} // namespace governikus
| 28.699115 | 152 | 0.758557 | [
"object"
] |
9a81f67e1c6caa22f83a0f5e4cb7594004acf84b | 2,804 | h | C | Export/macos/obj/include/dsHelper/flatInterleave/core/_Flat3x7/Flat3x7_Impl_.h | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | Export/macos/obj/include/dsHelper/flatInterleave/core/_Flat3x7/Flat3x7_Impl_.h | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | Export/macos/obj/include/dsHelper/flatInterleave/core/_Flat3x7/Flat3x7_Impl_.h | TrilateralX/TrilateralLimeTriangle | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.2.0-rc.1+cb30bd580
#ifndef INCLUDED_dsHelper_flatInterleave_core__Flat3x7_Flat3x7_Impl_
#define INCLUDED_dsHelper_flatInterleave_core__Flat3x7_Flat3x7_Impl_
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS4(dsHelper,flatInterleave,core,_Flat3x7,Flat3x7_Impl_)
HX_DECLARE_CLASS2(lime,utils,ArrayBufferView)
namespace dsHelper{
namespace flatInterleave{
namespace core{
namespace _Flat3x7{
class HXCPP_CLASS_ATTRIBUTES Flat3x7_Impl__obj : public ::hx::Object
{
public:
typedef ::hx::Object super;
typedef Flat3x7_Impl__obj OBJ_;
Flat3x7_Impl__obj();
public:
enum { _hx_ClassId = 0x14ae6bdf };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="dsHelper.flatInterleave.core._Flat3x7.Flat3x7_Impl_")
{ 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,"dsHelper.flatInterleave.core._Flat3x7.Flat3x7_Impl_"); }
inline static ::hx::ObjectPtr< Flat3x7_Impl__obj > __new() {
::hx::ObjectPtr< Flat3x7_Impl__obj > __this = new Flat3x7_Impl__obj();
__this->__construct();
return __this;
}
inline static ::hx::ObjectPtr< Flat3x7_Impl__obj > __alloc(::hx::Ctx *_hx_ctx) {
Flat3x7_Impl__obj *__this = (Flat3x7_Impl__obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(Flat3x7_Impl__obj), false, "dsHelper.flatInterleave.core._Flat3x7.Flat3x7_Impl_"));
*(void **)__this = Flat3x7_Impl__obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~Flat3x7_Impl__obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("Flat3x7_Impl_",d9,ae,cc,d6); }
static Float readItem( ::lime::utils::ArrayBufferView this1,int k);
static ::Dynamic readItem_dyn();
static Float writeItem( ::lime::utils::ArrayBufferView this1,int k,Float v);
static ::Dynamic writeItem_dyn();
static ::lime::utils::ArrayBufferView _new(int len);
static ::Dynamic _new_dyn();
static int get_index( ::lime::utils::ArrayBufferView this1);
static ::Dynamic get_index_dyn();
static int set_index( ::lime::utils::ArrayBufferView this1,int id);
static ::Dynamic set_index_dyn();
static ::lime::utils::ArrayBufferView getArray( ::lime::utils::ArrayBufferView this1);
static ::Dynamic getArray_dyn();
};
} // end namespace dsHelper
} // end namespace flatInterleave
} // end namespace core
} // end namespace _Flat3x7
#endif /* INCLUDED_dsHelper_flatInterleave_core__Flat3x7_Flat3x7_Impl_ */
| 33.783133 | 168 | 0.75535 | [
"object"
] |
9a82137bfa06bca4bbab996a4c7749cf5abf6544 | 4,059 | h | C | native/cocos/renderer/frame-graph/DevicePassResourceTable.h | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/renderer/frame-graph/DevicePassResourceTable.h | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/renderer/frame-graph/DevicePassResourceTable.h | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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
#include "Handle.h"
#include "RenderTargetAttachment.h"
#include "Resource.h"
#include "base/std/container/unordered_map.h"
namespace cc {
namespace framegraph {
class PassNode;
class FrameGraph;
class DevicePass;
class DevicePassResourceTable final {
public:
DevicePassResourceTable() = default;
~DevicePassResourceTable() = default;
DevicePassResourceTable(const DevicePassResourceTable &) = delete;
DevicePassResourceTable(DevicePassResourceTable &&) = delete;
DevicePassResourceTable &operator=(const DevicePassResourceTable &) = delete;
DevicePassResourceTable &operator=(DevicePassResourceTable &&) = delete;
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
getRead(TypedHandle<Type> handle) const noexcept;
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
getWrite(TypedHandle<Type> handle) const noexcept;
gfx::RenderPass *getRenderPass() const { return _renderPass; }
uint32_t getSubpassIndex() const { return _subpassIndex; }
private:
using ResourceDictionary = ccstd::unordered_map<Handle, gfx::GFXObject *, Handle::Hasher>;
static gfx::GFXObject *get(const ResourceDictionary &from, Handle handle) noexcept;
void extract(const FrameGraph &graph, const PassNode *passNode, ccstd::vector<const gfx::Texture *> const &renderTargets) noexcept;
static void extract(const FrameGraph &graph, ccstd::vector<Handle> const &from, ResourceDictionary &to, bool ignoreRenderTarget, ccstd::vector<const gfx::Texture *> const &renderTargets) noexcept;
ResourceDictionary _reads{};
ResourceDictionary _writes{};
gfx::RenderPass *_renderPass{nullptr};
uint32_t _subpassIndex{0U};
friend class DevicePass;
};
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
DevicePassResourceTable::getRead(TypedHandle<Type> handle) const noexcept {
return static_cast<typename Type::DeviceResource *>(get(_reads, handle));
}
template <typename Type>
std::enable_if_t<std::is_base_of<gfx::GFXObject, typename Type::DeviceResource>::value, typename Type::DeviceResource *>
DevicePassResourceTable::getWrite(TypedHandle<Type> handle) const noexcept {
return static_cast<typename Type::DeviceResource *>(get(_writes, handle));
}
} // namespace framegraph
} // namespace cc
| 45.1 | 211 | 0.720867 | [
"vector"
] |
9a84b5c7e9e7b9edf4ed7eb79358fc502ce4292c | 13,326 | c | C | src/fclist.c | tizenorg/framework.graphics.fontconfig | 7b69fc5828a18f6bc05c9fa1351556574f6ddd11 | [
"DOC"
] | null | null | null | src/fclist.c | tizenorg/framework.graphics.fontconfig | 7b69fc5828a18f6bc05c9fa1351556574f6ddd11 | [
"DOC"
] | null | null | null | src/fclist.c | tizenorg/framework.graphics.fontconfig | 7b69fc5828a18f6bc05c9fa1351556574f6ddd11 | [
"DOC"
] | null | null | null | /*
* fontconfig/src/fclist.c
*
* Copyright © 2000 Keith Packard
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of the author(s) not be used in
* advertising or publicity pertaining to distribution of the software without
* specific, written prior permission. The authors make no
* representations about the suitability of this software for any purpose. It
* is provided "as is" without express or implied warranty.
*
* THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include "fcint.h"
#include <stdlib.h>
FcObjectSet *
FcObjectSetCreate (void)
{
FcObjectSet *os;
os = (FcObjectSet *) malloc (sizeof (FcObjectSet));
if (!os)
return 0;
FcMemAlloc (FC_MEM_OBJECTSET, sizeof (FcObjectSet));
os->nobject = 0;
os->sobject = 0;
os->objects = 0;
return os;
}
FcBool
FcObjectSetAdd (FcObjectSet *os, const char *object)
{
int s;
const char **objects;
int high, low, mid, c;
if (os->nobject == os->sobject)
{
s = os->sobject + 4;
if (os->objects)
objects = (const char **) realloc ((void *) os->objects,
s * sizeof (const char *));
else
objects = (const char **) malloc (s * sizeof (const char *));
if (!objects)
return FcFalse;
if (os->sobject)
FcMemFree (FC_MEM_OBJECTPTR, os->sobject * sizeof (const char *));
FcMemAlloc (FC_MEM_OBJECTPTR, s * sizeof (const char *));
os->objects = objects;
os->sobject = s;
}
high = os->nobject - 1;
low = 0;
mid = 0;
c = 1;
object = (char *)FcStrStaticName ((FcChar8 *)object);
while (low <= high)
{
mid = (low + high) >> 1;
c = os->objects[mid] - object;
if (c == 0)
return FcTrue;
if (c < 0)
low = mid + 1;
else
high = mid - 1;
}
if (c < 0)
mid++;
memmove (os->objects + mid + 1, os->objects + mid,
(os->nobject - mid) * sizeof (const char *));
os->objects[mid] = object;
os->nobject++;
return FcTrue;
}
void
FcObjectSetDestroy (FcObjectSet *os)
{
if (os->objects)
{
FcMemFree (FC_MEM_OBJECTPTR, os->sobject * sizeof (const char *));
free ((void *) os->objects);
}
FcMemFree (FC_MEM_OBJECTSET, sizeof (FcObjectSet));
free (os);
}
FcObjectSet *
FcObjectSetVaBuild (const char *first, va_list va)
{
FcObjectSet *ret;
FcObjectSetVapBuild (ret, first, va);
return ret;
}
FcObjectSet *
FcObjectSetBuild (const char *first, ...)
{
va_list va;
FcObjectSet *os;
va_start (va, first);
FcObjectSetVapBuild (os, first, va);
va_end (va);
return os;
}
/*
* Font must have a containing value for every value in the pattern
*/
static FcBool
FcListValueListMatchAny (FcValueListPtr patOrig, /* pattern */
FcValueListPtr fntOrig) /* font */
{
FcValueListPtr pat, fnt;
for (pat = patOrig; pat != NULL; pat = FcValueListNext(pat))
{
for (fnt = fntOrig; fnt != NULL; fnt = FcValueListNext(fnt))
{
/*
* make sure the font 'contains' the pattern.
* (OpListing is OpContains except for strings
* where it requires an exact match)
*/
if (FcConfigCompareValue (&fnt->value,
FcOpListing,
&pat->value))
break;
}
if (fnt == NULL)
return FcFalse;
}
return FcTrue;
}
static FcBool
FcListValueListEqual (FcValueListPtr v1orig,
FcValueListPtr v2orig)
{
FcValueListPtr v1, v2;
for (v1 = v1orig; v1 != NULL; v1 = FcValueListNext(v1))
{
for (v2 = v2orig; v2 != NULL; v2 = FcValueListNext(v2))
if (FcValueEqual (FcValueCanonicalize(&(v1)->value),
FcValueCanonicalize(&(v2)->value)))
break;
if (v2 == NULL)
return FcFalse;
}
for (v2 = v2orig; v2 != NULL; v2 = FcValueListNext(v2))
{
for (v1 = v1orig; v1 != NULL; v1 = FcValueListNext(v1))
if (FcValueEqual (FcValueCanonicalize(&v1->value),
FcValueCanonicalize(&v2->value)))
break;
if (v1 == NULL)
return FcFalse;
}
return FcTrue;
}
static FcBool
FcListPatternEqual (FcPattern *p1,
FcPattern *p2,
FcObjectSet *os)
{
int i;
FcPatternElt *e1, *e2;
for (i = 0; i < os->nobject; i++)
{
e1 = FcPatternObjectFindElt (p1, FcObjectFromName (os->objects[i]));
e2 = FcPatternObjectFindElt (p2, FcObjectFromName (os->objects[i]));
if (!e1 && !e2)
continue;
if (!e1 || !e2)
return FcFalse;
if (!FcListValueListEqual (FcPatternEltValues(e1),
FcPatternEltValues(e2)))
return FcFalse;
}
return FcTrue;
}
/*
* FcTrue iff all objects in "p" match "font"
*/
FcBool
FcListPatternMatchAny (const FcPattern *p,
const FcPattern *font)
{
int i;
for (i = 0; i < p->num; i++)
{
FcPatternElt *pe = &FcPatternElts(p)[i];
FcPatternElt *fe = FcPatternObjectFindElt (font, pe->object);
if (!fe)
return FcFalse;
if (!FcListValueListMatchAny (FcPatternEltValues(pe), /* pat elts */
FcPatternEltValues(fe))) /* font elts */
return FcFalse;
}
return FcTrue;
}
static FcChar32
FcListMatrixHash (const FcMatrix *m)
{
int xx = (int) (m->xx * 100),
xy = (int) (m->xy * 100),
yx = (int) (m->yx * 100),
yy = (int) (m->yy * 100);
return ((FcChar32) xx) ^ ((FcChar32) xy) ^ ((FcChar32) yx) ^ ((FcChar32) yy);
}
static FcChar32
FcListValueHash (FcValue *value)
{
FcValue v = FcValueCanonicalize(value);
switch (v.type) {
case FcTypeVoid:
return 0;
case FcTypeInteger:
return (FcChar32) v.u.i;
case FcTypeDouble:
return (FcChar32) (int) v.u.d;
case FcTypeString:
return FcStrHashIgnoreCase (v.u.s);
case FcTypeBool:
return (FcChar32) v.u.b;
case FcTypeMatrix:
return FcListMatrixHash (v.u.m);
case FcTypeCharSet:
return FcCharSetCount (v.u.c);
case FcTypeFTFace:
return (long) v.u.f;
case FcTypeLangSet:
return FcLangSetHash (v.u.l);
}
return 0;
}
static FcChar32
FcListValueListHash (FcValueListPtr list)
{
FcChar32 h = 0;
while (list != NULL)
{
h = h ^ FcListValueHash (&list->value);
list = FcValueListNext(list);
}
return h;
}
static FcChar32
FcListPatternHash (FcPattern *font,
FcObjectSet *os)
{
int n;
FcPatternElt *e;
FcChar32 h = 0;
for (n = 0; n < os->nobject; n++)
{
e = FcPatternObjectFindElt (font, FcObjectFromName (os->objects[n]));
if (e)
h = h ^ FcListValueListHash (FcPatternEltValues(e));
}
return h;
}
typedef struct _FcListBucket {
struct _FcListBucket *next;
FcChar32 hash;
FcPattern *pattern;
} FcListBucket;
#define FC_LIST_HASH_SIZE 4099
typedef struct _FcListHashTable {
int entries;
FcListBucket *buckets[FC_LIST_HASH_SIZE];
} FcListHashTable;
static void
FcListHashTableInit (FcListHashTable *table)
{
table->entries = 0;
memset (table->buckets, '\0', sizeof (table->buckets));
}
static void
FcListHashTableCleanup (FcListHashTable *table)
{
int i;
FcListBucket *bucket, *next;
for (i = 0; i < FC_LIST_HASH_SIZE; i++)
{
for (bucket = table->buckets[i]; bucket; bucket = next)
{
next = bucket->next;
FcPatternDestroy (bucket->pattern);
FcMemFree (FC_MEM_LISTBUCK, sizeof (FcListBucket));
free (bucket);
}
table->buckets[i] = 0;
}
table->entries = 0;
}
static int
FcGetDefaultObjectLangIndex (FcPattern *font, FcObject object)
{
FcChar8 *lang = FcGetDefaultLang ();
FcPatternElt *e = FcPatternObjectFindElt (font, object);
FcValueListPtr v;
FcValue value;
int idx = -1;
int i;
if (e)
{
for (v = FcPatternEltValues(e), i = 0; v; v = FcValueListNext(v), ++i)
{
value = FcValueCanonicalize (&v->value);
if (value.type == FcTypeString)
{
FcLangResult res = FcLangCompare (value.u.s, lang);
if (res == FcLangEqual)
return i;
if (res == FcLangDifferentCountry && idx < 0)
idx = i;
}
}
}
return (idx > 0) ? idx : 0;
}
static FcBool
FcListAppend (FcListHashTable *table,
FcPattern *font,
FcObjectSet *os)
{
int o;
FcPatternElt *e;
FcValueListPtr v;
FcChar32 hash;
FcListBucket **prev, *bucket;
int familyidx = -1;
int fullnameidx = -1;
int styleidx = -1;
int defidx = 0;
int idx;
hash = FcListPatternHash (font, os);
for (prev = &table->buckets[hash % FC_LIST_HASH_SIZE];
(bucket = *prev); prev = &(bucket->next))
{
if (bucket->hash == hash &&
FcListPatternEqual (bucket->pattern, font, os))
return FcTrue;
}
bucket = (FcListBucket *) malloc (sizeof (FcListBucket));
if (!bucket)
goto bail0;
FcMemAlloc (FC_MEM_LISTBUCK, sizeof (FcListBucket));
bucket->next = 0;
bucket->hash = hash;
bucket->pattern = FcPatternCreate ();
if (!bucket->pattern)
goto bail1;
for (o = 0; o < os->nobject; o++)
{
if (!strcmp (os->objects[o], FC_FAMILY) || !strcmp (os->objects[o], FC_FAMILYLANG))
{
if (familyidx < 0)
familyidx = FcGetDefaultObjectLangIndex (font, FC_FAMILYLANG_OBJECT);
defidx = familyidx;
}
else if (!strcmp (os->objects[o], FC_FULLNAME) || !strcmp (os->objects[o], FC_FULLNAMELANG))
{
if (fullnameidx < 0)
fullnameidx = FcGetDefaultObjectLangIndex (font, FC_FULLNAMELANG_OBJECT);
defidx = fullnameidx;
}
else if (!strcmp (os->objects[o], FC_STYLE) || !strcmp (os->objects[o], FC_STYLELANG))
{
if (styleidx < 0)
styleidx = FcGetDefaultObjectLangIndex (font, FC_STYLELANG_OBJECT);
defidx = styleidx;
}
else
defidx = 0;
e = FcPatternObjectFindElt (font, FcObjectFromName (os->objects[o]));
if (e)
{
for (v = FcPatternEltValues(e), idx = 0; v;
v = FcValueListNext(v), ++idx)
{
if (!FcPatternAdd (bucket->pattern,
os->objects[o],
FcValueCanonicalize(&v->value), defidx != idx))
goto bail2;
}
}
}
*prev = bucket;
++table->entries;
return FcTrue;
bail2:
FcPatternDestroy (bucket->pattern);
bail1:
FcMemFree (FC_MEM_LISTBUCK, sizeof (FcListBucket));
free (bucket);
bail0:
return FcFalse;
}
FcFontSet *
FcFontSetList (FcConfig *config,
FcFontSet **sets,
int nsets,
FcPattern *p,
FcObjectSet *os)
{
FcFontSet *ret;
FcFontSet *s;
int f;
int set;
FcListHashTable table;
int i;
FcListBucket *bucket;
int destroy_os = 0;
if (!config)
{
if (!FcInitBringUptoDate ())
goto bail0;
config = FcConfigGetCurrent ();
if (!config)
goto bail0;
}
FcListHashTableInit (&table);
if (!os)
{
os = FcObjectGetSet ();
destroy_os = 1;
}
/*
* Walk all available fonts adding those that
* match to the hash table
*/
for (set = 0; set < nsets; set++)
{
s = sets[set];
if (!s)
continue;
for (f = 0; f < s->nfont; f++)
if (FcListPatternMatchAny (p, /* pattern */
s->fonts[f])) /* font */
if (!FcListAppend (&table, s->fonts[f], os))
goto bail1;
}
#if 0
{
int max = 0;
int full = 0;
int ents = 0;
int len;
for (i = 0; i < FC_LIST_HASH_SIZE; i++)
{
if ((bucket = table.buckets[i]))
{
len = 0;
for (; bucket; bucket = bucket->next)
{
ents++;
len++;
}
if (len > max)
max = len;
full++;
}
}
printf ("used: %d max: %d avg: %g\n", full, max,
(double) ents / FC_LIST_HASH_SIZE);
}
#endif
/*
* Walk the hash table and build
* a font set
*/
ret = FcFontSetCreate ();
if (!ret)
goto bail0;
for (i = 0; i < FC_LIST_HASH_SIZE; i++)
while ((bucket = table.buckets[i]))
{
if (!FcFontSetAdd (ret, bucket->pattern))
goto bail2;
table.buckets[i] = bucket->next;
FcMemFree (FC_MEM_LISTBUCK, sizeof (FcListBucket));
free (bucket);
}
return ret;
bail2:
FcFontSetDestroy (ret);
bail1:
FcListHashTableCleanup (&table);
bail0:
if (destroy_os)
FcObjectSetDestroy (os);
return 0;
}
FcFontSet *
FcFontList (FcConfig *config,
FcPattern *p,
FcObjectSet *os)
{
FcFontSet *sets[2];
int nsets;
if (!config)
{
if (!FcInitBringUptoDate ())
return 0;
config = FcConfigGetCurrent ();
if (!config)
return 0;
}
nsets = 0;
if (config->fonts[FcSetSystem])
sets[nsets++] = config->fonts[FcSetSystem];
if (config->fonts[FcSetApplication])
sets[nsets++] = config->fonts[FcSetApplication];
return FcFontSetList (config, sets, nsets, p, os);
}
#define __fclist__
#include "fcaliastail.h"
#undef __fclist__
| 23.055363 | 93 | 0.610236 | [
"object"
] |
9a8bab99bba9c58b4dc8d4adc985fbeea9596f9e | 5,277 | h | C | Code/Numerics/NeuralNetworks/itkRBFLayer.h | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | 1 | 2017-07-31T18:41:02.000Z | 2017-07-31T18:41:02.000Z | Code/Numerics/NeuralNetworks/itkRBFLayer.h | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | Code/Numerics/NeuralNetworks/itkRBFLayer.h | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRBFLayer.h
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.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.
=========================================================================*/
#ifndef __itkRBFLayer_h
#define __itkRBFLayer_h
#include "itkCompletelyConnectedWeightSet.h"
#include "itkLayerBase.h"
#include "itkObject.h"
#include "itkMacro.h"
#include "itkRadialBasisFunctionBase.h"
#ifdef ITK_USE_REVIEW_STATISTICS
#include "itkEuclideanDistanceMetric.h"
#else
#include "itkEuclideanDistance.h"
#endif
namespace itk
{
namespace Statistics
{
template<class TMeasurementVector, class TTargetVector>
class RBFLayer : public LayerBase<TMeasurementVector, TTargetVector>
{
public:
typedef RBFLayer Self;
typedef LayerBase<TMeasurementVector, TTargetVector> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkTypeMacro(RBFLayer, LayerBase);
itkNewMacro(Self);
typedef typename Superclass::ValueType ValueType;
typedef typename Superclass::ValuePointer ValuePointer;
typedef vnl_vector<ValueType> NodeVectorType;
typedef typename Superclass::InternalVectorType InternalVectorType;
typedef typename Superclass::OutputVectorType OutputVectorType;
typedef typename Superclass::LayerInterfaceType LayerInterfaceType;
typedef CompletelyConnectedWeightSet<TMeasurementVector,TTargetVector>
WeightSetType;
typedef typename Superclass::WeightSetInterfaceType WeightSetInterfaceType;
typedef typename Superclass::InputFunctionInterfaceType InputFunctionInterfaceType;
typedef typename Superclass::TransferFunctionInterfaceType TransferFunctionInterfaceType;
//Distance Metric
#ifdef ITK_USE_REVIEW_STATISTICS
typedef EuclideanDistanceMetric<InternalVectorType> DistanceMetricType;
#else
typedef EuclideanDistance<InternalVectorType> DistanceMetricType;
#endif
typedef typename DistanceMetricType::Pointer DistanceMetricPointer;
typedef RadialBasisFunctionBase<ValueType> RBFType;
//Member Functions
itkGetConstReferenceMacro(RBF_Dim, unsigned int);
void SetRBF_Dim(unsigned int size);
virtual void SetNumberOfNodes(unsigned int numNodes);
virtual ValueType GetInputValue(unsigned int i) const;
void SetInputValue(unsigned int i, ValueType value);
virtual ValueType GetOutputValue(unsigned int) const;
virtual void SetOutputValue(unsigned int, ValueType);
virtual ValueType * GetOutputVector();
void SetOutputVector(TMeasurementVector value);
virtual void ForwardPropagate();
virtual void ForwardPropagate(TMeasurementVector input);
virtual void BackwardPropagate();
virtual void BackwardPropagate(TTargetVector itkNotUsed(errors)){};
virtual void SetOutputErrorValues(TTargetVector);
virtual ValueType GetOutputErrorValue(unsigned int node_id) const;
virtual ValueType GetInputErrorValue(unsigned int node_id) const;
virtual ValueType * GetInputErrorVector();
virtual void SetInputErrorValue(ValueType, unsigned int node_id);
//TMeasurementVector GetCenter(int i);
InternalVectorType GetCenter(unsigned int i) const;
void SetCenter(TMeasurementVector c,unsigned int i);
ValueType GetRadii(unsigned int i) const;
void SetRadii(ValueType c,unsigned int i);
virtual ValueType Activation(ValueType);
virtual ValueType DActivation(ValueType);
/** Set/Get the bias */
itkSetMacro( Bias, ValueType );
itkGetConstReferenceMacro( Bias, ValueType );
void SetDistanceMetric(DistanceMetricType* f);
itkGetObjectMacro( DistanceMetric, DistanceMetricType );
itkGetConstObjectMacro( DistanceMetric, DistanceMetricType );
itkSetMacro(NumClasses,unsigned int);
itkGetConstReferenceMacro(NumClasses,unsigned int);
void SetRBF(RBFType* f);
itkGetObjectMacro(RBF, RBFType);
itkGetConstObjectMacro(RBF, RBFType);
protected:
RBFLayer();
virtual ~RBFLayer();
/** Method to print the object. */
virtual void PrintSelf( std::ostream& os, Indent indent ) const;
private:
NodeVectorType m_NodeInputValues;
NodeVectorType m_NodeOutputValues;
NodeVectorType m_InputErrorValues;
NodeVectorType m_OutputErrorValues;
typename DistanceMetricType::Pointer m_DistanceMetric;
std::vector<InternalVectorType> m_Centers; // ui....uc
InternalVectorType m_Radii;
unsigned int m_NumClasses;
ValueType m_Bias;
unsigned int m_RBF_Dim;
typename RBFType::Pointer m_RBF;
};
} // end namespace Statistics
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkRBFLayer.txx"
#endif
#endif
| 34.266234 | 91 | 0.735835 | [
"object",
"vector"
] |
9a9191ed7a95787642f4a8cb19b1952ff855c9df | 5,326 | h | C | third_party/libSBML-5.10.0-Source/src/sbml/packages/comp/validator/CompValidator.h | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | null | null | null | third_party/libSBML-5.10.0-Source/src/sbml/packages/comp/validator/CompValidator.h | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | null | null | null | third_party/libSBML-5.10.0-Source/src/sbml/packages/comp/validator/CompValidator.h | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | null | null | null | /**
* @file CompValidator.h
* @brief Base class for SBML CompValidators
* @author Sarah Keating
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2014 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright 2011-2012 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution and
* also available online as http://sbml.org/software/libsbml/license.html
* ---------------------------------------------------------------------- -->
*
* @class CompValidator
* @sbmlbrief{comp} Entry point for libSBML's implementation of SBML
* validation rules for the “comp” package.
*
* @htmlinclude not-sbml-warning.html
*
* LibSBML implements facilities for verifying that a given SBML document
* is valid according to the SBML specifications; it also exposes the
* validation interface so that user programs and SBML Level 3 package
* authors may use the facilities to implement new validators. There are
* two main interfaces to libSBML's validation facilities, based on the
* classes CompValidator and SBMLCompValidator.
*
* The CompValidator class is the basis of the system for validating an SBML
* document against the validation rules defined in the SBML
* specifications. The scheme used by CompValidator relies is compact and uses
* the @em visitor programming pattern, but it relies on C/C++ features and
* is not directly accessible from language bindings. SBMLCompValidator offers
* a framework for straightforward class-based extensibility, so that user
* code can subclass SBMLCompValidator to implement new validation systems,
* different validators can be introduced or turned off at run-time, and
* interfaces can be provided in the libSBML language bindings.
* SBMLCompValidator can call CompValidator functionality internally (as is the
* case in the current implementation of SBMLInternalCompValidator) or use
* entirely different implementation approaches, as necessary.
*/
#ifndef CompValidator_h
#define CompValidator_h
#ifdef __cplusplus
/** @cond doxygenLibsbmlInternal */
#include <list>
#include <string>
/** @endcond */
#include <sbml/SBMLError.h>
#include <sbml/validator/Validator.h>
LIBSBML_CPP_NAMESPACE_BEGIN
class VConstraint;
struct CompValidatorConstraints;
class SBMLDocument;
class CompValidator : public Validator
{
public:
/**
* Constructor; creates a new CompValidator object for the given
* category of validation.
*
* @param category code indicating the kind of validations that this
* validator will perform. The category code value must be
* @if clike taken from the enumeration #SBMLErrorCategory_t @endif@~
* @if java one of of the values from the set of constants whose names
* begin with the characters <code>LIBSBML_CAT_</code> in the interface
* class {@link libsbmlConstants}.@endif@~
* @if python one of of the values from the set of constants whose names
* begin with the characters <code>LIBSBML_CAT_</code> in the interface
* class @link libsbml libsbml@endlink.@endif@~
*/
CompValidator ( SBMLErrorCategory_t category = LIBSBML_CAT_SBML );
/**
* Destroys this CompValidator object.
*/
virtual ~CompValidator ();
/**
* Initializes this CompValidator object.
*
* When creating a subclass of CompValidator, override this method to add
* your own validation code.
*/
virtual void init () = 0;
/**
* Adds the given VContraint object to this validator.
*
* @param c the VConstraint ("validator constraint") object to add.
*/
virtual void addConstraint (VConstraint* c);
/**
* Validates the given SBML document.
*
* @param d the SBMLDocument object to be validated.
*
* @return the number of validation failures that occurred. The objects
* describing the actual failures can be retrieved using getFailures().
*/
virtual unsigned int validate (const SBMLDocument& d);
/**
* Validates the SBML document located at the given file name.
*
* @param filename the path to the file to be read and validated.
*
* @return the number of validation failures that occurred. The objects
* describing the actual failures can be retrieved using getFailures().
*/
virtual unsigned int validate (const std::string& filename);
protected:
/** @cond doxygenLibsbmlInternal */
CompValidatorConstraints* mCompConstraints;
friend class CompValidatingVisitor;
/** @endcond */
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#endif /* CompValidator_h */
| 33.2875 | 79 | 0.718551 | [
"object"
] |
9a955b5e8f5f2c5ff90e13e2fd15f72983d384a5 | 22,700 | c | C | source/blender/render/intern/source/external_engine.c | wangyxuan/blender | d09289ff7a8e8fe6d4da6b46dd153033d7cfd426 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2019-06-27T09:30:33.000Z | 2019-11-05T12:41:21.000Z | source/blender/render/intern/source/external_engine.c | tin2tin/blender | 42e0cf1a026bbde7e3a65157de5c54106e948cd8 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/render/intern/source/external_engine.c | tin2tin/blender | 42e0cf1a026bbde7e3a65157de5c54106e948cd8 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2006 Blender Foundation.
* All rights reserved.
*/
/** \file
* \ingroup render
*/
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "MEM_guardedalloc.h"
#include "BLT_translation.h"
#include "BLI_listbase.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"
#include "DNA_object_types.h"
#include "BKE_camera.h"
#include "BKE_global.h"
#include "BKE_colortools.h"
#include "BKE_layer.h"
#include "BKE_node.h"
#include "BKE_report.h"
#include "BKE_scene.h"
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_debug.h"
#include "DEG_depsgraph_query.h"
#include "RNA_access.h"
#ifdef WITH_PYTHON
# include "BPY_extern.h"
#endif
#include "RE_engine.h"
#include "RE_pipeline.h"
#include "RE_bake.h"
#include "DRW_engine.h"
#include "initrender.h"
#include "renderpipeline.h"
#include "render_types.h"
#include "render_result.h"
/* Render Engine Types */
ListBase R_engines = {NULL, NULL};
void RE_engines_init(void)
{
DRW_engines_register();
}
void RE_engines_exit(void)
{
RenderEngineType *type, *next;
DRW_engines_free();
for (type = R_engines.first; type; type = next) {
next = type->next;
BLI_remlink(&R_engines, type);
if (!(type->flag & RE_INTERNAL)) {
if (type->ext.free) {
type->ext.free(type->ext.data);
}
MEM_freeN(type);
}
}
}
void RE_engines_register(RenderEngineType *render_type)
{
if (render_type->draw_engine) {
DRW_engine_register(render_type->draw_engine);
}
BLI_addtail(&R_engines, render_type);
}
RenderEngineType *RE_engines_find(const char *idname)
{
RenderEngineType *type;
type = BLI_findstring(&R_engines, idname, offsetof(RenderEngineType, idname));
if (!type) {
type = BLI_findstring(&R_engines, "BLENDER_EEVEE", offsetof(RenderEngineType, idname));
}
return type;
}
bool RE_engine_is_external(Render *re)
{
return (re->engine && re->engine->type && re->engine->type->render);
}
bool RE_engine_is_opengl(RenderEngineType *render_type)
{
/* TODO refine? Can we have ogl render engine without ogl render pipeline? */
return (render_type->draw_engine != NULL) && DRW_engine_render_support(render_type->draw_engine);
}
/* Create, Free */
RenderEngine *RE_engine_create(RenderEngineType *type)
{
return RE_engine_create_ex(type, false);
}
RenderEngine *RE_engine_create_ex(RenderEngineType *type, bool use_for_viewport)
{
RenderEngine *engine = MEM_callocN(sizeof(RenderEngine), "RenderEngine");
engine->type = type;
if (use_for_viewport) {
engine->flag |= RE_ENGINE_USED_FOR_VIEWPORT;
BLI_threaded_malloc_begin();
}
BLI_mutex_init(&engine->update_render_passes_mutex);
return engine;
}
void RE_engine_free(RenderEngine *engine)
{
#ifdef WITH_PYTHON
if (engine->py_instance) {
BPY_DECREF_RNA_INVALIDATE(engine->py_instance);
}
#endif
if (engine->flag & RE_ENGINE_USED_FOR_VIEWPORT) {
BLI_threaded_malloc_end();
}
BLI_mutex_end(&engine->update_render_passes_mutex);
MEM_freeN(engine);
}
/* Render Results */
static RenderPart *get_part_from_result(Render *re, RenderResult *result)
{
RenderPart *pa;
for (pa = re->parts.first; pa; pa = pa->next) {
if (result->tilerect.xmin == pa->disprect.xmin - re->disprect.xmin &&
result->tilerect.ymin == pa->disprect.ymin - re->disprect.ymin &&
result->tilerect.xmax == pa->disprect.xmax - re->disprect.xmin &&
result->tilerect.ymax == pa->disprect.ymax - re->disprect.ymin) {
return pa;
}
}
return NULL;
}
RenderResult *RE_engine_begin_result(
RenderEngine *engine, int x, int y, int w, int h, const char *layername, const char *viewname)
{
Render *re = engine->re;
RenderResult *result;
rcti disprect;
/* ensure the coordinates are within the right limits */
CLAMP(x, 0, re->result->rectx);
CLAMP(y, 0, re->result->recty);
CLAMP(w, 0, re->result->rectx);
CLAMP(h, 0, re->result->recty);
if (x + w > re->result->rectx) {
w = re->result->rectx - x;
}
if (y + h > re->result->recty) {
h = re->result->recty - y;
}
/* allocate a render result */
disprect.xmin = x;
disprect.xmax = x + w;
disprect.ymin = y;
disprect.ymax = y + h;
result = render_result_new(re, &disprect, 0, RR_USE_MEM, layername, viewname);
/* todo: make this thread safe */
/* can be NULL if we CLAMP the width or height to 0 */
if (result) {
render_result_clone_passes(re, result, viewname);
RenderPart *pa;
/* Copy EXR tile settings, so pipeline knows whether this is a result
* for Save Buffers enabled rendering.
*/
result->do_exr_tile = re->result->do_exr_tile;
BLI_addtail(&engine->fullresult, result);
result->tilerect.xmin += re->disprect.xmin;
result->tilerect.xmax += re->disprect.xmin;
result->tilerect.ymin += re->disprect.ymin;
result->tilerect.ymax += re->disprect.ymin;
pa = get_part_from_result(re, result);
if (pa) {
pa->status = PART_STATUS_IN_PROGRESS;
}
}
return result;
}
void RE_engine_update_result(RenderEngine *engine, RenderResult *result)
{
Render *re = engine->re;
if (result) {
result->renlay = result->layers.first; /* weak, draws first layer always */
re->display_update(re->duh, result, NULL);
}
}
void RE_engine_add_pass(RenderEngine *engine,
const char *name,
int channels,
const char *chan_id,
const char *layername)
{
Render *re = engine->re;
if (!re || !re->result) {
return;
}
render_result_add_pass(re->result, name, channels, chan_id, layername, NULL);
}
void RE_engine_end_result(
RenderEngine *engine, RenderResult *result, bool cancel, bool highlight, bool merge_results)
{
Render *re = engine->re;
if (!result) {
return;
}
/* merge. on break, don't merge in result for preview renders, looks nicer */
if (!highlight) {
/* for exr tile render, detect tiles that are done */
RenderPart *pa = get_part_from_result(re, result);
if (pa) {
pa->status = (!cancel && merge_results) ? PART_STATUS_MERGED : PART_STATUS_RENDERED;
}
else if (re->result->do_exr_tile) {
/* if written result does not match any tile and we are using save
* buffers, we are going to get openexr save errors */
fprintf(stderr, "RenderEngine.end_result: dimensions do not match any OpenEXR tile.\n");
}
}
if (!cancel || merge_results) {
if (re->result->do_exr_tile) {
if (!cancel && merge_results) {
render_result_exr_file_merge(re->result, result, re->viewname);
}
}
else if (!(re->test_break(re->tbh) && (re->r.scemode & R_BUTS_PREVIEW))) {
render_result_merge(re->result, result);
}
/* draw */
if (!re->test_break(re->tbh)) {
result->renlay = result->layers.first; /* weak, draws first layer always */
re->display_update(re->duh, result, NULL);
}
}
/* free */
BLI_remlink(&engine->fullresult, result);
render_result_free(result);
}
RenderResult *RE_engine_get_result(RenderEngine *engine)
{
return engine->re->result;
}
/* Cancel */
bool RE_engine_test_break(RenderEngine *engine)
{
Render *re = engine->re;
if (re) {
return re->test_break(re->tbh);
}
return 0;
}
/* Statistics */
void RE_engine_update_stats(RenderEngine *engine, const char *stats, const char *info)
{
Render *re = engine->re;
/* stats draw callback */
if (re) {
re->i.statstr = stats;
re->i.infostr = info;
re->stats_draw(re->sdh, &re->i);
re->i.infostr = NULL;
re->i.statstr = NULL;
}
/* set engine text */
engine->text[0] = '\0';
if (stats && stats[0] && info && info[0]) {
BLI_snprintf(engine->text, sizeof(engine->text), "%s | %s", stats, info);
}
else if (info && info[0]) {
BLI_strncpy(engine->text, info, sizeof(engine->text));
}
else if (stats && stats[0]) {
BLI_strncpy(engine->text, stats, sizeof(engine->text));
}
}
void RE_engine_update_progress(RenderEngine *engine, float progress)
{
Render *re = engine->re;
if (re) {
CLAMP(progress, 0.0f, 1.0f);
re->progress(re->prh, progress);
}
}
void RE_engine_update_memory_stats(RenderEngine *engine, float mem_used, float mem_peak)
{
Render *re = engine->re;
if (re) {
re->i.mem_used = mem_used;
re->i.mem_peak = mem_peak;
}
}
void RE_engine_report(RenderEngine *engine, int type, const char *msg)
{
Render *re = engine->re;
if (re) {
BKE_report(engine->re->reports, type, msg);
}
else if (engine->reports) {
BKE_report(engine->reports, type, msg);
}
}
void RE_engine_set_error_message(RenderEngine *engine, const char *msg)
{
Render *re = engine->re;
if (re != NULL) {
RenderResult *rr = RE_AcquireResultRead(re);
if (rr) {
if (rr->error != NULL) {
MEM_freeN(rr->error);
}
rr->error = BLI_strdup(msg);
}
RE_ReleaseResult(re);
}
}
const char *RE_engine_active_view_get(RenderEngine *engine)
{
Render *re = engine->re;
return RE_GetActiveRenderView(re);
}
void RE_engine_active_view_set(RenderEngine *engine, const char *viewname)
{
Render *re = engine->re;
RE_SetActiveRenderView(re, viewname);
}
float RE_engine_get_camera_shift_x(RenderEngine *engine, Object *camera, bool use_spherical_stereo)
{
Render *re = engine->re;
/* When using spherical stereo, get camera shift without multiview,
* leaving stereo to be handled by the engine. */
if (use_spherical_stereo) {
re = NULL;
}
return BKE_camera_multiview_shift_x(re ? &re->r : NULL, camera, re->viewname);
}
void RE_engine_get_camera_model_matrix(RenderEngine *engine,
Object *camera,
bool use_spherical_stereo,
float *r_modelmat)
{
Render *re = engine->re;
/* When using spherical stereo, get model matrix without multiview,
* leaving stereo to be handled by the engine. */
if (use_spherical_stereo) {
re = NULL;
}
BKE_camera_multiview_model_matrix(
re ? &re->r : NULL, camera, re->viewname, (float(*)[4])r_modelmat);
}
bool RE_engine_get_spherical_stereo(RenderEngine *engine, Object *camera)
{
Render *re = engine->re;
return BKE_camera_multiview_spherical_stereo(re ? &re->r : NULL, camera) ? 1 : 0;
}
rcti *RE_engine_get_current_tiles(Render *re, int *r_total_tiles, bool *r_needs_free)
{
static rcti tiles_static[BLENDER_MAX_THREADS];
const int allocation_step = BLENDER_MAX_THREADS;
RenderPart *pa;
int total_tiles = 0;
rcti *tiles = tiles_static;
int allocation_size = BLENDER_MAX_THREADS;
BLI_rw_mutex_lock(&re->partsmutex, THREAD_LOCK_READ);
*r_needs_free = false;
if (re->engine && (re->engine->flag & RE_ENGINE_HIGHLIGHT_TILES) == 0) {
*r_total_tiles = 0;
BLI_rw_mutex_unlock(&re->partsmutex);
return NULL;
}
for (pa = re->parts.first; pa; pa = pa->next) {
if (pa->status == PART_STATUS_IN_PROGRESS) {
if (total_tiles >= allocation_size) {
/* Just in case we're using crazy network rendering with more
* workers than BLENDER_MAX_THREADS.
*/
allocation_size += allocation_step;
if (tiles == tiles_static) {
/* Can not realloc yet, tiles are pointing to a
* stack memory.
*/
tiles = MEM_mallocN(allocation_size * sizeof(rcti), "current engine tiles");
}
else {
tiles = MEM_reallocN(tiles, allocation_size * sizeof(rcti));
}
*r_needs_free = true;
}
tiles[total_tiles] = pa->disprect;
total_tiles++;
}
}
BLI_rw_mutex_unlock(&re->partsmutex);
*r_total_tiles = total_tiles;
return tiles;
}
RenderData *RE_engine_get_render_data(Render *re)
{
return &re->r;
}
/* Depsgraph */
static void engine_depsgraph_init(RenderEngine *engine, ViewLayer *view_layer)
{
Main *bmain = engine->re->main;
Scene *scene = engine->re->scene;
engine->depsgraph = DEG_graph_new(scene, view_layer, DAG_EVAL_RENDER);
DEG_debug_name_set(engine->depsgraph, "RENDER");
BKE_scene_graph_update_for_newframe(engine->depsgraph, bmain);
}
static void engine_depsgraph_free(RenderEngine *engine)
{
DEG_graph_free(engine->depsgraph);
engine->depsgraph = NULL;
}
void RE_engine_frame_set(RenderEngine *engine, int frame, float subframe)
{
if (!engine->depsgraph) {
return;
}
#ifdef WITH_PYTHON
BPy_BEGIN_ALLOW_THREADS;
#endif
Render *re = engine->re;
double cfra = (double)frame + (double)subframe;
CLAMP(cfra, MINAFRAME, MAXFRAME);
BKE_scene_frame_set(re->scene, cfra);
BKE_scene_graph_update_for_newframe(engine->depsgraph, re->main);
BKE_scene_camera_switch_update(re->scene);
#ifdef WITH_PYTHON
BPy_END_ALLOW_THREADS;
#endif
}
/* Bake */
void RE_bake_engine_set_engine_parameters(Render *re, Main *bmain, Scene *scene)
{
re->scene = scene;
re->main = bmain;
render_copy_renderdata(&re->r, &scene->r);
}
bool RE_bake_has_engine(Render *re)
{
RenderEngineType *type = RE_engines_find(re->r.engine);
return (type->bake != NULL);
}
bool RE_bake_engine(Render *re,
Depsgraph *depsgraph,
Object *object,
const int object_id,
const BakePixel pixel_array[],
const size_t num_pixels,
const int depth,
const eScenePassType pass_type,
const int pass_filter,
float result[])
{
RenderEngineType *type = RE_engines_find(re->r.engine);
RenderEngine *engine;
bool persistent_data = (re->r.mode & R_PERSISTENT_DATA) != 0;
/* set render info */
re->i.cfra = re->scene->r.cfra;
BLI_strncpy(re->i.scene_name, re->scene->id.name + 2, sizeof(re->i.scene_name) - 2);
re->i.totface = re->i.totvert = re->i.totstrand = re->i.totlamp = re->i.tothalo = 0;
/* render */
engine = re->engine;
if (!engine) {
engine = RE_engine_create(type);
re->engine = engine;
}
engine->flag |= RE_ENGINE_RENDERING;
/* TODO: actually link to a parent which shouldn't happen */
engine->re = re;
engine->resolution_x = re->winx;
engine->resolution_y = re->winy;
RE_parts_init(re);
engine->tile_x = re->r.tilex;
engine->tile_y = re->r.tiley;
if (type->bake) {
engine->depsgraph = depsgraph;
/* update is only called so we create the engine.session */
if (type->update) {
type->update(engine, re->main, engine->depsgraph);
}
type->bake(engine,
engine->depsgraph,
object,
pass_type,
pass_filter,
object_id,
pixel_array,
num_pixels,
depth,
result);
engine->depsgraph = NULL;
}
engine->tile_x = 0;
engine->tile_y = 0;
engine->flag &= ~RE_ENGINE_RENDERING;
BLI_rw_mutex_lock(&re->partsmutex, THREAD_LOCK_WRITE);
/* re->engine becomes zero if user changed active render engine during render */
if (!persistent_data || !re->engine) {
RE_engine_free(engine);
re->engine = NULL;
}
RE_parts_free(re);
BLI_rw_mutex_unlock(&re->partsmutex);
if (BKE_reports_contain(re->reports, RPT_ERROR)) {
G.is_break = true;
}
return true;
}
/* Render */
int RE_engine_render(Render *re, int do_all)
{
RenderEngineType *type = RE_engines_find(re->r.engine);
RenderEngine *engine;
bool persistent_data = (re->r.mode & R_PERSISTENT_DATA) != 0;
/* verify if we can render */
if (!type->render) {
return 0;
}
if ((re->r.scemode & R_BUTS_PREVIEW) && !(type->flag & RE_USE_PREVIEW)) {
return 0;
}
if (do_all && !(type->flag & RE_USE_POSTPROCESS)) {
return 0;
}
if (!do_all && (type->flag & RE_USE_POSTPROCESS)) {
return 0;
}
/* Lock drawing in UI during data phase. */
if (re->draw_lock) {
re->draw_lock(re->dlh, 1);
}
/* update animation here so any render layer animation is applied before
* creating the render result */
if ((re->r.scemode & (R_NO_FRAME_UPDATE | R_BUTS_PREVIEW)) == 0) {
render_update_anim_renderdata(re, &re->scene->r, &re->scene->view_layers);
}
/* create render result */
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
if (re->result == NULL || !(re->r.scemode & R_BUTS_PREVIEW)) {
int savebuffers = RR_USE_MEM;
if (re->result) {
render_result_free(re->result);
}
if ((type->flag & RE_USE_SAVE_BUFFERS) && (re->r.scemode & R_EXR_TILE_FILE)) {
savebuffers = RR_USE_EXR;
}
re->result = render_result_new(re, &re->disprect, 0, savebuffers, RR_ALL_LAYERS, RR_ALL_VIEWS);
}
BLI_rw_mutex_unlock(&re->resultmutex);
if (re->result == NULL) {
/* Clear UI drawing locks. */
if (re->draw_lock) {
re->draw_lock(re->dlh, 0);
}
/* Too small image is handled earlier, here it could only happen if
* there was no sufficient memory to allocate all passes.
*/
BKE_report(re->reports, RPT_ERROR, "Failed allocate render result, out of memory");
G.is_break = true;
return 1;
}
/* set render info */
re->i.cfra = re->scene->r.cfra;
BLI_strncpy(re->i.scene_name, re->scene->id.name + 2, sizeof(re->i.scene_name));
re->i.totface = re->i.totvert = re->i.totstrand = re->i.totlamp = re->i.tothalo = 0;
/* render */
engine = re->engine;
if (!engine) {
engine = RE_engine_create(type);
re->engine = engine;
}
engine->flag |= RE_ENGINE_RENDERING;
/* TODO: actually link to a parent which shouldn't happen */
engine->re = re;
if (re->flag & R_ANIMATION) {
engine->flag |= RE_ENGINE_ANIMATION;
}
if (re->r.scemode & R_BUTS_PREVIEW) {
engine->flag |= RE_ENGINE_PREVIEW;
}
engine->camera_override = re->camera_override;
engine->resolution_x = re->winx;
engine->resolution_y = re->winy;
RE_parts_init(re);
engine->tile_x = re->partx;
engine->tile_y = re->party;
if (re->result->do_exr_tile) {
render_result_exr_file_begin(re, engine);
}
/* Clear UI drawing locks. */
if (re->draw_lock) {
re->draw_lock(re->dlh, 0);
}
if (type->render) {
FOREACH_VIEW_LAYER_TO_RENDER_BEGIN (re, view_layer_iter) {
if (re->draw_lock) {
re->draw_lock(re->dlh, 1);
}
ViewLayer *view_layer = BLI_findstring(
&re->scene->view_layers, view_layer_iter->name, offsetof(ViewLayer, name));
engine_depsgraph_init(engine, view_layer);
if (type->update) {
type->update(engine, re->main, engine->depsgraph);
}
if (re->draw_lock) {
re->draw_lock(re->dlh, 0);
}
type->render(engine, engine->depsgraph);
/* Grease pencil render over previous render result.
*
* NOTE: External engine might have been requested to free its
* dependency graph, which is only allowed if there is no grease
* pencil (pipeline is taking care of that).
*/
if (!RE_engine_test_break(engine) && engine->depsgraph != NULL) {
DRW_render_gpencil(engine, engine->depsgraph);
}
engine_depsgraph_free(engine);
if (RE_engine_test_break(engine)) {
break;
}
}
FOREACH_VIEW_LAYER_TO_RENDER_END;
}
engine->tile_x = 0;
engine->tile_y = 0;
engine->flag &= ~RE_ENGINE_RENDERING;
render_result_free_list(&engine->fullresult, engine->fullresult.first);
BLI_rw_mutex_lock(&re->partsmutex, THREAD_LOCK_WRITE);
if (re->result->do_exr_tile) {
render_result_exr_file_end(re, engine);
}
/* re->engine becomes zero if user changed active render engine during render */
if (!persistent_data || !re->engine) {
RE_engine_free(engine);
re->engine = NULL;
}
if (re->r.scemode & R_EXR_CACHE_FILE) {
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
render_result_exr_file_cache_write(re);
BLI_rw_mutex_unlock(&re->resultmutex);
}
RE_parts_free(re);
BLI_rw_mutex_unlock(&re->partsmutex);
if (BKE_reports_contain(re->reports, RPT_ERROR)) {
G.is_break = true;
}
#ifdef WITH_FREESTYLE
if (re->r.mode & R_EDGE_FRS) {
RE_RenderFreestyleExternal(re);
}
#endif
return 1;
}
void RE_engine_update_render_passes(struct RenderEngine *engine,
struct Scene *scene,
struct ViewLayer *view_layer,
update_render_passes_cb_t callback,
void *callback_data)
{
if (!(scene && view_layer && engine && callback && engine->type->update_render_passes)) {
return;
}
BLI_mutex_lock(&engine->update_render_passes_mutex);
engine->update_render_passes_cb = callback;
engine->update_render_passes_data = callback_data;
engine->type->update_render_passes(engine, scene, view_layer);
engine->update_render_passes_cb = NULL;
engine->update_render_passes_data = NULL;
BLI_mutex_unlock(&engine->update_render_passes_mutex);
}
void RE_engine_register_pass(struct RenderEngine *engine,
struct Scene *scene,
struct ViewLayer *view_layer,
const char *name,
int channels,
const char *chanid,
int type)
{
if (!(scene && view_layer && engine && engine->update_render_passes_cb)) {
return;
}
engine->update_render_passes_cb(
engine->update_render_passes_data, scene, view_layer, name, channels, chanid, type);
}
void RE_engine_free_blender_memory(RenderEngine *engine)
{
/* Weak way to save memory, but not crash grease pencil.
*
* TODO(sergey): Find better solution for this.
* TODO(sergey): Try to find solution which does not involve looping over
* all the objects.
*/
if (DRW_render_check_grease_pencil(engine->depsgraph)) {
return;
}
DEG_graph_free(engine->depsgraph);
engine->depsgraph = NULL;
}
| 25.678733 | 99 | 0.651189 | [
"render",
"object",
"model"
] |
9a96a5fd45e4c48059ba8915f2108e4f9ac2aad7 | 3,776 | h | C | paddle/pten/kernels/funcs/common_shape.h | wwjiang007/Paddle | bdeb479c0edd1ab9bb5f696df3573dad63d67885 | [
"Apache-2.0"
] | null | null | null | paddle/pten/kernels/funcs/common_shape.h | wwjiang007/Paddle | bdeb479c0edd1ab9bb5f696df3573dad63d67885 | [
"Apache-2.0"
] | null | null | null | paddle/pten/kernels/funcs/common_shape.h | wwjiang007/Paddle | bdeb479c0edd1ab9bb5f696df3573dad63d67885 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include "paddle/pten/core/dense_tensor.h"
namespace pten {
namespace funcs {
inline void SetXShape(const DenseTensor &x, DenseTensor *xshape) {
const auto &in_dims = x.meta().dims;
std::vector<int64_t> xshape_dims(in_dims.size() + 1);
xshape_dims[0] = 0;
for (int i = 0; i < in_dims.size(); ++i) {
xshape_dims[i + 1] = in_dims[i];
}
xshape->ResizeAndAllocate(pten::framework::make_ddim(xshape_dims));
xshape->ResetLoD(x.meta().lod);
}
inline void GetBroadcastDimsArrays(const DDim &x_dims,
const DDim &y_dims,
int *x_dims_array,
int *y_dims_array,
int *out_dims_array,
const int max_dim,
const int axis) {
PADDLE_ENFORCE_GE(
axis,
0,
paddle::platform::errors::InvalidArgument(
"Axis should be great than or equal to 0, but received axis is %d.",
axis));
PADDLE_ENFORCE_LT(axis,
max_dim,
paddle::platform::errors::InvalidArgument(
"Axis should be less than %d, but received axis is %d.",
max_dim,
axis));
if (x_dims.size() > y_dims.size()) {
std::fill(y_dims_array, y_dims_array + axis, 1);
if (axis + y_dims.size() < max_dim) {
std::fill(y_dims_array + axis + y_dims.size(), y_dims_array + max_dim, 1);
}
std::copy(x_dims.Get(), x_dims.Get() + x_dims.size(), x_dims_array);
std::copy(y_dims.Get(), y_dims.Get() + y_dims.size(), y_dims_array + axis);
} else {
std::fill(x_dims_array, x_dims_array + axis, 1);
if (axis + x_dims.size() < max_dim) {
std::fill(x_dims_array + axis + x_dims.size(), x_dims_array + max_dim, 1);
}
std::copy(x_dims.Get(), x_dims.Get() + x_dims.size(), x_dims_array + axis);
std::copy(y_dims.Get(), y_dims.Get() + y_dims.size(), y_dims_array);
}
for (int i = 0; i < max_dim; i++) {
PADDLE_ENFORCE_EQ(
x_dims_array[i] == y_dims_array[i] || x_dims_array[i] <= 1 ||
y_dims_array[i] <= 1,
true,
paddle::platform::errors::InvalidArgument(
"Broadcast dimension mismatch. Operands could "
"not be broadcast together with the shape of X = [%s] and "
"the shape of Y = [%s]. Received [%d] in X is not equal to "
"[%d] in Y at i:%d.",
x_dims,
y_dims,
x_dims_array[i],
y_dims_array[i],
i));
if ((x_dims_array[i] > 1 || y_dims_array[i] > 1) ||
(x_dims_array[i] == 1 && y_dims_array[i] == 1)) {
out_dims_array[i] = (std::max)(x_dims_array[i], y_dims_array[i]);
} else {
out_dims_array[i] = -1;
}
}
}
inline void GetPrePostNumel(
const framework::DDim &dim, int axis, int *pre, int *n, int *post) {
*pre = 1;
*post = 1;
*n = dim[axis];
for (int i = 0; i < axis; ++i) {
(*pre) *= dim[i];
}
for (int i = axis + 1; i < dim.size(); ++i) {
(*post) *= dim[i];
}
}
} // namespace funcs
} // namespace pten
| 35.28972 | 80 | 0.574947 | [
"shape",
"vector"
] |
9a97ec8241c050bf7d42d36a3969cbfe2dd44c2e | 2,737 | h | C | src/libaten/renderer/_bdpt.h | nackdai/aten | 6d8ca0ddbf4ea77a87b1b5506d43d3a910cf9fef | [
"MIT"
] | 49 | 2018-02-04T07:13:52.000Z | 2021-11-23T16:44:17.000Z | src/libaten/renderer/_bdpt.h | nakdai/aten | f6de0840c1631bafbec3162da6a9af5767300e4d | [
"MIT"
] | 11 | 2020-01-21T01:40:20.000Z | 2022-02-06T08:14:34.000Z | src/libaten/renderer/_bdpt.h | nakdai/aten | f6de0840c1631bafbec3162da6a9af5767300e4d | [
"MIT"
] | 4 | 2018-10-28T22:19:27.000Z | 2021-03-26T09:27:36.000Z | #pragma once
#include "renderer/renderer.h"
#include "scene/scene.h"
#include "camera/camera.h"
#include "sampler/sampler.h"
namespace aten
{
class BDPT : public Renderer {
public:
BDPT() {}
~BDPT() {}
public:
virtual void render(
Destination& dst,
scene* scene,
camera* camera) override;
private:
struct Vertex {
vec3 pos;
vec3 nml;
hitable* obj{ nullptr };
material* mtrl{ nullptr };
Light* light{ nullptr };
real sampleLightPdf{ real(0) };
real u;
real v;
int x{ -1 };
int y{ -1 };
Vertex() {}
Vertex(
vec3 p,
vec3 n,
hitable* _obj,
material* _mtrl,
real _u, real _v,
int _x = -1, int _y = -1)
: pos(p), nml(n), obj(_obj), mtrl(_mtrl), u(_u), v(_v), x(_x), y(_y)
{}
Vertex(
vec3 p,
vec3 n,
hitable* _obj,
material* _mtrl,
Light* _light,
real lightPdf,
real _u, real _v)
: pos(p), nml(n), obj(_obj), mtrl(_mtrl), light(_light), sampleLightPdf(lightPdf), u(_u), v(_v)
{}
};
struct Result {
vec3 contrib;
int x{ -1 };
int y{ -1 };
CameraSampleResult camsample;
bool isStartFromPixel;
Result() {}
Result(const vec3& c, int _x, int _y, bool _isStartFromPixel)
: contrib(c), x(_x), y(_y), isStartFromPixel(_isStartFromPixel)
{}
};
vec3 trace(
bool isEyePath,
std::vector<Vertex>& vs,
uint32_t maxDepth,
const ray& r,
sampler* sampler,
scene* scene,
camera* camera);
Result genEyePath(
std::vector<Vertex>& vs,
int x, int y,
sampler* sampler,
scene* scene,
camera* camera);
Result genLightPath(
std::vector<Vertex>& vs,
Light* light,
sampler* sampler,
scene* scene,
camera* camera);
bool isConnectable(
scene* scene,
camera* cam,
const std::vector<Vertex>& eyepath,
const int numEye,
const std::vector<Vertex>& lightpath,
const int numLight,
int& px, int& py);
vec3 computeThroughput(
const std::vector<Vertex>& vs,
const CameraSampleResult& camsample,
camera* camera);
real BDPT::computePDF(
const std::vector<Vertex>& vs,
const CameraSampleResult& camsample,
camera* camera,
const int pathLenght,
const int specNumEye = -1,
const int specNumLight = -1);
real computeMISWeight(
const std::vector<Vertex>& vs,
const CameraSampleResult& camsample,
camera* camera,
const int numEyeVertices,
const int numLightVertices,
const int pathLength);
void combinePath(
std::vector<Result>& result,
const std::vector<Vertex>& eyepath,
const std::vector<Vertex>& lightpath,
scene* scene,
const CameraSampleResult& camsample,
camera* camera);
private:
uint32_t m_maxDepth{ 1 };
int m_width;
int m_height;
};
}
| 18.746575 | 99 | 0.630617 | [
"render",
"vector"
] |
9a9a96edaa71d3a3792bdbd905a6dec65b247f8d | 4,137 | h | C | services/viz/privileged/mojom/compositing/renderer_settings_mojom_traits.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | services/viz/privileged/mojom/compositing/renderer_settings_mojom_traits.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | services/viz/privileged/mojom/compositing/renderer_settings_mojom_traits.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 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 SERVICES_VIZ_PRIVILEGED_MOJOM_COMPOSITING_RENDERER_SETTINGS_MOJOM_TRAITS_H_
#define SERVICES_VIZ_PRIVILEGED_MOJOM_COMPOSITING_RENDERER_SETTINGS_MOJOM_TRAITS_H_
#include <vector>
#include "build/build_config.h"
#include "components/viz/common/display/renderer_settings.h"
#include "services/viz/privileged/cpp/overlay_strategy_mojom_traits.h"
#include "services/viz/privileged/mojom/compositing/renderer_settings.mojom-shared.h"
#include "ui/gfx/geometry/mojom/geometry_mojom_traits.h"
#if defined(USE_OZONE)
#include "components/viz/common/display/overlay_strategy.h"
#endif
namespace mojo {
template <>
struct StructTraits<viz::mojom::DebugRendererSettingsDataView,
viz::DebugRendererSettings> {
static bool tint_composited_content(const viz::DebugRendererSettings& input) {
return input.tint_composited_content;
}
static bool tint_composited_content_modulate(
const viz::DebugRendererSettings& input) {
return input.tint_composited_content_modulate;
}
static bool show_overdraw_feedback(const viz::DebugRendererSettings& input) {
return input.show_overdraw_feedback;
}
static bool show_dc_layer_debug_borders(
const viz::DebugRendererSettings& input) {
return input.show_dc_layer_debug_borders;
}
static bool show_aggregated_damage(const viz::DebugRendererSettings& input) {
return input.show_aggregated_damage;
}
static bool Read(viz::mojom::DebugRendererSettingsDataView data,
viz::DebugRendererSettings* out);
};
template <>
struct StructTraits<viz::mojom::RendererSettingsDataView,
viz::RendererSettings> {
static bool apply_simple_frame_rate_throttling(
const viz::RendererSettings& input) {
return input.apply_simple_frame_rate_throttling;
}
static bool allow_antialiasing(const viz::RendererSettings& input) {
return input.allow_antialiasing;
}
static bool force_antialiasing(const viz::RendererSettings& input) {
return input.force_antialiasing;
}
static bool force_blending_with_shaders(const viz::RendererSettings& input) {
return input.force_blending_with_shaders;
}
static bool partial_swap_enabled(const viz::RendererSettings& input) {
return input.partial_swap_enabled;
}
static bool should_clear_root_render_pass(
const viz::RendererSettings& input) {
return input.should_clear_root_render_pass;
}
static bool release_overlay_resources_after_gpu_query(
const viz::RendererSettings& input) {
return input.release_overlay_resources_after_gpu_query;
}
static int highp_threshold_min(const viz::RendererSettings& input) {
return input.highp_threshold_min;
}
static int slow_down_compositing_scale_factor(
const viz::RendererSettings& input) {
return input.slow_down_compositing_scale_factor;
}
static bool use_skia_renderer(const viz::RendererSettings& input) {
return input.use_skia_renderer;
}
static bool allow_overlays(const viz::RendererSettings& input) {
return input.allow_overlays;
}
static bool auto_resize_output_surface(const viz::RendererSettings& input) {
return input.auto_resize_output_surface;
}
static bool requires_alpha_channel(const viz::RendererSettings& input) {
return input.requires_alpha_channel;
}
#if defined(OS_ANDROID)
static gfx::Size initial_screen_size(const viz::RendererSettings& input) {
return input.initial_screen_size;
}
static gfx::ColorSpace color_space(const viz::RendererSettings& input) {
return input.color_space;
}
#endif
#if defined(USE_OZONE)
static std::vector<viz::OverlayStrategy> overlay_strategies(
const viz::RendererSettings& input) {
return input.overlay_strategies;
}
#endif
static bool Read(viz::mojom::RendererSettingsDataView data,
viz::RendererSettings* out);
};
} // namespace mojo
#endif // SERVICES_VIZ_PRIVILEGED_MOJOM_COMPOSITING_RENDERER_SETTINGS_MOJOM_TRAITS_H_
| 31.340909 | 86 | 0.772299 | [
"geometry",
"vector"
] |
9a9a9fd42afbb077be3bcfcf5ce50bed26ca80d3 | 11,502 | h | C | src/openms/include/OpenMS/FORMAT/DTA2DFile.h | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/include/OpenMS/FORMAT/DTA2DFile.h | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/include/OpenMS/FORMAT/DTA2DFile.h | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#ifndef OPENMS_FORMAT_DTA2DFILE_H
#define OPENMS_FORMAT_DTA2DFILE_H
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/CONCEPT/PrecisionWrapper.h>
#include <fstream>
#include <iostream>
namespace OpenMS
{
/**
@brief DTA2D File adapter.
File adapter for files with three tab/space-separated columns.
The default format is: retention time (seconds) , m/z , intensity.
If the first line starts with '#', a different order is defined by the
the order of the keywords 'MIN' (retention time in minutes) or 'SEC' (retention time in seconds), 'MZ', and 'INT'.
Example: '\#MZ MIN INT'
The peaks of one retention time have to be in subsequent lines.
@ingroup FileIO
*/
class OPENMS_DLLAPI DTA2DFile :
public ProgressLogger
{
private:
PeakFileOptions options_;
public:
/** @name Constructors and Destructor */
//@{
/// Default constructor
DTA2DFile();
/// Destructor
~DTA2DFile();
//@}
/// Mutable access to the options for loading/storing
PeakFileOptions& getOptions();
/// Non-mutable access to the options for loading/storing
const PeakFileOptions& getOptions() const;
/**
@brief Loads a map from a DTA2D file.
@param filename The file from which the map should be loaded.
@param map has to be a MSExperiment or have the same interface.
@exception Exception::FileNotFound is thrown if the file could not be opened
@exception Exception::ParseError is thrown if an error occurs during parsing
*/
template <typename MapType>
void load(const String& filename, MapType& map)
{
startProgress(0, 0, "loading DTA2D file");
//try to open file
std::ifstream is(filename.c_str());
if (!is)
{
throw Exception::FileNotFound(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename);
}
map.reset();
//set DocumentIdentifier
map.setLoadedFileType(filename);
map.setLoadedFilePath(filename);
// temporary variables to store the data in
std::vector<String> strings(3);
typename MapType::SpectrumType spec;
spec.setRT(-1.0); //to make sure the first RT is different from the the initialized value
typename MapType::SpectrumType::PeakType p;
double rt(0.0);
char delimiter;
// default dimension of the data
Size rt_dim = 0;
Size mz_dim = 1;
Size int_dim = 2;
//RT unit (default is seconds)
bool time_in_minutes = false;
// string to store the current line in
String line;
// native ID (numbers from 0)
UInt native_id = 0;
// line number counter
Size line_number = 0;
while (getline(is, line, '\n'))
{
++line_number;
line.trim();
if (line.empty()) continue;
//test which delimiter is used in the line
if (line.has('\t'))
{
delimiter = '\t';
}
else
{
delimiter = ' ';
}
//is header line
if (line.hasPrefix("#"))
{
line = line.substr(1).trim();
line.split(delimiter, strings);
// flags to check if dimension is set correctly
bool rt_set = false;
bool mz_set = false;
bool int_set = false;
//assign new order
for (Size i = 0; i < 3; ++i)
{
if (strings[i] == "RT" || strings[i] == "RETENTION_TIME" || strings[i] == "MASS-TO-CHARGE" || strings[i] == "IT" || strings[i] == "INTENSITY")
{
std::cerr << "Warning: This file contains the deprecated keyword '" << strings[i] << "'." << "\n";
std::cerr << " Please use only the new keywords SEC/MIN, MZ, INT." << "\n";
}
if ((strings[i] == "SEC" || strings[i] == "RT" || strings[i] == "RETENTION_TIME") && rt_set == false)
{
rt_dim = i;
rt_set = true;
}
else if ((strings[i] == "MIN") && rt_set == false)
{
rt_dim = i;
rt_set = true;
time_in_minutes = true;
}
else if ((strings[i] == "MZ" || strings[i] == "MASS-TO-CHARGE") && mz_set == false)
{
mz_dim = i;
mz_set = true;
}
else if ((strings[i] == "INT" || strings[i] == "IT" || strings[i] == "INTENSITY") && int_set == false)
{
int_dim = i;
int_set = true;
}
else
{
throw Exception::ParseError(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Misformatted header line!", filename);
}
}
continue;
}
try
{
line.split(delimiter, strings);
if (strings.size() != 3)
{
throw Exception::ParseError(__FILE__, __LINE__, __PRETTY_FUNCTION__, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\" (got " + String(strings.size()) + ", expected 3 entries)", filename);
}
p.setIntensity(strings[int_dim].toFloat());
p.setMZ(strings[mz_dim].toDouble());
rt = (strings[rt_dim].toDouble()) * (time_in_minutes ? 60.0 : 1.0);
}
// conversion to double or something else could have gone wrong
catch (Exception::BaseException& /*e*/)
{
throw Exception::ParseError(__FILE__, __LINE__, __PRETTY_FUNCTION__, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\"", filename);
}
// Retention time changed -> new Spectrum
if (fabs(rt - spec.getRT()) > 0.0001)
{
if (spec.size() != 0
&&
(!options_.hasRTRange() || options_.getRTRange().encloses(DPosition<1>(spec.getRT())))) // RT restriction fulfilled
{
map.addSpectrum(spec);
}
setProgress(0);
spec.clear(true);
spec.setRT(rt);
spec.setNativeID(String("index=") + native_id);
++native_id;
}
//Skip peaks with invalid m/z or intensity value
if (
(!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(p.getMZ())))
&&
(!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(p.getIntensity())))
)
{
spec.push_back(p);
}
}
// add last Spectrum
if (
spec.size() != 0
&&
(!options_.hasRTRange() || options_.getRTRange().encloses(DPosition<1>(spec.getRT()))) // RT restriction fulfilled
)
{
map.addSpectrum(spec);
}
is.close();
endProgress();
}
/**
@brief Stores a map in a DTA2D file.
@param filename The name of the file where the map should be stored.
@param map has to be a MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename MapType>
void store(const String& filename, const MapType& map) const
{
startProgress(0, map.size(), "storing DTA2D file");
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename);
}
// write header
os << "#SEC\tMZ\tINT\n";
// Iterate over all peaks of each spectrum and
// write one line for each peak of the spectrum.
UInt count = 0;
for (typename MapType::const_iterator spec = map.begin(); spec != map.end(); ++spec)
{
setProgress(count++);
for (typename MapType::SpectrumType::ConstIterator it = spec->begin(); it != spec->end(); ++it)
{
// Write rt, m/z and intensity.
os << precisionWrapper(spec->getRT()) << "\t" << precisionWrapper(it->getPos()) << "\t" << precisionWrapper(it->getIntensity()) << "\n";
}
}
os.close();
endProgress();
}
/**
@brief Stores the TIC of a map in a DTA2D file.
@param filename The name of the file where the map should be stored.
@param map has to be a MSExperiment or have the same interface.
@exception Exception::UnableToCreateFile is thrown if the file could not be created
*/
template <typename MapType>
void storeTIC(const String& filename, const MapType& map) const
{
startProgress(0, map.size(), "storing DTA2D file");
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename);
}
// write header (Always MZ=0 for chromatograms in DTA2D.)
os << "#SEC\tMZ\tINT\n";
typename MapType::ChromatogramType TIC = map.getTIC();
for (typename MapType::ChromatogramType::ConstIterator it = TIC.begin(); it != TIC.end(); ++it)
{
// write rt and intensity.
os << precisionWrapper(it->getRT()) << "\t" << precisionWrapper(0) << "\t" << precisionWrapper(it->getIntensity()) << "\n";
}
os.close();
endProgress();
}
};
} // namespace OpenMS
#endif // OPENMS_FORMAT_DTA2DFILE_H
| 34.029586 | 227 | 0.576943 | [
"vector"
] |
9aa17df214aa1c6cc504671b9de25f2fffd7547e | 21,883 | h | C | src/compiler/raw-machine-assembler.h | guillermomolina/v8-sparc | 40f43c91a59835819cdd544b25d0ea415a753bbb | [
"BSD-3-Clause"
] | null | null | null | src/compiler/raw-machine-assembler.h | guillermomolina/v8-sparc | 40f43c91a59835819cdd544b25d0ea415a753bbb | [
"BSD-3-Clause"
] | null | null | null | src/compiler/raw-machine-assembler.h | guillermomolina/v8-sparc | 40f43c91a59835819cdd544b25d0ea415a753bbb | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 the V8 project 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 V8_COMPILER_RAW_MACHINE_ASSEMBLER_H_
#define V8_COMPILER_RAW_MACHINE_ASSEMBLER_H_
#include "src/assembler.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/graph.h"
#include "src/compiler/linkage.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node.h"
#include "src/compiler/operator.h"
#include "src/factory.h"
namespace v8 {
namespace internal {
namespace compiler {
class BasicBlock;
class Schedule;
// The RawMachineAssembler produces a low-level IR graph. All nodes are wired
// into a graph and also placed into a schedule immediately, hence subsequent
// code generation can happen without the need for scheduling.
//
// In order to create a schedule on-the-fly, the assembler keeps track of basic
// blocks by having one current basic block being populated and by referencing
// other basic blocks through the use of labels.
//
// Also note that the generated graph is only valid together with the generated
// schedule, using one without the other is invalid as the graph is inherently
// non-schedulable due to missing control and effect dependencies.
class RawMachineAssembler {
public:
class Label {
public:
Label() : block_(NULL), used_(false), bound_(false) {}
~Label() { DCHECK(bound_ || !used_); }
private:
BasicBlock* block_;
bool used_;
bool bound_;
friend class RawMachineAssembler;
DISALLOW_COPY_AND_ASSIGN(Label);
};
RawMachineAssembler(Isolate* isolate, Graph* graph,
CallDescriptor* call_descriptor,
MachineType word = kMachPtr,
MachineOperatorBuilder::Flags flags =
MachineOperatorBuilder::Flag::kNoFlags);
~RawMachineAssembler() {}
Isolate* isolate() const { return isolate_; }
Graph* graph() const { return graph_; }
Schedule* schedule() { return schedule_; }
Zone* zone() const { return graph()->zone(); }
MachineOperatorBuilder* machine() { return &machine_; }
CommonOperatorBuilder* common() { return &common_; }
CallDescriptor* call_descriptor() const { return call_descriptor_; }
size_t parameter_count() const { return machine_sig()->parameter_count(); }
const MachineSignature* machine_sig() const {
return call_descriptor_->GetMachineSignature();
}
// Finalizes the schedule and exports it to be used for code generation. Note
// that this RawMachineAssembler becomes invalid after export.
Schedule* Export();
// ===========================================================================
// The following utility methods create new nodes with specific operators and
// place them into the current basic block. They don't perform control flow,
// hence will not switch the current basic block.
Node* UndefinedConstant() {
return HeapConstant(isolate()->factory()->undefined_value());
}
// Constants.
Node* PointerConstant(void* value) {
return IntPtrConstant(reinterpret_cast<intptr_t>(value));
}
Node* IntPtrConstant(intptr_t value) {
// TODO(dcarney): mark generated code as unserializable if value != 0.
return kPointerSize == 8 ? Int64Constant(value)
: Int32Constant(static_cast<int>(value));
}
Node* Int32Constant(int32_t value) {
return AddNode(common()->Int32Constant(value));
}
Node* Int64Constant(int64_t value) {
return AddNode(common()->Int64Constant(value));
}
Node* NumberConstant(double value) {
return AddNode(common()->NumberConstant(value));
}
Node* Float32Constant(float value) {
return AddNode(common()->Float32Constant(value));
}
Node* Float64Constant(double value) {
return AddNode(common()->Float64Constant(value));
}
Node* HeapConstant(Handle<HeapObject> object) {
return AddNode(common()->HeapConstant(object));
}
Node* BooleanConstant(bool value) {
Handle<Object> object = isolate()->factory()->ToBoolean(value);
return HeapConstant(Handle<HeapObject>::cast(object));
}
Node* ExternalConstant(ExternalReference address) {
return AddNode(common()->ExternalConstant(address));
}
Node* Projection(int index, Node* a) {
return AddNode(common()->Projection(index), a);
}
// Memory Operations.
Node* Load(MachineType rep, Node* base) {
return Load(rep, base, IntPtrConstant(0));
}
Node* Load(MachineType rep, Node* base, Node* index) {
return AddNode(machine()->Load(rep), base, index, graph()->start(),
graph()->start());
}
Node* Store(StoreRepresentation rep, Node* base, Node* value) {
return Store(rep, base, IntPtrConstant(0), value);
}
Node* Store(StoreRepresentation rep, Node* base, Node* index, Node* value) {
return AddNode(machine()->Store(rep), base, index, value, graph()->start(),
graph()->start());
}
// Arithmetic Operations.
Node* WordAnd(Node* a, Node* b) {
return AddNode(machine()->WordAnd(), a, b);
}
Node* WordOr(Node* a, Node* b) { return AddNode(machine()->WordOr(), a, b); }
Node* WordXor(Node* a, Node* b) {
return AddNode(machine()->WordXor(), a, b);
}
Node* WordShl(Node* a, Node* b) {
return AddNode(machine()->WordShl(), a, b);
}
Node* WordShr(Node* a, Node* b) {
return AddNode(machine()->WordShr(), a, b);
}
Node* WordSar(Node* a, Node* b) {
return AddNode(machine()->WordSar(), a, b);
}
Node* WordRor(Node* a, Node* b) {
return AddNode(machine()->WordRor(), a, b);
}
Node* WordEqual(Node* a, Node* b) {
return AddNode(machine()->WordEqual(), a, b);
}
Node* WordNotEqual(Node* a, Node* b) {
return WordBinaryNot(WordEqual(a, b));
}
Node* WordNot(Node* a) {
if (machine()->Is32()) {
return Word32Not(a);
} else {
return Word64Not(a);
}
}
Node* WordBinaryNot(Node* a) {
if (machine()->Is32()) {
return Word32BinaryNot(a);
} else {
return Word64BinaryNot(a);
}
}
Node* Word32And(Node* a, Node* b) {
return AddNode(machine()->Word32And(), a, b);
}
Node* Word32Or(Node* a, Node* b) {
return AddNode(machine()->Word32Or(), a, b);
}
Node* Word32Xor(Node* a, Node* b) {
return AddNode(machine()->Word32Xor(), a, b);
}
Node* Word32Shl(Node* a, Node* b) {
return AddNode(machine()->Word32Shl(), a, b);
}
Node* Word32Shr(Node* a, Node* b) {
return AddNode(machine()->Word32Shr(), a, b);
}
Node* Word32Sar(Node* a, Node* b) {
return AddNode(machine()->Word32Sar(), a, b);
}
Node* Word32Ror(Node* a, Node* b) {
return AddNode(machine()->Word32Ror(), a, b);
}
Node* Word32Clz(Node* a) { return AddNode(machine()->Word32Clz(), a); }
Node* Word32Equal(Node* a, Node* b) {
return AddNode(machine()->Word32Equal(), a, b);
}
Node* Word32NotEqual(Node* a, Node* b) {
return Word32BinaryNot(Word32Equal(a, b));
}
Node* Word32Not(Node* a) { return Word32Xor(a, Int32Constant(-1)); }
Node* Word32BinaryNot(Node* a) { return Word32Equal(a, Int32Constant(0)); }
Node* Word64And(Node* a, Node* b) {
return AddNode(machine()->Word64And(), a, b);
}
Node* Word64Or(Node* a, Node* b) {
return AddNode(machine()->Word64Or(), a, b);
}
Node* Word64Xor(Node* a, Node* b) {
return AddNode(machine()->Word64Xor(), a, b);
}
Node* Word64Shl(Node* a, Node* b) {
return AddNode(machine()->Word64Shl(), a, b);
}
Node* Word64Shr(Node* a, Node* b) {
return AddNode(machine()->Word64Shr(), a, b);
}
Node* Word64Sar(Node* a, Node* b) {
return AddNode(machine()->Word64Sar(), a, b);
}
Node* Word64Ror(Node* a, Node* b) {
return AddNode(machine()->Word64Ror(), a, b);
}
Node* Word64Equal(Node* a, Node* b) {
return AddNode(machine()->Word64Equal(), a, b);
}
Node* Word64NotEqual(Node* a, Node* b) {
return Word64BinaryNot(Word64Equal(a, b));
}
Node* Word64Not(Node* a) { return Word64Xor(a, Int64Constant(-1)); }
Node* Word64BinaryNot(Node* a) { return Word64Equal(a, Int64Constant(0)); }
Node* Int32Add(Node* a, Node* b) {
return AddNode(machine()->Int32Add(), a, b);
}
Node* Int32AddWithOverflow(Node* a, Node* b) {
return AddNode(machine()->Int32AddWithOverflow(), a, b);
}
Node* Int32Sub(Node* a, Node* b) {
return AddNode(machine()->Int32Sub(), a, b);
}
Node* Int32SubWithOverflow(Node* a, Node* b) {
return AddNode(machine()->Int32SubWithOverflow(), a, b);
}
Node* Int32Mul(Node* a, Node* b) {
return AddNode(machine()->Int32Mul(), a, b);
}
Node* Int32MulHigh(Node* a, Node* b) {
return AddNode(machine()->Int32MulHigh(), a, b);
}
Node* Int32Div(Node* a, Node* b) {
return AddNode(machine()->Int32Div(), a, b, graph()->start());
}
Node* Int32Mod(Node* a, Node* b) {
return AddNode(machine()->Int32Mod(), a, b, graph()->start());
}
Node* Int32LessThan(Node* a, Node* b) {
return AddNode(machine()->Int32LessThan(), a, b);
}
Node* Int32LessThanOrEqual(Node* a, Node* b) {
return AddNode(machine()->Int32LessThanOrEqual(), a, b);
}
Node* Uint32Div(Node* a, Node* b) {
return AddNode(machine()->Uint32Div(), a, b, graph()->start());
}
Node* Uint32LessThan(Node* a, Node* b) {
return AddNode(machine()->Uint32LessThan(), a, b);
}
Node* Uint32LessThanOrEqual(Node* a, Node* b) {
return AddNode(machine()->Uint32LessThanOrEqual(), a, b);
}
Node* Uint32Mod(Node* a, Node* b) {
return AddNode(machine()->Uint32Mod(), a, b, graph()->start());
}
Node* Uint32MulHigh(Node* a, Node* b) {
return AddNode(machine()->Uint32MulHigh(), a, b);
}
Node* Int32GreaterThan(Node* a, Node* b) { return Int32LessThan(b, a); }
Node* Int32GreaterThanOrEqual(Node* a, Node* b) {
return Int32LessThanOrEqual(b, a);
}
Node* Int32Neg(Node* a) { return Int32Sub(Int32Constant(0), a); }
Node* Int64Add(Node* a, Node* b) {
return AddNode(machine()->Int64Add(), a, b);
}
Node* Int64Sub(Node* a, Node* b) {
return AddNode(machine()->Int64Sub(), a, b);
}
Node* Int64Mul(Node* a, Node* b) {
return AddNode(machine()->Int64Mul(), a, b);
}
Node* Int64Div(Node* a, Node* b) {
return AddNode(machine()->Int64Div(), a, b);
}
Node* Int64Mod(Node* a, Node* b) {
return AddNode(machine()->Int64Mod(), a, b);
}
Node* Int64Neg(Node* a) { return Int64Sub(Int64Constant(0), a); }
Node* Int64LessThan(Node* a, Node* b) {
return AddNode(machine()->Int64LessThan(), a, b);
}
Node* Int64LessThanOrEqual(Node* a, Node* b) {
return AddNode(machine()->Int64LessThanOrEqual(), a, b);
}
Node* Uint64LessThan(Node* a, Node* b) {
return AddNode(machine()->Uint64LessThan(), a, b);
}
Node* Uint64LessThanOrEqual(Node* a, Node* b) {
return AddNode(machine()->Uint64LessThanOrEqual(), a, b);
}
Node* Int64GreaterThan(Node* a, Node* b) { return Int64LessThan(b, a); }
Node* Int64GreaterThanOrEqual(Node* a, Node* b) {
return Int64LessThanOrEqual(b, a);
}
Node* Uint64Div(Node* a, Node* b) {
return AddNode(machine()->Uint64Div(), a, b);
}
Node* Uint64Mod(Node* a, Node* b) {
return AddNode(machine()->Uint64Mod(), a, b);
}
#define INTPTR_BINOP(prefix, name) \
Node* IntPtr##name(Node* a, Node* b) { \
return kPointerSize == 8 ? prefix##64##name(a, b) \
: prefix##32##name(a, b); \
}
INTPTR_BINOP(Int, Add);
INTPTR_BINOP(Int, Sub);
INTPTR_BINOP(Int, LessThan);
INTPTR_BINOP(Int, LessThanOrEqual);
INTPTR_BINOP(Word, Equal);
INTPTR_BINOP(Word, NotEqual);
INTPTR_BINOP(Int, GreaterThanOrEqual);
INTPTR_BINOP(Int, GreaterThan);
#undef INTPTR_BINOP
Node* Float32Add(Node* a, Node* b) {
return AddNode(machine()->Float32Add(), a, b);
}
Node* Float32Sub(Node* a, Node* b) {
return AddNode(machine()->Float32Sub(), a, b);
}
Node* Float32Mul(Node* a, Node* b) {
return AddNode(machine()->Float32Mul(), a, b);
}
Node* Float32Div(Node* a, Node* b) {
return AddNode(machine()->Float32Div(), a, b);
}
Node* Float32Max(Node* a, Node* b) {
return AddNode(machine()->Float32Max().op(), a, b);
}
Node* Float32Min(Node* a, Node* b) {
return AddNode(machine()->Float32Min().op(), a, b);
}
Node* Float32Abs(Node* a) { return AddNode(machine()->Float32Abs(), a); }
Node* Float32Sqrt(Node* a) { return AddNode(machine()->Float32Sqrt(), a); }
Node* Float32Equal(Node* a, Node* b) {
return AddNode(machine()->Float32Equal(), a, b);
}
Node* Float32NotEqual(Node* a, Node* b) {
return WordBinaryNot(Float32Equal(a, b));
}
Node* Float32LessThan(Node* a, Node* b) {
return AddNode(machine()->Float32LessThan(), a, b);
}
Node* Float32LessThanOrEqual(Node* a, Node* b) {
return AddNode(machine()->Float32LessThanOrEqual(), a, b);
}
Node* Float32GreaterThan(Node* a, Node* b) { return Float32LessThan(b, a); }
Node* Float32GreaterThanOrEqual(Node* a, Node* b) {
return Float32LessThanOrEqual(b, a);
}
Node* Float64Add(Node* a, Node* b) {
return AddNode(machine()->Float64Add(), a, b);
}
Node* Float64Sub(Node* a, Node* b) {
return AddNode(machine()->Float64Sub(), a, b);
}
Node* Float64Mul(Node* a, Node* b) {
return AddNode(machine()->Float64Mul(), a, b);
}
Node* Float64Div(Node* a, Node* b) {
return AddNode(machine()->Float64Div(), a, b);
}
Node* Float64Mod(Node* a, Node* b) {
return AddNode(machine()->Float64Mod(), a, b);
}
Node* Float64Max(Node* a, Node* b) {
return AddNode(machine()->Float64Max().op(), a, b);
}
Node* Float64Min(Node* a, Node* b) {
return AddNode(machine()->Float64Min().op(), a, b);
}
Node* Float64Abs(Node* a) { return AddNode(machine()->Float64Abs(), a); }
Node* Float64Sqrt(Node* a) { return AddNode(machine()->Float64Sqrt(), a); }
Node* Float64Equal(Node* a, Node* b) {
return AddNode(machine()->Float64Equal(), a, b);
}
Node* Float64NotEqual(Node* a, Node* b) {
return WordBinaryNot(Float64Equal(a, b));
}
Node* Float64LessThan(Node* a, Node* b) {
return AddNode(machine()->Float64LessThan(), a, b);
}
Node* Float64LessThanOrEqual(Node* a, Node* b) {
return AddNode(machine()->Float64LessThanOrEqual(), a, b);
}
Node* Float64GreaterThan(Node* a, Node* b) { return Float64LessThan(b, a); }
Node* Float64GreaterThanOrEqual(Node* a, Node* b) {
return Float64LessThanOrEqual(b, a);
}
// Conversions.
Node* ChangeFloat32ToFloat64(Node* a) {
return AddNode(machine()->ChangeFloat32ToFloat64(), a);
}
Node* ChangeInt32ToFloat64(Node* a) {
return AddNode(machine()->ChangeInt32ToFloat64(), a);
}
Node* ChangeUint32ToFloat64(Node* a) {
return AddNode(machine()->ChangeUint32ToFloat64(), a);
}
Node* ChangeFloat64ToInt32(Node* a) {
return AddNode(machine()->ChangeFloat64ToInt32(), a);
}
Node* ChangeFloat64ToUint32(Node* a) {
return AddNode(machine()->ChangeFloat64ToUint32(), a);
}
Node* ChangeInt32ToInt64(Node* a) {
return AddNode(machine()->ChangeInt32ToInt64(), a);
}
Node* ChangeUint32ToUint64(Node* a) {
return AddNode(machine()->ChangeUint32ToUint64(), a);
}
Node* TruncateFloat64ToFloat32(Node* a) {
return AddNode(machine()->TruncateFloat64ToFloat32(), a);
}
Node* TruncateFloat64ToInt32(TruncationMode mode, Node* a) {
return AddNode(machine()->TruncateFloat64ToInt32(mode), a);
}
Node* TruncateInt64ToInt32(Node* a) {
return AddNode(machine()->TruncateInt64ToInt32(), a);
}
Node* BitcastFloat32ToInt32(Node* a) {
return AddNode(machine()->BitcastFloat32ToInt32(), a);
}
Node* BitcastFloat64ToInt64(Node* a) {
return AddNode(machine()->BitcastFloat64ToInt64(), a);
}
Node* BitcastInt32ToFloat32(Node* a) {
return AddNode(machine()->BitcastInt32ToFloat32(), a);
}
Node* BitcastInt64ToFloat64(Node* a) {
return AddNode(machine()->BitcastInt64ToFloat64(), a);
}
Node* Float64RoundDown(Node* a) {
return AddNode(machine()->Float64RoundDown().op(), a);
}
Node* Float64RoundTruncate(Node* a) {
return AddNode(machine()->Float64RoundTruncate().op(), a);
}
Node* Float64RoundTiesAway(Node* a) {
return AddNode(machine()->Float64RoundTiesAway().op(), a);
}
// Float64 bit operations.
Node* Float64ExtractLowWord32(Node* a) {
return AddNode(machine()->Float64ExtractLowWord32(), a);
}
Node* Float64ExtractHighWord32(Node* a) {
return AddNode(machine()->Float64ExtractHighWord32(), a);
}
Node* Float64InsertLowWord32(Node* a, Node* b) {
return AddNode(machine()->Float64InsertLowWord32(), a, b);
}
Node* Float64InsertHighWord32(Node* a, Node* b) {
return AddNode(machine()->Float64InsertHighWord32(), a, b);
}
// Stack operations.
Node* LoadStackPointer() { return AddNode(machine()->LoadStackPointer()); }
Node* LoadFramePointer() { return AddNode(machine()->LoadFramePointer()); }
// Parameters.
Node* Parameter(size_t index);
// Pointer utilities.
Node* LoadFromPointer(void* address, MachineType rep, int32_t offset = 0) {
return Load(rep, PointerConstant(address), Int32Constant(offset));
}
Node* StoreToPointer(void* address, StoreRepresentation rep, Node* node) {
return Store(rep, PointerConstant(address), node);
}
Node* StringConstant(const char* string) {
return HeapConstant(isolate()->factory()->InternalizeUtf8String(string));
}
// Call a given call descriptor and the given arguments.
Node* CallN(CallDescriptor* desc, Node* function, Node** args);
// Call a given call descriptor and the given arguments and frame-state.
Node* CallNWithFrameState(CallDescriptor* desc, Node* function, Node** args,
Node* frame_state);
// Tail call the given call descriptor and the given arguments.
Node* TailCallN(CallDescriptor* call_descriptor, Node* function, Node** args);
// Call through CallFunctionStub with lazy deopt and frame-state.
Node* CallFunctionStub0(Node* function, Node* receiver, Node* context,
Node* frame_state, CallFunctionFlags flags);
// Call to a runtime function with one arguments.
Node* CallRuntime1(Runtime::FunctionId function, Node* arg0, Node* context);
// Call to a runtime function with two arguments.
Node* CallRuntime2(Runtime::FunctionId function, Node* arg1, Node* arg2,
Node* context);
// Call to a runtime function with four arguments.
Node* CallRuntime4(Runtime::FunctionId function, Node* arg1, Node* arg2,
Node* arg3, Node* arg4, Node* context);
// Call to a C function with zero arguments.
Node* CallCFunction0(MachineType return_type, Node* function);
// Call to a C function with one parameter.
Node* CallCFunction1(MachineType return_type, MachineType arg0_type,
Node* function, Node* arg0);
// Call to a C function with two arguments.
Node* CallCFunction2(MachineType return_type, MachineType arg0_type,
MachineType arg1_type, Node* function, Node* arg0,
Node* arg1);
// Call to a C function with eight arguments.
Node* CallCFunction8(MachineType return_type, MachineType arg0_type,
MachineType arg1_type, MachineType arg2_type,
MachineType arg3_type, MachineType arg4_type,
MachineType arg5_type, MachineType arg6_type,
MachineType arg7_type, Node* function, Node* arg0,
Node* arg1, Node* arg2, Node* arg3, Node* arg4,
Node* arg5, Node* arg6, Node* arg7);
// ===========================================================================
// The following utility methods deal with control flow, hence might switch
// the current basic block or create new basic blocks for labels.
// Control flow.
void Goto(Label* label);
void Branch(Node* condition, Label* true_val, Label* false_val);
void Switch(Node* index, Label* default_label, int32_t* case_values,
Label** case_labels, size_t case_count);
void Return(Node* value);
void Return(Node* v1, Node* v2);
void Return(Node* v1, Node* v2, Node* v3);
void Bind(Label* label);
void Deoptimize(Node* state);
// Variables.
Node* Phi(MachineType type, Node* n1, Node* n2) {
return AddNode(common()->Phi(type, 2), n1, n2);
}
Node* Phi(MachineType type, Node* n1, Node* n2, Node* n3) {
return AddNode(common()->Phi(type, 3), n1, n2, n3);
}
Node* Phi(MachineType type, Node* n1, Node* n2, Node* n3, Node* n4) {
return AddNode(common()->Phi(type, 4), n1, n2, n3, n4);
}
// ===========================================================================
// The following generic node creation methods can be used for operators that
// are not covered by the above utility methods. There should rarely be a need
// to do that outside of testing though.
Node* AddNode(const Operator* op, int input_count, Node** inputs);
Node* AddNode(const Operator* op) {
return AddNode(op, 0, static_cast<Node**>(nullptr));
}
template <class... TArgs>
Node* AddNode(const Operator* op, Node* n1, TArgs... args) {
Node* buffer[] = {n1, args...};
return AddNode(op, sizeof...(args) + 1, buffer);
}
private:
Node* MakeNode(const Operator* op, int input_count, Node** inputs);
BasicBlock* Use(Label* label);
BasicBlock* EnsureBlock(Label* label);
BasicBlock* CurrentBlock();
Isolate* isolate_;
Graph* graph_;
Schedule* schedule_;
MachineOperatorBuilder machine_;
CommonOperatorBuilder common_;
CallDescriptor* call_descriptor_;
Node** parameters_;
BasicBlock* current_block_;
DISALLOW_COPY_AND_ASSIGN(RawMachineAssembler);
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_RAW_MACHINE_ASSEMBLER_H_
| 35.87377 | 80 | 0.649545 | [
"object"
] |
9aa3124f2e52fa4f193a51c8a85a1820ebb5b4da | 1,439 | h | C | src/NativeScript/Workers/JSWorkerConstructor.h | aaayushsingh/ios-runtime | f8714aaf20ba9cdd288fc34e53d181a4d7f8cd6e | [
"Apache-2.0"
] | 1 | 2021-11-14T02:57:26.000Z | 2021-11-14T02:57:26.000Z | src/NativeScript/Workers/JSWorkerConstructor.h | aaayushsingh/ios-runtime | f8714aaf20ba9cdd288fc34e53d181a4d7f8cd6e | [
"Apache-2.0"
] | null | null | null | src/NativeScript/Workers/JSWorkerConstructor.h | aaayushsingh/ios-runtime | f8714aaf20ba9cdd288fc34e53d181a4d7f8cd6e | [
"Apache-2.0"
] | 1 | 2021-11-14T02:56:06.000Z | 2021-11-14T02:56:06.000Z | //
// JSWorkerConstructor.h
// NativeScript
//
// Created by Ivan Buhov on 7/5/16.
//
//
#ifndef __NativeScript__JSWorkerConstructor__
#define __NativeScript__JSWorkerConstructor__
#include <JavaScriptCore/InternalFunction.h>
namespace NativeScript {
class JSWorkerPrototype;
class JSWorkerConstructor : public JSC::InternalFunction {
public:
typedef JSC::InternalFunction Base;
DECLARE_INFO;
static JSWorkerConstructor* create(JSC::VM& vm, JSC::Structure* structure, JSWorkerPrototype* prototype) {
JSWorkerConstructor* object = new (NotNull, JSC::allocateCell<JSWorkerConstructor>(vm.heap)) JSWorkerConstructor(vm, structure);
object->finishCreation(vm, prototype);
return object;
}
static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) {
return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());
}
private:
JSWorkerConstructor(JSC::VM& vm, JSC::Structure* structure)
: Base(vm, structure) {
}
static JSC::ConstructType getConstructData(JSC::JSCell* cell, JSC::ConstructData& constructData);
static JSC::CallType getCallData(JSC::JSCell* cell, JSC::CallData& callData);
void finishCreation(JSC::VM& vm, JSWorkerPrototype* prototype);
};
} // namespace NativeScript
#endif /* defined(__NativeScript__JSWorkerConstructor__) */ | 31.977778 | 136 | 0.736623 | [
"object"
] |
9aa3a1a80c1ac54d0d2ff0ac16531b56cdc2ee63 | 28,002 | h | C | Pods/AWSCore/AWSCore/CognitoIdentity/AWSCognitoIdentityService.h | BookSelves/Bookselves | 8ff46722f010df6fe05e7b13cbac4dae45aea87c | [
"MIT"
] | 4 | 2017-07-05T08:33:53.000Z | 2021-03-11T23:00:55.000Z | Pods/AWSCore/AWSCore/CognitoIdentity/AWSCognitoIdentityService.h | BookSelves/Bookselves | 8ff46722f010df6fe05e7b13cbac4dae45aea87c | [
"MIT"
] | 4 | 2015-11-11T08:59:37.000Z | 2019-07-31T07:18:31.000Z | Pods/AWSCore/AWSCore/CognitoIdentity/AWSCognitoIdentityService.h | BookSelves/Bookselves | 8ff46722f010df6fe05e7b13cbac4dae45aea87c | [
"MIT"
] | 3 | 2015-10-28T18:58:15.000Z | 2019-07-21T06:23:31.000Z | /**
Copyright 2010-2015 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.
*/
#import <Foundation/Foundation.h>
#import <AWSCore/AWSCore.h>
#import "AWSCognitoIdentityModel.h"
/**
<fullname>Amazon Cognito</fullname><p>Amazon Cognito is a web service that delivers scoped temporary credentials to mobile devices and other untrusted environments. Amazon Cognito uniquely identifies a device and supplies the user with a consistent identity over the lifetime of an application.</p><p>Using Amazon Cognito, you can enable authentication with one or more third-party identity providers (Facebook, Google, or Login with Amazon), and you can also choose to support unauthenticated access from your app. Cognito delivers a unique identifier for each user and acts as an OpenID token provider trusted by AWS Security Token Service (STS) to access temporary, limited-privilege AWS credentials.</p><p>To provide end-user credentials, first make an unsigned call to <a>GetId</a>. If the end user is authenticated with one of the supported identity providers, set the <code>Logins</code> map with the identity provider token. <code>GetId</code> returns a unique identifier for the user.</p><p>Next, make an unsigned call to <a>GetOpenIdToken</a>, which returns the OpenID token necessary to call STS and retrieve AWS credentials. This call expects the same <code>Logins</code> map as the <code>GetId</code> call, as well as the <code>IdentityID</code> originally returned by <code>GetId</code>. The token returned by <code>GetOpenIdToken</code> can be passed to the STS operation <a href="http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html">AssumeRoleWithWebIdentity</a> to retrieve AWS credentials.</p><p>If you want to use Amazon Cognito in an Android or iOS application, you will probably want to make API calls via the AWS Mobile SDK. To learn more, see the <a href="http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html">Developer Guide for Android</a> and the <a href="http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html">Developer Guide for iOS</a>.</p>
*/
@interface AWSCognitoIdentity : AWSService
/**
The service configuration used to instantiate this service client.
@warning Once the client is instantiated, do not modify the configuration object. It may cause unspecified behaviors.
*/
@property (nonatomic, strong, readonly) AWSServiceConfiguration *configuration;
/**
Returns the singleton service client. If the singleton object does not exist, the SDK instantiates the default service client with `defaultServiceConfiguration` from `[AWSServiceManager defaultServiceManager]`. The reference to this object is maintained by the SDK, and you do not need to retain it manually.
For example, set the default service configuration in `- application:didFinishLaunchingWithOptions:`
*Swift*
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YourIdentityPoolId")
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
return true
}
*Objective-C*
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1
identityPoolId:@"YourIdentityPoolId"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1
credentialsProvider:credentialsProvider];
[AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
return YES;
}
Then call the following to get the default service client:
*Swift*
let CognitoIdentity = AWSCognitoIdentity.defaultCognitoIdentity()
*Objective-C*
AWSCognitoIdentity *CognitoIdentity = [AWSCognitoIdentity defaultCognitoIdentity];
@return The default service client.
*/
+ (instancetype)defaultCognitoIdentity;
/**
Creates a service client with the given service configuration and registers it for the key.
For example, set the default service configuration in `- application:didFinishLaunchingWithOptions:`
*Swift*
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YourIdentityPoolId")
let configuration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: credentialProvider)
AWSCognitoIdentity.registerCognitoIdentityWithConfiguration(configuration, forKey: "USWest2CognitoIdentity")
return true
}
*Objective-C*
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1
identityPoolId:@"YourIdentityPoolId"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSWest2
credentialsProvider:credentialsProvider];
[AWSCognitoIdentity registerCognitoIdentityWithConfiguration:configuration forKey:@"USWest2CognitoIdentity"];
return YES;
}
Then call the following to get the service client:
*Swift*
let CognitoIdentity = AWSCognitoIdentity(forKey: "USWest2CognitoIdentity")
*Objective-C*
AWSCognitoIdentity *CognitoIdentity = [AWSCognitoIdentity CognitoIdentityForKey:@"USWest2CognitoIdentity"];
@warning After calling this method, do not modify the configuration object. It may cause unspecified behaviors.
@param configuration A service configuration object.
@param key A string to identify the service client.
*/
+ (void)registerCognitoIdentityWithConfiguration:(AWSServiceConfiguration *)configuration forKey:(NSString *)key;
/**
Retrieves the service client associated with the key. You need to call `+ registerCognitoIdentityWithConfiguration:forKey:` before invoking this method. If `+ registerCognitoIdentityWithConfiguration:forKey:` has not been called in advance or the key does not exist, this method returns `nil`.
For example, set the default service configuration in `- application:didFinishLaunchingWithOptions:`
*Swift*
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YourIdentityPoolId")
let configuration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: credentialProvider)
AWSCognitoIdentity.registerCognitoIdentityWithConfiguration(configuration, forKey: "USWest2CognitoIdentity")
return true
}
*Objective-C*
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1
identityPoolId:@"YourIdentityPoolId"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSWest2
credentialsProvider:credentialsProvider];
[AWSCognitoIdentity registerCognitoIdentityWithConfiguration:configuration forKey:@"USWest2CognitoIdentity"];
return YES;
}
Then call the following to get the service client:
*Swift*
let CognitoIdentity = AWSCognitoIdentity(forKey: "USWest2CognitoIdentity")
*Objective-C*
AWSCognitoIdentity *CognitoIdentity = [AWSCognitoIdentity CognitoIdentityForKey:@"USWest2CognitoIdentity"];
@param key A string to identify the service client.
@return An instance of the service client.
*/
+ (instancetype)CognitoIdentityForKey:(NSString *)key;
/**
Removes the service client associated with the key and release it.
@warning Before calling this method, make sure no method is running on this client.
@param key A string to identify the service client.
*/
+ (void)removeCognitoIdentityForKey:(NSString *)key;
/**
Instantiates the service client with the given service configuration.
@warning This method has been deprecated. Use `+ registerCognitoIdentityWithConfiguration:forKey:` and `+ CognitoIdentityForKey:` instead.
@warning Once the client is instantiated, do not modify the configuration object. It may cause unspecified behaviors.
@warning Unlike the singleton method, you are responsible for maintaining a strong reference to this object. If the service client is released before completing a service request, the request may fail with unspecified errors.
@param configuration The service configuration object.
@return An instance of the service client.
*/
- (instancetype)initWithConfiguration:(AWSServiceConfiguration *)configuration __attribute__ ((deprecated("Use '+ registerCognitoIdentityWithConfiguration:forKey:' and '+ CognitoIdentityForKey:' instead.")));
/**
<p>Creates a new identity pool. The identity pool is a store of user identity information that is specific to your AWS account. The limit on identity pools is 60 per account.</p>
@param request A container for the necessary parameters to execute the CreateIdentityPool service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityIdentityPool`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`, `AWSCognitoIdentityErrorLimitExceeded`.
@see AWSCognitoIdentityCreateIdentityPoolInput
@see AWSCognitoIdentityIdentityPool
*/
- (BFTask *)createIdentityPool:(AWSCognitoIdentityCreateIdentityPoolInput *)request;
/**
<p>Deletes a user pool. Once a pool is deleted, users will not be able to authenticate with the pool.</p>
@param request A container for the necessary parameters to execute the DeleteIdentityPool service method.
@return An instance of `BFTask`. On successful execution, `task.result` will be `nil`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityDeleteIdentityPoolInput
*/
- (BFTask *)deleteIdentityPool:(AWSCognitoIdentityDeleteIdentityPoolInput *)request;
/**
DescribeIdentity
@param request A container for the necessary parameters to execute the DescribeIdentity service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityIdentityDescription`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityDescribeIdentityInput
@see AWSCognitoIdentityIdentityDescription
*/
- (BFTask *)describeIdentity:(AWSCognitoIdentityDescribeIdentityInput *)request;
/**
<p>Gets details about a particular identity pool, including the pool name, ID description, creation date, and current number of users.</p>
@param request A container for the necessary parameters to execute the DescribeIdentityPool service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityIdentityPool`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityDescribeIdentityPoolInput
@see AWSCognitoIdentityIdentityPool
*/
- (BFTask *)describeIdentityPool:(AWSCognitoIdentityDescribeIdentityPoolInput *)request;
/**
GetCredentialsForIdentity
@param request A container for the necessary parameters to execute the GetCredentialsForIdentity service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityGetCredentialsForIdentityResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInvalidIdentityPoolConfiguration`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityGetCredentialsForIdentityInput
@see AWSCognitoIdentityGetCredentialsForIdentityResponse
*/
- (BFTask *)getCredentialsForIdentity:(AWSCognitoIdentityGetCredentialsForIdentityInput *)request;
/**
<p>Generates (or retrieves) a Cognito ID. Supplying multiple logins will create an implicit linked account.</p>
@param request A container for the necessary parameters to execute the GetId service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityGetIdResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`, `AWSCognitoIdentityErrorLimitExceeded`.
@see AWSCognitoIdentityGetIdInput
@see AWSCognitoIdentityGetIdResponse
*/
- (BFTask *)getId:(AWSCognitoIdentityGetIdInput *)request;
/**
GetIdentityPoolRoles
@param request A container for the necessary parameters to execute the GetIdentityPoolRoles service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityGetIdentityPoolRolesResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityGetIdentityPoolRolesInput
@see AWSCognitoIdentityGetIdentityPoolRolesResponse
*/
- (BFTask *)getIdentityPoolRoles:(AWSCognitoIdentityGetIdentityPoolRolesInput *)request;
/**
<p>Gets an OpenID token, using a known Cognito ID. This known Cognito ID is returned by <a>GetId</a>. You can optionally add additional logins for the identity. Supplying multiple logins creates an implicit link.</p><p>The OpenId token is valid for 15 minutes.</p>
@param request A container for the necessary parameters to execute the GetOpenIdToken service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityGetOpenIdTokenResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityGetOpenIdTokenInput
@see AWSCognitoIdentityGetOpenIdTokenResponse
*/
- (BFTask *)getOpenIdToken:(AWSCognitoIdentityGetOpenIdTokenInput *)request;
/**
<p>Registers (or retrieves) a Cognito <code>IdentityId</code> and an OpenID Connect token for a user authenticated by your backend authentication process. Supplying multiple logins will create an implicit linked account. You can only specify one developer provider as part of the <code>Logins</code> map, which is linked to the identity pool. The developer provider is the "domain" by which Cognito will refer to your users.</p><p>You can use <code>GetOpenIdTokenForDeveloperIdentity</code> to create a new identity and to link new logins (that is, user credentials issued by a public provider or developer provider) to an existing identity. When you want to create a new identity, the <code>IdentityId</code> should be null. When you want to associate a new login with an existing authenticated/unauthenticated identity, you can do so by providing the existing <code>IdentityId</code>. This API will create the identity in the specified <code>IdentityPoolId</code>.</p>
@param request A container for the necessary parameters to execute the GetOpenIdTokenForDeveloperIdentity service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityGetOpenIdTokenForDeveloperIdentityResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`, `AWSCognitoIdentityErrorDeveloperUserAlreadyRegistered`.
@see AWSCognitoIdentityGetOpenIdTokenForDeveloperIdentityInput
@see AWSCognitoIdentityGetOpenIdTokenForDeveloperIdentityResponse
*/
- (BFTask *)getOpenIdTokenForDeveloperIdentity:(AWSCognitoIdentityGetOpenIdTokenForDeveloperIdentityInput *)request;
/**
<p>Lists the identities in a pool.</p>
@param request A container for the necessary parameters to execute the ListIdentities service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityListIdentitiesResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityListIdentitiesInput
@see AWSCognitoIdentityListIdentitiesResponse
*/
- (BFTask *)listIdentities:(AWSCognitoIdentityListIdentitiesInput *)request;
/**
<p>Lists all of the Cognito identity pools registered for your account.</p>
@param request A container for the necessary parameters to execute the ListIdentityPools service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityListIdentityPoolsResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityListIdentityPoolsInput
@see AWSCognitoIdentityListIdentityPoolsResponse
*/
- (BFTask *)listIdentityPools:(AWSCognitoIdentityListIdentityPoolsInput *)request;
/**
<p>Retrieves the <code>IdentityID</code> associated with a <code>DeveloperUserIdentifier</code> or the list of <code>DeveloperUserIdentifier</code>s associated with an <code>IdentityId</code> for an existing identity. Either <code>IdentityID</code> or <code>DeveloperUserIdentifier</code> must not be null. If you supply only one of these values, the other value will be searched in the database and returned as a part of the response. If you supply both, <code>DeveloperUserIdentifier</code> will be matched against <code>IdentityID</code>. If the values are verified against the database, the response returns both values and is the same as the request. Otherwise a <code>ResourceConflictException</code> is thrown.</p>
@param request A container for the necessary parameters to execute the LookupDeveloperIdentity service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityLookupDeveloperIdentityResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityLookupDeveloperIdentityInput
@see AWSCognitoIdentityLookupDeveloperIdentityResponse
*/
- (BFTask *)lookupDeveloperIdentity:(AWSCognitoIdentityLookupDeveloperIdentityInput *)request;
/**
<p>Merges two users having different <code>IdentityId</code>s, existing in the same identity pool, and identified by the same developer provider. You can use this action to request that discrete users be merged and identified as a single user in the Cognito environment. Cognito associates the given source user (<code>SourceUserIdentifier</code>) with the <code>IdentityId</code> of the <code>DestinationUserIdentifier</code>. Only developer-authenticated users can be merged. If the users to be merged are associated with the same public provider, but as two different users, an exception will be thrown.</p>
@param request A container for the necessary parameters to execute the MergeDeveloperIdentities service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityMergeDeveloperIdentitiesResponse`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityMergeDeveloperIdentitiesInput
@see AWSCognitoIdentityMergeDeveloperIdentitiesResponse
*/
- (BFTask *)mergeDeveloperIdentities:(AWSCognitoIdentityMergeDeveloperIdentitiesInput *)request;
/**
SetIdentityPoolRoles
@param request A container for the necessary parameters to execute the SetIdentityPoolRoles service method.
@return An instance of `BFTask`. On successful execution, `task.result` will be `nil`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentitySetIdentityPoolRolesInput
*/
- (BFTask *)setIdentityPoolRoles:(AWSCognitoIdentitySetIdentityPoolRolesInput *)request;
/**
<p>Unlinks a <code>DeveloperUserIdentifier</code> from an existing identity. Unlinked developer users will be considered new identities next time they are seen. If, for a given Cognito identity, you remove all federated identities as well as the developer user identifier, the Cognito identity becomes inaccessible.</p>
@param request A container for the necessary parameters to execute the UnlinkDeveloperIdentity service method.
@return An instance of `BFTask`. On successful execution, `task.result` will be `nil`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityUnlinkDeveloperIdentityInput
*/
- (BFTask *)unlinkDeveloperIdentity:(AWSCognitoIdentityUnlinkDeveloperIdentityInput *)request;
/**
<p>Unlinks a federated identity from an existing account. Unlinked logins will be considered new identities next time they are seen. Removing the last linked login will make this identity inaccessible.</p>
@param request A container for the necessary parameters to execute the UnlinkIdentity service method.
@return An instance of `BFTask`. On successful execution, `task.result` will be `nil`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityUnlinkIdentityInput
*/
- (BFTask *)unlinkIdentity:(AWSCognitoIdentityUnlinkIdentityInput *)request;
/**
<p>Updates a user pool.</p>
@param request A container for the necessary parameters to execute the UpdateIdentityPool service method.
@return An instance of `BFTask`. On successful execution, `task.result` will contain an instance of `AWSCognitoIdentityIdentityPool`. On failed execution, `task.error` may contain an `NSError` with `AWSCognitoIdentityErrorDomain` domian and the following error code: `AWSCognitoIdentityErrorInvalidParameter`, `AWSCognitoIdentityErrorResourceNotFound`, `AWSCognitoIdentityErrorNotAuthorized`, `AWSCognitoIdentityErrorResourceConflict`, `AWSCognitoIdentityErrorTooManyRequests`, `AWSCognitoIdentityErrorInternalError`.
@see AWSCognitoIdentityIdentityPool
@see AWSCognitoIdentityIdentityPool
*/
- (BFTask *)updateIdentityPool:(AWSCognitoIdentityIdentityPool *)request;
@end
| 72.544041 | 1,955 | 0.799729 | [
"object"
] |
9aa624739f10f40d050d1a0dd8900dd644a2a5e1 | 2,912 | h | C | mitsuba/src/integrators/photonmapper/bre.h | anadodik/sdmm-mitsuba | 6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a | [
"MIT"
] | 6 | 2020-07-07T09:46:21.000Z | 2022-03-08T14:16:27.000Z | mitsuba/src/integrators/photonmapper/bre.h | anadodik/sdmm-mitsuba | 6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a | [
"MIT"
] | null | null | null | mitsuba/src/integrators/photonmapper/bre.h | anadodik/sdmm-mitsuba | 6103cb8ea36ec4ab0cfb5fcc792c7f1565637d9a | [
"MIT"
] | null | null | null | /*
This file is part of Mitsuba, a physically based rendering system.
Copyright (c) 2007-2014 by Wenzel Jakob and others.
Mitsuba is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License Version 3
as published by the Free Software Foundation.
Mitsuba is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(__BEAM_RADIANCE_ESTIMATOR_H)
#define __BEAM_RADIANCE_ESTIMATOR_H
#include <mitsuba/render/photonmap.h>
MTS_NAMESPACE_BEGIN
/**
* \brief Implements the beam radiance estimate described in
* "The Beam Radiance Estimator for Volumetric Photon Mapping"
* by Wojciech Jarosz, Matthias Zwicker, and Henrik Wann Jensen.
*/
class BeamRadianceEstimator : public SerializableObject {
public:
typedef PhotonMap::IndexType IndexType;
/**
* \brief Create a BRE acceleration data structure from
* an existing volumetric photon map
*/
BeamRadianceEstimator(const PhotonMap *pmap, size_t lookupSize);
/**
* \brief Unserialize a BRE acceleration data structure from
* a binary data stream
*/
BeamRadianceEstimator(Stream *stream, InstanceManager *manager);
/// Serialize to a binary data stream
void serialize(Stream *stream, InstanceManager *manager) const;
/// Compute the beam radiance estimate for the given ray segment and medium
Spectrum query(const Ray &ray, const Medium *medium) const;
MTS_DECLARE_CLASS()
protected:
/// Release all memory
virtual ~BeamRadianceEstimator();
/// Fit a hierarchy of bounding boxes to the stored photons
AABB buildHierarchy(IndexType index);
/// Blurring kernel used by the BRE
inline Float K2(Float sqrParam) const {
Float tmp = 1-sqrParam;
return (3/M_PI) * tmp * tmp;
}
/**
* \brief Return whether or not the inner node of the
* specified index has a right child node.
*
* This function is available for convenience and abstracts away some
* details about the underlying node representation.
*/
inline bool hasRightChild(IndexType index) const {
if (Photon::leftBalancedLayout) {
return 2*index+2 < m_photonCount;
} else {
return m_nodes[index].photon.getRightIndex(index) != 0;
}
}
protected:
struct BRENode {
AABB aabb;
Photon photon;
Float radius;
};
BRENode *m_nodes;
Float m_scaleFactor;
size_t m_photonCount;
size_t m_depth;
};
MTS_NAMESPACE_END
#endif /* __BEAM_RADIANCE_ESTIMATOR_H */
| 29.714286 | 79 | 0.698832 | [
"render"
] |
9aaa96abb3b1ca73ebd55263c882f45be4c166f7 | 936 | h | C | src/PlnConstants.h | tosyama/palan | ed809a26511366825cd0d7848b4444dcf8f09b1a | [
"MIT"
] | 32 | 2017-10-25T21:02:45.000Z | 2022-02-07T05:53:37.000Z | src/PlnConstants.h | tosyama/palan | ed809a26511366825cd0d7848b4444dcf8f09b1a | [
"MIT"
] | 39 | 2018-07-29T00:55:36.000Z | 2021-12-22T05:10:48.000Z | src/PlnConstants.h | tosyama/palan | ed809a26511366825cd0d7848b4444dcf8f09b1a | [
"MIT"
] | 1 | 2019-07-10T05:44:50.000Z | 2019-07-10T05:44:50.000Z | /// Difinition of constants to share.
///
/// @file PlnConstants.h
/// @copyright 2017-2016 YAMAGUCHI Toshinobu
#pragma once
// Data type on stack/register.
enum {
DT_SINT, /// Signed integer.
DT_UINT, /// Unsigned integer.
DT_FLOAT, /// Floating-point number.
DT_OBJECT, /// Instance of object.
DT_OBJECT_REF, /// Address of object.
DT_UNKNOWN /// Unkown data type. Not initialized.
};
// Function type.
enum {
FT_PLN, /// Palan standard function.
FT_INLINE, /// Palan inline function.
FT_C, /// C language function.
FT_SYS, /// System call.
FT_UNKNOWN /// Unkown function type. Not initialized.
};
// Comparison type.
enum PlnCmpType {
CMP_EQ,
CMP_NE,
CMP_G,
CMP_L,
CMP_GE,
CMP_LE,
CMP_A,
CMP_B,
CMP_AE,
CMP_BE,
CMP_CONST_TRUE,
CMP_CONST_FALSE
};
// Type mode
enum PlnTypeMode {
ACCESS_MD = 0,
IDENTITY_MD = 1,
ALLOC_MD = 2
};
enum PlnAsgnType {
NO_ASGN,
ASGN_COPY,
ASGN_MOVE,
ASGN_COPY_REF
};
| 16.714286 | 54 | 0.691239 | [
"object"
] |
9aaab40bf499168c2735c28ef98f83e12dad093a | 3,815 | h | C | tensorflow/lite/util.h | anonymous-313/tensorflow | b82785818b6b020d62340eaaece32b9c75858185 | [
"Apache-2.0"
] | 9 | 2019-06-05T06:48:07.000Z | 2020-09-29T07:08:02.000Z | tensorflow/lite/util.h | anonymous-313/tensorflow | b82785818b6b020d62340eaaece32b9c75858185 | [
"Apache-2.0"
] | 2 | 2021-11-10T20:21:47.000Z | 2022-02-10T04:12:28.000Z | tensorflow/lite/util.h | anonymous-313/tensorflow | b82785818b6b020d62340eaaece32b9c75858185 | [
"Apache-2.0"
] | 5 | 2021-05-03T12:45:32.000Z | 2022-02-08T19:28:18.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file provides general C++ utility functions in TFLite.
// For example: Converting between `TfLiteIntArray`, `std::vector` and
// Flatbuffer vectors. These functions can't live in `context.h` since it's pure
// C.
#ifndef TENSORFLOW_LITE_UTIL_H_
#define TENSORFLOW_LITE_UTIL_H_
#include <stddef.h>
#include <initializer_list>
#include <memory>
#include <string>
#include <vector>
#include "tensorflow/lite/c/common.h"
namespace tflite {
// Memory allocation parameter used by ArenaPlanner.
// Clients (such as delegates) might look at this to ensure interop between
// TFLite memory & hardware buffers.
// NOTE: This only holds for tensors allocated on the arena.
constexpr int kDefaultTensorAlignment = 64;
// The prefix of Flex op custom code.
// This will be matched agains the `custom_code` field in `OperatorCode`
// Flatbuffer Table.
// WARNING: This is an experimental API and subject to change.
constexpr char kFlexCustomCodePrefix[] = "Flex";
// Checks whether the prefix of the custom name indicates the operation is an
// Flex operation.
bool IsFlexOp(const char* custom_name);
// Converts a `std::vector` to a `TfLiteIntArray`. The caller takes ownership
// of the returned pointer.
TfLiteIntArray* ConvertVectorToTfLiteIntArray(const std::vector<int>& input);
// Converts an array (of the given size) to a `TfLiteIntArray`. The caller
// takes ownership of the returned pointer, and must make sure 'dims' has at
// least 'rank' elements.
TfLiteIntArray* ConvertArrayToTfLiteIntArray(const int rank, const int* dims);
// Checks whether a `TfLiteIntArray` and an int array have matching elements.
// The caller must guarantee that 'b' has at least 'b_size' elements.
bool EqualArrayAndTfLiteIntArray(const TfLiteIntArray* a, const int b_size,
const int* b);
size_t CombineHashes(std::initializer_list<size_t> hashes);
struct TfLiteIntArrayDeleter {
void operator()(TfLiteIntArray* a) {
if (a) TfLiteIntArrayFree(a);
}
};
// Helper for Building TfLiteIntArray that is wrapped in a unique_ptr,
// So that it is automatically freed when it goes out of the scope.
std::unique_ptr<TfLiteIntArray, TfLiteIntArrayDeleter> BuildTfLiteIntArray(
const std::vector<int>& data);
// Populates the size in bytes of a type into `bytes`. Returns kTfLiteOk for
// valid types, and kTfLiteError otherwise.
TfLiteStatus GetSizeOfType(TfLiteContext* context, const TfLiteType type,
size_t* bytes);
// Creates a stub TfLiteRegistration instance with the provided
// `custom_op_name`. The op will fail if invoked, and is useful as a
// placeholder to defer op resolution.
// Note that `custom_op_name` must remain valid for the returned op's lifetime..
TfLiteRegistration CreateUnresolvedCustomOp(const char* custom_op_name);
// Checks whether the provided op is an unresolved custom op.
bool IsUnresolvedCustomOp(const TfLiteRegistration& registration);
// Returns a descriptive name with the given op TfLiteRegistration.
std::string GetOpNameByRegistration(const TfLiteRegistration& registration);
} // namespace tflite
#endif // TENSORFLOW_LITE_UTIL_H_
| 39.329897 | 80 | 0.748624 | [
"vector"
] |
9aae2377e3bc99dec2eb114c31f459ac2cc2fcc8 | 6,746 | c | C | sources/nb/solver_bot/sparse/solvers/cg_precond_fsai.c | vecn/nbots | bda4f5a2c607c8e6d26567bb0865ccbb953418ac | [
"MIT"
] | 7 | 2016-02-09T17:53:25.000Z | 2019-09-19T02:02:14.000Z | sources/nb/solver_bot/sparse/solvers/cg_precond_fsai.c | vecn/nbots | bda4f5a2c607c8e6d26567bb0865ccbb953418ac | [
"MIT"
] | 1 | 2017-06-22T06:20:24.000Z | 2017-06-22T06:20:24.000Z | sources/nb/solver_bot/sparse/solvers/cg_precond_fsai.c | vecn/nbots | bda4f5a2c607c8e6d26567bb0865ccbb953418ac | [
"MIT"
] | 2 | 2018-02-08T12:09:50.000Z | 2019-09-19T02:02:23.000Z | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "nb/math_bot.h"
#include "nb/memory_bot.h"
#include "nb/container_bot.h"
#include "nb/solver_bot.h"
#include "../sparse_struct.h"
#define POW2(a) ((a)*(a))
int nb_sparse_solve_CG_precond_fsai
(const nb_sparse_t *const A,
const double *const b,
double *_x, /* Out */
double threshold,
uint32_t max_iter, double tolerance,
uint32_t* niter_performed, /* Out (NULL if not required) */
double* tolerance_reached, /* Out (NULL if not required) */
uint32_t omp_parallel_threads)
/* Return the num of iterations */
{
/* Conjugate gradient preconditioned with "Factorized sparse
* approximated inverse"
*/
double *D = nb_allocate_zero_mem(A->N * sizeof(double));
double *siD = nb_allocate_zero_mem(A->N * sizeof(double));
nb_sparse_t* G = nb_sparse_allocate(A->N);
nb_sparse_t* Gt = nb_sparse_allocate(A->N);
/* Generate D diagonal matrix as
*
* Dii = |Aii|, if |Aii| > 0
* 1 otherwise
*/
#pragma omp parallel for num_threads(omp_parallel_threads)
for(uint32_t i=0; i < A->N; i++){
D[i] = nb_sparse_get(A,i,i);
if(D[i] == 0)
D[i] = 1;
/* Compute D^(-1/2) */
siD[i] = 1/sqrt(D[i]);
}
/* Generate structure of G lower triangular matrix
*
* G = 1 , if (i == j) or (|[D^(-1/2) A D^(-1/2)]_ij| > threshold)
* 0 , otherwise
*
*/
for(uint32_t i=0; i < A->N; i++){
uint32_t isize = 0;
uint32_t isizet = 0;
#pragma omp parallel for reduction(+:isize,isizet) num_threads(omp_parallel_threads)
for(uint32_t q=0; q< A->rows_size[i]; q++){
uint32_t j = A->rows_index[i][q];
if(i == j ||
fabs(siD[i] * A->rows_values[i][q] * siD[j])
> threshold){
if(i > j)
isize++;
else if(i < j)
isizet++;
else{
isize++;
isizet++;
}
}
}
G->rows_size[i] = isize;
G->rows_index[i] = nb_allocate_zero_mem(isize *
sizeof(uint32_t));
G->rows_values[i] = nb_allocate_zero_mem(isize *
sizeof(double));
Gt->rows_size[i] = isizet;
Gt->rows_index[i] = nb_allocate_zero_mem(isizet *
sizeof(uint32_t));
Gt->rows_values[i] = nb_allocate_zero_mem(isizet *
sizeof(double));
}
#pragma omp parallel for num_threads(omp_parallel_threads)
for(uint32_t i=0; i < A->N; i++){
/* Compute values of ~G */
double* subA =
nb_allocate_zero_mem(POW2(G->rows_size[i]) *
sizeof(double));
/* The data of vector g is not allocated, is a pointer to each row of ~G */
double* subg = G->rows_values[i];
double *delta = nb_allocate_zero_mem(G->rows_size[i] *
sizeof(double));
uint32_t k = 0;
for(uint32_t q = 0; q < A->rows_size[i]; q++){
uint32_t j = A->rows_index[i][q];
if(i == j ||
fabs(siD[i] * A->rows_values[i][q] * siD[j]) > threshold){
if(i >= j){
G->rows_index[i][k] = j;
for(uint32_t l=0; l<k; l++){
subA[k*G->rows_size[i] + l] =
nb_sparse_get(A,j,G->rows_index[i][l]);
subA[l*G->rows_size[i] + k] =
nb_sparse_get(A,G->rows_index[i][l],j);
}
subA[k*G->rows_size[i] + k] = nb_sparse_get(A,j,j);
if(i == j)
delta[k] = 1;
else
delta[k] = 0;
k++;
}
}
}
double* L = nb_allocate_zero_mem(POW2(G->rows_size[i]) *
sizeof(double));
nb_matrix_cholesky_decomposition(subA, L, G->rows_size[i]);
nb_matrix_cholesky_solve(L, delta, subg, G->rows_size[i]);
/* Finally do G = [~G]*D */
for(uint32_t q=0; q < G->rows_size[i]; q++)
G->rows_values[i][q] *= D[G->rows_index[i][q]];
/* Free memory */
nb_free_mem(subA);
nb_free_mem(L);
nb_free_mem(delta);
}
/* Store G transposed */
nb_sparse_get_transpose(G,Gt);
/* Free memory */
nb_free_mem(D);
nb_free_mem(siD);
/* Solve Ax = b with Conjugate Gradient method */
double* r = nb_allocate_zero_mem(A->N * sizeof(double));
double* p = nb_allocate_zero_mem(A->N * sizeof(double));
double* w = nb_allocate_zero_mem(A->N * sizeof(double));
double* Gr = nb_allocate_zero_mem(A->N * sizeof(double));
double* Mr = nb_allocate_zero_mem(A->N * sizeof(double));
double dot_rr = 0;
#pragma omp parallel for reduction(+:dot_rr) schedule(guided) num_threads(omp_parallel_threads)
for(uint32_t i=0; i< A->N; i++){
double Ax_i = 0;
for(uint32_t j=0; j< A->rows_size[i]; j++)
Ax_i += A->rows_values[i][j] * _x[A->rows_index[i][j]];
r[i] = b[i] - Ax_i;
dot_rr += r[i]*r[i];
}
/* Compute Gr */
#pragma omp parallel for num_threads(omp_parallel_threads)
for(uint32_t i=0; i< A->N; i++){
Gr[i] = 0;
for(uint32_t j=0; j< G->rows_size[i]; j++)
Gr[i] += G->rows_values[i][j] * r[G->rows_index[i][j]];
}
/* Compute Mr <- G'(Gr) */
#pragma omp parallel for num_threads(omp_parallel_threads)
for(uint32_t i=0; i< A->N; i++){
Mr[i] = 0;
for(uint32_t j=0; j< Gt->rows_size[i]; j++)
Mr[i] += Gt->rows_values[i][j] * Gr[Gt->rows_index[i][j]];
p[i] = Mr[i];
}
uint32_t k = 0;
/* Start iterations */
while(dot_rr > tolerance*tolerance && k < max_iter){
double dot_pw = 0;
double dot_rMr = 0;
#pragma omp parallel for reduction(+:dot_pw, dot_rMr) num_threads(omp_parallel_threads) schedule(guided)
for(uint32_t i=0; i< A->N; i++){
w[i] = 0;
for(uint32_t j=0; j< A->rows_size[i]; j++)
w[i] += A->rows_values[i][j] * p[A->rows_index[i][j]];
dot_pw += p[i]*w[i];
dot_rMr += r[i]*Mr[i];
}
double alphak = dot_rMr/dot_pw;
dot_rr = 0;
#pragma omp parallel for reduction(+:dot_rr) num_threads(omp_parallel_threads) schedule(guided)
for(uint32_t i=0; i< A->N; i++){
_x[i] += alphak*p[i];
r[i] -= alphak*w[i];
dot_rr += r[i]*r[i];
}
/* Compute Gr */
#pragma omp parallel for num_threads(omp_parallel_threads)
for(uint32_t i=0; i< A->N; i++){
Gr[i] = 0;
for(uint32_t j=0; j< G->rows_size[i]; j++)
Gr[i] += G->rows_values[i][j] * r[G->rows_index[i][j]];
}
/* Compute Mr <- G'(Gr) */
double dot_rkMrk = 0;
#pragma omp parallel for reduction(+:dot_rkMrk) num_threads(omp_parallel_threads)
for(uint32_t i=0; i< A->N; i++){
Mr[i] = 0;
for(uint32_t j=0; j< Gt->rows_size[i]; j++)
Mr[i] += Gt->rows_values[i][j] * Gr[Gt->rows_index[i][j]];
dot_rkMrk += r[i]*Mr[i];
}
double betak = dot_rkMrk/dot_rMr;
#pragma omp parallel for num_threads(omp_parallel_threads)
for(uint32_t i=0; i< A->N; i++)
p[i] = Mr[i] + betak*p[i];
k++;
}
/* Free memory */
nb_sparse_destroy(G);
nb_sparse_destroy(Gt);
nb_free_mem(r);
nb_free_mem(p);
nb_free_mem(w);
nb_free_mem(Gr);
nb_free_mem(Mr);
if(niter_performed != NULL) niter_performed[0]= k;
if(tolerance_reached != NULL) *tolerance_reached = sqrt(dot_rr);
if(dot_rr > tolerance*tolerance)
return 1;
return 0;
}
| 27.991701 | 104 | 0.610881 | [
"vector"
] |
9ab4904edefb5a3c8f6e9ef2f0d49704f1989891 | 50,213 | c | C | terminal_programs/editor.c | samiam95124/petit-ami | 5cd9175744d0cc8aa58250e43943a09b56487ae3 | [
"BSD-3-Clause"
] | null | null | null | terminal_programs/editor.c | samiam95124/petit-ami | 5cd9175744d0cc8aa58250e43943a09b56487ae3 | [
"BSD-3-Clause"
] | null | null | null | terminal_programs/editor.c | samiam95124/petit-ami | 5cd9175744d0cc8aa58250e43943a09b56487ae3 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* *
* TEXT EDITTOR *
* *
* VS. 0.1 *
* *
* COPYRIGHT (C) 1996 *
* *
* S. A. MOORE *
* *
* Implements a basic screen based editor with Petit-ami. The standard controls *
* are implemented, plus the following function keys: *
* *
* F1 - Search *
* F2 - Search again *
* F3 - Replace *
* F4 - Replace again *
* F5 - Record macro start/stop *
* F6 - Playback macro *
* F7 - Save file *
* *
********************************************************************************/
#include <stdio.h>
#include <setjmp.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <localdefs.h>
#include <terminal.h>
#define MAXLIN 250 /* maximum entered line, must be greater than maxx */
#define MAXFIL 40 /* maximum length of filename */
typedef char* string; /* general string type */
typedef int lininx; /* index for line buffer */
typedef char linbuf[MAXLIN]; /* line buffer */
typedef struct line* linptr; /* pointer to line entry */
/* The lines in the edit buffer are stored as a double linked list of
dynamically allocated strings */
typedef struct line { /* line store entry */
linptr next; /* next line in store */
linptr last; /* last line in store */
string str; /* string data */
} line;
typedef int filinx; /* index for filename */
typedef char filbuf[MAXFIL]; /* filename */
typedef struct crdrec* crdptr; /* pointer to coordinate store */
typedef struct crdrec { /* cursor coordinate save */
crdptr next; /* next entry */
int x, y; /* cursor coordinates */
} crdrec;
linbuf inpbuf; /* input line buffer */
int buflin; /* current line in buffer flag */
linptr linstr; /* edit lines storage */
linptr paglin; /* top of page line */
int lincnt; /* number of lines in buffer */
int chrcnt; /* number of characters in buffer */
int linpos; /* current line */
int poschr; /* current character on line */
filbuf curfil; /* current file to edit */
pa_evtrec er; /* next event record */
crdptr curstk; /* cursor coordinate stack */
int mpx; /* mouse coordinates x */
int mpy; /* mouse coordinates y */
int insertc; /* insert/overwrite toggle */
linbuf cmdlin; /* command line */
lininx cmdptr; /* command line pointer */
jmp_buf inputloop_buf; /* buffer for return to input loop */
int redraws; /* in error display */
void errormsg(string s);
/*******************************************************************************
Find space padded strng length
Finds the true length of a string, without right hand padding.
*******************************************************************************/
int len(string s)
{
int i;
i = strlen(s)-1;
while (i > 0 && s[i] == ' ') i--;
if (s[i] != ' ') i++;
return i;
}
/*******************************************************************************
Push cursor coordinates
Saves the current cursor coordinates on the cursor coordinate stack.
*******************************************************************************/
void pshcur(void)
{
crdptr p; /* coordinate entry pointer */
p = malloc(sizeof(crdrec)); /* get a new stack entry */
if (!p) errormsg("*** Out of memory");
p->next = curstk; /* push onto stack */
curstk = p;
p->x = pa_curx(stdout); /* place save coordinates */
p->y = pa_cury(stdout);
}
/*******************************************************************************
Pop cursor coordinates
Restores the current cursor coordinates from the cursor coordinate stack.
*******************************************************************************/
void popcur(void)
{
crdptr p; /* coordinate entry pointer */
if (curstk != NULL) { /* cursor stack is not empty */
pa_cursor(stdout, curstk->x, curstk->y); /* restore old cursor position */
p = curstk; /* remove from stack */
curstk = curstk->next;
free(p); /* release entry */
}
}
/*******************************************************************************
Update status line
Draws the status line at screen bottom. The status line contains the name of
the current file, the line position, the character position, and the
insert/overwrite status.
*******************************************************************************/
void status(void)
{
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save cursor position */
pa_bcolor(stdout, pa_cyan); /* a nice (light) blue, if you please */
pa_cursor(stdout, 1, pa_maxy(stdout)); /* position to end line on screen */
printf("File: %-*s Line: %6d Char: %3d", MAXFIL, curfil, linpos, poschr);
if (insertc) printf(" Ins"); else printf(" Ovr"); /* write insert status */
while (pa_curx(stdout) < pa_maxx(stdout))
putchar(' '); /* blank out the rest */
putchar(' ');
pa_bcolor(stdout, pa_white); /* back to white */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
redraws = FALSE; /* set no redraw */
}
/*******************************************************************************
Update line position
Redraws just the line position in the status line.
*******************************************************************************/
void statusl(void)
{
if (redraws) status(); /* redraw complete */
else {
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save cursor position */
pa_bcolor(stdout, pa_cyan); /* a nice (light) blue, if you please */
pa_cursor(stdout, 54, pa_maxy(stdout)); /* go to line position field */
printf("%6d", linpos); /* update cursor position */
pa_bcolor(stdout, pa_white); /* reset color */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
}
}
/*******************************************************************************
Update character position
Redraws just the character position in the status line.
*******************************************************************************/
void statusc(void)
{
if (redraws) status(); /* redraw complete */
else {
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save cursor position */
pa_bcolor(stdout, pa_cyan); /* a nice (light) blue, if you please */
pa_cursor(stdout, 67, pa_maxy(stdout)); /* go to character position field */
printf("%3d", poschr); /* update cursor position */
pa_bcolor(stdout, pa_white); /* reset color */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
}
}
/*******************************************************************************
Update insert status
Redraws just the insert status in the status line.
*******************************************************************************/
void statusi(void)
{
if (redraws) status(); /* redraw complete */
else {
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save cursor position */
pa_bcolor(stdout, pa_cyan); /* a nice (light) blue, if you please */
pa_cursor(stdout, 71, pa_maxy(stdout)); /* go to character position field */
if (insertc) printf("Ins"); else printf("Ovr"); /* write insert status */
pa_bcolor(stdout, pa_white); /* reset color */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
}
}
/*******************************************************************************
Place information line on screen
Places the information line on screen. The specified string is placed on screen
at the status line position (bottom of screen), in the alert colors.
This will be overwritten by the next status change.
*******************************************************************************/
void info(string s)
{
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save cursor position */
pa_bcolor(stdout, pa_yellow); /* place alert color */
pa_cursor(stdout, 1, pa_maxy(stdout)); /* position to end line on screen */
if (*s) printf("%s", s); /* output string */
while (pa_curx(stdout) <= pa_maxx(stdout))
putchar(' '); /* blank out the rest */
pa_bcolor(stdout, pa_white); /* back to white */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
redraws = TRUE; /* set to redraw */
}
/*******************************************************************************
Process error
Places an information line in the status area, and aborts to input mode.
*******************************************************************************/
void errormsg(string s)
{
info(s); /* place error message */
longjmp(inputloop_buf, 1); /* back to input */
}
/*******************************************************************************
Place line at buffer end
Places the given string at the end of the current editor buffer as a new line
entry.
*******************************************************************************/
void plclin(string s)
{
linptr lp; /* pointer to line entry */
lininx i; /* index for line */
lp = malloc(sizeof(line)); /* get a new line entry */
lp->str = malloc(strlen(s)+1); /* get space for string */
strcpy(lp->str, s); /* copy string into place */
/* insert after line indexed as current */
if (!linstr) { /* this is the first line */
lp->next = lp; /* self link the entry */
lp->last = lp;
linstr = lp; /* and place root */
paglin = linstr; /* place the page pin */
} else { /* store not empty */
lp->next = linstr; /* link to next */
lp->last = linstr->last; /* link to last */
lp->next->last = lp; /* link next to this */
lp->last->next = lp; /* link last to this */
}
lincnt++; /* count lines in buffer */
}
/*******************************************************************************
Write line to display
Outputs the given line, truncated to the screen width. The line is checked for
control characters, and if found, these are replaced by "\".
*******************************************************************************/
void wrtlin(int y, /* position to place string */
string s) /* string to place */
{
int i; /* string index */
pa_cursor(stdout, 1, y); /* position to start of line */
for (i = 0; i < pa_maxx(stdout); i++) { /* write characters */
if (i+1 > strlen(s)) putchar(' '); /* pad end with blanks */
else if (s[i] >= ' ') putchar(s[i]); /* output as is */
else { /* is a control character */
pa_fcolor(stdout, pa_red); /* place in red */
pa_bcolor(stdout, pa_yellow);
putchar(s[i]+'@'); /* output as control sequence */
pa_fcolor(stdout, pa_black); /* back to normal */
pa_bcolor(stdout, pa_white);
}
}
}
/*******************************************************************************
Update entire screen display
Repaints the entire screen, including body text and status line. Takes a flag
to indicate if we will clear the screen or not. Screen geometry changes don't
need a clear, it just flashes the screen.
*******************************************************************************/
void update(int clr)
{
linptr lp; /* pointer to line entry */
int lc; /* line counter */
int y; /* y position holder */
pa_curvis(stdout, FALSE); /* turn off cursor */
if (clr) putchar('\f'); /* clear screen and home cursor */
lp = paglin; /* index top of page line */
lc = pa_maxy(stdout)-1; /* set number of lines to output */
y = 1; /* set 1st line */
if (lp) do { /* write lines */
wrtlin(y, lp->str); /* output line */
lp = lp->next; /* next line */
y = y+1;
lc = lc-1; /* count available lines on screen */
/* until we wrap around, or screen full */
} while (lp != linstr && lc != 0);
pa_curvis(stdout, TRUE); /* turn on cursor */
status(); /* replace status line */
pa_home(stdout); /* place cursor at home */
}
/*******************************************************************************
Read text line
Reads a line from the given text file into a string buffer. Returns EOF if end
of file is encountered and there were no characters available.
This routine should check for overflow.
*******************************************************************************/
int getlin(FILE* f, /* file to read */
string s, /* string to read to */
int l) /* string length */
{
int i; /* index for string */
char c;
for (i = 0; i < l; i++) s[i] = ' '; /* clear destination line */
i = 0; /* set 1st character position */
c = fgetc(f);
while (c != '\n' && c != EOF) { /* read line characters */
/* should check for line overflow */
s[i] = c; /* get the next character */
i = i+1;
c = fgetc(f);
}
s[i] = 0; /* place end of string */
return (c == EOF && !i); /* return EOF status */
}
/*******************************************************************************
Find current buffer line
Finds the current line in the buffer based on screen position, and returns
a line pointer to that entry.
*******************************************************************************/
linptr fndcur(void)
{
linptr lp; /* pointer to line */
int lc; /* line count */
lp = paglin; /* index page pin */
lc = pa_cury(stdout); /* get current line position */
while (lp && lc != 1) { /* walk down */
lp = lp->next; /* next line */
lc = lc-1; /* count */
/* if we wrapped around to the starting line, that is the end */
if (lp == linstr) lp = NULL;
}
return lp; /* return result */
}
/*******************************************************************************
Pull current line to buffer
The current line is "pulled" to the input buffer. In order to keep from
generating a lot of fractional lines, we keep the current line in a fixed
length buffer during edit on that line. Pulling a line is done before any
within-line edit void is done.
*******************************************************************************/
void getbuf(void)
{
linptr lp; /* pointer to current line */
int i; /* index for line */
int l; /* length of line */
if (!buflin) { /* line not in buffer */
for (i = 0; i < MAXLIN; i++) inpbuf[i] = ' '; /* clear input buffer */
lp = fndcur(); /* find current line */
if (lp) {
/* copy without terminating 0 */
l = strlen(lp->str);
for (i = 0; i < l; i++) inpbuf[i] = lp->str[i];
}
buflin = TRUE; /* set line in buffer */
}
}
/*******************************************************************************
Put buffer to current line
If the current line is held in the input buffer, we put it back to the current
line position. This is done by disposing of the contents of the old string,
and allocating and filling a new string.
It is possible for the current line to be null, which means that the buffer
is in the "virtual" space below the bottom of the file. In this case, we must
allocate a series of blank lines until we reach the current line position.
Since any command that moves off the current line will run into problems with
the fiction that having the current line cached in the buffer causes, this
routine should be called before any such movement or operation.
*******************************************************************************/
void putbuf(void)
{
linptr lp; /* pointer to current line */
int i; /* index for line */
int lc; /* line counter */
int l; /* length of buffered line */
if (buflin) { /* the line is in the buffer */
lp = fndcur(); /* find the current line */
if (!lp) { /* beyond end, create lines */
/* find number of new lines needed */
lp = paglin; /* index page pin */
lc = pa_cury(stdout); /* get current line position */
while (lp) { /* walk down */
lp = lp->next; /* next line */
lc--; /* count */
/* if we wrapped around to the starting line, that is the end */
if (lp == linstr) lp = NULL;
}
/* place blank lines to fill */
while (lc > 0) { plclin(""); lc--; }
lp = fndcur(); /* now find that */
}
/* ok, there is a dirty (but workable) trick here. notice that if we have
created blank lines below the buffer, we will be disposing of that
newly created blank line. this does not waste storage, however, because
zero length allocations don't actually exist. Note that this works
regardless of standard C interpretation. */
free(lp->str); /* remove old line */
l = len(inpbuf); /* find length of buffered line */
lp->str = malloc(l+1); /* create a new string */
strncpy(lp->str, inpbuf, l); /* copy to string */
inpbuf[l] = 0; /* terminate string */
buflin = FALSE; /* set line not in buffer */
}
}
/*******************************************************************************
Read file into buffer
The current buffer is cleared, and the given file is read in as a new buffer
contents.
*******************************************************************************/
void readfile(string fn) /* file to read */
{
FILE* f; /* text file */
linbuf ln; /* input line buffer */
int ef; /* end of file indication */
putbuf(); /* decache any buffer */
info("Reading file");
/* we should dispose of existing lines before this operation */
linstr = NULL; /* clear lines buffer */
lincnt = 0; /* clear total lines */
chrcnt = 0; /* clear total characters */
linpos = 1; /* set 1st line */
poschr = 1; /* set 1st character */
f = fopen(fn, "r"); /* open the input file */
if (!f) info("*** Cannot open file ***");
ef = FALSE;
while (!ef) { /* read lines */
ef = getlin(f, ln, MAXLIN); /* get the next line */
if (!ef) plclin(ln); /* place in edit buffer */
}
fclose(f); /* close input file */
paglin = linstr; /* index top of buffer */
update(TRUE); /* display that */
}
/*******************************************************************************
Write file from buffer
The current buffer is written to the given file.
*******************************************************************************/
void writefile(string fn) /* file to read */
{
FILE* f; /* text file */
linptr lp; /* line pointer */
putbuf(); /* decache any buffer */
info("Writing file");
f = fopen(fn, "w"); /* open the output file */
if (!f) info("*** Cannot open file ***");
lp = linstr; /* index top of buffer */
while (lp) { /* write lines */
fprintf(f, "%s\n", lp->str); /* output line to file */
lp = lp->next; /* go next line */
if (lp == linstr) lp = NULL; /* line wrapped to top, signal end */
}
fclose(f); /* close input file */
status(); /* refresh status line */
}
/*******************************************************************************
Move up one line
Moves the cursor position up one line. If the cursor is already at the top
of screen, then the screen is scrolled up to the next line (if it exists).
*******************************************************************************/
void movup(void)
{
putbuf(); /* decache any buffer */
if (linstr) { /* buffer not empty */
if (paglin != linstr || pa_cury(stdout) > 1) {
/* not at top of buffer, or not at top of displayed page */
linpos--; /* adjust line count */
/* if we aren't already at the top of screen, we can just move up */
if (pa_cury(stdout) > 1) {
pa_up(stdout); /* move cursor up */
statusl(); /* update just line position field */
} else { /* gotta scroll */
pa_curvis(stdout, FALSE); /* turn off cursor */
pa_scroll(stdout, 0, -1); /* scroll the screen down */
paglin = paglin->last; /* move page pin up */
pshcur(); /* save cursor position */
pa_home(stdout); /* go to top line */
wrtlin(1, paglin->str); /* output that line */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
status(); /* update status line */
}
}
}
}
/*******************************************************************************
Move down one line
Moves the cursor position down one line. If the cursor is already at the bottom
of screen, then the screen is scrolled down to the next line (if it exists).
Note that we allow positioning past the end of the buffer by one screen minus
one lines worth of text, which would leave the last line at the top.
*******************************************************************************/
void movdwn(void)
{
int lc; /* line counter */
linptr lp; /* line pointer */
putbuf(); /* decache any buffer */
if (linstr) { /* buffer not empty */
if (pa_cury(stdout) < pa_maxy(stdout)-1 ||
paglin->next != linstr) { /* not at last line */
/* Not last line on screen, or more lines left in buffer. We are a
"virtual space" editor, so we fake lines below the buffer end
as being real */
linpos++; /* adjust line count */
/* if we aren't already at the bottom of screen, we can just move
down */
if (pa_cury(stdout) < pa_maxy(stdout)-1) {
pa_down(stdout); /* move cursor down */
statusl(); /* update just line position field */
} else { /* gotta scroll */
/* clear last line */
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save current position */
pa_cursor(stdout, 1, pa_maxy(stdout));
while (pa_curx(stdout) < pa_maxx(stdout)) putchar(' ');
putchar(' ');
popcur(); /* restore cursor position */
pa_scroll(stdout, 0, +1); /* scroll the screen up */
paglin = paglin->next; /* move page pin down */
/* see if a line exists to fill the new slot */
lc = 1; /* set 1st line */
lp = paglin;
/* while not end of buffer, and on valid screen portion */
while (lp != linstr && lc < pa_maxy(stdout)-1) {
lp = lp->next; /* index next line */
lc++; /* count */
}
if (lp != linstr && lc < pa_maxy(stdout)) {
/* new line exists */
pshcur(); /* save cursor position */
wrtlin(pa_maxy(stdout)-1, lp->str); /* output that line */
popcur(); /* restore cursor position */
}
pa_curvis(stdout, TRUE); /* turn on cursor */
status(); /* repaint status line */
}
}
}
}
/*******************************************************************************
Move left one character
If we are not already at the extreme left, moves the cursor one character to
the left.
*******************************************************************************/
void movlft(void)
{
if (pa_curx(stdout) > 1) { /* not at extreme left */
pa_left(stdout); /* move cursor left */
poschr--; /* track character position */
statusc(); /* update just character position field */
}
}
/*******************************************************************************
Move right one character
If we are not already at the extreme right, moves the cursor one character to
the right.
*******************************************************************************/
void movrgt(void)
{
if (pa_curx(stdout) < pa_maxx(stdout)) { /* not at extreme right */
pa_right(stdout); /* move cursor right */
poschr++; /* track character position */
statusc(); /* update just character position field */
}
}
/*******************************************************************************
Go to top of document
Moves the cursor to the top of the document.
*******************************************************************************/
void movhom(void)
{
putbuf(); /* decache any buffer */
if (linstr) { /* buffer not empty */
linpos = 1; /* set 1st line */
poschr = 1; /* set 1st character */
if (paglin == linstr) {
/* we are at top, just move the cursor there */
pa_home(stdout); /* move home */
status(); /* update status */
} else { /* not at top, go there */
paglin = linstr; /* set page to home */
update(TRUE); /* redraw */
}
}
}
/*******************************************************************************
Go to bottom of document
Moves the cursor to the bottom of the document.
*******************************************************************************/
void movend(void)
{
linptr lp; /* line pointer */
int lc; /* line count */
int oc; /* offset count */
putbuf(); /* decache any buffer */
if (linstr) { /* buffer not empty */
lc = lincnt; /* set last line */
lp = linstr->last;
/* The "offset count" is the number of lines to back off from the true
end of the file. This is choosen to be 1/2 screenfull */
oc = (pa_maxy(stdout)-1)/2;
/* now back up to the offset point, or the beginning of file */
while (lp != linstr && oc) { /* back up */
lp = lp->last; /* index last line */
oc--; /* count */
lc--;
}
linpos = lincnt; /* set new line position */
poschr = strlen(linstr->last->str)+1; /* set new character position */
if (lp != paglin) { /* we are not already there */
paglin = lp; /* set new position */
update(TRUE); /* redraw */
}
pa_cursor(stdout, poschr, (pa_maxy(stdout)-1)/2+1);
}
}
/*******************************************************************************
Go to start of line
Moves the cursor to the start of the current line..
*******************************************************************************/
void movhoml(void)
{
poschr = 1; /* update position */
pa_cursor(stdout, 1, pa_cury(stdout)); /* move cursor */
statusc(); /* update status */
}
/*******************************************************************************
Go to end of line
Moves the cursor to the end of the current line..
*******************************************************************************/
void movendl(void)
{
linptr lp; /* pointer to line */
if (buflin) /* line is in buffer */
poschr = len(inpbuf)+1; /* set new position */
else { /* line is in file */
lp = fndcur(); /* find current line */
if (lp) poschr = strlen(lp->str)+1; /* set new position */
else poschr = 1; /* no line, position to start for empty line */
}
/* if the line was full, we cannot position past it */
if (poschr > pa_maxx(stdout)) poschr = pa_maxx(stdout);
pa_cursor(stdout, poschr, pa_cury(stdout)); /* move cursor */
statusc(); /* update status */
}
/*******************************************************************************
Go to top of screen
Moves the cursor to the top of the current screen.
*******************************************************************************/
void movhoms(void)
{
putbuf(); /* decache any buffer */
linpos = linpos-pa_cury(stdout)+1; /* set new position */
poschr = 1;
pa_home(stdout); /* position cursor */
status(); /* update status line */
}
/*******************************************************************************
Go to bottom of screen
Moves the cursor to the bottom of the current screen.
*******************************************************************************/
void movends(void)
{
linptr lp; /* pointer to line */
putbuf(); /* decache any buffer */
linpos = linpos+pa_maxy(stdout)-pa_cury(stdout); /* set new position */
lp = fndcur(); /* find current line */
if (lp) poschr = strlen(lp->str)+1; /* set new position */
else poschr = 1; /* no line, position to start for empty line */
pa_cursor(stdout, poschr, pa_maxy(stdout)-1); /* move cursor */
statusc(); /* update status */
}
/*******************************************************************************
Page up
Moves the position up by one screen minus one lines worth of text. One line
of overlap is allowed to give the user some context.
If there is not that much text above, we just position to the top of document.
*******************************************************************************/
void pagup(void)
{
int cnt;
putbuf();; /* decache any buffer */
if (paglin) { /* buffer not empty */
if (paglin == linstr) { /* already at top, just home cursor */
linpos = 1; /* set new position */
pa_cursor(stdout, poschr, 1); /* set to top of screen */
status(); /* update status line */
} else {
/* find number of lines on a page, minus status and slop line */
cnt = pa_maxy(stdout)-2;
/* move up to appropriate line */
while (cnt > 0 && paglin->last && paglin != linstr) {
paglin = paglin->last; /* move up one line */
cnt--; /* count lines */
linpos--;
}
pshcur(); /* push cursor coordinates */
update(TRUE); /* redraw */
popcur(); /* restore cursor coordinates */
}
}
}
/*******************************************************************************
Page down
Moves the position down by one screen minus one lines worth of text. One line
of overlap is allowed to give the user some context.
We allow positioning beyond the end of document by one screen minus one line
of text. If there is not that many lines to the "virtual end point", we just
position to the virtual end point.
*******************************************************************************/
void pagdwn(void)
{
int cnt;
putbuf(); /* decache any buffer */
if (paglin) { /* buffer not empty */
if (paglin->next != linstr) { /* not at end of buffer */
/* find number of lines on a page, minus status and slop line */
cnt = pa_maxy(stdout)-2;
/* move down to appropriate line */
while (cnt > 0 && paglin->next && paglin->next != linstr) {
paglin = paglin->next; /* move down one line */
cnt--; /* count lines */
linpos++;
}
pshcur(); /* push cursor coordinates */
update(TRUE); /* redraw */
popcur(); /* restore cursor coordinates */
}
}
}
/*******************************************************************************
Scroll up one line
The screen is scrolled up by one line, revealing at new line at bottom.
*******************************************************************************/
void scrup(void)
{
putbuf(); /* decache any buffer */
if (paglin != linstr) { /* not empty and not at buffer top */
/* not at top of buffer, or not at top of displayed page */
linpos--; /* adjust line count */
pa_curvis(stdout, FALSE); /* turn off cursor */
pa_scroll(stdout, 0, -1); /* scroll the screen down */
paglin = paglin->last; /* move page pin up */
pshcur(); /* save cursor position */
pa_home(stdout); /* go to top line */
if (strlen(paglin->str))
printf("%s", paglin->str); /* write revealed line over blanks */
popcur(); /* restore cursor position */
pa_curvis(stdout, TRUE); /* turn on cursor */
status(); /* update status line */
}
}
/*******************************************************************************
Scroll down one line
The screen is scrolled down by one line, revealing at new line at top.
*******************************************************************************/
void scrdwn(void)
{
int lc; /* line counter */
linptr lp; /* line pointer */
putbuf(); /* decache any buffer */
if (linstr) { /* buffer not empty */
if (paglin->next != linstr) { /* not at last line */
linpos++; /* adjust line count */
/* clear last line */
pa_curvis(stdout, FALSE); /* turn off cursor */
pshcur(); /* save current position */
pa_cursor(stdout, 1, pa_maxy(stdout));
while (pa_curx(stdout) < pa_maxx(stdout)) putchar(' ');
putchar(' ');
popcur(); /* restore cursor position */
pa_scroll(stdout, 0, +1); /* scroll the screen up */
paglin = paglin->next; /* move page pin down */
/* see if a line exists to fill the new slot */
lc = 1; /* set 1st line */
lp = paglin;
/* while not end of buffer, and on valid screen portion */
while (lp != linstr && lc < pa_maxy(stdout)-1) {
lp = lp->next; /* index next line */
lc++; /* count */
}
if (lp != linstr && lc < pa_maxy(stdout)) {
/* new line exists */
pshcur(); /* save cursor position */
pa_cursor(stdout, 1, pa_maxy(stdout)-1); /* go to last line */
if (strlen(lp->str))
printf("%s", lp->str); /* output that line */
popcur(); /* restore cursor position */
}
pa_curvis(stdout, TRUE); /* turn on cursor */
status(); /* repaint status line */
}
}
}
/*******************************************************************************
Track mouse movements
Updates the mouse location when it moves.
*******************************************************************************/
void moumov(void)
{
mpx = er.moupx; /* save current mouse coordinates */
mpy = er.moupy;
}
/*******************************************************************************
Handle mouse button assert
Performs the action for a mouse button assert. If the mouse position points
to the valid screen area (in the text pane and not the status line), then we
change the cursor location to equal that.
*******************************************************************************/
void mouass(void)
{
if (mpy < pa_maxy(stdout)) {
/* not on status line */
linpos = linpos+(mpy-pa_cury(stdout)); /* set new position */
poschr = mpx;
pa_cursor(stdout, mpx, mpy); /* place cursor at new position */
status(); /* update status line */
}
}
/*******************************************************************************
Toggle insert mode
Changes the insert/overwrite status to the opposite mode. Updates the display.
*******************************************************************************/
void togins(void)
{
insertc = !insertc; /* insert toggle */
statusi(); /* update display */
}
/*******************************************************************************
Enter character
Enters a single character to the current edit position. First, the line is
"pulled" to a buffer. Then, the character is inserted at the current character
position, and the line and status redrawn.
*******************************************************************************/
void entchr(char c)
{
int i; /* index for line */
int y; /* cursor y save */
int l; /* length of current line */
if (insertc) { /* process using insert mode */
getbuf(); /* pull line to buffer */
l = len(inpbuf); /* find current length of line */
if (l < pa_maxx(stdout)) { /* we have room to place */
/* move up buffer to make room */
for (i = l; i >= poschr; i--) inpbuf[i] = inpbuf[i-1];
inpbuf[poschr-1] = c; /* place character */
y = pa_cury(stdout); /* save location y */
pa_curvis(stdout, FALSE); /* turn off cursor */
l = len(inpbuf); /* find new length of line */
for (i = poschr-1; i < l; i++)
putchar(inpbuf[i]); /* output the line */
if (poschr < pa_maxx(stdout))
poschr++; /* advance character position */
pa_cursor(stdout, poschr, y); /* restore cursor to new position */
pa_curvis(stdout, TRUE); /* turn one cursor */
statusc(); /* update character position field */
}
} else /* process using overwrite mode */
if (poschr <= pa_maxx(stdout)) { /* we have room to place */
getbuf(); /* pull line to buffer */
y = pa_cury(stdout); /* save location y */
inpbuf[poschr] = c; /* place character */
putchar(c); /* place character on screen */
if (poschr < pa_maxx(stdout)) /* not at extreme right */
poschr++; /* advance character position */
pa_cursor(stdout, poschr, y); /* restore cursor to new position */
statusc(); /* update character position field */
}
}
/*******************************************************************************
Delete back
The character to the left of the cursor is removed, and all the characters
to the right are moved left one character.
*******************************************************************************/
void delbwd(void)
{
int i; /* index for line */
int l; /* length of line */
int y; /* y position save */
if (poschr > 1) { /* not already at extreme left */
getbuf(); /* pull line to buffer */
y = pa_cury(stdout); /* save location y */
/* gap character */
for (i = poschr; i <= MAXLIN; i++) inpbuf[i-1] = inpbuf[i];
inpbuf[MAXLIN-1] = ' '; /* fill last position */
poschr--; /* set new character position */
pa_left(stdout); /* move cursor left */
l = strlen(inpbuf); /* find length of input buffer */
pa_curvis(stdout, FALSE); /* turn off cursor */
for (i = poschr; i <= l; i++) putchar(inpbuf[i]); /* replace line */
if (l < pa_maxx(stdout)) putchar(' '); /* blank out last position */
pa_cursor(stdout, poschr, y); /* restore position */
pa_curvis(stdout, TRUE); /* turn on cursor */
statusc(); /* update character position field */
}
}
/*******************************************************************************
Delete forward
The character at the cursor is removed,and all the characters to the right of
the cursor are moved left one character.
*******************************************************************************/
void delfwd(void)
{
int i; /* index for line */
int l; /* length of line */
int y; /* y position save */
if (poschr < pa_maxx(stdout)) { /* not already at extreme right */
getbuf(); /* pull line to buffer */
y = pa_cury(stdout); /* save location y */
/* gap character */
for (i = poschr; i <= MAXLIN-1; i++) inpbuf[i] = inpbuf[i+1];
inpbuf[MAXLIN-1] = ' '; /* fill last position */
l = strlen(inpbuf); /* find length of input buffer */
pa_curvis(stdout, FALSE); /* turn off cursor */
for (i = poschr; i <= l; i++) putchar(inpbuf[i]); /* replace line */
if (l < pa_maxx(stdout)) putchar(' '); /* blank out last position */
pa_cursor(stdout, poschr, y); /* restore position */
pa_curvis(stdout, TRUE); /* turn on cursor */
statusc(); /* update character position field */
}
}
/*******************************************************************************
Line enter
Moves to beginning of the the next line. Enter does not really do anything
special in edit, its just the combination of two motions.
*******************************************************************************/
void enter(void)
{
movdwn(); /* move down a line */
pa_cursor(stdout, 1, pa_cury(stdout)); /* move to extreme left */
poschr = 1;
}
/*******************************************************************************
Tab
In overwrite mode, we simply position to the next tab. In insert mode, we
insert enough spaces to reach the next tab.
*******************************************************************************/
void tab(void)
{
if (poschr < pa_maxx(stdout)) /* not at extreme right */
do { /* output spaces */
entchr(' '); /* place a single space */
} while (poschr < pa_maxx(stdout) && !((poschr-1)%8==0));
}
/*******************************************************************************
Execute function key by number
Accepts a function key number, 1-n, and executes the associated function.
*******************************************************************************/
void func(int fn)
{
switch (fn) {
case 7:
if (!*curfil) errormsg("*** No filename set ***");
writefile(curfil); /* write output file */
break;
}
}
/*******************************************************************************
Main procedure
Initializes the program, loads the target source file, and enters the event
loop. Note during init we select screen 2, which on most PA implementations
causes the original screen to be saved, so that we can restore it again when
the program exits.
All of the command keys in the editor appear in the event loop. We leave it
mostly up to PA to assign which keys do what in the editor, the exception being
the function keys.
*******************************************************************************/
int main(int argc, char *argv[])
{
if (setjmp(inputloop_buf)) goto inputloop;
linstr = NULL; /* clear lines buffer */
paglin = NULL; /* clear top of page line */
curstk = NULL; /* clear coordinate stack */
lincnt = 0; /* clear total lines */
chrcnt = 0; /* clear total characters */
linpos = 1; /* set 1st line */
poschr = 1; /* set 1st character */
mpx = 0; /* set mouse is nowhere */
mpy = 0;
buflin = FALSE; /* set no line in buffer */
insertc = TRUE; /* set insert mode on */
redraws = FALSE; /* set no redraw required */
/* check screen size is less than our minimum */
if (pa_maxx(stdout) < 70 || pa_maxy(stdout) < 2) {
/* we take a special short exit because the display is not workable.
This only works for in-line display, separate windows just exit
because it happens too fast */
printf("*** Window too small\n");
goto stopprog;
}
pa_select(stdout, 2, 2); /* flip to private screen */
pa_auto(stdout, FALSE); /* turn off scrolling/wrapping */
update(TRUE); /* present blank screen */
strcpy(curfil, ""); /* clear current filename */
if (argc == 2) { /* input file exists */
strncpy(curfil, argv[1], MAXFIL);
readfile(curfil); /* read the file in */
}
inputloop: /* return to input level */
/* The screen is initalized with the specified file. Now we enter the event
loop */
do { /* event loop */
pa_event(stdin, &er); /* get the next event */
switch (er.etype) { /* event */
case pa_etchar: entchr(er.echar); /* ASCII character returned */
break;
case pa_etup: movup(); break; /* cursor up one line */
case pa_etdown: movdwn(); break; /* down one line */
case pa_etleft: movlft(); break; /* left one character */
case pa_etright: movrgt(); break; /* right one character */
case pa_etleftw: break; /* left one word */
case pa_etrightw: break; /* right one word */
case pa_ethome: movhom(); break; /* home of document */
case pa_ethomes: movhoms(); break; /* home of screen */
case pa_ethomel: movhoml(); break; /* home of line */
case pa_etend: movend(); break; /* end of document */
case pa_etends: movends(); break; /* end of screen */
case pa_etendl: movendl(); break; /* end of line */
case pa_etscrl: break; /* scroll left one character */
case pa_etscrr: break; /* scroll right one character */
case pa_etscru: scrup(); break; /* scroll up one line */
case pa_etscrd: scrdwn(); break; /* scroll down one line */
case pa_etpagu: pagup(); break; /* page up */
case pa_etpagd: pagdwn(); break; /* page down */
case pa_ettab: tab(); break; /* tab */
case pa_etenter: enter(); break; /* enter line */
case pa_etinsert: break; /* insert block */
case pa_etinsertl: break; /* insert line */
case pa_etinsertt: togins(); break; /* insert toggle */
case pa_etdel: break; /* delete block */
case pa_etdell: break; /* delete line */
case pa_etdelcf: delfwd(); break; /* delete character forward */
case pa_etdelcb: delbwd(); break; /* delete character backward */
case pa_etcopy: break; /* copy block */
case pa_etcopyl: break; /* copy line */
case pa_etcan: break; /* cancel current operation */
case pa_etstop: break; /* stop current operation */
case pa_etcont: break; /* continue current operation */
case pa_etprint: break; /* print document */
case pa_etprintb: break; /* print block */
case pa_etprints: break; /* print screen */
case pa_etfun: func(er.fkey); break; /* functions */
case pa_etmouba: mouass(); break; /* mouse button 1 assertion */
case pa_etmoumov: moumov(); break; /* mouse move */
case pa_etresize: update(FALSE); break; /* resize window */
case pa_etterm: break; /* terminate program */
default:;
}
} while (er.etype != pa_etterm); /* until terminal event */
pa_auto(stdout, TRUE); /* turn on scrolling */
pa_select(stdout, 1, 1); /* return to normal screen */
stopprog: ; /* exit program */
return (0); /* exit no error */
}
| 32.353737 | 85 | 0.459742 | [
"geometry",
"3d"
] |
9ab66a659b01cb59f4fd1fbf477f7c48d048650d | 1,565 | h | C | videopp/glyph_range.h | volcoma/videopp | 4da7ab1b189c0092eaa59064cfffb448312b7d41 | [
"BSD-2-Clause"
] | 1 | 2020-10-15T03:38:50.000Z | 2020-10-15T03:38:50.000Z | videopp/glyph_range.h | volcoma/videopp | 4da7ab1b189c0092eaa59064cfffb448312b7d41 | [
"BSD-2-Clause"
] | null | null | null | videopp/glyph_range.h | volcoma/videopp | 4da7ab1b189c0092eaa59064cfffb448312b7d41 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include "font.h"
#include <set>
namespace gfx
{
using glyph_range = std::pair<char_t, char_t>;
using glyphs = std::vector<glyph_range>;
const glyphs& get_default_glyph_range();
const glyphs& get_latin_glyph_range();
const glyphs& get_cyrillic_glyph_range();
const glyphs& get_arabic_glyph_range();
const glyphs& get_korean_glyph_range();
// Full chinese is around 25000 symbols
const glyphs& get_chinese_glyph_range();
// Store 2500 regularly used characters for Simplified Chinese.
// This table covers 97.97% of all characters
// used during the month in July, 1987.
const glyphs& get_chinese_simplified_common_glyph_range();
const glyphs& get_chinese_simplified_official_glyph_range();
const glyphs& get_japanese_glyph_range();
const glyphs& get_thai_glyph_range();
const glyphs& get_vietnamese_glyph_range();
const glyphs& get_currency_glyph_range();
const glyphs& get_all_glyph_range();
struct glyphs_builder
{
void add(const glyphs& range);
const glyphs &get() const;
private:
glyphs range_;
};
// parse from string with this format:
// range start with [ and end with ]
// [...][...]...[...]
// Inner range format:
// 1. [<start_char>-<end_char>]
// 2. [<char_1><char_2>...<char_n>]
// char formating: for special chars like []- use \\ in front of this chars
// for utf8 encode Can you U+XXXX (XXXX is id of char in utf8 table)
glyphs parse_glyph_range(const std::string &range);
}
| 30.096154 | 79 | 0.678594 | [
"vector"
] |
9aba85a804eafaf0de017ea3ada95ca4686992f6 | 1,551 | h | C | Mapping/VSCIMEvent.h | jbat100/VirtualSoundControl | f84ba15bba4bfce579c185e04df0e1be4f419cd7 | [
"MIT"
] | null | null | null | Mapping/VSCIMEvent.h | jbat100/VirtualSoundControl | f84ba15bba4bfce579c185e04df0e1be4f419cd7 | [
"MIT"
] | null | null | null | Mapping/VSCIMEvent.h | jbat100/VirtualSoundControl | f84ba15bba4bfce579c185e04df0e1be4f419cd7 | [
"MIT"
] | null | null | null |
#ifndef _VSC_IM_EVENT_H_
#define _VSC_IM_EVENT_H_
#include "VSC.h"
#include "VSCTask.h"
#include "VSCTaskQueue.h"
#include "VSCIM.h"
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <vector>
namespace VSC
{
namespace IM
{
class Event
{
public:
typedef boost::shared_ptr<Event> SPtr;
typedef boost::weak_ptr<Event> WPtr;
typedef std::map<Target, Mapping_SPtr> TargetMappingMap;
typedef std::map<Trigger, TargetMappingMap> TriggerTargetMappingMap;
typedef std::map<Target, Float> TargetValueMap;
Event() {}
virtual ~Event() {}
const Targets& getRequiredMappingTargets(void) {return mRequiredMappingTargets;}
Mapping_SPtr getMapping(const Trigger trigger, const Target target);
protected:
void addRequiredMappingTarget(Target target);
void clearRequiredMappingTargets();
void clearMappings(void);
void generateMappings(void);
bool checkRequiredMappings(void);
private:
Targets mRequiredMappingTargets;
TriggerTargetMappingMap mMappingMap;
};
typedef std::vector<Event::SPtr> Events;
}
}
#endif // _VSC_IM_EVENT_H_
| 23.861538 | 92 | 0.534494 | [
"vector"
] |
9abcf8fac2f51fbc5ce0e7d5cc6ca59289575732 | 1,625 | h | C | Misc/UnusedCode/jura_basics/control/jura_ScopedPointerLock.h | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Misc/UnusedCode/jura_basics/control/jura_ScopedPointerLock.h | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Misc/UnusedCode/jura_basics/control/jura_ScopedPointerLock.h | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | #ifndef jura_ScopedPointerLock_h
#define jura_ScopedPointerLock_h
/**
This class works analogously to juce::ScopedLock, except that it works with a
pointer-to-CriticalSection instead of a const reference. That makes it suitable to use with
pointers to CriticalSection objects, where the pointer may also be NULL. In this case, a regular
ScopedLock would try to dereference a NULL-pointer whereas this object here does nothing (i.e. it
verifies that the pointer is not NULL before dereferencing it).
*/
class JUCE_API ScopedPointerLock
{
public:
inline ScopedPointerLock(const CriticalSection *lock) throw() : lock_(lock)
{
if(lock_ != NULL)
lock->enter();
}
inline ~ScopedPointerLock() throw()
{
if(lock_ != NULL)
lock_->exit();
}
private:
const CriticalSection *lock_;
ScopedPointerLock(const ScopedPointerLock*);
const ScopedPointerLock& operator=(const ScopedPointerLock*);
};
//=================================================================================================
/**
This class works analogously to juce::ScopedUnlock but uses a pointer instead of a const reference
in the same way as ScopedPointerLock.
*/
class JUCE_API ScopedPointerUnlock
{
public:
inline ScopedPointerUnlock(const CriticalSection *lock) throw() : lock_(lock)
{
if(lock_ != NULL)
lock->exit();
}
inline ~ScopedPointerUnlock() throw()
{
if(lock_ != NULL)
lock_->enter();
}
private:
const CriticalSection *lock_;
ScopedPointerUnlock(const ScopedPointerLock*);
const ScopedPointerUnlock& operator=(const ScopedPointerUnlock*);
};
#endif
| 21.959459 | 99 | 0.685538 | [
"object"
] |
9abf58589e5d7cfd33cc6a3dd3a173a978b294e7 | 47,810 | h | C | google/cloud/spanner/admin/database_admin_client.h | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | 299 | 2019-01-31T12:17:56.000Z | 2022-03-30T15:46:15.000Z | google/cloud/spanner/admin/database_admin_client.h | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | 6,560 | 2019-01-29T03:15:15.000Z | 2022-03-31T23:58:48.000Z | google/cloud/spanner/admin/database_admin_client.h | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | 253 | 2019-02-07T01:18:13.000Z | 2022-03-30T17:21:10.000Z | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/spanner/admin/database/v1/spanner_database_admin.proto
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CLIENT_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CLIENT_H
#include "google/cloud/spanner/admin/database_admin_connection.h"
#include "google/cloud/future.h"
#include "google/cloud/iam_updater.h"
#include "google/cloud/options.h"
#include "google/cloud/polling_policy.h"
#include "google/cloud/status_or.h"
#include "google/cloud/version.h"
#include <google/longrunning/operations.grpc.pb.h>
#include <memory>
namespace google {
namespace cloud {
namespace spanner_admin {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
///
/// Cloud Spanner Database Admin API
///
/// The Cloud Spanner Database Admin API can be used to create, drop, and
/// list databases. It also enables updating the schema of pre-existing
/// databases. It can be also used to create, delete and list backups for a
/// database and to restore from an existing backup.
///
/// @par Equality
///
/// Instances of this class created via copy-construction or copy-assignment
/// always compare equal. Instances created with equal
/// `std::shared_ptr<*Connection>` objects compare equal. Objects that compare
/// equal share the same underlying resources.
///
/// @par Performance
///
/// Creating a new instance of this class is a relatively expensive operation,
/// new objects establish new connections to the service. In contrast,
/// copy-construction, move-construction, and the corresponding assignment
/// operations are relatively efficient as the copies share all underlying
/// resources.
///
/// @par Thread Safety
///
/// Concurrent access to different instances of this class, even if they compare
/// equal, is guaranteed to work. Two or more threads operating on the same
/// instance of this class is not guaranteed to work. Since copy-construction
/// and move-construction is a relatively efficient operation, consider using
/// such a copy when using this class from multiple threads.
///
class DatabaseAdminClient {
public:
explicit DatabaseAdminClient(
std::shared_ptr<DatabaseAdminConnection> connection,
Options options = {});
~DatabaseAdminClient();
//@{
// @name Copy and move support
DatabaseAdminClient(DatabaseAdminClient const&) = default;
DatabaseAdminClient& operator=(DatabaseAdminClient const&) = default;
DatabaseAdminClient(DatabaseAdminClient&&) = default;
DatabaseAdminClient& operator=(DatabaseAdminClient&&) = default;
//@}
//@{
// @name Equality
friend bool operator==(DatabaseAdminClient const& a,
DatabaseAdminClient const& b) {
return a.connection_ == b.connection_;
}
friend bool operator!=(DatabaseAdminClient const& a,
DatabaseAdminClient const& b) {
return !(a == b);
}
//@}
///
/// Lists Cloud Spanner databases.
///
/// @param parent Required. The instance whose databases should be listed.
/// Values are of the form `projects/<project>/instances/<instance>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.ListDatabasesRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L413}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
StreamRange<google::spanner::admin::database::v1::Database> ListDatabases(
std::string const& parent, Options options = {});
///
/// Lists Cloud Spanner databases.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::ListDatabasesRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L413}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.ListDatabasesRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L413}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
StreamRange<google::spanner::admin::database::v1::Database> ListDatabases(
google::spanner::admin::database::v1::ListDatabasesRequest request,
Options options = {});
///
/// Creates a new Cloud Spanner database and starts to prepare it for serving.
/// The returned [long-running operation][google.longrunning.Operation] will
/// have a name of the format `<database_name>/operations/<operation_id>` and
/// can be used to track preparation of the database. The
/// [metadata][google.longrunning.Operation.metadata] field type is
/// [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata].
/// The [response][google.longrunning.Operation.response] field type is
/// [Database][google.spanner.admin.database.v1.Database], if successful.
///
/// @param parent Required. The name of the instance that will serve the new
/// database.
/// Values are of the form `projects/<project>/instances/<instance>`.
/// @param create_statement Required. A `CREATE DATABASE` statement, which
/// specifies the ID of the
/// new database. The database ID must conform to the regular expression
/// `[a-z][a-z0-9_\-]*[a-z0-9]` and be between 2 and 30 characters in length.
/// If the database ID is a reserved word or if it contains a hyphen, the
/// database ID must be enclosed in backticks (`` ` ``).
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.CreateDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L445}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
future<StatusOr<google::spanner::admin::database::v1::Database>>
CreateDatabase(std::string const& parent, std::string const& create_statement,
Options options = {});
///
/// Creates a new Cloud Spanner database and starts to prepare it for serving.
/// The returned [long-running operation][google.longrunning.Operation] will
/// have a name of the format `<database_name>/operations/<operation_id>` and
/// can be used to track preparation of the database. The
/// [metadata][google.longrunning.Operation.metadata] field type is
/// [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata].
/// The [response][google.longrunning.Operation.response] field type is
/// [Database][google.spanner.admin.database.v1.Database], if successful.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::CreateDatabaseRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L445}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.CreateDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L445}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
future<StatusOr<google::spanner::admin::database::v1::Database>>
CreateDatabase(
google::spanner::admin::database::v1::CreateDatabaseRequest const&
request,
Options options = {});
///
/// Gets the state of a Cloud Spanner database.
///
/// @param name Required. The name of the requested database. Values are of
/// the form
/// `projects/<project>/instances/<instance>/databases/<database>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.GetDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L484}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
StatusOr<google::spanner::admin::database::v1::Database> GetDatabase(
std::string const& name, Options options = {});
///
/// Gets the state of a Cloud Spanner database.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::GetDatabaseRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L484}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.GetDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L484}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
StatusOr<google::spanner::admin::database::v1::Database> GetDatabase(
google::spanner::admin::database::v1::GetDatabaseRequest const& request,
Options options = {});
///
/// Updates the schema of a Cloud Spanner database by
/// creating/altering/dropping tables, columns, indexes, etc. The returned
/// [long-running operation][google.longrunning.Operation] will have a name of
/// the format `<database_name>/operations/<operation_id>` and can be used to
/// track execution of the schema change(s). The
/// [metadata][google.longrunning.Operation.metadata] field type is
/// [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata].
/// The operation has no response.
///
/// @param database Required. The database to update.
/// @param statements Required. DDL statements to be applied to the database.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata,google/spanner/admin/database/v1/spanner_database_admin.proto#L547}
///
/// [google.spanner.admin.database.v1.UpdateDatabaseDdlRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L511}
/// [google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L547}
///
future<
StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>>
UpdateDatabaseDdl(std::string const& database,
std::vector<std::string> const& statements,
Options options = {});
///
/// Updates the schema of a Cloud Spanner database by
/// creating/altering/dropping tables, columns, indexes, etc. The returned
/// [long-running operation][google.longrunning.Operation] will have a name of
/// the format `<database_name>/operations/<operation_id>` and can be used to
/// track execution of the schema change(s). The
/// [metadata][google.longrunning.Operation.metadata] field type is
/// [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata].
/// The operation has no response.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::UpdateDatabaseDdlRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L511}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata,google/spanner/admin/database/v1/spanner_database_admin.proto#L547}
///
/// [google.spanner.admin.database.v1.UpdateDatabaseDdlRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L511}
/// [google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L547}
///
future<
StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>>
UpdateDatabaseDdl(
google::spanner::admin::database::v1::UpdateDatabaseDdlRequest const&
request,
Options options = {});
///
/// Drops (aka deletes) a Cloud Spanner database.
/// Completed backups for the database will be retained according to their
/// `expire_time`.
///
/// @param database Required. The database to be dropped.
/// @param options Optional. Operation options.
///
/// [google.spanner.admin.database.v1.DropDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L579}
///
Status DropDatabase(std::string const& database, Options options = {});
///
/// Drops (aka deletes) a Cloud Spanner database.
/// Completed backups for the database will be retained according to their
/// `expire_time`.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::DropDatabaseRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L579}
/// @param options Optional. Operation options.
///
/// [google.spanner.admin.database.v1.DropDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L579}
///
Status DropDatabase(
google::spanner::admin::database::v1::DropDatabaseRequest const& request,
Options options = {});
///
/// Returns the schema of a Cloud Spanner database as a list of formatted
/// DDL statements. This method does not show pending schema updates, those
/// may be queried using the [Operations][google.longrunning.Operations] API.
///
/// @param database Required. The database whose schema we wish to get.
/// Values are of the form
/// `projects/<project>/instances/<instance>/databases/<database>`
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::GetDatabaseDdlResponse,google/spanner/admin/database/v1/spanner_database_admin.proto#L603}
///
/// [google.spanner.admin.database.v1.GetDatabaseDdlRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L590}
/// [google.spanner.admin.database.v1.GetDatabaseDdlResponse]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L603}
///
StatusOr<google::spanner::admin::database::v1::GetDatabaseDdlResponse>
GetDatabaseDdl(std::string const& database, Options options = {});
///
/// Returns the schema of a Cloud Spanner database as a list of formatted
/// DDL statements. This method does not show pending schema updates, those
/// may be queried using the [Operations][google.longrunning.Operations] API.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::GetDatabaseDdlRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L590}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::GetDatabaseDdlResponse,google/spanner/admin/database/v1/spanner_database_admin.proto#L603}
///
/// [google.spanner.admin.database.v1.GetDatabaseDdlRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L590}
/// [google.spanner.admin.database.v1.GetDatabaseDdlResponse]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L603}
///
StatusOr<google::spanner::admin::database::v1::GetDatabaseDdlResponse>
GetDatabaseDdl(
google::spanner::admin::database::v1::GetDatabaseDdlRequest const&
request,
Options options = {});
///
/// Sets the access control policy on a database or backup resource.
/// Replaces any existing policy.
///
/// Authorization requires `spanner.databases.setIamPolicy`
/// permission on [resource][google.iam.v1.SetIamPolicyRequest.resource].
/// For backups, authorization requires `spanner.backups.setIamPolicy`
/// permission on [resource][google.iam.v1.SetIamPolicyRequest.resource].
///
/// @param resource REQUIRED: The resource for which the policy is being
/// specified.
/// See the operation documentation for the appropriate value for this field.
/// @param policy REQUIRED: The complete policy to be applied to the
/// `resource`. The size of
/// the policy is limited to a few 10s of KB. An empty policy is a
/// valid policy but certain Cloud Platform services (such as Projects)
/// might reject them.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::iam::v1::Policy,google/iam/v1/policy.proto#L88}
///
/// [google.iam.v1.SetIamPolicyRequest]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L98}
/// [google.iam.v1.Policy]:
/// @googleapis_reference_link{google/iam/v1/policy.proto#L88}
///
StatusOr<google::iam::v1::Policy> SetIamPolicy(
std::string const& resource, google::iam::v1::Policy const& policy,
Options options = {});
/**
* Updates the IAM policy for @p resource using an optimistic concurrency
* control loop.
*
* The loop fetches the current policy for @p resource, and passes it to @p
* updater, which should return the new policy. This new policy should use the
* current etag so that the read-modify-write cycle can detect races and rerun
* the update when there is a mismatch. If the new policy does not have an
* etag, the existing policy will be blindly overwritten. If @p updater does
* not yield a policy, the control loop is terminated and kCancelled is
* returned.
*
* @param resource Required. The resource for which the policy is being
* specified. See the operation documentation for the appropriate value for
* this field.
* @param updater Required. Functor to map the current policy to a new one.
* @param options Optional. Options to control the loop. Expected options
* are:
* - `DatabaseAdminBackoffPolicyOption`
* @return google::iam::v1::Policy
*/
StatusOr<google::iam::v1::Policy> SetIamPolicy(std::string const& resource,
IamUpdater const& updater,
Options options = {});
///
/// Sets the access control policy on a database or backup resource.
/// Replaces any existing policy.
///
/// Authorization requires `spanner.databases.setIamPolicy`
/// permission on [resource][google.iam.v1.SetIamPolicyRequest.resource].
/// For backups, authorization requires `spanner.backups.setIamPolicy`
/// permission on [resource][google.iam.v1.SetIamPolicyRequest.resource].
///
/// @param request
/// @googleapis_link{google::iam::v1::SetIamPolicyRequest,google/iam/v1/iam_policy.proto#L98}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::iam::v1::Policy,google/iam/v1/policy.proto#L88}
///
/// [google.iam.v1.SetIamPolicyRequest]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L98}
/// [google.iam.v1.Policy]:
/// @googleapis_reference_link{google/iam/v1/policy.proto#L88}
///
StatusOr<google::iam::v1::Policy> SetIamPolicy(
google::iam::v1::SetIamPolicyRequest const& request,
Options options = {});
///
/// Gets the access control policy for a database or backup resource.
/// Returns an empty policy if a database or backup exists but does not have a
/// policy set.
///
/// Authorization requires `spanner.databases.getIamPolicy` permission on
/// [resource][google.iam.v1.GetIamPolicyRequest.resource].
/// For backups, authorization requires `spanner.backups.getIamPolicy`
/// permission on [resource][google.iam.v1.GetIamPolicyRequest.resource].
///
/// @param resource REQUIRED: The resource for which the policy is being
/// requested.
/// See the operation documentation for the appropriate value for this field.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::iam::v1::Policy,google/iam/v1/policy.proto#L88}
///
/// [google.iam.v1.GetIamPolicyRequest]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L113}
/// [google.iam.v1.Policy]:
/// @googleapis_reference_link{google/iam/v1/policy.proto#L88}
///
StatusOr<google::iam::v1::Policy> GetIamPolicy(std::string const& resource,
Options options = {});
///
/// Gets the access control policy for a database or backup resource.
/// Returns an empty policy if a database or backup exists but does not have a
/// policy set.
///
/// Authorization requires `spanner.databases.getIamPolicy` permission on
/// [resource][google.iam.v1.GetIamPolicyRequest.resource].
/// For backups, authorization requires `spanner.backups.getIamPolicy`
/// permission on [resource][google.iam.v1.GetIamPolicyRequest.resource].
///
/// @param request
/// @googleapis_link{google::iam::v1::GetIamPolicyRequest,google/iam/v1/iam_policy.proto#L113}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::iam::v1::Policy,google/iam/v1/policy.proto#L88}
///
/// [google.iam.v1.GetIamPolicyRequest]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L113}
/// [google.iam.v1.Policy]:
/// @googleapis_reference_link{google/iam/v1/policy.proto#L88}
///
StatusOr<google::iam::v1::Policy> GetIamPolicy(
google::iam::v1::GetIamPolicyRequest const& request,
Options options = {});
///
/// Returns permissions that the caller has on the specified database or
/// backup resource.
///
/// Attempting this RPC on a non-existent Cloud Spanner database will
/// result in a NOT_FOUND error if the user has
/// `spanner.databases.list` permission on the containing Cloud
/// Spanner instance. Otherwise returns an empty set of permissions.
/// Calling this method on a backup that does not exist will
/// result in a NOT_FOUND error if the user has
/// `spanner.backups.list` permission on the containing instance.
///
/// @param resource REQUIRED: The resource for which the policy detail is
/// being requested.
/// See the operation documentation for the appropriate value for this field.
/// @param permissions The set of permissions to check for the `resource`.
/// Permissions with
/// wildcards (such as '*' or 'storage.*') are not allowed. For more
/// information see
/// [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::iam::v1::TestIamPermissionsResponse,google/iam/v1/iam_policy.proto#L141}
///
/// [google.iam.v1.TestIamPermissionsRequest]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L126}
/// [google.iam.v1.TestIamPermissionsResponse]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L141}
///
StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions(
std::string const& resource, std::vector<std::string> const& permissions,
Options options = {});
///
/// Returns permissions that the caller has on the specified database or
/// backup resource.
///
/// Attempting this RPC on a non-existent Cloud Spanner database will
/// result in a NOT_FOUND error if the user has
/// `spanner.databases.list` permission on the containing Cloud
/// Spanner instance. Otherwise returns an empty set of permissions.
/// Calling this method on a backup that does not exist will
/// result in a NOT_FOUND error if the user has
/// `spanner.backups.list` permission on the containing instance.
///
/// @param request
/// @googleapis_link{google::iam::v1::TestIamPermissionsRequest,google/iam/v1/iam_policy.proto#L126}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::iam::v1::TestIamPermissionsResponse,google/iam/v1/iam_policy.proto#L141}
///
/// [google.iam.v1.TestIamPermissionsRequest]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L126}
/// [google.iam.v1.TestIamPermissionsResponse]:
/// @googleapis_reference_link{google/iam/v1/iam_policy.proto#L141}
///
StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions(
google::iam::v1::TestIamPermissionsRequest const& request,
Options options = {});
///
/// Starts creating a new Cloud Spanner Backup.
/// The returned backup [long-running operation][google.longrunning.Operation]
/// will have a name of the format
/// `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation_id>`
/// and can be used to track creation of the backup. The
/// [metadata][google.longrunning.Operation.metadata] field type is
/// [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata].
/// The [response][google.longrunning.Operation.response] field type is
/// [Backup][google.spanner.admin.database.v1.Backup], if successful.
/// Cancelling the returned operation will stop the creation and delete the
/// backup. There can be only one pending backup creation per database. Backup
/// creation of different databases can run concurrently.
///
/// @param parent Required. The name of the instance in which the backup will
/// be
/// created. This must be the same instance that contains the database the
/// backup will be created from. The backup will be stored in the
/// location(s) specified in the instance configuration of this
/// instance. Values are of the form
/// `projects/<project>/instances/<instance>`.
/// @param backup Required. The backup to create.
/// @param backup_id Required. The id of the backup to be created. The
/// `backup_id` appended to
/// `parent` forms the full backup name of the form
/// `projects/<project>/instances/<instance>/backups/<backup_id>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.CreateBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L123}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
future<StatusOr<google::spanner::admin::database::v1::Backup>> CreateBackup(
std::string const& parent,
google::spanner::admin::database::v1::Backup const& backup,
std::string const& backup_id, Options options = {});
///
/// Starts creating a new Cloud Spanner Backup.
/// The returned backup [long-running operation][google.longrunning.Operation]
/// will have a name of the format
/// `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation_id>`
/// and can be used to track creation of the backup. The
/// [metadata][google.longrunning.Operation.metadata] field type is
/// [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata].
/// The [response][google.longrunning.Operation.response] field type is
/// [Backup][google.spanner.admin.database.v1.Backup], if successful.
/// Cancelling the returned operation will stop the creation and delete the
/// backup. There can be only one pending backup creation per database. Backup
/// creation of different databases can run concurrently.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::CreateBackupRequest,google/spanner/admin/database/v1/backup.proto#L123}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.CreateBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L123}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
future<StatusOr<google::spanner::admin::database::v1::Backup>> CreateBackup(
google::spanner::admin::database::v1::CreateBackupRequest const& request,
Options options = {});
///
/// Gets metadata on a pending or completed
/// [Backup][google.spanner.admin.database.v1.Backup].
///
/// @param name Required. Name of the backup.
/// Values are of the form
/// `projects/<project>/instances/<instance>/backups/<backup>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.GetBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L202}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
StatusOr<google::spanner::admin::database::v1::Backup> GetBackup(
std::string const& name, Options options = {});
///
/// Gets metadata on a pending or completed
/// [Backup][google.spanner.admin.database.v1.Backup].
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::GetBackupRequest,google/spanner/admin/database/v1/backup.proto#L202}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.GetBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L202}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
StatusOr<google::spanner::admin::database::v1::Backup> GetBackup(
google::spanner::admin::database::v1::GetBackupRequest const& request,
Options options = {});
///
/// Updates a pending or completed
/// [Backup][google.spanner.admin.database.v1.Backup].
///
/// @param backup Required. The backup to update. `backup.name`, and the
/// fields to be updated
/// as specified by `update_mask` are required. Other fields are ignored.
/// Update is only supported for the following fields:
/// * `backup.expire_time`.
/// @param update_mask Required. A mask specifying which fields (e.g.
/// `expire_time`) in the
/// Backup resource should be updated. This mask is relative to the Backup
/// resource, not to the request message. The field mask must always be
/// specified; this prevents any future fields from being erased accidentally
/// by clients that do not know about them.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.UpdateBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L186}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
StatusOr<google::spanner::admin::database::v1::Backup> UpdateBackup(
google::spanner::admin::database::v1::Backup const& backup,
google::protobuf::FieldMask const& update_mask, Options options = {});
///
/// Updates a pending or completed
/// [Backup][google.spanner.admin.database.v1.Backup].
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::UpdateBackupRequest,google/spanner/admin/database/v1/backup.proto#L186}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.UpdateBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L186}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
StatusOr<google::spanner::admin::database::v1::Backup> UpdateBackup(
google::spanner::admin::database::v1::UpdateBackupRequest const& request,
Options options = {});
///
/// Deletes a pending or completed
/// [Backup][google.spanner.admin.database.v1.Backup].
///
/// @param name Required. Name of the backup to delete.
/// Values are of the form
/// `projects/<project>/instances/<instance>/backups/<backup>`.
/// @param options Optional. Operation options.
///
/// [google.spanner.admin.database.v1.DeleteBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L215}
///
Status DeleteBackup(std::string const& name, Options options = {});
///
/// Deletes a pending or completed
/// [Backup][google.spanner.admin.database.v1.Backup].
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::DeleteBackupRequest,google/spanner/admin/database/v1/backup.proto#L215}
/// @param options Optional. Operation options.
///
/// [google.spanner.admin.database.v1.DeleteBackupRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L215}
///
Status DeleteBackup(
google::spanner::admin::database::v1::DeleteBackupRequest const& request,
Options options = {});
///
/// Lists completed and pending backups.
/// Backups returned are ordered by `create_time` in descending order,
/// starting from the most recent `create_time`.
///
/// @param parent Required. The instance to list backups from. Values are of
/// the
/// form `projects/<project>/instances/<instance>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.ListBackupsRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L228}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
StreamRange<google::spanner::admin::database::v1::Backup> ListBackups(
std::string const& parent, Options options = {});
///
/// Lists completed and pending backups.
/// Backups returned are ordered by `create_time` in descending order,
/// starting from the most recent `create_time`.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::ListBackupsRequest,google/spanner/admin/database/v1/backup.proto#L228}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Backup,google/spanner/admin/database/v1/backup.proto#L36}
///
/// [google.spanner.admin.database.v1.ListBackupsRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L228}
/// [google.spanner.admin.database.v1.Backup]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L36}
///
StreamRange<google::spanner::admin::database::v1::Backup> ListBackups(
google::spanner::admin::database::v1::ListBackupsRequest request,
Options options = {});
///
/// Create a new database by restoring from a completed backup. The new
/// database must be in the same project and in an instance with the same
/// instance configuration as the instance containing
/// the backup. The returned database [long-running
/// operation][google.longrunning.Operation] has a name of the format
/// `projects/<project>/instances/<instance>/databases/<database>/operations/<operation_id>`,
/// and can be used to track the progress of the operation, and to cancel it.
/// The [metadata][google.longrunning.Operation.metadata] field type is
/// [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata].
/// The [response][google.longrunning.Operation.response] type
/// is [Database][google.spanner.admin.database.v1.Database], if
/// successful. Cancelling the returned operation will stop the restore and
/// delete the database.
/// There can be only one database being restored into an instance at a time.
/// Once the restore operation completes, a new restore operation can be
/// initiated, without waiting for the optimize operation associated with the
/// first restore to complete.
///
/// @param parent Required. The name of the instance in which to create the
/// restored database. This instance must be in the same project and
/// have the same instance configuration as the instance containing
/// the source backup. Values are of the form
/// `projects/<project>/instances/<instance>`.
/// @param database_id Required. The id of the database to create and restore
/// to. This
/// database must not already exist. The `database_id` appended to
/// `parent` forms the full database name of the form
/// `projects/<project>/instances/<instance>/databases/<database_id>`.
/// @param backup Name of the backup from which to restore. Values are of
/// the form
/// `projects/<project>/instances/<instance>/backups/<backup>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.RestoreDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L692}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
future<StatusOr<google::spanner::admin::database::v1::Database>>
RestoreDatabase(std::string const& parent, std::string const& database_id,
std::string const& backup, Options options = {});
///
/// Create a new database by restoring from a completed backup. The new
/// database must be in the same project and in an instance with the same
/// instance configuration as the instance containing
/// the backup. The returned database [long-running
/// operation][google.longrunning.Operation] has a name of the format
/// `projects/<project>/instances/<instance>/databases/<database>/operations/<operation_id>`,
/// and can be used to track the progress of the operation, and to cancel it.
/// The [metadata][google.longrunning.Operation.metadata] field type is
/// [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata].
/// The [response][google.longrunning.Operation.response] type
/// is [Database][google.spanner.admin.database.v1.Database], if
/// successful. Cancelling the returned operation will stop the restore and
/// delete the database.
/// There can be only one database being restored into an instance at a time.
/// Once the restore operation completes, a new restore operation can be
/// initiated, without waiting for the optimize operation associated with the
/// first restore to complete.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::RestoreDatabaseRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L692}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::spanner::admin::database::v1::Database,google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
/// [google.spanner.admin.database.v1.RestoreDatabaseRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L692}
/// [google.spanner.admin.database.v1.Database]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L326}
///
future<StatusOr<google::spanner::admin::database::v1::Database>>
RestoreDatabase(
google::spanner::admin::database::v1::RestoreDatabaseRequest const&
request,
Options options = {});
///
/// Lists database [longrunning-operations][google.longrunning.Operation].
/// A database operation has a name of the form
/// `projects/<project>/instances/<instance>/databases/<database>/operations/<operation>`.
/// The long-running operation
/// [metadata][google.longrunning.Operation.metadata] field type
/// `metadata.type_url` describes the type of the metadata. Operations
/// returned include those that have completed/failed/canceled within the last
/// 7 days, and pending operations.
///
/// @param parent Required. The instance of the database operations.
/// Values are of the form `projects/<project>/instances/<instance>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::longrunning::Operation,google/longrunning/operations.proto#L128}
///
/// [google.spanner.admin.database.v1.ListDatabaseOperationsRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L611}
/// [google.longrunning.Operation]:
/// @googleapis_reference_link{google/longrunning/operations.proto#L128}
///
StreamRange<google::longrunning::Operation> ListDatabaseOperations(
std::string const& parent, Options options = {});
///
/// Lists database [longrunning-operations][google.longrunning.Operation].
/// A database operation has a name of the form
/// `projects/<project>/instances/<instance>/databases/<database>/operations/<operation>`.
/// The long-running operation
/// [metadata][google.longrunning.Operation.metadata] field type
/// `metadata.type_url` describes the type of the metadata. Operations
/// returned include those that have completed/failed/canceled within the last
/// 7 days, and pending operations.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::ListDatabaseOperationsRequest,google/spanner/admin/database/v1/spanner_database_admin.proto#L611}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::longrunning::Operation,google/longrunning/operations.proto#L128}
///
/// [google.spanner.admin.database.v1.ListDatabaseOperationsRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/spanner_database_admin.proto#L611}
/// [google.longrunning.Operation]:
/// @googleapis_reference_link{google/longrunning/operations.proto#L128}
///
StreamRange<google::longrunning::Operation> ListDatabaseOperations(
google::spanner::admin::database::v1::ListDatabaseOperationsRequest
request,
Options options = {});
///
/// Lists the backup [long-running operations][google.longrunning.Operation]
/// in the given instance. A backup operation has a name of the form
/// `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation>`.
/// The long-running operation
/// [metadata][google.longrunning.Operation.metadata] field type
/// `metadata.type_url` describes the type of the metadata. Operations
/// returned include those that have completed/failed/canceled within the last
/// 7 days, and pending operations. Operations returned are ordered by
/// `operation.metadata.value.progress.start_time` in descending order
/// starting from the most recently started operation.
///
/// @param parent Required. The instance of the backup operations. Values are
/// of
/// the form `projects/<project>/instances/<instance>`.
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::longrunning::Operation,google/longrunning/operations.proto#L128}
///
/// [google.spanner.admin.database.v1.ListBackupOperationsRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L300}
/// [google.longrunning.Operation]:
/// @googleapis_reference_link{google/longrunning/operations.proto#L128}
///
StreamRange<google::longrunning::Operation> ListBackupOperations(
std::string const& parent, Options options = {});
///
/// Lists the backup [long-running operations][google.longrunning.Operation]
/// in the given instance. A backup operation has a name of the form
/// `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation>`.
/// The long-running operation
/// [metadata][google.longrunning.Operation.metadata] field type
/// `metadata.type_url` describes the type of the metadata. Operations
/// returned include those that have completed/failed/canceled within the last
/// 7 days, and pending operations. Operations returned are ordered by
/// `operation.metadata.value.progress.start_time` in descending order
/// starting from the most recently started operation.
///
/// @param request
/// @googleapis_link{google::spanner::admin::database::v1::ListBackupOperationsRequest,google/spanner/admin/database/v1/backup.proto#L300}
/// @param options Optional. Operation options.
/// @return
/// @googleapis_link{google::longrunning::Operation,google/longrunning/operations.proto#L128}
///
/// [google.spanner.admin.database.v1.ListBackupOperationsRequest]:
/// @googleapis_reference_link{google/spanner/admin/database/v1/backup.proto#L300}
/// [google.longrunning.Operation]:
/// @googleapis_reference_link{google/longrunning/operations.proto#L128}
///
StreamRange<google::longrunning::Operation> ListBackupOperations(
google::spanner::admin::database::v1::ListBackupOperationsRequest request,
Options options = {});
private:
std::shared_ptr<DatabaseAdminConnection> connection_;
Options options_;
};
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
namespace gcpcxxV1 = GOOGLE_CLOUD_CPP_NS; // NOLINT(misc-unused-alias-decls)
} // namespace spanner_admin
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CLIENT_H
| 49.802083 | 158 | 0.725643 | [
"vector"
] |
9ac15711a84afc585b880dc2413234b74a4d7c5e | 13,099 | h | C | Kernel/Arch/x86/Processor.h | pyshx/serenity | 4f2bcebe749a57f1367a9bd7d58b249a48981e23 | [
"BSD-2-Clause"
] | null | null | null | Kernel/Arch/x86/Processor.h | pyshx/serenity | 4f2bcebe749a57f1367a9bd7d58b249a48981e23 | [
"BSD-2-Clause"
] | null | null | null | Kernel/Arch/x86/Processor.h | pyshx/serenity | 4f2bcebe749a57f1367a9bd7d58b249a48981e23 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Array.h>
#include <AK/Concepts.h>
#include <AK/Function.h>
#include <AK/Types.h>
#include <Kernel/Arch/x86/ASM_wrapper.h>
#include <Kernel/Arch/x86/CPUID.h>
#include <Kernel/Arch/x86/DescriptorTable.h>
#include <Kernel/Arch/x86/PageDirectory.h>
#include <Kernel/Arch/x86/TSS.h>
#include <Kernel/Forward.h>
namespace Kernel {
class ProcessorInfo;
struct ProcessorMessageEntry;
enum class ProcessorSpecificDataID {
MemoryManager,
__Count,
};
#if ARCH(X86_64)
# define MSR_FS_BASE 0xc0000100
# define MSR_GS_BASE 0xc0000101
#endif
// FIXME: Find a better place for these
extern "C" void thread_context_first_enter(void);
extern "C" void exit_kernel_thread(void);
extern "C" void do_assume_context(Thread* thread, u32 flags);
struct [[gnu::aligned(16)]] FPUState
{
u8 buffer[512];
};
struct ProcessorMessage {
using CallbackFunction = Function<void()>;
enum Type {
FlushTlb,
Callback,
};
Type type;
Atomic<u32> refs;
union {
ProcessorMessage* next; // only valid while in the pool
alignas(CallbackFunction) u8 callback_storage[sizeof(CallbackFunction)];
struct {
Memory::PageDirectory const* page_directory;
u8* ptr;
size_t page_count;
} flush_tlb;
};
volatile bool async;
ProcessorMessageEntry* per_proc_entries;
CallbackFunction& callback_value()
{
return *bit_cast<CallbackFunction*>(&callback_storage);
}
void invoke_callback()
{
VERIFY(type == Type::Callback);
callback_value()();
}
};
struct ProcessorMessageEntry {
ProcessorMessageEntry* next;
ProcessorMessage* msg;
};
struct DeferredCallEntry {
using HandlerFunction = Function<void()>;
DeferredCallEntry* next;
alignas(HandlerFunction) u8 handler_storage[sizeof(HandlerFunction)];
bool was_allocated;
HandlerFunction& handler_value()
{
return *bit_cast<HandlerFunction*>(&handler_storage);
}
void invoke_handler()
{
handler_value()();
}
};
class Processor;
// Note: We only support 64 processors at most at the moment,
// so allocate 64 slots of inline capacity in the container.
using ProcessorContainer = Array<Processor*, 64>;
class Processor {
friend class ProcessorInfo;
AK_MAKE_NONCOPYABLE(Processor);
AK_MAKE_NONMOVABLE(Processor);
Processor* m_self;
DescriptorTablePointer m_gdtr;
Descriptor m_gdt[256];
u32 m_gdt_length;
u32 m_cpu;
FlatPtr m_in_irq;
volatile u32 m_in_critical;
static Atomic<u32> s_idle_cpu_mask;
TSS m_tss;
static FPUState s_clean_fpu_state;
CPUFeature m_features;
static Atomic<u32> g_total_processors;
u8 m_physical_address_bit_width;
ProcessorInfo* m_info;
Thread* m_current_thread;
Thread* m_idle_thread;
Atomic<ProcessorMessageEntry*> m_message_queue;
bool m_invoke_scheduler_async;
bool m_scheduler_initialized;
bool m_in_scheduler;
Atomic<bool> m_halt_requested;
DeferredCallEntry* m_pending_deferred_calls; // in reverse order
DeferredCallEntry* m_free_deferred_call_pool_entry;
DeferredCallEntry m_deferred_call_pool[5];
void* m_processor_specific_data[(size_t)ProcessorSpecificDataID::__Count];
void gdt_init();
void write_raw_gdt_entry(u16 selector, u32 low, u32 high);
void write_gdt_entry(u16 selector, Descriptor& descriptor);
static ProcessorContainer& processors();
static void smp_return_to_pool(ProcessorMessage& msg);
static ProcessorMessage& smp_get_from_pool();
static void smp_cleanup_message(ProcessorMessage& msg);
bool smp_enqueue_message(ProcessorMessage&);
static void smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async);
static void smp_broadcast_message(ProcessorMessage& msg);
static void smp_broadcast_wait_sync(ProcessorMessage& msg);
static void smp_broadcast_halt();
void deferred_call_pool_init();
void deferred_call_execute_pending();
DeferredCallEntry* deferred_call_get_free();
void deferred_call_return_to_pool(DeferredCallEntry*);
void deferred_call_queue_entry(DeferredCallEntry*);
void cpu_detect();
void cpu_setup();
String features_string() const;
public:
Processor() = default;
void early_initialize(u32 cpu);
void initialize(u32 cpu);
void detect_hypervisor();
void detect_hypervisor_hyperv(CPUID const& hypervisor_leaf_range);
void idle_begin()
{
s_idle_cpu_mask.fetch_or(1u << m_cpu, AK::MemoryOrder::memory_order_relaxed);
}
void idle_end()
{
s_idle_cpu_mask.fetch_and(~(1u << m_cpu), AK::MemoryOrder::memory_order_relaxed);
}
static Processor& by_id(u32);
static u32 count()
{
// NOTE: because this value never changes once all APs are booted,
// we can safely bypass loading it atomically.
return *g_total_processors.ptr();
}
ALWAYS_INLINE static void pause()
{
asm volatile("pause");
}
ALWAYS_INLINE static void wait_check()
{
Processor::pause();
if (Processor::is_smp_enabled())
Processor::current().smp_process_pending_messages();
}
[[noreturn]] static void halt();
static void flush_entire_tlb_local()
{
write_cr3(read_cr3());
}
static void flush_tlb_local(VirtualAddress vaddr, size_t page_count);
static void flush_tlb(Memory::PageDirectory const*, VirtualAddress, size_t);
Descriptor& get_gdt_entry(u16 selector);
void flush_gdt();
const DescriptorTablePointer& get_gdtr();
static size_t processor_count() { return processors().size(); }
template<IteratorFunction<Processor&> Callback>
static inline IterationDecision for_each(Callback callback)
{
auto& procs = processors();
size_t count = procs.size();
for (size_t i = 0; i < count; i++) {
if (callback(*procs[i]) == IterationDecision::Break)
return IterationDecision::Break;
}
return IterationDecision::Continue;
}
template<VoidFunction<Processor&> Callback>
static inline IterationDecision for_each(Callback callback)
{
auto& procs = processors();
size_t count = procs.size();
for (size_t i = 0; i < count; i++) {
if (procs[i] != nullptr)
callback(*procs[i]);
}
return IterationDecision::Continue;
}
ALWAYS_INLINE u8 physical_address_bit_width() const { return m_physical_address_bit_width; }
ALWAYS_INLINE ProcessorInfo& info() { return *m_info; }
static bool is_smp_enabled();
ALWAYS_INLINE static Processor& current()
{
return *(Processor*)read_gs_ptr(__builtin_offsetof(Processor, m_self));
}
ALWAYS_INLINE static bool is_initialized()
{
return
#if ARCH(I386)
get_gs() == GDT_SELECTOR_PROC &&
#endif
read_gs_ptr(__builtin_offsetof(Processor, m_self)) != 0;
}
template<typename T>
T* get_specific()
{
return static_cast<T*>(m_processor_specific_data[static_cast<size_t>(T::processor_specific_data_id())]);
}
void set_specific(ProcessorSpecificDataID specific_id, void* ptr)
{
m_processor_specific_data[static_cast<size_t>(specific_id)] = ptr;
}
ALWAYS_INLINE void set_idle_thread(Thread& idle_thread)
{
m_idle_thread = &idle_thread;
}
ALWAYS_INLINE static Thread* current_thread()
{
// If we were to use Processor::current here, we'd have to
// disable interrupts to prevent a race where we may get pre-empted
// right after getting the Processor structure and then get moved
// to another processor, which would lead us to get the wrong thread.
// To avoid having to disable interrupts, we can just read the field
// directly in an atomic fashion, similar to Processor::current.
return (Thread*)read_gs_ptr(__builtin_offsetof(Processor, m_current_thread));
}
ALWAYS_INLINE static void set_current_thread(Thread& current_thread)
{
// See comment in Processor::current_thread
write_gs_ptr(__builtin_offsetof(Processor, m_current_thread), FlatPtr(¤t_thread));
}
ALWAYS_INLINE static Thread* idle_thread()
{
// See comment in Processor::current_thread
return (Thread*)read_gs_ptr(__builtin_offsetof(Processor, m_idle_thread));
}
ALWAYS_INLINE u32 id() const
{
// NOTE: This variant should only be used when iterating over all
// Processor instances, or when it's guaranteed that the thread
// cannot move to another processor in between calling Processor::current
// and Processor::get_id, or if this fact is not important.
// All other cases should use Processor::id instead!
return m_cpu;
}
ALWAYS_INLINE static u32 current_id()
{
// See comment in Processor::current_thread
return read_gs_ptr(__builtin_offsetof(Processor, m_cpu));
}
ALWAYS_INLINE static bool is_bootstrap_processor()
{
return Processor::current_id() == 0;
}
ALWAYS_INLINE static FlatPtr current_in_irq()
{
return read_gs_ptr(__builtin_offsetof(Processor, m_in_irq));
}
ALWAYS_INLINE static void restore_in_critical(u32 critical)
{
write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), critical);
}
ALWAYS_INLINE static void enter_critical()
{
write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), in_critical() + 1);
}
ALWAYS_INLINE static bool current_in_scheduler()
{
return read_gs_value<decltype(m_in_scheduler)>(__builtin_offsetof(Processor, m_in_scheduler));
}
ALWAYS_INLINE static void set_current_in_scheduler(bool value)
{
write_gs_value<decltype(m_in_scheduler)>(__builtin_offsetof(Processor, m_in_scheduler), value);
}
private:
ALWAYS_INLINE void do_leave_critical()
{
VERIFY(m_in_critical > 0);
if (m_in_critical == 1) {
if (!m_in_irq) {
deferred_call_execute_pending();
VERIFY(m_in_critical == 1);
}
m_in_critical = 0;
if (!m_in_irq)
check_invoke_scheduler();
} else {
m_in_critical = m_in_critical - 1;
}
}
public:
ALWAYS_INLINE static void leave_critical()
{
current().do_leave_critical();
}
ALWAYS_INLINE static u32 clear_critical()
{
auto prev_critical = in_critical();
write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), 0);
auto& proc = current();
if (!proc.m_in_irq)
proc.check_invoke_scheduler();
return prev_critical;
}
ALWAYS_INLINE static void restore_critical(u32 prev_critical)
{
// NOTE: This doesn't have to be atomic, and it's also fine if we
// get preempted in between these steps. If we move to another
// processors m_in_critical will move along with us. And if we
// are preempted, we would resume with the same flags.
write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), prev_critical);
}
ALWAYS_INLINE static u32 in_critical()
{
// See comment in Processor::current_thread
return read_gs_ptr(__builtin_offsetof(Processor, m_in_critical));
}
ALWAYS_INLINE static FPUState const& clean_fpu_state() { return s_clean_fpu_state; }
static void smp_enable();
bool smp_process_pending_messages();
static void smp_unicast(u32 cpu, Function<void()>, bool async);
static void smp_broadcast_flush_tlb(Memory::PageDirectory const*, VirtualAddress, size_t);
static u32 smp_wake_n_idle_processors(u32 wake_count);
static void deferred_call_queue(Function<void()> callback);
ALWAYS_INLINE bool has_feature(CPUFeature f) const
{
return (static_cast<u32>(m_features) & static_cast<u32>(f)) != 0;
}
void check_invoke_scheduler();
void invoke_scheduler_async() { m_invoke_scheduler_async = true; }
void enter_trap(TrapFrame& trap, bool raise_irq);
void exit_trap(TrapFrame& trap);
[[noreturn]] void initialize_context_switching(Thread& initial_thread);
NEVER_INLINE void switch_context(Thread*& from_thread, Thread*& to_thread);
[[noreturn]] static void assume_context(Thread& thread, FlatPtr flags);
FlatPtr init_context(Thread& thread, bool leave_crit);
static Vector<FlatPtr> capture_stack_trace(Thread& thread, size_t max_frames = 0);
static StringView platform_string();
};
template<typename T>
class ProcessorSpecific {
public:
static void initialize()
{
Processor::current().set_specific(T::processor_specific_data_id(), new T);
}
static T& get()
{
return *Processor::current().get_specific<T>();
}
};
}
| 28.916115 | 112 | 0.683411 | [
"vector"
] |
9ac29ff78e06daaeb19c2ff3d82ef35b6a7defa0 | 4,556 | h | C | core/src/wallet/ripple/keychains/RippleLikeKeychain.h | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | null | null | null | core/src/wallet/ripple/keychains/RippleLikeKeychain.h | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 1 | 2020-10-05T11:33:07.000Z | 2020-10-05T11:33:07.000Z | core/src/wallet/ripple/keychains/RippleLikeKeychain.h | RomanWlm/lib-ledger-core | 8c068fccb074c516096abb818a4e20786e02318b | [
"MIT"
] | 2 | 2020-10-16T10:31:41.000Z | 2020-10-16T13:08:45.000Z | /*
*
* RippleLikeKeychain
*
* Created by El Khalil Bellakrid on 05/01/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* 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 LEDGER_CORE_RIPPLELIKEKEYCHAIN_H
#define LEDGER_CORE_RIPPLELIKEKEYCHAIN_H
#include <string>
#include <vector>
#include <utils/DerivationScheme.hpp>
#include <utils/Option.hpp>
#include <preferences/Preferences.hpp>
#include <api/Configuration.hpp>
#include <api/DynamicObject.hpp>
#include <api/Currency.hpp>
#include <api/AccountCreationInfo.hpp>
#include <api/ExtendedKeyAccountCreationInfo.hpp>
#include <api/Keychain.hpp>
#include <api/RippleLikeExtendedPublicKey.hpp>
#include <ripple/RippleLikeAddress.h>
namespace ledger {
namespace core {
class RippleLikeKeychain: public api::Keychain {
public:
using Address = std::shared_ptr<RippleLikeAddress>;
RippleLikeKeychain(const std::shared_ptr<api::DynamicObject> &configuration,
const api::Currency ¶ms,
int account,
const std::shared_ptr<Preferences> &preferences);
RippleLikeKeychain(const std::shared_ptr<api::DynamicObject> &configuration,
const api::Currency ¶ms,
int account,
const std::shared_ptr<api::RippleLikeExtendedPublicKey> &xpub,
const std::shared_ptr<Preferences> &preferences);
RippleLikeKeychain(const std::shared_ptr<api::DynamicObject> &configuration,
const api::Currency ¶ms,
int account,
const std::string &accountAddress,
const std::shared_ptr<Preferences> &preferences);
std::vector<Address> getAllObservableAddresses(uint32_t from, uint32_t to);
Address getAddress() const;
Option<std::string> getAddressDerivationPath(const std::string &address) const;
std::shared_ptr<api::RippleLikeExtendedPublicKey> getExtendedPublicKey() const;
int getAccountIndex() const;
const api::RippleLikeNetworkParameters &getNetworkParameters() const;
const api::Currency &getCurrency() const;
Option<std::vector<uint8_t>> getPublicKey(const std::string &address) const;
std::shared_ptr<api::DynamicObject> getConfiguration() const;
const DerivationScheme &getDerivationScheme() const;
const DerivationScheme &getFullDerivationScheme() const;
std::string getRestoreKey() const;
bool contains(const std::string &address) const;
int32_t getOutputSizeAsSignedTxInput() const;
protected:
std::shared_ptr<Preferences> getPreferences() const;
DerivationScheme &getDerivationScheme();
private:
RippleLikeKeychain::Address derive();
const api::Currency _currency;
DerivationScheme _scheme;
DerivationScheme _fullScheme;
int _account;
std::shared_ptr<Preferences> _preferences;
std::shared_ptr<api::DynamicObject> _configuration;
std::shared_ptr<api::RippleLikeExtendedPublicKey> _xpub;
std::string _localPath;
std::string _address;
};
}
}
#endif //LEDGER_CORE_RIPPLELIKEKEYCHAIN_H
| 35.59375 | 93 | 0.658911 | [
"vector"
] |
9ac6646f08d4c1541413145dcba14abc3ef7085a | 3,470 | h | C | interfaces/kits/js/medialibrary/include/album_napi.h | openharmony-gitee-mirror/multimedia_medialibrary_standard | 84968c9e4b6292182bfeb4f6aa88b227ffeebab6 | [
"Apache-2.0"
] | null | null | null | interfaces/kits/js/medialibrary/include/album_napi.h | openharmony-gitee-mirror/multimedia_medialibrary_standard | 84968c9e4b6292182bfeb4f6aa88b227ffeebab6 | [
"Apache-2.0"
] | null | null | null | interfaces/kits/js/medialibrary/include/album_napi.h | openharmony-gitee-mirror/multimedia_medialibrary_standard | 84968c9e4b6292182bfeb4f6aa88b227ffeebab6 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:20:49.000Z | 2021-09-13T11:20:49.000Z | /*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALBUM_NAPI_H
#define ALBUM_NAPI_H
#include <vector>
#include <algorithm>
#include "ability.h"
#include "ability_loader.h"
#include "abs_shared_result_set.h"
#include "album_asset.h"
#include "data_ability_helper.h"
#include "data_ability_predicates.h"
#include "fetch_file_result_napi.h"
#include "fetch_result.h"
#include "medialibrary_napi_utils.h"
#include "media_data_ability_const.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "result_set.h"
#include "uri.h"
#include "values_bucket.h"
namespace OHOS {
static const std::string ALBUM_NAPI_CLASS_NAME = "Album";
class AlbumNapi {
public:
static napi_value Init(napi_env env, napi_value exports);
static napi_value CreateAlbumNapi(napi_env env, Media::AlbumAsset &albumData,
std::shared_ptr<AppExecFwk::DataAbilityHelper> abilityHelper);
int32_t GetAlbumId() const;
std::shared_ptr<AppExecFwk::DataAbilityHelper> GetDataAbilityHelper() const;
std::string GetAlbumName() const;
std::string GetAlbumPath() const;
AlbumNapi();
~AlbumNapi();
private:
static void AlbumNapiDestructor(napi_env env, void* nativeObject, void* finalize_hint);
static napi_value AlbumNapiConstructor(napi_env env, napi_callback_info info);
void SetAlbumNapiProperties(const Media::AlbumAsset &albumData);
static napi_value JSGetAlbumId(napi_env env, napi_callback_info info);
static napi_value JSGetAlbumName(napi_env env, napi_callback_info info);
static napi_value JSGetAlbumPath(napi_env env, napi_callback_info info);
static napi_value JSGetAlbumDateModified(napi_env env, napi_callback_info info);
static napi_value JSGetAlbumVirtual(napi_env env, napi_callback_info info);
static napi_value JSGetAlbumRelativePath(napi_env env, napi_callback_info info);
static napi_value JSGetAlbumFileAssets(napi_env env, napi_callback_info info);
static napi_value JSSetAlbumPath(napi_env env, napi_callback_info info);
static napi_value JSAlbumNameSetter(napi_env env, napi_callback_info info);
int32_t albumId_;
std::string albumName_;
std::string albumPath_ = "";
int64_t albumDateModified_;
bool albumVirtual_;
std::string albumRelativePath_;
std::shared_ptr<AppExecFwk::DataAbilityHelper> abilityHelper_;
napi_env env_;
napi_ref wrapper_;
static napi_ref sConstructor_;
static Media::AlbumAsset *sAlbumData_;
static std::shared_ptr<AppExecFwk::DataAbilityHelper> sAbilityHelper;
};
struct AlbumNapiAsyncContext {
napi_env env;
napi_async_work work;
napi_deferred deferred;
napi_ref callbackRef;
AlbumNapi *objectInfo;
bool status;
std::string selection;
std::vector<std::string> selectionArgs;
std::string order;
std::unique_ptr<Media::FetchResult> fetchResult;
};
} // namespace OHOS
#endif /* ALBUM_NAPI_H */
| 34.356436 | 91 | 0.763401 | [
"vector"
] |
9ac671eefe79032b0cfce9cec086866efa0af93c | 24,195 | h | C | libraries/spectra/include/GenEigsSolver.h | maxchernet/TheiaSfM | 603f3ad8bfea1e54fe23fa553f268760a9c9276c | [
"BSD-3-Clause"
] | 770 | 2015-02-12T14:32:01.000Z | 2022-03-16T00:54:33.000Z | libraries/spectra/include/GenEigsSolver.h | maxchernet/TheiaSfM | 603f3ad8bfea1e54fe23fa553f268760a9c9276c | [
"BSD-3-Clause"
] | 237 | 2015-02-20T18:50:16.000Z | 2022-01-18T05:21:48.000Z | libraries/spectra/include/GenEigsSolver.h | maxchernet/TheiaSfM | 603f3ad8bfea1e54fe23fa553f268760a9c9276c | [
"BSD-3-Clause"
] | 278 | 2015-02-12T06:20:26.000Z | 2022-03-23T17:25:21.000Z | // Copyright (C) 2016-2017 Yixuan Qiu <yixuan.qiu@cos.name>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef GEN_EIGS_SOLVER_H
#define GEN_EIGS_SOLVER_H
#include <Eigen/Core>
#include <vector> // std::vector
#include <cmath> // std::abs, std::pow
#include <algorithm> // std::min, std::copy
#include <complex> // std::complex, std::conj, std::norm, std::abs
#include <stdexcept> // std::invalid_argument
#include "Util/SelectionRule.h"
#include "Util/CompInfo.h"
#include "Util/SimpleRandom.h"
#include "LinAlg/UpperHessenbergQR.h"
#include "LinAlg/UpperHessenbergEigen.h"
#include "LinAlg/DoubleShiftQR.h"
#include "MatOp/DenseGenMatProd.h"
namespace Spectra {
///
/// \ingroup EigenSolver
///
/// This class implements the eigen solver for general real matrices, i.e.,
/// to solve \f$Ax=\lambda x\f$ for a possibly non-symmetric \f$A\f$ matrix.
///
/// Most of the background information documented in the SymEigsSolver class
/// also applies to the GenEigsSolver class here, except that the eigenvalues
/// and eigenvectors of a general matrix can now be complex-valued.
///
/// \tparam Scalar The element type of the matrix.
/// Currently supported types are `float`, `double` and `long double`.
/// \tparam SelectionRule An enumeration value indicating the selection rule of
/// the requested eigenvalues, for example `LARGEST_MAGN`
/// to retrieve eigenvalues with the largest magnitude.
/// The full list of enumeration values can be found in
/// \ref Enumerations.
/// \tparam OpType The name of the matrix operation class. Users could either
/// use the wrapper classes such as DenseGenMatProd and
/// SparseGenMatProd, or define their
/// own that impelemnts all the public member functions as in
/// DenseGenMatProd.
///
/// An example that illustrates the usage of GenEigsSolver is give below:
///
/// \code{.cpp}
/// #include <Eigen/Core>
/// #include <GenEigsSolver.h> // Also includes <MatOp/DenseGenMatProd.h>
/// #include <iostream>
///
/// using namespace Spectra;
///
/// int main()
/// {
/// // We are going to calculate the eigenvalues of M
/// Eigen::MatrixXd M = Eigen::MatrixXd::Random(10, 10);
///
/// // Construct matrix operation object using the wrapper class
/// DenseGenMatProd<double> op(M);
///
/// // Construct eigen solver object, requesting the largest
/// // (in magnitude, or norm) three eigenvalues
/// GenEigsSolver< double, LARGEST_MAGN, DenseGenMatProd<double> > eigs(&op, 3, 6);
///
/// // Initialize and compute
/// eigs.init();
/// int nconv = eigs.compute();
///
/// // Retrieve results
/// Eigen::VectorXcd evalues;
/// if(eigs.info() == SUCCESSFUL)
/// evalues = eigs.eigenvalues();
///
/// std::cout << "Eigenvalues found:\n" << evalues << std::endl;
///
/// return 0;
/// }
/// \endcode
///
/// And also an example for sparse matrices:
///
/// \code{.cpp}
/// #include <Eigen/Core>
/// #include <Eigen/SparseCore>
/// #include <GenEigsSolver.h>
/// #include <MatOp/SparseGenMatProd.h>
/// #include <iostream>
///
/// using namespace Spectra;
///
/// int main()
/// {
/// // A band matrix with 1 on the main diagonal, 2 on the below-main subdiagonal,
/// // and 3 on the above-main subdiagonal
/// const int n = 10;
/// Eigen::SparseMatrix<double> M(n, n);
/// M.reserve(Eigen::VectorXi::Constant(n, 3));
/// for(int i = 0; i < n; i++)
/// {
/// M.insert(i, i) = 1.0;
/// if(i > 0)
/// M.insert(i - 1, i) = 3.0;
/// if(i < n - 1)
/// M.insert(i + 1, i) = 2.0;
/// }
///
/// // Construct matrix operation object using the wrapper class SparseGenMatProd
/// SparseGenMatProd<double> op(M);
///
/// // Construct eigen solver object, requesting the largest three eigenvalues
/// GenEigsSolver< double, LARGEST_MAGN, SparseGenMatProd<double> > eigs(&op, 3, 6);
///
/// // Initialize and compute
/// eigs.init();
/// int nconv = eigs.compute();
///
/// // Retrieve results
/// Eigen::VectorXcd evalues;
/// if(eigs.info() == SUCCESSFUL)
/// evalues = eigs.eigenvalues();
///
/// std::cout << "Eigenvalues found:\n" << evalues << std::endl;
///
/// return 0;
/// }
/// \endcode
template < typename Scalar = double,
int SelectionRule = LARGEST_MAGN,
typename OpType = DenseGenMatProd<double> >
class GenEigsSolver
{
private:
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;
typedef Eigen::Array<Scalar, Eigen::Dynamic, 1> Array;
typedef Eigen::Array<bool, Eigen::Dynamic, 1> BoolArray;
typedef Eigen::Map<Matrix> MapMat;
typedef Eigen::Map<Vector> MapVec;
typedef std::complex<Scalar> Complex;
typedef Eigen::Matrix<Complex, Eigen::Dynamic, Eigen::Dynamic> ComplexMatrix;
typedef Eigen::Matrix<Complex, Eigen::Dynamic, 1> ComplexVector;
protected:
OpType *m_op; // object to conduct matrix operation,
// e.g. matrix-vector product
const int m_n; // dimension of matrix A
const int m_nev; // number of eigenvalues requested
private:
const int m_ncv; // number of ritz values
int m_nmatop; // number of matrix operations called
int m_niter; // number of restarting iterations
protected:
Matrix m_fac_V; // V matrix in the Arnoldi factorization
Matrix m_fac_H; // H matrix in the Arnoldi factorization
Vector m_fac_f; // residual in the Arnoldi factorization
ComplexVector m_ritz_val; // ritz values
ComplexMatrix m_ritz_vec; // ritz vectors
ComplexVector m_ritz_est; // last row of m_ritz_vec
private:
BoolArray m_ritz_conv; // indicator of the convergence of ritz values
int m_info; // status of the computation
const Scalar m_eps; // the machine precision,
// e.g. ~= 1e-16 for the "double" type
const Scalar m_approx_0; // a number that is approximately zero
// m_eps23 = m_eps^(2/3)
// used to test whether a number is complex, and
// to test the orthogonality of vectors
// Arnoldi factorization starting from step-k
void factorize_from(int from_k, int to_m, const Vector& fk)
{
if(to_m <= from_k) return;
m_fac_f = fk;
Vector w(m_n);
Scalar beta = m_fac_f.norm();
// Keep the upperleft k x k submatrix of H and set other elements to 0
m_fac_H.rightCols(m_ncv - from_k).setZero();
m_fac_H.block(from_k, 0, m_ncv - from_k, from_k).setZero();
for(int i = from_k; i <= to_m - 1; i++)
{
bool restart = false;
// If beta = 0, then the next V is not full rank
// We need to generate a new residual vector that is orthogonal
// to the current V, which we call a restart
if(beta < m_eps)
{
SimpleRandom<Scalar> rng(2 * i);
m_fac_f.noalias() = rng.random_vec(m_n);
// f <- f - V * V' * f, so that f is orthogonal to V
MapMat V(m_fac_V.data(), m_n, i); // The first i columns
Vector Vf = V.transpose() * m_fac_f;
m_fac_f.noalias() -= V * Vf;
// beta <- ||f||
beta = m_fac_f.norm();
restart = true;
}
// v <- f / ||f||
m_fac_V.col(i).noalias() = m_fac_f / beta; // The (i+1)-th column
// Note that H[i+1, i] equals to the unrestarted beta
if(restart)
m_fac_H(i, i - 1) = 0.0;
else
m_fac_H(i, i - 1) = beta;
// w <- A * v, v = m_fac_V.col(i)
m_op->perform_op(&m_fac_V(0, i), w.data());
m_nmatop++;
// First i+1 columns of V
MapMat Vs(m_fac_V.data(), m_n, i + 1);
// h = m_fac_H(0:i, i)
MapVec h(&m_fac_H(0, i), i + 1);
// h <- V' * w
h.noalias() = Vs.transpose() * w;
// f <- w - V * h
m_fac_f.noalias() = w - Vs * h;
beta = m_fac_f.norm();
if(beta > 0.717 * h.norm())
continue;
// f/||f|| is going to be the next column of V, so we need to test
// whether V' * (f/||f||) ~= 0
Vector Vf = Vs.transpose() * m_fac_f;
// If not, iteratively correct the residual
int count = 0;
while(count < 5 && Vf.cwiseAbs().maxCoeff() > m_approx_0 * beta)
{
// f <- f - V * Vf
m_fac_f.noalias() -= Vs * Vf;
// h <- h + Vf
h.noalias() += Vf;
// beta <- ||f||
beta = m_fac_f.norm();
Vf.noalias() = Vs.transpose() * m_fac_f;
count++;
}
}
}
// Real Ritz values calculated from UpperHessenbergEigen have exact zero imaginary part
// Complex Ritz values have exact conjugate pairs
// So we use exact tests here
static bool is_complex(const Complex& v) { return v.imag() != Scalar(0); }
static bool is_conj(const Complex& v1, const Complex& v2) { return v1 == Eigen::numext::conj(v2); }
// Implicitly restarted Arnoldi factorization
void restart(int k)
{
using std::norm;
if(k >= m_ncv)
return;
DoubleShiftQR<Scalar> decomp_ds(m_ncv);
UpperHessenbergQR<Scalar> decomp_hb;
Matrix Q = Matrix::Identity(m_ncv, m_ncv);
for(int i = k; i < m_ncv; i++)
{
if(is_complex(m_ritz_val[i]) && is_conj(m_ritz_val[i], m_ritz_val[i + 1]))
{
// H - mu * I = Q1 * R1
// H <- R1 * Q1 + mu * I = Q1' * H * Q1
// H - conj(mu) * I = Q2 * R2
// H <- R2 * Q2 + conj(mu) * I = Q2' * H * Q2
//
// (H - mu * I) * (H - conj(mu) * I) = Q1 * Q2 * R2 * R1 = Q * R
Scalar s = 2 * m_ritz_val[i].real();
Scalar t = norm(m_ritz_val[i]);
decomp_ds.compute(m_fac_H, s, t);
// Q -> Q * Qi
decomp_ds.apply_YQ(Q);
// H -> Q'HQ
// Matrix Q = Matrix::Identity(m_ncv, m_ncv);
// decomp_ds.apply_YQ(Q);
// m_fac_H = Q.transpose() * m_fac_H * Q;
m_fac_H = decomp_ds.matrix_QtHQ();
i++;
} else {
// QR decomposition of H - mu * I, mu is real
m_fac_H.diagonal().array() -= m_ritz_val[i].real();
decomp_hb.compute(m_fac_H);
// Q -> Q * Qi
decomp_hb.apply_YQ(Q);
// H -> Q'HQ = RQ + mu * I
m_fac_H = decomp_hb.matrix_RQ();
m_fac_H.diagonal().array() += m_ritz_val[i].real();
}
}
// V -> VQ, only need to update the first k+1 columns
// Q has some elements being zero
// The first (ncv - k + i) elements of the i-th column of Q are non-zero
Matrix Vs(m_n, k + 1);
int nnz;
for(int i = 0; i < k; i++)
{
nnz = m_ncv - k + i + 1;
MapMat V(m_fac_V.data(), m_n, nnz);
MapVec q(&Q(0, i), nnz);
Vs.col(i).noalias() = V * q;
}
Vs.col(k).noalias() = m_fac_V * Q.col(k);
m_fac_V.leftCols(k + 1).noalias() = Vs;
Vector fk = m_fac_f * Q(m_ncv - 1, k - 1) + m_fac_V.col(k) * m_fac_H(k, k - 1);
factorize_from(k, m_ncv, fk);
retrieve_ritzpair();
}
// Calculates the number of converged Ritz values
int num_converged(Scalar tol)
{
// thresh = tol * max(m_approx_0, abs(theta)), theta for ritz value
Array thresh = tol * m_ritz_val.head(m_nev).array().abs().max(m_approx_0);
Array resid = m_ritz_est.head(m_nev).array().abs() * m_fac_f.norm();
// Converged "wanted" ritz values
m_ritz_conv = (resid < thresh);
return m_ritz_conv.cast<int>().sum();
}
// Returns the adjusted nev for restarting
int nev_adjusted(int nconv)
{
using std::abs;
int nev_new = m_nev;
for(int i = m_nev; i < m_ncv; i++)
if(abs(m_ritz_est[i]) < m_eps) nev_new++;
// Adjust nev_new, according to dnaup2.f line 660~674 in ARPACK
nev_new += std::min(nconv, (m_ncv - nev_new) / 2);
if(nev_new == 1 && m_ncv >= 6)
nev_new = m_ncv / 2;
else if(nev_new == 1 && m_ncv > 3)
nev_new = 2;
if(nev_new > m_ncv - 2)
nev_new = m_ncv - 2;
// Increase nev by one if ritz_val[nev - 1] and
// ritz_val[nev] are conjugate pairs
if(is_complex(m_ritz_val[nev_new - 1]) &&
is_conj(m_ritz_val[nev_new - 1], m_ritz_val[nev_new]))
{
nev_new++;
}
return nev_new;
}
// Retrieves and sorts ritz values and ritz vectors
void retrieve_ritzpair()
{
UpperHessenbergEigen<Scalar> decomp(m_fac_H);
ComplexVector evals = decomp.eigenvalues();
ComplexMatrix evecs = decomp.eigenvectors();
SortEigenvalue<Complex, SelectionRule> sorting(evals.data(), evals.size());
std::vector<int> ind = sorting.index();
// Copy the ritz values and vectors to m_ritz_val and m_ritz_vec, respectively
for(int i = 0; i < m_ncv; i++)
{
m_ritz_val[i] = evals[ind[i]];
m_ritz_est[i] = evecs(m_ncv - 1, ind[i]);
}
for(int i = 0; i < m_nev; i++)
{
m_ritz_vec.col(i) = evecs.col(ind[i]);
}
}
protected:
// Sorts the first nev Ritz pairs in the specified order
// This is used to return the final results
virtual void sort_ritzpair(int sort_rule)
{
// First make sure that we have a valid index vector
SortEigenvalue<Complex, LARGEST_MAGN> sorting(m_ritz_val.data(), m_nev);
std::vector<int> ind = sorting.index();
switch(sort_rule)
{
case LARGEST_MAGN:
break;
case LARGEST_REAL:
{
SortEigenvalue<Complex, LARGEST_REAL> sorting(m_ritz_val.data(), m_nev);
ind = sorting.index();
}
break;
case LARGEST_IMAG:
{
SortEigenvalue<Complex, LARGEST_IMAG> sorting(m_ritz_val.data(), m_nev);
ind = sorting.index();
}
break;
case SMALLEST_MAGN:
{
SortEigenvalue<Complex, SMALLEST_MAGN> sorting(m_ritz_val.data(), m_nev);
ind = sorting.index();
}
break;
case SMALLEST_REAL:
{
SortEigenvalue<Complex, SMALLEST_REAL> sorting(m_ritz_val.data(), m_nev);
ind = sorting.index();
}
break;
case SMALLEST_IMAG:
{
SortEigenvalue<Complex, SMALLEST_IMAG> sorting(m_ritz_val.data(), m_nev);
ind = sorting.index();
}
break;
default:
throw std::invalid_argument("unsupported sorting rule");
}
ComplexVector new_ritz_val(m_ncv);
ComplexMatrix new_ritz_vec(m_ncv, m_nev);
BoolArray new_ritz_conv(m_nev);
for(int i = 0; i < m_nev; i++)
{
new_ritz_val[i] = m_ritz_val[ind[i]];
new_ritz_vec.col(i) = m_ritz_vec.col(ind[i]);
new_ritz_conv[i] = m_ritz_conv[ind[i]];
}
m_ritz_val.swap(new_ritz_val);
m_ritz_vec.swap(new_ritz_vec);
m_ritz_conv.swap(new_ritz_conv);
}
public:
///
/// Constructor to create a solver object.
///
/// \param op_ Pointer to the matrix operation object, which should implement
/// the matrix-vector multiplication operation of \f$A\f$:
/// calculating \f$Av\f$ for any vector \f$v\f$. Users could either
/// create the object from the wrapper class such as DenseGenMatProd, or
/// define their own that impelemnts all the public member functions
/// as in DenseGenMatProd.
/// \param nev_ Number of eigenvalues requested. This should satisfy \f$1\le nev \le n-2\f$,
/// where \f$n\f$ is the size of matrix.
/// \param ncv_ Parameter that controls the convergence speed of the algorithm.
/// Typically a larger `ncv_` means faster convergence, but it may
/// also result in greater memory use and more matrix operations
/// in each iteration. This parameter must satisfy \f$nev+2 \le ncv \le n\f$,
/// and is advised to take \f$ncv \ge 2\cdot nev + 1\f$.
///
GenEigsSolver(OpType* op_, int nev_, int ncv_) :
m_op(op_),
m_n(m_op->rows()),
m_nev(nev_),
m_ncv(ncv_ > m_n ? m_n : ncv_),
m_nmatop(0),
m_niter(0),
m_info(NOT_COMPUTED),
m_eps(Eigen::NumTraits<Scalar>::epsilon()),
m_approx_0(Eigen::numext::pow(m_eps, Scalar(2.0) / 3))
{
if(nev_ < 1 || nev_ > m_n - 2)
throw std::invalid_argument("nev must satisfy 1 <= nev <= n - 2, n is the size of matrix");
if(ncv_ < nev_ + 2 || ncv_ > m_n)
throw std::invalid_argument("ncv must satisfy nev + 2 <= ncv <= n, n is the size of matrix");
}
///
/// Virtual destructor
///
virtual ~GenEigsSolver() {}
///
/// Initializes the solver by providing an initial residual vector.
///
/// \param init_resid Pointer to the initial residual vector.
///
/// **Spectra** (and also **ARPACK**) uses an iterative algorithm
/// to find eigenvalues. This function allows the user to provide the initial
/// residual vector.
///
void init(const Scalar* init_resid)
{
// Reset all matrices/vectors to zero
m_fac_V.resize(m_n, m_ncv);
m_fac_H.resize(m_ncv, m_ncv);
m_fac_f.resize(m_n);
m_ritz_val.resize(m_ncv);
m_ritz_vec.resize(m_ncv, m_nev);
m_ritz_est.resize(m_ncv);
m_ritz_conv.resize(m_nev);
m_fac_V.setZero();
m_fac_H.setZero();
m_fac_f.setZero();
m_ritz_val.setZero();
m_ritz_vec.setZero();
m_ritz_est.setZero();
m_ritz_conv.setZero();
// Set the initial vector
Vector v(m_n);
std::copy(init_resid, init_resid + m_n, v.data());
Scalar vnorm = v.norm();
if(vnorm < m_eps)
throw std::invalid_argument("initial residual vector cannot be zero");
v /= vnorm;
Vector w(m_n);
m_op->perform_op(v.data(), w.data());
m_nmatop++;
m_fac_H(0, 0) = v.dot(w);
m_fac_f = w - v * m_fac_H(0, 0);
m_fac_V.col(0) = v;
}
///
/// Initializes the solver by providing a random initial residual vector.
///
/// This overloaded function generates a random initial residual vector
/// (with a fixed random seed) for the algorithm. Elements in the vector
/// follow independent Uniform(-0.5, 0.5) distribution.
///
void init()
{
SimpleRandom<Scalar> rng(0);
Vector init_resid = rng.random_vec(m_n);
init(init_resid.data());
}
///
/// Conducts the major computation procedure.
///
/// \param maxit Maximum number of iterations allowed in the algorithm.
/// \param tol Precision parameter for the calculated eigenvalues.
/// \param sort_rule Rule to sort the eigenvalues and eigenvectors.
/// Supported values are
/// `Spectra::LARGEST_MAGN`, `Spectra::LARGEST_REAL`,
/// `Spectra::LARGEST_IMAG`, `Spectra::SMALLEST_MAGN`,
/// `Spectra::SMALLEST_REAL` and `Spectra::SMALLEST_IMAG`,
/// for example `LARGEST_MAGN` indicates that eigenvalues
/// with largest magnitude come first.
/// Note that this argument is only used to
/// **sort** the final result, and the **selection** rule
/// (e.g. selecting the largest or smallest eigenvalues in the
/// full spectrum) is specified by the template parameter
/// `SelectionRule` of GenEigsSolver.
///
/// \return Number of converged eigenvalues.
///
int compute(int maxit = 1000, Scalar tol = 1e-10, int sort_rule = LARGEST_MAGN)
{
// The m-step Arnoldi factorization
factorize_from(1, m_ncv, m_fac_f);
retrieve_ritzpair();
// Restarting
int i, nconv = 0, nev_adj;
for(i = 0; i < maxit; i++)
{
nconv = num_converged(tol);
if(nconv >= m_nev)
break;
nev_adj = nev_adjusted(nconv);
restart(nev_adj);
}
// Sorting results
sort_ritzpair(sort_rule);
m_niter += i + 1;
m_info = (nconv >= m_nev) ? SUCCESSFUL : NOT_CONVERGING;
return std::min(m_nev, nconv);
}
///
/// Returns the status of the computation.
/// The full list of enumeration values can be found in \ref Enumerations.
///
int info() const { return m_info; }
///
/// Returns the number of iterations used in the computation.
///
int num_iterations() const { return m_niter; }
///
/// Returns the number of matrix operations used in the computation.
///
int num_operations() const { return m_nmatop; }
///
/// Returns the converged eigenvalues.
///
/// \return A complex-valued vector containing the eigenvalues.
/// Returned vector type will be `Eigen::Vector<std::complex<Scalar>, ...>`, depending on
/// the template parameter `Scalar` defined.
///
ComplexVector eigenvalues() const
{
int nconv = m_ritz_conv.cast<int>().sum();
ComplexVector res(nconv);
if(!nconv)
return res;
int j = 0;
for(int i = 0; i < m_nev; i++)
{
if(m_ritz_conv[i])
{
res[j] = m_ritz_val[i];
j++;
}
}
return res;
}
///
/// Returns the eigenvectors associated with the converged eigenvalues.
///
/// \param nvec The number of eigenvectors to return.
///
/// \return A complex-valued matrix containing the eigenvectors.
/// Returned matrix type will be `Eigen::Matrix<std::complex<Scalar>, ...>`,
/// depending on the template parameter `Scalar` defined.
///
ComplexMatrix eigenvectors(int nvec) const
{
int nconv = m_ritz_conv.cast<int>().sum();
nvec = std::min(nvec, nconv);
ComplexMatrix res(m_n, nvec);
if(!nvec)
return res;
ComplexMatrix ritz_vec_conv(m_ncv, nvec);
int j = 0;
for(int i = 0; i < m_nev && j < nvec; i++)
{
if(m_ritz_conv[i])
{
ritz_vec_conv.col(j) = m_ritz_vec.col(i);
j++;
}
}
res.noalias() = m_fac_V * ritz_vec_conv;
return res;
}
///
/// Returns all converged eigenvectors.
///
ComplexMatrix eigenvectors() const
{
return eigenvectors(m_nev);
}
};
} // namespace Spectra
#endif // GEN_EIGS_SOLVER_H
| 34.663324 | 105 | 0.546105 | [
"object",
"vector"
] |
9ac751fdb415896bdb343f2173b75f4fb002c743 | 5,128 | h | C | content/browser/accessibility/browser_accessibility_cocoa.h | SlimKatLegacy/android_external_chromium_org | ee480ef5039d7c561fc66ccf52169ead186f1bea | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | content/browser/accessibility/browser_accessibility_cocoa.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | content/browser/accessibility/browser_accessibility_cocoa.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.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 CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_COCOA_H_
#define CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_COCOA_H_
#import <Cocoa/Cocoa.h>
#import "base/mac/scoped_nsobject.h"
#include "content/browser/accessibility/browser_accessibility.h"
#import "content/browser/accessibility/browser_accessibility_delegate_mac.h"
#include "third_party/WebKit/public/web/WebAXEnums.h"
// BrowserAccessibilityCocoa is a cocoa wrapper around the BrowserAccessibility
// object. The renderer converts webkit's accessibility tree into a
// WebAccessibility tree and passes it to the browser process over IPC.
// This class converts it into a format Cocoa can query.
@interface BrowserAccessibilityCocoa : NSObject {
@private
content::BrowserAccessibility* browserAccessibility_;
base::scoped_nsobject<NSMutableArray> children_;
id<BrowserAccessibilityDelegateCocoa> delegate_;
}
// This creates a cocoa browser accessibility object around
// the cross platform BrowserAccessibility object. The delegate is
// used to communicate with the host renderer. None of these
// parameters can be null.
- (id)initWithObject:(content::BrowserAccessibility*)accessibility
delegate:(id<BrowserAccessibilityDelegateCocoa>)delegate;
// Clear this object's pointer to the wrapped BrowserAccessibility object
// because the wrapped object has been deleted, but this object may
// persist if the system still has references to it.
- (void)detach;
// Invalidate children for a non-ignored ancestor (including self).
- (void)childrenChanged;
// Convenience method to get the internal, cross-platform role
// from browserAccessibility_.
- (blink::WebAXRole)internalRole;
// Return the method name for the given attribute. For testing only.
- (NSString*)methodNameForAttribute:(NSString*)attribute;
// Internally-used method.
@property(nonatomic, readonly) NSPoint origin;
// Children is an array of BrowserAccessibility objects, representing
// the accessibility children of this object.
@property(nonatomic, readonly) NSString* accessKey;
@property(nonatomic, readonly) NSNumber* ariaAtomic;
@property(nonatomic, readonly) NSNumber* ariaBusy;
@property(nonatomic, readonly) NSString* ariaLive;
@property(nonatomic, readonly) NSString* ariaRelevant;
@property(nonatomic, readonly) NSArray* children;
@property(nonatomic, readonly) NSArray* columns;
@property(nonatomic, readonly) NSArray* columnHeaders;
@property(nonatomic, readonly) NSValue* columnIndexRange;
@property(nonatomic, readonly) NSString* description;
@property(nonatomic, readonly) NSNumber* disclosing;
@property(nonatomic, readonly) id disclosedByRow;
@property(nonatomic, readonly) NSNumber* disclosureLevel;
@property(nonatomic, readonly) id disclosedRows;
@property(nonatomic, readonly) NSNumber* enabled;
@property(nonatomic, readonly) NSNumber* focused;
@property(nonatomic, readonly) NSString* help;
// isIgnored returns whether or not the accessibility object
// should be ignored by the accessibility hierarchy.
@property(nonatomic, readonly, getter=isIgnored) BOOL ignored;
// Index of a row, column, or tree item.
@property(nonatomic, readonly) NSNumber* index;
@property(nonatomic, readonly) NSString* invalid;
@property(nonatomic, readonly) NSNumber* loaded;
@property(nonatomic, readonly) NSNumber* loadingProgress;
@property(nonatomic, readonly) NSNumber* maxValue;
@property(nonatomic, readonly) NSNumber* minValue;
@property(nonatomic, readonly) NSNumber* numberOfCharacters;
@property(nonatomic, readonly) NSString* orientation;
@property(nonatomic, readonly) id parent;
@property(nonatomic, readonly) NSValue* position;
@property(nonatomic, readonly) NSNumber* required;
// A string indicating the role of this object as far as accessibility
// is concerned.
@property(nonatomic, readonly) NSString* role;
@property(nonatomic, readonly) NSString* roleDescription;
@property(nonatomic, readonly) NSArray* rowHeaders;
@property(nonatomic, readonly) NSValue* rowIndexRange;
@property(nonatomic, readonly) NSArray* rows;
// The size of this object.
@property(nonatomic, readonly) NSValue* size;
// A string indicating the subrole of this object as far as accessibility
// is concerned.
@property(nonatomic, readonly) NSString* subrole;
// The tabs owned by a tablist.
@property(nonatomic, readonly) NSArray* tabs;
@property(nonatomic, readonly) NSString* title;
@property(nonatomic, readonly) id titleUIElement;
@property(nonatomic, readonly) NSString* url;
@property(nonatomic, readonly) NSString* value;
@property(nonatomic, readonly) NSString* valueDescription;
@property(nonatomic, readonly) NSValue* visibleCharacterRange;
@property(nonatomic, readonly) NSArray* visibleCells;
@property(nonatomic, readonly) NSArray* visibleColumns;
@property(nonatomic, readonly) NSArray* visibleRows;
@property(nonatomic, readonly) NSNumber* visited;
@property(nonatomic, readonly) id window;
@end
#endif // CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_COCOA_H_
| 45.380531 | 79 | 0.802262 | [
"object"
] |
9acb50e46ef1e5cd73b1c7a7c8a80e281ff01c05 | 9,072 | h | C | src/mumble/GlobalShortcut.h | bogie/mumble | 48c3a19aba885177e2b7a17f90bf5617104b18fa | [
"BSD-3-Clause"
] | 2 | 2019-09-10T18:12:41.000Z | 2020-07-04T23:57:45.000Z | src/mumble/GlobalShortcut.h | bogie/mumble | 48c3a19aba885177e2b7a17f90bf5617104b18fa | [
"BSD-3-Clause"
] | null | null | null | src/mumble/GlobalShortcut.h | bogie/mumble | 48c3a19aba885177e2b7a17f90bf5617104b18fa | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION 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 MUMBLE_MUMBLE_GLOBALSHORTCUT_H_
#define MUMBLE_MUMBLE_GLOBALSHORTCUT_H_
#include <QtCore/QtGlobal>
#include <QtCore/QThread>
#if QT_VERSION >= 0x050000
# include <QtWidgets/QToolButton>
# include <QtWidgets/QStyledItemDelegate>
#else
# include <QtGui/QToolButton>
# include <QtGui/QStyledItemDelegate>
#endif
#include "ConfigDialog.h"
#include "Timer.h"
#include "ui_GlobalShortcut.h"
#include "ui_GlobalShortcutTarget.h"
class GlobalShortcut : public QObject {
friend class GlobalShortcutEngine;
friend class GlobalShortcutConfig;
private:
Q_OBJECT
Q_DISABLE_COPY(GlobalShortcut)
protected:
QList<QVariant> qlActive;
signals:
void down(QVariant);
void triggered(bool, QVariant);
public:
QString qsToolTip;
QString qsWhatsThis;
QString name;
QVariant qvDefault;
bool bExpert;
int idx;
GlobalShortcut(QObject *parent, int index, QString qsName, bool expert = true, QVariant def = QVariant());
~GlobalShortcut() Q_DECL_OVERRIDE;
bool active() const {
return ! qlActive.isEmpty();
}
};
/**
* Widget used to define and key combination for a shortcut. Once it gains
* focus it will listen for a button combination until it looses focus.
*/
class ShortcutKeyWidget : public QLineEdit {
private:
Q_OBJECT
Q_DISABLE_COPY(ShortcutKeyWidget)
Q_PROPERTY(QList<QVariant> shortcut READ getShortcut WRITE setShortcut USER true)
protected:
virtual void focusInEvent(QFocusEvent *event);
virtual void focusOutEvent(QFocusEvent *event);
virtual void mouseDoubleClickEvent(QMouseEvent *e);
virtual bool eventFilter(QObject *, QEvent *);
public:
QList<QVariant> qlButtons;
bool bModified;
ShortcutKeyWidget(QWidget *p = NULL);
QList<QVariant> getShortcut() const;
void displayKeys(bool last = true);
public slots:
void updateKeys(bool last);
void setShortcut(const QList<QVariant> &shortcut);
signals:
void keySet(bool, bool);
};
/**
* Combo box widget used to define the kind of action a shortcut triggers. Then
* entries get auto-generated from the GlobalShortcutEngine::qmShortcuts store.
*
* @see GlobalShortcutEngine
*/
class ShortcutActionWidget : public QComboBox {
private:
Q_OBJECT
Q_DISABLE_COPY(ShortcutActionWidget)
Q_PROPERTY(unsigned int index READ index WRITE setIndex USER true)
public:
ShortcutActionWidget(QWidget *p = NULL);
unsigned int index() const;
void setIndex(int);
};
class ShortcutToggleWidget : public QComboBox {
private:
Q_OBJECT
Q_DISABLE_COPY(ShortcutToggleWidget)
Q_PROPERTY(int index READ index WRITE setIndex USER true)
public:
ShortcutToggleWidget(QWidget *p = NULL);
int index() const;
void setIndex(int);
};
/**
* Dialog which is used to select the targets of a targeted shortcut like Whisper.
*/
class ShortcutTargetDialog : public QDialog, public Ui::GlobalShortcutTarget {
private:
Q_OBJECT
Q_DISABLE_COPY(ShortcutTargetDialog)
protected:
QMap<QString, QString> qmHashNames;
ShortcutTarget stTarget;
public:
ShortcutTargetDialog(const ShortcutTarget &, QWidget *p = NULL);
ShortcutTarget target() const;
public slots:
void accept() Q_DECL_OVERRIDE;
void on_qrbUsers_clicked();
void on_qrbChannel_clicked();
void on_qpbAdd_clicked();
void on_qpbRemove_clicked();
};
enum ShortcutTargetTypes {
SHORTCUT_TARGET_ROOT = -1,
SHORTCUT_TARGET_PARENT = -2,
SHORTCUT_TARGET_CURRENT = -3,
SHORTCUT_TARGET_SUBCHANNEL = -4,
SHORTCUT_TARGET_PARENT_SUBCHANNEL = -12
};
/**
* Widget used to display and change a ShortcutTarget. The widget displays a textual representation
* of a ShortcutTarget and enable its editing with a ShortCutTargetDialog.
*/
class ShortcutTargetWidget : public QFrame {
private:
Q_OBJECT
Q_DISABLE_COPY(ShortcutTargetWidget)
Q_PROPERTY(ShortcutTarget target READ target WRITE setTarget USER true)
protected:
ShortcutTarget stTarget;
QLineEdit *qleTarget;
QToolButton *qtbEdit;
public:
ShortcutTargetWidget(QWidget *p = NULL);
ShortcutTarget target() const;
void setTarget(const ShortcutTarget &);
static QString targetString(const ShortcutTarget &);
public slots:
void on_qtbEdit_clicked();
};
/**
* Used to get custom display and edit behaviour for the model used in GlobalShortcutConfig::qtwShortcuts.
* It registers custom handlers which link specific types to custom ShortcutXWidget editors and also
* provides a basic textual representation for them when they are not edited.
*
* @see GlobalShortcutConfig
* @see ShortcutKeyWidget
* @see ShortcutActionWidget
* @see ShortcutTargetWidget
*/
class ShortcutDelegate : public QStyledItemDelegate {
Q_OBJECT
Q_DISABLE_COPY(ShortcutDelegate)
public:
ShortcutDelegate(QObject *);
~ShortcutDelegate() Q_DECL_OVERRIDE;
QString displayText(const QVariant &, const QLocale &) const Q_DECL_OVERRIDE;
};
/**
* Contains the Shortcut tab from the settings. This ConfigWidget provides
* the user with the interface to add/edit/delete global shortcuts in Mumble.
*/
class GlobalShortcutConfig : public ConfigWidget, public Ui::GlobalShortcut {
friend class ShortcutActionWidget;
private:
Q_OBJECT
Q_DISABLE_COPY(GlobalShortcutConfig)
protected:
QList<Shortcut> qlShortcuts;
QTreeWidgetItem *itemForShortcut(const Shortcut &) const;
bool bExpert;
bool showWarning() const;
bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE;
public:
GlobalShortcutConfig(Settings &st);
virtual QString title() const Q_DECL_OVERRIDE;
virtual QIcon icon() const Q_DECL_OVERRIDE;
public slots:
void accept() const Q_DECL_OVERRIDE;
void save() const Q_DECL_OVERRIDE;
void load(const Settings &r) Q_DECL_OVERRIDE;
void reload();
bool expert(bool) Q_DECL_OVERRIDE;
void commit();
void on_qcbEnableGlobalShortcuts_stateChanged(int);
void on_qpbAdd_clicked(bool);
void on_qpbRemove_clicked(bool);
void on_qtwShortcuts_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *);
void on_qtwShortcuts_itemChanged(QTreeWidgetItem *, int);
void on_qpbOpenAccessibilityPrefs_clicked();
void on_qpbSkipWarning_clicked();
};
struct ShortcutKey {
Shortcut s;
int iNumUp;
GlobalShortcut *gs;
};
/**
* Creates a background thread which handles global shortcut behaviour. This class inherits
* a system unspecific interface and basic functionality to the actually used native backend
* classes (GlobalShortcutPlatform).
*
* @see GlobalShortcutX
* @see GlobalShortcutMac
* @see GlobalShortcutWin
*/
class GlobalShortcutEngine : public QThread {
private:
Q_OBJECT
Q_DISABLE_COPY(GlobalShortcutEngine)
public:
bool bNeedRemap;
Timer tReset;
static GlobalShortcutEngine *engine;
static GlobalShortcutEngine *platformInit();
QHash<int, GlobalShortcut *> qmShortcuts;
QList<QVariant> qlActiveButtons;
QList<QVariant> qlDownButtons;
QList<QVariant> qlSuppressed;
QList<QVariant> qlButtonList;
QList<QList<ShortcutKey *> > qlShortcutList;
GlobalShortcutEngine(QObject *p = NULL);
~GlobalShortcutEngine() Q_DECL_OVERRIDE;
void resetMap();
void remap();
virtual void needRemap();
void run();
bool handleButton(const QVariant &, bool);
static void add(GlobalShortcut *);
static void remove(GlobalShortcut *);
static QString buttonText(const QList<QVariant> &);
virtual QString buttonName(const QVariant &) = 0;
virtual bool canSuppress();
virtual void setEnabled(bool b);
virtual bool enabled();
virtual bool canDisable();
virtual void prepareInput();
signals:
void buttonPressed(bool last);
};
#endif
| 30.648649 | 108 | 0.768849 | [
"model"
] |
9acc46f4883e345971d175014669311ea75d7c48 | 98,788 | h | C | qrenderdoc/Code/Interface/QRDInterface.h | songhong/renderdoc | 745c4ca8e5d0ddb79bea1c63239056ebc08870ed | [
"MIT"
] | 6,181 | 2015-01-07T11:49:11.000Z | 2022-03-31T21:46:55.000Z | qrenderdoc/Code/Interface/QRDInterface.h | songhong/renderdoc | 745c4ca8e5d0ddb79bea1c63239056ebc08870ed | [
"MIT"
] | 2,015 | 2015-01-16T01:45:25.000Z | 2022-03-25T12:01:06.000Z | qrenderdoc/Code/Interface/QRDInterface.h | songhong/renderdoc | 745c4ca8e5d0ddb79bea1c63239056ebc08870ed | [
"MIT"
] | 1,088 | 2015-01-06T08:36:25.000Z | 2022-03-30T03:31:21.000Z | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2021 Baldur Karlsson
*
* 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
// don't add any Qt headers visible to SWIG, as we don't want a Qt dependency for the SWIG-generated
// qrenderdoc module. Instead we should use public RDC types for any public QRenderDoc headers, and
// define conversions to/from Qt types. See rdcstr / QString, rdcpair / QPair, and
// rdcdatetime / QDateTime.
#include <functional>
// For string literals - use either tr() for translated strings, lit() for untranslated strings, or
// QFormatStr for the special case of literals without text used to format text with .arg().
//
// A default constructed QString() should be preferred to "".
//
// Instead of comparisons to "", use .isEmpty() - either !foo.isEmpty() for foo != "" or
// foo.isEmpty() for foo == "".
// this macro is fairly small/non-namespaced which is generally not good, but it's intended to
// be correspond to the tr() function in QObject, but for string literals. It makes the code a
// little bit more readable.
//
// If you have some text which should not be translated, then it should use lit().
#define lit(a) QStringLiteral(a)
// Same as lit() above, but only for formatting strings like QFormatStr("%1: %2[%3]").
// Note that tr() and lit() can format as well, so if there's text in the format string like
// QFormatStr("Sprocket thingy: %1.%2") then it should use either tr() or lit() depending on whether
// or not it should be translated
#define QFormatStr(fmt) QStringLiteral(fmt)
// this is pre-declared as an opaque type as we only support converting to QWidget* via PySide
class QWidget;
class QMenu;
// we only support QVariant as an 'internal' interface, it's not exposed to python. However we need
// to use it in constructors/operators so conditionally compile it rather than split small structs
// into interface/implementations
#if defined(SWIG) || defined(SWIG_GENERATED)
#define VARIANT_CAST(classname)
#else
#include <QVariant>
// conversion to/from QVariant
#define VARIANT_CAST(classname) \
classname(const QVariant &var); \
operator QVariant() const;
// we also add some headers here that are only needed for Qt helpers in the replay interface, which
// is not exposed to swig
#define RENDERDOC_QT_COMPAT
#include <QColor>
#include <QDateTime>
#include <QList>
#include <QString>
#include <QVector>
#endif
// we depend on the internal RenderDoc API, but the bindings for that are imported entirely
#include "renderdoc_replay.h"
typedef rdcpair<rdcstr, rdcstr> rdcstrpair;
typedef rdcarray<rdcstrpair> rdcstrpairs;
struct ICaptureContext;
#include "Analytics.h"
#include "Extensions.h"
#include "PersistantConfig.h"
#include "RemoteHost.h"
DOCUMENT("Contains all of the settings that control how to capture an executable.");
struct CaptureSettings
{
CaptureSettings();
VARIANT_CAST(CaptureSettings);
DOCUMENT(R"(The settings for the capture.
:type: renderdoc.CaptureOptions
)");
CaptureOptions options;
DOCUMENT(
"``True`` if the described capture is an inject-into-process instead of a launched "
"executable.");
bool inject;
DOCUMENT("``True`` if this capture settings object should be immediately executed upon load.");
bool autoStart;
DOCUMENT("The path to the executable to run.");
rdcstr executable;
DOCUMENT("The path to the working directory to run in, or blank for the executable's directory.");
rdcstr workingDir;
DOCUMENT("The command line to pass when running :data:`executable`.");
rdcstr commandLine;
DOCUMENT(R"(The environment changes to apply.
:type: List[renderdoc.EnvironmentModification]
)");
rdcarray<EnvironmentModification> environment;
DOCUMENT("The number of queued frames to capture, or 0 if no frames are queued to be captured.");
uint32_t numQueuedFrames;
DOCUMENT("The first queued frame to capture. Ignored if :data:`numQueuedFrames` is 0.");
uint32_t queuedFrameCap;
};
DECLARE_REFLECTION_STRUCT(CaptureSettings);
DOCUMENT(R"(The main parent window of the application.
.. function:: ShortcutCallback(QWidget focusWidget)
Not a member function - the signature for any ``ShortcutCallback`` callbacks.
:param QWidget focusWidget: The widget with focus at the time this shortcut was detected. May be
``None``.
)");
struct IMainWindow
{
typedef std::function<void(QWidget *focusWidget)> ShortcutCallback;
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`MainWindow` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Register a callback for a particular key shortcut.
This creates a managed shortcut. Qt's shortcut system doesn't allow specialisation/duplication, so
you can't use ``Ctrl+S`` for a shortcut in a window to update some changes if there's also a global
``Ctrl+S`` shortcut on the window. In the end, neither shortcut will be called.
Instead this function allows the main window to manage shortcuts internally, and it will pick the
closest shortcut to a given action. The search goes from the widget with the focus currently up the
chain of parents, with the first match being used. If no matches are found, then a 'global' default
will be invoked, if it exists.
:param str shortcut: The text string representing the shortcut, e.g. 'Ctrl+S'.
:param QWidget widget: A handle to the widget to use as the context for this shortcut, or ``None``
for a global shortcut. Note that if an existing global shortcut exists the new one will not be
registered.
:param ShortcutCallback callback: The function to callback when the shortcut is hit.
)");
virtual void RegisterShortcut(const rdcstr &shortcut, QWidget *widget,
ShortcutCallback callback) = 0;
DOCUMENT(R"(Unregister a callback for a particular key shortcut, made in a previous call to
:meth:`RegisterShortcut`.
See the documentation for :meth:`RegisterShortcut` for what these shortcuts are for.
:param str shortcut: The text string representing the shortcut, e.g. 'Ctrl+S'. To unregister all
shortcuts for a particular widget, you can pass an empty string here. In this case,
:paramref:`UnregisterShortcut.widget` must not be ``None``.
:param QWidget widget: A handle to the widget used as the context for the shortcut, or ``None``
if referring to a global shortcut.
)");
virtual void UnregisterShortcut(const rdcstr &shortcut, QWidget *widget) = 0;
protected:
IMainWindow() = default;
~IMainWindow() = default;
};
DECLARE_REFLECTION_STRUCT(IMainWindow);
DOCUMENT(R"(The event browser window.
.. function:: EventFilterCallback(context, filter, params, eventId, chunk, action, name)
Not a member function - the signature for any ``EventFilterCallback`` callbacks.
Called for each event in a capture when performing filtering in the Event Browser. The associated
``FilterParseCallback`` will be called first to parse the parameters, and is available for caching
or syntax checking. The same filter name and params string will be passed to this function.
:param CaptureContext context: The current capture context.
:param str filter: The name of the filter function.
:param str params: The parameters to the filter function.
:param int eventId: The event's :data:`eventId <renderdoc.APIEvent.eventId>`.
:param renderdoc.SDChunk chunk: The structured data chunk for this event.
:param renderdoc.ActionDescription action: The action that contains this event. If the event is
the action itself then the event ID will be equal.
:param str name: The name of the event as shown in the event browser, for string-based filtering.
:return: Whether or not this event matches the filter
:rtype: bool
.. function:: FilterParseCallback(context, filter, params)
Not a member function - the signature for any ``FilterParseCallback`` callbacks.
Called once when the filter changes, to allow parsing any any data caching, as well as reporting
of errors in the filter usage.
:param CaptureContext context: The current capture context.
:param str filter: The name of the filter function.
:param str params: The parameters to the filter function.
:return: An empty string if the parse succeeded, otherwise any error messages to be displayed to
the user, such as syntax or other errors.
:rtype: str
.. function:: AutoCompleteCallback(context, filter, params)
Not a member function - the signature for any ``AutoCompleteCallback`` callbacks.
Called when autocompletion is triggered inside a filter. The params passed are any previous
text inside the filter's parameter list up to where the cursor is. The callback should return a
list of identifiers used for auto-completion.
The list does not have to be pre-filtered for matches to the :paramref:`params`, that is provided
to allow different autocompletion at different stages (e.g. if there are no parameters, you can
autocomplete a property, if a property is already present you can autocomplete valid values for
it)
:param CaptureContext context: The current capture context.
:param str filter: The name of the filter function.
:param str params: The previous parameter text to the filter function.
:return: A list of strings giving identifiers to autocomplete, or an empty list of there are no
such identifiers to prompt.
:rtype: List[str]
)");
struct IEventBrowser
{
typedef std::function<bool(ICaptureContext *, const rdcstr &, const rdcstr &, uint32_t,
const SDChunk *, const ActionDescription *, const rdcstr &)>
EventFilterCallback;
typedef std::function<rdcstr(ICaptureContext *, const rdcstr &, const rdcstr &)> FilterParseCallback;
typedef std::function<rdcarray<rdcstr>(ICaptureContext *, const rdcstr &, const rdcstr &)>
AutoCompleteCallback;
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`EventBrowser` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT("Updates the duration column if the selected time unit changes.");
virtual void UpdateDurationColumn() = 0;
DOCUMENT(R"(Uses the existing caching in the event browser to return a :class:`~renderdoc.APIEvent`
for a specified EID.
If no capture is loaded or the EID doesn't correspond to a known event, an empty struct will be
returned.
:param int eventId: The EID to look up.
:return: The event corresponding to the EID, or an empty struct if no such EID exists.
:rtype: renderdoc.APIEvent
)");
virtual APIEvent GetAPIEventForEID(uint32_t eventId) = 0;
DOCUMENT(R"(Uses the existing caching in the event browser to return a
:class:`~renderdoc.ActionDescription` for a specified EID. This action may not be the exact EID
specified, but it will be the action that the EID is associated with. I.e. if you specify the EID for
a state setting event the next action will be returned.
If no capture is loaded or the EID doesn't correspond to a known event, ``None`` will be returned.
:param int eventId: The EID to look up.
:return: The action containing the EID, or ``None`` if no such EID exists.
:rtype: renderdoc.ActionDescription
)");
virtual const ActionDescription *GetActionForEID(uint32_t eventId) = 0;
DOCUMENT(R"(Returns the formatted name of an event according to the current settings, whether
that be a custom name or an auto-generated name with/without parameter names.
If no capture is loaded or the EID doesn't correspond to a known event, an empty string will be
returned.
:param int eventId: The EID to look up.
:return: The formatted name of the specified event, or ``None`` if no such EID exists.
:rtype: str
)");
virtual rdcstr GetEventName(uint32_t eventId) = 0;
DOCUMENT(R"(Determines if a given EID is visible with the current filters applied to the event
browser.
If no capture is loaded or the EID doesn't correspond to a known event, ``False`` will be returned.
:param int eventId: The EID to look up.
:return: Whether or not the event is currently visible (passing the filters).
:rtype: bool
)");
virtual bool IsAPIEventVisible(uint32_t eventId) = 0;
DOCUMENT(R"(Registers a new event browser filter function.
Filter functions are available as $name() so long as they don't shadow an existing function. The
filter callback will be called for each event to filter.
The parser callback will be called once when a filter is first specified or the parameters change.
Note that a filter can be used multiple times in a filter expression! For this reason the parser
may be called multiple times and the filter callback takes the parameters string. If any expensive
work is done then the parameters can be used as a cache key to cache any data once per filter
expression.
:param str name: The name of the filter function.
:param str description: The description of the filter function. This should explain the available
parameters (if applicable) and what the filter does. It will be used for documenting to users
what each filter means.
:param EventFilterCallback filter: The callback to call for each candidate event to perform
filtering.
:param FilterParseCallback parser: The callback to call when the parsing the parameters and checking
for any errors. This can be ``None`` if no pre-parsing is required.
:param AutoCompleteCallback completer: The callback to call when trying to provide autocomplete
suggestions. This can be ``None`` if no completion is desired/applicable.
:return: Whether or not the registration was successful.
:rtype: bool
)");
virtual bool RegisterEventFilterFunction(const rdcstr &name, const rdcstr &description,
EventFilterCallback filter, FilterParseCallback parser,
AutoCompleteCallback completer) = 0;
DOCUMENT(R"(Unregisters an event browser filter function that was previously registered.
:param str name: The name of the filter function.
:return: Whether or not the unregistration was successful.
:rtype: bool
)");
virtual bool UnregisterEventFilterFunction(const rdcstr &name) = 0;
DOCUMENT(R"(Sets the current filter text. This will not modify any saved filter but will modify
the scratch filter. The filter is applied immediately.
:param str text: The filter text.
)");
virtual void SetCurrentFilterText(const rdcstr &text) = 0;
DOCUMENT(R"(Returns the current filter text, whether temporary or a saved filter.
:return: The current filter text.
:rtype: str
)");
virtual rdcstr GetCurrentFilterText() = 0;
DOCUMENT(R"(Sets whether or not custom action names are used. Certain actions such as indirect
actions it is useful to show a custom action name which contains the actual indirect parameters
instead of the 'raw' parameters.
:param bool use: Whether or not custom action names will be used.
)");
virtual void SetUseCustomActionNames(bool use) = 0;
DOCUMENT(R"(Sets whether or not parameter names are shown in the events. If disabled, only the
value is shown and the parameter is implicit.
.. note::
If custom action names are used this will not have an effect for any such actions. See
:meth:`SetUseCustomActionNames`.
:param bool show: Whether or not parameter names will be shown.
)");
virtual void SetShowParameterNames(bool show) = 0;
DOCUMENT(R"(Sets whether or not all parameters are shown in the events. By default only
the most significant parameters are shown.
.. note::
If custom action names are used this will not have an effect for any such actions. See
:meth:`SetUseCustomActionNames`.
:param bool show: Whether or not parameter names will be shown.
)");
virtual void SetShowAllParameters(bool show) = 0;
DOCUMENT(R"(Sets whether or not marker regions which have no visible actions.
:param bool show: Whether or not empty regions after filtering will be shown.
)");
virtual void SetEmptyRegionsVisible(bool show) = 0;
protected:
IEventBrowser() = default;
~IEventBrowser() = default;
};
DECLARE_REFLECTION_STRUCT(IEventBrowser);
DOCUMENT("The API inspector window.");
struct IAPIInspector
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`APIInspector` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT("Refresh the current API view - useful if callstacks are now available.");
virtual void Refresh() = 0;
DOCUMENT(R"(Expand the API view to reveal a given parameter and select it.
:param renderdoc.SDObject param: The parameter to reveal and select.
)");
virtual void RevealParameter(SDObject *param) = 0;
protected:
IAPIInspector() = default;
~IAPIInspector() = default;
};
DECLARE_REFLECTION_STRUCT(IAPIInspector);
DOCUMENT(R"(Specifies a pipeline stage for the :class:`PipelineStateViewer`.
.. data:: VertexInput
The fixed function vertex input stage.
.. data:: VertexShader
The vertex shader.
.. data:: HullShader
The vertex shader.
.. data:: TessControlShader
The tessellation control shader.
.. data:: DomainShader
The domain shader.
.. data:: TessEvalShader
The tessellation evaluation shader.
.. data:: GeometryShader
The geometry shader, including stream-out/transform feedback.
.. data:: Rasterizer
The fixed function rasterizer stage.
.. data:: ViewportsScissors
The viewports and scissors. Helper alias for :data:`Rasterizer`.
.. data:: PixelShader
The pixel shader.
.. data:: FragmentShader
The fragment shader.
.. data:: ColorDepthOutput
The fixed function color and depth output stage, including color blending and depth/stencil
testing state.
.. data:: Blending
The color blending state. Helper alias for :data:`ColorDepthOutput`.
.. data:: DepthTest
The depth test state. Helper alias for :data:`ColorDepthOutput`.
.. data:: StencilTest
The stencil test state. Helper alias for :data:`ColorDepthOutput`.
.. data:: ComputeShader
The compute shader.
.. data:: SampleMask
The sample mask.
)");
enum class PipelineStage : int
{
VertexInput = 0,
VertexShader,
HullShader,
TessControlShader = HullShader,
DomainShader,
TessEvalShader = DomainShader,
GeometryShader,
Rasterizer,
ViewportsScissors = Rasterizer,
PixelShader,
FragmentShader = PixelShader,
ColorDepthOutput,
Blending = ColorDepthOutput,
DepthTest = ColorDepthOutput,
StencilTest = ColorDepthOutput,
ComputeShader,
// these vary by API
SampleMask,
};
DOCUMENT("The pipeline state viewer window.");
struct IPipelineStateViewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`PipelineStateViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Prompt the user to save the binary form of the given shader to disk.
:param renderdoc.ShaderReflection shader: The shader reflection data to save.
:return: ``True`` if the shader was saved successfully, ``False`` if an error occurred.
:rtype: bool
)");
virtual bool SaveShaderFile(const ShaderReflection *shader) = 0;
DOCUMENT(R"(Select a given pipeline stage in the viewer.
:param PipelineStage stage: The stage to select.
)");
virtual void SelectPipelineStage(PipelineStage stage) = 0;
protected:
IPipelineStateViewer() = default;
~IPipelineStateViewer() = default;
};
DECLARE_REFLECTION_STRUCT(IPipelineStateViewer);
DOCUMENT(R"(Specifies a type of followed resource for the :class:`TextureViewer`.
.. data:: OutputColor
The index specifies which output color target to select. Shader stage and array index are ignored.
.. data:: OutputDepth
The resource followed is the depth/stencil output target. All other parameters are ignored.
.. data:: ReadWrite
The index specifies a resource within the given shader's
:data:`read-write resources <~renderdoc.ShaderReflection.readWriteResources>`. The array element
then specifies the index within that resource's array, if applicable.
.. data:: ReadOnly
The index specifies a resource within the given shader's
:data:`read-only resources <~renderdoc.ShaderReflection.readOnlyResources>`. The array element
then specifies the index within that resource's array, if applicable.
)");
enum class FollowType : int
{
OutputColor,
OutputDepth,
ReadWrite,
ReadOnly
};
DOCUMENT("The texture viewer window.");
struct ITextureViewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`TextureViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Open a texture view, optionally raising this window to the foreground.
:param renderdoc.ResourceId resourceId: The ID of the texture to view.
:param renderdoc.CompType typeCast: If possible interpret the texture with this type instead of its
normal type. If set to :data:`~renderdoc.CompType.Typeless` then no cast is applied, otherwise
where allowed the texture data will be reinterpreted - e.g. from unsigned integers to floats, or
to unsigned normalised values.
:param bool focus: ``True`` if the :class:`TextureViewer` should be raised.
)");
virtual void ViewTexture(ResourceId resourceId, CompType typeCast, bool focus) = 0;
DOCUMENT(R"(Select the 'following' view and choose which resource slot to follow.
:param FollowType followType: The type of followed resource.
:param renderdoc.ShaderStage stage: The shader stage of the shader reflection data to look up.
:param int index: The index within the given resource list (if applicable) to follow.
:param int arrayElement: The index within the given resource array (if applicable) to follow.
)");
virtual void ViewFollowedResource(FollowType followType, ShaderStage stage, int32_t index,
int32_t arrayElement) = 0;
DOCUMENT(R"(Return which resource is currently being displayed in the active tab.
:return: The ID of the resource being displayed.
:rtype: renderdoc.ResourceId
)");
virtual ResourceId GetCurrentResource() = 0;
DOCUMENT(R"(Return which subresource is currently selected for viewing.
:return: The subresource currently selected.
:rtype: renderdoc.Subresource
)");
virtual Subresource GetSelectedSubresource() = 0;
DOCUMENT(R"(Select a particular subresource within the currently selected texture. Any out of
bounds parameters will be clamped to the available subresources.
:param renderdoc.Subresource sub: The subresource to select.
)");
virtual void SetSelectedSubresource(Subresource sub) = 0;
DOCUMENT(R"(Highlights the given pixel location in the current texture.
:param int x: The X co-ordinate.
:param int y: The Y co-ordinate.
)");
virtual void GotoLocation(uint32_t x, uint32_t y) = 0;
DOCUMENT(R"(Return the currently selected texture overlay.
:return: The currently selected texture overlay.
:rtype: renderdoc.DebugOverlay
)");
virtual DebugOverlay GetTextureOverlay() = 0;
DOCUMENT(R"(Changes the currently selected overlay the given pixel location in the current texture.
:param renderdoc.DebugOverlay overlay: The overlay to enable.
)");
virtual void SetTextureOverlay(DebugOverlay overlay) = 0;
DOCUMENT(R"(Return whether or not the texture viewer is currently auto-fitting the zoom level.
:return: ``True`` if the zoom level is currently auto-fitting.
:rtype: bool
)");
virtual bool IsZoomAutoFit() = 0;
DOCUMENT(R"(Return the current zoom level, whether manually set or auto-calculated.
:return: The current zoom level, with 100% being represented as 1.0.
:rtype: float
)");
virtual float GetZoomLevel() = 0;
DOCUMENT(R"(Set the zoom level for displaying textures.
:param bool autofit: ``True`` if the zoom level should be auto-calculated continuously to
automatically fit the texture completely in view.
:param float zoom: The zoom level as a percentage, with 100% being 1.0. Ignored if
:paramref:`autofit` is ``True``.
)");
virtual void SetZoomLevel(bool autofit, float zoom) = 0;
DOCUMENT(R"(Return the current histogram blackpoint to whitepoint range.
:return: The current histogram range.
:rtype: Tuple[float,float]
)");
virtual rdcpair<float, float> GetHistogramRange() = 0;
DOCUMENT(R"(Set the current histogram blackpoint to whitepoint range.
:param float blackpoint: The value that should be mapped to black, component-wise.
:param float whitepoint: The value that should be mapped to white, component-wise.
)");
virtual void SetHistogramRange(float blackpoint, float whitepoint) = 0;
DOCUMENT(R"(Return which channels are currently displayed, as a bitmask.
If red is visible ``0x1`` will be set in the returned value, if blue is visible ``0x2`` will be set,
etc.
:return: The current bitmask showing channel visibility.
:rtype: int
)");
virtual uint32_t GetChannelVisibilityBits() = 0;
DOCUMENT(R"(Set the visibility of each channel.
:param bool red: Whether the red channel should be visible.
:param bool green: Whether the green channel should be visible.
:param bool blue: Whether the blue channel should be visible.
:param bool alpha: Whether the alpha channel should be visible.
)");
virtual void SetChannelVisibility(bool red, bool green, bool blue, bool alpha) = 0;
protected:
ITextureViewer() = default;
~ITextureViewer() = default;
};
DECLARE_REFLECTION_STRUCT(ITextureViewer);
DOCUMENT("The buffer viewer window, either a raw buffer or the geometry pipeline.");
struct IBufferViewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`BufferViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Scroll to the given row in the given stage's data.
:param int row: the row to scroll to.
:param renderdoc.MeshDataStage stage: The stage of the geometry pipeline to scroll within.
)");
virtual void ScrollToRow(int32_t row, MeshDataStage stage = MeshDataStage::VSIn) = 0;
DOCUMENT(R"(Scroll to the given column in the given stage's data.
:param int column: the column to scroll to.
:param renderdoc.MeshDataStage stage: The stage of the geometry pipeline to scroll within.
)");
virtual void ScrollToColumn(int32_t column, MeshDataStage stage = MeshDataStage::VSIn) = 0;
DOCUMENT(R"(For a mesh view, set the current instance. This is ignored when called on a raw buffer
view.
:param int instance: The instance to select, will be clamped to the range [0, numInstances-1]
)");
virtual void SetCurrentInstance(int32_t instance) = 0;
DOCUMENT(R"(For a mesh view, set the current multiview view. This is ignored when called on a raw
buffer view.
:param int view: The view to select, will be clamped to the range [0, numViews-1]
)");
virtual void SetCurrentView(int32_t view) = 0;
DOCUMENT(R"(For a mesh view, set the current preview stage. This is ignored when called on a raw
buffer view.
:param renderdoc.MeshDataStage stage: The stage to show
)");
virtual void SetPreviewStage(MeshDataStage stage) = 0;
protected:
IBufferViewer() = default;
~IBufferViewer() = default;
};
DECLARE_REFLECTION_STRUCT(IBufferViewer);
DOCUMENT("The Resource inspector window.");
struct IResourceInspector
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`ResourceInspector` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Change the current resource being inspected.
:param renderdoc.ResourceId id: The ID of the resource to inspect.
)");
virtual void Inspect(ResourceId id) = 0;
DOCUMENT(R"(Return which resource is currently being inspected.
:return: The ID of the resource being inspected.
:rtype: renderdoc.ResourceId
)");
virtual ResourceId CurrentResource() = 0;
DOCUMENT(R"(Expand the resource initialisation chunks to reveal and select a given parameter.
:param renderdoc.SDObject param: The parameter to reveal and select.
)");
virtual void RevealParameter(SDObject *param) = 0;
protected:
IResourceInspector() = default;
~IResourceInspector() = default;
};
DECLARE_REFLECTION_STRUCT(IResourceInspector);
DOCUMENT("The executable capture window.");
struct ICaptureDialog
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`CaptureDialog` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Determines if the window is in inject or launch mode.
:return: ``True`` if the window is set up for injecting.
:rtype: bool
)");
virtual bool IsInjectMode() = 0;
DOCUMENT(R"(Switches the window to or from inject mode.
:param bool inject: ``True`` if the window should configure for injecting into processes.
)");
virtual void SetInjectMode(bool inject) = 0;
DOCUMENT(R"(Sets the executable filename to capture.
:param str filename: The filename to execute.
)");
virtual void SetExecutableFilename(const rdcstr &filename) = 0;
DOCUMENT(R"(Sets the working directory for capture.
:param str dir: The directory to use.
)");
virtual void SetWorkingDirectory(const rdcstr &dir) = 0;
DOCUMENT(R"(Sets the command line string to use when launching an executable.
:param str cmd: The command line to use.
)");
virtual void SetCommandLine(const rdcstr &cmd) = 0;
DOCUMENT(R"(Sets the list of environment modifications to apply when launching.
:param List[renderdoc.EnvironmentModification] modifications: The list of modifications to apply.
)");
virtual void SetEnvironmentModifications(const rdcarray<EnvironmentModification> &modifications) = 0;
DOCUMENT(R"(Configures the window based on a bulk structure of settings.
:param CaptureSettings settings: The settings to apply.
)");
virtual void SetSettings(CaptureSettings settings) = 0;
DOCUMENT(R"(Retrieves the current state of the window as a structure of settings.
:return: The settings describing the current window state.
:rtype: CaptureSettings
)");
virtual CaptureSettings Settings() = 0;
DOCUMENT("Launches a capture of the current executable.");
virtual void TriggerCapture() = 0;
DOCUMENT(R"(Loads settings from a file and applies them. See :meth:`SetSettings`.
:param str filename: The filename to load the settings from.
)");
virtual void LoadSettings(const rdcstr &filename) = 0;
DOCUMENT(R"(Saves the current settings to a file. See :meth:`Settings`.
:param str filename: The filename to save the settings to.
)");
virtual void SaveSettings(const rdcstr &filename) = 0;
DOCUMENT("Update the current state of the global hook, e.g. if it has been enabled.");
virtual void UpdateGlobalHook() = 0;
DOCUMENT("Update the current state based on the current remote host, when that changes.");
virtual void UpdateRemoteHost() = 0;
protected:
ICaptureDialog() = default;
~ICaptureDialog() = default;
};
DECLARE_REFLECTION_STRUCT(ICaptureDialog);
DOCUMENT("The debug warnings and errors window.");
struct IDebugMessageView
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`DebugMessageView` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
protected:
IDebugMessageView() = default;
~IDebugMessageView() = default;
};
DECLARE_REFLECTION_STRUCT(IDebugMessageView);
DOCUMENT("The diagnostic log viewing window.");
struct IDiagnosticLogView
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`DiagnosticLogView` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
protected:
IDiagnosticLogView() = default;
~IDiagnosticLogView() = default;
};
DECLARE_REFLECTION_STRUCT(IDiagnosticLogView);
DOCUMENT("The capture comments window.");
struct ICommentView
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`CommentView` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Sets the current comments text.
:param str text: The new comments text.
)");
virtual void SetComments(const rdcstr &text) = 0;
DOCUMENT(R"(Gets the current comments text.
:return: The current comments text.
:rtype: str
)");
virtual rdcstr GetComments() = 0;
protected:
ICommentView() = default;
~ICommentView() = default;
};
DECLARE_REFLECTION_STRUCT(ICommentView);
DOCUMENT("The statistics window.");
struct IStatisticsViewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`StatisticsViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
protected:
IStatisticsViewer() = default;
~IStatisticsViewer() = default;
};
DOCUMENT("The timeline bar.");
struct ITimelineBar
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`TimelineBar` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Highlights the frame usage of the specified resource.
:param renderdoc.ResourceId id: The ID of the resource to highlight.
)");
virtual void HighlightResourceUsage(ResourceId id) = 0;
DOCUMENT(R"(Highlights the modifications in a frame of a given resource.
:param renderdoc.ResourceId id: The ID of the resource that is being modified.
:param List[renderdoc.PixelModification] history: A list of pixel events to display.
)");
virtual void HighlightHistory(ResourceId id, const rdcarray<PixelModification> &history) = 0;
protected:
ITimelineBar() = default;
~ITimelineBar() = default;
};
DECLARE_REFLECTION_STRUCT(IStatisticsViewer);
DOCUMENT("The performance counter view window.");
struct IPerformanceCounterViewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`PerformanceCounterViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT("Updates duration columns if the selected time unit changes.");
virtual void UpdateDurationColumn() = 0;
protected:
IPerformanceCounterViewer() = default;
~IPerformanceCounterViewer() = default;
};
DECLARE_REFLECTION_STRUCT(IPerformanceCounterViewer);
DOCUMENT("The interactive python shell.");
struct IPythonShell
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`PythonShell` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
protected:
IPythonShell() = default;
~IPythonShell() = default;
};
DECLARE_REFLECTION_STRUCT(IPythonShell);
DOCUMENT(R"(A shader window used for viewing, editing, or debugging.
.. function:: SaveCallback(context, viewer, encoding, flags, entry, compiled)
Not a member function - the signature for any ``SaveCallback`` callbacks.
Called whenever a shader viewer that was open for editing triggers a save/update.
:param CaptureContext context: The current capture context.
:param ShaderViewer viewer: The open shader viewer.
:param renderdoc.ResourceId id: The id of the shader being replaced.
:param renderdoc.ShaderStage stage: The shader stage of the shader being replaced.
:param renderdoc.ShaderEncoding encoding: The encoding of the files being passed.
:param renderdoc.ShaderCompileFlags flags: The flags to use during compilation.
:param str entryFunc: The name of the entry point.
:param bytes source: The byte buffer containing the source - may just be text depending on the
encoding.
.. function:: CloseCallback(context)
Not a member function - the signature for any ``CloseCallback`` callbacks.
Called whenever a shader viewer that was open for editing is closed.
:param CaptureContext context: The current capture context.
:param ShaderViewer viewer: The open shader viewer.
:param renderdoc.ResourceId id: The id of the shader being replaced.
)");
struct IShaderViewer
{
typedef std::function<void(ICaptureContext *, IShaderViewer *, ResourceId, ShaderStage,
ShaderEncoding, ShaderCompileFlags, rdcstr, bytebuf)>
SaveCallback;
typedef std::function<void(ICaptureContext *, IShaderViewer *, ResourceId)> CloseCallback;
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`ShaderViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Retrieves the current step in the debugging.
:return: The current step.
:rtype: int
)");
virtual uint32_t CurrentStep() = 0;
DOCUMENT(R"(Sets the current step in the debugging.
:param int step: The current step to jump to.
)");
virtual void SetCurrentStep(uint32_t step) = 0;
DOCUMENT(R"(Toggles a breakpoint at a given instruction.
:param int instruction: The instruction to toggle breakpoint at. If this is ``-1`` the nearest
instruction after the current caret position is used.
)");
virtual void ToggleBreakpointOnInstruction(int32_t instruction = -1) = 0;
DOCUMENT(R"(Toggles a breakpoint at a given disassembly line (starting from 1).
:param int disassemblyLine: The line of the disassembly to toggle a breakpoint on.
)");
virtual void ToggleBreakpointOnDisassemblyLine(int32_t disassemblyLine) = 0;
DOCUMENT(R"(Runs execution forward to the next breakpoint, or the end of the trace.
)");
virtual void RunForward() = 0;
DOCUMENT(R"(Show a list of shader compilation errors or warnings.
:param str errors: The string of errors or warnings to display.
)");
virtual void ShowErrors(const rdcstr &errors) = 0;
DOCUMENT(R"(Add an expression to the watch panel.
:param str expression: The name of the expression to watch.
)");
virtual void AddWatch(const rdcstr &expression) = 0;
DOCUMENT(R"(Return the current text of source files within the viewer. Primarily useful for
returning any edits applied when editing a shader.
:return: The current file contents as a list of (filename, contents) pairs.
:rtype: List[Tuple[str,str]]
)");
virtual rdcstrpairs GetCurrentFileContents() = 0;
protected:
IShaderViewer() = default;
~IShaderViewer() = default;
};
DECLARE_REFLECTION_STRUCT(IShaderViewer);
DOCUMENT("A shader message list window.");
struct IShaderMessageViewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`ShaderMessageViewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Return the EID that this viewer is displaying messages from.
:return: The EID.
:rtype: int
)");
virtual uint32_t GetEvent() = 0;
DOCUMENT(R"(Return the shader messages displayed in this viewer.
:return: The shader messages.
:rtype: List[renderdoc.ShaderMessage]
)");
virtual rdcarray<ShaderMessage> GetShaderMessages() = 0;
DOCUMENT(R"(Returns whether or not this viewer is out of date - if the shaders have been edited
since the messages were fetched.
:return: ``True`` if the viewer is out of date.
:rtype: bool
)");
virtual bool IsOutOfDate() = 0;
protected:
IShaderMessageViewer() = default;
~IShaderMessageViewer() = default;
};
DECLARE_REFLECTION_STRUCT(IShaderMessageViewer);
DOCUMENT("A constant buffer preview window.");
struct IConstantBufferPreviewer
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`ConstantBufferPreviewer` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
protected:
IConstantBufferPreviewer() = default;
~IConstantBufferPreviewer() = default;
};
DECLARE_REFLECTION_STRUCT(IConstantBufferPreviewer);
DOCUMENT("A pixel history window.");
struct IPixelHistoryView
{
DOCUMENT(R"(Retrieves the PySide2 QWidget for this :class:`PixelHistoryView` if PySide2 is available, or otherwise
returns a unique opaque pointer that can be passed back to any RenderDoc functions expecting a
QWidget.
:return: Return the widget handle, either a PySide2 handle or an opaque handle.
:rtype: QWidget
)");
virtual QWidget *Widget() = 0;
DOCUMENT(R"(Set the history displayed in this window.
:param List[renderdoc.PixelModification] history: A list of pixel events to display.
)");
virtual void SetHistory(const rdcarray<PixelModification> &history) = 0;
protected:
IPixelHistoryView() = default;
~IPixelHistoryView() = default;
};
DECLARE_REFLECTION_STRUCT(IPixelHistoryView);
DOCUMENT("An interface implemented by any object wanting to be notified of capture events.");
struct ICaptureViewer
{
DOCUMENT("Called whenever a capture is opened.");
virtual void OnCaptureLoaded() = 0;
DOCUMENT("Called whenever a capture is closed.");
virtual void OnCaptureClosed() = 0;
DOCUMENT(R"(Called whenever the current selected event changes. This is distinct from the actual
effective current event, since for example selecting a marker region will change the current event
to be the last event inside that region, to be consistent with selecting an item reflecting the
current state after that item.
The selected event shows the :data:`eventId <renderdoc.APIEvent.eventId>` that was actually selected,
which will usually but not always be the same as the current effective
:data:`eventId <renderdoc.APIEvent.eventId>`.
The distinction for this callback is not normally desired, instead use :meth:`OnEventChanged` to
be notified whenever the current event changes. The API inspector uses this to display API events up
to a marker region.
:param int eventId: The new :data:`eventId <renderdoc.APIEvent.eventId>`.
)");
virtual void OnSelectedEventChanged(uint32_t eventId) = 0;
DOCUMENT(R"(Called whenever the effective current event changes.
:param int eventId: The new :data:`eventId <renderdoc.APIEvent.eventId>`.
)");
virtual void OnEventChanged(uint32_t eventId) = 0;
protected:
ICaptureViewer() = default;
virtual ~ICaptureViewer() = default;
};
DECLARE_REFLECTION_STRUCT(ICaptureViewer);
DECLARE_REFLECTION_STRUCT(ICaptureViewer *);
DOCUMENT(R"(A manager for accessing the underlying replay information that isn't already abstracted
in UI side structures. This manager controls and serialises access to the underlying
:class:`~renderdoc.ReplayController`, as well as handling remote server connections.
.. function:: InvokeCallback(controller)
Not a member function - the signature for any ``InvokeCallback`` callbacks.
:param renderdoc.ReplayController controller: The controller to access. Must not be cached or
used after the callback returns.
.. function:: DirectoryBrowseCallback(path, entries)
Not a member function - the signature for any ``DirectoryBrowseCallback`` callbacks.
:param str path: The path that was queried for.
:param List[renderdoc.PathEntry] entries: The entries underneath the path, as relevant.
)");
struct IReplayManager
{
typedef std::function<void(IReplayController *)> InvokeCallback;
typedef std::function<void(const rdcstr &, const rdcarray<PathEntry> &)> DirectoryBrowseCallback;
DOCUMENT(R"(Delete a capture file, whether local or remote.
:param str capturefile: The path to the file.
:param bool local: ``True`` if the file is on the local machine.
)");
virtual void DeleteCapture(const rdcstr &capturefile, bool local) = 0;
DOCUMENT(R"(Connect to a remote server.
:param RemoteHost host: The host to connect to.
:return: Whether or not the connection was successful.
:rtype: renderdoc.ReplayStatus
)");
virtual ReplayStatus ConnectToRemoteServer(RemoteHost host) = 0;
DOCUMENT("Disconnect from the server the manager is currently connected to.");
virtual void DisconnectFromRemoteServer() = 0;
DOCUMENT("Shutdown the server the manager is currently connected to.");
virtual void ShutdownServer() = 0;
DOCUMENT("Ping the remote server to ensure the connection is still alive.");
virtual void PingRemote() = 0;
DOCUMENT("Cancels the active replay loop. See :meth:`~renderdoc.ReplayController.ReplayLoop`.");
virtual void CancelReplayLoop() = 0;
DOCUMENT(R"(Retrieves the host that the manager is currently connected to.
:return: The host connected to, or an invalid RemoteHost if no connection is active.
:rtype: RemoteHost
)");
virtual RemoteHost CurrentRemote() = 0;
DOCUMENT(R"(Retrieves the capture file handle for the currently open file.
:return: The file handle active, or ``None`` if no capture is open.
:rtype: renderdoc.CaptureAccess
)");
virtual ICaptureAccess *GetCaptureAccess() = 0;
DOCUMENT(R"(Launch an application and inject into it to allow capturing.
This happens either locally, or on the remote server, depending on whether a connection is active.
:param str exe: The path to the executable to run.
:param str workingDir: The working directory to use when running the application. If blank, the
directory containing the executable is used.
:param str cmdLine: The command line to use when running the executable, it will be processed in a
platform specific way to generate arguments.
:param List[renderdoc.EnvironmentModification] env: Any environment changes that should be made when
running the program.
:param str capturefile: The location to save any captures, if running locally.
:param renderdoc.CaptureOptions opts: The capture options to use when injecting into the program.
:return: The :class:`~renderdoc.ExecuteResult` indicating both the status of the operation (success
or failure) and any reason for failure, or else the ident where the new application is listening
for target control if everything succeeded.
:rtype: renderdoc.ExecuteResult
)");
virtual ExecuteResult ExecuteAndInject(const rdcstr &exe, const rdcstr &workingDir,
const rdcstr &cmdLine,
const rdcarray<EnvironmentModification> &env,
const rdcstr &capturefile, CaptureOptions opts) = 0;
DOCUMENT(R"(Retrieve a list of drivers that the current remote server supports.
:return: The list of supported replay drivers.
:rtype: List[str]
)");
virtual rdcarray<rdcstr> GetRemoteSupport() = 0;
DOCUMENT(R"(Query the remote host for its home directory.
If a capture is open, the callback will happen on the replay thread, otherwise it will happen in a
blocking fashion on the current thread.
:param bool synchronous: If a capture is open, then ``True`` will use :meth:`BlockInvoke` to call
the callback. Otherwise if ``False`` then :meth:`AsyncInvoke` will be used.
:param DirectoryBrowseCallback callback: The function to callback on the replay thread.
)");
virtual void GetHomeFolder(bool synchronous, DirectoryBrowseCallback callback) = 0;
DOCUMENT(R"(Query the remote host for the contents of a path.
If a capture is open, the callback will happen on the replay thread, otherwise it will happen in a
blocking fashion on the current thread.
:param str path: The path to query the contents of.
:param bool synchronous: If a capture is open, then ``True`` will use :meth:`BlockInvoke` to call
the callback. Otherwise if ``False`` then :meth:`AsyncInvoke` will be used.
:param DirectoryBrowseCallback callback: The function to callback on the replay thread.
)");
virtual void ListFolder(const rdcstr &path, bool synchronous, DirectoryBrowseCallback callback) = 0;
DOCUMENT(R"(Copy a capture from the local machine to the remote host.
:param str localpath: The path on the local machine to copy from.
:param QWidget window: A handle to the window to use when showing a progress bar.
:return: The path on the local machine where the file was saved, or empty if something went wrong.
:rtype: str
)");
virtual rdcstr CopyCaptureToRemote(const rdcstr &localpath, QWidget *window) = 0;
DOCUMENT(R"(Copy a capture from the remote host to the local machine.
:param str remotepath: The path on the remote server to copy from.
:param str localpath: The path on the local machine to copy to.
:param QWidget window: A handle to the window to use when showing a progress bar.
)");
virtual void CopyCaptureFromRemote(const rdcstr &remotepath, const rdcstr &localpath,
QWidget *window) = 0;
DOCUMENT(R"(Return the amount of time that the currently active command on the replay thread has
been executing for.
This can be used to identify if a command is long-running to display a progress bar or notification.
:return: The time in seconds that the current command has been executing for, or 0.0 if no command
is executing.
:rtype: float
)");
virtual float GetCurrentProcessingTime() = 0;
DOCUMENT(R"(Make a tagged non-blocking invoke call onto the replay thread.
This tagged function is for cases when we might send a request - e.g. to pick a vertex or pixel -
and want to pre-empt it with a new request before the first has returned. Either because some
other work is taking a while or because we're sending requests faster than they can be
processed.
The manager processes only the request on the top of the queue, so when a new tagged invoke
comes in, we remove any other requests in the queue before it that have the same tag.
:param str tag: The tag to identify this callback.
:param InvokeCallback method: The function to callback on the replay thread.
)");
virtual void AsyncInvoke(const rdcstr &tag, InvokeCallback method) = 0;
DOCUMENT(R"(Make a non-blocking invoke call onto the replay thread.
:param InvokeCallback method: The function to callback on the replay thread.
)");
virtual void AsyncInvoke(InvokeCallback method) = 0;
// This is an ugly hack, but we leave BlockInvoke as the last method, so that when the class is
// extended and the wrapper around BlockInvoke to release the python GIL happens, it picks up the
// same docstring.
DOCUMENT(R"(Make a blocking invoke call onto the replay thread.
:param InvokeCallback method: The function to callback on the replay thread.
)");
virtual void BlockInvoke(InvokeCallback method) = 0;
protected:
IReplayManager() = default;
~IReplayManager() = default;
};
DECLARE_REFLECTION_STRUCT(IReplayManager);
// should match ToolWindowManager::AreaReferenceType
DOCUMENT(R"(Specifies the relationship between the existing dock window and the new one when adding
a new dock window or moving an existing dock window.
.. data:: LastUsedArea
The existing dock window is not used, the new dock window is placed wherever the last dock window
was placed.
.. data:: NewFloatingArea
The existing dock window is not used, the new dock window is placed in a new floating area.
.. data:: EmptySpace
The existing dock window is not used, the new dock window is placed in empty area in the dockarea.
.. data:: NoArea
The existing dock window is not used, the new window is hidden.
.. data:: AddTo
The new dock window is placed in a tab set with the existing dock window.
.. data:: LeftOf
The new dock window is placed to the left of the existing dock window, at a specified proportion.
.. data:: RightOf
The new dock window is placed to the right of the existing dock window, at a specified proportion.
.. data:: TopOf
The new dock window is placed above the existing dock window, at a specified proportion.
.. data:: BottomOf
The new dock window is placed below the existing dock window, at a specified proportion.
.. data:: LeftWindowSide
The new dock window is placed left of *all* docks in the window, at a specified proportion.
.. data:: RightWindowSide
The new dock window is placed right of *all* docks in the window, at a specified proportion.
.. data:: TopWindowSide
The new dock window is placed above *all* docks in the window, at a specified proportion.
.. data:: BottomWindowSide
The new dock window is placed below *all* docks in the window, at a specified proportion.
.. data:: MainToolArea
The new dock window is placed in the 'main' tool area as defined by finding an existing known
window and using that as the main area. In the default layout this is where most windows are
placed.
.. data:: LeftToolArea
The new dock window is placed in the 'left' tool area as defined by finding an existing known
window and using that as the main area, then adding to the left of that. In the default layout
this is where the event browser is placed.
.. data:: TransientPopupArea
The new dock window is docked with other similar transient views like constant buffer or pixel
history windows, if they exist, or else docked to the right of the main window.
)");
enum class DockReference : int
{
LastUsedArea,
NewFloatingArea,
EmptySpace,
NoArea,
AddTo,
LeftOf,
RightOf,
TopOf,
BottomOf,
LeftWindowSide,
RightWindowSide,
TopWindowSide,
BottomWindowSide,
// extra values here
MainToolArea,
LeftToolArea,
TransientPopupArea,
};
DOCUMENT(R"(Details any changes that have been made to a capture in the UI which can be saved to
disk but currently aren't. Note that detection is conservative - e.g. if a change is made, then
cancelled out by reversing the change, this will still count as 'modified' even if the end result is
the same data. In that sense it's analogous to adding and then deleting some characters in a text
editor, since there is no actual undo system.
This is a bitmask, so several values can be present at once.
.. data:: NoModifications
Fixed value of 0 indicating no modifications have been made.
.. data:: Renames
One or more resources have been given a custom name which hasn't been saved.
.. data:: Bookmarks
Event bookmarks have been added or removed.
.. data:: Notes
The general notes field has been changed.
.. data:: EditedShaders
There are shader editing changes (new edits or reverts).
.. data:: All
Fixed value with all bits set, indication all modifications have been made.
)");
enum class CaptureModifications : uint32_t
{
NoModifications = 0x0000,
Renames = 0x0001,
Bookmarks = 0x0002,
Notes = 0x0004,
EditedShaders = 0x0008,
All = 0xffffffff,
};
BITMASK_OPERATORS(CaptureModifications);
DOCUMENT("A description of a bookmark on an event");
struct EventBookmark
{
DOCUMENT("The :data:`eventId <renderdoc.APIEvent.eventId>` at which this bookmark is placed.");
uint32_t eventId = 0;
DOCUMENT("The text associated with this bookmark - could be empty");
rdcstr text;
DOCUMENT("");
EventBookmark() = default;
EventBookmark(uint32_t e) : eventId(e) {}
bool operator==(const EventBookmark &o) const { return eventId == o.eventId; }
bool operator!=(const EventBookmark &o) const { return eventId != o.eventId; }
bool operator<(const EventBookmark &o) const { return eventId < o.eventId; }
};
DECLARE_REFLECTION_STRUCT(EventBookmark);
DOCUMENT("Controlling interface for interop with RGP tool.");
struct IRGPInterop
{
DOCUMENT(R"(Return true if the given :data:`eventId <renderdoc.APIEvent.eventId>` has and
equivalent in RGP.
:param int eventId: The :data:`eventId <renderdoc.APIEvent.eventId>` to query for.
:return: ``True`` if there is an equivalent. This only confirms the equivalent exists, not that it
will be selectable in all cases.
:rtype: bool
)");
virtual bool HasRGPEvent(uint32_t eventId) = 0;
DOCUMENT(R"(Select the given :data:`eventId <renderdoc.APIEvent.eventId>` equivalent in RGP.
:param int eventId: The :data:`eventId <renderdoc.APIEvent.eventId>` to query for.
:return: ``True`` if the selection request succeeded. This only confirms the request was sent, not
that the event was selected in RGP.
:rtype: bool
)");
virtual bool SelectRGPEvent(uint32_t eventId) = 0;
DOCUMENT("");
virtual ~IRGPInterop() = default;
protected:
IRGPInterop() = default;
};
DECLARE_REFLECTION_STRUCT(IRGPInterop);
DOCUMENT("The capture context that the python script is running in.")
struct ICaptureContext
{
DOCUMENT(R"(Retrieve the absolute path where a given temporary capture should be stored.
data.
:param str appname: The name of the application to use as part of the template.
:return: The absolute path.
:rtype: str
)");
virtual rdcstr TempCaptureFilename(const rdcstr &appname) = 0;
DOCUMENT(R"(Open a capture file for replay.
:param str captureFile: The actual path to the capture file.
:param renderdoc.ReplayOptions opts: The options controlling how the capture should be replayed.
:param str origFilename: The original filename, if the capture was copied remotely for replay.
:param bool temporary: ``True`` if this is a temporary capture which should prompt the user for
either save or delete on close.
:param bool local: ``True`` if ``captureFile`` refers to a file on the local machine.
)");
virtual void LoadCapture(const rdcstr &captureFile, const ReplayOptions &opts,
const rdcstr &origFilename, bool temporary, bool local) = 0;
DOCUMENT(R"(Saves the current capture file to a given path.
If the capture was temporary, this save action means it is no longer temporary and will be treated
like any other capture.
Any modifications to the capture (see :meth:`GetCaptureModifications`) will be applied at the same
time.
:param str captureFile: The path to save the capture file to.
:return: ``True`` if the save operation was successful.
:rtype: bool
)");
virtual bool SaveCaptureTo(const rdcstr &captureFile) = 0;
DOCUMENT("Recompress the current capture as much as possible.");
virtual void RecompressCapture() = 0;
DOCUMENT("Close the currently open capture file.");
virtual void CloseCapture() = 0;
DOCUMENT(R"(Imports a capture file from a non-native format, via conversion to temporary rdc.
This converts the file to a specified temporary .rdc and loads it, closing any existing capture.
The capture must be available locally, if it's not this function will fail.
:param renderdoc.CaptureFileFormat fmt: The capture file format to import from.
:param str importfile: The path to import from.
:param str rdcfile: The temporary path to save the rdc file to.
:return: ``True`` if the import operation was successful and the capture was loaded.
:rtype: bool
)");
virtual bool ImportCapture(const CaptureFileFormat &fmt, const rdcstr &importfile,
const rdcstr &rdcfile) = 0;
DOCUMENT(R"(Exports the current capture file to a given path with a specified capture file format.
The capture must be available locally, if it's not this function will fail.
:param renderdoc.CaptureFileFormat fmt: The capture file format to export to.
:param str exportfile: The path to export the capture file to.
)");
virtual void ExportCapture(const CaptureFileFormat &fmt, const rdcstr &exportfile) = 0;
DOCUMENT(R"(Move the current replay to a new event in the capture.
:param List[CaptureViewer] exclude: A list of viewers to exclude from being notified of this change,
to stop infinite recursion.
:param int selectedEventId: The selected :data:`eventId <renderdoc.APIEvent.eventId>`. See
:meth:`CaptureViewer.OnSelectedEventChanged` for more information.
:param int eventId: The new current :data:`eventId <renderdoc.APIEvent.eventId>`. See
:meth:`CaptureViewer.OnEventChanged` for more information.
:param bool force: Optional parameter, if ``True`` then the replay will 'move' even if it is moving
to the same :data:`eventId <renderdoc.APIEvent.eventId>` as it's currently on.
)");
virtual void SetEventID(const rdcarray<ICaptureViewer *> &exclude, uint32_t selectedEventId,
uint32_t eventId, bool force = false) = 0;
DOCUMENT(R"(Replay the capture to the current event again, to pick up any changes that might have
been made.
)");
virtual void RefreshStatus() = 0;
DOCUMENT(R"(Determine if a resource has been replaced. See :meth:`RegisterReplacement`.
:param renderdoc.ResourceId id: The id of the resource to check.
:return: ``True`` if the resource has been replaced.
:rtype: bool
)");
virtual bool IsResourceReplaced(ResourceId id) = 0;
DOCUMENT(R"(Return the id of a replacement for the given resource. See
:meth:`RegisterReplacement` and :meth:`IsResourceReplaced`.
:param renderdoc.ResourceId id: The id of the resource to check.
:return: The replacement id, or a null id if the resource hasn't been replaced
:rtype: renderdoc.ResourceId
)");
virtual ResourceId GetResourceReplacement(ResourceId id) = 0;
DOCUMENT(R"(Register that a resource has replaced, so that the UI can be updated to reflect the
change.
This should be called at the same time as :meth:`ReplayController.ReplaceResource`.
:param renderdoc.ResourceId from: The id of the resource being replaced.
:param renderdoc.ResourceId to: The id of the resource replacing it.
)");
virtual void RegisterReplacement(ResourceId from, ResourceId to) = 0;
DOCUMENT(R"(Register that a replacement has been removed, so that the UI can be updated to reflect
the change.
This should be called at the same time as :meth:`ReplayController.RemoveReplacement`.
See :meth:`ReplaceResource`.
:param renderdoc.ResourceId id: The id of the original resource that was previously replaced.
)");
virtual void UnregisterReplacement(ResourceId id) = 0;
DOCUMENT(R"(Register a new instance of :class:`CaptureViewer` to receive capture event notifications.
:param CaptureViewer viewer: The viewer to register.
)");
virtual void AddCaptureViewer(ICaptureViewer *viewer) = 0;
DOCUMENT(R"(Unregister an instance of :class:`CaptureViewer` from receiving notifications.
:param CaptureViewer viewer: The viewer to unregister.
)");
virtual void RemoveCaptureViewer(ICaptureViewer *viewer) = 0;
//////////////////////////////////////////////////////////////////////////////
// Accessors
DOCUMENT(R"(Retrieve the replay manager for access to the internal RenderDoc replay controller.
:return: The current replay manager.
:rtype: ReplayManager
)");
virtual IReplayManager &Replay() = 0;
DOCUMENT(R"(Connect to a remote server.
:param RemoteHost host: The host to connect to.
)");
virtual void ConnectToRemoteServer(RemoteHost host) = 0;
DOCUMENT(R"(Check whether or not a capture is currently loaded.
:return: ``True`` if a capture is loaded.
:rtype: bool
)");
virtual bool IsCaptureLoaded() = 0;
DOCUMENT(R"(Check whether or not the current capture is stored locally, or on a remote host.
:return: ``True`` if a capture is local.
:rtype: bool
)");
virtual bool IsCaptureLocal() = 0;
DOCUMENT(R"(Check whether or not the current capture is considered temporary. Captures that were
made by an application and then have not been explicitly saved anywhere are temporary and will be
cleaned up on close (with a final prompt to save). Once they are save to disk, they are no longer
temporary and treated like any other capture.
:return: ``True`` if a capture is temporary.
:rtype: bool
)");
virtual bool IsCaptureTemporary() = 0;
DOCUMENT(R"(Check whether or not a capture is currently loading in-progress.
:return: ``True`` if a capture is currently loading.
:rtype: bool
)");
virtual bool IsCaptureLoading() = 0;
DOCUMENT(R"(If a capture is loaded, return the current fatal error status.
:return: If a capture is currently loaded, return the fatal error status.
:rtype: renderdoc.ReplayStatus
)");
virtual ReplayStatus GetFatalError() = 0;
DOCUMENT(R"(Retrieve the filename for the currently loaded capture.
:return: The filename of the current capture.
:rtype: str
)");
virtual rdcstr GetCaptureFilename() = 0;
DOCUMENT(R"(Get a bitmask indicating which modifications (if any) have been made to the capture in
the UI which aren't reflected in the capture file on disk.
:return: The modifications (if any) that have been made to the capture.
:rtype: CaptureModifications
)");
virtual CaptureModifications GetCaptureModifications() = 0;
DOCUMENT(R"(Retrieve the :class:`~renderdoc.FrameDescription` for the currently loaded capture.
:return: The frame information.
:rtype: renderdoc.FrameDescription
)");
virtual const FrameDescription &FrameInfo() = 0;
DOCUMENT(R"(Retrieve the :class:`~renderdoc.APIProperties` for the currently loaded capture.
:return: The API properties.
:rtype: renderdoc.APIProperties
)");
virtual const APIProperties &APIProps() = 0;
DOCUMENT(R"(Retrieve the list of :class:`~renderdoc.ShaderEncoding` that are available for
building target shaders for the currently loaded capture. See
:meth:`~renderdoc.ReplayController.BuildTargetShader`.
:return: The available encodings.
:rtype: List[renderdoc.ShaderEncoding]
)");
virtual rdcarray<ShaderEncoding> TargetShaderEncodings() = 0;
DOCUMENT(R"(Retrieve the list of :class:`~renderdoc.ShaderEncoding` that are available for
building custom shaders for the currently loaded capture. See
:meth:`~renderdoc.ReplayController.BuildCustomShader`.
:return: The available encodings.
:rtype: List[renderdoc.ShaderEncoding]
)");
virtual rdcarray<ShaderEncoding> CustomShaderEncodings() = 0;
DOCUMENT(R"(Retrieve the currently selected :data:`eventId <renderdoc.APIEvent.eventId>`.
In most cases, prefer using :meth:`CurEvent`. See :meth:`CaptureViewer.OnSelectedEventChanged` for more
information for how this differs.
:return: The current selected event.
:rtype: int
)");
virtual uint32_t CurSelectedEvent() = 0;
DOCUMENT(R"(Retrieve the current :data:`eventId <renderdoc.APIEvent.eventId>`.
:return: The current event.
:rtype: int
)");
virtual uint32_t CurEvent() = 0;
DOCUMENT(R"(Retrieve the currently selected action.
In most cases, prefer using :meth:`CurAction`. See :meth:`CaptureViewer.OnSelectedEventChanged` for
more information for how this differs.
:return: The currently selected action.
:rtype: renderdoc.ActionDescription
)");
virtual const ActionDescription *CurSelectedAction() = 0;
DOCUMENT(R"(Retrieve the current action.
:return: The current action, or ``None`` if no action is selected.
:rtype: renderdoc.ActionDescription
)");
virtual const ActionDescription *CurAction() = 0;
DOCUMENT(R"(Retrieve the first action in the capture.
:return: The first action.
:rtype: renderdoc.ActionDescription
)");
virtual const ActionDescription *GetFirstAction() = 0;
DOCUMENT(R"(Retrieve the last action in the capture.
:return: The last action.
:rtype: renderdoc.ActionDescription
)");
virtual const ActionDescription *GetLastAction() = 0;
DOCUMENT(R"(Retrieve the root list of actions in the current capture.
:return: The root actions.
:rtype: List[renderdoc.ActionDescription]
)");
virtual const rdcarray<ActionDescription> &CurRootActions() = 0;
DOCUMENT(R"(Retrieve the information about a particular resource.
:param renderdoc.ResourceId id: The ID of the resource to query about.
:return: The information about a resource, or ``None`` if the ID does not correspond to a resource.
:rtype: renderdoc.ResourceDescription
)");
virtual ResourceDescription *GetResource(ResourceId id) = 0;
DOCUMENT(R"(Retrieve the list of resources in the current capture.
:return: The list of resources.
:rtype: List[renderdoc.ResourceDescription]
)");
virtual const rdcarray<ResourceDescription> &GetResources() = 0;
DOCUMENT(R"(Retrieve the human-readable name for the resource to display.
This will first check to see if a custom name has been set for the resource, and if so use that. See
:meth:`SetResourceCustomName`. If no custom name has been set, it will use the resource name found
in the capture, either a name set via API-specific debug methods, or an auto-generated name based on
the resource type.
:param renderdoc.ResourceId id: The ID of the resource to query.
:return: The current name of the resource.
:rtype: str
)");
virtual rdcstr GetResourceName(ResourceId id) = 0;
DOCUMENT(R"(Returns the same name as :meth:`GetResourceName` but without any added suffix, e.g. to
indicate the resource's status such as (Edited).
:param renderdoc.ResourceId id: The ID of the resource to query.
:return: The unsuffixed resource name.
:rtype: str
)");
virtual rdcstr GetResourceNameUnsuffixed(ResourceId id) = 0;
DOCUMENT(R"(Determines whether the name for the given resource has been customised at all, either
during capture time or with :meth:`SetResourceCustomName`.
If not, the name is just auto-generated based on the ID and resource type, so depending on
circumstance it may be preferable to omit the name.
:param renderdoc.ResourceId id: The ID of the resource to query.
:return: Whether the name for the resource has just been auto-generated.
:rtype: bool
)");
virtual bool IsAutogeneratedName(ResourceId id) = 0;
DOCUMENT(R"(Checks whether a runtime custom name has been set with :meth:`SetResourceCustomName`.
In general, :meth:`IsAutogeneratedName` should be preferred to check if the resource name is default
generated just from the ID, or if it has been set to some human readable name. This function will
only check if a name has been set in the UI itself, a resource could still have a custom name that
was set programmatically during capture time.
:param renderdoc.ResourceId id: The ID of the resource to query.
:return: Whether the name for the resource has been customised with :meth:`SetResourceCustomName`.
:rtype: bool
)");
virtual bool HasResourceCustomName(ResourceId id) = 0;
DOCUMENT(R"(Set a custom name for a resource.
This allows an override to the name returned by :meth:`GetResourceName`, most useful when there are
no pre-existing debug names specified in the capture.
To remove a custom name that has been set previously, specify the empty string as the name. Then the
custom name will be removed, and instead :meth:`GetResourceName` will fall back to returning any
name fetched from the capture.
:param renderdoc.ResourceId id: The ID of the resource to name.
:param str name: The name to provide, or an empty string to remove any previous custom name.
)");
virtual void SetResourceCustomName(ResourceId id, const rdcstr &name) = 0;
DOCUMENT(R"(Returns an index that can be used to cache the results of resource naming.
In some cases (e.g. formatting in widgets) there might be high frequency fetches to names without an
easy way to force a refresh on a rename. Instead, the index here can be cached and compared each
time to see if any names have changed.
The index starts at 1, so initialising an internal cache to 0 will cause the first check to be
considered out of date
:return: An incrementing index that can be used as a quick check if any names have changed.
:rtype: int
)");
virtual int32_t ResourceNameCacheID() = 0;
DOCUMENT(R"(Retrieve the information about a particular texture.
:param renderdoc.ResourceId id: The ID of the texture to query about.
:return: The information about a texture, or ``None`` if the ID does not correspond to a texture.
:rtype: renderdoc.TextureDescription
)");
virtual TextureDescription *GetTexture(ResourceId id) = 0;
DOCUMENT(R"(Retrieve the list of textures in the current capture.
:return: The list of textures.
:rtype: List[renderdoc.TextureDescription]
)");
virtual const rdcarray<TextureDescription> &GetTextures() = 0;
DOCUMENT(R"(Retrieve the information about a particular buffer.
:param renderdoc.ResourceId id: The ID of the buffer to query about.
:return: The information about a buffer, or ``None`` if the ID does not correspond to a buffer.
:rtype: renderdoc.BufferDescription
)");
virtual BufferDescription *GetBuffer(ResourceId id) = 0;
DOCUMENT(R"(Retrieve the list of buffers in the current capture.
:return: The list of buffers.
:rtype: List[renderdoc.BufferDescription]
)");
virtual const rdcarray<BufferDescription> &GetBuffers() = 0;
DOCUMENT(R"(Retrieve the information about an action at a given
:data:`eventId <renderdoc.APIEvent.eventId>`.
:param int eventId: The :data:`eventId <renderdoc.APIEvent.eventId>` to query for.
:return: The information about the action, or ``None`` if the
:data:`eventId <renderdoc.APIEvent.eventId>` doesn't correspond to an action.
:rtype: renderdoc.ActionDescription
)");
virtual const ActionDescription *GetAction(uint32_t eventId) = 0;
DOCUMENT(R"(Sets the path to the RGP profile to use with :meth:`GetRGPInterop`, launches RGP and
opens an interop connection. This function will block (with a progress dialog) until either an
error is encountered or else the connection is successfully established.
This could be newly created, or extracted from an embedded section in the RDC.
The connection is automatically closed when the capture is closed. If OpenRGPProfile is called
again, any previous connection will be closed.
:param str filename: The filename of the extracted temporary RGP capture on disk.
:return: Whether RGP launched successfully.
:rtype: bool
)");
virtual bool OpenRGPProfile(const rdcstr &filename) = 0;
DOCUMENT(R"(Returns the current interop handle for RGP.
This may return ``None`` in several cases:
- if there is no capture loaded
- if no RGP profile has been associated with the current capture yet (See :meth:`OpenRGPProfile`)
- if RGP failed to launch or connect.
The handle returned is invalidated when the capture is closed, or if :meth:`OpenRGPProfile` is
called.
:return: The RGP interop connection handle.
:rtype: RGPInterop
)");
virtual IRGPInterop *GetRGPInterop() = 0;
DOCUMENT(R"(Retrieve the :class:`~renderdoc.SDFile` for the currently open capture.
:return: The structured file.
:rtype: renderdoc.SDFile
)");
virtual const SDFile &GetStructuredFile() = 0;
DOCUMENT(R"(Retrieve the current windowing system in use.
:return: The active windowing system.
:rtype: renderdoc.WindowingSystem
)");
virtual WindowingSystem CurWindowingSystem() = 0;
DOCUMENT(R"(Create an opaque pointer suitable for passing to
:meth:`~renderdoc.ReplayController.CreateOutput` or other functions that expect windowing data.
.. note::
This function must be called on the main UI thread.
:param QWidget window: The window to create windowing data for.
:return: The windowing data.
:rtype: renderdoc.WindowingData
)");
virtual WindowingData CreateWindowingData(QWidget *window) = 0;
DOCUMENT(R"(Retrieve the current list of debug messages. This includes messages from the capture
as well as messages generated during replay and analysis.
:return: The debug messages generated to date.
:rtype: List[renderdoc.DebugMessage]
)");
virtual const rdcarray<DebugMessage> &DebugMessages() = 0;
DOCUMENT(R"(Retrieve how many messages in :meth:`DebugMessages` are currently unread.
:return: The number of unread messages.
:rtype: int
)");
virtual int32_t UnreadMessageCount() = 0;
DOCUMENT("Mark all messages as read, resets :meth:`UnreadMessageCount` to 0.");
virtual void MarkMessagesRead() = 0;
DOCUMENT(R"(Add messages into the list returned by :meth:`DebugMessages`. Initially set to unread.
:param List[renderdoc.DebugMessage] msgs: A list of debug messages to add.
)");
virtual void AddMessages(const rdcarray<DebugMessage> &msgs) = 0;
DOCUMENT(R"(Retrieve the contents for a given notes field.
Examples of fields are:
* 'comments' for generic comments to be displayed in a text field
* 'hwinfo' for a plaintext summary of the hardware and driver configuration of the system.
:param str key: The name of the notes field to retrieve.
:return: The contents, or an empty string if the field doesn't exist.
:rtype: str
)");
virtual rdcstr GetNotes(const rdcstr &key) = 0;
DOCUMENT(R"(Set the contents for a given notes field.
See :meth:`GetNotes` for a list of possible common field keys.
:param str key: The name of the notes field to set.
:param str contents: The new contents to assign to that field.
)");
virtual void SetNotes(const rdcstr &key, const rdcstr &contents) = 0;
DOCUMENT(R"(Get the current list of bookmarks in the capture. Each bookmark is associated with an
eventId and has some text attached. There will only be at most one bookmark for any given eventId.
The list of bookmarks is not necessarily sorted by eventId. Thus, bookmark 1 is always bookmark 1
until it is removed, the indices do not shift as new bookmarks are added or removed.
:return: The currently set bookmarks.
:rtype: List[EventBookmark]
)");
virtual rdcarray<EventBookmark> GetBookmarks() = 0;
DOCUMENT(R"(Set or update a bookmark.
A bookmark will be added at the specified eventId, or if one already exists then the attached text
will be replaced.
:param EventBookmark mark: The bookmark to add.
)");
virtual void SetBookmark(const EventBookmark &mark) = 0;
DOCUMENT(R"(Remove a bookmark at a given eventId.
If no bookmark exists, this function will do nothing.
:param int eventId: The eventId of the bookmark to remove.
)");
virtual void RemoveBookmark(uint32_t eventId) = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`MainWindow`.
:return: The current window.
:rtype: MainWindow
)");
virtual IMainWindow *GetMainWindow() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`EventBrowser`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: EventBrowser
)");
virtual IEventBrowser *GetEventBrowser() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`APIInspector`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: APIInspector
)");
virtual IAPIInspector *GetAPIInspector() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`TextureViewer`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: TextureViewer
)");
virtual ITextureViewer *GetTextureViewer() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`BufferViewer` configured for mesh viewing.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: BufferViewer
)");
virtual IBufferViewer *GetMeshPreview() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`PipelineStateViewer`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: PipelineStateViewer
)");
virtual IPipelineStateViewer *GetPipelineViewer() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`CaptureDialog`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: CaptureDialog
)");
virtual ICaptureDialog *GetCaptureDialog() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`DebugMessageView`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: DebugMessageView
)");
virtual IDebugMessageView *GetDebugMessageView() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`LogView`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: DiagnosticLogView
)");
virtual IDiagnosticLogView *GetDiagnosticLogView() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`CommentView`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: CommentView
)");
virtual ICommentView *GetCommentView() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`PerformanceCounterViewer`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: PerformanceCounterViewer
)");
virtual IPerformanceCounterViewer *GetPerformanceCounterViewer() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`StatisticsViewer`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: StatisticsViewer
)");
virtual IStatisticsViewer *GetStatisticsViewer() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`TimelineBar`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: TimelineBar
)");
virtual ITimelineBar *GetTimelineBar() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`PythonShell`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: PythonShell
)");
virtual IPythonShell *GetPythonShell() = 0;
DOCUMENT(R"(Retrieve the current singleton :class:`ResourceInspector`.
:return: The current window, which is created (but not shown) it there wasn't one open.
:rtype: ResourceInspector
)");
virtual IResourceInspector *GetResourceInspector() = 0;
DOCUMENT(R"(Check if there is a current :class:`EventBrowser` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasEventBrowser() = 0;
DOCUMENT(R"(Check if there is a current :class:`APIInspector` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasAPIInspector() = 0;
DOCUMENT(R"(Check if there is a current :class:`TextureViewer` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasTextureViewer() = 0;
DOCUMENT(R"(Check if there is a current :class:`PipelineStateViewer` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasPipelineViewer() = 0;
DOCUMENT(R"(Check if there is a current mesh previewing :class:`BufferViewer` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasMeshPreview() = 0;
DOCUMENT(R"(Check if there is a current :class:`CaptureDialog` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasCaptureDialog() = 0;
DOCUMENT(R"(Check if there is a current :class:`DebugMessageView` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasDebugMessageView() = 0;
DOCUMENT(R"(Check if there is a current :class:`DiagnosticLogView` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasDiagnosticLogView() = 0;
DOCUMENT(R"(Check if there is a current :class:`CommentView` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasCommentView() = 0;
DOCUMENT(R"(Check if there is a current :class:`PerformanceCounterViewer` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasPerformanceCounterViewer() = 0;
DOCUMENT(R"(Check if there is a current :class:`StatisticsViewer` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasStatisticsViewer() = 0;
DOCUMENT(R"(Check if there is a current :class:`TimelineBar` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasTimelineBar() = 0;
DOCUMENT(R"(Check if there is a current :class:`PythonShell` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasPythonShell() = 0;
DOCUMENT(R"(Check if there is a current :class:`ResourceInspector` open.
:return: ``True`` if there is a window open.
:rtype: bool
)");
virtual bool HasResourceInspector() = 0;
DOCUMENT("Raise the current :class:`EventBrowser`, showing it in the default place if needed.");
virtual void ShowEventBrowser() = 0;
DOCUMENT("Raise the current :class:`APIInspector`, showing it in the default place if needed.");
virtual void ShowAPIInspector() = 0;
DOCUMENT("Raise the current :class:`TextureViewer`, showing it in the default place if needed.");
virtual void ShowTextureViewer() = 0;
DOCUMENT(R"(Raise the current mesh previewing :class:`BufferViewer`, showing it in the default
place if needed.
)");
virtual void ShowMeshPreview() = 0;
DOCUMENT(
"Raise the current :class:`PipelineStateViewer`, showing it in the default place if needed.");
virtual void ShowPipelineViewer() = 0;
DOCUMENT("Raise the current :class:`CaptureDialog`, showing it in the default place if needed.");
virtual void ShowCaptureDialog() = 0;
DOCUMENT(
"Raise the current :class:`DebugMessageView`, showing it in the default place if needed.");
virtual void ShowDebugMessageView() = 0;
DOCUMENT(
"Raise the current :class:`DiagnosticLogView`, showing it in the default place if needed.");
virtual void ShowDiagnosticLogView() = 0;
DOCUMENT("Raise the current :class:`CommentView`, showing it in the default place if needed.");
virtual void ShowCommentView() = 0;
DOCUMENT(
"Raise the current :class:`PerformanceCounterViewer`, showing it in the default place if "
"needed.");
virtual void ShowPerformanceCounterViewer() = 0;
DOCUMENT(
"Raise the current :class:`StatisticsViewer`, showing it in the default place if needed.");
virtual void ShowStatisticsViewer() = 0;
DOCUMENT("Raise the current :class:`TimelineBar`, showing it in the default place if needed.");
virtual void ShowTimelineBar() = 0;
DOCUMENT("Raise the current :class:`PythonShell`, showing it in the default place if needed.");
virtual void ShowPythonShell() = 0;
DOCUMENT(
"Raise the current :class:`ResourceInspector`, showing it in the default place if needed.");
virtual void ShowResourceInspector() = 0;
DOCUMENT(R"(Show a new :class:`ShaderViewer` window, showing an editable view of a given shader.
:param renderdoc.ResourceId id: The shader object, if applicable, that's being edited. If this edit
corresponds to no shader object (such as if it's a custom shader) this can be a null ID.
:param renderdoc.ShaderStage stage: The shader stage for this shader.
:param str entryPoint: The entry point to be used when compiling the edited shader.
:param List[Tuple[str,str]] files: The source files, with each tuple being a pair of the filename
and the file contents.
:param renderdoc.ShaderEncoding shaderEncoding: The encoding of the input files.
:param renderdoc.ShaderCompileFlags flags: The flags originally used to compile the shader.
:param ShaderViewer.SaveCallback saveCallback: The callback function to call when a save/update is
triggered.
:param ShaderViewer.CloseCallback closeCallback: The callback function to call when the shader
viewer is closed.
:return: The new :class:`ShaderViewer` window opened but not shown for editing.
:rtype: ShaderViewer
)");
virtual IShaderViewer *EditShader(ResourceId id, ShaderStage stage, const rdcstr &entryPoint,
const rdcstrpairs &files, ShaderEncoding shaderEncoding,
ShaderCompileFlags flags,
IShaderViewer::SaveCallback saveCallback,
IShaderViewer::CloseCallback closeCallback) = 0;
DOCUMENT(R"(Show a new :class:`ShaderViewer` window, showing a read-only view of a debug trace
through the execution of a given shader.
:param renderdoc.ShaderBindpointMapping bind: The bindpoint mapping for the shader to view.
:param renderdoc.ShaderReflection shader: The reflection data for the shader to view.
:param renderdoc.ResourceId pipeline: The pipeline state object, if applicable, that this shader is
bound to.
:param renderdoc.ShaderDebugTrace trace: The execution trace of the debugged shader.
:param str debugContext: A human-readable context string describing which invocation of this shader
was debugged. For example 'Pixel 12,34 at eventId 678'.
:return: The new :class:`ShaderViewer` window opened, but not shown.
:rtype: ShaderViewer
)");
virtual IShaderViewer *DebugShader(const ShaderBindpointMapping *bind,
const ShaderReflection *shader, ResourceId pipeline,
ShaderDebugTrace *trace, const rdcstr &debugContext) = 0;
DOCUMENT(R"(Show a new :class:`ShaderViewer` window, showing a read-only view of a given shader.
:param renderdoc.ShaderReflection shader: The reflection data for the shader to view.
:param renderdoc.ResourceId pipeline: The pipeline state object, if applicable, that this shader is
bound to.
:return: The new :class:`ShaderViewer` window opened, but not shown.
:rtype: ShaderViewer
)");
virtual IShaderViewer *ViewShader(const ShaderReflection *shader, ResourceId pipeline) = 0;
DOCUMENT(R"(Show a new :class:`ShaderMessageViewer` window, showing the current event's messages.
:param renderdoc.ShaderStageMask stages: The initial stages being viewed.
:return: The new :class:`ShaderMessageViewer` window opened, but not shown.
:rtype: ShaderMessageViewer
)");
virtual IShaderMessageViewer *ViewShaderMessages(ShaderStageMask stages) = 0;
DOCUMENT(R"(Show a new :class:`BufferViewer` window, showing a read-only view of buffer data.
:param int byteOffset: The offset in bytes to the start of the buffer data to show.
:param int byteSize: The number of bytes in the buffer to show.
:param renderdoc.ResourceId id: The ID of the buffer to fetch data from.
:param str format: Optionally a HLSL/GLSL style formatting string.
:return: The new :class:`BufferViewer` window opened, but not shown.
:rtype: BufferViewer
)");
virtual IBufferViewer *ViewBuffer(uint64_t byteOffset, uint64_t byteSize, ResourceId id,
const rdcstr &format = "") = 0;
DOCUMENT(R"(Show a new :class:`BufferViewer` window, showing a read-only view of a texture's raw
bytes.
:param renderdoc.ResourceId id: The ID of the texture itself.
:param renderdoc.Subresource sub: The subresource within this texture to use.
:param str format: Optionally a HLSL/GLSL style formatting string.
:return: The new :class:`BufferViewer` window opened, but not shown.
:rtype: BufferViewer
)");
virtual IBufferViewer *ViewTextureAsBuffer(ResourceId id, const Subresource &sub,
const rdcstr &format = "") = 0;
DOCUMENT(R"(Show a new :class:`ConstantBufferPreviewer` window, showing a read-only view of a the
variables in a constant buffer with their values.
:param renderdoc.ShaderStage stage: The stage that the constant buffer is bound to.
:param int slot: The index in the shader's constant buffer list to look up.
:param int idx: For APIs that support arrayed resource binds, the index in the constant buffer
array.
:return: The new :class:`ConstantBufferPreviewer` window opened, but not shown.
:rtype: ConstantBufferPreviewer
)");
virtual IConstantBufferPreviewer *ViewConstantBuffer(ShaderStage stage, uint32_t slot,
uint32_t idx) = 0;
DOCUMENT(R"(Show a new :class:`PixelHistoryView` window, showing the results from a pixel history
operation.
:param renderdoc.ResourceId id: The ID of the texture to show the history of.
:param int x: The x co-ordinate of the pixel to search for.
:param int y: The y co-ordinate of the pixel to search for.
:param renderdoc.TextureDisplay display: The texture display configuration to use when looking up
the history.
:return: The new :class:`PixelHistoryView` window opened, but not shown.
:rtype: PixelHistoryView
)");
virtual IPixelHistoryView *ViewPixelHistory(ResourceId id, uint32_t x, uint32_t y,
const TextureDisplay &display) = 0;
DOCUMENT(R"(Creates and returns a built-in window.
This function is intended for internal use for restoring layouts, and generally should not be used
by user code.
:param str objectName: The built-in name of a singleton window.
:return: The handle to the existing or newly created window of this type.
:rtype: QWidget
)");
virtual QWidget *CreateBuiltinWindow(const rdcstr &objectName) = 0;
DOCUMENT(R"(Marks a built-in window as closed.
This function is intended for internal use by the built-in windows for singleton management, and
should not be called by user code.
:param QWidget window: The built-in window that closed.
)");
virtual void BuiltinWindowClosed(QWidget *window) = 0;
DOCUMENT(R"(Raises a window within its docking manager so it becomes the focus of wherever it is
currently docked.
:param QWidget dockWindow: The window to raise.
)");
virtual void RaiseDockWindow(QWidget *dockWindow) = 0;
DOCUMENT(R"(Adds a new window within the docking system.
:param QWidget newWindow: The new window to add.
:param DockReference ref: The location to add the new window, possibly relative to ``refWindow``.
:param QWidget refWindow: The window to refer to if the new window is being added relative, or can
be ``None`` if the new location is absolute.
:param float percentage: Optionally the percentage to split the area. If omitted, a 50% split is
used.
)");
virtual void AddDockWindow(QWidget *newWindow, DockReference ref, QWidget *refWindow,
float percentage = 0.5f) = 0;
DOCUMENT(R"(Retrieve the current :class:`~renderdoc.D3D11State` pipeline state.
The return value will be ``None`` if the capture is not using the D3D11 API.
You should determine the API of the capture first before fetching it.
:return: The current D3D11 pipeline state.
:rtype: renderdoc.D3D11State
)");
virtual const D3D11Pipe::State *CurD3D11PipelineState() = 0;
DOCUMENT(R"(Retrieve the current :class:`~renderdoc.D3D12State` pipeline state.
The return value will be ``None`` if the capture is not using the D3D12 API.
You should determine the API of the capture first before fetching it.
:return: The current D3D12 pipeline state.
:rtype: renderdoc.D3D12State
)");
virtual const D3D12Pipe::State *CurD3D12PipelineState() = 0;
DOCUMENT(R"(Retrieve the current :class:`~renderdoc.GLState` pipeline state.
The return value will be ``None`` if the capture is not using the OpenGL API.
You should determine the API of the capture first before fetching it.
:return: The current OpenGL pipeline state.
:rtype: renderdoc.GLState
)");
virtual const GLPipe::State *CurGLPipelineState() = 0;
DOCUMENT(R"(Retrieve the current :class:`~renderdoc.VKState` pipeline state.
The return value will be ``None`` if the capture is not using the Vulkan API.
You should determine the API of the capture first before fetching it.
:return: The current Vulkan pipeline state.
:rtype: renderdoc.VKState
)");
virtual const VKPipe::State *CurVulkanPipelineState() = 0;
DOCUMENT(R"(Retrieve the current :class:`~renderdoc.PipeState` abstracted pipeline state.
This pipeline state will always be valid, and allows queries that will work regardless of the
capture's API.
:return: The current API-agnostic abstracted pipeline state.
:rtype: renderdoc.PipeState
)");
virtual const PipeState &CurPipelineState() = 0;
DOCUMENT(R"(Retrieve the current persistant config.
:return: The current persistant config manager.
:rtype: PersistantConfig
)");
virtual PersistantConfig &Config() = 0;
DOCUMENT(R"(Retrieve the manager for extensions.
:return: The current extension manager.
:rtype: ExtensionManager
)");
virtual IExtensionManager &Extensions() = 0;
protected:
ICaptureContext() = default;
~ICaptureContext() = default;
};
DECLARE_REFLECTION_STRUCT(ICaptureContext);
DOCUMENT(R"(Retrieve the absolute path where a given file can be stored with other application
data.
:param str filename: The base filename.
:return: The absolute path.
:rtype: str
)");
rdcstr ConfigFilePath(const rdcstr &filename);
// simple helper for the common case of 'we just need to run this on the replay thread'
#define INVOKE_MEMFN(function) \
m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) { function(r); });
| 36.520518 | 124 | 0.752298 | [
"mesh",
"geometry",
"object",
"transform"
] |
9acc7c0cf4193939ebcec473497ee97291689db5 | 2,987 | h | C | content/browser/media/media_power_experiment_manager.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | content/browser/media/media_power_experiment_manager.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | content/browser/media/media_power_experiment_manager.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_MEDIA_MEDIA_POWER_EXPERIMENT_MANAGER_H_
#define CONTENT_BROWSER_MEDIA_MEDIA_POWER_EXPERIMENT_MANAGER_H_
#include <map>
#include <set>
#include <vector>
#include "base/callback.h"
#include "base/memory/scoped_refptr.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
#include "content/common/content_export.h"
#include "content/public/browser/media_player_id.h"
#include "media/base/video_codecs.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace content {
// Keeps track of all media players across all pages, and notifies them when
// they enter or leave an active experiment.
class CONTENT_EXPORT MediaPowerExperimentManager {
public:
// Callback to notify the client when an experiment starts / stops.
using ExperimentCB = base::RepeatingCallback<void(bool)>;
// Flags for handling notifications of stopped players.
enum class NotificationMode {
// If the stopped player is the current experiment, then notify it that it
// no longer is.
kNotify,
// If the stopped player is the current experiment, then skip notification.
// This is useful if the player is being destroyed.
kSkip
};
MediaPowerExperimentManager();
MediaPowerExperimentManager(const MediaPowerExperimentManager&) = delete;
MediaPowerExperimentManager& operator=(const MediaPowerExperimentManager&) =
delete;
virtual ~MediaPowerExperimentManager();
// May return nullptr if experiments aren't enabled.
static MediaPowerExperimentManager* Instance();
// Called when the given player begins playing. |cb| will be called if it
// becomes / stops being the only playing player, though never re-entrantly.
virtual void PlayerStarted(const MediaPlayerId& player, ExperimentCB cb);
// Called when the given player has stopped playing. It is okay if it was
// never started via PlayerStarted; we'll just ignore it. If
// |notification_mode| is kSkip, then we won't notify |player| that it's
// stopping, if it's the current experiment.
virtual void PlayerStopped(
const MediaPlayerId& player,
NotificationMode notification_mode = NotificationMode::kNotify);
private:
// Send start / stop notifications and update |current_experiment_player_|
// based on whether an experiment should be running.
void CheckExperimentState();
// Set of all playing players that we know about.
std::map<MediaPlayerId, ExperimentCB> players_;
// If set, this is the player that has a running experiment.
absl::optional<MediaPlayerId> current_experiment_player_;
ExperimentCB current_experiment_cb_;
scoped_refptr<base::SequencedTaskRunner> task_runner_;
SEQUENCE_CHECKER(sequence_checker_);
};
} // namespace content
#endif // CONTENT_BROWSER_MEDIA_MEDIA_POWER_EXPERIMENT_MANAGER_H_
| 35.987952 | 79 | 0.770673 | [
"vector"
] |
9acc988a65c09317c5c776fbee208c6d7cf607c3 | 8,422 | c | C | linux-imx6/drivers/misc/ftp628mcl.c | ub-rms/rushmore | 9e6c06e94420349f94fa9c1529e1817efd547c7d | [
"BSD-2-Clause"
] | 1 | 2022-02-21T07:09:11.000Z | 2022-02-21T07:09:11.000Z | linux-imx6/drivers/misc/ftp628mcl.c | ub-rms/rushmore | 9e6c06e94420349f94fa9c1529e1817efd547c7d | [
"BSD-2-Clause"
] | null | null | null | linux-imx6/drivers/misc/ftp628mcl.c | ub-rms/rushmore | 9e6c06e94420349f94fa9c1529e1817efd547c7d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2017 Boundary Devices, Inc.
*
* Driver for the Fujitsu FTP-628 MCL printer
*
* Inspired from TI PRU sample code (TIDEP0056)
*
* Licensed under the GPL-2 or later.
*/
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/uaccess.h>
#define DEV_NAME "ftp628"
#define DOTS_PER_LINE 384
#define BYTES_PER_LINE (DOTS_PER_LINE / 8)
#define MOTOR_A1 (1 << 0)
#define MOTOR_An1 (3 << 0)
#define MOTOR_B1 (1 << 2)
#define MOTOR_Bn1 (3 << 2)
const uint32_t mt_phases[] = {
MOTOR_Bn1,
MOTOR_Bn1 | MOTOR_An1,
MOTOR_An1,
MOTOR_An1 | MOTOR_B1,
MOTOR_B1,
MOTOR_B1 | MOTOR_A1,
MOTOR_A1,
MOTOR_A1 | MOTOR_Bn1
};
static struct ftp628_data {
struct spi_device *spi;
struct gpio_desc *latch_gpio;
struct gpio_desc *mt_ab_gpios[4];
struct gpio_desc *mt_ate_gpio;
struct gpio_desc *mt_dcay_gpios[2];
struct gpio_desc *mt_fault_gpio;
struct gpio_desc *mt_sleep_gpio;
struct gpio_desc *mt_toff_gpio;
struct gpio_desc *mt_trq_gpios[2];
struct gpio_desc *paper_out_gpio;
struct gpio_desc *strobe_gpios[6];
int mt_phase;
} ftp628_data;
static void ftp628_suspend_motors(struct ftp628_data *pdata, int suspend)
{
gpiod_direction_output(pdata->mt_sleep_gpio, !!suspend);
mdelay(1);
}
static void ftp628_init_motors(struct ftp628_data *pdata)
{
int i;
pdata->mt_phase = 0;
ftp628_suspend_motors(pdata, 1);
for (i = 0; i < ARRAY_SIZE(pdata->mt_ab_gpios); i++)
gpiod_direction_output(pdata->mt_ab_gpios[i], 0);
gpiod_direction_output(pdata->mt_ate_gpio, 1);
for (i = 0; i < ARRAY_SIZE(pdata->mt_dcay_gpios); i++)
gpiod_direction_output(pdata->mt_dcay_gpios[i], 0);
gpiod_direction_input(pdata->mt_fault_gpio);
gpiod_direction_output(pdata->mt_toff_gpio, 0);
for (i = 0; i < ARRAY_SIZE(pdata->mt_trq_gpios); i++)
gpiod_direction_output(pdata->mt_trq_gpios[i], 0);
}
static void ftp628_init_printer(struct ftp628_data *pdata)
{
int i;
gpiod_direction_output(pdata->latch_gpio, 1);
gpiod_direction_input(pdata->paper_out_gpio);
for (i = 0; i < ARRAY_SIZE(pdata->strobe_gpios); i++)
gpiod_direction_output(pdata->strobe_gpios[i], 0);
}
static void ftp628_motor_next_phase(struct ftp628_data *pdata)
{
struct device *dev = &pdata->spi->dev;
int i;
dev_dbg(dev, "%s (%d/%d): %x\n", __func__, pdata->mt_phase + 1,
ARRAY_SIZE(mt_phases), mt_phases[pdata->mt_phase]);
/* Not sure which delay should be used */
mdelay(2);
for (i = 0; i < ARRAY_SIZE(pdata->mt_ab_gpios); i++) {
if (mt_phases[pdata->mt_phase] & (1 << i))
gpiod_set_value(pdata->mt_ab_gpios[i], 1);
else
gpiod_set_value(pdata->mt_ab_gpios[i], 0);
}
pdata->mt_phase = (pdata->mt_phase + 1) %
ARRAY_SIZE(mt_phases);
}
static void ftp628_motor_next_line(struct ftp628_data *pdata)
{
ftp628_motor_next_phase(pdata);
}
static void ftp628_toggle_gpio(struct gpio_desc *gpio, int state, int delay_us)
{
udelay(1);
gpiod_set_value(gpio, state);
if (delay_us >= 1000)
mdelay(delay_us/1000);
else
udelay(delay_us);
gpiod_set_value(gpio, !state);
udelay(1);
}
static ssize_t ftp628_write(struct file *file, const char __user *data,
size_t count, loff_t *off)
{
uint8_t buffer[BYTES_PER_LINE];
struct ftp628_data *pdata = &ftp628_data;
struct device *dev = &pdata->spi->dev;
int ret;
int i;
loff_t file_off = 0;
size_t size = simple_write_to_buffer(&buffer, sizeof(buffer),
&file_off, data, count);
dev_dbg(dev, "%s count %d (size %d)\n", __func__, count, size);
/* Only accept one line of data or advance paper only */
if ((count != BYTES_PER_LINE) && (count != 1))
return -EINVAL;
/* Handle carriage return command */
if (size == 1) {
if (buffer[0] == '\r') {
ftp628_motor_next_line(pdata);
} else if (buffer[0] == 'B') {
ftp628_suspend_motors(pdata, 0);
} else {
ftp628_suspend_motors(pdata, 1); /* 'E' */
}
return size;
}
/* Send dots to shift registers */
ret = spi_write(pdata->spi, buffer, sizeof(buffer));
if (ret < 0)
return -EIO;
/* Toggle the latch signal (hold 1us) */
ftp628_toggle_gpio(pdata->latch_gpio, 0, 1);
/* Toggle all the strobe signals (hold 2ms) */
for (i = 0; i < ARRAY_SIZE(pdata->strobe_gpios); i++)
ftp628_toggle_gpio(pdata->strobe_gpios[i], 1, 2000);
return size;
}
static const struct file_operations ftp628_fops = {
.owner = THIS_MODULE,
.write = ftp628_write,
};
static struct miscdevice ftp628_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEV_NAME,
.fops = &ftp628_fops,
};
#ifdef CONFIG_OF
static const struct of_device_id ftp628_dt_ids[] = {
{ .compatible = "fujitsu,ftp628" },
{ }
};
MODULE_DEVICE_TABLE(of, ftp628_dt_ids);
static int ftp628_probe_dt(struct device *dev, struct ftp628_data *pdata)
{
struct device_node *node = dev->of_node;
const struct of_device_id *match;
int i;
if (!node) {
dev_err(dev, "Device does not have associated DT data\n");
return -EINVAL;
}
match = of_match_device(ftp628_dt_ids, dev);
if (!match) {
dev_err(dev, "Unknown device model\n");
return -EINVAL;
}
pdata->latch_gpio = devm_gpiod_get(dev, "latch");
if (IS_ERR(pdata->latch_gpio)) {
dev_err(dev, "Can't get latch gpio\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(pdata->mt_ab_gpios); i++) {
pdata->mt_ab_gpios[i] = devm_gpiod_get_index(dev, "mt-ab", i);
if (IS_ERR(pdata->mt_ab_gpios[i])) {
dev_err(dev, "Can't get motor ab gpio (%d)\n", i);
return -ENODEV;
}
}
pdata->mt_ate_gpio = devm_gpiod_get(dev, "mt-ate");
if (IS_ERR(pdata->mt_ate_gpio)) {
dev_err(dev, "Can't get motor autotune gpio\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(pdata->mt_dcay_gpios); i++) {
pdata->mt_dcay_gpios[i] = devm_gpiod_get_index(dev,
"mt-dcay", i);
if (IS_ERR(pdata->mt_dcay_gpios[i])) {
dev_err(dev, "Can't get dcay gpio (%d)\n", i);
return -ENODEV;
}
}
pdata->mt_fault_gpio = devm_gpiod_get(dev, "mt-fault");
if (IS_ERR(pdata->mt_fault_gpio)) {
dev_err(dev, "Can't get motor fault gpio\n");
return -ENODEV;
}
pdata->mt_sleep_gpio = devm_gpiod_get(dev, "mt-sleep");
if (IS_ERR(pdata->mt_sleep_gpio)) {
dev_err(dev, "Can't get motor sleep gpio\n");
return -ENODEV;
}
pdata->mt_toff_gpio = devm_gpiod_get(dev, "mt-toff");
if (IS_ERR(pdata->mt_toff_gpio)) {
dev_err(dev, "Can't get motor toff gpio\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(pdata->mt_trq_gpios); i++) {
pdata->mt_trq_gpios[i] = devm_gpiod_get_index(dev,
"mt-trq", i);
if (IS_ERR(pdata->mt_trq_gpios[i])) {
dev_err(dev, "Can't get motor trq gpio (%d)\n", i);
return -ENODEV;
}
}
pdata->paper_out_gpio = devm_gpiod_get(dev, "paper-out");
if (IS_ERR(pdata->paper_out_gpio)) {
dev_err(dev, "Can't get paper out gpio\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(pdata->strobe_gpios); i++) {
pdata->strobe_gpios[i] = devm_gpiod_get_index(dev, "strobe", i);
if (IS_ERR(pdata->strobe_gpios[i])) {
dev_err(dev, "Can't get strobe gpio (%d)\n", i);
return -ENODEV;
}
}
return 0;
}
#else
#define ftp628_dt_ids NULL
static int ftp628_probe_dt(struct device *dev, struct ftp628_data *pdata)
{
dev_err(dev, "no platform data defined\n");
return -EINVAL;
}
#endif
static int ftp628_probe(struct spi_device *spi)
{
struct ftp628_data *pdata = &ftp628_data;
int ret;
ret = ftp628_probe_dt(&spi->dev, pdata);
if (ret != 0)
return ret;
/* Initialize all the values */
pdata->spi = spi;
spi_set_drvdata(spi, pdata);
ftp628_init_motors(pdata);
ftp628_init_printer(pdata);
/* Add misc char device for user-space access */
ret = misc_register(&ftp628_device);
if (ret) {
dev_err(&spi->dev, "Failed to misc_register: %d\n", ret);
return ret;
}
dev_info(&spi->dev, "probed!\n");
return 0;
}
static int ftp628_remove(struct spi_device *spi)
{
misc_deregister(&ftp628_device);
dev_info(&spi->dev, "removed!\n");
return 0;
}
static struct spi_driver ftp628_driver = {
.driver = {
.name = DEV_NAME,
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(ftp628_dt_ids),
},
.probe = ftp628_probe,
.remove = ftp628_remove,
};
module_spi_driver(ftp628_driver);
MODULE_AUTHOR("Boundary Devices <info@boundarydevices.com>");
MODULE_DESCRIPTION("Driver for Fujitsu FTP628 thermal printer");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:ftp628");
| 24.482558 | 79 | 0.69271 | [
"model"
] |
9acce3f52af8d53b0ada0cea7c0f364975d80d38 | 10,369 | h | C | src/contour/helper.h | sebastianrakel/contour | f0004230be75bb99fc899851a216f41d1dca2a81 | [
"Apache-2.0"
] | null | null | null | src/contour/helper.h | sebastianrakel/contour | f0004230be75bb99fc899851a216f41d1dca2a81 | [
"Apache-2.0"
] | null | null | null | src/contour/helper.h | sebastianrakel/contour | f0004230be75bb99fc899851a216f41d1dca2a81 | [
"Apache-2.0"
] | null | null | null | /**
* This file is part of the "contour" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <contour/Config.h>
#include <terminal/InputGenerator.h>
#include <terminal/ScreenEvents.h>
#include <terminal_renderer/GridMetrics.h>
#include <crispy/logstore.h>
#include <QtCore/QCoreApplication>
#include <QtCore/Qt>
#include <QtGui/QKeyEvent>
#include <QtGui/QScreen>
#include <QtWidgets/QWidget>
#include <cctype>
#include <map>
#include <string>
#include <string_view>
namespace terminal::renderer
{
class Renderer;
}
namespace contour
{
auto inline const DisplayLog =
logstore::Category("gui.display", "Logs display driver details (e.g. OpenGL).");
auto inline const InputLog =
logstore::Category("gui.input", "Logs input driver details (e.g. GUI input events).");
auto inline const SessionLog = logstore::Category("gui.session", "VT terminal session logs");
namespace detail
{
template <typename F>
class FunctionCallEvent: public QEvent
{
private:
using Fun = typename std::decay<F>::type;
Fun fun;
public:
FunctionCallEvent(Fun&& fun): QEvent(QEvent::None), fun(std::move(fun)) {}
FunctionCallEvent(Fun const& fun): QEvent(QEvent::None), fun(fun) {}
~FunctionCallEvent() { fun(); }
};
} // namespace detail
enum class MouseCursorShape
{
Hidden,
PointingHand,
IBeam,
Arrow,
};
template <typename F>
void postToObject(QObject* obj, F fun)
{
#if 0
// Qt >= 5.10
QMetaObject::invokeMethod(obj, std::forward<F>(fun));
#else
// Qt < 5.10
QCoreApplication::postEvent(obj, new detail::FunctionCallEvent<F>(std::forward<F>(fun)));
#endif
}
QScreen* screenOf(QWidget const* _widget);
constexpr inline bool isModifier(Qt::Key _key)
{
switch (_key)
{
case Qt::Key_Alt:
case Qt::Key_Control:
case Qt::Key_Shift:
case Qt::Key_Meta: return true;
default: return false;
}
}
constexpr inline char32_t makeChar(Qt::Key _key, Qt::KeyboardModifiers _mods)
{
auto const value = static_cast<int>(_key);
if (value >= 'A' && value <= 'Z')
{
if (_mods & Qt::ShiftModifier)
return static_cast<char32_t>(value);
else
return static_cast<char32_t>(std::tolower(value));
}
return 0;
}
constexpr inline terminal::Modifier makeModifier(Qt::KeyboardModifiers _mods)
{
using terminal::Modifier;
Modifier mods {};
if (_mods & Qt::AltModifier)
mods |= Modifier::Alt;
if (_mods & Qt::ShiftModifier)
mods |= Modifier::Shift;
#if defined(__APPLE__)
// XXX https://doc.qt.io/qt-5/qt.html#KeyboardModifier-enum
// "Note: On macOS, the ControlModifier value corresponds to the Command keys on the keyboard,
// and the MetaModifier value corresponds to the Control keys."
if (_mods & Qt::MetaModifier)
mods |= Modifier::Control;
if (_mods & Qt::ControlModifier)
mods |= Modifier::Meta;
#else
if (_mods & Qt::ControlModifier)
mods |= Modifier::Control;
if (_mods & Qt::MetaModifier)
mods |= Modifier::Meta;
#endif
return mods;
}
constexpr inline terminal::MouseButton makeMouseButton(Qt::MouseButton _button)
{
switch (_button)
{
case Qt::MouseButton::RightButton: return terminal::MouseButton::Right;
case Qt::MiddleButton: return terminal::MouseButton::Middle;
case Qt::LeftButton: [[fallthrough]];
default: // d'oh
return terminal::MouseButton::Left;
}
}
class TerminalSession;
bool sendKeyEvent(QKeyEvent* _keyEvent, TerminalSession& _session);
void sendWheelEvent(QWheelEvent* _event, TerminalSession& _session);
void sendMousePressEvent(QMouseEvent* _event, TerminalSession& _session);
void sendMouseMoveEvent(QMouseEvent* _event, TerminalSession& _session);
void sendMouseReleaseEvent(QMouseEvent* _event, TerminalSession& _session);
void spawnNewTerminal(std::string const& _programPath,
std::string const& _configPath,
std::string const& _profileName,
std::string const& _cwdUrl);
using PermissionCache = std::map<std::string, bool>;
bool requestPermission(PermissionCache& _cache,
QWidget* _parent,
config::Permission _allowedByConfig,
std::string_view _topicText);
terminal::FontDef getFontDefinition(terminal::renderer::Renderer& _renderer);
terminal::renderer::PageMargin computeMargin(terminal::ImageSize _cellSize,
terminal::PageSize _charCells,
terminal::ImageSize _pixels) noexcept;
terminal::renderer::FontDescriptions sanitizeFontDescription(terminal::renderer::FontDescriptions _fonts,
text::DPI _screenDPI);
constexpr terminal::PageSize pageSizeForPixels(crispy::ImageSize viewSize,
crispy::ImageSize cellSize) noexcept
{
return terminal::PageSize { boxed_cast<terminal::LineCount>((viewSize / cellSize).height),
boxed_cast<terminal::ColumnCount>((viewSize / cellSize).width) };
}
void applyResize(terminal::ImageSize _newPixelSize,
TerminalSession& _session,
terminal::renderer::Renderer& _renderer);
bool applyFontDescription(terminal::ImageSize _cellSize,
terminal::PageSize _pageSize,
terminal::ImageSize _pixelSize,
text::DPI _dpi,
terminal::renderer::Renderer& _renderer,
terminal::renderer::FontDescriptions _fontDescriptions);
constexpr Qt::CursorShape toQtMouseShape(MouseCursorShape _shape)
{
switch (_shape)
{
case contour::MouseCursorShape::Hidden: return Qt::CursorShape::BlankCursor;
case contour::MouseCursorShape::Arrow: return Qt::CursorShape::ArrowCursor;
case contour::MouseCursorShape::IBeam: return Qt::CursorShape::IBeamCursor;
case contour::MouseCursorShape::PointingHand: return Qt::CursorShape::PointingHandCursor;
}
// should never be reached
return Qt::CursorShape::ArrowCursor;
}
/// Declares the screen-dirtiness-vs-rendering state.
enum class RenderState
{
CleanIdle, //!< No screen updates and no rendering currently in progress.
DirtyIdle, //!< Screen updates pending and no rendering currently in progress.
CleanPainting, //!< No screen updates and rendering currently in progress.
DirtyPainting //!< Screen updates pending and rendering currently in progress.
};
/// Defines the current screen-dirtiness-vs-rendering state.
///
/// This is primarily updated by two independant threads, the rendering thread and the I/O
/// thread.
/// The rendering thread constantly marks the rendering state CleanPainting whenever it is about
/// to render and, depending on whether new screen changes happened, in the frameSwapped()
/// callback either DirtyPainting and continues to rerender or CleanIdle if no changes came in
/// since last render.
///
/// The I/O thread constantly marks the state dirty whenever new data has arrived,
/// either DirtyIdle if no painting is currently in progress, DirtyPainting otherwise.
struct RenderStateManager
{
std::atomic<RenderState> state_ = RenderState::CleanIdle;
bool renderingPressure_ = false;
RenderState fetchAndClear() { return state_.exchange(RenderState::CleanPainting); }
bool touch()
{
for (;;)
{
auto state = state_.load();
switch (state)
{
case RenderState::CleanIdle:
if (state_.compare_exchange_strong(state, RenderState::DirtyIdle))
return true;
break;
case RenderState::CleanPainting:
if (state_.compare_exchange_strong(state, RenderState::DirtyPainting))
return false;
break;
case RenderState::DirtyIdle:
case RenderState::DirtyPainting: return false;
}
}
}
/// @retval true finished rendering, nothing pending yet. So please start update timer.
/// @retval false more data pending. Rerun paint() immediately.
bool finish()
{
for (;;)
{
auto state = state_.load();
switch (state)
{
case RenderState::DirtyIdle:
// assert(!"The impossible happened, painting but painting. Shakesbeer.");
// qDebug() << "The impossible happened, onFrameSwapped() called in wrong state DirtyIdle.";
[[fallthrough]];
case RenderState::DirtyPainting: return false;
case RenderState::CleanPainting:
if (!state_.compare_exchange_strong(state, RenderState::CleanIdle))
break;
[[fallthrough]];
case RenderState::CleanIdle: renderingPressure_ = false; return true;
}
}
}
};
} // namespace contour
namespace fmt
{
template <>
struct formatter<contour::RenderState>
{
using State = contour::RenderState;
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(State state, FormatContext& ctx)
{
switch (state)
{
case State::CleanIdle: return format_to(ctx.out(), "clean-idle");
case State::CleanPainting: return format_to(ctx.out(), "clean-painting");
case State::DirtyIdle: return format_to(ctx.out(), "dirty-idle");
case State::DirtyPainting: return format_to(ctx.out(), "dirty-painting");
}
return format_to(ctx.out(), "Invalid");
}
};
} // namespace fmt
| 33.233974 | 108 | 0.653101 | [
"render"
] |
9acee314a8aa5048dd197e6cadc7982e830037be | 23,292 | c | C | src/mame/video/decocass.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | src/mame/video/decocass.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | src/mame/video/decocass.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | /***********************************************************************
DECO Cassette System video
***********************************************************************/
#include "driver.h"
#include "machine/decocass.h"
static INT32 watchdog_count;
static INT32 watchdog_flip;
static INT32 color_missiles;
static INT32 color_center_bot;
static INT32 mode_set;
static INT32 back_h_shift;
static INT32 back_vl_shift;
static INT32 back_vr_shift;
static INT32 part_h_shift;
static INT32 part_v_shift;
static INT32 center_h_shift_space;
static INT32 center_v_shift;
UINT8 *decocass_charram;
UINT8 *decocass_fgvideoram;
UINT8 *decocass_colorram;
UINT8 *decocass_bgvideoram; /* shares bits D0-3 with tileram! */
UINT8 *decocass_tileram;
UINT8 *decocass_objectram;
size_t decocass_fgvideoram_size;
size_t decocass_colorram_size;
size_t decocass_bgvideoram_size;
size_t decocass_tileram_size;
size_t decocass_objectram_size;
static tilemap *fg_tilemap, *bg_tilemap_l, *bg_tilemap_r;
static char *sprite_dirty;
static char *char_dirty;
static char *tile_dirty;
static char object_dirty;
static rectangle bg_tilemap_l_clip;
static rectangle bg_tilemap_r_clip;
static const UINT32 tile_offset[32*32] = {
0x078,0x079,0x07a,0x07b,0x07c,0x07d,0x07e,0x07f,0x0ff,0x0fe,0x0fd,0x0fc,0x0fb,0x0fa,0x0f9,0x0f8,0x278,0x279,0x27a,0x27b,0x27c,0x27d,0x27e,0x27f,0x2ff,0x2fe,0x2fd,0x2fc,0x2fb,0x2fa,0x2f9,0x2f8,
0x070,0x071,0x072,0x073,0x074,0x075,0x076,0x077,0x0f7,0x0f6,0x0f5,0x0f4,0x0f3,0x0f2,0x0f1,0x0f0,0x270,0x271,0x272,0x273,0x274,0x275,0x276,0x277,0x2f7,0x2f6,0x2f5,0x2f4,0x2f3,0x2f2,0x2f1,0x2f0,
0x068,0x069,0x06a,0x06b,0x06c,0x06d,0x06e,0x06f,0x0ef,0x0ee,0x0ed,0x0ec,0x0eb,0x0ea,0x0e9,0x0e8,0x268,0x269,0x26a,0x26b,0x26c,0x26d,0x26e,0x26f,0x2ef,0x2ee,0x2ed,0x2ec,0x2eb,0x2ea,0x2e9,0x2e8,
0x060,0x061,0x062,0x063,0x064,0x065,0x066,0x067,0x0e7,0x0e6,0x0e5,0x0e4,0x0e3,0x0e2,0x0e1,0x0e0,0x260,0x261,0x262,0x263,0x264,0x265,0x266,0x267,0x2e7,0x2e6,0x2e5,0x2e4,0x2e3,0x2e2,0x2e1,0x2e0,
0x058,0x059,0x05a,0x05b,0x05c,0x05d,0x05e,0x05f,0x0df,0x0de,0x0dd,0x0dc,0x0db,0x0da,0x0d9,0x0d8,0x258,0x259,0x25a,0x25b,0x25c,0x25d,0x25e,0x25f,0x2df,0x2de,0x2dd,0x2dc,0x2db,0x2da,0x2d9,0x2d8,
0x050,0x051,0x052,0x053,0x054,0x055,0x056,0x057,0x0d7,0x0d6,0x0d5,0x0d4,0x0d3,0x0d2,0x0d1,0x0d0,0x250,0x251,0x252,0x253,0x254,0x255,0x256,0x257,0x2d7,0x2d6,0x2d5,0x2d4,0x2d3,0x2d2,0x2d1,0x2d0,
0x048,0x049,0x04a,0x04b,0x04c,0x04d,0x04e,0x04f,0x0cf,0x0ce,0x0cd,0x0cc,0x0cb,0x0ca,0x0c9,0x0c8,0x248,0x249,0x24a,0x24b,0x24c,0x24d,0x24e,0x24f,0x2cf,0x2ce,0x2cd,0x2cc,0x2cb,0x2ca,0x2c9,0x2c8,
0x040,0x041,0x042,0x043,0x044,0x045,0x046,0x047,0x0c7,0x0c6,0x0c5,0x0c4,0x0c3,0x0c2,0x0c1,0x0c0,0x240,0x241,0x242,0x243,0x244,0x245,0x246,0x247,0x2c7,0x2c6,0x2c5,0x2c4,0x2c3,0x2c2,0x2c1,0x2c0,
0x038,0x039,0x03a,0x03b,0x03c,0x03d,0x03e,0x03f,0x0bf,0x0be,0x0bd,0x0bc,0x0bb,0x0ba,0x0b9,0x0b8,0x238,0x239,0x23a,0x23b,0x23c,0x23d,0x23e,0x23f,0x2bf,0x2be,0x2bd,0x2bc,0x2bb,0x2ba,0x2b9,0x2b8,
0x030,0x031,0x032,0x033,0x034,0x035,0x036,0x037,0x0b7,0x0b6,0x0b5,0x0b4,0x0b3,0x0b2,0x0b1,0x0b0,0x230,0x231,0x232,0x233,0x234,0x235,0x236,0x237,0x2b7,0x2b6,0x2b5,0x2b4,0x2b3,0x2b2,0x2b1,0x2b0,
0x028,0x029,0x02a,0x02b,0x02c,0x02d,0x02e,0x02f,0x0af,0x0ae,0x0ad,0x0ac,0x0ab,0x0aa,0x0a9,0x0a8,0x228,0x229,0x22a,0x22b,0x22c,0x22d,0x22e,0x22f,0x2af,0x2ae,0x2ad,0x2ac,0x2ab,0x2aa,0x2a9,0x2a8,
0x020,0x021,0x022,0x023,0x024,0x025,0x026,0x027,0x0a7,0x0a6,0x0a5,0x0a4,0x0a3,0x0a2,0x0a1,0x0a0,0x220,0x221,0x222,0x223,0x224,0x225,0x226,0x227,0x2a7,0x2a6,0x2a5,0x2a4,0x2a3,0x2a2,0x2a1,0x2a0,
0x018,0x019,0x01a,0x01b,0x01c,0x01d,0x01e,0x01f,0x09f,0x09e,0x09d,0x09c,0x09b,0x09a,0x099,0x098,0x218,0x219,0x21a,0x21b,0x21c,0x21d,0x21e,0x21f,0x29f,0x29e,0x29d,0x29c,0x29b,0x29a,0x299,0x298,
0x010,0x011,0x012,0x013,0x014,0x015,0x016,0x017,0x097,0x096,0x095,0x094,0x093,0x092,0x091,0x090,0x210,0x211,0x212,0x213,0x214,0x215,0x216,0x217,0x297,0x296,0x295,0x294,0x293,0x292,0x291,0x290,
0x008,0x009,0x00a,0x00b,0x00c,0x00d,0x00e,0x00f,0x08f,0x08e,0x08d,0x08c,0x08b,0x08a,0x089,0x088,0x208,0x209,0x20a,0x20b,0x20c,0x20d,0x20e,0x20f,0x28f,0x28e,0x28d,0x28c,0x28b,0x28a,0x289,0x288,
0x000,0x001,0x002,0x003,0x004,0x005,0x006,0x007,0x087,0x086,0x085,0x084,0x083,0x082,0x081,0x080,0x200,0x201,0x202,0x203,0x204,0x205,0x206,0x207,0x287,0x286,0x285,0x284,0x283,0x282,0x281,0x280,
0x178,0x179,0x17a,0x17b,0x17c,0x17d,0x17e,0x17f,0x1ff,0x1fe,0x1fd,0x1fc,0x1fb,0x1fa,0x1f9,0x1f8,0x378,0x379,0x37a,0x37b,0x37c,0x37d,0x37e,0x37f,0x3ff,0x3fe,0x3fd,0x3fc,0x3fb,0x3fa,0x3f9,0x3f8,
0x170,0x171,0x172,0x173,0x174,0x175,0x176,0x177,0x1f7,0x1f6,0x1f5,0x1f4,0x1f3,0x1f2,0x1f1,0x1f0,0x370,0x371,0x372,0x373,0x374,0x375,0x376,0x377,0x3f7,0x3f6,0x3f5,0x3f4,0x3f3,0x3f2,0x3f1,0x3f0,
0x168,0x169,0x16a,0x16b,0x16c,0x16d,0x16e,0x16f,0x1ef,0x1ee,0x1ed,0x1ec,0x1eb,0x1ea,0x1e9,0x1e8,0x368,0x369,0x36a,0x36b,0x36c,0x36d,0x36e,0x36f,0x3ef,0x3ee,0x3ed,0x3ec,0x3eb,0x3ea,0x3e9,0x3e8,
0x160,0x161,0x162,0x163,0x164,0x165,0x166,0x167,0x1e7,0x1e6,0x1e5,0x1e4,0x1e3,0x1e2,0x1e1,0x1e0,0x360,0x361,0x362,0x363,0x364,0x365,0x366,0x367,0x3e7,0x3e6,0x3e5,0x3e4,0x3e3,0x3e2,0x3e1,0x3e0,
0x158,0x159,0x15a,0x15b,0x15c,0x15d,0x15e,0x15f,0x1df,0x1de,0x1dd,0x1dc,0x1db,0x1da,0x1d9,0x1d8,0x358,0x359,0x35a,0x35b,0x35c,0x35d,0x35e,0x35f,0x3df,0x3de,0x3dd,0x3dc,0x3db,0x3da,0x3d9,0x3d8,
0x150,0x151,0x152,0x153,0x154,0x155,0x156,0x157,0x1d7,0x1d6,0x1d5,0x1d4,0x1d3,0x1d2,0x1d1,0x1d0,0x350,0x351,0x352,0x353,0x354,0x355,0x356,0x357,0x3d7,0x3d6,0x3d5,0x3d4,0x3d3,0x3d2,0x3d1,0x3d0,
0x148,0x149,0x14a,0x14b,0x14c,0x14d,0x14e,0x14f,0x1cf,0x1ce,0x1cd,0x1cc,0x1cb,0x1ca,0x1c9,0x1c8,0x348,0x349,0x34a,0x34b,0x34c,0x34d,0x34e,0x34f,0x3cf,0x3ce,0x3cd,0x3cc,0x3cb,0x3ca,0x3c9,0x3c8,
0x140,0x141,0x142,0x143,0x144,0x145,0x146,0x147,0x1c7,0x1c6,0x1c5,0x1c4,0x1c3,0x1c2,0x1c1,0x1c0,0x340,0x341,0x342,0x343,0x344,0x345,0x346,0x347,0x3c7,0x3c6,0x3c5,0x3c4,0x3c3,0x3c2,0x3c1,0x3c0,
0x138,0x139,0x13a,0x13b,0x13c,0x13d,0x13e,0x13f,0x1bf,0x1be,0x1bd,0x1bc,0x1bb,0x1ba,0x1b9,0x1b8,0x338,0x339,0x33a,0x33b,0x33c,0x33d,0x33e,0x33f,0x3bf,0x3be,0x3bd,0x3bc,0x3bb,0x3ba,0x3b9,0x3b8,
0x130,0x131,0x132,0x133,0x134,0x135,0x136,0x137,0x1b7,0x1b6,0x1b5,0x1b4,0x1b3,0x1b2,0x1b1,0x1b0,0x330,0x331,0x332,0x333,0x334,0x335,0x336,0x337,0x3b7,0x3b6,0x3b5,0x3b4,0x3b3,0x3b2,0x3b1,0x3b0,
0x128,0x129,0x12a,0x12b,0x12c,0x12d,0x12e,0x12f,0x1af,0x1ae,0x1ad,0x1ac,0x1ab,0x1aa,0x1a9,0x1a8,0x328,0x329,0x32a,0x32b,0x32c,0x32d,0x32e,0x32f,0x3af,0x3ae,0x3ad,0x3ac,0x3ab,0x3aa,0x3a9,0x3a8,
0x120,0x121,0x122,0x123,0x124,0x125,0x126,0x127,0x1a7,0x1a6,0x1a5,0x1a4,0x1a3,0x1a2,0x1a1,0x1a0,0x320,0x321,0x322,0x323,0x324,0x325,0x326,0x327,0x3a7,0x3a6,0x3a5,0x3a4,0x3a3,0x3a2,0x3a1,0x3a0,
0x118,0x119,0x11a,0x11b,0x11c,0x11d,0x11e,0x11f,0x19f,0x19e,0x19d,0x19c,0x19b,0x19a,0x199,0x198,0x318,0x319,0x31a,0x31b,0x31c,0x31d,0x31e,0x31f,0x39f,0x39e,0x39d,0x39c,0x39b,0x39a,0x399,0x398,
0x110,0x111,0x112,0x113,0x114,0x115,0x116,0x117,0x197,0x196,0x195,0x194,0x193,0x192,0x191,0x190,0x310,0x311,0x312,0x313,0x314,0x315,0x316,0x317,0x397,0x396,0x395,0x394,0x393,0x392,0x391,0x390,
0x108,0x109,0x10a,0x10b,0x10c,0x10d,0x10e,0x10f,0x18f,0x18e,0x18d,0x18c,0x18b,0x18a,0x189,0x188,0x308,0x309,0x30a,0x30b,0x30c,0x30d,0x30e,0x30f,0x38f,0x38e,0x38d,0x38c,0x38b,0x38a,0x389,0x388,
0x100,0x101,0x102,0x103,0x104,0x105,0x106,0x107,0x187,0x186,0x185,0x184,0x183,0x182,0x181,0x180,0x300,0x301,0x302,0x303,0x304,0x305,0x306,0x307,0x387,0x386,0x385,0x384,0x383,0x382,0x381,0x380
};
/********************************************
state saving setup
********************************************/
void decocass_video_state_save_init(void)
{
state_save_register_global(watchdog_count);
state_save_register_global(watchdog_flip);
state_save_register_global(color_missiles);
state_save_register_global(color_center_bot);
state_save_register_global(mode_set);
state_save_register_global(back_h_shift);
state_save_register_global(back_vl_shift);
state_save_register_global(back_vr_shift);
state_save_register_global(part_h_shift);
state_save_register_global(part_v_shift);
state_save_register_global(center_h_shift_space);
state_save_register_global(center_v_shift);
}
/********************************************
tilemap callbacks
********************************************/
static TILEMAP_MAPPER( fgvideoram_scan_cols )
{
/* logical (col,row) -> memory offset */
return (num_cols - 1 - col) * num_rows + row;
}
static TILEMAP_MAPPER( bgvideoram_scan_cols )
{
/* logical (col,row) -> memory offset */
return tile_offset[col * num_rows + row];
}
static TILE_GET_INFO( get_bg_l_tile_info )
{
int color = (color_center_bot >> 7) & 1;
SET_TILE_INFO(
2,
(0x80 == (tile_index & 0x80)) ? 16 : decocass_bgvideoram[tile_index] >> 4,
color,
0);
}
static TILE_GET_INFO( get_bg_r_tile_info )
{
int color = (color_center_bot >> 7) & 1;
SET_TILE_INFO(
2,
(0x00 == (tile_index & 0x80)) ? 16 : decocass_bgvideoram[tile_index] >> 4,
color,
TILE_FLIPY);
}
static TILE_GET_INFO( get_fg_tile_info )
{
UINT8 code = decocass_fgvideoram[tile_index];
UINT8 attr = decocass_colorram[tile_index];
SET_TILE_INFO(
0,
256 * (attr & 3) + code,
color_center_bot & 1,
0);
}
/********************************************
big object
********************************************/
static void draw_object(running_machine* machine, mame_bitmap *bitmap, const rectangle *cliprect)
{
int sx, sy, color;
if (0 == (mode_set & 0x80)) /* part_h_enable off? */
return;
color = (color_center_bot >> 4) & 15;
sy = 192 - (part_v_shift & 0x7f);
if (part_h_shift & 0x80)
sx = (part_h_shift & 0x7f) + 1;
else
sx = 91 - (part_h_shift & 0x7f);
drawgfx(bitmap, machine->gfx[3], 0, color, 0, 0, sx + 64, sy, cliprect, TRANSPARENCY_PEN, 0);
drawgfx(bitmap, machine->gfx[3], 1, color, 0, 0, sx, sy, cliprect, TRANSPARENCY_PEN, 0);
drawgfx(bitmap, machine->gfx[3], 0, color, 0, 1, sx + 64, sy - 64, cliprect, TRANSPARENCY_PEN, 0);
drawgfx(bitmap, machine->gfx[3], 1, color, 0, 1, sx, sy - 64, cliprect, TRANSPARENCY_PEN, 0);
}
static void draw_center(running_machine* machine, mame_bitmap *bitmap, const rectangle *cliprect)
{
int sx, sy, x, y, color;
color = 0;
if (color_center_bot & 0x10)
color |= 4;
if (color_center_bot & 0x20)
color |= 2;
if (color_center_bot & 0x40)
color |= 1;
if (color_center_bot & 0x80)
color = (color & 4) + ((color << 1) & 2) + ((color >> 1) & 1);
sy = center_v_shift;
sx = (center_h_shift_space >> 2) & 0x3c;
for (y = 0; y < 4; y++)
if ((sy + y) >= cliprect->min_y && (sy + y) <= cliprect->max_y)
{
if (((sy + y) & color_center_bot & 3) == (sy & color_center_bot & 3))
for (x = 0; x < 256; x++)
if (0 != (x & 16) || 0 != (center_h_shift_space & 1))
*BITMAP_ADDR16(bitmap, sy + y, (sx + x) & 255) = machine->pens[color];
}
}
/********************************************
memory handlers
********************************************/
WRITE8_HANDLER( decocass_paletteram_w )
{
/*
* RGB output is inverted and A4 is inverted too
* (ME/ input on 1st paletteram, inverter -> ME/ on 2nd)
*/
offset = (offset & 31) ^ 16;
paletteram_BBGGGRRR_w( offset, ~data );
}
WRITE8_HANDLER( decocass_charram_w )
{
if (data == decocass_charram[offset])
return;
decocass_charram[offset] = data;
/* dirty sprite */
sprite_dirty[(offset >> 5) & 255] = 1;
/* dirty char */
char_dirty[(offset >> 3) & 1023] = 1;
}
WRITE8_HANDLER( decocass_fgvideoram_w )
{
decocass_fgvideoram[offset] = data;
tilemap_mark_tile_dirty( fg_tilemap, offset );
}
WRITE8_HANDLER( decocass_colorram_w )
{
decocass_colorram[offset] = data;
tilemap_mark_tile_dirty( fg_tilemap, offset );
}
static void mark_bg_tile_dirty(offs_t offset)
{
if (offset & 0x80)
tilemap_mark_tile_dirty( bg_tilemap_r, offset );
else
tilemap_mark_tile_dirty( bg_tilemap_l, offset );
}
WRITE8_HANDLER( decocass_tileram_w )
{
if (data == decocass_tileram[offset])
return;
decocass_tileram[offset] = data;
/* dirty tile (64 bytes per tile) */
tile_dirty[(offset / 64) & 15] = 1;
/* first 1KB of tile RAM is shared with tilemap RAM */
if (offset < decocass_bgvideoram_size)
mark_bg_tile_dirty( offset );
}
WRITE8_HANDLER( decocass_objectram_w )
{
if (data == decocass_objectram[offset])
return;
decocass_objectram[offset] = data;
/* dirty the object */
object_dirty = 1;
}
WRITE8_HANDLER( decocass_bgvideoram_w )
{
if (data == decocass_bgvideoram[offset])
return;
decocass_bgvideoram[offset] = data;
mark_bg_tile_dirty( offset );
}
/* The watchdog is a 4bit counter counting down every frame */
WRITE8_HANDLER( decocass_watchdog_count_w )
{
LOG(1,("decocass_watchdog_count_w: $%02x\n", data));
watchdog_count = data & 0x0f;
}
WRITE8_HANDLER( decocass_watchdog_flip_w )
{
LOG(1,("decocass_watchdog_flip_w: $%02x\n", data));
watchdog_flip = data;
}
WRITE8_HANDLER( decocass_color_missiles_w )
{
LOG(1,("decocass_color_missiles_w: $%02x\n", data));
/* only bits D0-D2 and D4-D6 are connected to
* the color RAM demux:
* D0-D2 to the IC0 inputs
* D4-D6 to the IC1 inputs
*/
color_missiles = data & 0x77;
}
/*
* D0 - ??
* D1 - ??
* D2 - ptn 1/2
* D3 - BKG ena
* D4 - center L on
* D5 - cross on
* D6 - tunnel
* D7 - part h enable
*/
WRITE8_HANDLER( decocass_mode_set_w )
{
if (data == mode_set)
return;
LOG(1,("decocass_mode_set_w: $%02x (%s%s%s%s%s%s%s%s)\n", data,
(data & 0x01) ? "D0?" : "",
(data & 0x02) ? " D1?" : "",
(data & 0x04) ? " ptn1/2" : "",
(data & 0x08) ? " bkg_ena" : "",
(data & 0x10) ? " center_l_on" : "",
(data & 0x20) ? " cross_on" : "",
(data & 0x40) ? " tunnel" : "",
(data & 0x80) ? " part_h_enable" : ""));
mode_set = data;
}
WRITE8_HANDLER( decocass_color_center_bot_w )
{
if (data == color_center_bot)
return;
LOG(1,("decocass_color_center_bot_w: $%02x (color:%d, center_bot:%d)\n", data, data&3, data>>4));
/*
* D7 CL3/4 (swap 2+4)
* D6 CL1
* D5 CL2
* D4 CL4
* D3 nc
* D2 nc
* D1 CLD4
* D0 CLD3
*/
if ((color_center_bot ^ data) & 0x80)
{
tilemap_mark_all_tiles_dirty(bg_tilemap_r);
tilemap_mark_all_tiles_dirty(bg_tilemap_l);
}
if ((color_center_bot ^ data) & 0x01)
tilemap_mark_all_tiles_dirty(fg_tilemap);
color_center_bot = data;
}
WRITE8_HANDLER( decocass_back_h_shift_w )
{
if (data == back_h_shift)
return;
LOG(1,("decocass_back_h_shift_w: $%02x\n", data));
back_h_shift = data;
}
WRITE8_HANDLER( decocass_back_vl_shift_w )
{
if (data == back_vl_shift)
return;
LOG(1,("decocass_back_vl_shift_w: $%02x\n", data));
back_vl_shift = data;
}
WRITE8_HANDLER( decocass_back_vr_shift_w )
{
if (data == back_vr_shift)
return;
LOG(1,("decocass_back_vr_shift_w: $%02x\n", data));
back_vr_shift = data;
}
WRITE8_HANDLER( decocass_part_h_shift_w )
{
if (data == part_v_shift )
return;
LOG(1,("decocass_part_h_shift_w: $%02x\n", data));
part_h_shift = data;
}
WRITE8_HANDLER( decocass_part_v_shift_w )
{
if (data == part_v_shift )
return;
LOG(1,("decocass_part_v_shift_w: $%02x\n", data));
part_v_shift = data;
}
WRITE8_HANDLER( decocass_center_h_shift_space_w )
{
if (data == center_h_shift_space)
return;
LOG(1,("decocass_center_h_shift_space_w: $%02x\n", data));
center_h_shift_space = data;
}
WRITE8_HANDLER( decocass_center_v_shift_w )
{
LOG(1,("decocass_center_v_shift_w: $%02x\n", data));
center_v_shift = data;
}
/********************************************
memory handlers
********************************************/
static void draw_sprites(running_machine* machine, mame_bitmap *bitmap, const rectangle *cliprect, int color,
int sprite_y_adjust, int sprite_y_adjust_flip_screen,
UINT8 *sprite_ram, int interleave)
{
int i,offs;
/* Draw the sprites */
for (i = 0, offs = 0;i < 8; i++, offs += 4*interleave)
{
int sx,sy,flipx,flipy;
if (!(sprite_ram[offs + 0] & 0x01))
continue;
sx = 240 - sprite_ram[offs + 3*interleave];
sy = 240 - sprite_ram[offs + 2*interleave];
flipx = sprite_ram[offs + 0] & 0x04;
flipy = sprite_ram[offs + 0] & 0x02;
if (flip_screen)
{
sx = 240 - sx;
sy = 240 - sy + sprite_y_adjust_flip_screen;
flipx = !flipx;
flipy = !flipy;
}
sy -= sprite_y_adjust;
drawgfx(bitmap,machine->gfx[1],
sprite_ram[offs + interleave],
color,
flipx,flipy,
sx,sy,
cliprect, TRANSPARENCY_PEN, 0);
sy += (flip_screen ? -256 : 256);
// Wrap around
drawgfx(bitmap,machine->gfx[1],
sprite_ram[offs + interleave],
color,
flipx,flipy,
sx,sy,
cliprect, TRANSPARENCY_PEN, 0);
}
}
static void draw_missiles(running_machine* machine, mame_bitmap *bitmap, const rectangle *cliprect,
int missile_y_adjust, int missile_y_adjust_flip_screen,
UINT8 *missile_ram, int interleave)
{
int i,offs,x;
/* Draw the missiles (16 of them) seemingly with alternating colors
* from the E302 latch (color_missiles) */
for (i = 0, offs = 0; i < 8; i++, offs += 4*interleave)
{
int sx,sy;
sy = 255 - missile_ram[offs + 0*interleave];
sx = 255 - missile_ram[offs + 2*interleave];
if (flip_screen)
{
sx = 240 - sx;
sy = 240 - sy + missile_y_adjust_flip_screen;
}
sy -= missile_y_adjust;
if (sy >= cliprect->min_y && sy <= cliprect->max_y)
for (x = 0; x < 4; x++)
{
if (sx >= cliprect->min_x && sx <= cliprect->max_x)
*BITMAP_ADDR16(bitmap, sy, sx) = machine->pens[(color_missiles >> 4) & 7];
sx++;
}
sy = 255 - missile_ram[offs + 1*interleave];
sx = 255 - missile_ram[offs + 3*interleave];
if (flip_screen)
{
sx = 240 - sx;
sy = 240 - sy + missile_y_adjust_flip_screen;
}
sy -= missile_y_adjust;
if (sy >= cliprect->min_y && sy <= cliprect->max_y)
for (x = 0; x < 4; x++)
{
if (sx >= cliprect->min_x && sx <= cliprect->max_x)
*BITMAP_ADDR16(bitmap, sy, sx) = machine->pens[color_missiles & 7];
sx++;
}
}
}
static void decode_modified(running_machine* machine, UINT8 *sprite_ram, int interleave)
{
int i,offs;
/* decode dirty characters */
for (offs = decocass_fgvideoram_size - 1;offs >= 0;offs--)
{
int code;
code = decocass_fgvideoram[offs] + 256 * (decocass_colorram[offs] & 3);
switch (char_dirty[code])
{
case 1:
decodechar(machine->gfx[0],code,decocass_charram,machine->drv->gfxdecodeinfo[0].gfxlayout);
char_dirty[code] = 2;
/* fall through */
case 2:
tilemap_mark_tile_dirty(fg_tilemap, offs);
break;
default:
break;
}
}
for (i = 0; i < 1024; i++)
{
if (char_dirty[i] == 2)
char_dirty[i] = 0;
}
/* decode dirty sprites */
for (i = 0, offs = 0;i < 8; i++, offs += 4*interleave)
{
int code;
code = sprite_ram[offs + interleave];
if (sprite_dirty[code])
{
sprite_dirty[code] = 0;
decodechar(machine->gfx[1],code,decocass_charram,machine->drv->gfxdecodeinfo[1].gfxlayout);
}
}
/* decode dirty tiles */
for (offs = 0; offs < decocass_bgvideoram_size; offs++)
{
int code = (decocass_tileram[offs] >> 4) & 15;
if (tile_dirty[code])
{
tile_dirty[code] = 0;
decodechar(machine->gfx[2],code,decocass_tileram,machine->drv->gfxdecodeinfo[2].gfxlayout);
/* mark all visible tiles dirty */
for (i = offs; i < decocass_bgvideoram_size; i++)
if (code == ((decocass_tileram[i] >> 4) & 15))
mark_bg_tile_dirty(i);
}
}
/* decode object if it is dirty */
if (object_dirty)
{
decodechar(machine->gfx[3], 0, decocass_objectram, machine->drv->gfxdecodeinfo[3].gfxlayout);
decodechar(machine->gfx[3], 1, decocass_objectram, machine->drv->gfxdecodeinfo[3].gfxlayout);
object_dirty = 0;
}
}
VIDEO_START( decocass )
{
sprite_dirty = auto_malloc(256);
char_dirty = auto_malloc(1024);
tile_dirty = auto_malloc(16);
bg_tilemap_l = tilemap_create( get_bg_l_tile_info, bgvideoram_scan_cols, TILEMAP_TYPE_PEN, 16, 16, 32, 32 );
bg_tilemap_r = tilemap_create( get_bg_r_tile_info, bgvideoram_scan_cols, TILEMAP_TYPE_PEN, 16, 16, 32, 32 );
fg_tilemap = tilemap_create( get_fg_tile_info, fgvideoram_scan_cols, TILEMAP_TYPE_PEN, 8, 8, 32, 32 );
tilemap_set_transparent_pen( bg_tilemap_l, 0 );
tilemap_set_transparent_pen( bg_tilemap_r, 0 );
tilemap_set_transparent_pen( fg_tilemap, 0 );
bg_tilemap_l_clip = machine->screen[0].visarea;
bg_tilemap_l_clip.max_y = machine->screen[0].height / 2;
bg_tilemap_r_clip = machine->screen[0].visarea;
bg_tilemap_r_clip.min_y = machine->screen[0].height / 2;
/* background videroam bits D0-D3 are shared with the tileram */
decocass_bgvideoram = decocass_tileram;
decocass_bgvideoram_size = 0x0400; /* d000-d3ff */
}
VIDEO_UPDATE( decocass )
{
int scrollx, scrolly_l, scrolly_r;
rectangle clip;
if (0xc0 != (input_port_2_r(0) & 0xc0)) /* coin slots assert an NMI */
cpunum_set_input_line(0, INPUT_LINE_NMI, ASSERT_LINE);
if (0 == (watchdog_flip & 0x04))
watchdog_reset_w (0,0);
else if (watchdog_count-- > 0)
watchdog_reset_w (0,0);
#if TAPE_UI_DISPLAY
if (tape_timer)
{
mame_time tape_time = decocass_adjust_tape_time(tape_time0);
popmessage("%c%c [%05.1fs] %c%c",
(tape_dir < 0 && tape_speed) ? '<' : ' ',
(tape_dir < 0) ? '<' : ' ',
mame_time_to_double(tape_time),
(tape_dir > 0) ? '>' : ' ',
(tape_dir > 0 && tape_speed) ? '>' : ' ');
}
#endif
#ifdef MAME_DEBUG
{
static int showmsg;
if (input_code_pressed_once(KEYCODE_I))
showmsg ^= 1;
if (showmsg)
popmessage("mode:$%02x cm:$%02x ccb:$%02x h:$%02x vl:$%02x vr:$%02x ph:$%02x pv:$%02x ch:$%02x cv:$%02x",
mode_set,
color_missiles,
color_center_bot,
back_h_shift,
back_vl_shift,
back_vr_shift,
part_h_shift,
part_v_shift,
center_h_shift_space,
center_v_shift);
}
#endif
fillbitmap( bitmap, machine->pens[0], cliprect );
decode_modified(machine, decocass_fgvideoram, 0x20 );
scrolly_l = back_vl_shift;
scrolly_r = 256 - back_vr_shift;
scrollx = 256 - back_h_shift;
if (0 == (mode_set & 0x02))
scrollx += 256;
#if 0
/* this is wrong */
if (0 != back_h_shift && 0 == ((mode_set ^ (mode_set >> 1)) & 1))
scrollx += 256;
#endif
if (0 == (mode_set & 0x04))
scrolly_r += 256;
else
scrolly_l += 256;
tilemap_set_scrollx( bg_tilemap_l, 0, scrollx );
tilemap_set_scrolly( bg_tilemap_l, 0, scrolly_l );
tilemap_set_scrollx( bg_tilemap_r, 0, scrollx );
tilemap_set_scrolly( bg_tilemap_r, 0, scrolly_r );
if (mode_set & 0x08) /* bkg_ena on ? */
{
clip = bg_tilemap_l_clip;
sect_rect(&clip,cliprect);
tilemap_draw(bitmap,&clip, bg_tilemap_l, TILEMAP_DRAW_OPAQUE, 0);
clip = bg_tilemap_r_clip;
sect_rect(&clip,cliprect);
tilemap_draw(bitmap,&clip, bg_tilemap_r, TILEMAP_DRAW_OPAQUE, 0);
}
if (mode_set & 0x20)
{
draw_object(machine,bitmap,cliprect);
draw_center(machine,bitmap,cliprect);
}
else
{
draw_object(machine,bitmap,cliprect);
draw_center(machine,bitmap,cliprect);
if (mode_set & 0x08) /* bkg_ena on ? */
{
clip = bg_tilemap_l_clip;
sect_rect(&clip,cliprect);
tilemap_draw(bitmap,&clip, bg_tilemap_l, 0, 0);
clip = bg_tilemap_r_clip;
sect_rect(&clip,cliprect);
tilemap_draw(bitmap,&clip, bg_tilemap_r, 0, 0);
}
}
tilemap_draw(bitmap,cliprect, fg_tilemap, 0, 0);
draw_sprites(machine,bitmap,cliprect, (color_center_bot >> 1) & 1, 0, 0, decocass_fgvideoram, 0x20);
draw_missiles(machine,bitmap,cliprect, 1, 0, decocass_colorram, 0x20);
return 0;
}
| 32.576224 | 193 | 0.701786 | [
"object"
] |
9acfafa95a70998e414dc95fba1bf029df123887 | 3,792 | h | C | src/Game/GameGraphic.h | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 9 | 2020-11-02T17:20:40.000Z | 2021-12-25T15:35:36.000Z | src/Game/GameGraphic.h | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 2 | 2020-06-27T23:14:13.000Z | 2020-11-02T17:28:32.000Z | src/Game/GameGraphic.h | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 1 | 2021-05-12T23:05:42.000Z | 2021-05-12T23:05:42.000Z | //%includeGuardStart {
#ifndef GAMEGRAPHIC_H
#define GAMEGRAPHIC_H
//%includeGuardStart } mSvX5xP5Zam4WQhfpheceQ
//%Header {
/*****************************************************************************
*
* File: src/Game/GameGraphic.h
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* 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.
*
****************************************************************************/
//%Header } 6aMxybwtHLM6Xk16UGgatw
/*
* $Id: GameGraphic.h,v 1.19 2006/06/01 15:38:58 southa Exp $
* $Log: GameGraphic.h,v $
* Revision 1.19 2006/06/01 15:38:58 southa
* DrawArray verification and fixes
*
* Revision 1.18 2005/05/19 13:02:02 southa
* Mac release work
*
* Revision 1.17 2004/01/06 20:46:50 southa
* Build fixes
*
* Revision 1.16 2004/01/02 21:13:07 southa
* Source conditioning
*
* Revision 1.15 2003/09/17 19:40:32 southa
* Source conditioning upgrades
*
* Revision 1.14 2003/08/21 23:08:46 southa
* Fixed file headers
*
* Revision 1.13 2003/01/11 13:03:13 southa
* Use Mushcore header
*
* Revision 1.12 2003/01/09 14:57:02 southa
* Created Mushcore
*
* Revision 1.11 2002/12/29 20:30:54 southa
* Work for gcc 3.1 build
*
* Revision 1.10 2002/12/20 13:17:40 southa
* Namespace changes, licence changes and source conditioning
*
* Revision 1.9 2002/11/24 23:18:23 southa
* Added type name accessor to MushcorePickle
*
* Revision 1.8 2002/10/22 20:42:04 southa
* Source conditioning
*
* Revision 1.7 2002/10/12 11:22:21 southa
* GraphicModel work
*
* Revision 1.6 2002/08/27 08:56:24 southa
* Source conditioning
*
* Revision 1.5 2002/08/07 13:36:50 southa
* Conditioned source
*
* Revision 1.4 2002/07/06 18:04:19 southa
* More designer work
*
* Revision 1.3 2002/06/27 12:36:07 southa
* Build process fixes
*
* Revision 1.2 2002/06/04 20:27:37 southa
* Pickles for game traits and graphics. Removed mac libraries from archive.
*
* Revision 1.1 2002/06/04 17:02:11 southa
* More work
*
*/
#include "mushMushcore.h"
class GameGraphic : public MushcorePickle, protected MushcoreXMLHandler
{
public:
GameGraphic() {}
virtual ~GameGraphic() {}
virtual void Pickle(std::ostream& inOut, const std::string& inPrefix="") const = 0;
virtual void Unpickle(MushcoreXML& inXML) = 0;
virtual void Render(void) = 0;
virtual char *TypeNameGet(void) const = 0;
static GameGraphic& NewFromType(const std::string& inName);
protected:
void UnpicklePrologue(void) {}
void UnpickleEpilogue(void) {}
private:
};
inline std::ostream& operator<<(std::ostream &inOut, const GameGraphic& inObj)
{
inObj.Pickle(inOut);
return inOut;
}
//%includeGuardEnd {
#endif
//%includeGuardEnd } hNb4yLSsimk5RFvFdUzHEw
| 30.829268 | 87 | 0.683808 | [
"render"
] |
9ad01da6eacb7d5afd2c20e62440dfc84b1cf00c | 10,548 | c | C | sources/drivers/gpu/drm/nouveau/core/subdev/therm/base.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | sources/drivers/gpu/drm/nouveau/core/subdev/therm/base.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | sources/drivers/gpu/drm/nouveau/core/subdev/therm/base.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 3 | 2017-06-24T20:23:09.000Z | 2018-03-25T04:30:11.000Z | /*
* Copyright 2012 The Nouveau community
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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.
*
* Authors: Martin Peres
*/
#include <core/object.h>
#include <core/device.h>
#include <subdev/bios.h>
#include "priv.h"
static int
nouveau_therm_update_trip(struct nouveau_therm *therm)
{
struct nouveau_therm_priv *priv = (void *)therm;
struct nouveau_therm_trip_point *trip = priv->fan->bios.trip,
*cur_trip = NULL,
*last_trip = priv->last_trip;
u8 temp = therm->temp_get(therm);
u16 duty, i;
/* look for the trip point corresponding to the current temperature */
cur_trip = NULL;
for (i = 0; i < priv->fan->bios.nr_fan_trip; i++) {
if (temp >= trip[i].temp)
cur_trip = &trip[i];
}
/* account for the hysteresis cycle */
if (last_trip && temp <= (last_trip->temp) &&
temp > (last_trip->temp - last_trip->hysteresis))
cur_trip = last_trip;
if (cur_trip) {
duty = cur_trip->fan_duty;
priv->last_trip = cur_trip;
} else {
duty = 0;
priv->last_trip = NULL;
}
return duty;
}
static int
nouveau_therm_update_linear(struct nouveau_therm *therm)
{
struct nouveau_therm_priv *priv = (void *)therm;
u8 linear_min_temp = priv->fan->bios.linear_min_temp;
u8 linear_max_temp = priv->fan->bios.linear_max_temp;
u8 temp = therm->temp_get(therm);
u16 duty;
/* handle the non-linear part first */
if (temp < linear_min_temp)
return priv->fan->bios.min_duty;
else if (temp > linear_max_temp)
return priv->fan->bios.max_duty;
/* we are in the linear zone */
duty = (temp - linear_min_temp);
duty *= (priv->fan->bios.max_duty - priv->fan->bios.min_duty);
duty /= (linear_max_temp - linear_min_temp);
duty += priv->fan->bios.min_duty;
return duty;
}
static void
nouveau_therm_update(struct nouveau_therm *therm, int mode)
{
struct nouveau_timer *ptimer = nouveau_timer(therm);
struct nouveau_therm_priv *priv = (void *)therm;
unsigned long flags;
bool immd = true;
bool poll = true;
int duty = -1;
spin_lock_irqsave(&priv->lock, flags);
if (mode < 0)
mode = priv->mode;
priv->mode = mode;
switch (mode) {
case NOUVEAU_THERM_CTRL_MANUAL:
ptimer->alarm_cancel(ptimer, &priv->alarm);
duty = nouveau_therm_fan_get(therm);
if (duty < 0)
duty = 100;
poll = false;
break;
case NOUVEAU_THERM_CTRL_AUTO:
switch(priv->fan->bios.fan_mode) {
case NVBIOS_THERM_FAN_TRIP:
duty = nouveau_therm_update_trip(therm);
break;
case NVBIOS_THERM_FAN_LINEAR:
duty = nouveau_therm_update_linear(therm);
break;
case NVBIOS_THERM_FAN_OTHER:
if (priv->cstate)
duty = priv->cstate;
poll = false;
break;
}
immd = false;
break;
case NOUVEAU_THERM_CTRL_NONE:
default:
ptimer->alarm_cancel(ptimer, &priv->alarm);
poll = false;
}
if (list_empty(&priv->alarm.head) && poll)
ptimer->alarm(ptimer, 1000000000ULL, &priv->alarm);
spin_unlock_irqrestore(&priv->lock, flags);
if (duty >= 0) {
nv_debug(therm, "FAN target request: %d%%\n", duty);
nouveau_therm_fan_set(therm, immd, duty);
}
}
int
nouveau_therm_cstate(struct nouveau_therm *ptherm, int fan, int dir)
{
struct nouveau_therm_priv *priv = (void *)ptherm;
if (!dir || (dir < 0 && fan < priv->cstate) ||
(dir > 0 && fan > priv->cstate)) {
nv_debug(ptherm, "default fan speed -> %d%%\n", fan);
priv->cstate = fan;
nouveau_therm_update(ptherm, -1);
}
return 0;
}
static void
nouveau_therm_alarm(struct nouveau_alarm *alarm)
{
struct nouveau_therm_priv *priv =
container_of(alarm, struct nouveau_therm_priv, alarm);
nouveau_therm_update(&priv->base, -1);
}
int
nouveau_therm_fan_mode(struct nouveau_therm *therm, int mode)
{
struct nouveau_therm_priv *priv = (void *)therm;
struct nouveau_device *device = nv_device(therm);
static const char *name[] = {
"disabled",
"manual",
"automatic"
};
/* The default PPWR ucode on fermi interferes with fan management */
if ((mode >= ARRAY_SIZE(name)) ||
(mode != NOUVEAU_THERM_CTRL_NONE && device->card_type >= NV_C0 &&
!nouveau_subdev(device, NVDEV_SUBDEV_PWR)))
return -EINVAL;
/* do not allow automatic fan management if the thermal sensor is
* not available */
if (mode == NOUVEAU_THERM_CTRL_AUTO && therm->temp_get(therm) < 0)
return -EINVAL;
if (priv->mode == mode)
return 0;
nv_info(therm, "fan management: %s\n", name[mode]);
nouveau_therm_update(therm, mode);
return 0;
}
int
nouveau_therm_attr_get(struct nouveau_therm *therm,
enum nouveau_therm_attr_type type)
{
struct nouveau_therm_priv *priv = (void *)therm;
switch (type) {
case NOUVEAU_THERM_ATTR_FAN_MIN_DUTY:
return priv->fan->bios.min_duty;
case NOUVEAU_THERM_ATTR_FAN_MAX_DUTY:
return priv->fan->bios.max_duty;
case NOUVEAU_THERM_ATTR_FAN_MODE:
return priv->mode;
case NOUVEAU_THERM_ATTR_THRS_FAN_BOOST:
return priv->bios_sensor.thrs_fan_boost.temp;
case NOUVEAU_THERM_ATTR_THRS_FAN_BOOST_HYST:
return priv->bios_sensor.thrs_fan_boost.hysteresis;
case NOUVEAU_THERM_ATTR_THRS_DOWN_CLK:
return priv->bios_sensor.thrs_down_clock.temp;
case NOUVEAU_THERM_ATTR_THRS_DOWN_CLK_HYST:
return priv->bios_sensor.thrs_down_clock.hysteresis;
case NOUVEAU_THERM_ATTR_THRS_CRITICAL:
return priv->bios_sensor.thrs_critical.temp;
case NOUVEAU_THERM_ATTR_THRS_CRITICAL_HYST:
return priv->bios_sensor.thrs_critical.hysteresis;
case NOUVEAU_THERM_ATTR_THRS_SHUTDOWN:
return priv->bios_sensor.thrs_shutdown.temp;
case NOUVEAU_THERM_ATTR_THRS_SHUTDOWN_HYST:
return priv->bios_sensor.thrs_shutdown.hysteresis;
}
return -EINVAL;
}
int
nouveau_therm_attr_set(struct nouveau_therm *therm,
enum nouveau_therm_attr_type type, int value)
{
struct nouveau_therm_priv *priv = (void *)therm;
switch (type) {
case NOUVEAU_THERM_ATTR_FAN_MIN_DUTY:
if (value < 0)
value = 0;
if (value > priv->fan->bios.max_duty)
value = priv->fan->bios.max_duty;
priv->fan->bios.min_duty = value;
return 0;
case NOUVEAU_THERM_ATTR_FAN_MAX_DUTY:
if (value < 0)
value = 0;
if (value < priv->fan->bios.min_duty)
value = priv->fan->bios.min_duty;
priv->fan->bios.max_duty = value;
return 0;
case NOUVEAU_THERM_ATTR_FAN_MODE:
return nouveau_therm_fan_mode(therm, value);
case NOUVEAU_THERM_ATTR_THRS_FAN_BOOST:
priv->bios_sensor.thrs_fan_boost.temp = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_FAN_BOOST_HYST:
priv->bios_sensor.thrs_fan_boost.hysteresis = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_DOWN_CLK:
priv->bios_sensor.thrs_down_clock.temp = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_DOWN_CLK_HYST:
priv->bios_sensor.thrs_down_clock.hysteresis = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_CRITICAL:
priv->bios_sensor.thrs_critical.temp = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_CRITICAL_HYST:
priv->bios_sensor.thrs_critical.hysteresis = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_SHUTDOWN:
priv->bios_sensor.thrs_shutdown.temp = value;
priv->sensor.program_alarms(therm);
return 0;
case NOUVEAU_THERM_ATTR_THRS_SHUTDOWN_HYST:
priv->bios_sensor.thrs_shutdown.hysteresis = value;
priv->sensor.program_alarms(therm);
return 0;
}
return -EINVAL;
}
int
_nouveau_therm_init(struct nouveau_object *object)
{
struct nouveau_therm *therm = (void *)object;
struct nouveau_therm_priv *priv = (void *)therm;
int ret;
ret = nouveau_subdev_init(&therm->base);
if (ret)
return ret;
if (priv->suspend >= 0) {
/* restore the pwm value only when on manual or auto mode */
if (priv->suspend > 0)
nouveau_therm_fan_set(therm, true, priv->fan->percent);
nouveau_therm_fan_mode(therm, priv->suspend);
}
nouveau_therm_sensor_init(therm);
nouveau_therm_fan_init(therm);
return 0;
}
int
_nouveau_therm_fini(struct nouveau_object *object, bool suspend)
{
struct nouveau_therm *therm = (void *)object;
struct nouveau_therm_priv *priv = (void *)therm;
nouveau_therm_fan_fini(therm, suspend);
nouveau_therm_sensor_fini(therm, suspend);
if (suspend) {
priv->suspend = priv->mode;
priv->mode = NOUVEAU_THERM_CTRL_NONE;
}
return nouveau_subdev_fini(&therm->base, suspend);
}
int
nouveau_therm_create_(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass,
int length, void **pobject)
{
struct nouveau_therm_priv *priv;
int ret;
ret = nouveau_subdev_create_(parent, engine, oclass, 0, "PTHERM",
"therm", length, pobject);
priv = *pobject;
if (ret)
return ret;
nouveau_alarm_init(&priv->alarm, nouveau_therm_alarm);
spin_lock_init(&priv->lock);
spin_lock_init(&priv->sensor.alarm_program_lock);
priv->base.fan_get = nouveau_therm_fan_user_get;
priv->base.fan_set = nouveau_therm_fan_user_set;
priv->base.fan_sense = nouveau_therm_fan_sense;
priv->base.attr_get = nouveau_therm_attr_get;
priv->base.attr_set = nouveau_therm_attr_set;
priv->mode = priv->suspend = -1; /* undefined */
return 0;
}
int
nouveau_therm_preinit(struct nouveau_therm *therm)
{
nouveau_therm_sensor_ctor(therm);
nouveau_therm_ic_ctor(therm);
nouveau_therm_fan_ctor(therm);
nouveau_therm_fan_mode(therm, NOUVEAU_THERM_CTRL_AUTO);
nouveau_therm_sensor_preinit(therm);
return 0;
}
void
_nouveau_therm_dtor(struct nouveau_object *object)
{
struct nouveau_therm_priv *priv = (void *)object;
kfree(priv->fan);
nouveau_subdev_destroy(&priv->base.base);
}
| 28.128 | 77 | 0.737391 | [
"object"
] |
9adec64898dc916f4621d06064a5e2a575547f67 | 525 | h | C | tests/unit/transformer/MockTransformer.h | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 2,753 | 2015-01-02T11:34:13.000Z | 2022-03-25T07:04:27.000Z | tests/unit/transformer/MockTransformer.h | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 2,404 | 2015-01-02T19:31:41.000Z | 2022-03-09T10:58:22.000Z | tests/unit/transformer/MockTransformer.h | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 1,156 | 2015-01-03T01:57:21.000Z | 2022-03-26T01:06:28.000Z | #include <gmock/gmock.h>
#include <shogun/transformer/Transformer.h>
namespace shogun
{
class MockTransformer : public Transformer
{
public:
MOCK_METHOD1(fit, void(std::shared_ptr<Features>));
MOCK_METHOD2(fit, void(std::shared_ptr<Features>, std::shared_ptr<Labels>));
MOCK_METHOD2(transform, std::shared_ptr<Features>(std::shared_ptr<Features>, bool));
MOCK_CONST_METHOD0(train_require_labels, bool());
virtual const char* get_name() const
{
return "MockTransformer";
}
};
} // namespace shogun
| 21 | 86 | 0.733333 | [
"transform"
] |
9adfe691d6348eb52d6efe817d8d0a4ec1afccf4 | 1,040 | h | C | Examples/include/asposecpplib/system/component_model/progress_changed_event_args.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/asposecpplib/system/component_model/progress_changed_event_args.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/asposecpplib/system/component_model/progress_changed_event_args.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | #ifndef __progress_changed_event_args_h__
#define __progress_changed_event_args_h__
#include <system/eventargs.h>
namespace System { namespace ComponentModel {
class ASPOSECPP_SHARED_CLASS ProgressChangedEventArgs : public EventArgs
{
public:
/// Constructor
/// @param progressPercentage The percentage of an asynchronous task that has been completed.
/// @param userState A unique user state.
ProgressChangedEventArgs(int progressPercentage, System::SharedPtr<System::Object> userState)
: m_progressPercentage(progressPercentage)
, m_userState(userState)
{}
/// Gets the asynchronous task progress percentage.
inline int get_ProgressPercentage() const { return m_progressPercentage; }
/// Gets a unique user state.
inline System::SharedPtr<System::Object> get_UserState() const { return m_userState; }
private:
int m_progressPercentage;
System::SharedPtr<System::Object> m_userState;
};
} }
#endif
| 32.5 | 101 | 0.702885 | [
"object"
] |
36edd2263d76c85397b2373e5ac023b691291a75 | 5,370 | h | C | tests/service/src/TestService.h | DaniilOkrug/REST-Server | 853ebaca28b1a7344677165e0c8abf2a8a1193c5 | [
"Apache-2.0"
] | 1 | 2019-12-29T19:36:18.000Z | 2019-12-29T19:36:18.000Z | tests/service/src/TestService.h | DaniilOkrug/REST-Server | 853ebaca28b1a7344677165e0c8abf2a8a1193c5 | [
"Apache-2.0"
] | null | null | null | tests/service/src/TestService.h | DaniilOkrug/REST-Server | 853ebaca28b1a7344677165e0c8abf2a8a1193c5 | [
"Apache-2.0"
] | null | null | null |
#ifndef NGREST_TESTSERVICE_H
#define NGREST_TESTSERVICE_H
#include <string>
#include <list>
#include <vector>
#include <map>
#include <ngrest/common/Nullable.h>
#include <ngrest/common/Service.h>
#include <ngrest/common/Callback.h>
#include <ngrest/common/ObjectModel.h>
namespace ngrest {
struct Test
{
struct Nested
{
bool b;
// Node* node;
};
enum TestEnum
{
Some,
Values,
Here
};
int a;
std::string b;
TestEnum testEnum;
Nested n;
std::list<std::string> ls;
};
struct TestChild: public Test
{
bool isSomething;
};
typedef Test TestTypedef;
typedef std::map<std::string, std::string> StringMap;
typedef std::list<std::string> StringList;
enum ValType
{
Zero,
One,
Two
};
struct TestPtr
{
ngrest::Nullable<int> intValue;
ngrest::Nullable<ValType> enumValue;
ngrest::Nullable<std::string> strValue;
ngrest::Nullable<Test> structValue;
ngrest::Nullable<std::list<std::string>> listValue;
ngrest::Nullable<std::map<int, std::string>> mapValue;
};
// *location: ngrest/test
class TestService: public ngrest::Service
{
public:
bool get() const;
// *resultElement: resultValue
std::string echoSync(const std::string& value);
void echoASync(const std::string& value, ngrest::Callback<const std::string&>& callback);
// default location is: add?a={a}&b={b}
int add(int a, int b);
void set(bool val);
void notify();
// *method: PUT
// *location: theTest
Test test(const Test& arg);
// serialized as array
std::list<std::string> templListStr(const std::list<std::string>& arg);
std::list<int> templList(const std::list<int>& arg);
std::vector<int> templVector(const std::vector<int>& arg);
std::list<Test> templListOfStruct(const std::list<Test>& arg);
std::list<TestTypedef> templListOfTypedef(const std::list<TestTypedef>& arg);
StringList templListOfTypedefList(const StringList& arg);
std::list<std::list<int>> templListList(const std::list<std::list<int>>& arg);
std::list<std::list<std::string>> templListListString(const std::list<std::list<std::string>>& arg);
std::list<std::list<Test>> templListListStruct(const std::list<std::list<Test>>& arg);
std::list<std::list<TestTypedef>> templListListTypedef(const std::list<std::list<TestTypedef>>& arg);
std::list<std::list<std::list<int>>> templListListList(const std::list<std::list<std::list<int>>>& arg);
// serialized as object
std::map<int, std::string> templMapInt(const std::map<int, std::string>& arg);
std::map<ValType, std::string> templMapEnum(const std::map<ValType, std::string>& arg);
std::map<std::string, std::string> templMapStr(const std::map<std::string, std::string>& arg);
std::map<std::string, std::map<std::string, std::string>> templMapStrMapStrStr(const std::map<std::string, std::map<std::string, std::string>>& arg);
StringMap testTypedef(const StringMap& arg);
ValType testEnum(ValType arg);
Test::TestEnum testNestedEnum(Test::TestEnum arg);
Test::Nested testNestedStruct(Test::Nested arg);
ngrest::Nullable<int> ptrInt(ngrest::Nullable<int> arg);
ngrest::Nullable<int> ptrIntConst(const ngrest::Nullable<int>& arg);
ngrest::Nullable<std::string> ptrString(ngrest::Nullable<std::string> arg);
ngrest::Nullable<ValType> ptrEnum(ngrest::Nullable<ValType> arg);
ngrest::Nullable<Test> ptrStruct(ngrest::Nullable<Test> arg);
ngrest::Nullable<std::list<Test>> ptrStructList(ngrest::Nullable<std::list<Test>> arg);
TestPtr ptrNull();
TestPtr ptrNotNull();
TestPtr ptrTest(const TestPtr& arg);
ngrest::Nullable<TestPtr> ptrTestNull(const ngrest::Nullable<TestPtr>& arg);
// inline result element
// *inlineResult: true
bool getInline() const;
// *inlineResult: true
std::string echoSyncInline(const std::string& value);
// *inlineResult: true
int addInline(int a, int b);
// *inlineResult: true
void notifyInline();
// *method: PUT
// *location: theTestInline
// *inlineResult: true
Test testInline(const Test& arg);
// serialized as array
// *inlineResult: true
std::list<std::string> templListStrInline(const std::list<std::string>& arg);
// *inlineResult: true
std::vector<int> templVectorInline(const std::vector<int>& arg);
// *inlineResult: true
StringList templListOfTypedefListInline(const StringList& arg);
// *inlineResult: true
std::list<std::list<int>> templListListInline(const std::list<std::list<int>>& arg);
// *inlineResult: true
std::map<int, std::string> templMapIntInline(const std::map<int, std::string>& arg);
// *inlineResult: true
StringMap testTypedefInline(const StringMap& arg);
// *inlineResult: true
ValType testEnumInline(ValType arg);
// *inlineResult: true
Test::TestEnum testNestedEnumInline(Test::TestEnum arg);
// *inlineResult: true
Test::Nested testNestedStructInline(Test::Nested arg);
// *inlineResult: true
ngrest::Nullable<int> ptrIntInline(ngrest::Nullable<int> arg);
// to test filters
std::string echo(const std::string& value);
// *method: POST
// *location: echo
std::string echoPost(const std::string& value);
};
} // namespace ngrest
#endif // NGREST_TESTSERVICE_H
| 29.505495 | 153 | 0.675233 | [
"object",
"vector"
] |
36edf81a3126362187d01839429c08cc1b0938b7 | 1,405 | h | C | component/oai-amf/src/sbi/amf_server/model/AssignEbiError.h | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/sbi/amf_server/model/AssignEbiError.h | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/sbi/amf_server/model/AssignEbiError.h | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /**
* Namf_Communication
* AMF Communication Service © 2019, 3GPP Organizational Partners (ARIB, ATIS,
* CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 1.1.0.alpha-1
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
/*
* AssignEbiError.h
*
*
*/
#ifndef AssignEbiError_H_
#define AssignEbiError_H_
#include "ProblemDetails_2.h"
#include "AssignEbiFailed.h"
#include <nlohmann/json.hpp>
namespace oai {
namespace amf {
namespace model {
/// <summary>
///
/// </summary>
class AssignEbiError {
public:
AssignEbiError();
virtual ~AssignEbiError();
void validate();
/////////////////////////////////////////////
/// AssignEbiError members
/// <summary>
///
/// </summary>
ProblemDetails_2 getError() const;
void setError(ProblemDetails_2 const& value);
/// <summary>
///
/// </summary>
AssignEbiFailed getFailureDetails() const;
void setFailureDetails(AssignEbiFailed const& value);
friend void to_json(nlohmann::json& j, const AssignEbiError& o);
friend void from_json(const nlohmann::json& j, AssignEbiError& o);
protected:
ProblemDetails_2 m_Error;
AssignEbiFailed m_FailureDetails;
};
} // namespace model
} // namespace amf
} // namespace oai
#endif /* AssignEbiError_H_ */
| 20.661765 | 79 | 0.678292 | [
"model"
] |
36eeeee1b4b5f6dcf58713f8348d06c9ac476204 | 37,808 | c | C | vl/hog.c | unsky/vlfeat | 50e4b5df072d2b135390bd1d621f3a46e4386b69 | [
"BSD-2-Clause"
] | 297 | 2015-02-02T06:48:13.000Z | 2022-03-25T06:53:33.000Z | vl/hog.c | j-bo/vlfeat | bb0cf8d05e240853b9ac04f07ba25e285086fe15 | [
"BSD-2-Clause"
] | 18 | 2015-09-08T14:03:25.000Z | 2020-05-14T18:53:47.000Z | vl/hog.c | j-bo/vlfeat | bb0cf8d05e240853b9ac04f07ba25e285086fe15 | [
"BSD-2-Clause"
] | 109 | 2015-01-23T23:41:13.000Z | 2022-01-11T09:06:47.000Z | /** @file hog.c
** @brief Histogram of Oriented Gradients (HOG) - Definition
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
#include "hog.h"
#include "mathop.h"
#include <string.h>
/**
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@page hog Histogram of Oriented Gradients (HOG) features
@author Andrea Vedaldi
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@ref hog.h implements the Histogram of Oriented Gradients (HOG) features
in the variants of Dalal Triggs @cite{dalal05histograms} and of UOCTTI
@cite{felzenszwalb09object}. Applications include object detection
and deformable object detection.
- @ref hog-overview
- @ref hog-tech
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@section hog-overview Overview
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
HOG is a standard image feature used, among others, in object detection
and deformable object detection. It decomposes the image into square cells
of a given size (typically eight pixels), compute a histogram of oriented
gradient in each cell (similar to @ref sift), and then renormalizes
the cells by looking into adjacent blocks.
VLFeat implements two HOG variants: the original one of Dalal-Triggs
@cite{dalal05histograms} and the one proposed in Felzenszwalb et al.
@cite{felzenszwalb09object}.
In order to use HOG, start by creating a new HOG object, set the desired
parameters, pass a (color or grayscale) image, and read off the results.
@code
VlHog * hog = vl_hog_new(VlHogVariantDalalTriggs, numOrientations, VL_FALSE) ;
vl_hog_put_image(hog, image, height, width, numChannels, cellSize) ;
hogWidth = vl_hog_get_width(hog) ;
hogHeight = vl_hog_get_height(hog) ;
hogDimenison = vl_hog_get_dimension(hog) ;
hogArray = vl_malloc(hogWidth*hogHeight*hogDimension*sizeof(float)) ;
vl_hog_extract(hog, hogArray) ;
vl_hog_delete(hog) ;
@endcode
HOG is a feature array of the dimension returned by ::vl_hog_get_width,
::vl_hog_get_height, with each feature (histogram) having
dimension ::vl_hog_get_dimension. The array is stored in row major order,
with the slowest varying dimension beying the dimension indexing the histogram
elements.
The number of entreis in the histogram as well as their meaning depends
on the HOG variant and is detailed later. However, it is usually
unnecessary to know such details. @ref hog.h provides support for
creating an inconic representation of a HOG feature array:
@code
glyphSize = vl_hog_get_glyph_size(hog) ;
imageHeight = glyphSize * hogArrayHeight ;
imageWidth = glyphSize * hogArrayWidth ;
image = vl_malloc(sizeof(float)*imageWidth*imageHeight) ;
vl_hog_render(hog, image, hogArray) ;
@endcode
It is often convenient to mirror HOG features from left to right. This
can be obtained by mirroring an array of HOG cells, but the content
of each cell must also be rearranged. This can be done by
the permutation obtaiend by ::vl_hog_get_permutation.
Furthermore, @ref hog.h suppots computing HOG features not from
images but from vector fields.
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@section hog-tech Technical details
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
HOG divdes the input image into square cells of size @c cellSize,
fitting as many cells as possible, filling the image domain from
the upper-left corner down to the right one. For each row and column,
the last cell is at least half contained in the image.
More precisely, the number of cells obtained in this manner is:
@code
hogWidth = (width + cellSize/2) / cellSize ;
hogHeight = (height + cellSize/2) / cellSize ;
@endcode
Then the image gradient @f$ \nabla \ell(x,y) @f$
is computed by using central difference (for colour image
the channel with the largest gradient at that pixel is used).
The gradient @f$ \nabla \ell(x,y) @f$ is assigned to one of @c 2*numOrientations orientation in the
range @f$ [0,2\pi) @f$ (see @ref hog-conventions for details).
Contributions are then accumulated by using bilinear interpolation
to four neigbhour cells, as in @ref sift.
This results in an histogram @f$h_d@f$ of dimension
2*numOrientations, called of @e directed orientations
since it accounts for the direction as well as the orientation
of the gradient. A second histogram @f$h_u@f$ of undirected orientations
of half the size is obtained by folding @f$ h_d @f$ into two.
Let a block of cell be a @f$ 2\times 2 @f$ sub-array of cells.
Let the norm of a block be the @f$ l^2 @f$ norm of the stacking of the
respective unoriented histogram. Given a HOG cell, four normalisation
factors are then obtained as the inverse of the norm of the four
blocks that contain the cell.
For the Dalal-Triggs variant, each histogram @f$ h_d @f$ is copied
four times, normalised using the four different normalisation factors,
the four vectors are stacked, saturated at 0.2, and finally stored as the descriptor
of the cell. This results in a @c numOrientations * 4 dimensional
cell descriptor. Blocks are visited from left to right and top to bottom
when forming the final descriptor.
For the UOCCTI descriptor, the same is done for both the undirected
as well as the directed orientation histograms. This would yield
a dimension of @c 4*(2+1)*numOrientations elements, but the resulting
vector is projected down to @c (2+1)*numOrientations elements
by averaging corresponding histogram dimensions. This was shown to
be an algebraic approximation of PCA for descriptors computed on natural
images.
In addition, for the UOCTTI variant the l1 norm of each of the
four l2 normalised undirected histograms is computed and stored
as additional four dimensions, for a total of
@c 4+3*numOrientations dimensions.
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@subsection hog-conventions Conventions
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
The orientation of a gradient is expressed as the angle it forms with the
horizontal axis of the image. Angles are measured clock-wise (as the vertical
image axis points downards), and the null angle corresponds to
an horizontal vector pointing right. The quantized directed
orientations are @f$ \mathrm{k} \pi / \mathrm{numOrientations} @f$, where
@c k is an index that varies in the ingeger
range @f$ \{0, \dots, 2\mathrm{numOrientations} - 1\} @f$.
Note that the orientations capture the orientation of the gradeint;
image edges would be oriented at 90 degrees from these.
**/
/* ---------------------------------------------------------------- */
/** @brief Create a new HOG object
** @param variant HOG descriptor variant.
** @param numOrientations number of distinguished orientations.
** @param transposed wether images are transposed (column major).
** @return the new HOG object.
**
** The function creates a new HOG object to extract descriptors of
** the prescribed @c variant. The angular resolution is set by
** @a numOrientations, which specifies the number of <em>undirected</em>
** orientations. The object can work with column major images
** by setting @a transposed to true.
**/
VlHog *
vl_hog_new (VlHogVariant variant, vl_size numOrientations, vl_bool transposed)
{
vl_index o, k ;
VlHog * self = vl_calloc(1, sizeof(VlHog)) ;
assert(numOrientations >= 1) ;
self->variant = variant ;
self->numOrientations = numOrientations ;
self->glyphSize = 21 ;
self->transposed = transposed ;
self->useBilinearOrientationAssigment = VL_FALSE ;
self->orientationX = vl_malloc(sizeof(float) * self->numOrientations) ;
self->orientationY = vl_malloc(sizeof(float) * self->numOrientations) ;
/*
Create a vector along the center of each orientation bin. These
are used to map gradients to bins. If the image is transposed,
then this can be adjusted here by swapping X and Y in these
vectors.
*/
for(o = 0 ; o < (signed)self->numOrientations ; ++o) {
double angle = o * VL_PI / self->numOrientations ;
if (!self->transposed) {
self->orientationX[o] = (float) cos(angle) ;
self->orientationY[o] = (float) sin(angle) ;
} else {
self->orientationX[o] = (float) sin(angle) ;
self->orientationY[o] = (float) cos(angle) ;
}
}
/*
If the number of orientation is equal to 9, one gets:
Uoccti:: 18 directed orientations + 9 undirected orientations + 4 texture
DalalTriggs:: 9 undirected orientations x 4 blocks.
*/
switch (self->variant) {
case VlHogVariantUoctti:
self->dimension = 3*self->numOrientations + 4 ;
break ;
case VlHogVariantDalalTriggs:
self->dimension = 4*self->numOrientations ;
break ;
default:
assert(0) ;
}
/*
A permutation specifies how to permute elements in a HOG
descriptor to flip it horizontally. Since the first orientation
of index 0 points to the right, this must be swapped with orientation
self->numOrientation that points to the left (for the directed case,
and to itself for the undirected one).
*/
self->permutation = vl_malloc(self->dimension * sizeof(vl_index)) ;
switch (self->variant) {
case VlHogVariantUoctti:
for(o = 0 ; o < (signed)self->numOrientations ; ++o) {
vl_index op = self->numOrientations - o ;
self->permutation[o] = op ;
self->permutation[o + self->numOrientations] = (op + self->numOrientations) % (2*self->numOrientations) ;
self->permutation[o + 2*self->numOrientations] = (op % self->numOrientations) + 2*self->numOrientations ;
}
for (k = 0 ; k < 4 ; ++k) {
/* The texture features correspond to four displaced block around
a cell. These permute with a lr flip as for DalalTriggs. */
vl_index blockx = k % 2 ;
vl_index blocky = k / 2 ;
vl_index q = (1 - blockx) + blocky * 2 ;
self->permutation[k + self->numOrientations * 3] = q + self->numOrientations * 3 ;
}
break ;
case VlHogVariantDalalTriggs:
for(k = 0 ; k < 4 ; ++k) {
/* Find the corresponding block. Blocks are listed in order 1,2,3,4,...
from left to right and top to bottom */
vl_index blockx = k % 2 ;
vl_index blocky = k / 2 ;
vl_index q = (1 - blockx) + blocky * 2 ;
for(o = 0 ; o < (signed)self->numOrientations ; ++o) {
vl_index op = self->numOrientations - o ;
self->permutation[o + k*self->numOrientations] = (op % self->numOrientations) + q*self->numOrientations ;
}
}
break ;
default:
assert(0) ;
}
/*
Create glyphs for representing the HOG features/ filters. The glyphs
are simple bars, oriented orthogonally to the gradients to represent
image edges. If the object is configured to work on transposed image,
the glyphs images are also stored in column-major.
*/
self->glyphs = vl_calloc(self->glyphSize * self->glyphSize * self->numOrientations, sizeof(float)) ;
#define atglyph(x,y,k) self->glyphs[(x) + self->glyphSize * (y) + self->glyphSize * self->glyphSize * (k)]
for (o = 0 ; o < (signed)self->numOrientations ; ++o) {
double angle = fmod(o * VL_PI / self->numOrientations + VL_PI/2, VL_PI) ;
double x2 = self->glyphSize * cos(angle) / 2 ;
double y2 = self->glyphSize * sin(angle) / 2 ;
if (angle <= VL_PI / 4 || angle >= VL_PI * 3 / 4) {
/* along horizontal direction */
double slope = y2 / x2 ;
double offset = (1 - slope) * (self->glyphSize - 1) / 2 ;
vl_index skip = (1 - fabs(cos(angle))) / 2 * self->glyphSize ;
vl_index i, j ;
for (i = skip ; i < (signed)self->glyphSize - skip ; ++i) {
j = vl_round_d(slope * i + offset) ;
if (! self->transposed) {
atglyph(i,j,o) = 1 ;
} else {
atglyph(j,i,o) = 1 ;
}
}
} else {
/* along vertical direction */
double slope = x2 / y2 ;
double offset = (1 - slope) * (self->glyphSize - 1) / 2 ;
vl_index skip = (1 - sin(angle)) / 2 * self->glyphSize ;
vl_index i, j ;
for (j = skip ; j < (signed)self->glyphSize - skip; ++j) {
i = vl_round_d(slope * j + offset) ;
if (! self->transposed) {
atglyph(i,j,o) = 1 ;
} else {
atglyph(j,i,o) = 1 ;
}
}
}
}
return self ;
}
/* ---------------------------------------------------------------- */
/** @brief Delete a HOG object
** @param self HOG object to delete.
**/
void
vl_hog_delete (VlHog * self)
{
if (self->orientationX) {
vl_free(self->orientationX) ;
self->orientationX = NULL ;
}
if (self->orientationY) {
vl_free(self->orientationY) ;
self->orientationY = NULL ;
}
if (self->glyphs) {
vl_free(self->glyphs) ;
self->glyphs = NULL ;
}
if (self->permutation) {
vl_free(self->permutation) ;
self->permutation = NULL ;
}
if (self->hog) {
vl_free(self->hog) ;
self->hog = NULL ;
}
if (self->hogNorm) {
vl_free(self->hogNorm) ;
self->hogNorm = NULL ;
}
vl_free(self) ;
}
/* ---------------------------------------------------------------- */
/** @brief Get HOG glyph size
** @param self HOG object.
** @return size (height and width) of a glyph.
**/
vl_size
vl_hog_get_glyph_size (VlHog const * self)
{
return self->glyphSize ;
}
/* ---------------------------------------------------------------- */
/** @brief Get HOG left-right flip permutation
** @param self HOG object.
** @return left-right permutation.
**
** The function returns a pointer to an array @c permutation of ::vl_hog_get_dimension
** elements. Given a HOG descriptor (for a cell) @c hog, which is also
** a vector of ::vl_hog_get_dimension elements, the
** descriptor obtained for the same image flipped horizotnally is
** given by <code>flippedHog[i] = hog[permutation[i]]</code>.
**/
vl_index const *
vl_hog_get_permutation (VlHog const * self)
{
return self->permutation ;
}
/* ---------------------------------------------------------------- */
/** @brief Turn bilinear interpolation of assignments on or off
** @param self HOG object.
** @param x @c true if orientations should be assigned with bilinear interpolation.
**/
void
vl_hog_set_use_bilinear_orientation_assignments (VlHog * self, vl_bool x) {
self->useBilinearOrientationAssigment = x ;
}
/** @brief Tell whether assignments use bilinear interpolation or not
** @param self HOG object.
** @return @c true if orientations are be assigned with bilinear interpolation.
**/
vl_bool
vl_hog_get_use_bilinear_orientation_assignments (VlHog const * self) {
return self->useBilinearOrientationAssigment ;
}
/* ---------------------------------------------------------------- */
/** @brief Render a HOG descriptor to a glyph image
** @param self HOG object.
** @param image glyph image (output).
** @param descriptor HOG descriptor.
** @param width HOG descriptor width.
** @param height HOG descriptor height.
**
** The function renders the HOG descriptor or filter
** @a descriptor as an image (for visualization) and stores the result in
** the buffer @a image. This buffer
** must be an array of dimensions @c width*glyphSize
** by @c height*glyphSize elements, where @c glyphSize is
** obtained from ::vl_hog_get_glyph_size and is the size in pixels
** of the image element used to represent the descriptor of one
** HOG cell.
**/
void
vl_hog_render (VlHog const * self,
float * image,
float const * descriptor,
vl_size width,
vl_size height)
{
vl_index x, y, k, cx, cy ;
vl_size hogStride = width * height ;
assert(self) ;
assert(image) ;
assert(descriptor) ;
assert(width > 0) ;
assert(height > 0) ;
for (y = 0 ; y < (signed)height ; ++y) {
for (x = 0 ; x < (signed)width ; ++x) {
float minWeight = 0 ;
float maxWeight = 0 ;
for (k = 0 ; k < (signed)self->numOrientations ; ++k) {
float weight ;
float const * glyph = self->glyphs + k * (self->glyphSize*self->glyphSize) ;
float * glyphImage = image + self->glyphSize * x + y * width * (self->glyphSize*self->glyphSize) ;
switch (self->variant) {
case VlHogVariantUoctti:
weight =
descriptor[k * hogStride] +
descriptor[(k + self->numOrientations) * hogStride] +
descriptor[(k + 2 * self->numOrientations) * hogStride] ;
break ;
case VlHogVariantDalalTriggs:
weight =
descriptor[k * hogStride] +
descriptor[(k + self->numOrientations) * hogStride] +
descriptor[(k + 2 * self->numOrientations) * hogStride] +
descriptor[(k + 3 * self->numOrientations) * hogStride] ;
break ;
default:
abort() ;
}
maxWeight = VL_MAX(weight, maxWeight) ;
minWeight = VL_MIN(weight, minWeight);
for (cy = 0 ; cy < (signed)self->glyphSize ; ++cy) {
for (cx = 0 ; cx < (signed)self->glyphSize ; ++cx) {
*glyphImage++ += weight * (*glyph++) ;
}
glyphImage += (width - 1) * self->glyphSize ;
}
} /* next orientation */
{
float * glyphImage = image + self->glyphSize * x + y * width * (self->glyphSize*self->glyphSize) ;
for (cy = 0 ; cy < (signed)self->glyphSize ; ++cy) {
for (cx = 0 ; cx < (signed)self->glyphSize ; ++cx) {
float value = *glyphImage ;
*glyphImage++ = VL_MAX(minWeight, VL_MIN(maxWeight, value)) ;
}
glyphImage += (width - 1) * self->glyphSize ;
}
}
++ descriptor ;
} /* next column of cells (x) */
} /* next row of cells (y) */
}
/* ---------------------------------------------------------------- */
/** @brief Get the dimension of the HOG features
** @param self HOG object.
** @return imension of a HOG cell descriptors.
**/
vl_size
vl_hog_get_dimension (VlHog const * self)
{
return self->dimension ;
}
/** @brief Get the width of the HOG cell array
** @param self HOG object.
** @return number of HOG cells in the horizontal direction.
**/
vl_size
vl_hog_get_width (VlHog * self)
{
return self->hogWidth ;
}
/** @brief Get the height of the HOG cell array
** @param self HOG object.
** @return number of HOG cells in the vertical direction.
**/
vl_size
vl_hog_get_height (VlHog * self)
{
return self->hogHeight ;
}
/* ---------------------------------------------------------------- */
/** @internal @brief Prepare internal buffers
** @param self HOG object.
** @param width image width.
** @param height image height.
** @param cellSize size of a HOG cell.
**/
static void
vl_hog_prepare_buffers (VlHog * self, vl_size width, vl_size height, vl_size cellSize)
{
vl_size hogWidth = (width + cellSize/2) / cellSize ;
vl_size hogHeight = (height + cellSize/2) / cellSize ;
assert(width > 3) ;
assert(height > 3) ;
assert(hogWidth > 0) ;
assert(hogHeight > 0) ;
if (self->hog &&
self->hogWidth == hogWidth &&
self->hogHeight == hogHeight) {
/* a suitable buffer is already allocated */
memset(self->hog, 0, sizeof(float) * hogWidth * hogHeight * self->numOrientations * 2) ;
memset(self->hogNorm, 0, sizeof(float) * hogWidth * hogHeight) ;
return ;
}
if (self->hog) {
vl_free(self->hog) ;
self->hog = NULL ;
}
if (self->hogNorm) {
vl_free(self->hogNorm) ;
self->hogNorm = NULL ;
}
self->hog = vl_calloc(hogWidth * hogHeight * self->numOrientations * 2, sizeof(float)) ;
self->hogNorm = vl_calloc(hogWidth * hogHeight, sizeof(float)) ;
self->hogWidth = hogWidth ;
self->hogHeight = hogHeight ;
}
/* ---------------------------------------------------------------- */
/** @brief Process features starting from an image
** @param self HOG object.
** @param image image to process.
** @param width image width.
** @param height image height.
** @param numChannels number of image channles.
** @param cellSize size of a HOG cell.
**
** The buffer @c hog must be a three-dimensional array.
** The first two dimensions are @c (width + cellSize/2)/cellSize and
** @c (height + cellSize/2)/cellSize, where divisions are integer.
** This is approximately @c width/cellSize and @c height/cellSize,
** adjusted so that the last cell is at least half contained in the
** image.
**
** The image @c width and @c height must be not smaller than three
** pixels and not smaller than @c cellSize.
**/
void
vl_hog_put_image (VlHog * self,
float const * image,
vl_size width, vl_size height, vl_size numChannels,
vl_size cellSize)
{
vl_size hogStride ;
vl_size channelStride = width * height ;
vl_index x, y ;
vl_uindex k ;
assert(self) ;
assert(image) ;
/* clear features */
vl_hog_prepare_buffers(self, width, height, cellSize) ;
hogStride = self->hogWidth * self->hogHeight ;
#define at(x,y,k) (self->hog[(x) + (y) * self->hogWidth + (k) * hogStride])
/* compute gradients and map the to HOG cells by bilinear interpolation */
for (y = 1 ; y < (signed)height - 1 ; ++y) {
for (x = 1 ; x < (signed)width - 1 ; ++x) {
float gradx = 0 ;
float grady = 0 ;
float grad ;
float orientationWeights [2] = {0,0} ;
vl_index orientationBins [2] = {-1,-1} ;
vl_index orientation = 0 ;
float hx, hy, wx1, wx2, wy1, wy2 ;
vl_index binx, biny, o ;
/*
Compute the gradient at (x,y). The image channel with
the maximum gradient at each location is selected.
*/
{
float const * iter = image + y * width + x ;
float grad2 = 0 ;
for (k = 0 ; k < numChannels ; ++k) {
float gradx_ = *(iter + 1) - *(iter - 1) ;
float grady_ = *(iter + width) - *(iter - width) ;
float grad2_ = gradx_ * gradx_ + grady_ * grady_ ;
if (grad2_ > grad2) {
gradx = gradx_ ;
grady = grady_ ;
grad2 = grad2_ ;
}
iter += channelStride ;
}
grad = sqrtf(grad2) ;
gradx /= VL_MAX(grad, 1e-10) ;
grady /= VL_MAX(grad, 1e-10) ;
}
/*
Map the gradient to the closest and second closets orientation bins.
There are numOrientations orientation in the interval [0,pi).
The next numOriantations are the symmetric ones, for a total
of 2*numOrientation directed orientations.
*/
for (k = 0 ; k < self->numOrientations ; ++k) {
float orientationScore_ = gradx * self->orientationX[k] + grady * self->orientationY[k] ;
vl_index orientationBin_ = k ;
if (orientationScore_ < 0) {
orientationScore_ = - orientationScore_ ;
orientationBin_ += self->numOrientations ;
}
if (orientationScore_ > orientationWeights[0]) {
orientationBins[1] = orientationBins[0] ;
orientationWeights[1] = orientationWeights[0] ;
orientationBins[0] = orientationBin_ ; ;
orientationWeights[0] = orientationScore_ ;
} else if (orientationScore_ > orientationWeights[1]) {
orientationBins[1] = orientationBin_ ;
orientationWeights[1] = orientationScore_ ;
}
}
if (self->useBilinearOrientationAssigment) {
/* min(1.0,...) guards against small overflows causing NaNs */
float angle0 = acosf(VL_MIN(orientationWeights[0],1.0)) ;
orientationWeights[1] = angle0 / (VL_PI / self->numOrientations) ;
orientationWeights[0] = 1 - orientationWeights[1] ;
} else {
orientationWeights[0] = 1 ;
orientationBins[1] = -1 ;
}
for (o = 0 ; o < 2 ; ++o) {
/*
Accumulate the gradient. hx is the distance of the
pixel x to the cell center at its left, in units of cellSize.
With this parametrixation, a pixel on the cell center
has hx = 0, which gradually increases to 1 moving to the next
center.
*/
orientation = orientationBins[o] ;
if (orientation < 0) continue ;
/* (x - (w-1)/2) / w = (x + 0.5)/w - 0.5 */
hx = (x + 0.5) / cellSize - 0.5 ;
hy = (y + 0.5) / cellSize - 0.5 ;
binx = vl_floor_f(hx) ;
biny = vl_floor_f(hy) ;
wx2 = hx - binx ;
wy2 = hy - biny ;
wx1 = 1.0 - wx2 ;
wy1 = 1.0 - wy2 ;
wx1 *= orientationWeights[o] ;
wx2 *= orientationWeights[o] ;
wy1 *= orientationWeights[o] ;
wy2 *= orientationWeights[o] ;
/*VL_PRINTF("%d %d - %d %d %f %f - %f %f %f %f - %d \n ",x,y,binx,biny,hx,hy,wx1,wx2,wy1,wy2,o);*/
if (binx >= 0 && biny >=0) {
at(binx,biny,orientation) += grad * wx1 * wy1 ;
}
if (binx < (signed)self->hogWidth - 1 && biny >=0) {
at(binx+1,biny,orientation) += grad * wx2 * wy1 ;
}
if (binx < (signed)self->hogWidth - 1 && biny < (signed)self->hogHeight - 1) {
at(binx+1,biny+1,orientation) += grad * wx2 * wy2 ;
}
if (binx >= 0 && biny < (signed)self->hogHeight - 1) {
at(binx,biny+1,orientation) += grad * wx1 * wy2 ;
}
} /* next o */
} /* next x */
} /* next y */
}
/* ---------------------------------------------------------------- */
/** @brief Process features starting from a field in polar notation
** @param self HOG object.
** @param modulus image gradient modulus.
** @param angle image gradient angle.
** @param directed wrap the gradient angles at 2pi (directed) or pi (undirected).
** @param width image width.
** @param height image height.
** @param cellSize size of a HOG cell.
**
** The function behaves like ::vl_hog_put_image, but foregoes the internal
** computation of the gradient field, allowing the user to specify
** their own. Angles are measure clockwise, the y axis pointing downwards,
** starting from the x axis (pointing to the right).
**/
void vl_hog_put_polar_field (VlHog * self,
float const * modulus,
float const * angle,
vl_bool directed,
vl_size width, vl_size height,
vl_size cellSize)
{
vl_size hogStride ;
vl_index x, y, o ;
vl_index period = self->numOrientations * (directed ? 2 : 1) ;
double angleStep = VL_PI / self->numOrientations ;
assert(self) ;
assert(modulus) ;
assert(angle) ;
/* clear features */
vl_hog_prepare_buffers(self, width, height, cellSize) ;
hogStride = self->hogWidth * self->hogHeight ;
#define at(x,y,k) (self->hog[(x) + (y) * self->hogWidth + (k) * hogStride])
#define atNorm(x,y) (self->hogNorm[(x) + (y) * self->hogWidth])
/* fill HOG cells from gradient field */
for (y = 0 ; y < (signed)height ; ++y) {
for (x = 0 ; x < (signed)width ; ++x) {
float ho, hx, hy, wo1, wo2, wx1, wx2, wy1, wy2 ;
vl_index bino, binx, biny ;
float orientationWeights [2] = {0,0} ;
vl_index orientationBins [2] = {-1,-1} ;
vl_index orientation = 0 ;
float thisAngle = *angle++ ;
float thisModulus = *modulus++ ;
if (thisModulus <= 0.0f) continue ;
/* (x - (w-1)/2) / w = (x + 0.5)/w - 0.5 */
ho = (float)thisAngle / angleStep ;
bino = vl_floor_f(ho) ;
wo2 = ho - bino ;
wo1 = 1.0f - wo2 ;
while (bino < 0) { bino += self->numOrientations * 2 ; }
if (self->useBilinearOrientationAssigment) {
orientationBins[0] = bino % period ;
orientationBins[1] = (bino + 1) % period ;
orientationWeights[0] = wo1 ;
orientationWeights[1] = wo2 ;
} else {
orientationBins[0] = (bino + ((wo1 > wo2) ? 0 : 1)) % period ;
orientationWeights[0] = 1 ;
orientationBins[1] = -1 ;
}
for (o = 0 ; o < 2 ; ++o) {
/*
Accumulate the gradient. hx is the distance of the
pixel x to the cell center at its left, in units of cellSize.
With this parametrixation, a pixel on the cell center
has hx = 0, which gradually increases to 1 moving to the next
center.
*/
orientation = orientationBins[o] ;
if (orientation < 0) continue ;
hx = (x + 0.5) / cellSize - 0.5 ;
hy = (y + 0.5) / cellSize - 0.5 ;
binx = vl_floor_f(hx) ;
biny = vl_floor_f(hy) ;
wx2 = hx - binx ;
wy2 = hy - biny ;
wx1 = 1.0 - wx2 ;
wy1 = 1.0 - wy2 ;
wx1 *= orientationWeights[o] ;
wx2 *= orientationWeights[o] ;
wy1 *= orientationWeights[o] ;
wy2 *= orientationWeights[o] ;
/*VL_PRINTF("%d %d - %d %d %f %f - %f %f %f %f - %d \n ",x,y,binx,biny,hx,hy,wx1,wx2,wy1,wy2,o);*/
if (binx >= 0 && biny >=0) {
at(binx,biny,orientation) += thisModulus * wx1 * wy1 ;
}
if (binx < (signed)self->hogWidth - 1 && biny >=0) {
at(binx+1,biny,orientation) += thisModulus * wx2 * wy1 ;
}
if (binx < (signed)self->hogWidth - 1 && biny < (signed)self->hogHeight - 1) {
at(binx+1,biny+1,orientation) += thisModulus * wx2 * wy2 ;
}
if (binx >= 0 && biny < (signed)self->hogHeight - 1) {
at(binx,biny+1,orientation) += thisModulus * wx1 * wy2 ;
}
} /* next o */
} /* next x */
} /* next y */
}
/* ---------------------------------------------------------------- */
/** @brief Extract HOG features
** @param self HOG object.
** @param features HOG features (output).
**
** This method is called after ::vl_hog_put_image or ::vl_hog_put_polar_field
** in order to retrieve the computed HOG features. The buffer @c features must have the dimensions returned by
** ::vl_hog_get_width, ::vl_hog_get_height, and ::vl_hog_get_dimension.
**/
void
vl_hog_extract (VlHog * self, float * features)
{
vl_index x, y ;
vl_uindex k ;
vl_size hogStride = self->hogWidth * self->hogHeight ;
assert(features) ;
#define at(x,y,k) (self->hog[(x) + (y) * self->hogWidth + (k) * hogStride])
#define atNorm(x,y) (self->hogNorm[(x) + (y) * self->hogWidth])
/*
Computes the squared L2 norm of each HOG cell. This is the norm of the
undirected orientation histogram, counting only numOrientations. This
histogram is obtained by folding the 2*numOrientations directed
orientations that are computed.
*/
{
float const * iter = self->hog ;
for (k = 0 ; k < self->numOrientations ; ++k) {
float * niter = self->hogNorm ;
float * niterEnd = self->hogNorm + self->hogWidth * self->hogHeight ;
vl_size stride = self->hogWidth*self->hogHeight*self->numOrientations ;
while (niter != niterEnd) {
float h1 = *iter ;
float h2 = *(iter + stride) ;
float h = h1 + h2 ;
*niter += h * h ;
niter++ ;
iter++ ;
}
}
}
/*
HOG block-normalisation. For each cell, there are four 2x2 blocks
covering it. For example, the cell number 5 in the following scheme
is covered by the four blocks 1245, 2356, 4578, 5689.
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
| 7 | 8 | 9 |
+---+---+---+
In the Dalal-Triggs implementation, one forms all possible 2x2 blocks
of cells, computes a descriptor vector for each by stacking the corresponding
2x2 HOG cells, and L2 normalizes (and truncates) the result.
Thus each HOG cell appears in four blocks. These are then decomposed
again to produce descriptors for each cell. Each descriptor is simply
the stacking of the portion of each block descriptor that arised
from that cell. This process result in a descriptor
of each cell which contains four copies of the original HOG,
with four different normalization factors.
@remark By stacking together the cell descriptors for a large retangular block
of cells, one effectively stacks together the block descriptors of
an equal number of blocks (except for the boundaries, for which
blocks are only partially included). Since blocks are L2 normalized
(up to truncation), this implies that the L2 norm of the resulting
vector is approximately equal to the area of the region.
*/
{
float const * iter = self->hog ;
for (y = 0 ; y < (signed)self->hogHeight ; ++y) {
for (x = 0 ; x < (signed)self->hogWidth ; ++x) {
/* norm of upper-left, upper-right, ... blocks */
vl_index xm = VL_MAX(x - 1, 0) ;
vl_index xp = VL_MIN(x + 1, (signed)self->hogWidth - 1) ;
vl_index ym = VL_MAX(y - 1, 0) ;
vl_index yp = VL_MIN(y + 1, (signed)self->hogHeight - 1) ;
double norm1 = atNorm(xm,ym) ;
double norm2 = atNorm(x,ym) ;
double norm3 = atNorm(xp,ym) ;
double norm4 = atNorm(xm,y) ;
double norm5 = atNorm(x,y) ;
double norm6 = atNorm(xp,y) ;
double norm7 = atNorm(xm,yp) ;
double norm8 = atNorm(x,yp) ;
double norm9 = atNorm(xp,yp) ;
double factor1, factor2, factor3, factor4 ;
double t1 = 0 ;
double t2 = 0 ;
double t3 = 0 ;
double t4 = 0 ;
float * oiter = features + x + self->hogWidth * y ;
/* each factor is the inverse of the l2 norm of one of the 2x2 blocks surrounding
cell x,y */
#if 0
if (self->transposed) {
/* if the image is transposed, y and x are swapped */
factor1 = 1.0 / VL_MAX(sqrt(norm1 + norm2 + norm4 + norm5), 1e-10) ;
factor3 = 1.0 / VL_MAX(sqrt(norm2 + norm3 + norm5 + norm6), 1e-10) ;
factor2 = 1.0 / VL_MAX(sqrt(norm4 + norm5 + norm7 + norm8), 1e-10) ;
factor4 = 1.0 / VL_MAX(sqrt(norm5 + norm6 + norm8 + norm9), 1e-10) ;
} else {
factor1 = 1.0 / VL_MAX(sqrt(norm1 + norm2 + norm4 + norm5), 1e-10) ;
factor2 = 1.0 / VL_MAX(sqrt(norm2 + norm3 + norm5 + norm6), 1e-10) ;
factor3 = 1.0 / VL_MAX(sqrt(norm4 + norm5 + norm7 + norm8), 1e-10) ;
factor4 = 1.0 / VL_MAX(sqrt(norm5 + norm6 + norm8 + norm9), 1e-10) ;
}
#else
/* as implemented in UOCTTI code */
if (self->transposed) {
/* if the image is transposed, y and x are swapped */
factor1 = 1.0 / sqrt(norm1 + norm2 + norm4 + norm5 + 1e-4) ;
factor3 = 1.0 / sqrt(norm2 + norm3 + norm5 + norm6 + 1e-4) ;
factor2 = 1.0 / sqrt(norm4 + norm5 + norm7 + norm8 + 1e-4) ;
factor4 = 1.0 / sqrt(norm5 + norm6 + norm8 + norm9 + 1e-4) ;
} else {
factor1 = 1.0 / sqrt(norm1 + norm2 + norm4 + norm5 + 1e-4) ;
factor2 = 1.0 / sqrt(norm2 + norm3 + norm5 + norm6 + 1e-4) ;
factor3 = 1.0 / sqrt(norm4 + norm5 + norm7 + norm8 + 1e-4) ;
factor4 = 1.0 / sqrt(norm5 + norm6 + norm8 + norm9 + 1e-4) ;
}
#endif
for (k = 0 ; k < self->numOrientations ; ++k) {
double ha = iter[hogStride * k] ;
double hb = iter[hogStride * (k + self->numOrientations)] ;
double hc ;
double ha1 = factor1 * ha ;
double ha2 = factor2 * ha ;
double ha3 = factor3 * ha ;
double ha4 = factor4 * ha ;
double hb1 = factor1 * hb ;
double hb2 = factor2 * hb ;
double hb3 = factor3 * hb ;
double hb4 = factor4 * hb ;
double hc1 = ha1 + hb1 ;
double hc2 = ha2 + hb2 ;
double hc3 = ha3 + hb3 ;
double hc4 = ha4 + hb4 ;
ha1 = VL_MIN(0.2, ha1) ;
ha2 = VL_MIN(0.2, ha2) ;
ha3 = VL_MIN(0.2, ha3) ;
ha4 = VL_MIN(0.2, ha4) ;
hb1 = VL_MIN(0.2, hb1) ;
hb2 = VL_MIN(0.2, hb2) ;
hb3 = VL_MIN(0.2, hb3) ;
hb4 = VL_MIN(0.2, hb4) ;
hc1 = VL_MIN(0.2, hc1) ;
hc2 = VL_MIN(0.2, hc2) ;
hc3 = VL_MIN(0.2, hc3) ;
hc4 = VL_MIN(0.2, hc4) ;
t1 += hc1 ;
t2 += hc2 ;
t3 += hc3 ;
t4 += hc4 ;
switch (self->variant) {
case VlHogVariantUoctti :
ha = 0.5 * (ha1 + ha2 + ha3 + ha4) ;
hb = 0.5 * (hb1 + hb2 + hb3 + hb4) ;
hc = 0.5 * (hc1 + hc2 + hc3 + hc4) ;
*oiter = ha ;
*(oiter + hogStride * self->numOrientations) = hb ;
*(oiter + 2 * hogStride * self->numOrientations) = hc ;
break ;
case VlHogVariantDalalTriggs :
*oiter = hc1 ;
*(oiter + hogStride * self->numOrientations) = hc2 ;
*(oiter + 2 * hogStride * self->numOrientations) = hc3 ;
*(oiter + 3 * hogStride * self->numOrientations) = hc4 ;
break ;
}
oiter += hogStride ;
} /* next orientation */
switch (self->variant) {
case VlHogVariantUoctti :
oiter += 2 * hogStride * self->numOrientations ;
*oiter = (1.0f/sqrtf(18.0f)) * t1 ; oiter += hogStride ;
*oiter = (1.0f/sqrtf(18.0f)) * t2 ; oiter += hogStride ;
*oiter = (1.0f/sqrtf(18.0f)) * t3 ; oiter += hogStride ;
*oiter = (1.0f/sqrtf(18.0f)) * t4 ; oiter += hogStride ;
break ;
case VlHogVariantDalalTriggs :
break ;
}
++iter ;
} /* next x */
} /* next y */
} /* block normalization */
}
| 35.533835 | 115 | 0.59006 | [
"render",
"object",
"vector"
] |
36f01de8f3eedba803d91b0325498c942775ab8a | 1,978 | h | C | ffmpeg/frame.h | rkb-1/quad | 66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e | [
"Apache-2.0"
] | 64 | 2017-01-18T15:12:05.000Z | 2022-02-16T08:28:11.000Z | ffmpeg/frame.h | rkb-1/quad | 66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e | [
"Apache-2.0"
] | 2 | 2021-02-11T14:39:38.000Z | 2021-10-03T16:49:57.000Z | ffmpeg/frame.h | rkb-1/quad | 66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e | [
"Apache-2.0"
] | 14 | 2021-01-11T09:48:34.000Z | 2021-12-16T16:20:35.000Z | // Copyright 2020 Josh Pieper, jjp@pobox.com.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
extern "C" {
#include <libavutil/frame.h>
}
#include <utility>
#include <Eigen/Core>
#include "ffmpeg/error.h"
#include "ffmpeg/ref_base.h"
namespace mjmech {
namespace ffmpeg {
class Frame {
public:
/// Allocate an empty frame with no backing data. This is required
/// for certain APIs which need an empty object to dump into.
Frame() {
frame_ = av_frame_alloc();
}
~Frame() {
av_frame_free(&frame_);
}
Frame(const Frame&) = delete;
Frame& operator=(const Frame&) = delete;
class Ref : public RefBase<AVFrame, Ref> {
public:
using RefBase<AVFrame, Ref>::RefBase;
void reset() {
if (value_) {
av_frame_unref(value_);
}
value_ = nullptr;
}
};
/// Allocate a Frame of given size and alignment.
///
/// @param align == 0 means select based on platform
Ref Allocate(AVPixelFormat format, Eigen::Vector2i size, int align = 1) {
frame_->format = format;
frame_->width = size.x();
frame_->height = size.y();
ErrorCheck(av_frame_get_buffer(frame_, align));
return Ref::MakeInternal(frame_);
}
Eigen::Vector2i size() const {
return {frame_->width, frame_->height};
}
AVPixelFormat format() const {
return static_cast<AVPixelFormat>(frame_->format);
}
AVFrame* get() { return frame_; }
private:
AVFrame* frame_ = nullptr;
};
}
}
| 23.270588 | 75 | 0.673407 | [
"object"
] |
36f06c55b92a157cd553544e96641a49c89cc0bf | 45,576 | h | C | dlib/dnn/tensor_tools.h | rageappliedgame/EmotionDetectionCPP-RAGE-Architecture | 073c64298a37b96b69bcf595fa902a6a9137de18 | [
"Apache-2.0"
] | null | null | null | dlib/dnn/tensor_tools.h | rageappliedgame/EmotionDetectionCPP-RAGE-Architecture | 073c64298a37b96b69bcf595fa902a6a9137de18 | [
"Apache-2.0"
] | null | null | null | dlib/dnn/tensor_tools.h | rageappliedgame/EmotionDetectionCPP-RAGE-Architecture | 073c64298a37b96b69bcf595fa902a6a9137de18 | [
"Apache-2.0"
] | 2 | 2019-02-21T18:19:37.000Z | 2020-04-21T18:03:37.000Z | // Copyright (C) 2015 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_TeNSOR_TOOLS_H_
#define DLIB_TeNSOR_TOOLS_H_
#include "tensor.h"
#include "cudnn_dlibapi.h"
#include "cublas_dlibapi.h"
#include "curand_dlibapi.h"
#include "cpu_dlib.h"
#include "cuda_dlib.h"
#include "../rand.h"
#include <memory>
namespace dlib
{
bool dnn_prefer_fastest_algorithms();
void set_dnn_prefer_fastest_algorithms();
void set_dnn_prefer_smallest_algorithms();
}
namespace dlib { namespace tt
{
// ----------------------------------------------------------------------------------------
void gemm (
float beta,
tensor& dest,
float alpha,
const tensor& lhs,
bool trans_lhs,
const tensor& rhs,
bool trans_rhs
);
/*!
requires
- The dimensions of lhs and rhs must be compatible for matrix multiplication.
In particular:
- Let L == trans_lhs ? trans(mat(lhs)) : mat(lhs)
- Let R == trans_rhs ? trans(mat(rhs)) : mat(rhs)
- Let D == mat(dest)
- D.nr() == L.nr() && D.nc() == R.nc()
(i.e. dest must be preallocated and have the correct output dimensions)
- L.nc() == R.nr()
ensures
- performs: dest = alpha*L*R + beta*mat(dest)
!*/
// ----------------------------------------------------------------------------------------
class tensor_rand
{
/*!
WHAT THIS OBJECT REPRESENTS
This is a tool for filling a tensor with random numbers.
Note that the sequence of random numbers output by this object is different
when dlib is compiled with DLIB_USE_CUDA. So you should not write code
that depends on any specific sequence of numbers coming out of a
tensor_rand.
!*/
public:
// not copyable
tensor_rand(const tensor_rand&) = delete;
tensor_rand& operator=(const tensor_rand&) = delete;
tensor_rand() : tensor_rand(0) {}
tensor_rand(unsigned long long seed);
void fill_gaussian (
tensor& data,
float mean,
float stddev
);
/*!
requires
- data.size()%2 == 0
ensures
- Fills data with random numbers drawn from a Gaussian distribution
with the given mean and standard deviation.
!*/
void fill_uniform (
tensor& data
);
/*!
ensures
- Fills data with uniform random numbers in the range (0.0, 1.0].
!*/
#ifdef DLIB_USE_CUDA
cuda::curand_generator rnd;
#else
dlib::rand rnd;
#endif
};
// ----------------------------------------------------------------------------------------
void multiply (
bool add_to,
tensor& dest,
const tensor& src1,
const tensor& src2
);
/*!
requires
- dest.k() == src1.k() == src2.k()
- dest.nr() == src1.nr() == src2.nr()
- dest.nc() == src1.nc() == src2.nc()
- dest.num_samples(), src1.num_samples(), and src2.num_samples() must each
either be 1 or whichever ones aren't equal to 1 must have the same values.
ensures
- let MD = max(dest.num_samples(), src1.num_samples(), src2.num_samples)
- This function pointwise multiplies src1 with src2 and stores the result into
#dest. However, how the multiplication happens depends on the dimensions of
the tensors. First, when src1 and src2 are multiplied together, if either
has a num_samples() dimension that is != MD, then it is first replicated to
produce a tensor with num_samples()==MD dimensions and then they are
pointwise multiplied together.
Second, if dest.num_samples()==1, then after the pointwise multiplication of
src1 with src2, the result has its samples summed to produce an output tensor
with num_samples()==1 which is then assigned to #dest.
- if (add_to) then
- Instead of assigning the result to dest, this function adds the result to dest.
!*/
void multiply_conv (
bool add_to,
tensor& dest,
const tensor& src1,
const tensor& src2
);
/*!
requires
- if (have_same_dimensions(dest, src1) == true) then
- src2.num_samples() == 1
- src2.nr() == 1
- src2.nc() == 1
- src2.k() == src1.k()
- else
- have_same_dimensions(src1, src2) == true)
- dest.num_samples() == 1
- dest.nr() == 1
- dest.nc() == 1
- dest.k() == src1.k()
ensures
- Performs #dest == src1*src2
In particular, if the elements of dest, src1, and src2 were indexed by (n,k,r,c) then
we would have:
- if (have_same_dimensions(dest,src1)) then
#dest(n,k,r,c) == src1(n,k,r,c)*src2(k)
- else
#dest(k) == sum over {n,r,c} of src1(n,k,r,c)*src2(n,k,r,c)
- if (add_to) then
- Instead of assigning the result to dest, this function adds the result to dest.
!*/
// ----------------------------------------------------------------------------------------
void affine_transform(
tensor& dest,
const tensor& src,
const float A,
const float B
);
/*!
requires
- dest.size()==src.size()
ensures
- #dest == A*src + B
!*/
void affine_transform(
tensor& dest,
const tensor& src,
const float A
);
/*!
requires
- dest.size()==src.size()
ensures
- #dest == A*src
!*/
void affine_transform(
tensor& dest,
const tensor& src1,
const tensor& src2,
const float A,
const float B,
const float C
);
/*!
requires
- dest.size()==src1.size()
- dest.size()==src2.size()
ensures
- #dest == A*src1 + B*src2 + C
!*/
void affine_transform(
tensor& dest,
const tensor& src1,
const tensor& src2,
const float A,
const float B
);
/*!
requires
- dest.size()==src1.size()
- dest.size()==src2.size()
ensures
- #dest == A*src1 + B*src2
!*/
void affine_transform(
tensor& dest,
const tensor& src1,
const tensor& src2,
const tensor& src3,
const float A,
const float B,
const float C,
const float D
);
/*!
requires
- dest.size()==src1.size()
- dest.size()==src2.size()
- dest.size()==src3.size()
ensures
- #dest == A*src1 + B*src2 + C*src3 + D
!*/
void affine_transform(
tensor& dest,
const tensor& src1,
const tensor& src2,
const tensor& src3,
const float A,
const float B,
const float C
);
/*!
requires
- dest.size()==src1.size()
- dest.size()==src2.size()
- dest.size()==src3.size()
ensures
- #dest == A*src1 + B*src2 + C*src3
!*/
void affine_transform_range(
size_t begin,
size_t end,
tensor& dest,
const tensor& src1,
const tensor& src2,
const tensor& src3,
const float A,
const float B,
const float C
);
/*!
requires
- dest.size()==src1.size()
- dest.size()==src2.size()
- dest.size()==src3.size()
- begin <= end <= dest.size()
ensures
- This function operates much like
affine_transform(dest,src1,src2,src3,A,B,C,0), except that it runs over only
the half open range [begin,end) rather than processing the entire tensor.
Specifically, it does this:
- for i in the range [begin, end):
- #dest.host()[i] == A*src1.host()[i] + B*src2.host()[i] + C*src3.host()[i]
!*/
// ----------------------------------------------------------------------------------------
void affine_transform(
tensor& dest,
const tensor& src,
const tensor& A,
const tensor& B
);
/*!
requires
- have_same_dimensions(dest,src) == true
- if (A.num_samples() == 1) then
- B.num_samples() == 1
- else
- A.num_samples() == src.num_samples()
- B.num_samples() == src.num_samples()
- A.nr() == B.nr() == src.nr()
- A.nc() == B.nc() == src.nc()
- A.k() == B.k() == src.k()
ensures
- if (A.num_samples() == 1) then
- #dest == A*src + B
(done for each sample in src)
- else
- for all valid i:
- #dest.host()[i] == A.host()[i]*src.host()[i] + B.host()[i]
!*/
// ----------------------------------------------------------------------------------------
void affine_transform_conv(
tensor& dest,
const tensor& src,
const tensor& A,
const tensor& B
);
/*!
requires
- have_same_dimensions(dest,src) == true
- have_same_dimensions(A, B) == true
- A.num_samples() == 1
- A.nr() == 1
- A.nc() == 1
- A.k() == src.k()
ensures
- Performs #dest == A*src + B
In particular, if the elements of dest and src were indexed by (n,k,r,c) then
we would have:
#dest(n,k,r,c) == A(k)*src(n,k,r,c) + B(k).
!*/
// ----------------------------------------------------------------------------------------
void compute_adam_update (
size_t begin,
size_t end,
tensor& s,
tensor& m,
tensor& v,
const float t,
const float learning_rate,
const float weight_decay,
const float momentum1,
const float momentum2,
const tensor& params,
const tensor& params_grad
);
/*!
requires
- s.size() == m.size() = v.size() == params.size() == params_grad.size()
- t > 0
- learning_rate > 0
- weight_decay >= 0
- 0 <= momentum1 < 1
- 0 <= momentum2 < 1
- begin <= end <= params.size()
ensures
- This function implements the ADAM parameter update method described in the paper:
Kingma, Diederik P., and Jimmy Ba Adam. "A method for stochastic
optimization." International Conference on Learning Representation. 2015.
Specifically, it implements the method shown as Algorithm 1.
- #s is the update vector that should be added to the parameters.
- The function only operates in the half open range [begin,end) of the memory
blocks of each tensor. E.g. to make this function run on the entire tensor
set begin to 0 and end to params.size().
!*/
// ----------------------------------------------------------------------------------------
void batch_normalize_inference (
const double eps,
resizable_tensor& dest,
const tensor& src,
const tensor& gamma,
const tensor& beta,
const tensor& running_means,
const tensor& running_variances
);
/*!
requires
- eps > 0
- gamma.num_samples() == 1
- gamma.nr() == src.nr()
- gamma.nc() == src.nc()
- gamma.k() == src.k()
- have_same_dimensions(gamma, beta)
- have_same_dimensions(gamma, running_means)
- have_same_dimensions(gamma, running_variances)
ensures
- Linearly transforms src as a call to batch_normalize() would if src had means
and variances as given by running_means and running_variances. That is, this
function performs:
dest = gamma*(src-running_means)/sqrt(running_variances+eps) + beta
Note that it does it in a pointwise fashion over the samples in src.
!*/
void batch_normalize (
const double eps,
resizable_tensor& dest,
resizable_tensor& means,
resizable_tensor& invstds,
const double averaging_factor,
resizable_tensor& running_means,
resizable_tensor& running_variances,
const tensor& src,
const tensor& gamma,
const tensor& beta
);
/*!
requires
- eps > 0
- src.num_samples() > 1
- gamma.num_samples() == 1
- beta.num_samples() == 1
- gamma.nr() == beta.nr() == src.nr()
- gamma.nc() == beta.nc() == src.nc()
- gamma.k() == beta.k() == src.k()
- 0 <= averaging_factor <= 1
- if (averaging_factor != 1)
- have_same_dimensions(running_means, means) == true
- have_same_dimensions(running_variances, invstds) == true
ensures
- have_same_dimensions(#dest, src) == true
- #means.num_samples() == 1
- #invstds.num_samples() == 1
- means.nr() == invstds.nr() == src.nr()
- means.nc() == invstds.nc() == src.nc()
- means.k() == invstds.k() == src.k()
- #src == the batch normalized version of src.
- #means == the mean values of the contents of src.
- #invstds == 1/(the standard deviation values of the contents of src).
- #running_means = (1-averaging_factor)*mat(#running_means) + averaging_factor*mat(#means);
- #running_variances = (1-averaging_factor)*mat(#running_variances) + averaging_factor*(variance of contents of src);
!*/
void batch_normalize_gradient (
const double eps,
const tensor& gradient_input,
const tensor& means,
const tensor& invstds,
const tensor& src,
const tensor& gamma,
tensor& src_grad,
tensor& gamma_grad,
tensor& beta_grad
);
/*!
requires
- eps > 0
- invstds and means should be the output of a call to
batch_normalize(eps,dest,means,invstds,src,gamma,beta)
- have_same_dimensions(gradient_input, src) == true
- have_same_dimensions(src, src_grad) == true
- src.num_samples() > 1
- gamma.num_samples() == 1
- have_same_dimensions(gamma, gamma_grad) == true
- have_same_dimensions(gamma, beta_grad) == true
- gamma.nr() == src.nr()
- gamma.nc() == src.nc()
- gamma.k() == src.k()
- have_same_dimensions(means, gamma) == true
- have_same_dimensions(invstds, gamma) == true
ensures
- Let f(src,gamma,beta) == dot(gradient_input, dest output of
batch_normalize(eps,dest,means,invstds,src,gamma,beta))
- Adds the gradient of f() with respect to src to #src_grad.
- Assigns the gradient of f() with respect to gamma to #gamma_grad.
- Assigns the gradient of f() with respect to beta to #beta_grad.
!*/
// ----------------------------------------------------------------------------------------
void batch_normalize_conv_inference (
const double eps,
resizable_tensor& dest,
const tensor& src,
const tensor& gamma,
const tensor& beta,
const tensor& running_means,
const tensor& running_variances
);
/*!
requires
- eps > 0
- gamma.num_samples() == 1
- gamma.nr() == 1
- gamma.nc() == 1
- gamma.k() == src.k()
- have_same_dimensions(gamma, beta)
- have_same_dimensions(gamma, running_means)
- have_same_dimensions(gamma, running_variances)
ensures
- Linearly transforms src as a call to batch_normalize_conv() would if src had
means and variances as given by running_means and running_variances. That
is, this function performs:
dest = gamma*(src-running_means)/sqrt(running_variances+eps) + beta
Note that it does this in a pointwise fashion over the samples, rows, and
columns in src.
!*/
void batch_normalize_conv (
const double eps,
resizable_tensor& dest,
resizable_tensor& means,
resizable_tensor& invstds,
const double averaging_factor,
resizable_tensor& running_means,
resizable_tensor& running_variances,
const tensor& src,
const tensor& gamma,
const tensor& beta
);
/*!
requires
- eps > 0
- src.num_samples() > 1
- gamma.num_samples()==gamma.nr()==gamma.nc() == 1
- beta.num_samples() ==beta.nr() ==gamma.nc() == 1
- gamma.k() == beta.k() == src.k()
- 0 <= averaging_factor <= 1
- if (averaging_factor != 1)
- have_same_dimensions(running_means, means) == true
- have_same_dimensions(running_variances, invstds) == true
ensures
- have_same_dimensions(#dest, src) == true
- #means.num_samples()==means.nr()==means.nc() == 1
- #invstds.num_samples() ==invstds.nr() ==invstds.nc() == 1
- means.k() == invstds.k() == src.k()
- #src == the batch normalized version of src.
- #means == the mean values of the contents of src.
- #invstds == 1/(the standard deviation values of the contents of src).
- #running_means = (1-averaging_factor)*mat(#running_means) + averaging_factor*mat(#means);
- #running_variances = (1-averaging_factor)*mat(#running_variances) + averaging_factor*(variance of contents of src);
!*/
void batch_normalize_conv_gradient (
const double eps,
const tensor& gradient_input,
const tensor& means,
const tensor& invstds,
const tensor& src,
const tensor& gamma,
tensor& src_grad,
tensor& gamma_grad,
tensor& beta_grad
);
/*!
requires
- eps > 0
- invstds and means should be the output of a call to
batch_normalize_conv(eps,dest,means,invstds,src,gamma,beta)
- have_same_dimensions(gradient_input, src) == true
- have_same_dimensions(src, src_grad) == true
- src.num_samples() > 1
- gamma.num_samples()==gamma.nr()==gamma.nc() == 1
- have_same_dimensions(gamma, gamma_grad) == true
- have_same_dimensions(gamma, beta_grad) == true
- gamma.k() == src.k()
- have_same_dimensions(means, gamma) == true
- have_same_dimensions(invstds, gamma) == true
ensures
- Let f(src,gamma,beta) == dot(gradient_input, dest output of
batch_normalize_conv(eps,dest,means,invstds,src,gamma,beta))
- Adds the gradient of f() with respect to src to #src_grad.
- Assigns the gradient of f() with respect to gamma to #gamma_grad.
- Assigns the gradient of f() with respect to beta to #beta_grad.
!*/
// -----------------------------------------------------------------------------------
void threshold (
tensor& data,
float thresh
);
/*!
ensures
- Sets all elements of data to 1 or 0 depending on if they are above or below
the given threshold. Specifically, for all valid i:
- #data.host()[i] == data.host()[i]>thresh ? 1 : 0
!*/
void dot (
const tensor& a,
const tensor& b,
tensor& result,
size_t idx
);
/*!
requires
- a.size() == b.size()
- idx < result.size()
ensures
- #result.host()[idx] == result.host()[idx] + dot(a,b);
I.e. Adds the dot product between a and b into the idx-th element of result.
The reason you might want to use this more complex version of dot() is
because, when using CUDA, it runs by generating asynchronous kernel launches
whereas the version of dot() that returns the result immediately as a scalar
must block the host while we wait for the result to be computed and then
transfered from the GPU do the host for return by dot(). So this version of
dot() might be much faster in some cases.
!*/
// ----------------------------------------------------------------------------------------
void add(
float beta,
tensor& dest,
float alpha,
const tensor& src
);
/*!
requires
- One of the following is true:
- have_same_dimensions(src, dest)
- src.num_samples()==1 && src.k()==dest.k() && src.nr()==1 && src.nc()==1
- src.num_samples()==1 && src.k()==dest.k() && src.nr()==dest.nr() && src.nc()==dest.nc()
- src.num_samples()==1 && src.k()==1 && src.nr()==dest.nr() && src.nc()==dest.nc()
- is_same_object(src,dest) == false
ensures
- performs: dest = beta*dest + alpha*src
However, how the addition happens depends on the dimensions of src. In
particular, this function adds the scaled values of one src tensor to dest.
Each dimension of the src tensor must match the corresponding dimension of
the dest tensor or must be equal to 1. In the latter case, the same value
from the src tensor, for those dimensions, will be used to add into the dest
tensor.
!*/
// ----------------------------------------------------------------------------------------
void add (
tensor& dest,
const tensor& src1,
const tensor& src2
);
/*!
ensures
- performs: dest = src1 + src2
The addition happens pointwise according to 4D tensor arithmetic. If the
dimensions don't match then missing elements are presumed to be equal to 0.
!*/
// ----------------------------------------------------------------------------------------
void assign_conv_bias_gradient (
tensor& grad,
const tensor& gradient_input
);
/*!
requires
- grad.num_samples() == 1
- grad.k() >= 1
- grad.nr() == 1
- grad.nc() == 1
- gradient_input.k() == grad.k()
- gradient_input.size() > 0
- is_same_object(grad,gradient_input) == false
ensures
- let BIAS be a tensor with the same dimensions as grad.
- let OUT be the output of add(1,OUT,1,BIAS)
- let f(gradient_input,BIAS) == dot(gradient_input,OUT)
- Then this function computes the gradient of f() with respect to BIAS and
assigns it to grad.
!*/
// ----------------------------------------------------------------------------------------
void assign_bias_gradient (
tensor& grad,
const tensor& gradient_input
);
/*!
requires
- grad.num_samples() == 1
- gradient_input.k() == grad.k()
- gradient_input.nr() == grad.nr()
- gradient_input.nc() == grad.nc()
- gradient_input.size() > 0
- is_same_object(grad,gradient_input) == false
ensures
- let BIAS be a tensor with the same dimensions as grad.
- let OUT be the output of add(1,OUT,1,BIAS)
- let f(gradient_input,BIAS) == dot(gradient_input,OUT)
- Then this function computes the gradient of f() with respect to BIAS and
assigns it to grad.
!*/
// ----------------------------------------------------------------------------------------
class tensor_conv
{
public:
tensor_conv(const tensor_conv&) = delete;
tensor_conv& operator=(const tensor_conv&) = delete;
tensor_conv() {}
void clear(
) { impl.clear(); }
void operator() (
resizable_tensor& output,
const tensor& data,
const tensor& filters,
int stride_y,
int stride_x,
int padding_y,
int padding_x
) { impl(output,data,filters,stride_y,stride_x,padding_y,padding_x); }
/*!
requires
- stride_y > 0
- stride_x > 0
- 0 <= padding_y < filters.nr()
- 0 <= padding_x < filters.nc()
- is_same_object(output,data) == false
- is_same_object(output,filters) == false
- filters.k() == data.k()
- filters.nr() <= src.nr() + 2*padding_y
- filters.nc() <= src.nc() + 2*padding_x
ensures
- convolves filters over data.
- filters contains filters.num_samples() filters.
- #output.num_samples() == data.num_samples()
- #output.k() == filters.num_samples()
- #output.nr() == 1+(data.nr() + 2*padding_y - filters.nr())/stride_y
- #output.nc() == 1+(data.nc() + 2*padding_x - filters.nc())/stride_x
!*/
void get_gradient_for_data (
const tensor& gradient_input,
const tensor& filters,
tensor& data_gradient
) { impl.get_gradient_for_data(gradient_input,filters,data_gradient); }
/*!
requires
- filters has the same dimensions as the filters object given to the last
call to operator().
- data_gradient has the same dimensions as the data object given to the last
call to operator().
- gradient_input has the same dimensions as the last output of operator().
- is_same_object(data_gradient,filters) == false
- is_same_object(data_gradient,gradient_input) == false
ensures
- let OUT be the output of (*this)(OUT,data,filters,sx,sy).
- let f(data,filters) == dot(OUT, gradient_input)
- This function finds the gradient of f() with respect to data and adds
this gradient to data_gradient.
!*/
void get_gradient_for_filters (
const tensor& gradient_input,
const tensor& data,
tensor& filters_gradient
) { impl.get_gradient_for_filters(gradient_input,data,filters_gradient); }
/*!
requires
- filters_gradient has the same dimensions as the filters object given to
the last call to operator().
- data has the same dimensions as the data object given to the last call to
operator().
- gradient_input has the same dimensions as the last output of operator().
- is_same_object(filters_gradient,data) == false
- is_same_object(filters_gradient,gradient_input) == false
ensures
- let OUT be the output of (*this)(OUT,data,filters,sx,sy).
- let f(data,filters) == dot(OUT, gradient_input)
- This function finds the gradient of f() with respect to filters and assigns
this gradient to filters_gradient.
!*/
private:
#ifdef DLIB_USE_CUDA
cuda::tensor_conv impl;
#else
cpu::tensor_conv impl;
#endif
};
// ----------------------------------------------------------------------------------------
class pooling
{
/*!
WHAT THIS OBJECT REPRESENTS
The pooling object is a tool for performing spatial pooling over a tensor.
It can be configured to do either max or average pooling.
!*/
public:
pooling(const pooling&) = delete;
pooling& operator=(const pooling&) = delete;
pooling (
) = default;
void clear(
) { impl.clear(); }
void setup_max_pooling(
int window_height,
int window_width,
int stride_y,
int stride_x,
int padding_y,
int padding_x
) { impl.setup_max_pooling(window_height, window_width, stride_y, stride_x, padding_y, padding_x); }
/*!
requires
- window_height > 0
- window_width > 0
- stride_y > 0
- stride_x > 0
- 0 <= padding_y < window_height
- 0 <= padding_x < window_width
ensures
- When you call operator() it will do max pooling with the given
parameters.
!*/
void setup_avg_pooling(
int window_height,
int window_width,
int stride_y,
int stride_x,
int padding_y,
int padding_x
) { impl.setup_avg_pooling(window_height, window_width, stride_y, stride_x, padding_y, padding_x); }
/*!
requires
- window_height > 0
- window_width > 0
- stride_y > 0
- stride_x > 0
- 0 <= padding_y < window_height
- 0 <= padding_x < window_width
ensures
- When you call operator() it will do average pooling with the given
parameters.
!*/
bool does_max_pooling(
) const { return impl.does_max_pooling(); }
void operator() (
resizable_tensor& dest,
const tensor& src
) { impl(dest, src); }
/*!
requires
- is_same_object(dest,src) == false
- either setup_max_pooling() or setup_avg_pooling() has been called.
- window_width <= src.nc() + 2*padding_x
- window_height <= src.nr() + 2*padding_y
ensures
- #dest.num_samples() == src.num_samples()
- #dest.k() == src.k()
- #dest.nr() == 1 + (src.nr() + 2*padding_y - window_height)/stride_y
- #dest.nc() == 1 + (src.nc() + 2*padding_x - window_width)/stride_x
- WINDOW == centered_rect(x*stride_x + window_width/2 - padding_x,
y*stride_y + window_height/2 - padding_y,
window_width,
window_height)
- for all valid s, k, r, and c:
- if (does_max_pooling()) then
- image_plane(#dest,s,k)(r,c) == max(subm_clipped(image_plane(src,s,k),WINDOW(c,r)))
- else
- image_plane(#dest,s,k)(r,c) == mean(subm_clipped(image_plane(src,s,k),WINDOW(c,r)))
!*/
void get_gradient(
const tensor& gradient_input,
const tensor& dest,
const tensor& src,
tensor& grad
) { impl.get_gradient(gradient_input, dest, src, grad); }
/*!
requires
- have_same_dimensions(gradient_input,dest) == true
- have_same_dimensions(src,grad) == true
- dest contains the result of calling (*this)(dest,src)
- is_same_object(grad,gradient_input) == false
- is_same_object(grad,dest) == false
- is_same_object(grad,src) == false
ensures
- Recalling that dest is the output of (*this)(dest,src),
let f(src) == dot(gradient_input,dest)
- Then this function computes the gradient of f() with respect to src and
adds it to grad.
!*/
private:
#ifdef DLIB_USE_CUDA
cuda::pooling impl;
#else
cpu::pooling impl;
#endif
};
// ----------------------------------------------------------------------------------------
void softmax (
tensor& dest,
const tensor& src
);
/*!
requires
- have_same_dimensions(dest, src) == true
ensures
- Note that the softmax function is a vector valued function:
s(x) == exp(x)/sum(exp(x))
- Computes the softmax function on src and writes the results to dest. The
softmax is computed per spatial location across the different channels at
each location. That is, softmax() outputs a new tensor, #dest, where each of
the spatial locations in dest (i.e. image idx, row idx, and column idx)
contains the output of s() evaluated over the channel values at each
location.
- This function supports in-place operation, i.e. having
is_same_object(dest, src)==true
!*/
void softmax_gradient (
tensor& grad,
const tensor& dest,
const tensor& gradient_input
);
/*!
requires
- have_same_dimensions(dest,gradient_input) == true
- have_same_dimensions(dest,grad) == true
ensures
- We interpret dest as the output of softmax(dest,SRC) for some SRC tensor.
Then let f(SRC) == dot(gradient_input,dest). Then this function computes the
gradient of f() with respect to SRC and stores it to grad. Moreover, if
is_same_object(grad,gradient_input)==true then the output is assigned to
grad, replacing its previous contents. Otherwise the output is added to
grad.
- This function supports in-place operation, i.e. having
is_same_object(grad, gradient_input)==true
!*/
// ----------------------------------------------------------------------------------------
void sigmoid (
tensor& dest,
const tensor& src
);
/*!
requires
- have_same_dimensions(dest, src) == true
ensures
- for all valid i:
- #dest.host()[i] == 1/(1+std::exp(-src.host()[i]))
- This function supports in-place operation, i.e. having
is_same_object(dest, src)==true
!*/
void sigmoid_gradient (
tensor& grad,
const tensor& dest,
const tensor& gradient_input
);
/*!
requires
- have_same_dimensions(dest,gradient_input) == true
- have_same_dimensions(dest,grad) == true
ensures
- Recalling that dest is the output of sigmoid(dest,SRC) for some SRC tensor,
let f(SRC) == dot(gradient_input,dest). Then this function computes the
gradient of f() with respect to SRC and stores it to grad. Moreover, if
is_same_object(grad,gradient_input)==true then the output is assigned to
grad, replacing its previous contents. Otherwise the output is added to
grad.
- This function supports in-place operation, i.e. having
is_same_object(grad, gradient_input)==true
!*/
// ----------------------------------------------------------------------------------------
void relu (
tensor& dest,
const tensor& src
);
/*!
requires
- have_same_dimensions(dest, src) == true
ensures
- for all valid i:
- #dest.host()[i] == std::max(0,src.host()[i])
- This function supports in-place operation, i.e. having
is_same_object(dest, src)==true
!*/
void relu_gradient (
tensor& grad,
const tensor& dest,
const tensor& gradient_input
);
/*!
requires
- have_same_dimensions(dest,gradient_input) == true
- have_same_dimensions(dest,grad) == true
ensures
- Recalling that dest is the output of relu(dest,SRC) for some SRC tensor,
let f(SRC) == dot(gradient_input,dest). Then this function computes the
gradient of f() with respect to SRC and stores it to grad. Moreover, if
is_same_object(grad,gradient_input)==true then the output is assigned to
grad, replacing its previous contents. Otherwise the output is added to
grad.
- This function supports in-place operation, i.e. having
is_same_object(grad, gradient_input)==true
!*/
// ----------------------------------------------------------------------------------------
void prelu (
tensor& dest,
const tensor& src,
const tensor& param
);
/*!
requires
- have_same_dimensions(dest, src) == true
- param.size() == 1
ensures
- for all valid i:
- if (src.host()[i] > 0) then
- #dest.host()[i] == src.host()[i]
- else
- #dest.host()[i] == src.host()[i] * param.host()[0]
- This function supports in-place operation, i.e. having
is_same_object(dest, src)==true
!*/
void prelu_gradient (
tensor& grad,
const tensor& src,
const tensor& gradient_input,
const tensor& param,
tensor& params_grad
);
/*!
requires
- have_same_dimensions(grad,src) == true
- have_same_dimensions(grad,gradient_input) == true
- param.size() == 1
- params_grad.size() == 1
- is_same_object(grad, gradient_input) == false
ensures
- Recalling that dest is the output of prelu(dest,src,param) let
f(src,param) == dot(gradient_input,dest)
- Then this function computes the gradient of f() with respect to src and
param. It assigns the gradient with respect to param to #params_grad and
adds the gradient with respect to src to #grad.
!*/
// ----------------------------------------------------------------------------------------
void tanh (
tensor& dest,
const tensor& src
);
/*!
requires
- have_same_dimensions(dest, src) == true
ensures
- for all valid i:
- #dest.host()[i] == std::tanh(src.host()[i])
- This function supports in-place operation, i.e. having
is_same_object(dest, src)==true
!*/
void tanh_gradient (
tensor& grad,
const tensor& dest,
const tensor& gradient_input
);
/*!
requires
- have_same_dimensions(dest,gradient_input) == true
- have_same_dimensions(dest,grad) == true
ensures
- Recalling that dest is the output of tanh(dest,SRC) for some SRC tensor,
let f(SRC) == dot(gradient_input,dest). Then this function computes the
gradient of f() with respect to SRC and stores it to grad. Moreover, if
is_same_object(grad,gradient_input)==true then the output is assigned to
grad, replacing its previous contents. Otherwise the output is added to
grad.
- This function supports in-place operation, i.e. having
is_same_object(grad, gradient_input)==true
!*/
// ----------------------------------------------------------------------------------------
class multi_device_tensor_averager
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is a tool for very quickly averaging a bunch of tensors
together.
!*/
public:
multi_device_tensor_averager(const multi_device_tensor_averager&) = delete;
multi_device_tensor_averager& operator=(const multi_device_tensor_averager&) = delete;
multi_device_tensor_averager() = default;
void set(
std::vector<tensor*> items
)
/*!
requires
- All the tensors in items are the same size
ensures
- When you call average() we will average the tensors in items.
- It's important that the tensors already be allocated to their devices
before you call set(). This is because set() will setup the types of
between device transfers now and use them when you call average().
!*/
{
using namespace ::dlib::cuda;
accessible_groups.clear();
epa.clear();
if (items.size() < 1)
return;
scale = 1.0/items.size();
// split item into groups of accessible devices
std::vector<tensor*> group, unused;
while(items.size() > 0)
{
group.push_back(items[0]);
for(size_t i = 1; i < items.size(); ++i)
{
if (can_access_peer(*items[0], *items[i]))
group.push_back(items[i]);
else
unused.push_back(items[i]);
}
accessible_groups.push_back(group);
unused.swap(items);
unused.clear();
group.clear();
}
for (auto&& g : accessible_groups)
{
for (size_t i = 1; i < g.size(); ++i)
{
epa.emplace_back(new enable_peer_access(*g[0], *g[i]));
}
}
}
size_t num_device_groups(
) const { return accessible_groups.size(); }
/*!
ensures
- The devices given to set() are grouped together when they can directly
access each other using GPUDirect. This function returns the number of
such groups. For example, if all devices can directly access each other
then the number of groups is 1.
!*/
void average()
/*!
requires
- All the devices have stopped writing to the tensors given to set(). So
you should probably call cudaDeviceSynchronize() on each of the relevant
devices before calling average().
ensures
- Computes the average of all the tensors given to set() and then sets them
all equal to the average.
!*/
{
using namespace ::dlib::cuda;
// First we average things within each group
for (auto&& g : accessible_groups)
{
raii_set_device set_dev(*g[0]);
if (g.size() == 1)
tt::affine_transform(*g[0], *g[0], scale);
else
tt::affine_transform(*g[0], *g[0], *g[1], scale, scale);
for (size_t i = 2; i < g.size(); ++i)
tt::affine_transform(*g[0], *g[0], *g[i], 1, scale);
}
if (accessible_groups.size() > 1)
{
tensor& total_avg = *accessible_groups[0][0];
raii_set_device set_dev(total_avg);
accum_buffer.copy_size(total_avg);
// now we need to average things across groups
for (size_t i = 1; i < accessible_groups.size(); ++i)
{
memcpy(accum_buffer, *accessible_groups[i][0]);
tt::add(total_avg, total_avg, accum_buffer);
}
// Now total_avg has the final average in it. So we need to send
// copies of it back to each of the groups.
for (size_t i = 1; i < accessible_groups.size(); ++i)
{
memcpy(*accessible_groups[i][0], total_avg);
}
}
// Now propagate averages back out to each element using point to point
// communication inside a group.
for (auto&& g : accessible_groups)
{
raii_set_device set_dev(*g[0]);
for (size_t i = 1; i < g.size(); ++i)
memcpy(*g[i], *g[0]);
}
}
private:
std::vector<std::unique_ptr<::dlib::cuda::enable_peer_access>> epa;
std::vector<std::vector<tensor*>> accessible_groups;
float scale;
resizable_tensor accum_buffer;
};
// ----------------------------------------------------------------------------------------
}}
#ifdef NO_MAKEFILE
#include "tensor_tools.cpp"
#endif
#endif // DLIB_TeNSOR_TOOLS_H_
| 36.548516 | 129 | 0.502984 | [
"object",
"vector"
] |
36f1f79ecef0208dda3194aec5565ab2d3a3c6d7 | 2,789 | h | C | include/ndarray_container.h | lijiansong/ndarray | 9f843d5039292ce035b3ede1a0fbb0d103f959b5 | [
"WTFPL"
] | 3 | 2018-03-14T06:49:00.000Z | 2019-08-06T18:28:00.000Z | include/ndarray_container.h | lijiansong/ndarray | 9f843d5039292ce035b3ede1a0fbb0d103f959b5 | [
"WTFPL"
] | null | null | null | include/ndarray_container.h | lijiansong/ndarray | 9f843d5039292ce035b3ede1a0fbb0d103f959b5 | [
"WTFPL"
] | 2 | 2019-01-13T10:38:02.000Z | 2020-09-18T12:37:46.000Z | #ifndef NDARRAY_CONTAINER_H
#define NDARRAY_CONTAINER_H
#include "third_party/meta/nano.hpp"
#include <array>
namespace ndarray {
template <typename DT, size_t... Sizes>
class NDArrayContainer;
// Template parameters:
// - DT = data type
// - SF = size of first dimension
// - SR = size of other dimensions
// static container
template <typename DT, std::size_t SF, std::size_t... SR>
class NDArrayContainer<DT, SF, SR...> {
public:
// ---------------------------------------- ALIAS'S -----------------------------------------------------
using data_type = DT;
using dimension_sizes = nano::list<nano::size_t<SF>, nano::size_t<SR>...>;
using dimension_product = nano::multiplies<dimension_sizes>;
using data_container = std::array<data_type, dimension_product::result>;
using dim_container = typename nano::runtime_converter<dimension_sizes>::array_type;
using size_type = typename data_container::size_type;
using iterator = typename data_container::iterator;
// ------------------------------------------------------------------------------------------------------
NDArrayContainer() {}
constexpr NDArrayContainer(data_container& data) : _data(data) {}
template <typename... TR>
constexpr NDArrayContainer(TR&&... values) : _data{{std::forward<TR>(values)...}} {}
constexpr std::size_t size() const { return dimension_product::result; }
inline data_type& operator[](std::size_t i) { return _data[i]; }
inline const data_type& operator[](std::size_t i) const { return _data[i]; }
iterator begin() { return _data.begin(); }
iterator end() { return _data.end(); }
private:
data_container _data;
};
// dynamic container
template <typename DT>
class NDArrayContainer<DT> {
public:
// ---------------------------------------- ALIAS'S -----------------------------------------------------
using data_type = DT;
using data_container = std::vector<data_type>;
using size_type = typename data_container::size_type;
using dim_container = std::vector<size_type>;
using iterator = typename data_container::iterator;
// ------------------------------------------------------------------------------------------------------
NDArrayContainer() : _size(0), _data(0) {}
NDArrayContainer(data_container& data) : _size(data.size()), _data(data){}
inline std::size_t size() const { return _size; }
inline data_type& operator[](std::size_t i) { return _data[i]; }
inline const data_type& operator[](std::size_t i) const { return _data[i]; }
iterator begin() { return _data.begin(); }
iterator end() { return _data.end(); }
private:
data_container _data;
std::size_t _size;
};
} // end of namespace ndarray
#endif // NDARRAY_CONTAINER_H
| 32.430233 | 109 | 0.589459 | [
"vector"
] |
36f82a8180e1749a201ee5318b76d8edfd03c8a8 | 2,566 | h | C | production_apps/BEM4I/IdentityOperator.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | production_apps/BEM4I/IdentityOperator.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | null | null | null | production_apps/BEM4I/IdentityOperator.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 1 | 2018-09-30T19:04:38.000Z | 2018-09-30T19:04:38.000Z | /*!
* @file IdentityOperator.h
* @author Michal Merta
* @date July 18, 2013
* @brief Header file for class IdentityOperator
*
*/
#ifndef IDENTITYOPERATOR_H
#define IDENTITYOPERATOR_H
#include <vector>
#include "LinearOperator.h"
#include "Vector.h"
#include "BESpace.h"
#include "SparseMatrix.h"
#include "IterativeSolver.h"
namespace bem4i {
/*!
* Class representing a weak identity operator on given discretized space
*/
template<class LO, class SC>
class IdentityOperator : public LinearOperator<LO, SC> {
typedef typename GetType<LO, SC>::SCVT SCVT;
public:
//! constructor taking a boundary element space as argument
IdentityOperator(
BESpace<LO, SC> * space
);
/*!
* @brief Applies operator on a vector
*
* Computes y = beta*y + alpha*this*x
* @param A
* @param x
* @param y
* @param alpha
* @param beta
*/
void apply(
Vector<LO, SC> const &x,
Vector<LO, SC> &y,
bool transA = false,
SC alpha = 1.0,
SC beta = 0.0
);
void assemble(
SparseMatrix< LO, SC > & M
) const;
//! destructor
virtual ~IdentityOperator( );
private:
BESpace<LO, SC> * space;
//! default constructor
IdentityOperator( ) {};
//! copy constructor
IdentityOperator(
const IdentityOperator & orig
) {};
//! applies operator for combination p0, p0
void applyP0P0(
Vector<LO, SC> const &x,
Vector<LO, SC> &y,
bool transA = false,
SC alpha = 1.0,
SC beta = 0.0
);
//! applies operator for combination p0, p1
void applyP0P1(
Vector<LO, SC> const &x,
Vector<LO, SC> &y,
bool transA = false,
SC alpha = 1.0,
SC beta = 0.0
);
//! applies operator for combination p1, p0
void applyP1P0(
Vector<LO, SC> const &x,
Vector<LO, SC> &y,
bool transA = false,
SC alpha = 1.0,
SC beta = 0.0
);
//! applies operator for combination p1, p1
void applyP1P1(
Vector<LO, SC> const &x,
Vector<LO, SC> &y,
bool transA = false,
SC alpha = 1.0,
SC beta = 0.0
);
void assembleP0P1(
SparseMatrix< LO, SC > & M
) const;
void assembleP1P0(
SparseMatrix< LO, SC > & M
) const;
void assembleP1P1(
SparseMatrix< LO, SC > & M
) const;
void assembleP0P0(
SparseMatrix< LO, SC > & M
) const;
};
}
// include .cpp file to overcome linking problems due to templates
#include "IdentityOperator.cpp"
#endif /* IDENTITYOPERATOR_H */
| 19.149254 | 73 | 0.592362 | [
"vector"
] |
36f833a617ff15785d1b2098f1e1590e9e1b1d5a | 34,332 | c | C | lapack-netlib/SRC/dlatrs.c | mmuetzel/OpenBLAS | b7873605d4a3eb66a0488b54b3dc1dd7d4b79170 | [
"BSD-3-Clause"
] | null | null | null | lapack-netlib/SRC/dlatrs.c | mmuetzel/OpenBLAS | b7873605d4a3eb66a0488b54b3dc1dd7d4b79170 | [
"BSD-3-Clause"
] | null | null | null | lapack-netlib/SRC/dlatrs.c | mmuetzel/OpenBLAS | b7873605d4a3eb66a0488b54b3dc1dd7d4b79170 | [
"BSD-3-Clause"
] | null | null | null | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c__1 = 1;
static doublereal c_b36 = .5;
/* > \brief \b DLATRS solves a triangular system of equations with the scale factor set to prevent overflow.
*/
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DLATRS + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dlatrs.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dlatrs.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dlatrs.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DLATRS( UPLO, TRANS, DIAG, NORMIN, N, A, LDA, X, SCALE, */
/* CNORM, INFO ) */
/* CHARACTER DIAG, NORMIN, TRANS, UPLO */
/* INTEGER INFO, LDA, N */
/* DOUBLE PRECISION SCALE */
/* DOUBLE PRECISION A( LDA, * ), CNORM( * ), X( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DLATRS solves one of the triangular systems */
/* > */
/* > A *x = s*b or A**T *x = s*b */
/* > */
/* > with scaling to prevent overflow. Here A is an upper or lower */
/* > triangular matrix, A**T denotes the transpose of A, x and b are */
/* > n-element vectors, and s is a scaling factor, usually less than */
/* > or equal to 1, chosen so that the components of x will be less than */
/* > the overflow threshold. If the unscaled problem will not cause */
/* > overflow, the Level 2 BLAS routine DTRSV is called. If the matrix A */
/* > is singular (A(j,j) = 0 for some j), then s is set to 0 and a */
/* > non-trivial solution to A*x = 0 is returned. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] UPLO */
/* > \verbatim */
/* > UPLO is CHARACTER*1 */
/* > Specifies whether the matrix A is upper or lower triangular. */
/* > = 'U': Upper triangular */
/* > = 'L': Lower triangular */
/* > \endverbatim */
/* > */
/* > \param[in] TRANS */
/* > \verbatim */
/* > TRANS is CHARACTER*1 */
/* > Specifies the operation applied to A. */
/* > = 'N': Solve A * x = s*b (No transpose) */
/* > = 'T': Solve A**T* x = s*b (Transpose) */
/* > = 'C': Solve A**T* x = s*b (Conjugate transpose = Transpose) */
/* > \endverbatim */
/* > */
/* > \param[in] DIAG */
/* > \verbatim */
/* > DIAG is CHARACTER*1 */
/* > Specifies whether or not the matrix A is unit triangular. */
/* > = 'N': Non-unit triangular */
/* > = 'U': Unit triangular */
/* > \endverbatim */
/* > */
/* > \param[in] NORMIN */
/* > \verbatim */
/* > NORMIN is CHARACTER*1 */
/* > Specifies whether CNORM has been set or not. */
/* > = 'Y': CNORM contains the column norms on entry */
/* > = 'N': CNORM is not set on entry. On exit, the norms will */
/* > be computed and stored in CNORM. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > The triangular matrix A. If UPLO = 'U', the leading n by n */
/* > upper triangular part of the array A contains the upper */
/* > triangular matrix, and the strictly lower triangular part of */
/* > A is not referenced. If UPLO = 'L', the leading n by n lower */
/* > triangular part of the array A contains the lower triangular */
/* > matrix, and the strictly upper triangular part of A is not */
/* > referenced. If DIAG = 'U', the diagonal elements of A are */
/* > also not referenced and are assumed to be 1. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax (1,N). */
/* > \endverbatim */
/* > */
/* > \param[in,out] X */
/* > \verbatim */
/* > X is DOUBLE PRECISION array, dimension (N) */
/* > On entry, the right hand side b of the triangular system. */
/* > On exit, X is overwritten by the solution vector x. */
/* > \endverbatim */
/* > */
/* > \param[out] SCALE */
/* > \verbatim */
/* > SCALE is DOUBLE PRECISION */
/* > The scaling factor s for the triangular system */
/* > A * x = s*b or A**T* x = s*b. */
/* > If SCALE = 0, the matrix A is singular or badly scaled, and */
/* > the vector x is an exact or approximate solution to A*x = 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] CNORM */
/* > \verbatim */
/* > CNORM is DOUBLE PRECISION array, dimension (N) */
/* > */
/* > If NORMIN = 'Y', CNORM is an input argument and CNORM(j) */
/* > contains the norm of the off-diagonal part of the j-th column */
/* > of A. If TRANS = 'N', CNORM(j) must be greater than or equal */
/* > to the infinity-norm, and if TRANS = 'T' or 'C', CNORM(j) */
/* > must be greater than or equal to the 1-norm. */
/* > */
/* > If NORMIN = 'N', CNORM is an output argument and CNORM(j) */
/* > returns the 1-norm of the offdiagonal part of the j-th column */
/* > of A. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -k, the k-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup doubleOTHERauxiliary */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > A rough bound on x is computed; if that is less than overflow, DTRSV */
/* > is called, otherwise, specific code is used which checks for possible */
/* > overflow or divide-by-zero at every operation. */
/* > */
/* > A columnwise scheme is used for solving A*x = b. The basic algorithm */
/* > if A is lower triangular is */
/* > */
/* > x[1:n] := b[1:n] */
/* > for j = 1, ..., n */
/* > x(j) := x(j) / A(j,j) */
/* > x[j+1:n] := x[j+1:n] - x(j) * A[j+1:n,j] */
/* > end */
/* > */
/* > Define bounds on the components of x after j iterations of the loop: */
/* > M(j) = bound on x[1:j] */
/* > G(j) = bound on x[j+1:n] */
/* > Initially, let M(0) = 0 and G(0) = f2cmax{x(i), i=1,...,n}. */
/* > */
/* > Then for iteration j+1 we have */
/* > M(j+1) <= G(j) / | A(j+1,j+1) | */
/* > G(j+1) <= G(j) + M(j+1) * | A[j+2:n,j+1] | */
/* > <= G(j) ( 1 + CNORM(j+1) / | A(j+1,j+1) | ) */
/* > */
/* > where CNORM(j+1) is greater than or equal to the infinity-norm of */
/* > column j+1 of A, not counting the diagonal. Hence */
/* > */
/* > G(j) <= G(0) product ( 1 + CNORM(i) / | A(i,i) | ) */
/* > 1<=i<=j */
/* > and */
/* > */
/* > |x(j)| <= ( G(0) / |A(j,j)| ) product ( 1 + CNORM(i) / |A(i,i)| ) */
/* > 1<=i< j */
/* > */
/* > Since |x(j)| <= M(j), we use the Level 2 BLAS routine DTRSV if the */
/* > reciprocal of the largest M(j), j=1,..,n, is larger than */
/* > f2cmax(underflow, 1/overflow). */
/* > */
/* > The bound on x(j) is also used to determine when a step in the */
/* > columnwise method can be performed without fear of overflow. If */
/* > the computed bound is greater than a large constant, x is scaled to */
/* > prevent overflow, but if the bound overflows, x is set to 0, x(j) to */
/* > 1, and scale to 0, and a non-trivial solution to A*x = 0 is found. */
/* > */
/* > Similarly, a row-wise scheme is used to solve A**T*x = b. The basic */
/* > algorithm for A upper triangular is */
/* > */
/* > for j = 1, ..., n */
/* > x(j) := ( b(j) - A[1:j-1,j]**T * x[1:j-1] ) / A(j,j) */
/* > end */
/* > */
/* > We simultaneously compute two bounds */
/* > G(j) = bound on ( b(i) - A[1:i-1,i]**T * x[1:i-1] ), 1<=i<=j */
/* > M(j) = bound on x(i), 1<=i<=j */
/* > */
/* > The initial values are G(0) = 0, M(0) = f2cmax{b(i), i=1,..,n}, and we */
/* > add the constraint G(j) >= G(j-1) and M(j) >= M(j-1) for j >= 1. */
/* > Then the bound on x(j) is */
/* > */
/* > M(j) <= M(j-1) * ( 1 + CNORM(j) ) / | A(j,j) | */
/* > */
/* > <= M(0) * product ( ( 1 + CNORM(i) ) / |A(i,i)| ) */
/* > 1<=i<=j */
/* > */
/* > and we can safely call DTRSV if 1/M(n) and 1/G(n) are both greater */
/* > than f2cmax(underflow, 1/overflow). */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int dlatrs_(char *uplo, char *trans, char *diag, char *
normin, integer *n, doublereal *a, integer *lda, doublereal *x,
doublereal *scale, doublereal *cnorm, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
doublereal d__1, d__2, d__3;
/* Local variables */
integer jinc;
extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *,
integer *);
doublereal xbnd;
integer imax;
doublereal tmax, tjjs, xmax, grow, sumj;
integer i__, j;
extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *,
integer *);
extern logical lsame_(char *, char *);
doublereal tscal, uscal;
extern doublereal dasum_(integer *, doublereal *, integer *);
integer jlast;
extern /* Subroutine */ int daxpy_(integer *, doublereal *, doublereal *,
integer *, doublereal *, integer *);
logical upper;
extern /* Subroutine */ int dtrsv_(char *, char *, char *, integer *,
doublereal *, integer *, doublereal *, integer *);
extern doublereal dlamch_(char *);
doublereal xj;
extern integer idamax_(integer *, doublereal *, integer *);
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
doublereal bignum;
logical notran;
integer jfirst;
doublereal smlnum;
logical nounit;
doublereal rec, tjj;
/* -- LAPACK auxiliary routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--x;
--cnorm;
/* Function Body */
*info = 0;
upper = lsame_(uplo, "U");
notran = lsame_(trans, "N");
nounit = lsame_(diag, "N");
/* Test the input parameters. */
if (! upper && ! lsame_(uplo, "L")) {
*info = -1;
} else if (! notran && ! lsame_(trans, "T") && !
lsame_(trans, "C")) {
*info = -2;
} else if (! nounit && ! lsame_(diag, "U")) {
*info = -3;
} else if (! lsame_(normin, "Y") && ! lsame_(normin,
"N")) {
*info = -4;
} else if (*n < 0) {
*info = -5;
} else if (*lda < f2cmax(1,*n)) {
*info = -7;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DLATRS", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
if (*n == 0) {
return 0;
}
/* Determine machine dependent parameters to control overflow. */
smlnum = dlamch_("Safe minimum") / dlamch_("Precision");
bignum = 1. / smlnum;
*scale = 1.;
if (lsame_(normin, "N")) {
/* Compute the 1-norm of each column, not including the diagonal. */
if (upper) {
/* A is upper triangular. */
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = j - 1;
cnorm[j] = dasum_(&i__2, &a[j * a_dim1 + 1], &c__1);
/* L10: */
}
} else {
/* A is lower triangular. */
i__1 = *n - 1;
for (j = 1; j <= i__1; ++j) {
i__2 = *n - j;
cnorm[j] = dasum_(&i__2, &a[j + 1 + j * a_dim1], &c__1);
/* L20: */
}
cnorm[*n] = 0.;
}
}
/* Scale the column norms by TSCAL if the maximum element in CNORM is */
/* greater than BIGNUM. */
imax = idamax_(n, &cnorm[1], &c__1);
tmax = cnorm[imax];
if (tmax <= bignum) {
tscal = 1.;
} else {
tscal = 1. / (smlnum * tmax);
dscal_(n, &tscal, &cnorm[1], &c__1);
}
/* Compute a bound on the computed solution vector to see if the */
/* Level 2 BLAS routine DTRSV can be used. */
j = idamax_(n, &x[1], &c__1);
xmax = (d__1 = x[j], abs(d__1));
xbnd = xmax;
if (notran) {
/* Compute the growth in A * x = b. */
if (upper) {
jfirst = *n;
jlast = 1;
jinc = -1;
} else {
jfirst = 1;
jlast = *n;
jinc = 1;
}
if (tscal != 1.) {
grow = 0.;
goto L50;
}
if (nounit) {
/* A is non-unit triangular. */
/* Compute GROW = 1/G(j) and XBND = 1/M(j). */
/* Initially, G(0) = f2cmax{x(i), i=1,...,n}. */
grow = 1. / f2cmax(xbnd,smlnum);
xbnd = grow;
i__1 = jlast;
i__2 = jinc;
for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) {
/* Exit the loop if the growth factor is too small. */
if (grow <= smlnum) {
goto L50;
}
/* M(j) = G(j-1) / abs(A(j,j)) */
tjj = (d__1 = a[j + j * a_dim1], abs(d__1));
/* Computing MIN */
d__1 = xbnd, d__2 = f2cmin(1.,tjj) * grow;
xbnd = f2cmin(d__1,d__2);
if (tjj + cnorm[j] >= smlnum) {
/* G(j) = G(j-1)*( 1 + CNORM(j) / abs(A(j,j)) ) */
grow *= tjj / (tjj + cnorm[j]);
} else {
/* G(j) could overflow, set GROW to 0. */
grow = 0.;
}
/* L30: */
}
grow = xbnd;
} else {
/* A is unit triangular. */
/* Compute GROW = 1/G(j), where G(0) = f2cmax{x(i), i=1,...,n}. */
/* Computing MIN */
d__1 = 1., d__2 = 1. / f2cmax(xbnd,smlnum);
grow = f2cmin(d__1,d__2);
i__2 = jlast;
i__1 = jinc;
for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) {
/* Exit the loop if the growth factor is too small. */
if (grow <= smlnum) {
goto L50;
}
/* G(j) = G(j-1)*( 1 + CNORM(j) ) */
grow *= 1. / (cnorm[j] + 1.);
/* L40: */
}
}
L50:
;
} else {
/* Compute the growth in A**T * x = b. */
if (upper) {
jfirst = 1;
jlast = *n;
jinc = 1;
} else {
jfirst = *n;
jlast = 1;
jinc = -1;
}
if (tscal != 1.) {
grow = 0.;
goto L80;
}
if (nounit) {
/* A is non-unit triangular. */
/* Compute GROW = 1/G(j) and XBND = 1/M(j). */
/* Initially, M(0) = f2cmax{x(i), i=1,...,n}. */
grow = 1. / f2cmax(xbnd,smlnum);
xbnd = grow;
i__1 = jlast;
i__2 = jinc;
for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) {
/* Exit the loop if the growth factor is too small. */
if (grow <= smlnum) {
goto L80;
}
/* G(j) = f2cmax( G(j-1), M(j-1)*( 1 + CNORM(j) ) ) */
xj = cnorm[j] + 1.;
/* Computing MIN */
d__1 = grow, d__2 = xbnd / xj;
grow = f2cmin(d__1,d__2);
/* M(j) = M(j-1)*( 1 + CNORM(j) ) / abs(A(j,j)) */
tjj = (d__1 = a[j + j * a_dim1], abs(d__1));
if (xj > tjj) {
xbnd *= tjj / xj;
}
/* L60: */
}
grow = f2cmin(grow,xbnd);
} else {
/* A is unit triangular. */
/* Compute GROW = 1/G(j), where G(0) = f2cmax{x(i), i=1,...,n}. */
/* Computing MIN */
d__1 = 1., d__2 = 1. / f2cmax(xbnd,smlnum);
grow = f2cmin(d__1,d__2);
i__2 = jlast;
i__1 = jinc;
for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) {
/* Exit the loop if the growth factor is too small. */
if (grow <= smlnum) {
goto L80;
}
/* G(j) = ( 1 + CNORM(j) )*G(j-1) */
xj = cnorm[j] + 1.;
grow /= xj;
/* L70: */
}
}
L80:
;
}
if (grow * tscal > smlnum) {
/* Use the Level 2 BLAS solve if the reciprocal of the bound on */
/* elements of X is not too small. */
dtrsv_(uplo, trans, diag, n, &a[a_offset], lda, &x[1], &c__1);
} else {
/* Use a Level 1 BLAS solve, scaling intermediate results. */
if (xmax > bignum) {
/* Scale X so that its components are less than or equal to */
/* BIGNUM in absolute value. */
*scale = bignum / xmax;
dscal_(n, scale, &x[1], &c__1);
xmax = bignum;
}
if (notran) {
/* Solve A * x = b */
i__1 = jlast;
i__2 = jinc;
for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) {
/* Compute x(j) = b(j) / A(j,j), scaling x if necessary. */
xj = (d__1 = x[j], abs(d__1));
if (nounit) {
tjjs = a[j + j * a_dim1] * tscal;
} else {
tjjs = tscal;
if (tscal == 1.) {
goto L100;
}
}
tjj = abs(tjjs);
if (tjj > smlnum) {
/* abs(A(j,j)) > SMLNUM: */
if (tjj < 1.) {
if (xj > tjj * bignum) {
/* Scale x by 1/b(j). */
rec = 1. / xj;
dscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
x[j] /= tjjs;
xj = (d__1 = x[j], abs(d__1));
} else if (tjj > 0.) {
/* 0 < abs(A(j,j)) <= SMLNUM: */
if (xj > tjj * bignum) {
/* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM */
/* to avoid overflow when dividing by A(j,j). */
rec = tjj * bignum / xj;
if (cnorm[j] > 1.) {
/* Scale by 1/CNORM(j) to avoid overflow when */
/* multiplying x(j) times column j. */
rec /= cnorm[j];
}
dscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
x[j] /= tjjs;
xj = (d__1 = x[j], abs(d__1));
} else {
/* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and */
/* scale = 0, and compute a solution to A*x = 0. */
i__3 = *n;
for (i__ = 1; i__ <= i__3; ++i__) {
x[i__] = 0.;
/* L90: */
}
x[j] = 1.;
xj = 1.;
*scale = 0.;
xmax = 0.;
}
L100:
/* Scale x if necessary to avoid overflow when adding a */
/* multiple of column j of A. */
if (xj > 1.) {
rec = 1. / xj;
if (cnorm[j] > (bignum - xmax) * rec) {
/* Scale x by 1/(2*abs(x(j))). */
rec *= .5;
dscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
}
} else if (xj * cnorm[j] > bignum - xmax) {
/* Scale x by 1/2. */
dscal_(n, &c_b36, &x[1], &c__1);
*scale *= .5;
}
if (upper) {
if (j > 1) {
/* Compute the update */
/* x(1:j-1) := x(1:j-1) - x(j) * A(1:j-1,j) */
i__3 = j - 1;
d__1 = -x[j] * tscal;
daxpy_(&i__3, &d__1, &a[j * a_dim1 + 1], &c__1, &x[1],
&c__1);
i__3 = j - 1;
i__ = idamax_(&i__3, &x[1], &c__1);
xmax = (d__1 = x[i__], abs(d__1));
}
} else {
if (j < *n) {
/* Compute the update */
/* x(j+1:n) := x(j+1:n) - x(j) * A(j+1:n,j) */
i__3 = *n - j;
d__1 = -x[j] * tscal;
daxpy_(&i__3, &d__1, &a[j + 1 + j * a_dim1], &c__1, &
x[j + 1], &c__1);
i__3 = *n - j;
i__ = j + idamax_(&i__3, &x[j + 1], &c__1);
xmax = (d__1 = x[i__], abs(d__1));
}
}
/* L110: */
}
} else {
/* Solve A**T * x = b */
i__2 = jlast;
i__1 = jinc;
for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) {
/* Compute x(j) = b(j) - sum A(k,j)*x(k). */
/* k<>j */
xj = (d__1 = x[j], abs(d__1));
uscal = tscal;
rec = 1. / f2cmax(xmax,1.);
if (cnorm[j] > (bignum - xj) * rec) {
/* If x(j) could overflow, scale x by 1/(2*XMAX). */
rec *= .5;
if (nounit) {
tjjs = a[j + j * a_dim1] * tscal;
} else {
tjjs = tscal;
}
tjj = abs(tjjs);
if (tjj > 1.) {
/* Divide by A(j,j) when scaling x if A(j,j) > 1. */
/* Computing MIN */
d__1 = 1., d__2 = rec * tjj;
rec = f2cmin(d__1,d__2);
uscal /= tjjs;
}
if (rec < 1.) {
dscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
sumj = 0.;
if (uscal == 1.) {
/* If the scaling needed for A in the dot product is 1, */
/* call DDOT to perform the dot product. */
if (upper) {
i__3 = j - 1;
sumj = ddot_(&i__3, &a[j * a_dim1 + 1], &c__1, &x[1],
&c__1);
} else if (j < *n) {
i__3 = *n - j;
sumj = ddot_(&i__3, &a[j + 1 + j * a_dim1], &c__1, &x[
j + 1], &c__1);
}
} else {
/* Otherwise, use in-line code for the dot product. */
if (upper) {
i__3 = j - 1;
for (i__ = 1; i__ <= i__3; ++i__) {
sumj += a[i__ + j * a_dim1] * uscal * x[i__];
/* L120: */
}
} else if (j < *n) {
i__3 = *n;
for (i__ = j + 1; i__ <= i__3; ++i__) {
sumj += a[i__ + j * a_dim1] * uscal * x[i__];
/* L130: */
}
}
}
if (uscal == tscal) {
/* Compute x(j) := ( x(j) - sumj ) / A(j,j) if 1/A(j,j) */
/* was not used to scale the dotproduct. */
x[j] -= sumj;
xj = (d__1 = x[j], abs(d__1));
if (nounit) {
tjjs = a[j + j * a_dim1] * tscal;
} else {
tjjs = tscal;
if (tscal == 1.) {
goto L150;
}
}
/* Compute x(j) = x(j) / A(j,j), scaling if necessary. */
tjj = abs(tjjs);
if (tjj > smlnum) {
/* abs(A(j,j)) > SMLNUM: */
if (tjj < 1.) {
if (xj > tjj * bignum) {
/* Scale X by 1/abs(x(j)). */
rec = 1. / xj;
dscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
}
x[j] /= tjjs;
} else if (tjj > 0.) {
/* 0 < abs(A(j,j)) <= SMLNUM: */
if (xj > tjj * bignum) {
/* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM. */
rec = tjj * bignum / xj;
dscal_(n, &rec, &x[1], &c__1);
*scale *= rec;
xmax *= rec;
}
x[j] /= tjjs;
} else {
/* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and */
/* scale = 0, and compute a solution to A**T*x = 0. */
i__3 = *n;
for (i__ = 1; i__ <= i__3; ++i__) {
x[i__] = 0.;
/* L140: */
}
x[j] = 1.;
*scale = 0.;
xmax = 0.;
}
L150:
;
} else {
/* Compute x(j) := x(j) / A(j,j) - sumj if the dot */
/* product has already been divided by 1/A(j,j). */
x[j] = x[j] / tjjs - sumj;
}
/* Computing MAX */
d__2 = xmax, d__3 = (d__1 = x[j], abs(d__1));
xmax = f2cmax(d__2,d__3);
/* L160: */
}
}
*scale /= tscal;
}
/* Scale the column norms by 1/TSCAL for return. */
if (tscal != 1.) {
d__1 = 1. / tscal;
dscal_(n, &d__1, &cnorm[1], &c__1);
}
return 0;
/* End of DLATRS */
} /* dlatrs_ */
| 26.759158 | 329 | 0.503932 | [
"object",
"vector"
] |
36fc0d45db2174e005f200dd11c9e1392b3ff285 | 2,107 | h | C | include/scheduler/real_scheduler.h | juruen/cavalieri | c3451579193fc8f081b6228ae295b463a0fd23bd | [
"MIT"
] | 54 | 2015-01-14T21:11:56.000Z | 2021-06-27T13:29:40.000Z | include/scheduler/real_scheduler.h | juruen/cavalieri | c3451579193fc8f081b6228ae295b463a0fd23bd | [
"MIT"
] | null | null | null | include/scheduler/real_scheduler.h | juruen/cavalieri | c3451579193fc8f081b6228ae295b463a0fd23bd | [
"MIT"
] | 10 | 2015-07-15T05:09:34.000Z | 2019-01-10T07:32:02.000Z | #ifndef CAVALIERI_SCHEDULER_REAL_SCHEDULER_H
#define CAVALIERI_SCHEDULER_REAL_SCHEDULER_H
#include <vector>
#include <tbb/concurrent_queue.h>
#include <future>
#include <scheduler/scheduler.h>
#include <pool/async_thread_pool.h>
class real_scheduler : public scheduler_interface {
public:
real_scheduler();
remove_task_future_t add_periodic_task(task_fn_t task,
float interval) override;
remove_task_future_t add_once_task(task_fn_t task, float dt) override;
remove_ns_tasks_future_t remove_ns_tasks(const std::string) override;
time_t unix_time() override;
void set_time(const time_t t) override;
void clear() override;
void stop();
private:
void async_callback(async_loop & loop);
void add_tasks(async_loop & loop);
void remove_ns_tasks(async_loop & loop);
std::future<remove_task_fn_t> add_task(task_fn_t task,
float interval, bool once);
private:
using task_promise_shared_t = std::shared_ptr<std::promise<remove_task_fn_t>>;
using task_promise_t = struct {
task_promise_shared_t promise;
task_cb_fn_t task;
float interval;
bool once;
std::string nm;
};
using promise_queue_t =
tbb::concurrent_bounded_queue<task_promise_t>;
using remove_task_queue_t = tbb::concurrent_bounded_queue<timer_id_t>;
using ns_promise_shared_t = std::shared_ptr<std::promise<bool>>;
using ns_promise_t = struct {
ns_promise_shared_t promise;
std::shared_ptr<std::atomic<unsigned int>> loops;
std::string nm;
};
using ns_queue_t = tbb::concurrent_bounded_queue<ns_promise_t>;
private:
async_thread_pool threads_;
std::vector<promise_queue_t> task_promises_;
std::vector<remove_task_queue_t> remove_tasks_;
std::vector<ns_queue_t> ns_promises_;
};
#endif
| 32.415385 | 80 | 0.635975 | [
"vector"
] |
3c063ecf52c14d864b6933098b364545e5b75c5b | 3,637 | c | C | src/libdm/color.c | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libdm/color.c | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libdm/color.c | behollis/brlcad-svn-rev65072-gsoc2015 | c2e49d80e0776ea6da4358a345a04f56e0088b90 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* C O L O R . C
* BRL-CAD
*
* Copyright (c) 2004-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file libdm/color.c
*
*/
#include "common.h"
#ifdef DM_X
#include <stdio.h>
#include <string.h>
#ifdef HAVE_X11_XLIB_H
# include <X11/Xlib.h>
#endif
#include "bu/malloc.h"
#include "dm/dm_xvars.h"
/* Return the allocated pixel value that most closely represents
the color requested. */
unsigned long
X_get_pixel(unsigned char r, unsigned char g, unsigned char b, long unsigned int *pixels, int cd)
/* values assumed to be [0, 255] */
/* cube dimension */
{
fastf_t f;
int rf, gf, bf;
int idx;
if (r == 0 && g == 0 && b == 0)
return pixels[0];
f = cd >> 8;
rf = r * f;
gf = g * f;
bf = b * f;
idx = rf * cd * cd + gf * cd + bf;
if (idx == 0) {
if (r != 0)
idx = cd * cd;
if (g != 0)
idx += cd;
if (b != 0)
idx += 1;
}
return pixels[idx];
}
/*
* Alloc/Store (hi - low) colors from src colormap into dest.
*/
HIDDEN void
_X_copy_cmap(Display *dpy, Colormap dest, Colormap src, int low, int hi, int store)
{
int i;
int ncolors;
XColor *colors;
ncolors = hi - low;
colors = (XColor *)bu_calloc(ncolors, sizeof(XColor), "dm_load_cmap: colors");
for (i = low; i < hi; ++i)
colors[i].pixel = i;
XQueryColors(dpy, src, colors, ncolors);
if (store) {
XStoreColors(dpy, dest, colors, ncolors);
} else {
for (i = 0; i < ncolors; ++i) {
XAllocColor(dpy, dest, &colors[i]);
}
}
bu_free((void *)colors, "dm_load_cmap: colors");
}
void
X_allocate_color_cube(Display *dpy, Colormap cmap, long unsigned int *pixels, int cd, int cmap_base, int store)
/* cube dimension */
{
XColor color;
Colormap default_cmap;
int i;
int r, g, b;
int incr; /* increment */
INIT_XCOLOR(&color);
/*
* Copy default colors below cmap_base to private colormap to help
* reduce flashing. Assuming cmap is private and empty, we can be
* fairly certain to get the colors we want in the right order even
* though cmap may be shared.
*/
default_cmap = DefaultColormap(dpy, DefaultScreen(dpy));
_X_copy_cmap(dpy, cmap, default_cmap, 0, cmap_base, store);
incr = 65535 / (cd - 1);
/* store color cube at cmap_base and above */
for (i = r = 0; r < 65536; r = r + incr)
for (g = 0; g < 65536; g = g + incr)
for (b = 0; b < 65536; b = b + incr, ++i) {
color.red = (unsigned short)r;
color.green = (unsigned short)g;
color.blue = (unsigned short)b;
if (store) {
color.flags = DoRed|DoGreen|DoBlue;
pixels[i] = color.pixel = i + cmap_base;
XStoreColor(dpy, cmap, &color);
} else {
XAllocColor(dpy, cmap, &color);
pixels[i] = color.pixel;
}
}
}
#endif /* DM_X */
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
| 22.590062 | 111 | 0.616167 | [
"cad"
] |
3c073c66a951723268b5ed4cc30c570c4f786186 | 759 | h | C | C/argparse.h | YuexuanX/WSDAD-MODEL | e24a566f6a4f54b7ab780a7a852b4801a411eede | [
"BSD-2-Clause"
] | 29 | 2018-08-01T00:27:16.000Z | 2021-12-16T06:20:46.000Z | C/argparse.h | YuexuanX/WSDAD-MODEL | e24a566f6a4f54b7ab780a7a852b4801a411eede | [
"BSD-2-Clause"
] | 2 | 2018-09-05T07:07:17.000Z | 2019-05-20T23:26:12.000Z | C/argparse.h | YuexuanX/WSDAD-MODEL | e24a566f6a4f54b7ab780a7a852b4801a411eede | [
"BSD-2-Clause"
] | 8 | 2018-08-29T02:53:31.000Z | 2021-06-15T06:11:55.000Z | #ifndef ARGPARSE
#define ARGPARSE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "common.h"
#include "object.h"
#include "strfun.h"
typedef struct option {
char sarg;
char* larg;
char* name;
char* desc;
char* default_value;
char* value;
bool isflag;
bool flagged;
} option;
//Program specific, to be defined by user elsewhere.
struct parsed_args;
typedef struct parsed_args parsed_args;
d(option)* option_spec();
parsed_args* validate_args(d(option)* opts);
//Defined in argparse.c
d(option)* populate_options(d(option)* opts,int argc, char** argv);
parsed_args* parse_args(int argc, char** argv);
void print_help(const char* pname,d(option)* opts);
d(int)* parse_multi_ints(const char* spec);
#endif
| 22.323529 | 67 | 0.71278 | [
"object"
] |
3c0bfb45c164491744e7e5a678bd9c501c0bb35f | 73,629 | c | C | Reloaded/trunk/src/osd/windows/input.c | lofunz/mieme | 4226c2960b46121ec44fa8eab9717d2d644bff04 | [
"Unlicense"
] | 51 | 2015-11-22T14:53:28.000Z | 2021-12-14T07:17:42.000Z | Reloaded/trunk/src/osd/windows/input.c | lofunz/mieme | 4226c2960b46121ec44fa8eab9717d2d644bff04 | [
"Unlicense"
] | 8 | 2018-01-14T07:19:06.000Z | 2021-08-22T15:29:59.000Z | Reloaded/trunk/src/osd/windows/input.c | lofunz/mieme | 4226c2960b46121ec44fa8eab9717d2d644bff04 | [
"Unlicense"
] | 35 | 2017-02-15T09:39:00.000Z | 2021-12-14T07:17:43.000Z | //============================================================
//
// input.c - Win32 implementation of MAME input routines
//
//============================================================
//
// Copyright Aaron Giles
// 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 'MAME' 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 AARON GILES ''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 AARON GILES BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGE (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.
//
//============================================================
// For testing purposes: force DirectInput
#define FORCE_DIRECTINPUT 0
// standard windows headers
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winioctl.h>
#include <tchar.h>
// undef WINNT for dinput.h to prevent duplicate definition
#undef WINNT
#include <dinput.h>
#undef interface
// standard C headers
#include <conio.h>
#include <ctype.h>
#include <stddef.h>
// MAME headers
#include "osdepend.h"
#include "emu.h"
#include "ui.h"
// MAMEOS headers
#include "winmain.h"
#include "window.h"
#include "input.h"
#include "debugwin.h"
#include "video.h"
#include "strconv.h"
#include "config.h"
#ifdef MESS
#include "uimess.h"
#endif
//============================================================
// PARAMETERS
//============================================================
enum
{
POVDIR_LEFT = 0,
POVDIR_RIGHT,
POVDIR_UP,
POVDIR_DOWN
};
#define MAX_KEYS 256
#define MAME_KEY 0
#define DI_KEY 1
#define VIRTUAL_KEY 2
#define ASCII_KEY 3
//============================================================
// MACROS
//============================================================
#define STRUCTSIZE(x) ((dinput_version == 0x0300) ? sizeof(x##_DX3) : sizeof(x))
#ifdef UNICODE
#define UNICODE_SUFFIX "W"
#else
#define UNICODE_SUFFIX "A"
#endif
//============================================================
// TYPEDEFS
//============================================================
// state information for a keyboard; DirectInput state must be first element
typedef struct _keyboard_state keyboard_state;
struct _keyboard_state
{
UINT8 state[MAX_KEYS];
INT8 oldkey[MAX_KEYS];
INT8 currkey[MAX_KEYS];
};
// state information for a mouse; DirectInput state must be first element
typedef struct _mouse_state mouse_state;
struct _mouse_state
{
DIMOUSESTATE2 state;
LONG raw_x, raw_y, raw_z;
};
// state information for a joystick; DirectInput state must be first element
typedef struct _joystick_state joystick_state;
struct _joystick_state
{
DIJOYSTATE state;
LONG rangemin[8];
LONG rangemax[8];
};
// DirectInput-specific information about a device
typedef struct _dinput_device_info dinput_device_info;
struct _dinput_device_info
{
LPDIRECTINPUTDEVICE device;
LPDIRECTINPUTDEVICE2 device2;
DIDEVCAPS caps;
LPCDIDATAFORMAT format;
};
// RawInput-specific information about a device
typedef struct _rawinput_device_info rawinput_device_info;
struct _rawinput_device_info
{
HANDLE device;
};
// generic device information
typedef struct _device_info device_info;
struct _device_info
{
// device information
device_info ** head;
device_info * next;
const char * name;
void (*poll)(device_info *info);
// MAME information
running_machine * machine;
input_device * device;
// device state
union
{
keyboard_state keyboard;
mouse_state mouse;
joystick_state joystick;
};
// DirectInput/RawInput-specific state
dinput_device_info dinput;
rawinput_device_info rawinput;
};
// RawInput APIs
typedef /*WINUSERAPI*/ INT (WINAPI *get_rawinput_device_list_ptr)(OUT PRAWINPUTDEVICELIST pRawInputDeviceList, IN OUT PINT puiNumDevices, IN UINT cbSize);
typedef /*WINUSERAPI*/ INT (WINAPI *get_rawinput_data_ptr)(IN HRAWINPUT hRawInput, IN UINT uiCommand, OUT LPVOID pData, IN OUT PINT pcbSize, IN UINT cbSizeHeader);
typedef /*WINUSERAPI*/ INT (WINAPI *get_rawinput_device_info_ptr)(IN HANDLE hDevice, IN UINT uiCommand, OUT LPVOID pData, IN OUT PINT pcbSize);
typedef /*WINUSERAPI*/ BOOL (WINAPI *register_rawinput_devices_ptr)(IN PCRAWINPUTDEVICE pRawInputDevices, IN UINT uiNumDevices, IN UINT cbSize);
//============================================================
// LOCAL VARIABLES
//============================================================
// global states
static UINT8 input_enabled;
static osd_lock * input_lock;
static UINT8 input_paused;
static DWORD last_poll;
// DirectInput variables
static LPDIRECTINPUT dinput;
static int dinput_version;
// RawInput variables
static get_rawinput_device_list_ptr get_rawinput_device_list;
static get_rawinput_data_ptr get_rawinput_data;
static get_rawinput_device_info_ptr get_rawinput_device_info;
static register_rawinput_devices_ptr register_rawinput_devices;
// keyboard states
static UINT8 keyboard_win32_reported_key_down;
static device_info * keyboard_list;
// mouse states
static UINT8 mouse_enabled;
static device_info * mouse_list;
// lightgun states
static UINT8 lightgun_shared_axis_mode;
static UINT8 lightgun_enabled;
static device_info * lightgun_list;
// joystick states
static device_info * joystick_list;
// default axis names
static const TCHAR *const default_axis_name[] =
{
TEXT("X"), TEXT("Y"), TEXT("Z"), TEXT("RX"),
TEXT("RY"), TEXT("RZ"), TEXT("SL1"), TEXT("SL2")
};
//============================================================
// PROTOTYPES
//============================================================
static void wininput_pause(running_machine &machine);
static void wininput_resume(running_machine &machine);
static void wininput_exit(running_machine &machine);
// device list management
static void device_list_poll_devices(device_info *devlist_head);
static void device_list_reset_devices(device_info *devlist_head);
// generic device management
static device_info *generic_device_alloc(running_machine *machine, device_info **devlist_head_ptr, const TCHAR *name);
static void generic_device_free(device_info *devinfo);
static int generic_device_index(device_info *devlist_head, device_info *devinfo);
static void generic_device_reset(device_info *devinfo);
static INT32 generic_button_get_state(void *device_internal, void *item_internal);
static INT32 generic_axis_get_state(void *device_internal, void *item_internal);
// Win32-specific input code
static void win32_init(running_machine *machine);
static void win32_exit(running_machine &machine);
static void win32_keyboard_poll(device_info *devinfo);
static void win32_lightgun_poll(device_info *devinfo);
// DirectInput-specific code
static void dinput_init(running_machine *machine);
static void dinput_exit(running_machine &machine);
static HRESULT dinput_set_dword_property(LPDIRECTINPUTDEVICE device, REFGUID property_guid, DWORD object, DWORD how, DWORD value);
static device_info *dinput_device_create(running_machine *machine, device_info **devlist_head_ptr, LPCDIDEVICEINSTANCE instance, LPCDIDATAFORMAT format1, LPCDIDATAFORMAT format2, DWORD cooperative_level);
static void dinput_device_release(device_info *devinfo);
static char *dinput_device_item_name(device_info *devinfo, int offset, const TCHAR *defstring, const TCHAR *suffix);
static HRESULT dinput_device_poll(device_info *devinfo);
static BOOL CALLBACK dinput_keyboard_enum(LPCDIDEVICEINSTANCE instance, LPVOID ref);
static void dinput_keyboard_poll(device_info *devinfo);
static BOOL CALLBACK dinput_mouse_enum(LPCDIDEVICEINSTANCE instance, LPVOID ref);
static void dinput_mouse_poll(device_info *devinfo);
static BOOL CALLBACK dinput_joystick_enum(LPCDIDEVICEINSTANCE instance, LPVOID ref);
static void dinput_joystick_poll(device_info *devinfo);
static INT32 dinput_joystick_pov_get_state(void *device_internal, void *item_internal);
// RawInput-specific code
static void rawinput_init(running_machine *machine);
static void rawinput_exit(running_machine &machine);
static device_info *rawinput_device_create(running_machine *machine, device_info **devlist_head_ptr, PRAWINPUTDEVICELIST device);
static void rawinput_device_release(device_info *info);
static TCHAR *rawinput_device_improve_name(TCHAR *name);
static void rawinput_keyboard_enum(running_machine *machine, PRAWINPUTDEVICELIST device);
static void rawinput_keyboard_update(HANDLE device, RAWKEYBOARD *data);
static void rawinput_mouse_enum(running_machine *machine, PRAWINPUTDEVICELIST device);
static void rawinput_mouse_update(HANDLE device, RAWMOUSE *data);
static void rawinput_mouse_poll(device_info *devinfo);
// misc utilities
static TCHAR *reg_query_string(HKEY key, const TCHAR *path);
static const TCHAR *default_button_name(int which);
static const TCHAR *default_pov_name(int which);
//============================================================
// KEYBOARD/JOYSTICK LIST
//============================================================
// master keyboard translation table
static const int win_key_trans_table[][4] =
{
// MAME key dinput key virtual key ascii
{ ITEM_ID_ESC, DIK_ESCAPE, VK_ESCAPE, 27 },
{ ITEM_ID_1, DIK_1, '1', '1' },
{ ITEM_ID_2, DIK_2, '2', '2' },
{ ITEM_ID_3, DIK_3, '3', '3' },
{ ITEM_ID_4, DIK_4, '4', '4' },
{ ITEM_ID_5, DIK_5, '5', '5' },
{ ITEM_ID_6, DIK_6, '6', '6' },
{ ITEM_ID_7, DIK_7, '7', '7' },
{ ITEM_ID_8, DIK_8, '8', '8' },
{ ITEM_ID_9, DIK_9, '9', '9' },
{ ITEM_ID_0, DIK_0, '0', '0' },
{ ITEM_ID_MINUS, DIK_MINUS, VK_OEM_MINUS, '-' },
{ ITEM_ID_EQUALS, DIK_EQUALS, VK_OEM_PLUS, '=' },
{ ITEM_ID_BACKSPACE, DIK_BACK, VK_BACK, 8 },
{ ITEM_ID_TAB, DIK_TAB, VK_TAB, 9 },
{ ITEM_ID_Q, DIK_Q, 'Q', 'Q' },
{ ITEM_ID_W, DIK_W, 'W', 'W' },
{ ITEM_ID_E, DIK_E, 'E', 'E' },
{ ITEM_ID_R, DIK_R, 'R', 'R' },
{ ITEM_ID_T, DIK_T, 'T', 'T' },
{ ITEM_ID_Y, DIK_Y, 'Y', 'Y' },
{ ITEM_ID_U, DIK_U, 'U', 'U' },
{ ITEM_ID_I, DIK_I, 'I', 'I' },
{ ITEM_ID_O, DIK_O, 'O', 'O' },
{ ITEM_ID_P, DIK_P, 'P', 'P' },
{ ITEM_ID_OPENBRACE, DIK_LBRACKET, VK_OEM_4, '[' },
{ ITEM_ID_CLOSEBRACE, DIK_RBRACKET, VK_OEM_6, ']' },
{ ITEM_ID_ENTER, DIK_RETURN, VK_RETURN, 13 },
{ ITEM_ID_LCONTROL, DIK_LCONTROL, VK_LCONTROL, 0 },
{ ITEM_ID_A, DIK_A, 'A', 'A' },
{ ITEM_ID_S, DIK_S, 'S', 'S' },
{ ITEM_ID_D, DIK_D, 'D', 'D' },
{ ITEM_ID_F, DIK_F, 'F', 'F' },
{ ITEM_ID_G, DIK_G, 'G', 'G' },
{ ITEM_ID_H, DIK_H, 'H', 'H' },
{ ITEM_ID_J, DIK_J, 'J', 'J' },
{ ITEM_ID_K, DIK_K, 'K', 'K' },
{ ITEM_ID_L, DIK_L, 'L', 'L' },
{ ITEM_ID_COLON, DIK_SEMICOLON, VK_OEM_1, ';' },
{ ITEM_ID_QUOTE, DIK_APOSTROPHE, VK_OEM_7, '\'' },
{ ITEM_ID_TILDE, DIK_GRAVE, VK_OEM_3, '`' },
{ ITEM_ID_LSHIFT, DIK_LSHIFT, VK_LSHIFT, 0 },
{ ITEM_ID_BACKSLASH, DIK_BACKSLASH, VK_OEM_5, '\\' },
{ ITEM_ID_Z, DIK_Z, 'Z', 'Z' },
{ ITEM_ID_X, DIK_X, 'X', 'X' },
{ ITEM_ID_C, DIK_C, 'C', 'C' },
{ ITEM_ID_V, DIK_V, 'V', 'V' },
{ ITEM_ID_B, DIK_B, 'B', 'B' },
{ ITEM_ID_N, DIK_N, 'N', 'N' },
{ ITEM_ID_M, DIK_M, 'M', 'M' },
{ ITEM_ID_COMMA, DIK_COMMA, VK_OEM_COMMA, ',' },
{ ITEM_ID_STOP, DIK_PERIOD, VK_OEM_PERIOD, '.' },
{ ITEM_ID_SLASH, DIK_SLASH, VK_OEM_2, '/' },
{ ITEM_ID_RSHIFT, DIK_RSHIFT, VK_RSHIFT, 0 },
{ ITEM_ID_ASTERISK, DIK_MULTIPLY, VK_MULTIPLY, '*' },
{ ITEM_ID_LALT, DIK_LMENU, VK_LMENU, 0 },
{ ITEM_ID_SPACE, DIK_SPACE, VK_SPACE, ' ' },
{ ITEM_ID_CAPSLOCK, DIK_CAPITAL, VK_CAPITAL, 0 },
{ ITEM_ID_F1, DIK_F1, VK_F1, 0 },
{ ITEM_ID_F2, DIK_F2, VK_F2, 0 },
{ ITEM_ID_F3, DIK_F3, VK_F3, 0 },
{ ITEM_ID_F4, DIK_F4, VK_F4, 0 },
{ ITEM_ID_F5, DIK_F5, VK_F5, 0 },
{ ITEM_ID_F6, DIK_F6, VK_F6, 0 },
{ ITEM_ID_F7, DIK_F7, VK_F7, 0 },
{ ITEM_ID_F8, DIK_F8, VK_F8, 0 },
{ ITEM_ID_F9, DIK_F9, VK_F9, 0 },
{ ITEM_ID_F10, DIK_F10, VK_F10, 0 },
{ ITEM_ID_NUMLOCK, DIK_NUMLOCK, VK_NUMLOCK, 0 },
{ ITEM_ID_SCRLOCK, DIK_SCROLL, VK_SCROLL, 0 },
{ ITEM_ID_7_PAD, DIK_NUMPAD7, VK_NUMPAD7, 0 },
{ ITEM_ID_8_PAD, DIK_NUMPAD8, VK_NUMPAD8, 0 },
{ ITEM_ID_9_PAD, DIK_NUMPAD9, VK_NUMPAD9, 0 },
{ ITEM_ID_MINUS_PAD, DIK_SUBTRACT, VK_SUBTRACT, 0 },
{ ITEM_ID_4_PAD, DIK_NUMPAD4, VK_NUMPAD4, 0 },
{ ITEM_ID_5_PAD, DIK_NUMPAD5, VK_NUMPAD5, 0 },
{ ITEM_ID_6_PAD, DIK_NUMPAD6, VK_NUMPAD6, 0 },
{ ITEM_ID_PLUS_PAD, DIK_ADD, VK_ADD, 0 },
{ ITEM_ID_1_PAD, DIK_NUMPAD1, VK_NUMPAD1, 0 },
{ ITEM_ID_2_PAD, DIK_NUMPAD2, VK_NUMPAD2, 0 },
{ ITEM_ID_3_PAD, DIK_NUMPAD3, VK_NUMPAD3, 0 },
{ ITEM_ID_0_PAD, DIK_NUMPAD0, VK_NUMPAD0, 0 },
{ ITEM_ID_DEL_PAD, DIK_DECIMAL, VK_DECIMAL, 0 },
{ ITEM_ID_F11, DIK_F11, VK_F11, 0 },
{ ITEM_ID_F12, DIK_F12, VK_F12, 0 },
{ ITEM_ID_F13, DIK_F13, VK_F13, 0 },
{ ITEM_ID_F14, DIK_F14, VK_F14, 0 },
{ ITEM_ID_F15, DIK_F15, VK_F15, 0 },
{ ITEM_ID_ENTER_PAD, DIK_NUMPADENTER, VK_RETURN, 0 },
{ ITEM_ID_RCONTROL, DIK_RCONTROL, VK_RCONTROL, 0 },
{ ITEM_ID_SLASH_PAD, DIK_DIVIDE, VK_DIVIDE, 0 },
{ ITEM_ID_PRTSCR, DIK_SYSRQ, 0, 0 },
{ ITEM_ID_RALT, DIK_RMENU, VK_RMENU, 0 },
{ ITEM_ID_HOME, DIK_HOME, VK_HOME, 0 },
{ ITEM_ID_UP, DIK_UP, VK_UP, 0 },
{ ITEM_ID_PGUP, DIK_PRIOR, VK_PRIOR, 0 },
{ ITEM_ID_LEFT, DIK_LEFT, VK_LEFT, 0 },
{ ITEM_ID_RIGHT, DIK_RIGHT, VK_RIGHT, 0 },
{ ITEM_ID_END, DIK_END, VK_END, 0 },
{ ITEM_ID_DOWN, DIK_DOWN, VK_DOWN, 0 },
{ ITEM_ID_PGDN, DIK_NEXT, VK_NEXT, 0 },
{ ITEM_ID_INSERT, DIK_INSERT, VK_INSERT, 0 },
{ ITEM_ID_DEL, DIK_DELETE, VK_DELETE, 0 },
{ ITEM_ID_LWIN, DIK_LWIN, VK_LWIN, 0 },
{ ITEM_ID_RWIN, DIK_RWIN, VK_RWIN, 0 },
{ ITEM_ID_MENU, DIK_APPS, VK_APPS, 0 },
{ ITEM_ID_PAUSE, DIK_PAUSE, VK_PAUSE, 0 },
{ ITEM_ID_CANCEL, 0, VK_CANCEL, 0 },
// New keys introduced in Windows 2000. These have no MAME codes to
// preserve compatibility with old config files that may refer to them
// as e.g. FORWARD instead of e.g. KEYCODE_WEBFORWARD. They need table
// entries anyway because otherwise they aren't recognized when
// GetAsyncKeyState polling is used (as happens currently when MAME is
// paused). Some codes are missing because the mapping to vkey codes
// isn't clear, and MapVirtualKey is no help.
{ ITEM_ID_OTHER_SWITCH, DIK_MUTE, VK_VOLUME_MUTE, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_VOLUMEDOWN, VK_VOLUME_DOWN, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_VOLUMEUP, VK_VOLUME_UP, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBHOME, VK_BROWSER_HOME, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBSEARCH, VK_BROWSER_SEARCH, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBFAVORITES, VK_BROWSER_FAVORITES, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBREFRESH, VK_BROWSER_REFRESH, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBSTOP, VK_BROWSER_STOP, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBFORWARD, VK_BROWSER_FORWARD, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_WEBBACK, VK_BROWSER_BACK, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_MAIL, VK_LAUNCH_MAIL, 0 },
{ ITEM_ID_OTHER_SWITCH, DIK_MEDIASELECT, VK_LAUNCH_MEDIA_SELECT, 0 },
};
//============================================================
// INLINE FUNCTIONS
//============================================================
INLINE void poll_if_necessary(running_machine *machine)
{
// make sure we poll at least once every 1/4 second
if (GetTickCount() > last_poll + 1000 / 4)
wininput_poll(machine);
}
INLINE input_item_id keyboard_map_scancode_to_itemid(int scancode)
{
int tablenum;
// scan the table for a match
for (tablenum = 0; tablenum < ARRAY_LENGTH(win_key_trans_table); tablenum++)
if (win_key_trans_table[tablenum][DI_KEY] == scancode)
return (input_item_id)win_key_trans_table[tablenum][MAME_KEY];
// default to an "other" switch
return ITEM_ID_OTHER_SWITCH;
}
INLINE INT32 normalize_absolute_axis(INT32 raw, INT32 rawmin, INT32 rawmax)
{
INT32 center = (rawmax + rawmin) / 2;
// make sure we have valid data
if (rawmin >= rawmax)
return raw;
// above center
if (raw >= center)
{
INT32 result = (INT64)(raw - center) * (INT64)INPUT_ABSOLUTE_MAX / (INT64)(rawmax - center);
return MIN(result, INPUT_ABSOLUTE_MAX);
}
// below center
else
{
INT32 result = -((INT64)(center - raw) * (INT64)-INPUT_ABSOLUTE_MIN / (INT64)(center - rawmin));
return MAX(result, INPUT_ABSOLUTE_MIN);
}
}
//============================================================
// wininput_init
//============================================================
void wininput_init(running_machine *machine)
{
// we need pause and exit callbacks
machine->add_notifier(MACHINE_NOTIFY_PAUSE, wininput_pause);
machine->add_notifier(MACHINE_NOTIFY_RESUME, wininput_resume);
machine->add_notifier(MACHINE_NOTIFY_EXIT, wininput_exit);
// allocate a lock for input synchronizations, since messages sometimes come from another thread
input_lock = osd_lock_alloc();
assert_always(input_lock != NULL, "Failed to allocate input_lock");
// decode the options
lightgun_shared_axis_mode = options_get_bool(machine->options(), WINOPTION_DUAL_LIGHTGUN);
// initialize RawInput and DirectInput (RawInput first so we can fall back)
rawinput_init(machine);
dinput_init(machine);
win32_init(machine);
// poll once to get the initial states
input_enabled = TRUE;
wininput_poll(machine);
}
//============================================================
// wininput_pause
//============================================================
static void wininput_pause(running_machine &machine)
{
// keep track of the paused state
input_paused = true;
}
static void wininput_resume(running_machine &machine)
{
// keep track of the paused state
input_paused = false;
}
//============================================================
// wininput_exit
//============================================================
static void wininput_exit(running_machine &machine)
{
// acquire the lock and turn off input (this ensures everyone is done)
osd_lock_acquire(input_lock);
input_enabled = FALSE;
osd_lock_release(input_lock);
// free the lock
osd_lock_free(input_lock);
}
//============================================================
// wininput_poll
//============================================================
void wininput_poll(running_machine *machine)
{
int hasfocus = winwindow_has_focus() && input_enabled;
// ignore if not enabled
if (input_enabled)
{
// remember when this happened
last_poll = GetTickCount();
// periodically process events, in case they're not coming through
// this also will make sure the mouse state is up-to-date
winwindow_process_events_periodic(machine);
// track if mouse/lightgun is enabled, for mouse hiding purposes
mouse_enabled = input_device_class_enabled(machine, DEVICE_CLASS_MOUSE);
lightgun_enabled = input_device_class_enabled(machine, DEVICE_CLASS_LIGHTGUN);
}
// poll all of the devices
if (hasfocus)
{
device_list_poll_devices(keyboard_list);
device_list_poll_devices(mouse_list);
device_list_poll_devices(lightgun_list);
device_list_poll_devices(joystick_list);
}
else
{
device_list_reset_devices(keyboard_list);
device_list_reset_devices(mouse_list);
device_list_reset_devices(lightgun_list);
device_list_reset_devices(joystick_list);
}
}
//============================================================
// wininput_should_hide_mouse
//============================================================
int wininput_should_hide_mouse(void)
{
// if we are paused or disabled, no
if (input_paused || !input_enabled)
return FALSE;
// if neither mice nor lightguns enabled in the core, then no
if (!mouse_enabled && !lightgun_enabled)
return FALSE;
// if the window has a menu, no
if (win_window_list != NULL && win_has_menu(win_window_list))
return FALSE;
// otherwise, yes
return TRUE;
}
//============================================================
// wininput_handle_mouse_button
//============================================================
BOOL wininput_handle_mouse_button(int button, int down, int x, int y)
{
device_info *devinfo;
// ignore if not enabled
if (!input_enabled)
return FALSE;
// only need this for shared axis hack
if (!lightgun_shared_axis_mode || button >= 4)
return FALSE;
// choose a device based on the button
devinfo = lightgun_list;
if (button >= 2 && devinfo != NULL)
{
button -= 2;
devinfo = devinfo->next;
}
// take the lock
osd_lock_acquire(input_lock);
// set the button state
devinfo->mouse.state.rgbButtons[button] = down ? 0x80 : 0x00;
if (down)
{
RECT client_rect;
POINT mousepos;
// get the position relative to the window
GetClientRect(win_window_list->hwnd, &client_rect);
mousepos.x = x;
mousepos.y = y;
ScreenToClient(win_window_list->hwnd, &mousepos);
// convert to absolute coordinates
devinfo->mouse.state.lX = normalize_absolute_axis(mousepos.x, client_rect.left, client_rect.right);
devinfo->mouse.state.lY = normalize_absolute_axis(mousepos.y, client_rect.top, client_rect.bottom);
}
// release the lock
osd_lock_release(input_lock);
return TRUE;
}
//============================================================
// wininput_handle_raw
//============================================================
BOOL wininput_handle_raw(HANDLE device)
{
BYTE small_buffer[4096];
LPBYTE data = small_buffer;
BOOL result = FALSE;
int size;
// ignore if not enabled
if (!input_enabled)
return result;
// determine the size of databuffer we need
if ((*get_rawinput_data)((HRAWINPUT)device, RID_INPUT, NULL, &size, sizeof(RAWINPUTHEADER)) != 0)
return result;
// if necessary, allocate a temporary buffer and fetch the data
if (size > sizeof(small_buffer))
{
data = global_alloc_array(BYTE, size);
if (data == NULL)
return result;
}
// fetch the data and process the appropriate message types
result = (*get_rawinput_data)((HRAWINPUT)device, RID_INPUT, data, &size, sizeof(RAWINPUTHEADER));
if (result != 0)
{
RAWINPUT *input = (RAWINPUT *)data;
// handle keyboard input
if (input->header.dwType == RIM_TYPEKEYBOARD)
{
osd_lock_acquire(input_lock);
rawinput_keyboard_update(input->header.hDevice, &input->data.keyboard);
osd_lock_release(input_lock);
result = TRUE;
}
// handle mouse input
else if (input->header.dwType == RIM_TYPEMOUSE)
{
osd_lock_acquire(input_lock);
rawinput_mouse_update(input->header.hDevice, &input->data.mouse);
osd_lock_release(input_lock);
result = TRUE;
}
}
// free the temporary buffer and return the result
if (data != small_buffer)
global_free(data);
return result;
}
//============================================================
// wininput_vkey_for_mame_code
//============================================================
int wininput_vkey_for_mame_code(input_code code)
{
// only works for keyboard switches
if (INPUT_CODE_DEVCLASS(code) == DEVICE_CLASS_KEYBOARD && INPUT_CODE_ITEMCLASS(code) == ITEM_CLASS_SWITCH)
{
input_item_id id = INPUT_CODE_ITEMID(code);
int tablenum;
// scan the table for a match
for (tablenum = 0; tablenum < ARRAY_LENGTH(win_key_trans_table); tablenum++)
if (win_key_trans_table[tablenum][MAME_KEY] == id)
return win_key_trans_table[tablenum][VIRTUAL_KEY];
}
return 0;
}
//============================================================
// osd_customize_mapping_list
//============================================================
void osd_customize_input_type_list(input_type_desc *typelist)
{
input_type_desc *typedesc;
// loop over the defaults
for (typedesc = typelist; typedesc != NULL; typedesc = typedesc->next)
switch (typedesc->type)
{
// disable the config menu if the ALT key is down
// (allows ALT-TAB to switch between windows apps)
case IPT_UI_CONFIGURE:
input_seq_set_5(&typedesc->seq[SEQ_TYPE_STANDARD], KEYCODE_TAB, SEQCODE_NOT, KEYCODE_LALT, SEQCODE_NOT, KEYCODE_RALT);
break;
// alt-enter for fullscreen
case IPT_OSD_1:
typedesc->token = "TOGGLE_FULLSCREEN";
typedesc->name = "Toggle Fullscreen";
input_seq_set_2(&typedesc->seq[SEQ_TYPE_STANDARD], KEYCODE_LALT, KEYCODE_ENTER);
break;
case IPT_OSD_2:
if (ui_use_newui())
{
typedesc->token = "TOGGLE_MENUBAR";
typedesc->name = "Toggle Menu Bar";
input_seq_set_1(&typedesc->seq[SEQ_TYPE_STANDARD], KEYCODE_ESC);
}
break;
#ifdef MESS
case IPT_UI_THROTTLE:
input_seq_set_0(&typedesc->seq[SEQ_TYPE_STANDARD]);
break;
#endif
}
}
//============================================================
// device_list_poll_devices
//============================================================
static void device_list_poll_devices(device_info *devlist_head)
{
device_info *curdev;
for (curdev = devlist_head; curdev != NULL; curdev = curdev->next)
if (curdev->poll != NULL)
(*curdev->poll)(curdev);
}
//============================================================
// device_list_reset_devices
//============================================================
static void device_list_reset_devices(device_info *devlist_head)
{
device_info *curdev;
for (curdev = devlist_head; curdev != NULL; curdev = curdev->next)
generic_device_reset(curdev);
}
//============================================================
// generic_device_alloc
//============================================================
static device_info *generic_device_alloc(running_machine *machine, device_info **devlist_head_ptr, const TCHAR *name)
{
device_info **curdev_ptr;
device_info *devinfo;
// allocate memory for the device object
devinfo = global_alloc_clear(device_info);
devinfo->head = devlist_head_ptr;
devinfo->machine = machine;
// allocate a UTF8 copy of the name
devinfo->name = utf8_from_tstring(name);
if (devinfo->name == NULL)
goto error;
// append us to the list
for (curdev_ptr = devinfo->head; *curdev_ptr != NULL; curdev_ptr = &(*curdev_ptr)->next) ;
*curdev_ptr = devinfo;
return devinfo;
error:
global_free(devinfo);
return NULL;
}
//============================================================
// generic_device_free
//============================================================
static void generic_device_free(device_info *devinfo)
{
device_info **curdev_ptr;
// remove us from the list
for (curdev_ptr = devinfo->head; *curdev_ptr != devinfo && *curdev_ptr != NULL; curdev_ptr = &(*curdev_ptr)->next) ;
if (*curdev_ptr == devinfo)
*curdev_ptr = devinfo->next;
// free the copy of the name if present
if (devinfo->name != NULL)
osd_free((void *)devinfo->name);
devinfo->name = NULL;
// and now free the info
global_free(devinfo);
}
//============================================================
// generic_device_index
//============================================================
static int generic_device_index(device_info *devlist_head, device_info *devinfo)
{
int index = 0;
while (devlist_head != NULL)
{
if (devlist_head == devinfo)
return index;
index++;
devlist_head = devlist_head->next;
}
return -1;
}
//============================================================
// generic_device_reset
//============================================================
static void generic_device_reset(device_info *devinfo)
{
// keyboard case
if (devinfo->head == &keyboard_list)
memset(devinfo->keyboard.state, 0, sizeof(devinfo->keyboard.state));
// mouse/lightgun case
else if (devinfo->head == &mouse_list || devinfo->head == &lightgun_list)
memset(&devinfo->mouse.state, 0, sizeof(devinfo->mouse.state));
// joystick case
else if (devinfo->head == &joystick_list)
{
int povnum;
memset(&devinfo->joystick.state, 0, sizeof(devinfo->joystick.state));
for (povnum = 0; povnum < ARRAY_LENGTH(devinfo->joystick.state.rgdwPOV); povnum++)
devinfo->joystick.state.rgdwPOV[povnum] = 0xffff;
}
}
//============================================================
// generic_button_get_state
//============================================================
static INT32 generic_button_get_state(void *device_internal, void *item_internal)
{
device_info *devinfo = (device_info *)device_internal;
BYTE *itemdata = (BYTE *)item_internal;
// return the current state
poll_if_necessary(devinfo->machine);
return *itemdata >> 7;
}
//============================================================
// generic_axis_get_state
//============================================================
static INT32 generic_axis_get_state(void *device_internal, void *item_internal)
{
device_info *devinfo = (device_info *)device_internal;
LONG *axisdata = (LONG *)item_internal;
// return the current state
poll_if_necessary(devinfo->machine);
return *axisdata;
}
//============================================================
// win32_init
//============================================================
static void win32_init(running_machine *machine)
{
int gunnum;
// we don't need any initialization unless we are using shared axis mode for lightguns
if (!lightgun_shared_axis_mode)
return;
// we need an exit callback
machine->add_notifier(MACHINE_NOTIFY_EXIT, win32_exit);
// allocate two lightgun devices
for (gunnum = 0; gunnum < 2; gunnum++)
{
static const TCHAR *const gun_names[] = { TEXT("Shared Axis Gun 1"), TEXT("Shared Axis Gun 2") };
device_info *devinfo;
int axisnum, butnum;
// allocate a device
devinfo = generic_device_alloc(machine, &lightgun_list, gun_names[gunnum]);
if (devinfo == NULL)
break;
// add the device
devinfo->device = input_device_add(machine, DEVICE_CLASS_LIGHTGUN, devinfo->name, devinfo);
// populate the axes
for (axisnum = 0; axisnum < 2; axisnum++)
{
char *name = utf8_from_tstring(default_axis_name[axisnum]);
input_device_item_add(devinfo->device, name, &devinfo->mouse.state.lX + axisnum, (input_item_id)(ITEM_ID_XAXIS + axisnum), generic_axis_get_state);
osd_free(name);
}
// populate the buttons
for (butnum = 0; butnum < 2; butnum++)
{
char *name = utf8_from_tstring(default_button_name(butnum));
input_device_item_add(devinfo->device, name, &devinfo->mouse.state.rgbButtons[butnum], (input_item_id)(ITEM_ID_BUTTON1 + butnum), generic_button_get_state);
osd_free(name);
}
}
}
//============================================================
// win32_exit
//============================================================
static void win32_exit(running_machine &machine)
{
// skip if we're in shared axis mode
if (!lightgun_shared_axis_mode)
return;
// delete the lightgun devices
while (lightgun_list != NULL)
generic_device_free(lightgun_list);
}
//============================================================
// win32_keyboard_poll
//============================================================
static void win32_keyboard_poll(device_info *devinfo)
{
int keynum;
// clear the flag that says we detected a key down via win32
keyboard_win32_reported_key_down = FALSE;
// reset the keyboard state and then repopulate
memset(devinfo->keyboard.state, 0, sizeof(devinfo->keyboard.state));
// iterate over keys
for (keynum = 0; keynum < ARRAY_LENGTH(win_key_trans_table); keynum++)
{
int vk = win_key_trans_table[keynum][VIRTUAL_KEY];
if (vk != 0 && (GetAsyncKeyState(vk) & 0x8000) != 0)
{
int dik = win_key_trans_table[keynum][DI_KEY];
// conver the VK code to a scancode (DIK code)
if (dik != 0)
devinfo->keyboard.state[dik] = 0x80;
// set this flag so that we continue to use win32 until all keys are up
keyboard_win32_reported_key_down = TRUE;
}
}
}
//============================================================
// win32_lightgun_poll
//============================================================
static void win32_lightgun_poll(device_info *devinfo)
{
INT32 xpos = 0, ypos = 0;
POINT mousepos;
// if we are using the shared axis hack, the data is updated via Windows messages only
if (lightgun_shared_axis_mode)
return;
// get the cursor position and transform into final results
GetCursorPos(&mousepos);
if (win_window_list != NULL)
{
RECT client_rect;
// get the position relative to the window
GetClientRect(win_window_list->hwnd, &client_rect);
ScreenToClient(win_window_list->hwnd, &mousepos);
// convert to absolute coordinates
xpos = normalize_absolute_axis(mousepos.x, client_rect.left, client_rect.right);
ypos = normalize_absolute_axis(mousepos.y, client_rect.top, client_rect.bottom);
}
// update the X/Y positions
devinfo->mouse.state.lX = xpos;
devinfo->mouse.state.lY = ypos;
}
//============================================================
// dinput_init
//============================================================
static void dinput_init(running_machine *machine)
{
HRESULT result;
#if DIRECTINPUT_VERSION >= 0x800
int didevtype_keyboard = DI8DEVCLASS_KEYBOARD;
int didevtype_mouse = DI8DEVCLASS_POINTER;
int didevtype_joystick = DI8DEVCLASS_GAMECTRL;
dinput_version = DIRECTINPUT_VERSION;
result = DirectInput8Create(GetModuleHandle(NULL), dinput_version, IID_IDirectInput8, (void **)&dinput, NULL);
if (result != DI_OK)
{
dinput_version = 0;
return;
}
#else
int didevtype_keyboard = DIDEVTYPE_KEYBOARD;
int didevtype_mouse = DIDEVTYPE_MOUSE;
int didevtype_joystick = DIDEVTYPE_JOYSTICK;
// first attempt to initialize DirectInput at the current version
dinput_version = DIRECTINPUT_VERSION;
result = DirectInputCreate(GetModuleHandle(NULL), dinput_version, &dinput, NULL);
if (result != DI_OK)
{
// if that fails, try version 5
dinput_version = 0x0500;
result = DirectInputCreate(GetModuleHandle(NULL), dinput_version, &dinput, NULL);
if (result != DI_OK)
{
// if that fails, try version 3
dinput_version = 0x0300;
result = DirectInputCreate(GetModuleHandle(NULL), dinput_version, &dinput, NULL);
if (result != DI_OK)
{
dinput_version = 0;
return;
}
}
}
#endif
mame_printf_verbose("DirectInput: Using DirectInput %d\n", dinput_version >> 8);
// we need an exit callback
machine->add_notifier(MACHINE_NOTIFY_EXIT, dinput_exit);
// initialize keyboard devices, but only if we don't have any yet
if (keyboard_list == NULL)
{
// enumerate the ones we have
result = IDirectInput_EnumDevices(dinput, didevtype_keyboard, dinput_keyboard_enum, machine, DIEDFL_ATTACHEDONLY);
if (result != DI_OK)
fatalerror("DirectInput: Unable to enumerate keyboards (result=%08X)\n", (UINT32)result);
}
// initialize mouse & lightgun devices, but only if we don't have any yet
if (mouse_list == NULL)
{
// enumerate the ones we have
result = IDirectInput_EnumDevices(dinput, didevtype_mouse, dinput_mouse_enum, machine, DIEDFL_ATTACHEDONLY);
if (result != DI_OK)
fatalerror("DirectInput: Unable to enumerate mice (result=%08X)\n", (UINT32)result);
}
// initialize joystick devices
result = IDirectInput_EnumDevices(dinput, didevtype_joystick, dinput_joystick_enum, machine, DIEDFL_ATTACHEDONLY);
if (result != DI_OK)
fatalerror("DirectInput: Unable to enumerate joysticks (result=%08X)\n", (UINT32)result);
}
//============================================================
// dinput_exit
//============================================================
static void dinput_exit(running_machine &machine)
{
// release all our devices
while (joystick_list != NULL && joystick_list->dinput.device != NULL)
dinput_device_release(joystick_list);
while (lightgun_list != NULL)
generic_device_free(lightgun_list);
while (mouse_list != NULL && mouse_list->dinput.device != NULL)
dinput_device_release(mouse_list);
while (keyboard_list != NULL && keyboard_list->dinput.device != NULL)
dinput_device_release(keyboard_list);
// release DirectInput
if (dinput != NULL)
IDirectInput_Release(dinput);
dinput = NULL;
}
//============================================================
// dinput_set_dword_property
//============================================================
static HRESULT dinput_set_dword_property(LPDIRECTINPUTDEVICE device, REFGUID property_guid, DWORD object, DWORD how, DWORD value)
{
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(dipdw);
dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
dipdw.diph.dwObj = object;
dipdw.diph.dwHow = how;
dipdw.dwData = value;
return IDirectInputDevice_SetProperty(device, property_guid, &dipdw.diph);
}
//============================================================
// dinput_device_create
//============================================================
static device_info *dinput_device_create(running_machine *machine, device_info **devlist_head_ptr, LPCDIDEVICEINSTANCE instance, LPCDIDATAFORMAT format1, LPCDIDATAFORMAT format2, DWORD cooperative_level)
{
device_info *devinfo;
HRESULT result;
// allocate memory for the device object
devinfo = generic_device_alloc(machine, devlist_head_ptr, instance->tszInstanceName);
// attempt to create a device
result = IDirectInput_CreateDevice(dinput, WRAP_REFIID(instance->guidInstance), &devinfo->dinput.device, NULL);
if (result != DI_OK)
goto error;
// try to get a version 2 device for it
result = IDirectInputDevice_QueryInterface(devinfo->dinput.device, WRAP_REFIID(IID_IDirectInputDevice2), (void **)&devinfo->dinput.device2);
if (result != DI_OK)
devinfo->dinput.device2 = NULL;
// get the caps
devinfo->dinput.caps.dwSize = STRUCTSIZE(DIDEVCAPS);
result = IDirectInputDevice_GetCapabilities(devinfo->dinput.device, &devinfo->dinput.caps);
if (result != DI_OK)
goto error;
// attempt to set the data format
devinfo->dinput.format = format1;
result = IDirectInputDevice_SetDataFormat(devinfo->dinput.device, devinfo->dinput.format);
if (result != DI_OK)
{
// use the secondary format if available
if (format2 != NULL)
{
devinfo->dinput.format = format2;
result = IDirectInputDevice_SetDataFormat(devinfo->dinput.device, devinfo->dinput.format);
}
if (result != DI_OK)
goto error;
}
// set the cooperative level
result = IDirectInputDevice_SetCooperativeLevel(devinfo->dinput.device, win_window_list->hwnd, cooperative_level);
if (result != DI_OK)
goto error;
return devinfo;
error:
dinput_device_release(devinfo);
return NULL;
}
//============================================================
// dinput_device_release
//============================================================
static void dinput_device_release(device_info *devinfo)
{
// release the version 2 device if present
if (devinfo->dinput.device2 != NULL)
IDirectInputDevice_Release(devinfo->dinput.device2);
devinfo->dinput.device2 = NULL;
// release the regular device if present
if (devinfo->dinput.device != NULL)
IDirectInputDevice_Release(devinfo->dinput.device);
devinfo->dinput.device = NULL;
// free the item list
generic_device_free(devinfo);
}
//============================================================
// dinput_device_item_name
//============================================================
static char *dinput_device_item_name(device_info *devinfo, int offset, const TCHAR *defstring, const TCHAR *suffix)
{
DIDEVICEOBJECTINSTANCE instance = { 0 };
const TCHAR *namestring = instance.tszName;
TCHAR *combined;
HRESULT result;
char *utf8;
// query the key name
instance.dwSize = STRUCTSIZE(DIDEVICEOBJECTINSTANCE);
result = IDirectInputDevice_GetObjectInfo(devinfo->dinput.device, &instance, offset, DIPH_BYOFFSET);
// if we got an error and have no default string, just return NULL
if (result != DI_OK)
{
if (defstring == NULL)
return NULL;
namestring = defstring;
}
// if no suffix, return as-is
if (suffix == NULL)
return utf8_from_tstring(namestring);
// otherwise, allocate space to add the suffix
combined = global_alloc_array(TCHAR, _tcslen(namestring) + 1 + _tcslen(suffix) + 1);
_tcscpy(combined, namestring);
_tcscat(combined, TEXT(" "));
_tcscat(combined, suffix);
// convert to UTF8, free the temporary string, and return
utf8 = utf8_from_tstring(combined);
global_free(combined);
return utf8;
}
//============================================================
// dinput_device_poll
//============================================================
static HRESULT dinput_device_poll(device_info *devinfo)
{
HRESULT result;
// first poll the device, then get the state
if (devinfo->dinput.device2 != NULL)
IDirectInputDevice2_Poll(devinfo->dinput.device2);
result = IDirectInputDevice_GetDeviceState(devinfo->dinput.device, devinfo->dinput.format->dwDataSize, &devinfo->joystick.state);
// handle lost inputs here
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED)
{
result = IDirectInputDevice_Acquire(devinfo->dinput.device);
if (result == DI_OK)
result = IDirectInputDevice_GetDeviceState(devinfo->dinput.device, devinfo->dinput.format->dwDataSize, &devinfo->joystick.state);
}
return result;
}
//============================================================
// dinput_keyboard_enum
//============================================================
static BOOL CALLBACK dinput_keyboard_enum(LPCDIDEVICEINSTANCE instance, LPVOID ref)
{
running_machine *machine = (running_machine *)ref;
device_info *devinfo;
int keynum;
// allocate and link in a new device
devinfo = dinput_device_create(machine, &keyboard_list, instance, &c_dfDIKeyboard, NULL, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
if (devinfo == NULL)
goto exit;
// add the device
devinfo->device = input_device_add(machine, DEVICE_CLASS_KEYBOARD, devinfo->name, devinfo);
devinfo->poll = dinput_keyboard_poll;
// populate it
for (keynum = 0; keynum < MAX_KEYS; keynum++)
{
input_item_id itemid = keyboard_map_scancode_to_itemid(keynum);
TCHAR defname[20];
char *name;
// generate/fetch the name
_sntprintf(defname, ARRAY_LENGTH(defname), TEXT("Scan%03d"), keynum);
name = dinput_device_item_name(devinfo, keynum, defname, NULL);
// add the item to the device
input_device_item_add(devinfo->device, name, &devinfo->keyboard.state[keynum], itemid, generic_button_get_state);
osd_free(name);
}
exit:
return DIENUM_CONTINUE;
}
//============================================================
// dinput_keyboard_poll
//============================================================
static void dinput_keyboard_poll(device_info *devinfo)
{
HRESULT result = dinput_device_poll(devinfo);
// for the first device, if we errored, or if we previously reported win32 keys,
// then ignore the dinput state and poll using win32
if (devinfo == keyboard_list && (result != DI_OK || keyboard_win32_reported_key_down))
win32_keyboard_poll(devinfo);
}
//============================================================
// dinput_mouse_enum
//============================================================
static BOOL CALLBACK dinput_mouse_enum(LPCDIDEVICEINSTANCE instance, LPVOID ref)
{
device_info *devinfo, *guninfo = NULL;
running_machine *machine = (running_machine *)ref;
int axisnum, butnum;
HRESULT result;
// allocate and link in a new device
devinfo = dinput_device_create(machine, &mouse_list, instance, &c_dfDIMouse2, &c_dfDIMouse, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
if (devinfo == NULL)
goto exit;
// allocate a second device for the gun (unless we are using the shared axis mode)
// we only support a single gun in dinput mode, so only add one
if (!lightgun_shared_axis_mode && devinfo == mouse_list)
{
guninfo = generic_device_alloc(machine, &lightgun_list, instance->tszInstanceName);
if (guninfo == NULL)
goto exit;
}
// set relative mode on the mouse device
result = dinput_set_dword_property(devinfo->dinput.device, DIPROP_AXISMODE, 0, DIPH_DEVICE, DIPROPAXISMODE_REL);
if (result != DI_OK)
{
mame_printf_error("DirectInput: Unable to set relative mode for mouse %d (%s)\n", generic_device_index(mouse_list, devinfo), devinfo->name);
goto error;
}
// add the device
devinfo->device = input_device_add(machine, DEVICE_CLASS_MOUSE, devinfo->name, devinfo);
devinfo->poll = dinput_mouse_poll;
if (guninfo != NULL)
{
guninfo->device = input_device_add(machine, DEVICE_CLASS_LIGHTGUN, guninfo->name, guninfo);
guninfo->poll = win32_lightgun_poll;
}
// cap the number of axes and buttons based on the format
devinfo->dinput.caps.dwAxes = MIN(devinfo->dinput.caps.dwAxes, 3);
devinfo->dinput.caps.dwButtons = MIN(devinfo->dinput.caps.dwButtons, (devinfo->dinput.format == &c_dfDIMouse) ? 4 : 8);
// populate the axes
for (axisnum = 0; axisnum < devinfo->dinput.caps.dwAxes; axisnum++)
{
char *name = dinput_device_item_name(devinfo, offsetof(DIMOUSESTATE, lX) + axisnum * sizeof(LONG), default_axis_name[axisnum], NULL);
// add to the mouse device and optionally to the gun device as well
input_device_item_add(devinfo->device, name, &devinfo->mouse.state.lX + axisnum, (input_item_id)(ITEM_ID_XAXIS + axisnum), generic_axis_get_state);
if (guninfo != NULL && axisnum < 2)
input_device_item_add(guninfo->device, name, &guninfo->mouse.state.lX + axisnum, (input_item_id)(ITEM_ID_XAXIS + axisnum), generic_axis_get_state);
osd_free(name);
}
// populate the buttons
for (butnum = 0; butnum < devinfo->dinput.caps.dwButtons; butnum++)
{
FPTR offset = (FPTR)(&((DIMOUSESTATE *)NULL)->rgbButtons[butnum]);
char *name = dinput_device_item_name(devinfo, offset, default_button_name(butnum), NULL);
// add to the mouse device and optionally to the gun device as well
// note that the gun device points to the mouse buttons rather than its own
input_device_item_add(devinfo->device, name, &devinfo->mouse.state.rgbButtons[butnum], (input_item_id)(ITEM_ID_BUTTON1 + butnum), generic_button_get_state);
if (guninfo != NULL)
input_device_item_add(guninfo->device, name, &devinfo->mouse.state.rgbButtons[butnum], (input_item_id)(ITEM_ID_BUTTON1 + butnum), generic_button_get_state);
osd_free(name);
}
exit:
return DIENUM_CONTINUE;
error:
if (guninfo != NULL)
generic_device_free(guninfo);
if (devinfo != NULL)
dinput_device_release(devinfo);
goto exit;
}
//============================================================
// dinput_mouse_poll
//============================================================
static void dinput_mouse_poll(device_info *devinfo)
{
// poll
dinput_device_poll(devinfo);
// scale the axis data
devinfo->mouse.state.lX *= INPUT_RELATIVE_PER_PIXEL;
devinfo->mouse.state.lY *= INPUT_RELATIVE_PER_PIXEL;
devinfo->mouse.state.lZ *= INPUT_RELATIVE_PER_PIXEL;
}
//============================================================
// dinput_joystick_enum
//============================================================
static BOOL CALLBACK dinput_joystick_enum(LPCDIDEVICEINSTANCE instance, LPVOID ref)
{
DWORD cooperative_level = (HAS_WINDOW_MENU ? DISCL_BACKGROUND : DISCL_FOREGROUND) | DISCL_EXCLUSIVE;
int axisnum, axiscount, povnum, butnum;
running_machine *machine = (running_machine *)ref;
device_info *devinfo;
HRESULT result;
// allocate and link in a new device
devinfo = dinput_device_create(machine, &joystick_list, instance, &c_dfDIJoystick, NULL, cooperative_level);
if (devinfo == NULL)
goto exit;
// set absolute mode
result = dinput_set_dword_property(devinfo->dinput.device, DIPROP_AXISMODE, 0, DIPH_DEVICE, DIPROPAXISMODE_ABS);
if (result != DI_OK)
mame_printf_warning("DirectInput: Unable to set absolute mode for joystick %d (%s)\n", generic_device_index(joystick_list, devinfo), devinfo->name);
// turn off deadzone; we do our own calculations
result = dinput_set_dword_property(devinfo->dinput.device, DIPROP_DEADZONE, 0, DIPH_DEVICE, 0);
if (result != DI_OK)
mame_printf_warning("DirectInput: Unable to reset deadzone for joystick %d (%s)\n", generic_device_index(joystick_list, devinfo), devinfo->name);
// turn off saturation; we do our own calculations
result = dinput_set_dword_property(devinfo->dinput.device, DIPROP_SATURATION, 0, DIPH_DEVICE, 10000);
if (result != DI_OK)
mame_printf_warning("DirectInput: Unable to reset saturation for joystick %d (%s)\n", generic_device_index(joystick_list, devinfo), devinfo->name);
// cap the number of axes, POVs, and buttons based on the format
devinfo->dinput.caps.dwAxes = MIN(devinfo->dinput.caps.dwAxes, 8);
devinfo->dinput.caps.dwPOVs = MIN(devinfo->dinput.caps.dwPOVs, 4);
devinfo->dinput.caps.dwButtons = MIN(devinfo->dinput.caps.dwButtons, 128);
// add the device
devinfo->device = input_device_add(machine, DEVICE_CLASS_JOYSTICK, devinfo->name, devinfo);
devinfo->poll = dinput_joystick_poll;
// populate the axes
for (axisnum = axiscount = 0; axiscount < devinfo->dinput.caps.dwAxes && axisnum < 8; axisnum++)
{
DIPROPRANGE dipr;
char *name;
// fetch the range of this axis
dipr.diph.dwSize = sizeof(dipr);
dipr.diph.dwHeaderSize = sizeof(dipr.diph);
dipr.diph.dwObj = offsetof(DIJOYSTATE2, lX) + axisnum * sizeof(LONG);
dipr.diph.dwHow = DIPH_BYOFFSET;
result = IDirectInputDevice_GetProperty(devinfo->dinput.device, DIPROP_RANGE, &dipr.diph);
if (result != DI_OK)
continue;
devinfo->joystick.rangemin[axisnum] = dipr.lMin;
devinfo->joystick.rangemax[axisnum] = dipr.lMax;
// populate the item description as well
name = dinput_device_item_name(devinfo, offsetof(DIJOYSTATE2, lX) + axisnum * sizeof(LONG), default_axis_name[axisnum], NULL);
input_device_item_add(devinfo->device, name, &devinfo->joystick.state.lX + axisnum, (input_item_id)(ITEM_ID_XAXIS + axisnum), generic_axis_get_state);
osd_free(name);
axiscount++;
}
// populate the POVs
for (povnum = 0; povnum < devinfo->dinput.caps.dwPOVs; povnum++)
{
char *name;
// left
name = dinput_device_item_name(devinfo, offsetof(DIJOYSTATE2, rgdwPOV) + povnum * sizeof(DWORD), default_pov_name(povnum), TEXT("L"));
input_device_item_add(devinfo->device, name, (void *)(FPTR)(povnum * 4 + POVDIR_LEFT), ITEM_ID_OTHER_SWITCH, dinput_joystick_pov_get_state);
osd_free(name);
// right
name = dinput_device_item_name(devinfo, offsetof(DIJOYSTATE2, rgdwPOV) + povnum * sizeof(DWORD), default_pov_name(povnum), TEXT("R"));
input_device_item_add(devinfo->device, name, (void *)(FPTR)(povnum * 4 + POVDIR_RIGHT), ITEM_ID_OTHER_SWITCH, dinput_joystick_pov_get_state);
osd_free(name);
// up
name = dinput_device_item_name(devinfo, offsetof(DIJOYSTATE2, rgdwPOV) + povnum * sizeof(DWORD), default_pov_name(povnum), TEXT("U"));
input_device_item_add(devinfo->device, name, (void *)(FPTR)(povnum * 4 + POVDIR_UP), ITEM_ID_OTHER_SWITCH, dinput_joystick_pov_get_state);
osd_free(name);
// down
name = dinput_device_item_name(devinfo, offsetof(DIJOYSTATE2, rgdwPOV) + povnum * sizeof(DWORD), default_pov_name(povnum), TEXT("D"));
input_device_item_add(devinfo->device, name, (void *)(FPTR)(povnum * 4 + POVDIR_DOWN), ITEM_ID_OTHER_SWITCH, dinput_joystick_pov_get_state);
osd_free(name);
}
// populate the buttons
for (butnum = 0; butnum < devinfo->dinput.caps.dwButtons; butnum++)
{
FPTR offset = (FPTR)(&((DIJOYSTATE2 *)NULL)->rgbButtons[butnum]);
char *name = dinput_device_item_name(devinfo, offset, default_button_name(butnum), NULL);
input_device_item_add(devinfo->device, name, &devinfo->joystick.state.rgbButtons[butnum], (butnum < 16) ? (input_item_id)(ITEM_ID_BUTTON1 + butnum) : ITEM_ID_OTHER_SWITCH, generic_button_get_state);
osd_free(name);
}
exit:
return DIENUM_CONTINUE;
}
//============================================================
// dinput_joystick_poll
//============================================================
static void dinput_joystick_poll(device_info *devinfo)
{
int axisnum;
// poll the device first
dinput_device_poll(devinfo);
// normalize axis values
for (axisnum = 0; axisnum < 8; axisnum++)
{
LONG *axis = (&devinfo->joystick.state.lX) + axisnum;
*axis = normalize_absolute_axis(*axis, devinfo->joystick.rangemin[axisnum], devinfo->joystick.rangemax[axisnum]);
}
}
//============================================================
// dinput_joystick_pov_get_state
//============================================================
static INT32 dinput_joystick_pov_get_state(void *device_internal, void *item_internal)
{
device_info *devinfo = (device_info *)device_internal;
int povnum = (FPTR)item_internal / 4;
int povdir = (FPTR)item_internal % 4;
INT32 result = 0;
DWORD pov;
// get the current state
poll_if_necessary(devinfo->machine);
pov = devinfo->joystick.state.rgdwPOV[povnum];
// if invalid, return 0
if ((pov & 0xffff) == 0xffff)
return result;
// return the current state
switch (povdir)
{
case POVDIR_LEFT: result = (pov >= 22500 && pov <= 31500); break;
case POVDIR_RIGHT: result = (pov >= 4500 && pov <= 13500); break;
case POVDIR_UP: result = (pov >= 31500 || pov <= 4500); break;
case POVDIR_DOWN: result = (pov >= 13500 && pov <= 22500); break;
}
return result;
}
//============================================================
// rawinput_init
//============================================================
static void rawinput_init(running_machine *machine)
{
RAWINPUTDEVICELIST *devlist = NULL;
int device_count, devnum, regcount;
RAWINPUTDEVICE reglist[2];
HMODULE user32;
// we need pause and exit callbacks
machine->add_notifier(MACHINE_NOTIFY_EXIT, rawinput_exit);
// look in user32 for the raw input APIs
user32 = LoadLibrary(TEXT("user32.dll"));
if (user32 == NULL)
goto error;
// look up the entry points
register_rawinput_devices = (register_rawinput_devices_ptr)GetProcAddress(user32, "RegisterRawInputDevices");
get_rawinput_device_list = (get_rawinput_device_list_ptr)GetProcAddress(user32, "GetRawInputDeviceList");
get_rawinput_device_info = (get_rawinput_device_info_ptr)GetProcAddress(user32, "GetRawInputDeviceInfo" UNICODE_SUFFIX);
get_rawinput_data = (get_rawinput_data_ptr)GetProcAddress(user32, "GetRawInputData");
if (register_rawinput_devices == NULL || get_rawinput_device_list == NULL || get_rawinput_device_info == NULL || get_rawinput_data == NULL)
goto error;
mame_printf_verbose("RawInput: APIs detected\n");
// get the number of devices, allocate a device list, and fetch it
if ((*get_rawinput_device_list)(NULL, &device_count, sizeof(*devlist)) != 0)
goto error;
if (device_count == 0)
goto error;
devlist = global_alloc_array(RAWINPUTDEVICELIST, device_count);
if ((*get_rawinput_device_list)(devlist, &device_count, sizeof(*devlist)) == -1)
goto error;
// iterate backwards through devices; new devices are added at the head
for (devnum = device_count - 1; devnum >= 0; devnum--)
{
RAWINPUTDEVICELIST *device = &devlist[devnum];
// handle keyboards
if (device->dwType == RIM_TYPEKEYBOARD && !FORCE_DIRECTINPUT)
rawinput_keyboard_enum(machine, device);
// handle mice
else if (device->dwType == RIM_TYPEMOUSE && !FORCE_DIRECTINPUT)
rawinput_mouse_enum(machine, device);
}
// finally, register to recieve raw input WM_INPUT messages
regcount = 0;
if (keyboard_list != NULL)
{
reglist[regcount].usUsagePage = 0x01;
reglist[regcount].usUsage = 0x06;
reglist[regcount].dwFlags = RIDEV_INPUTSINK;
reglist[regcount].hwndTarget = win_window_list->hwnd;
regcount++;
}
if (mouse_list != NULL)
{
reglist[regcount].usUsagePage = 0x01;
reglist[regcount].usUsage = 0x02;
reglist[regcount].dwFlags = 0;
reglist[regcount].hwndTarget = win_window_list->hwnd;
regcount++;
}
// if the registration fails, we need to back off
if (regcount > 0)
if (!(*register_rawinput_devices)(reglist, regcount, sizeof(reglist[0])))
goto error;
global_free(devlist);
return;
error:
if (devlist != NULL)
global_free(devlist);
}
//============================================================
// rawinput_exit
//============================================================
static void rawinput_exit(running_machine &machine)
{
// release all our devices
while (lightgun_list != NULL && lightgun_list->rawinput.device != NULL)
rawinput_device_release(lightgun_list);
while (mouse_list != NULL && mouse_list->rawinput.device != NULL)
rawinput_device_release(mouse_list);
while (keyboard_list != NULL && keyboard_list->rawinput.device != NULL)
rawinput_device_release(keyboard_list);
}
//============================================================
// rawinput_device_create
//============================================================
static device_info *rawinput_device_create(running_machine *machine, device_info **devlist_head_ptr, PRAWINPUTDEVICELIST device)
{
device_info *devinfo = NULL;
TCHAR *tname = NULL;
INT name_length;
// determine the length of the device name, allocate it, and fetch it
if ((*get_rawinput_device_info)(device->hDevice, RIDI_DEVICENAME, NULL, &name_length) != 0)
goto error;
tname = global_alloc_array(TCHAR, name_length);
if ((*get_rawinput_device_info)(device->hDevice, RIDI_DEVICENAME, tname, &name_length) == -1)
goto error;
// if this is an RDP name, skip it
if (_tcsstr(tname, TEXT("Root#RDP_")) != NULL)
goto error;
// improve the name and then allocate a device
tname = rawinput_device_improve_name(tname);
devinfo = generic_device_alloc(machine, devlist_head_ptr, tname);
global_free(tname);
// copy the handle
devinfo->rawinput.device = device->hDevice;
return devinfo;
error:
if (tname != NULL)
global_free(tname);
if (devinfo != NULL)
rawinput_device_release(devinfo);
return NULL;
}
//============================================================
// rawinput_device_release
//============================================================
static void rawinput_device_release(device_info *devinfo)
{
// free the item list
generic_device_free(devinfo);
}
//============================================================
// rawinput_device_improve_name
//============================================================
static TCHAR *rawinput_device_improve_name(TCHAR *name)
{
static const TCHAR usbbasepath[] = TEXT("SYSTEM\\CurrentControlSet\\Enum\\USB");
static const TCHAR basepath[] = TEXT("SYSTEM\\CurrentControlSet\\Enum\\");
TCHAR *regstring = NULL;
TCHAR *parentid = NULL;
TCHAR *regpath = NULL;
const TCHAR *chsrc;
HKEY regkey = NULL;
int usbindex;
TCHAR *chdst;
LONG result;
// The RAW name received is formatted as:
// \??\type-id#hardware-id#instance-id#{DeviceClasses-id}
// XP starts with "\??\"
// Vista64 starts with "\\?\"
// ensure the name is something we can handle
if (_tcsncmp(name, TEXT("\\\\?\\"), 4) != 0 && _tcsncmp(name, TEXT("\\??\\"), 4) != 0)
return name;
// allocate a temporary string and concatenate the base path plus the name
regpath = global_alloc_array(TCHAR, _tcslen(basepath) + 1 + _tcslen(name));
_tcscpy(regpath, basepath);
chdst = regpath + _tcslen(regpath);
// convert all # to \ in the name
for (chsrc = name + 4; *chsrc != 0; chsrc++)
*chdst++ = (*chsrc == '#') ? '\\' : *chsrc;
*chdst = 0;
// remove the final chunk
chdst = _tcsrchr(regpath, '\\');
if (chdst == NULL)
goto exit;
*chdst = 0;
// now try to open the registry key
result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, ®key);
if (result != ERROR_SUCCESS)
goto exit;
// fetch the device description; if it exists, we are finished
regstring = reg_query_string(regkey, TEXT("DeviceDesc"));
if (regstring != NULL)
goto convert;
// close this key
RegCloseKey(regkey);
regkey = NULL;
// if the key name does not contain "HID", it's not going to be in the USB tree; give up
if (_tcsstr(regpath, TEXT("HID")) == NULL)
goto exit;
// extract the expected parent ID from the regpath
parentid = _tcsrchr(regpath, '\\');
if (parentid == NULL)
goto exit;
parentid++;
// open the USB key
result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, usbbasepath, 0, KEY_READ, ®key);
if (result != ERROR_SUCCESS)
goto exit;
// enumerate the USB key
for (usbindex = 0; result == ERROR_SUCCESS && regstring == NULL; usbindex++)
{
TCHAR keyname[MAX_PATH];
DWORD namelen;
// get the next enumerated subkey and scan it
namelen = ARRAY_LENGTH(keyname) - 1;
result = RegEnumKeyEx(regkey, usbindex, keyname, &namelen, NULL, NULL, NULL, NULL);
if (result == ERROR_SUCCESS)
{
LONG subresult;
int subindex;
HKEY subkey;
// open the subkey
subresult = RegOpenKeyEx(regkey, keyname, 0, KEY_READ, &subkey);
if (subresult != ERROR_SUCCESS)
continue;
// enumerate the subkey
for (subindex = 0; subresult == ERROR_SUCCESS && regstring == NULL; subindex++)
{
// get the next enumerated subkey and scan it
namelen = ARRAY_LENGTH(keyname) - 1;
subresult = RegEnumKeyEx(subkey, subindex, keyname, &namelen, NULL, NULL, NULL, NULL);
if (subresult == ERROR_SUCCESS)
{
TCHAR *endparentid;
LONG endresult;
HKEY endkey;
// open this final key
endresult = RegOpenKeyEx(subkey, keyname, 0, KEY_READ, &endkey);
if (endresult != ERROR_SUCCESS)
continue;
// do we have a match?
endparentid = reg_query_string(endkey, TEXT("ParentIdPrefix"));
if (endparentid != NULL && _tcsncmp(parentid, endparentid, _tcslen(endparentid)) == 0)
regstring = reg_query_string(endkey, TEXT("DeviceDesc"));
// free memory and close the key
if (endparentid != NULL)
global_free(endparentid);
RegCloseKey(endkey);
}
}
// close the subkey
RegCloseKey(subkey);
}
}
// if we didn't find anything, go to the exit
if (regstring == NULL)
goto exit;
convert:
// replace the name with the nicer one
global_free(name);
// remove anything prior to the final semicolon
chsrc = _tcsrchr(regstring, ';');
if (chsrc != NULL)
chsrc++;
else
chsrc = regstring;
name = global_alloc_array(TCHAR, _tcslen(chsrc) + 1);
_tcscpy(name, chsrc);
exit:
if (regstring != NULL)
global_free(regstring);
if (regpath != NULL)
global_free(regpath);
if (regkey != NULL)
RegCloseKey(regkey);
return name;
}
//============================================================
// rawinput_keyboard_enum
//============================================================
static void rawinput_keyboard_enum(running_machine *machine, PRAWINPUTDEVICELIST device)
{
device_info *devinfo;
int keynum;
// allocate and link in a new device
devinfo = rawinput_device_create(machine, &keyboard_list, device);
if (devinfo == NULL)
return;
// add the device
devinfo->device = input_device_add(machine, DEVICE_CLASS_KEYBOARD, devinfo->name, devinfo);
// populate it
for (keynum = 0; keynum < MAX_KEYS; keynum++)
{
input_item_id itemid = keyboard_map_scancode_to_itemid(keynum);
TCHAR keyname[100];
char *name;
// generate the name
if (GetKeyNameText(((keynum & 0x7f) << 16) | ((keynum & 0x80) << 17), keyname, ARRAY_LENGTH(keyname)) == 0)
_sntprintf(keyname, ARRAY_LENGTH(keyname), TEXT("Scan%03d"), keynum);
name = utf8_from_tstring(keyname);
// add the item to the device
input_device_item_add(devinfo->device, name, &devinfo->keyboard.state[keynum], itemid, generic_button_get_state);
osd_free(name);
}
}
//============================================================
// rawinput_keyboard_update
//============================================================
static void rawinput_keyboard_update(HANDLE device, RAWKEYBOARD *data)
{
device_info *devinfo;
// find the keyboard in the list and process
for (devinfo = keyboard_list; devinfo != NULL; devinfo = devinfo->next)
if (devinfo->rawinput.device == device)
{
// determine the full DIK-compatible scancode
UINT8 scancode = (data->MakeCode & 0x7f) | ((data->Flags & RI_KEY_E0) ? 0x80 : 0x00);
// scancode 0xaa is a special shift code we need to ignore
if (scancode == 0xaa)
break;
// set or clear the key
if (!(data->Flags & RI_KEY_BREAK))
devinfo->keyboard.state[scancode] = 0x80;
else
devinfo->keyboard.state[scancode] = 0x00;
break;
}
}
//============================================================
// rawinput_mouse_enum
//============================================================
static void rawinput_mouse_enum(running_machine *machine, PRAWINPUTDEVICELIST device)
{
device_info *devinfo, *guninfo = NULL;
int axisnum, butnum;
// allocate and link in a new mouse device
devinfo = rawinput_device_create(machine, &mouse_list, device);
if (devinfo == NULL)
return;
devinfo->poll = rawinput_mouse_poll;
// allocate a second device for the gun (unless we are using the shared axis mode)
if (!lightgun_shared_axis_mode)
{
guninfo = rawinput_device_create(machine, &lightgun_list, device);
assert(guninfo != NULL);
}
// add the device
devinfo->device = input_device_add(machine, DEVICE_CLASS_MOUSE, devinfo->name, devinfo);
if (guninfo != NULL)
{
guninfo->device = input_device_add(machine, DEVICE_CLASS_LIGHTGUN, guninfo->name, guninfo);
guninfo->poll = NULL;
}
// populate the axes
for (axisnum = 0; axisnum < 3; axisnum++)
{
char *name = utf8_from_tstring(default_axis_name[axisnum]);
// add to the mouse device and optionally to the gun device as well
input_device_item_add(devinfo->device, name, &devinfo->mouse.state.lX + axisnum, (input_item_id)(ITEM_ID_XAXIS + axisnum), generic_axis_get_state);
if (guninfo != NULL && axisnum < 2)
input_device_item_add(guninfo->device, name, &guninfo->mouse.state.lX + axisnum, (input_item_id)(ITEM_ID_XAXIS + axisnum), generic_axis_get_state);
osd_free(name);
}
// populate the buttons
for (butnum = 0; butnum < 5; butnum++)
{
char *name = utf8_from_tstring(default_button_name(butnum));
// add to the mouse device and optionally to the gun device as well
input_device_item_add(devinfo->device, name, &devinfo->mouse.state.rgbButtons[butnum], (input_item_id)(ITEM_ID_BUTTON1 + butnum), generic_button_get_state);
if (guninfo != NULL)
input_device_item_add(guninfo->device, name, &guninfo->mouse.state.rgbButtons[butnum], (input_item_id)(ITEM_ID_BUTTON1 + butnum), generic_button_get_state);
osd_free(name);
}
}
//============================================================
// rawinput_mouse_update
//============================================================
static void rawinput_mouse_update(HANDLE device, RAWMOUSE *data)
{
device_info *devlist = (data->usFlags & MOUSE_MOVE_ABSOLUTE) ? lightgun_list : mouse_list;
device_info *devinfo;
// find the mouse in the list and process
for (devinfo = devlist; devinfo != NULL; devinfo = devinfo->next)
if (devinfo->rawinput.device == device)
{
// if we got relative data, update it as a mouse
if (!(data->usFlags & MOUSE_MOVE_ABSOLUTE))
{
devinfo->mouse.raw_x += data->lLastX * INPUT_RELATIVE_PER_PIXEL;
devinfo->mouse.raw_y += data->lLastY * INPUT_RELATIVE_PER_PIXEL;
// update zaxis
if (data->usButtonFlags & RI_MOUSE_WHEEL)
devinfo->mouse.raw_z += (INT16)data->usButtonData * INPUT_RELATIVE_PER_PIXEL;
}
// otherwise, update it as a lightgun
else
{
devinfo->mouse.state.lX = normalize_absolute_axis(data->lLastX, 0, 0xffff);
devinfo->mouse.state.lY = normalize_absolute_axis(data->lLastY, 0, 0xffff);
}
// update the button states; always update the corresponding mouse buttons
if (data->usButtonFlags & RI_MOUSE_BUTTON_1_DOWN) devinfo->mouse.state.rgbButtons[0] = 0x80;
if (data->usButtonFlags & RI_MOUSE_BUTTON_1_UP) devinfo->mouse.state.rgbButtons[0] = 0x00;
if (data->usButtonFlags & RI_MOUSE_BUTTON_2_DOWN) devinfo->mouse.state.rgbButtons[1] = 0x80;
if (data->usButtonFlags & RI_MOUSE_BUTTON_2_UP) devinfo->mouse.state.rgbButtons[1] = 0x00;
if (data->usButtonFlags & RI_MOUSE_BUTTON_3_DOWN) devinfo->mouse.state.rgbButtons[2] = 0x80;
if (data->usButtonFlags & RI_MOUSE_BUTTON_3_UP) devinfo->mouse.state.rgbButtons[2] = 0x00;
if (data->usButtonFlags & RI_MOUSE_BUTTON_4_DOWN) devinfo->mouse.state.rgbButtons[3] = 0x80;
if (data->usButtonFlags & RI_MOUSE_BUTTON_4_UP) devinfo->mouse.state.rgbButtons[3] = 0x00;
if (data->usButtonFlags & RI_MOUSE_BUTTON_5_DOWN) devinfo->mouse.state.rgbButtons[4] = 0x80;
if (data->usButtonFlags & RI_MOUSE_BUTTON_5_UP) devinfo->mouse.state.rgbButtons[4] = 0x00;
break;
}
}
//============================================================
// rawinput_mouse_poll
//============================================================
static void rawinput_mouse_poll(device_info *devinfo)
{
poll_if_necessary(devinfo->machine);
// copy the accumulated raw state to the actual state
osd_lock_acquire(input_lock);
devinfo->mouse.state.lX = devinfo->mouse.raw_x;
devinfo->mouse.state.lY = devinfo->mouse.raw_y;
devinfo->mouse.state.lZ = devinfo->mouse.raw_z;
devinfo->mouse.raw_x = 0;
devinfo->mouse.raw_y = 0;
devinfo->mouse.raw_z = 0;
osd_lock_release(input_lock);
}
//============================================================
// reg_query_string
//============================================================
static TCHAR *reg_query_string(HKEY key, const TCHAR *path)
{
TCHAR *buffer;
DWORD datalen;
LONG result;
// first query to get the length
result = RegQueryValueEx(key, path, NULL, NULL, NULL, &datalen);
if (result != ERROR_SUCCESS)
return NULL;
// allocate a buffer
buffer = global_alloc_array(TCHAR, datalen + sizeof(*buffer));
buffer[datalen / sizeof(*buffer)] = 0;
// now get the actual data
result = RegQueryValueEx(key, path, NULL, NULL, (LPBYTE)buffer, &datalen);
if (result == ERROR_SUCCESS)
return buffer;
// otherwise return a NULL buffer
global_free(buffer);
return NULL;
}
//============================================================
// default_button_name
//============================================================
static const TCHAR *default_button_name(int which)
{
static TCHAR buffer[20];
_sntprintf(buffer, ARRAY_LENGTH(buffer), TEXT("B%d"), which);
return buffer;
}
//============================================================
// default_pov_name
//============================================================
static const TCHAR *default_pov_name(int which)
{
static TCHAR buffer[20];
_sntprintf(buffer, ARRAY_LENGTH(buffer), TEXT("POV%d"), which);
return buffer;
}
| 33.346467 | 205 | 0.635904 | [
"object",
"transform"
] |
3c11a6e4fbdc7b2d345057bc9af51db14fa42119 | 4,218 | h | C | bindings/C/c/adios2_c_adios.h | aronhelser/ADIOS2 | 6577a335c5a95f47fbf76905f509cd379e602a4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | bindings/C/c/adios2_c_adios.h | aronhelser/ADIOS2 | 6577a335c5a95f47fbf76905f509cd379e602a4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | bindings/C/c/adios2_c_adios.h | aronhelser/ADIOS2 | 6577a335c5a95f47fbf76905f509cd379e602a4d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* adios2_c_adios.h
*
* Created on: Nov 8, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#ifndef ADIOS2_BINDINGS_C_C_ADIOS2_C_ADIOS_H_
#define ADIOS2_BINDINGS_C_C_ADIOS2_C_ADIOS_H_
#include "adios2_c_types.h"
#ifdef ADIOS2_HAVE_MPI
#include <mpi.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef ADIOS2_HAVE_MPI
/**
* Starting point for MPI apps. Creates an ADIOS handler.
* @param comm defines domain scope from application
* @param debug_mode true: extra user-input debugging information, false:
* run without checking user-input (stable workflows)
* @return success: handler, failure: NULL
*/
adios2_adios *adios2_init(MPI_Comm comm, const adios2_debug_mode debug_mode);
/**
* Starting point for MPI apps. Creates an ADIOS handler allowing a runtime
* config file.
* @param config_file runtime configuration file in xml format
* @param comm defines domain scope from application
* @param debug_mode true: extra user-input debugging information, false:
* run without checking user-input (stable workflows)
* @return success: handler, failure: NULL
*/
adios2_adios *adios2_init_config(const char *config_file, MPI_Comm comm,
const adios2_debug_mode debug_mode);
#else
/**
* Initialize an ADIOS struct pointer handler in a serial, non-MPI application.
* Doesn't require a runtime config file.
* @param debug_mode adios2_debug_mode_on or adios2_debug_mode_off, adds extra
* checking to user input to be captured by adios2_error. Use it for stable
* workflows
* @return success: handler, failure: NULL
*/
adios2_adios *adios2_init(const adios2_debug_mode debug_mode);
/**
* Initialize an ADIOS struct pointer handler in a serial, non-MPI application.
* Doesn't require a runtime config file.
* @param debug_mode adios2_debug_mode_on or adios2_debug_mode_off, adds extra
* checking to user input to be captured by adios2_error. Use it for stable
* workflows
* @return success: handler, failure: NULL
*/
adios2_adios *adios2_init_config(const char *config_file,
const adios2_debug_mode debug_mode);
#endif
/**
* Declares a new io handler
* @param adios owner the io handler
* @param name unique io identifier within current adios handler
* @return success: handler, failure: NULL
*/
adios2_io *adios2_declare_io(adios2_adios *adios, const char *name);
/**
* Retrieves a previously declared io handler by name
* @param adios owner the io handler
* @param name unique name for the previously declared io handler
* @return success: handler, failure: NULL
*/
adios2_io *adios2_at_io(adios2_adios *adios, const char *name);
/**
* Defines an adios2 supported operator by its type.
* @param adios owner the op handler
* @param name unique operator name identifier within current ADIOS object
* @param type supported ADIOS2 operator type: zfp, sz
* @return success: handler, failure: NULL
*/
adios2_operator *adios2_define_operator(adios2_adios *adios, const char *name,
const char *type);
/**
* Retrieves a previously defined operator handler
* @param adios owner the op handler
* @param name unique name for the previously defined op handler
* @return success: handler, failure: NULL
*/
adios2_operator *adios2_inquire_operator(adios2_adios *adios, const char *name);
/**
* Flushes all adios2_engine in write mode in all adios2_io handlers.
* If no adios2_io or adios2_engine exists it does nothing.
* @param adios owner of all io and engines to be flushed
* @return adios2_error 0: success, see enum adios2_error for errors
*/
adios2_error adios2_flush_all(adios2_adios *adios);
/**
* Final point for adios handler. Deallocates adios pointer. Required to avoid
* memory leaks.
* @param adios handler to be deallocated, must be initialized with
* adios2_init or adios2_init_config
* @return adios2_error 0: success, see enum adios2_error for errors
*/
adios2_error adios2_finalize(adios2_adios *adios);
#ifdef __cplusplus
} // end extern C
#endif
#endif /* ADIOS2_BINDINGS_C_C_ADIOS2_C_ADIOS_H_ */
| 33.47619 | 80 | 0.747511 | [
"object"
] |
3c1c8cfd4366d342c3cc245c5ce2fabd60dab1ce | 1,740 | h | C | Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/LandscapeCanvas/Code/Source/Editor/Core/GraphContext.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
// AZ
#include <AzCore/std/smart_ptr/enable_shared_from_this.h>
// GraphModel
#include <GraphModel/Model/IGraphContext.h>
// Landscape Canvas
#include <Editor/Core/DataTypes.h>
namespace LandscapeCanvas
{
class GraphContext : public GraphModel::IGraphContext, public AZStd::enable_shared_from_this<GraphContext>
{
public:
static void SetInstance(AZStd::shared_ptr<GraphContext> graphContext);
static AZStd::shared_ptr<GraphContext> GetInstance();
GraphContext();
virtual ~GraphContext() = default;
const char* GetSystemName() const override;
const char* GetModuleFileExtension() const override;
const DataTypeList& GetAllDataTypes() const override;
GraphModel::DataTypePtr GetDataType(AZ::Uuid typeId) const override;
GraphModel::DataTypePtr GetDataTypeForValue(const AZStd::any& value) const override;
GraphModel::DataTypePtr GetDataType(GraphModel::DataType::Enum typeEnum) const override;
template<typename T>
GraphModel::DataTypePtr GetDataType() const { return IGraphContext::GetDataType<T>(); }
GraphModel::ModuleGraphManagerPtr GetModuleGraphManager() const override;
private:
//! Performs initialization that can't be done in the constructor
void Init();
static AZStd::shared_ptr<GraphContext> s_instance;
DataTypeList m_dataTypes;
GraphModel::ModuleGraphManagerPtr m_moduleGraphManager;
};
} // namespace LandscapeCanvas
| 32.830189 | 110 | 0.723563 | [
"model",
"3d"
] |
3c2336463b82c57aace78ef4a4d4f0207890da3f | 2,772 | h | C | aws-cpp-sdk-inspector2/include/aws/inspector2/model/EnableDelegatedAdminAccountResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-inspector2/include/aws/inspector2/model/EnableDelegatedAdminAccountResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-inspector2/include/aws/inspector2/model/EnableDelegatedAdminAccountResult.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/inspector2/Inspector2_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 Inspector2
{
namespace Model
{
class AWS_INSPECTOR2_API EnableDelegatedAdminAccountResult
{
public:
EnableDelegatedAdminAccountResult();
EnableDelegatedAdminAccountResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
EnableDelegatedAdminAccountResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline const Aws::String& GetDelegatedAdminAccountId() const{ return m_delegatedAdminAccountId; }
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline void SetDelegatedAdminAccountId(const Aws::String& value) { m_delegatedAdminAccountId = value; }
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline void SetDelegatedAdminAccountId(Aws::String&& value) { m_delegatedAdminAccountId = std::move(value); }
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline void SetDelegatedAdminAccountId(const char* value) { m_delegatedAdminAccountId.assign(value); }
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline EnableDelegatedAdminAccountResult& WithDelegatedAdminAccountId(const Aws::String& value) { SetDelegatedAdminAccountId(value); return *this;}
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline EnableDelegatedAdminAccountResult& WithDelegatedAdminAccountId(Aws::String&& value) { SetDelegatedAdminAccountId(std::move(value)); return *this;}
/**
* <p>The Amazon Web Services account ID of the successfully Amazon Inspector
* delegated administrator.</p>
*/
inline EnableDelegatedAdminAccountResult& WithDelegatedAdminAccountId(const char* value) { SetDelegatedAdminAccountId(value); return *this;}
private:
Aws::String m_delegatedAdminAccountId;
};
} // namespace Model
} // namespace Inspector2
} // namespace Aws
| 32.611765 | 157 | 0.731962 | [
"model"
] |
3c24d4cce67daa6043b7a6d88979f20d33cc78ac | 1,170 | h | C | Test/Test.h | skyclad0x7b7/MIni-Mahjong | 3c0bdad1f6070fc0479c3ed6229737490dac4c8e | [
"MIT"
] | 2 | 2019-07-18T14:26:34.000Z | 2020-04-10T18:07:31.000Z | Test/Test.h | skyclad0x7b7/MIni-Mahjong | 3c0bdad1f6070fc0479c3ed6229737490dac4c8e | [
"MIT"
] | 5 | 2018-08-11T07:27:53.000Z | 2020-04-16T12:32:05.000Z | Test/Test.h | skyclad0x7b7/MIni-Mahjong | 3c0bdad1f6070fc0479c3ed6229737490dac4c8e | [
"MIT"
] | 1 | 2020-04-12T22:13:43.000Z | 2020-04-12T22:13:43.000Z | #ifndef __MINI_MAHJONG_TEST_H__
#define __MINI_MAHJONG_TEST_H__
#include <Source/Yaku.h>
#include <Source/Tile.h>
#include <Source/TileGroup.h>
#include <vector>
namespace Mini
{
void Test01();
void Test02();
void Test03();
void Test04();
void Test05();
void Test06();
void Test07();
void Test08();
void Test09();
void Test10();
void Test11();
void Test12();
void Test13();
void Test14();
/* Utility for Test */
void CalcAndPrintYaku(std::vector<Yaku*> yakuList, const ReassembledTileGroup& reassembledTileGroup, const Tile *pickedTile, bool isMenzen, bool isRon, WindType roundWind, WindType selfWind);
void CheckPossibleAndPrintResult(const std::vector<TileGroup>& calledTileGroupList, const std::vector<const Tile *>& handTiles, const Tile *pickedTile, std::vector<ReassembledTileGroup>& result);
void CheckPossibleYakuAndPrintResult(const std::vector<Yaku*> yakuList, const std::vector<TileGroup>& calledTileGroupList, const std::vector<const Tile *>& handTiles, const Tile *pickedTile, bool isMenzen, bool isRon, WindType roundWind, WindType selfWind);
}
#endif // __MINI_MAHJONG_TEST_H__ | 35.454545 | 261 | 0.72735 | [
"vector"
] |
3c30b55c67edabb96f61e439f4aa9b642ab0936d | 140,184 | c | C | videocodec/libvpx_internal/libvpx/third_party/libyuv/source/scale.c | Omegaphora/hardware_intel_common_omx-components | 2dc257bd12d2604f5bac67d039e2b7e53c255ac9 | [
"Apache-2.0"
] | 49 | 2015-01-07T04:37:04.000Z | 2022-03-25T08:37:14.000Z | videocodec/libvpx_internal/libvpx/third_party/libyuv/source/scale.c | Omegaphora/hardware_intel_common_omx-components | 2dc257bd12d2604f5bac67d039e2b7e53c255ac9 | [
"Apache-2.0"
] | 1 | 2016-03-22T11:48:22.000Z | 2016-12-05T15:26:52.000Z | videocodec/libvpx_internal/libvpx/third_party/libyuv/source/scale.c | Omegaphora/hardware_intel_common_omx-components | 2dc257bd12d2604f5bac67d039e2b7e53c255ac9 | [
"Apache-2.0"
] | 8 | 2015-06-29T21:53:18.000Z | 2019-11-01T21:22:47.000Z | /*
* Copyright (c) 2011 The LibYuv project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/libyuv/include/libyuv/scale.h"
#include <assert.h>
#include <string.h>
#include "third_party/libyuv/include/libyuv/cpu_id.h"
#include "third_party/libyuv/source/row.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
/*
* Note: Defining YUV_DISABLE_ASM allows to use c version.
*/
//#define YUV_DISABLE_ASM
#if defined(_MSC_VER)
#define ALIGN16(var) __declspec(align(16)) var
#else
#define ALIGN16(var) var __attribute__((aligned(16)))
#endif
// Note: A Neon reference manual
// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204j/CJAJIIGG.html
// Note: Some SSE2 reference manuals
// cpuvol1.pdf agner_instruction_tables.pdf 253666.pdf 253667.pdf
// Set the following flag to true to revert to only
// using the reference implementation ScalePlaneBox(), and
// NOT the optimized versions. Useful for debugging and
// when comparing the quality of the resulting YUV planes
// as produced by the optimized and non-optimized versions.
static int use_reference_impl_ = 0;
void SetUseReferenceImpl(int use) {
use_reference_impl_ = use;
}
// ScaleRowDown2Int also used by planar functions
/**
* NEON downscalers with interpolation.
*
* Provided by Fritz Koenig
*
*/
#if defined(__ARM_NEON__) && !defined(YUV_DISABLE_ASM)
#define HAS_SCALEROWDOWN2_NEON
void ScaleRowDown2_NEON(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
asm volatile (
"1: \n"
"vld2.u8 {q0,q1}, [%0]! \n" // load even pixels into q0, odd into q1
"vst1.u8 {q0}, [%1]! \n" // store even pixels
"subs %2, %2, #16 \n" // 16 processed per loop
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst), // %1
"+r"(dst_width) // %2
:
: "q0", "q1" // Clobber List
);
}
void ScaleRowDown2Int_NEON(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
asm volatile (
"add %1, %0 \n" // change the stride to row 2 pointer
"1: \n"
"vld1.u8 {q0,q1}, [%0]! \n" // load row 1 and post increment
"vld1.u8 {q2,q3}, [%1]! \n" // load row 2 and post increment
"vpaddl.u8 q0, q0 \n" // row 1 add adjacent
"vpaddl.u8 q1, q1 \n"
"vpadal.u8 q0, q2 \n" // row 2 add adjacent, add row 1 to row 2
"vpadal.u8 q1, q3 \n"
"vrshrn.u16 d0, q0, #2 \n" // downshift, round and pack
"vrshrn.u16 d1, q1, #2 \n"
"vst1.u8 {q0}, [%2]! \n"
"subs %3, %3, #16 \n" // 16 processed per loop
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(src_stride), // %1
"+r"(dst), // %2
"+r"(dst_width) // %3
:
: "q0", "q1", "q2", "q3" // Clobber List
);
}
#define HAS_SCALEROWDOWN4_NEON
static void ScaleRowDown4_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"1: \n"
"vld2.u8 {d0, d1}, [%0]! \n"
"vtrn.u8 d1, d0 \n"
"vshrn.u16 d0, q0, #8 \n"
"vst1.u32 {d0[1]}, [%1]! \n"
"subs %2, #4 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
:
: "q0", "q1", "memory", "cc"
);
}
static void ScaleRowDown4Int_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"add r4, %0, %3 \n"
"add r5, r4, %3 \n"
"add %3, r5, %3 \n"
"1: \n"
"vld1.u8 {q0}, [%0]! \n" // load up 16x4 block of input data
"vld1.u8 {q1}, [r4]! \n"
"vld1.u8 {q2}, [r5]! \n"
"vld1.u8 {q3}, [%3]! \n"
"vpaddl.u8 q0, q0 \n"
"vpadal.u8 q0, q1 \n"
"vpadal.u8 q0, q2 \n"
"vpadal.u8 q0, q3 \n"
"vpaddl.u16 q0, q0 \n"
"vrshrn.u32 d0, q0, #4 \n" // divide by 16 w/rounding
"vmovn.u16 d0, q0 \n"
"vst1.u32 {d0[0]}, [%1]! \n"
"subs %2, #4 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"(src_stride) // %3
: "r4", "r5", "q0", "q1", "q2", "q3", "memory", "cc"
);
}
#define HAS_SCALEROWDOWN34_NEON
// Down scale from 4 to 3 pixels. Use the neon multilane read/write
// to load up the every 4th pixel into a 4 different registers.
// Point samples 32 pixels to 24 pixels.
static void ScaleRowDown34_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"1: \n"
"vld4.u8 {d0, d1, d2, d3}, [%0]! \n" // src line 0
"vmov d2, d3 \n" // order needs to be d0, d1, d2
"vst3.u8 {d0, d1, d2}, [%1]! \n"
"subs %2, #24 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
:
: "d0", "d1", "d2", "d3", "memory", "cc"
);
}
static void ScaleRowDown34_0_Int_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"vmov.u8 d24, #3 \n"
"add %3, %0 \n"
"1: \n"
"vld4.u8 {d0, d1, d2, d3}, [%0]! \n" // src line 0
"vld4.u8 {d4, d5, d6, d7}, [%3]! \n" // src line 1
// filter src line 0 with src line 1
// expand chars to shorts to allow for room
// when adding lines together
"vmovl.u8 q8, d4 \n"
"vmovl.u8 q9, d5 \n"
"vmovl.u8 q10, d6 \n"
"vmovl.u8 q11, d7 \n"
// 3 * line_0 + line_1
"vmlal.u8 q8, d0, d24 \n"
"vmlal.u8 q9, d1, d24 \n"
"vmlal.u8 q10, d2, d24 \n"
"vmlal.u8 q11, d3, d24 \n"
// (3 * line_0 + line_1) >> 2
"vqrshrn.u16 d0, q8, #2 \n"
"vqrshrn.u16 d1, q9, #2 \n"
"vqrshrn.u16 d2, q10, #2 \n"
"vqrshrn.u16 d3, q11, #2 \n"
// a0 = (src[0] * 3 + s[1] * 1) >> 2
"vmovl.u8 q8, d1 \n"
"vmlal.u8 q8, d0, d24 \n"
"vqrshrn.u16 d0, q8, #2 \n"
// a1 = (src[1] * 1 + s[2] * 1) >> 1
"vrhadd.u8 d1, d1, d2 \n"
// a2 = (src[2] * 1 + s[3] * 3) >> 2
"vmovl.u8 q8, d2 \n"
"vmlal.u8 q8, d3, d24 \n"
"vqrshrn.u16 d2, q8, #2 \n"
"vst3.u8 {d0, d1, d2}, [%1]! \n"
"subs %2, #24 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width), // %2
"+r"(src_stride) // %3
:
: "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "d24", "memory", "cc"
);
}
static void ScaleRowDown34_1_Int_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"vmov.u8 d24, #3 \n"
"add %3, %0 \n"
"1: \n"
"vld4.u8 {d0, d1, d2, d3}, [%0]! \n" // src line 0
"vld4.u8 {d4, d5, d6, d7}, [%3]! \n" // src line 1
// average src line 0 with src line 1
"vrhadd.u8 q0, q0, q2 \n"
"vrhadd.u8 q1, q1, q3 \n"
// a0 = (src[0] * 3 + s[1] * 1) >> 2
"vmovl.u8 q3, d1 \n"
"vmlal.u8 q3, d0, d24 \n"
"vqrshrn.u16 d0, q3, #2 \n"
// a1 = (src[1] * 1 + s[2] * 1) >> 1
"vrhadd.u8 d1, d1, d2 \n"
// a2 = (src[2] * 1 + s[3] * 3) >> 2
"vmovl.u8 q3, d2 \n"
"vmlal.u8 q3, d3, d24 \n"
"vqrshrn.u16 d2, q3, #2 \n"
"vst3.u8 {d0, d1, d2}, [%1]! \n"
"subs %2, #24 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width), // %2
"+r"(src_stride) // %3
:
: "r4", "q0", "q1", "q2", "q3", "d24", "memory", "cc"
);
}
#define HAS_SCALEROWDOWN38_NEON
const uint8 shuf38[16] __attribute__ ((aligned(16))) =
{ 0, 3, 6, 8, 11, 14, 16, 19, 22, 24, 27, 30, 0, 0, 0, 0 };
const uint8 shuf38_2[16] __attribute__ ((aligned(16))) =
{ 0, 8, 16, 2, 10, 17, 4, 12, 18, 6, 14, 19, 0, 0, 0, 0 };
const unsigned short mult38_div6[8] __attribute__ ((aligned(16))) =
{ 65536 / 12, 65536 / 12, 65536 / 12, 65536 / 12,
65536 / 12, 65536 / 12, 65536 / 12, 65536 / 12 };
const unsigned short mult38_div9[8] __attribute__ ((aligned(16))) =
{ 65536 / 18, 65536 / 18, 65536 / 18, 65536 / 18,
65536 / 18, 65536 / 18, 65536 / 18, 65536 / 18 };
// 32 -> 12
static void ScaleRowDown38_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"vld1.u8 {q3}, [%3] \n"
"1: \n"
"vld1.u8 {d0, d1, d2, d3}, [%0]! \n"
"vtbl.u8 d4, {d0, d1, d2, d3}, d6 \n"
"vtbl.u8 d5, {d0, d1, d2, d3}, d7 \n"
"vst1.u8 {d4}, [%1]! \n"
"vst1.u32 {d5[0]}, [%1]! \n"
"subs %2, #12 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"(shuf38) // %3
: "d0", "d1", "d2", "d3", "d4", "d5", "memory", "cc"
);
}
// 32x3 -> 12x1
static void ScaleRowDown38_3_Int_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"vld1.u16 {q13}, [%4] \n"
"vld1.u8 {q14}, [%5] \n"
"vld1.u8 {q15}, [%6] \n"
"add r4, %0, %3, lsl #1 \n"
"add %3, %0 \n"
"1: \n"
// d0 = 00 40 01 41 02 42 03 43
// d1 = 10 50 11 51 12 52 13 53
// d2 = 20 60 21 61 22 62 23 63
// d3 = 30 70 31 71 32 72 33 73
"vld4.u8 {d0, d1, d2, d3}, [%0]! \n"
"vld4.u8 {d4, d5, d6, d7}, [%3]! \n"
"vld4.u8 {d16, d17, d18, d19}, [r4]! \n"
// Shuffle the input data around to get align the data
// so adjacent data can be added. 0,1 - 2,3 - 4,5 - 6,7
// d0 = 00 10 01 11 02 12 03 13
// d1 = 40 50 41 51 42 52 43 53
"vtrn.u8 d0, d1 \n"
"vtrn.u8 d4, d5 \n"
"vtrn.u8 d16, d17 \n"
// d2 = 20 30 21 31 22 32 23 33
// d3 = 60 70 61 71 62 72 63 73
"vtrn.u8 d2, d3 \n"
"vtrn.u8 d6, d7 \n"
"vtrn.u8 d18, d19 \n"
// d0 = 00+10 01+11 02+12 03+13
// d2 = 40+50 41+51 42+52 43+53
"vpaddl.u8 q0, q0 \n"
"vpaddl.u8 q2, q2 \n"
"vpaddl.u8 q8, q8 \n"
// d3 = 60+70 61+71 62+72 63+73
"vpaddl.u8 d3, d3 \n"
"vpaddl.u8 d7, d7 \n"
"vpaddl.u8 d19, d19 \n"
// combine source lines
"vadd.u16 q0, q2 \n"
"vadd.u16 q0, q8 \n"
"vadd.u16 d4, d3, d7 \n"
"vadd.u16 d4, d19 \n"
// dst_ptr[3] = (s[6 + st * 0] + s[7 + st * 0]
// + s[6 + st * 1] + s[7 + st * 1]
// + s[6 + st * 2] + s[7 + st * 2]) / 6
"vqrdmulh.s16 q2, q13 \n"
"vmovn.u16 d4, q2 \n"
// Shuffle 2,3 reg around so that 2 can be added to the
// 0,1 reg and 3 can be added to the 4,5 reg. This
// requires expanding from u8 to u16 as the 0,1 and 4,5
// registers are already expanded. Then do transposes
// to get aligned.
// q2 = xx 20 xx 30 xx 21 xx 31 xx 22 xx 32 xx 23 xx 33
"vmovl.u8 q1, d2 \n"
"vmovl.u8 q3, d6 \n"
"vmovl.u8 q9, d18 \n"
// combine source lines
"vadd.u16 q1, q3 \n"
"vadd.u16 q1, q9 \n"
// d4 = xx 20 xx 30 xx 22 xx 32
// d5 = xx 21 xx 31 xx 23 xx 33
"vtrn.u32 d2, d3 \n"
// d4 = xx 20 xx 21 xx 22 xx 23
// d5 = xx 30 xx 31 xx 32 xx 33
"vtrn.u16 d2, d3 \n"
// 0+1+2, 3+4+5
"vadd.u16 q0, q1 \n"
// Need to divide, but can't downshift as the the value
// isn't a power of 2. So multiply by 65536 / n
// and take the upper 16 bits.
"vqrdmulh.s16 q0, q15 \n"
// Align for table lookup, vtbl requires registers to
// be adjacent
"vmov.u8 d2, d4 \n"
"vtbl.u8 d3, {d0, d1, d2}, d28 \n"
"vtbl.u8 d4, {d0, d1, d2}, d29 \n"
"vst1.u8 {d3}, [%1]! \n"
"vst1.u32 {d4[0]}, [%1]! \n"
"subs %2, #12 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width), // %2
"+r"(src_stride) // %3
: "r"(mult38_div6), // %4
"r"(shuf38_2), // %5
"r"(mult38_div9) // %6
: "r4", "q0", "q1", "q2", "q3", "q8", "q9",
"q13", "q14", "q15", "memory", "cc"
);
}
// 32x2 -> 12x1
static void ScaleRowDown38_2_Int_NEON(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"vld1.u16 {q13}, [%4] \n"
"vld1.u8 {q14}, [%5] \n"
"add %3, %0 \n"
"1: \n"
// d0 = 00 40 01 41 02 42 03 43
// d1 = 10 50 11 51 12 52 13 53
// d2 = 20 60 21 61 22 62 23 63
// d3 = 30 70 31 71 32 72 33 73
"vld4.u8 {d0, d1, d2, d3}, [%0]! \n"
"vld4.u8 {d4, d5, d6, d7}, [%3]! \n"
// Shuffle the input data around to get align the data
// so adjacent data can be added. 0,1 - 2,3 - 4,5 - 6,7
// d0 = 00 10 01 11 02 12 03 13
// d1 = 40 50 41 51 42 52 43 53
"vtrn.u8 d0, d1 \n"
"vtrn.u8 d4, d5 \n"
// d2 = 20 30 21 31 22 32 23 33
// d3 = 60 70 61 71 62 72 63 73
"vtrn.u8 d2, d3 \n"
"vtrn.u8 d6, d7 \n"
// d0 = 00+10 01+11 02+12 03+13
// d2 = 40+50 41+51 42+52 43+53
"vpaddl.u8 q0, q0 \n"
"vpaddl.u8 q2, q2 \n"
// d3 = 60+70 61+71 62+72 63+73
"vpaddl.u8 d3, d3 \n"
"vpaddl.u8 d7, d7 \n"
// combine source lines
"vadd.u16 q0, q2 \n"
"vadd.u16 d4, d3, d7 \n"
// dst_ptr[3] = (s[6] + s[7] + s[6+st] + s[7+st]) / 4
"vqrshrn.u16 d4, q2, #2 \n"
// Shuffle 2,3 reg around so that 2 can be added to the
// 0,1 reg and 3 can be added to the 4,5 reg. This
// requires expanding from u8 to u16 as the 0,1 and 4,5
// registers are already expanded. Then do transposes
// to get aligned.
// q2 = xx 20 xx 30 xx 21 xx 31 xx 22 xx 32 xx 23 xx 33
"vmovl.u8 q1, d2 \n"
"vmovl.u8 q3, d6 \n"
// combine source lines
"vadd.u16 q1, q3 \n"
// d4 = xx 20 xx 30 xx 22 xx 32
// d5 = xx 21 xx 31 xx 23 xx 33
"vtrn.u32 d2, d3 \n"
// d4 = xx 20 xx 21 xx 22 xx 23
// d5 = xx 30 xx 31 xx 32 xx 33
"vtrn.u16 d2, d3 \n"
// 0+1+2, 3+4+5
"vadd.u16 q0, q1 \n"
// Need to divide, but can't downshift as the the value
// isn't a power of 2. So multiply by 65536 / n
// and take the upper 16 bits.
"vqrdmulh.s16 q0, q13 \n"
// Align for table lookup, vtbl requires registers to
// be adjacent
"vmov.u8 d2, d4 \n"
"vtbl.u8 d3, {d0, d1, d2}, d28 \n"
"vtbl.u8 d4, {d0, d1, d2}, d29 \n"
"vst1.u8 {d3}, [%1]! \n"
"vst1.u32 {d4[0]}, [%1]! \n"
"subs %2, #12 \n"
"bhi 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width), // %2
"+r"(src_stride) // %3
: "r"(mult38_div6), // %4
"r"(shuf38_2) // %5
: "q0", "q1", "q2", "q3", "q13", "q14", "memory", "cc"
);
}
/**
* SSE2 downscalers with interpolation.
*
* Provided by Frank Barchard (fbarchard@google.com)
*
*/
// Constants for SSE2 code
#elif (defined(_M_IX86) || defined(__i386__) || defined(__x86_64__)) && \
!defined(YUV_DISABLE_ASM)
#if defined(_MSC_VER)
#define TALIGN16(t, var) __declspec(align(16)) t _ ## var
#elif (defined(__APPLE__) || defined(__MINGW32__) || defined(__CYGWIN__)) && defined(__i386__)
#define TALIGN16(t, var) t var __attribute__((aligned(16)))
#else
#define TALIGN16(t, var) t _ ## var __attribute__((aligned(16)))
#endif
#if (defined(__APPLE__) || defined(__MINGW32__) || defined(__CYGWIN__)) && \
defined(__i386__)
#define DECLARE_FUNCTION(name) \
".text \n" \
".globl _" #name " \n" \
"_" #name ": \n"
#else
#define DECLARE_FUNCTION(name) \
".text \n" \
".global " #name " \n" \
#name ": \n"
#endif
// Offsets for source bytes 0 to 9
//extern "C"
TALIGN16(const uint8, shuf0[16]) =
{ 0, 1, 3, 4, 5, 7, 8, 9, 128, 128, 128, 128, 128, 128, 128, 128 };
// Offsets for source bytes 11 to 20 with 8 subtracted = 3 to 12.
//extern "C"
TALIGN16(const uint8, shuf1[16]) =
{ 3, 4, 5, 7, 8, 9, 11, 12, 128, 128, 128, 128, 128, 128, 128, 128 };
// Offsets for source bytes 21 to 31 with 16 subtracted = 5 to 31.
//extern "C"
TALIGN16(const uint8, shuf2[16]) =
{ 5, 7, 8, 9, 11, 12, 13, 15, 128, 128, 128, 128, 128, 128, 128, 128 };
// Offsets for source bytes 0 to 10
//extern "C"
TALIGN16(const uint8, shuf01[16]) =
{ 0, 1, 1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 9, 10 };
// Offsets for source bytes 10 to 21 with 8 subtracted = 3 to 13.
//extern "C"
TALIGN16(const uint8, shuf11[16]) =
{ 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 9, 10, 10, 11, 12, 13 };
// Offsets for source bytes 21 to 31 with 16 subtracted = 5 to 31.
//extern "C"
TALIGN16(const uint8, shuf21[16]) =
{ 5, 6, 6, 7, 8, 9, 9, 10, 10, 11, 12, 13, 13, 14, 14, 15 };
// Coefficients for source bytes 0 to 10
//extern "C"
TALIGN16(const uint8, madd01[16]) =
{ 3, 1, 2, 2, 1, 3, 3, 1, 2, 2, 1, 3, 3, 1, 2, 2 };
// Coefficients for source bytes 10 to 21
//extern "C"
TALIGN16(const uint8, madd11[16]) =
{ 1, 3, 3, 1, 2, 2, 1, 3, 3, 1, 2, 2, 1, 3, 3, 1 };
// Coefficients for source bytes 21 to 31
//extern "C"
TALIGN16(const uint8, madd21[16]) =
{ 2, 2, 1, 3, 3, 1, 2, 2, 1, 3, 3, 1, 2, 2, 1, 3 };
// Coefficients for source bytes 21 to 31
//extern "C"
TALIGN16(const int16, round34[8]) =
{ 2, 2, 2, 2, 2, 2, 2, 2 };
//extern "C"
TALIGN16(const uint8, shuf38a[16]) =
{ 0, 3, 6, 8, 11, 14, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 };
//extern "C"
TALIGN16(const uint8, shuf38b[16]) =
{ 128, 128, 128, 128, 128, 128, 0, 3, 6, 8, 11, 14, 128, 128, 128, 128 };
// Arrange words 0,3,6 into 0,1,2
//extern "C"
TALIGN16(const uint8, shufac0[16]) =
{ 0, 1, 6, 7, 12, 13, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 };
// Arrange words 0,3,6 into 3,4,5
//extern "C"
TALIGN16(const uint8, shufac3[16]) =
{ 128, 128, 128, 128, 128, 128, 0, 1, 6, 7, 12, 13, 128, 128, 128, 128 };
// Scaling values for boxes of 3x3 and 2x3
//extern "C"
TALIGN16(const uint16, scaleac3[8]) =
{ 65536 / 9, 65536 / 9, 65536 / 6, 65536 / 9, 65536 / 9, 65536 / 6, 0, 0 };
// Arrange first value for pixels 0,1,2,3,4,5
//extern "C"
TALIGN16(const uint8, shufab0[16]) =
{ 0, 128, 3, 128, 6, 128, 8, 128, 11, 128, 14, 128, 128, 128, 128, 128 };
// Arrange second value for pixels 0,1,2,3,4,5
//extern "C"
TALIGN16(const uint8, shufab1[16]) =
{ 1, 128, 4, 128, 7, 128, 9, 128, 12, 128, 15, 128, 128, 128, 128, 128 };
// Arrange third value for pixels 0,1,2,3,4,5
//extern "C"
TALIGN16(const uint8, shufab2[16]) =
{ 2, 128, 5, 128, 128, 128, 10, 128, 13, 128, 128, 128, 128, 128, 128, 128 };
// Scaling values for boxes of 3x2 and 2x2
//extern "C"
TALIGN16(const uint16, scaleab2[8]) =
{ 65536 / 3, 65536 / 3, 65536 / 2, 65536 / 3, 65536 / 3, 65536 / 2, 0, 0 };
#endif
#if defined(_M_IX86) && !defined(YUV_DISABLE_ASM) && defined(_MSC_VER)
#define HAS_SCALEROWDOWN2_SSE2
// Reads 32 pixels, throws half away and writes 16 pixels.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 16 byte aligned.
__declspec(naked)
static void ScaleRowDown2_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
mov eax, [esp + 4] // src_ptr
// src_stride ignored
mov edx, [esp + 12] // dst_ptr
mov ecx, [esp + 16] // dst_width
pcmpeqb xmm5, xmm5 // generate mask 0x00ff00ff
psrlw xmm5, 8
wloop:
movdqa xmm0, [eax]
movdqa xmm1, [eax + 16]
lea eax, [eax + 32]
pand xmm0, xmm5
pand xmm1, xmm5
packuswb xmm0, xmm1
movdqa [edx], xmm0
lea edx, [edx + 16]
sub ecx, 16
ja wloop
ret
}
}
// Blends 32x2 rectangle to 16x1.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 16 byte aligned.
__declspec(naked)
void ScaleRowDown2Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
push esi
mov eax, [esp + 4 + 4] // src_ptr
mov esi, [esp + 4 + 8] // src_stride
mov edx, [esp + 4 + 12] // dst_ptr
mov ecx, [esp + 4 + 16] // dst_width
pcmpeqb xmm5, xmm5 // generate mask 0x00ff00ff
psrlw xmm5, 8
wloop:
movdqa xmm0, [eax]
movdqa xmm1, [eax + 16]
movdqa xmm2, [eax + esi]
movdqa xmm3, [eax + esi + 16]
lea eax, [eax + 32]
pavgb xmm0, xmm2 // average rows
pavgb xmm1, xmm3
movdqa xmm2, xmm0 // average columns (32 to 16 pixels)
psrlw xmm0, 8
movdqa xmm3, xmm1
psrlw xmm1, 8
pand xmm2, xmm5
pand xmm3, xmm5
pavgw xmm0, xmm2
pavgw xmm1, xmm3
packuswb xmm0, xmm1
movdqa [edx], xmm0
lea edx, [edx + 16]
sub ecx, 16
ja wloop
pop esi
ret
}
}
#define HAS_SCALEROWDOWN4_SSE2
// Point samples 32 pixels to 8 pixels.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 8 byte aligned.
__declspec(naked)
static void ScaleRowDown4_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
// src_stride ignored
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
pcmpeqb xmm5, xmm5 // generate mask 0x000000ff
psrld xmm5, 24
wloop:
movdqa xmm0, [esi]
movdqa xmm1, [esi + 16]
lea esi, [esi + 32]
pand xmm0, xmm5
pand xmm1, xmm5
packuswb xmm0, xmm1
packuswb xmm0, xmm0
movq qword ptr [edi], xmm0
lea edi, [edi + 8]
sub ecx, 8
ja wloop
popad
ret
}
}
// Blends 32x4 rectangle to 8x1.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 8 byte aligned.
__declspec(naked)
static void ScaleRowDown4Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov ebx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
pcmpeqb xmm7, xmm7 // generate mask 0x00ff00ff
psrlw xmm7, 8
lea edx, [ebx + ebx * 2] // src_stride * 3
wloop:
movdqa xmm0, [esi]
movdqa xmm1, [esi + 16]
movdqa xmm2, [esi + ebx]
movdqa xmm3, [esi + ebx + 16]
pavgb xmm0, xmm2 // average rows
pavgb xmm1, xmm3
movdqa xmm2, [esi + ebx * 2]
movdqa xmm3, [esi + ebx * 2 + 16]
movdqa xmm4, [esi + edx]
movdqa xmm5, [esi + edx + 16]
lea esi, [esi + 32]
pavgb xmm2, xmm4
pavgb xmm3, xmm5
pavgb xmm0, xmm2
pavgb xmm1, xmm3
movdqa xmm2, xmm0 // average columns (32 to 16 pixels)
psrlw xmm0, 8
movdqa xmm3, xmm1
psrlw xmm1, 8
pand xmm2, xmm7
pand xmm3, xmm7
pavgw xmm0, xmm2
pavgw xmm1, xmm3
packuswb xmm0, xmm1
movdqa xmm2, xmm0 // average columns (16 to 8 pixels)
psrlw xmm0, 8
pand xmm2, xmm7
pavgw xmm0, xmm2
packuswb xmm0, xmm0
movq qword ptr [edi], xmm0
lea edi, [edi + 8]
sub ecx, 8
ja wloop
popad
ret
}
}
#define HAS_SCALEROWDOWN8_SSE2
// Point samples 32 pixels to 4 pixels.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 4 byte aligned.
__declspec(naked)
static void ScaleRowDown8_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
// src_stride ignored
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
pcmpeqb xmm5, xmm5 // generate mask isolating 1 src 8 bytes
psrlq xmm5, 56
wloop:
movdqa xmm0, [esi]
movdqa xmm1, [esi + 16]
lea esi, [esi + 32]
pand xmm0, xmm5
pand xmm1, xmm5
packuswb xmm0, xmm1 // 32->16
packuswb xmm0, xmm0 // 16->8
packuswb xmm0, xmm0 // 8->4
movd dword ptr [edi], xmm0
lea edi, [edi + 4]
sub ecx, 4
ja wloop
popad
ret
}
}
// Blends 32x8 rectangle to 4x1.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 4 byte aligned.
__declspec(naked)
static void ScaleRowDown8Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov ebx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
lea edx, [ebx + ebx * 2] // src_stride * 3
pxor xmm7, xmm7
wloop:
movdqa xmm0, [esi] // average 8 rows to 1
movdqa xmm1, [esi + 16]
movdqa xmm2, [esi + ebx]
movdqa xmm3, [esi + ebx + 16]
pavgb xmm0, xmm2
pavgb xmm1, xmm3
movdqa xmm2, [esi + ebx * 2]
movdqa xmm3, [esi + ebx * 2 + 16]
movdqa xmm4, [esi + edx]
movdqa xmm5, [esi + edx + 16]
lea ebp, [esi + ebx * 4]
lea esi, [esi + 32]
pavgb xmm2, xmm4
pavgb xmm3, xmm5
pavgb xmm0, xmm2
pavgb xmm1, xmm3
movdqa xmm2, [ebp]
movdqa xmm3, [ebp + 16]
movdqa xmm4, [ebp + ebx]
movdqa xmm5, [ebp + ebx + 16]
pavgb xmm2, xmm4
pavgb xmm3, xmm5
movdqa xmm4, [ebp + ebx * 2]
movdqa xmm5, [ebp + ebx * 2 + 16]
movdqa xmm6, [ebp + edx]
pavgb xmm4, xmm6
movdqa xmm6, [ebp + edx + 16]
pavgb xmm5, xmm6
pavgb xmm2, xmm4
pavgb xmm3, xmm5
pavgb xmm0, xmm2
pavgb xmm1, xmm3
psadbw xmm0, xmm7 // average 32 pixels to 4
psadbw xmm1, xmm7
pshufd xmm0, xmm0, 0xd8 // x1x0 -> xx01
pshufd xmm1, xmm1, 0x8d // x3x2 -> 32xx
por xmm0, xmm1 // -> 3201
psrlw xmm0, 3
packuswb xmm0, xmm0
packuswb xmm0, xmm0
movd dword ptr [edi], xmm0
lea edi, [edi + 4]
sub ecx, 4
ja wloop
popad
ret
}
}
#define HAS_SCALEROWDOWN34_SSSE3
// Point samples 32 pixels to 24 pixels.
// Produces three 8 byte values. For each 8 bytes, 16 bytes are read.
// Then shuffled to do the scaling.
// Note that movdqa+palign may be better than movdqu.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 8 byte aligned.
__declspec(naked)
static void ScaleRowDown34_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
// src_stride ignored
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
movdqa xmm3, _shuf0
movdqa xmm4, _shuf1
movdqa xmm5, _shuf2
wloop:
movdqa xmm0, [esi]
movdqa xmm1, [esi + 16]
lea esi, [esi + 32]
movdqa xmm2, xmm1
palignr xmm1, xmm0, 8
pshufb xmm0, xmm3
pshufb xmm1, xmm4
pshufb xmm2, xmm5
movq qword ptr [edi], xmm0
movq qword ptr [edi + 8], xmm1
movq qword ptr [edi + 16], xmm2
lea edi, [edi + 24]
sub ecx, 24
ja wloop
popad
ret
}
}
// Blends 32x2 rectangle to 24x1
// Produces three 8 byte values. For each 8 bytes, 16 bytes are read.
// Then shuffled to do the scaling.
// Register usage:
// xmm0 src_row 0
// xmm1 src_row 1
// xmm2 shuf 0
// xmm3 shuf 1
// xmm4 shuf 2
// xmm5 madd 0
// xmm6 madd 1
// xmm7 round34
// Note that movdqa+palign may be better than movdqu.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 8 byte aligned.
__declspec(naked)
static void ScaleRowDown34_1_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov ebx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
movdqa xmm2, _shuf01
movdqa xmm3, _shuf11
movdqa xmm4, _shuf21
movdqa xmm5, _madd01
movdqa xmm6, _madd11
movdqa xmm7, _round34
wloop:
movdqa xmm0, [esi] // pixels 0..7
movdqa xmm1, [esi+ebx]
pavgb xmm0, xmm1
pshufb xmm0, xmm2
pmaddubsw xmm0, xmm5
paddsw xmm0, xmm7
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edi], xmm0
movdqu xmm0, [esi+8] // pixels 8..15
movdqu xmm1, [esi+ebx+8]
pavgb xmm0, xmm1
pshufb xmm0, xmm3
pmaddubsw xmm0, xmm6
paddsw xmm0, xmm7
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edi+8], xmm0
movdqa xmm0, [esi+16] // pixels 16..23
movdqa xmm1, [esi+ebx+16]
lea esi, [esi+32]
pavgb xmm0, xmm1
pshufb xmm0, xmm4
movdqa xmm1, _madd21
pmaddubsw xmm0, xmm1
paddsw xmm0, xmm7
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edi+16], xmm0
lea edi, [edi+24]
sub ecx, 24
ja wloop
popad
ret
}
}
// Note that movdqa+palign may be better than movdqu.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 8 byte aligned.
__declspec(naked)
static void ScaleRowDown34_0_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov ebx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
movdqa xmm2, _shuf01
movdqa xmm3, _shuf11
movdqa xmm4, _shuf21
movdqa xmm5, _madd01
movdqa xmm6, _madd11
movdqa xmm7, _round34
wloop:
movdqa xmm0, [esi] // pixels 0..7
movdqa xmm1, [esi+ebx]
pavgb xmm1, xmm0
pavgb xmm0, xmm1
pshufb xmm0, xmm2
pmaddubsw xmm0, xmm5
paddsw xmm0, xmm7
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edi], xmm0
movdqu xmm0, [esi+8] // pixels 8..15
movdqu xmm1, [esi+ebx+8]
pavgb xmm1, xmm0
pavgb xmm0, xmm1
pshufb xmm0, xmm3
pmaddubsw xmm0, xmm6
paddsw xmm0, xmm7
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edi+8], xmm0
movdqa xmm0, [esi+16] // pixels 16..23
movdqa xmm1, [esi+ebx+16]
lea esi, [esi+32]
pavgb xmm1, xmm0
pavgb xmm0, xmm1
pshufb xmm0, xmm4
movdqa xmm1, _madd21
pmaddubsw xmm0, xmm1
paddsw xmm0, xmm7
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edi+16], xmm0
lea edi, [edi+24]
sub ecx, 24
ja wloop
popad
ret
}
}
#define HAS_SCALEROWDOWN38_SSSE3
// 3/8 point sampler
// Scale 32 pixels to 12
__declspec(naked)
static void ScaleRowDown38_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov edx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
movdqa xmm4, _shuf38a
movdqa xmm5, _shuf38b
xloop:
movdqa xmm0, [esi] // 16 pixels -> 0,1,2,3,4,5
movdqa xmm1, [esi + 16] // 16 pixels -> 6,7,8,9,10,11
lea esi, [esi + 32]
pshufb xmm0, xmm4
pshufb xmm1, xmm5
paddusb xmm0, xmm1
movq qword ptr [edi], xmm0 // write 12 pixels
movhlps xmm1, xmm0
movd [edi + 8], xmm1
lea edi, [edi + 12]
sub ecx, 12
ja xloop
popad
ret
}
}
// Scale 16x3 pixels to 6x1 with interpolation
__declspec(naked)
static void ScaleRowDown38_3_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov edx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
movdqa xmm4, _shufac0
movdqa xmm5, _shufac3
movdqa xmm6, _scaleac3
pxor xmm7, xmm7
xloop:
movdqa xmm0, [esi] // sum up 3 rows into xmm0/1
movdqa xmm2, [esi + edx]
movhlps xmm1, xmm0
movhlps xmm3, xmm2
punpcklbw xmm0, xmm7
punpcklbw xmm1, xmm7
punpcklbw xmm2, xmm7
punpcklbw xmm3, xmm7
paddusw xmm0, xmm2
paddusw xmm1, xmm3
movdqa xmm2, [esi + edx * 2]
lea esi, [esi + 16]
movhlps xmm3, xmm2
punpcklbw xmm2, xmm7
punpcklbw xmm3, xmm7
paddusw xmm0, xmm2
paddusw xmm1, xmm3
movdqa xmm2, xmm0 // 8 pixels -> 0,1,2 of xmm2
psrldq xmm0, 2
paddusw xmm2, xmm0
psrldq xmm0, 2
paddusw xmm2, xmm0
pshufb xmm2, xmm4
movdqa xmm3, xmm1 // 8 pixels -> 3,4,5 of xmm2
psrldq xmm1, 2
paddusw xmm3, xmm1
psrldq xmm1, 2
paddusw xmm3, xmm1
pshufb xmm3, xmm5
paddusw xmm2, xmm3
pmulhuw xmm2, xmm6 // divide by 9,9,6, 9,9,6
packuswb xmm2, xmm2
movd [edi], xmm2 // write 6 pixels
pextrw eax, xmm2, 2
mov [edi + 4], ax
lea edi, [edi + 6]
sub ecx, 6
ja xloop
popad
ret
}
}
// Scale 16x2 pixels to 6x1 with interpolation
__declspec(naked)
static void ScaleRowDown38_2_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov edx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
movdqa xmm4, _shufab0
movdqa xmm5, _shufab1
movdqa xmm6, _shufab2
movdqa xmm7, _scaleab2
xloop:
movdqa xmm2, [esi] // average 2 rows into xmm2
pavgb xmm2, [esi + edx]
lea esi, [esi + 16]
movdqa xmm0, xmm2 // 16 pixels -> 0,1,2,3,4,5 of xmm0
pshufb xmm0, xmm4
movdqa xmm1, xmm2
pshufb xmm1, xmm5
paddusw xmm0, xmm1
pshufb xmm2, xmm6
paddusw xmm0, xmm2
pmulhuw xmm0, xmm7 // divide by 3,3,2, 3,3,2
packuswb xmm0, xmm0
movd [edi], xmm0 // write 6 pixels
pextrw eax, xmm0, 2
mov [edi + 4], ax
lea edi, [edi + 6]
sub ecx, 6
ja xloop
popad
ret
}
}
#define HAS_SCALEADDROWS_SSE2
// Reads 8xN bytes and produces 16 shorts at a time.
__declspec(naked)
static void ScaleAddRows_SSE2(const uint8* src_ptr, int src_stride,
uint16* dst_ptr, int src_width,
int src_height) {
__asm {
pushad
mov esi, [esp + 32 + 4] // src_ptr
mov edx, [esp + 32 + 8] // src_stride
mov edi, [esp + 32 + 12] // dst_ptr
mov ecx, [esp + 32 + 16] // dst_width
mov ebx, [esp + 32 + 20] // height
pxor xmm5, xmm5
dec ebx
xloop:
// first row
movdqa xmm2, [esi]
lea eax, [esi + edx]
movhlps xmm3, xmm2
mov ebp, ebx
punpcklbw xmm2, xmm5
punpcklbw xmm3, xmm5
// sum remaining rows
yloop:
movdqa xmm0, [eax] // read 16 pixels
lea eax, [eax + edx] // advance to next row
movhlps xmm1, xmm0
punpcklbw xmm0, xmm5
punpcklbw xmm1, xmm5
paddusw xmm2, xmm0 // sum 16 words
paddusw xmm3, xmm1
sub ebp, 1
ja yloop
movdqa [edi], xmm2
movdqa [edi + 16], xmm3
lea edi, [edi + 32]
lea esi, [esi + 16]
sub ecx, 16
ja xloop
popad
ret
}
}
// Bilinear row filtering combines 16x2 -> 16x1. SSE2 version.
#define HAS_SCALEFILTERROWS_SSE2
__declspec(naked)
static void ScaleFilterRows_SSE2(uint8* dst_ptr, const uint8* src_ptr,
int src_stride, int dst_width,
int source_y_fraction) {
__asm {
push esi
push edi
mov edi, [esp + 8 + 4] // dst_ptr
mov esi, [esp + 8 + 8] // src_ptr
mov edx, [esp + 8 + 12] // src_stride
mov ecx, [esp + 8 + 16] // dst_width
mov eax, [esp + 8 + 20] // source_y_fraction (0..255)
cmp eax, 0
je xloop1
cmp eax, 128
je xloop2
movd xmm6, eax // xmm6 = y fraction
punpcklwd xmm6, xmm6
pshufd xmm6, xmm6, 0
neg eax // xmm5 = 256 - y fraction
add eax, 256
movd xmm5, eax
punpcklwd xmm5, xmm5
pshufd xmm5, xmm5, 0
pxor xmm7, xmm7
xloop:
movdqa xmm0, [esi]
movdqa xmm2, [esi + edx]
lea esi, [esi + 16]
movdqa xmm1, xmm0
movdqa xmm3, xmm2
punpcklbw xmm0, xmm7
punpcklbw xmm2, xmm7
punpckhbw xmm1, xmm7
punpckhbw xmm3, xmm7
pmullw xmm0, xmm5 // scale row 0
pmullw xmm1, xmm5
pmullw xmm2, xmm6 // scale row 1
pmullw xmm3, xmm6
paddusw xmm0, xmm2 // sum rows
paddusw xmm1, xmm3
psrlw xmm0, 8
psrlw xmm1, 8
packuswb xmm0, xmm1
movdqa [edi], xmm0
lea edi, [edi + 16]
sub ecx, 16
ja xloop
mov al, [edi - 1]
mov [edi], al
pop edi
pop esi
ret
xloop1:
movdqa xmm0, [esi]
lea esi, [esi + 16]
movdqa [edi], xmm0
lea edi, [edi + 16]
sub ecx, 16
ja xloop1
mov al, [edi - 1]
mov [edi], al
pop edi
pop esi
ret
xloop2:
movdqa xmm0, [esi]
movdqa xmm2, [esi + edx]
lea esi, [esi + 16]
pavgb xmm0, xmm2
movdqa [edi], xmm0
lea edi, [edi + 16]
sub ecx, 16
ja xloop2
mov al, [edi - 1]
mov [edi], al
pop edi
pop esi
ret
}
}
// Bilinear row filtering combines 16x2 -> 16x1. SSSE3 version.
#define HAS_SCALEFILTERROWS_SSSE3
__declspec(naked)
static void ScaleFilterRows_SSSE3(uint8* dst_ptr, const uint8* src_ptr,
int src_stride, int dst_width,
int source_y_fraction) {
__asm {
push esi
push edi
mov edi, [esp + 8 + 4] // dst_ptr
mov esi, [esp + 8 + 8] // src_ptr
mov edx, [esp + 8 + 12] // src_stride
mov ecx, [esp + 8 + 16] // dst_width
mov eax, [esp + 8 + 20] // source_y_fraction (0..255)
shr eax, 1
cmp eax, 0
je xloop1
cmp eax, 64
je xloop2
mov ah,al
neg al
add al, 128
movd xmm5, eax
punpcklwd xmm5, xmm5
pshufd xmm5, xmm5, 0
xloop:
movdqa xmm0, [esi]
movdqa xmm2, [esi + edx]
lea esi, [esi + 16]
movdqa xmm1, xmm0
punpcklbw xmm0, xmm2
punpckhbw xmm1, xmm2
pmaddubsw xmm0, xmm5
pmaddubsw xmm1, xmm5
psrlw xmm0, 7
psrlw xmm1, 7
packuswb xmm0, xmm1
movdqa [edi], xmm0
lea edi, [edi + 16]
sub ecx, 16
ja xloop
mov al, [edi - 1]
mov [edi], al
pop edi
pop esi
ret
xloop1:
movdqa xmm0, [esi]
lea esi, [esi + 16]
movdqa [edi], xmm0
lea edi, [edi + 16]
sub ecx, 16
ja xloop1
mov al, [edi - 1]
mov [edi], al
pop edi
pop esi
ret
xloop2:
movdqa xmm0, [esi]
movdqa xmm2, [esi + edx]
lea esi, [esi + 16]
pavgb xmm0, xmm2
movdqa [edi], xmm0
lea edi, [edi + 16]
sub ecx, 16
ja xloop2
mov al, [edi - 1]
mov [edi], al
pop edi
pop esi
ret
}
}
// Note that movdqa+palign may be better than movdqu.
// Alignment requirement: src_ptr 16 byte aligned, dst_ptr 8 byte aligned.
__declspec(naked)
static void ScaleFilterCols34_SSSE3(uint8* dst_ptr, const uint8* src_ptr,
int dst_width) {
__asm {
mov edx, [esp + 4] // dst_ptr
mov eax, [esp + 8] // src_ptr
mov ecx, [esp + 12] // dst_width
movdqa xmm1, _round34
movdqa xmm2, _shuf01
movdqa xmm3, _shuf11
movdqa xmm4, _shuf21
movdqa xmm5, _madd01
movdqa xmm6, _madd11
movdqa xmm7, _madd21
wloop:
movdqa xmm0, [eax] // pixels 0..7
pshufb xmm0, xmm2
pmaddubsw xmm0, xmm5
paddsw xmm0, xmm1
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edx], xmm0
movdqu xmm0, [eax+8] // pixels 8..15
pshufb xmm0, xmm3
pmaddubsw xmm0, xmm6
paddsw xmm0, xmm1
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edx+8], xmm0
movdqa xmm0, [eax+16] // pixels 16..23
lea eax, [eax+32]
pshufb xmm0, xmm4
pmaddubsw xmm0, xmm7
paddsw xmm0, xmm1
psrlw xmm0, 2
packuswb xmm0, xmm0
movq qword ptr [edx+16], xmm0
lea edx, [edx+24]
sub ecx, 24
ja wloop
ret
}
}
#elif (defined(__x86_64__) || defined(__i386__)) && !defined(YUV_DISABLE_ASM)
// GCC versions of row functions are verbatim conversions from Visual C.
// Generated using gcc disassembly on Visual C object file:
// objdump -D yuvscaler.obj >yuvscaler.txt
#define HAS_SCALEROWDOWN2_SSE2
static void ScaleRowDown2_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
:
: "memory", "cc"
);
}
static void ScaleRowDown2Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlw $0x8,%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"movdqa (%0,%3,1),%%xmm2 \n"
"movdqa 0x10(%0,%3,1),%%xmm3 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"psrlw $0x8,%%xmm0 \n"
"movdqa %%xmm1,%%xmm3 \n"
"psrlw $0x8,%%xmm1 \n"
"pand %%xmm5,%%xmm2 \n"
"pand %%xmm5,%%xmm3 \n"
"pavgw %%xmm2,%%xmm0 \n"
"pavgw %%xmm3,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,(%1) \n"
"lea 0x10(%1),%1 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)) // %3
: "memory", "cc"
);
}
#define HAS_SCALEROWDOWN4_SSE2
static void ScaleRowDown4_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrld $0x18,%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x8,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
:
: "memory", "cc"
);
}
static void ScaleRowDown4Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
intptr_t temp = 0;
asm volatile (
"pcmpeqb %%xmm7,%%xmm7 \n"
"psrlw $0x8,%%xmm7 \n"
"lea (%4,%4,2),%3 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"movdqa (%0,%4,1),%%xmm2 \n"
"movdqa 0x10(%0,%4,1),%%xmm3 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"movdqa (%0,%4,2),%%xmm2 \n"
"movdqa 0x10(%0,%4,2),%%xmm3 \n"
"movdqa (%0,%3,1),%%xmm4 \n"
"movdqa 0x10(%0,%3,1),%%xmm5 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm4,%%xmm2 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm5,%%xmm3 \n"
"pavgb %%xmm3,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"psrlw $0x8,%%xmm0 \n"
"movdqa %%xmm1,%%xmm3 \n"
"psrlw $0x8,%%xmm1 \n"
"pand %%xmm7,%%xmm2 \n"
"pand %%xmm7,%%xmm3 \n"
"pavgw %%xmm2,%%xmm0 \n"
"pavgw %%xmm3,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,%%xmm2 \n"
"psrlw $0x8,%%xmm0 \n"
"pand %%xmm7,%%xmm2 \n"
"pavgw %%xmm2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"lea 0x8(%1),%1 \n"
"sub $0x8,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width), // %2
"+r"(temp) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc"
#if defined(__x86_64__)
, "xmm6", "xmm7"
#endif
);
}
#define HAS_SCALEROWDOWN8_SSE2
static void ScaleRowDown8_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"pcmpeqb %%xmm5,%%xmm5 \n"
"psrlq $0x38,%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pand %%xmm5,%%xmm0 \n"
"pand %%xmm5,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movd %%xmm0,(%1) \n"
"lea 0x4(%1),%1 \n"
"sub $0x4,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
:
: "memory", "cc"
);
}
#if defined(__i386__)
void ScaleRowDown8Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown8Int_SSE2)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%ebx \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"lea (%ebx,%ebx,2),%edx \n"
"pxor %xmm7,%xmm7 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa 0x10(%esi),%xmm1 \n"
"movdqa (%esi,%ebx,1),%xmm2 \n"
"movdqa 0x10(%esi,%ebx,1),%xmm3 \n"
"pavgb %xmm2,%xmm0 \n"
"pavgb %xmm3,%xmm1 \n"
"movdqa (%esi,%ebx,2),%xmm2 \n"
"movdqa 0x10(%esi,%ebx,2),%xmm3 \n"
"movdqa (%esi,%edx,1),%xmm4 \n"
"movdqa 0x10(%esi,%edx,1),%xmm5 \n"
"lea (%esi,%ebx,4),%ebp \n"
"lea 0x20(%esi),%esi \n"
"pavgb %xmm4,%xmm2 \n"
"pavgb %xmm5,%xmm3 \n"
"pavgb %xmm2,%xmm0 \n"
"pavgb %xmm3,%xmm1 \n"
"movdqa 0x0(%ebp),%xmm2 \n"
"movdqa 0x10(%ebp),%xmm3 \n"
"movdqa 0x0(%ebp,%ebx,1),%xmm4 \n"
"movdqa 0x10(%ebp,%ebx,1),%xmm5 \n"
"pavgb %xmm4,%xmm2 \n"
"pavgb %xmm5,%xmm3 \n"
"movdqa 0x0(%ebp,%ebx,2),%xmm4 \n"
"movdqa 0x10(%ebp,%ebx,2),%xmm5 \n"
"movdqa 0x0(%ebp,%edx,1),%xmm6 \n"
"pavgb %xmm6,%xmm4 \n"
"movdqa 0x10(%ebp,%edx,1),%xmm6 \n"
"pavgb %xmm6,%xmm5 \n"
"pavgb %xmm4,%xmm2 \n"
"pavgb %xmm5,%xmm3 \n"
"pavgb %xmm2,%xmm0 \n"
"pavgb %xmm3,%xmm1 \n"
"psadbw %xmm7,%xmm0 \n"
"psadbw %xmm7,%xmm1 \n"
"pshufd $0xd8,%xmm0,%xmm0 \n"
"pshufd $0x8d,%xmm1,%xmm1 \n"
"por %xmm1,%xmm0 \n"
"psrlw $0x3,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movd %xmm0,(%edi) \n"
"lea 0x4(%edi),%edi \n"
"sub $0x4,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
// fpic is used for magiccam plugin
#if !defined(__PIC__)
#define HAS_SCALEROWDOWN34_SSSE3
void ScaleRowDown34_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown34_SSSE3)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"movdqa _shuf0,%xmm3 \n"
"movdqa _shuf1,%xmm4 \n"
"movdqa _shuf2,%xmm5 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa 0x10(%esi),%xmm2 \n"
"lea 0x20(%esi),%esi \n"
"movdqa %xmm2,%xmm1 \n"
"palignr $0x8,%xmm0,%xmm1 \n"
"pshufb %xmm3,%xmm0 \n"
"pshufb %xmm4,%xmm1 \n"
"pshufb %xmm5,%xmm2 \n"
"movq %xmm0,(%edi) \n"
"movq %xmm1,0x8(%edi) \n"
"movq %xmm2,0x10(%edi) \n"
"lea 0x18(%edi),%edi \n"
"sub $0x18,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
void ScaleRowDown34_1_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown34_1_Int_SSSE3)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%ebp \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"movdqa _shuf01,%xmm2 \n"
"movdqa _shuf11,%xmm3 \n"
"movdqa _shuf21,%xmm4 \n"
"movdqa _madd01,%xmm5 \n"
"movdqa _madd11,%xmm6 \n"
"movdqa _round34,%xmm7 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%ebp),%xmm1 \n"
"pavgb %xmm1,%xmm0 \n"
"pshufb %xmm2,%xmm0 \n"
"pmaddubsw %xmm5,%xmm0 \n"
"paddsw %xmm7,%xmm0 \n"
"psrlw $0x2,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movq %xmm0,(%edi) \n"
"movdqu 0x8(%esi),%xmm0 \n"
"movdqu 0x8(%esi,%ebp),%xmm1 \n"
"pavgb %xmm1,%xmm0 \n"
"pshufb %xmm3,%xmm0 \n"
"pmaddubsw %xmm6,%xmm0 \n"
"paddsw %xmm7,%xmm0 \n"
"psrlw $0x2,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movq %xmm0,0x8(%edi) \n"
"movdqa 0x10(%esi),%xmm0 \n"
"movdqa 0x10(%esi,%ebp),%xmm1 \n"
"lea 0x20(%esi),%esi \n"
"pavgb %xmm1,%xmm0 \n"
"pshufb %xmm4,%xmm0 \n"
"movdqa _madd21,%xmm1 \n"
"pmaddubsw %xmm1,%xmm0 \n"
"paddsw %xmm7,%xmm0 \n"
"psrlw $0x2,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movq %xmm0,0x10(%edi) \n"
"lea 0x18(%edi),%edi \n"
"sub $0x18,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
void ScaleRowDown34_0_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown34_0_Int_SSSE3)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%ebp \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"movdqa _shuf01,%xmm2 \n"
"movdqa _shuf11,%xmm3 \n"
"movdqa _shuf21,%xmm4 \n"
"movdqa _madd01,%xmm5 \n"
"movdqa _madd11,%xmm6 \n"
"movdqa _round34,%xmm7 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%ebp,1),%xmm1 \n"
"pavgb %xmm0,%xmm1 \n"
"pavgb %xmm1,%xmm0 \n"
"pshufb %xmm2,%xmm0 \n"
"pmaddubsw %xmm5,%xmm0 \n"
"paddsw %xmm7,%xmm0 \n"
"psrlw $0x2,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movq %xmm0,(%edi) \n"
"movdqu 0x8(%esi),%xmm0 \n"
"movdqu 0x8(%esi,%ebp,1),%xmm1 \n"
"pavgb %xmm0,%xmm1 \n"
"pavgb %xmm1,%xmm0 \n"
"pshufb %xmm3,%xmm0 \n"
"pmaddubsw %xmm6,%xmm0 \n"
"paddsw %xmm7,%xmm0 \n"
"psrlw $0x2,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movq %xmm0,0x8(%edi) \n"
"movdqa 0x10(%esi),%xmm0 \n"
"movdqa 0x10(%esi,%ebp,1),%xmm1 \n"
"lea 0x20(%esi),%esi \n"
"pavgb %xmm0,%xmm1 \n"
"pavgb %xmm1,%xmm0 \n"
"pshufb %xmm4,%xmm0 \n"
"movdqa _madd21,%xmm1 \n"
"pmaddubsw %xmm1,%xmm0 \n"
"paddsw %xmm7,%xmm0 \n"
"psrlw $0x2,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movq %xmm0,0x10(%edi) \n"
"lea 0x18(%edi),%edi \n"
"sub $0x18,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
#define HAS_SCALEROWDOWN38_SSSE3
void ScaleRowDown38_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown38_SSSE3)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%edx \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"movdqa _shuf38a ,%xmm4 \n"
"movdqa _shuf38b ,%xmm5 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa 0x10(%esi),%xmm1 \n"
"lea 0x20(%esi),%esi \n"
"pshufb %xmm4,%xmm0 \n"
"pshufb %xmm5,%xmm1 \n"
"paddusb %xmm1,%xmm0 \n"
"movq %xmm0,(%edi) \n"
"movhlps %xmm0,%xmm1 \n"
"movd %xmm1,0x8(%edi) \n"
"lea 0xc(%edi),%edi \n"
"sub $0xc,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
void ScaleRowDown38_3_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown38_3_Int_SSSE3)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%edx \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"movdqa _shufac0,%xmm4 \n"
"movdqa _shufac3,%xmm5 \n"
"movdqa _scaleac3,%xmm6 \n"
"pxor %xmm7,%xmm7 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%edx,1),%xmm2 \n"
"movhlps %xmm0,%xmm1 \n"
"movhlps %xmm2,%xmm3 \n"
"punpcklbw %xmm7,%xmm0 \n"
"punpcklbw %xmm7,%xmm1 \n"
"punpcklbw %xmm7,%xmm2 \n"
"punpcklbw %xmm7,%xmm3 \n"
"paddusw %xmm2,%xmm0 \n"
"paddusw %xmm3,%xmm1 \n"
"movdqa (%esi,%edx,2),%xmm2 \n"
"lea 0x10(%esi),%esi \n"
"movhlps %xmm2,%xmm3 \n"
"punpcklbw %xmm7,%xmm2 \n"
"punpcklbw %xmm7,%xmm3 \n"
"paddusw %xmm2,%xmm0 \n"
"paddusw %xmm3,%xmm1 \n"
"movdqa %xmm0,%xmm2 \n"
"psrldq $0x2,%xmm0 \n"
"paddusw %xmm0,%xmm2 \n"
"psrldq $0x2,%xmm0 \n"
"paddusw %xmm0,%xmm2 \n"
"pshufb %xmm4,%xmm2 \n"
"movdqa %xmm1,%xmm3 \n"
"psrldq $0x2,%xmm1 \n"
"paddusw %xmm1,%xmm3 \n"
"psrldq $0x2,%xmm1 \n"
"paddusw %xmm1,%xmm3 \n"
"pshufb %xmm5,%xmm3 \n"
"paddusw %xmm3,%xmm2 \n"
"pmulhuw %xmm6,%xmm2 \n"
"packuswb %xmm2,%xmm2 \n"
"movd %xmm2,(%edi) \n"
"pextrw $0x2,%xmm2,%eax \n"
"mov %ax,0x4(%edi) \n"
"lea 0x6(%edi),%edi \n"
"sub $0x6,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
void ScaleRowDown38_2_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
asm(
DECLARE_FUNCTION(ScaleRowDown38_2_Int_SSSE3)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%edx \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"movdqa _shufab0,%xmm4 \n"
"movdqa _shufab1,%xmm5 \n"
"movdqa _shufab2,%xmm6 \n"
"movdqa _scaleab2,%xmm7 \n"
"1:"
"movdqa (%esi),%xmm2 \n"
"pavgb (%esi,%edx,1),%xmm2 \n"
"lea 0x10(%esi),%esi \n"
"movdqa %xmm2,%xmm0 \n"
"pshufb %xmm4,%xmm0 \n"
"movdqa %xmm2,%xmm1 \n"
"pshufb %xmm5,%xmm1 \n"
"paddusw %xmm1,%xmm0 \n"
"pshufb %xmm6,%xmm2 \n"
"paddusw %xmm2,%xmm0 \n"
"pmulhuw %xmm7,%xmm0 \n"
"packuswb %xmm0,%xmm0 \n"
"movd %xmm0,(%edi) \n"
"pextrw $0x2,%xmm0,%eax \n"
"mov %ax,0x4(%edi) \n"
"lea 0x6(%edi),%edi \n"
"sub $0x6,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
#endif // __PIC__
#define HAS_SCALEADDROWS_SSE2
void ScaleAddRows_SSE2(const uint8* src_ptr, int src_stride,
uint16* dst_ptr, int src_width,
int src_height);
asm(
DECLARE_FUNCTION(ScaleAddRows_SSE2)
"pusha \n"
"mov 0x24(%esp),%esi \n"
"mov 0x28(%esp),%edx \n"
"mov 0x2c(%esp),%edi \n"
"mov 0x30(%esp),%ecx \n"
"mov 0x34(%esp),%ebx \n"
"pxor %xmm5,%xmm5 \n"
"1:"
"movdqa (%esi),%xmm2 \n"
"lea (%esi,%edx,1),%eax \n"
"movhlps %xmm2,%xmm3 \n"
"lea -0x1(%ebx),%ebp \n"
"punpcklbw %xmm5,%xmm2 \n"
"punpcklbw %xmm5,%xmm3 \n"
"2:"
"movdqa (%eax),%xmm0 \n"
"lea (%eax,%edx,1),%eax \n"
"movhlps %xmm0,%xmm1 \n"
"punpcklbw %xmm5,%xmm0 \n"
"punpcklbw %xmm5,%xmm1 \n"
"paddusw %xmm0,%xmm2 \n"
"paddusw %xmm1,%xmm3 \n"
"sub $0x1,%ebp \n"
"ja 2b \n"
"movdqa %xmm2,(%edi) \n"
"movdqa %xmm3,0x10(%edi) \n"
"lea 0x20(%edi),%edi \n"
"lea 0x10(%esi),%esi \n"
"sub $0x10,%ecx \n"
"ja 1b \n"
"popa \n"
"ret \n"
);
// Bilinear row filtering combines 16x2 -> 16x1. SSE2 version
#define HAS_SCALEFILTERROWS_SSE2
void ScaleFilterRows_SSE2(uint8* dst_ptr,
const uint8* src_ptr, int src_stride,
int dst_width, int source_y_fraction);
asm(
DECLARE_FUNCTION(ScaleFilterRows_SSE2)
"push %esi \n"
"push %edi \n"
"mov 0xc(%esp),%edi \n"
"mov 0x10(%esp),%esi \n"
"mov 0x14(%esp),%edx \n"
"mov 0x18(%esp),%ecx \n"
"mov 0x1c(%esp),%eax \n"
"cmp $0x0,%eax \n"
"je 2f \n"
"cmp $0x80,%eax \n"
"je 3f \n"
"movd %eax,%xmm6 \n"
"punpcklwd %xmm6,%xmm6 \n"
"pshufd $0x0,%xmm6,%xmm6 \n"
"neg %eax \n"
"add $0x100,%eax \n"
"movd %eax,%xmm5 \n"
"punpcklwd %xmm5,%xmm5 \n"
"pshufd $0x0,%xmm5,%xmm5 \n"
"pxor %xmm7,%xmm7 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%edx,1),%xmm2 \n"
"lea 0x10(%esi),%esi \n"
"movdqa %xmm0,%xmm1 \n"
"movdqa %xmm2,%xmm3 \n"
"punpcklbw %xmm7,%xmm0 \n"
"punpcklbw %xmm7,%xmm2 \n"
"punpckhbw %xmm7,%xmm1 \n"
"punpckhbw %xmm7,%xmm3 \n"
"pmullw %xmm5,%xmm0 \n"
"pmullw %xmm5,%xmm1 \n"
"pmullw %xmm6,%xmm2 \n"
"pmullw %xmm6,%xmm3 \n"
"paddusw %xmm2,%xmm0 \n"
"paddusw %xmm3,%xmm1 \n"
"psrlw $0x8,%xmm0 \n"
"psrlw $0x8,%xmm1 \n"
"packuswb %xmm1,%xmm0 \n"
"movdqa %xmm0,(%edi) \n"
"lea 0x10(%edi),%edi \n"
"sub $0x10,%ecx \n"
"ja 1b \n"
"mov -0x1(%edi),%al \n"
"mov %al,(%edi) \n"
"pop %edi \n"
"pop %esi \n"
"ret \n"
"2:"
"movdqa (%esi),%xmm0 \n"
"lea 0x10(%esi),%esi \n"
"movdqa %xmm0,(%edi) \n"
"lea 0x10(%edi),%edi \n"
"sub $0x10,%ecx \n"
"ja 2b \n"
"mov -0x1(%edi),%al \n"
"mov %al,(%edi) \n"
"pop %edi \n"
"pop %esi \n"
"ret \n"
"3:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%edx,1),%xmm2 \n"
"lea 0x10(%esi),%esi \n"
"pavgb %xmm2,%xmm0 \n"
"movdqa %xmm0,(%edi) \n"
"lea 0x10(%edi),%edi \n"
"sub $0x10,%ecx \n"
"ja 3b \n"
"mov -0x1(%edi),%al \n"
"mov %al,(%edi) \n"
"pop %edi \n"
"pop %esi \n"
"ret \n"
);
// Bilinear row filtering combines 16x2 -> 16x1. SSSE3 version
#define HAS_SCALEFILTERROWS_SSSE3
void ScaleFilterRows_SSSE3(uint8* dst_ptr,
const uint8* src_ptr, int src_stride,
int dst_width, int source_y_fraction);
asm(
DECLARE_FUNCTION(ScaleFilterRows_SSSE3)
"push %esi \n"
"push %edi \n"
"mov 0xc(%esp),%edi \n"
"mov 0x10(%esp),%esi \n"
"mov 0x14(%esp),%edx \n"
"mov 0x18(%esp),%ecx \n"
"mov 0x1c(%esp),%eax \n"
"shr %eax \n"
"cmp $0x0,%eax \n"
"je 2f \n"
"cmp $0x40,%eax \n"
"je 3f \n"
"mov %al,%ah \n"
"neg %al \n"
"add $0x80,%al \n"
"movd %eax,%xmm5 \n"
"punpcklwd %xmm5,%xmm5 \n"
"pshufd $0x0,%xmm5,%xmm5 \n"
"1:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%edx,1),%xmm2 \n"
"lea 0x10(%esi),%esi \n"
"movdqa %xmm0,%xmm1 \n"
"punpcklbw %xmm2,%xmm0 \n"
"punpckhbw %xmm2,%xmm1 \n"
"pmaddubsw %xmm5,%xmm0 \n"
"pmaddubsw %xmm5,%xmm1 \n"
"psrlw $0x7,%xmm0 \n"
"psrlw $0x7,%xmm1 \n"
"packuswb %xmm1,%xmm0 \n"
"movdqa %xmm0,(%edi) \n"
"lea 0x10(%edi),%edi \n"
"sub $0x10,%ecx \n"
"ja 1b \n"
"mov -0x1(%edi),%al \n"
"mov %al,(%edi) \n"
"pop %edi \n"
"pop %esi \n"
"ret \n"
"2:"
"movdqa (%esi),%xmm0 \n"
"lea 0x10(%esi),%esi \n"
"movdqa %xmm0,(%edi) \n"
"lea 0x10(%edi),%edi \n"
"sub $0x10,%ecx \n"
"ja 2b \n"
"mov -0x1(%edi),%al \n"
"mov %al,(%edi) \n"
"pop %edi \n"
"pop %esi \n"
"ret \n"
"3:"
"movdqa (%esi),%xmm0 \n"
"movdqa (%esi,%edx,1),%xmm2 \n"
"lea 0x10(%esi),%esi \n"
"pavgb %xmm2,%xmm0 \n"
"movdqa %xmm0,(%edi) \n"
"lea 0x10(%edi),%edi \n"
"sub $0x10,%ecx \n"
"ja 3b \n"
"mov -0x1(%edi),%al \n"
"mov %al,(%edi) \n"
"pop %edi \n"
"pop %esi \n"
"ret \n"
);
#elif defined(__x86_64__)
static void ScaleRowDown8Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"lea (%3,%3,2),%%r10 \n"
"pxor %%xmm7,%%xmm7 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"movdqa (%0,%3,1),%%xmm2 \n"
"movdqa 0x10(%0,%3,1),%%xmm3 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"movdqa (%0,%3,2),%%xmm2 \n"
"movdqa 0x10(%0,%3,2),%%xmm3 \n"
"movdqa (%0,%%r10,1),%%xmm4 \n"
"movdqa 0x10(%0,%%r10,1),%%xmm5 \n"
"lea (%0,%3,4),%%r11 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm4,%%xmm2 \n"
"pavgb %%xmm5,%%xmm3 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"movdqa 0x0(%%r11),%%xmm2 \n"
"movdqa 0x10(%%r11),%%xmm3 \n"
"movdqa 0x0(%%r11,%3,1),%%xmm4 \n"
"movdqa 0x10(%%r11,%3,1),%%xmm5 \n"
"pavgb %%xmm4,%%xmm2 \n"
"pavgb %%xmm5,%%xmm3 \n"
"movdqa 0x0(%%r11,%3,2),%%xmm4 \n"
"movdqa 0x10(%%r11,%3,2),%%xmm5 \n"
"movdqa 0x0(%%r11,%%r10,1),%%xmm6 \n"
"pavgb %%xmm6,%%xmm4 \n"
"movdqa 0x10(%%r11,%%r10,1),%%xmm6 \n"
"pavgb %%xmm6,%%xmm5 \n"
"pavgb %%xmm4,%%xmm2 \n"
"pavgb %%xmm5,%%xmm3 \n"
"pavgb %%xmm2,%%xmm0 \n"
"pavgb %%xmm3,%%xmm1 \n"
"psadbw %%xmm7,%%xmm0 \n"
"psadbw %%xmm7,%%xmm1 \n"
"pshufd $0xd8,%%xmm0,%%xmm0 \n"
"pshufd $0x8d,%%xmm1,%%xmm1 \n"
"por %%xmm1,%%xmm0 \n"
"psrlw $0x3,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movd %%xmm0,(%1) \n"
"lea 0x4(%1),%1 \n"
"sub $0x4,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)) // %3
: "memory", "cc", "r10", "r11", "xmm6", "xmm7"
);
}
#define HAS_SCALEROWDOWN34_SSSE3
static void ScaleRowDown34_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"movdqa (%3),%%xmm3 \n"
"movdqa (%4),%%xmm4 \n"
"movdqa (%5),%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm2 \n"
"lea 0x20(%0),%0 \n"
"movdqa %%xmm2,%%xmm1 \n"
"palignr $0x8,%%xmm0,%%xmm1 \n"
"pshufb %%xmm3,%%xmm0 \n"
"pshufb %%xmm4,%%xmm1 \n"
"pshufb %%xmm5,%%xmm2 \n"
"movq %%xmm0,(%1) \n"
"movq %%xmm1,0x8(%1) \n"
"movq %%xmm2,0x10(%1) \n"
"lea 0x18(%1),%1 \n"
"sub $0x18,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"(_shuf0), // %3
"r"(_shuf1), // %4
"r"(_shuf2) // %5
: "memory", "cc"
);
}
static void ScaleRowDown34_1_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"movdqa (%4),%%xmm2 \n" // _shuf01
"movdqa (%5),%%xmm3 \n" // _shuf11
"movdqa (%6),%%xmm4 \n" // _shuf21
"movdqa (%7),%%xmm5 \n" // _madd01
"movdqa (%8),%%xmm6 \n" // _madd11
"movdqa (%9),%%xmm7 \n" // _round34
"movdqa (%10),%%xmm8 \n" // _madd21
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa (%0,%3),%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"pshufb %%xmm2,%%xmm0 \n"
"pmaddubsw %%xmm5,%%xmm0 \n"
"paddsw %%xmm7,%%xmm0 \n"
"psrlw $0x2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"movdqu 0x8(%0),%%xmm0 \n"
"movdqu 0x8(%0,%3),%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"pshufb %%xmm3,%%xmm0 \n"
"pmaddubsw %%xmm6,%%xmm0 \n"
"paddsw %%xmm7,%%xmm0 \n"
"psrlw $0x2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x8(%1) \n"
"movdqa 0x10(%0),%%xmm0 \n"
"movdqa 0x10(%0,%3),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm1,%%xmm0 \n"
"pshufb %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm8,%%xmm0 \n"
"paddsw %%xmm7,%%xmm0 \n"
"psrlw $0x2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x10(%1) \n"
"lea 0x18(%1),%1 \n"
"sub $0x18,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)), // %3
"r"(_shuf01), // %4
"r"(_shuf11), // %5
"r"(_shuf21), // %6
"r"(_madd01), // %7
"r"(_madd11), // %8
"r"(_round34), // %9
"r"(_madd21) // %10
: "memory", "cc", "xmm6", "xmm7", "xmm8"
);
}
static void ScaleRowDown34_0_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"movdqa (%4),%%xmm2 \n" // _shuf01
"movdqa (%5),%%xmm3 \n" // _shuf11
"movdqa (%6),%%xmm4 \n" // _shuf21
"movdqa (%7),%%xmm5 \n" // _madd01
"movdqa (%8),%%xmm6 \n" // _madd11
"movdqa (%9),%%xmm7 \n" // _round34
"movdqa (%10),%%xmm8 \n" // _madd21
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa (%0,%3,1),%%xmm1 \n"
"pavgb %%xmm0,%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"pshufb %%xmm2,%%xmm0 \n"
"pmaddubsw %%xmm5,%%xmm0 \n"
"paddsw %%xmm7,%%xmm0 \n"
"psrlw $0x2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"movdqu 0x8(%0),%%xmm0 \n"
"movdqu 0x8(%0,%3,1),%%xmm1 \n"
"pavgb %%xmm0,%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"pshufb %%xmm3,%%xmm0 \n"
"pmaddubsw %%xmm6,%%xmm0 \n"
"paddsw %%xmm7,%%xmm0 \n"
"psrlw $0x2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x8(%1) \n"
"movdqa 0x10(%0),%%xmm0 \n"
"movdqa 0x10(%0,%3,1),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pavgb %%xmm0,%%xmm1 \n"
"pavgb %%xmm1,%%xmm0 \n"
"pshufb %%xmm4,%%xmm0 \n"
"pmaddubsw %%xmm8,%%xmm0 \n"
"paddsw %%xmm7,%%xmm0 \n"
"psrlw $0x2,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movq %%xmm0,0x10(%1) \n"
"lea 0x18(%1),%1 \n"
"sub $0x18,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)), // %3
"r"(_shuf01), // %4
"r"(_shuf11), // %5
"r"(_shuf21), // %6
"r"(_madd01), // %7
"r"(_madd11), // %8
"r"(_round34), // %9
"r"(_madd21) // %10
: "memory", "cc", "xmm6", "xmm7", "xmm8"
);
}
#define HAS_SCALEROWDOWN38_SSSE3
static void ScaleRowDown38_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"movdqa (%3),%%xmm4 \n"
"movdqa (%4),%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa 0x10(%0),%%xmm1 \n"
"lea 0x20(%0),%0 \n"
"pshufb %%xmm4,%%xmm0 \n"
"pshufb %%xmm5,%%xmm1 \n"
"paddusb %%xmm1,%%xmm0 \n"
"movq %%xmm0,(%1) \n"
"movhlps %%xmm0,%%xmm1 \n"
"movd %%xmm1,0x8(%1) \n"
"lea 0xc(%1),%1 \n"
"sub $0xc,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"(_shuf38a), // %3
"r"(_shuf38b) // %4
: "memory", "cc"
);
}
static void ScaleRowDown38_3_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"movdqa (%4),%%xmm4 \n"
"movdqa (%5),%%xmm5 \n"
"movdqa (%6),%%xmm6 \n"
"pxor %%xmm7,%%xmm7 \n"
"1:"
"movdqa (%0),%%xmm0 \n"
"movdqa (%0,%3,1),%%xmm2 \n"
"movhlps %%xmm0,%%xmm1 \n"
"movhlps %%xmm2,%%xmm3 \n"
"punpcklbw %%xmm7,%%xmm0 \n"
"punpcklbw %%xmm7,%%xmm1 \n"
"punpcklbw %%xmm7,%%xmm2 \n"
"punpcklbw %%xmm7,%%xmm3 \n"
"paddusw %%xmm2,%%xmm0 \n"
"paddusw %%xmm3,%%xmm1 \n"
"movdqa (%0,%3,2),%%xmm2 \n"
"lea 0x10(%0),%0 \n"
"movhlps %%xmm2,%%xmm3 \n"
"punpcklbw %%xmm7,%%xmm2 \n"
"punpcklbw %%xmm7,%%xmm3 \n"
"paddusw %%xmm2,%%xmm0 \n"
"paddusw %%xmm3,%%xmm1 \n"
"movdqa %%xmm0,%%xmm2 \n"
"psrldq $0x2,%%xmm0 \n"
"paddusw %%xmm0,%%xmm2 \n"
"psrldq $0x2,%%xmm0 \n"
"paddusw %%xmm0,%%xmm2 \n"
"pshufb %%xmm4,%%xmm2 \n"
"movdqa %%xmm1,%%xmm3 \n"
"psrldq $0x2,%%xmm1 \n"
"paddusw %%xmm1,%%xmm3 \n"
"psrldq $0x2,%%xmm1 \n"
"paddusw %%xmm1,%%xmm3 \n"
"pshufb %%xmm5,%%xmm3 \n"
"paddusw %%xmm3,%%xmm2 \n"
"pmulhuw %%xmm6,%%xmm2 \n"
"packuswb %%xmm2,%%xmm2 \n"
"movd %%xmm2,(%1) \n"
"pextrw $0x2,%%xmm2,%%eax \n"
"mov %%ax,0x4(%1) \n"
"lea 0x6(%1),%1 \n"
"sub $0x6,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)), // %3
"r"(_shufac0), // %4
"r"(_shufac3), // %5
"r"(_scaleac3) // %6
: "memory", "cc", "rax", "xmm6", "xmm7"
);
}
static void ScaleRowDown38_2_Int_SSSE3(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
asm volatile (
"movdqa (%4),%%xmm4 \n"
"movdqa (%5),%%xmm5 \n"
"movdqa (%6),%%xmm6 \n"
"movdqa (%7),%%xmm7 \n"
"1:"
"movdqa (%0),%%xmm2 \n"
"pavgb (%0,%3,1),%%xmm2 \n"
"lea 0x10(%0),%0 \n"
"movdqa %%xmm2,%%xmm0 \n"
"pshufb %%xmm4,%%xmm0 \n"
"movdqa %%xmm2,%%xmm1 \n"
"pshufb %%xmm5,%%xmm1 \n"
"paddusw %%xmm1,%%xmm0 \n"
"pshufb %%xmm6,%%xmm2 \n"
"paddusw %%xmm2,%%xmm0 \n"
"pmulhuw %%xmm7,%%xmm0 \n"
"packuswb %%xmm0,%%xmm0 \n"
"movd %%xmm0,(%1) \n"
"pextrw $0x2,%%xmm0,%%eax \n"
"mov %%ax,0x4(%1) \n"
"lea 0x6(%1),%1 \n"
"sub $0x6,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)), // %3
"r"(_shufab0), // %4
"r"(_shufab1), // %5
"r"(_shufab2), // %6
"r"(_scaleab2) // %7
: "memory", "cc", "rax", "xmm6", "xmm7"
);
}
#define HAS_SCALEADDROWS_SSE2
static void ScaleAddRows_SSE2(const uint8* src_ptr, int src_stride,
uint16* dst_ptr, int src_width,
int src_height) {
asm volatile (
"pxor %%xmm5,%%xmm5 \n"
"1:"
"movdqa (%0),%%xmm2 \n"
"lea (%0,%4,1),%%r10 \n"
"movhlps %%xmm2,%%xmm3 \n"
"lea -0x1(%3),%%r11 \n"
"punpcklbw %%xmm5,%%xmm2 \n"
"punpcklbw %%xmm5,%%xmm3 \n"
"2:"
"movdqa (%%r10),%%xmm0 \n"
"lea (%%r10,%4,1),%%r10 \n"
"movhlps %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm5,%%xmm0 \n"
"punpcklbw %%xmm5,%%xmm1 \n"
"paddusw %%xmm0,%%xmm2 \n"
"paddusw %%xmm1,%%xmm3 \n"
"sub $0x1,%%r11 \n"
"ja 2b \n"
"movdqa %%xmm2,(%1) \n"
"movdqa %%xmm3,0x10(%1) \n"
"lea 0x20(%1),%1 \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
: "+r"(src_ptr), // %0
"+r"(dst_ptr), // %1
"+r"(src_width), // %2
"+r"(src_height) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "r10", "r11"
);
}
// Bilinear row filtering combines 16x2 -> 16x1. SSE2 version
#define HAS_SCALEFILTERROWS_SSE2
static void ScaleFilterRows_SSE2(uint8* dst_ptr,
const uint8* src_ptr, int src_stride,
int dst_width, int source_y_fraction) {
if (source_y_fraction == 0) {
asm volatile (
"1:"
"movdqa (%1),%%xmm0 \n"
"lea 0x10(%1),%1 \n"
"movdqa %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
"mov -0x1(%0),%%al \n"
"mov %%al,(%0) \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+r"(dst_width) // %2
:
: "memory", "cc", "rax"
);
return;
} else if (source_y_fraction == 128) {
asm volatile (
"1:"
"movdqa (%1),%%xmm0 \n"
"movdqa (%1,%3,1),%%xmm2 \n"
"lea 0x10(%1),%1 \n"
"pavgb %%xmm2,%%xmm0 \n"
"movdqa %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
"mov -0x1(%0),%%al \n"
"mov %%al,(%0) \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)) // %3
: "memory", "cc", "rax"
);
return;
} else {
asm volatile (
"mov %3,%%eax \n"
"movd %%eax,%%xmm6 \n"
"punpcklwd %%xmm6,%%xmm6 \n"
"pshufd $0x0,%%xmm6,%%xmm6 \n"
"neg %%eax \n"
"add $0x100,%%eax \n"
"movd %%eax,%%xmm5 \n"
"punpcklwd %%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"pxor %%xmm7,%%xmm7 \n"
"1:"
"movdqa (%1),%%xmm0 \n"
"movdqa (%1,%4,1),%%xmm2 \n"
"lea 0x10(%1),%1 \n"
"movdqa %%xmm0,%%xmm1 \n"
"movdqa %%xmm2,%%xmm3 \n"
"punpcklbw %%xmm7,%%xmm0 \n"
"punpcklbw %%xmm7,%%xmm2 \n"
"punpckhbw %%xmm7,%%xmm1 \n"
"punpckhbw %%xmm7,%%xmm3 \n"
"pmullw %%xmm5,%%xmm0 \n"
"pmullw %%xmm5,%%xmm1 \n"
"pmullw %%xmm6,%%xmm2 \n"
"pmullw %%xmm6,%%xmm3 \n"
"paddusw %%xmm2,%%xmm0 \n"
"paddusw %%xmm3,%%xmm1 \n"
"psrlw $0x8,%%xmm0 \n"
"psrlw $0x8,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
"mov -0x1(%0),%%al \n"
"mov %%al,(%0) \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+r"(dst_width), // %2
"+r"(source_y_fraction) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "rax", "xmm6", "xmm7"
);
}
return;
}
// Bilinear row filtering combines 16x2 -> 16x1. SSSE3 version
#define HAS_SCALEFILTERROWS_SSSE3
static void ScaleFilterRows_SSSE3(uint8* dst_ptr,
const uint8* src_ptr, int src_stride,
int dst_width, int source_y_fraction) {
source_y_fraction >>= 1;
if (source_y_fraction == 0) {
asm volatile (
"1:"
"movdqa (%1),%%xmm0 \n"
"lea 0x10(%1),%1 \n"
"movdqa %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
"mov -0x1(%0),%%al \n"
"mov %%al,(%0) \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+r"(dst_width) // %2
:
: "memory", "cc", "rax"
);
return;
} else if (source_y_fraction == 64) {
asm volatile (
"1:"
"movdqa (%1),%%xmm0 \n"
"movdqa (%1,%3,1),%%xmm2 \n"
"lea 0x10(%1),%1 \n"
"pavgb %%xmm2,%%xmm0 \n"
"movdqa %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
"mov -0x1(%0),%%al \n"
"mov %%al,(%0) \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+r"(dst_width) // %2
: "r"((intptr_t)(src_stride)) // %3
: "memory", "cc", "rax"
);
return;
} else {
asm volatile (
"mov %3,%%eax \n"
"mov %%al,%%ah \n"
"neg %%al \n"
"add $0x80,%%al \n"
"movd %%eax,%%xmm5 \n"
"punpcklwd %%xmm5,%%xmm5 \n"
"pshufd $0x0,%%xmm5,%%xmm5 \n"
"1:"
"movdqa (%1),%%xmm0 \n"
"movdqa (%1,%4,1),%%xmm2 \n"
"lea 0x10(%1),%1 \n"
"movdqa %%xmm0,%%xmm1 \n"
"punpcklbw %%xmm2,%%xmm0 \n"
"punpckhbw %%xmm2,%%xmm1 \n"
"pmaddubsw %%xmm5,%%xmm0 \n"
"pmaddubsw %%xmm5,%%xmm1 \n"
"psrlw $0x7,%%xmm0 \n"
"psrlw $0x7,%%xmm1 \n"
"packuswb %%xmm1,%%xmm0 \n"
"movdqa %%xmm0,(%0) \n"
"lea 0x10(%0),%0 \n"
"sub $0x10,%2 \n"
"ja 1b \n"
"mov -0x1(%0),%%al \n"
"mov %%al,(%0) \n"
: "+r"(dst_ptr), // %0
"+r"(src_ptr), // %1
"+r"(dst_width), // %2
"+r"(source_y_fraction) // %3
: "r"((intptr_t)(src_stride)) // %4
: "memory", "cc", "rax"
);
}
return;
}
#endif
#endif
// CPU agnostic row functions
static void ScaleRowDown2_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
int x;
for (x = 0; x < dst_width; ++x) {
*dst++ = *src_ptr;
src_ptr += 2;
}
}
static void ScaleRowDown2Int_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
int x;
for (x = 0; x < dst_width; ++x) {
*dst++ = (src_ptr[0] + src_ptr[1] +
src_ptr[src_stride] + src_ptr[src_stride + 1] + 2) >> 2;
src_ptr += 2;
}
}
static void ScaleRowDown4_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
int x;
for (x = 0; x < dst_width; ++x) {
*dst++ = *src_ptr;
src_ptr += 4;
}
}
static void ScaleRowDown4Int_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
int x;
for (x = 0; x < dst_width; ++x) {
*dst++ = (src_ptr[0] + src_ptr[1] + src_ptr[2] + src_ptr[3] +
src_ptr[src_stride + 0] + src_ptr[src_stride + 1] +
src_ptr[src_stride + 2] + src_ptr[src_stride + 3] +
src_ptr[src_stride * 2 + 0] + src_ptr[src_stride * 2 + 1] +
src_ptr[src_stride * 2 + 2] + src_ptr[src_stride * 2 + 3] +
src_ptr[src_stride * 3 + 0] + src_ptr[src_stride * 3 + 1] +
src_ptr[src_stride * 3 + 2] + src_ptr[src_stride * 3 + 3] +
8) >> 4;
src_ptr += 4;
}
}
// 640 output pixels is enough to allow 5120 input pixels with 1/8 scale down.
// Keeping the total buffer under 4096 bytes avoids a stackcheck, saving 4% cpu.
// The following 2 lines cause error on Windows.
//static const int kMaxOutputWidth = 640;
//static const int kMaxRow12 = 1280; //kMaxOutputWidth * 2;
#define kMaxOutputWidth 640
#define kMaxRow12 1280
static void ScaleRowDown8_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
int x;
for (x = 0; x < dst_width; ++x) {
*dst++ = *src_ptr;
src_ptr += 8;
}
}
// Note calling code checks width is less than max and if not
// uses ScaleRowDown8_C instead.
static void ScaleRowDown8Int_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
ALIGN16(uint8 src_row[kMaxRow12 * 2]);
assert(dst_width <= kMaxOutputWidth);
ScaleRowDown4Int_C(src_ptr, src_stride, src_row, dst_width * 2);
ScaleRowDown4Int_C(src_ptr + src_stride * 4, src_stride,
src_row + kMaxOutputWidth,
dst_width * 2);
ScaleRowDown2Int_C(src_row, kMaxOutputWidth, dst, dst_width);
}
static void ScaleRowDown34_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
uint8* dend;
assert((dst_width % 3 == 0) && (dst_width > 0));
dend = dst + dst_width;
do {
dst[0] = src_ptr[0];
dst[1] = src_ptr[1];
dst[2] = src_ptr[3];
dst += 3;
src_ptr += 4;
} while (dst < dend);
}
// Filter rows 0 and 1 together, 3 : 1
static void ScaleRowDown34_0_Int_C(const uint8* src_ptr, int src_stride,
uint8* d, int dst_width) {
uint8* dend;
const uint8* s;
const uint8* t;
assert((dst_width % 3 == 0) && (dst_width > 0));
dend = d + dst_width;
s = src_ptr;
t = src_ptr + src_stride;
do {
uint8 a0 = (s[0] * 3 + s[1] * 1 + 2) >> 2;
uint8 a1 = (s[1] * 1 + s[2] * 1 + 1) >> 1;
uint8 a2 = (s[2] * 1 + s[3] * 3 + 2) >> 2;
uint8 b0 = (t[0] * 3 + t[1] * 1 + 2) >> 2;
uint8 b1 = (t[1] * 1 + t[2] * 1 + 1) >> 1;
uint8 b2 = (t[2] * 1 + t[3] * 3 + 2) >> 2;
d[0] = (a0 * 3 + b0 + 2) >> 2;
d[1] = (a1 * 3 + b1 + 2) >> 2;
d[2] = (a2 * 3 + b2 + 2) >> 2;
d += 3;
s += 4;
t += 4;
} while (d < dend);
}
// Filter rows 1 and 2 together, 1 : 1
static void ScaleRowDown34_1_Int_C(const uint8* src_ptr, int src_stride,
uint8* d, int dst_width) {
uint8* dend;
const uint8* s;
const uint8* t;
assert((dst_width % 3 == 0) && (dst_width > 0));
dend = d + dst_width;
s = src_ptr;
t = src_ptr + src_stride;
do {
uint8 a0 = (s[0] * 3 + s[1] * 1 + 2) >> 2;
uint8 a1 = (s[1] * 1 + s[2] * 1 + 1) >> 1;
uint8 a2 = (s[2] * 1 + s[3] * 3 + 2) >> 2;
uint8 b0 = (t[0] * 3 + t[1] * 1 + 2) >> 2;
uint8 b1 = (t[1] * 1 + t[2] * 1 + 1) >> 1;
uint8 b2 = (t[2] * 1 + t[3] * 3 + 2) >> 2;
d[0] = (a0 + b0 + 1) >> 1;
d[1] = (a1 + b1 + 1) >> 1;
d[2] = (a2 + b2 + 1) >> 1;
d += 3;
s += 4;
t += 4;
} while (d < dend);
}
#if defined(HAS_SCALEFILTERROWS_SSE2)
// Filter row to 3/4
static void ScaleFilterCols34_C(uint8* dst_ptr, const uint8* src_ptr,
int dst_width) {
uint8* dend;
const uint8* s;
assert((dst_width % 3 == 0) && (dst_width > 0));
dend = dst_ptr + dst_width;
s = src_ptr;
do {
dst_ptr[0] = (s[0] * 3 + s[1] * 1 + 2) >> 2;
dst_ptr[1] = (s[1] * 1 + s[2] * 1 + 1) >> 1;
dst_ptr[2] = (s[2] * 1 + s[3] * 3 + 2) >> 2;
dst_ptr += 3;
s += 4;
} while (dst_ptr < dend);
}
#endif
static void ScaleFilterCols_C(uint8* dst_ptr, const uint8* src_ptr,
int dst_width, int dx) {
int x = 0;
int j;
for (j = 0; j < dst_width; ++j) {
int xi = x >> 16;
int xf1 = x & 0xffff;
int xf0 = 65536 - xf1;
*dst_ptr++ = (src_ptr[xi] * xf0 + src_ptr[xi + 1] * xf1) >> 16;
x += dx;
}
}
//Not work on Windows
//static const int kMaxInputWidth = 2560;
#define kMaxInputWidth 2560
#if defined(HAS_SCALEFILTERROWS_SSE2)
#define HAS_SCALEROWDOWN34_SSE2
// Filter rows 0 and 1 together, 3 : 1
static void ScaleRowDown34_0_Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
ALIGN16(uint8 row[kMaxInputWidth]);
assert((dst_width % 3 == 0) && (dst_width > 0));
ScaleFilterRows_SSE2(row, src_ptr, src_stride, dst_width * 4 / 3, 256 / 4);
ScaleFilterCols34_C(dst_ptr, row, dst_width);
}
// Filter rows 1 and 2 together, 1 : 1
static void ScaleRowDown34_1_Int_SSE2(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
ALIGN16(uint8 row[kMaxInputWidth]);
assert((dst_width % 3 == 0) && (dst_width > 0));
ScaleFilterRows_SSE2(row, src_ptr, src_stride, dst_width * 4 / 3, 256 / 2);
ScaleFilterCols34_C(dst_ptr, row, dst_width);
}
#endif
static void ScaleRowDown38_C(const uint8* src_ptr, int src_stride,
uint8* dst, int dst_width) {
int x;
assert(dst_width % 3 == 0);
for (x = 0; x < dst_width; x += 3) {
dst[0] = src_ptr[0];
dst[1] = src_ptr[3];
dst[2] = src_ptr[6];
dst += 3;
src_ptr += 8;
}
}
// 8x3 -> 3x1
static void ScaleRowDown38_3_Int_C(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
int i;
assert((dst_width % 3 == 0) && (dst_width > 0));
for (i = 0; i < dst_width; i+=3) {
dst_ptr[0] = (src_ptr[0] + src_ptr[1] + src_ptr[2] +
src_ptr[src_stride + 0] + src_ptr[src_stride + 1] +
src_ptr[src_stride + 2] + src_ptr[src_stride * 2 + 0] +
src_ptr[src_stride * 2 + 1] + src_ptr[src_stride * 2 + 2]) *
(65536 / 9) >> 16;
dst_ptr[1] = (src_ptr[3] + src_ptr[4] + src_ptr[5] +
src_ptr[src_stride + 3] + src_ptr[src_stride + 4] +
src_ptr[src_stride + 5] + src_ptr[src_stride * 2 + 3] +
src_ptr[src_stride * 2 + 4] + src_ptr[src_stride * 2 + 5]) *
(65536 / 9) >> 16;
dst_ptr[2] = (src_ptr[6] + src_ptr[7] +
src_ptr[src_stride + 6] + src_ptr[src_stride + 7] +
src_ptr[src_stride * 2 + 6] + src_ptr[src_stride * 2 + 7]) *
(65536 / 6) >> 16;
src_ptr += 8;
dst_ptr += 3;
}
}
// 8x2 -> 3x1
static void ScaleRowDown38_2_Int_C(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width) {
int i;
assert((dst_width % 3 == 0) && (dst_width > 0));
for (i = 0; i < dst_width; i+=3) {
dst_ptr[0] = (src_ptr[0] + src_ptr[1] + src_ptr[2] +
src_ptr[src_stride + 0] + src_ptr[src_stride + 1] +
src_ptr[src_stride + 2]) * (65536 / 6) >> 16;
dst_ptr[1] = (src_ptr[3] + src_ptr[4] + src_ptr[5] +
src_ptr[src_stride + 3] + src_ptr[src_stride + 4] +
src_ptr[src_stride + 5]) * (65536 / 6) >> 16;
dst_ptr[2] = (src_ptr[6] + src_ptr[7] +
src_ptr[src_stride + 6] + src_ptr[src_stride + 7]) *
(65536 / 4) >> 16;
src_ptr += 8;
dst_ptr += 3;
}
}
// C version 8x2 -> 8x1
static void ScaleFilterRows_C(uint8* dst_ptr,
const uint8* src_ptr, int src_stride,
int dst_width, int source_y_fraction) {
int y1_fraction;
int y0_fraction;
const uint8* src_ptr1;
uint8* end;
assert(dst_width > 0);
y1_fraction = source_y_fraction;
y0_fraction = 256 - y1_fraction;
src_ptr1 = src_ptr + src_stride;
end = dst_ptr + dst_width;
do {
dst_ptr[0] = (src_ptr[0] * y0_fraction + src_ptr1[0] * y1_fraction) >> 8;
dst_ptr[1] = (src_ptr[1] * y0_fraction + src_ptr1[1] * y1_fraction) >> 8;
dst_ptr[2] = (src_ptr[2] * y0_fraction + src_ptr1[2] * y1_fraction) >> 8;
dst_ptr[3] = (src_ptr[3] * y0_fraction + src_ptr1[3] * y1_fraction) >> 8;
dst_ptr[4] = (src_ptr[4] * y0_fraction + src_ptr1[4] * y1_fraction) >> 8;
dst_ptr[5] = (src_ptr[5] * y0_fraction + src_ptr1[5] * y1_fraction) >> 8;
dst_ptr[6] = (src_ptr[6] * y0_fraction + src_ptr1[6] * y1_fraction) >> 8;
dst_ptr[7] = (src_ptr[7] * y0_fraction + src_ptr1[7] * y1_fraction) >> 8;
src_ptr += 8;
src_ptr1 += 8;
dst_ptr += 8;
} while (dst_ptr < end);
dst_ptr[0] = dst_ptr[-1];
}
void ScaleAddRows_C(const uint8* src_ptr, int src_stride,
uint16* dst_ptr, int src_width, int src_height) {
int x,y;
assert(src_width > 0);
assert(src_height > 0);
for (x = 0; x < src_width; ++x) {
const uint8* s = src_ptr + x;
int sum = 0;
for (y = 0; y < src_height; ++y) {
sum += s[0];
s += src_stride;
}
dst_ptr[x] = sum;
}
}
/**
* Scale plane, 1/2
*
* This is an optimized version for scaling down a plane to 1/2 of
* its original size.
*
*/
static void ScalePlaneDown2(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
void (*ScaleRowDown2)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
assert(IS_ALIGNED(src_width, 2));
assert(IS_ALIGNED(src_height, 2));
#if defined(HAS_SCALEROWDOWN2_NEON)
if (TestCpuFlag(kCpuHasNEON) &&
IS_ALIGNED(dst_width, 16)) {
ScaleRowDown2 = filtering ? ScaleRowDown2Int_NEON : ScaleRowDown2_NEON;
} else
#endif
#if defined(HAS_SCALEROWDOWN2_SSE2)
if (TestCpuFlag(kCpuHasSSE2) &&
IS_ALIGNED(dst_width, 16) &&
IS_ALIGNED(src_ptr, 16) && IS_ALIGNED(src_stride, 16) &&
IS_ALIGNED(dst_ptr, 16) && IS_ALIGNED(dst_stride, 16)) {
ScaleRowDown2 = filtering ? ScaleRowDown2Int_SSE2 : ScaleRowDown2_SSE2;
} else
#endif
{
ScaleRowDown2 = filtering ? ScaleRowDown2Int_C : ScaleRowDown2_C;
}
{
int y;
for (y = 0; y < dst_height; ++y) {
ScaleRowDown2(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += (src_stride << 1);
dst_ptr += dst_stride;
}
}
}
/**
* Scale plane, 1/4
*
* This is an optimized version for scaling down a plane to 1/4 of
* its original size.
*/
static void ScalePlaneDown4(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
void (*ScaleRowDown4)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
assert(IS_ALIGNED(src_width, 4));
assert(IS_ALIGNED(src_height, 4));
#if defined(HAS_SCALEROWDOWN4_NEON)
if (TestCpuFlag(kCpuHasNEON) &&
IS_ALIGNED(dst_width, 4)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Int_NEON : ScaleRowDown4_NEON;
} else
#endif
#if defined(HAS_SCALEROWDOWN4_SSE2)
if (TestCpuFlag(kCpuHasSSE2) &&
IS_ALIGNED(dst_width, 8) &&
IS_ALIGNED(src_ptr, 16) && IS_ALIGNED(src_stride, 16) &&
IS_ALIGNED(dst_ptr, 8) && IS_ALIGNED(dst_stride, 8)) {
ScaleRowDown4 = filtering ? ScaleRowDown4Int_SSE2 : ScaleRowDown4_SSE2;
} else
#endif
{
ScaleRowDown4 = filtering ? ScaleRowDown4Int_C : ScaleRowDown4_C;
}
{
int y;
for (y = 0; y < dst_height; ++y) {
ScaleRowDown4(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += (src_stride << 2);
dst_ptr += dst_stride;
}
}
}
/**
* Scale plane, 1/8
*
* This is an optimized version for scaling down a plane to 1/8
* of its original size.
*
*/
static void ScalePlaneDown8(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
void (*ScaleRowDown8)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
assert(IS_ALIGNED(src_width, 8));
assert(IS_ALIGNED(src_height, 8));
#if defined(HAS_SCALEROWDOWN8_SSE2)
if (TestCpuFlag(kCpuHasSSE2) &&
IS_ALIGNED(dst_width, 4) &&
IS_ALIGNED(src_ptr, 16) && IS_ALIGNED(src_stride, 16) &&
IS_ALIGNED(dst_ptr, 4) && IS_ALIGNED(dst_stride, 4)) {
ScaleRowDown8 = filtering ? ScaleRowDown8Int_SSE2 : ScaleRowDown8_SSE2;
} else
#endif
{
ScaleRowDown8 = filtering && (dst_width <= kMaxOutputWidth) ?
ScaleRowDown8Int_C : ScaleRowDown8_C;
}
{
int y;
for (y = 0; y < dst_height; ++y) {
ScaleRowDown8(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += (src_stride << 3);
dst_ptr += dst_stride;
}
}
}
/**
* Scale plane down, 3/4
*
* Provided by Frank Barchard (fbarchard@google.com)
*
*/
static void ScalePlaneDown34(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
void (*ScaleRowDown34_0)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
void (*ScaleRowDown34_1)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
assert(dst_width % 3 == 0);
#if defined(HAS_SCALEROWDOWN34_NEON)
if (TestCpuFlag(kCpuHasNEON) &&
(dst_width % 24 == 0)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_NEON;
ScaleRowDown34_1 = ScaleRowDown34_NEON;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Int_NEON;
ScaleRowDown34_1 = ScaleRowDown34_1_Int_NEON;
}
} else
#endif
#if defined(HAS_SCALEROWDOWN34_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) &&
(dst_width % 24 == 0) &&
IS_ALIGNED(src_ptr, 16) && IS_ALIGNED(src_stride, 16) &&
IS_ALIGNED(dst_ptr, 8) && IS_ALIGNED(dst_stride, 8)) {
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_SSSE3;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Int_SSSE3;
ScaleRowDown34_1 = ScaleRowDown34_1_Int_SSSE3;
}
} else
#endif
#if defined(HAS_SCALEROWDOWN34_SSE2)
if (TestCpuFlag(kCpuHasSSE2) &&
(dst_width % 24 == 0) && IS_ALIGNED(src_stride, 16) &&
IS_ALIGNED(dst_stride, 8) &&
IS_ALIGNED(src_ptr, 16) && IS_ALIGNED(dst_ptr, 8) &&
filtering) {
ScaleRowDown34_0 = ScaleRowDown34_0_Int_SSE2;
ScaleRowDown34_1 = ScaleRowDown34_1_Int_SSE2;
} else
#endif
{
if (!filtering) {
ScaleRowDown34_0 = ScaleRowDown34_C;
ScaleRowDown34_1 = ScaleRowDown34_C;
} else {
ScaleRowDown34_0 = ScaleRowDown34_0_Int_C;
ScaleRowDown34_1 = ScaleRowDown34_1_Int_C;
}
}
{
int src_row = 0;
int y;
for (y = 0; y < dst_height; ++y) {
switch (src_row) {
case 0:
ScaleRowDown34_0(src_ptr, src_stride, dst_ptr, dst_width);
break;
case 1:
ScaleRowDown34_1(src_ptr, src_stride, dst_ptr, dst_width);
break;
case 2:
ScaleRowDown34_0(src_ptr + src_stride, -src_stride,
dst_ptr, dst_width);
break;
}
++src_row;
src_ptr += src_stride;
dst_ptr += dst_stride;
if (src_row >= 3) {
src_ptr += src_stride;
src_row = 0;
}
}
}
}
/**
* Scale plane, 3/8
*
* This is an optimized version for scaling down a plane to 3/8
* of its original size.
*
* Reduces 16x3 to 6x1
*/
static void ScalePlaneDown38(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
void (*ScaleRowDown38_3)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
void (*ScaleRowDown38_2)(const uint8* src_ptr, int src_stride,
uint8* dst_ptr, int dst_width);
assert(dst_width % 3 == 0);
#if defined(HAS_SCALEROWDOWN38_NEON)
if (TestCpuFlag(kCpuHasNEON) &&
(dst_width % 12 == 0)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_NEON;
ScaleRowDown38_2 = ScaleRowDown38_NEON;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Int_NEON;
ScaleRowDown38_2 = ScaleRowDown38_2_Int_NEON;
}
} else
#endif
#if defined(HAS_SCALEROWDOWN38_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) &&
(dst_width % 24 == 0) && IS_ALIGNED(src_stride, 16) &&
IS_ALIGNED(dst_stride, 8) &&
IS_ALIGNED(src_ptr, 16) && IS_ALIGNED(dst_ptr, 8)) {
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_SSSE3;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Int_SSSE3;
ScaleRowDown38_2 = ScaleRowDown38_2_Int_SSSE3;
}
} else
#endif
{
if (!filtering) {
ScaleRowDown38_3 = ScaleRowDown38_C;
ScaleRowDown38_2 = ScaleRowDown38_C;
} else {
ScaleRowDown38_3 = ScaleRowDown38_3_Int_C;
ScaleRowDown38_2 = ScaleRowDown38_2_Int_C;
}
}
{
int src_row = 0;
int y;
for (y = 0; y < dst_height; ++y) {
switch (src_row) {
case 0:
case 1:
ScaleRowDown38_3(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += src_stride * 3;
++src_row;
break;
case 2:
ScaleRowDown38_2(src_ptr, src_stride, dst_ptr, dst_width);
src_ptr += src_stride * 2;
src_row = 0;
break;
}
dst_ptr += dst_stride;
}
}
}
__inline static uint32 SumBox(int iboxwidth, int iboxheight,
int src_stride, const uint8* src_ptr) {
int x, y;
uint32 sum;
assert(iboxwidth > 0);
assert(iboxheight > 0);
sum = 0u;
for (y = 0; y < iboxheight; ++y) {
for (x = 0; x < iboxwidth; ++x) {
sum += src_ptr[x];
}
src_ptr += src_stride;
}
return sum;
}
static void ScalePlaneBoxRow(int dst_width, int boxheight,
int dx, int src_stride,
const uint8* src_ptr, uint8* dst_ptr) {
int x = 0;
int i;
for (i = 0; i < dst_width; ++i) {
int ix = x >> 16;
int boxwidth;
x += dx;
boxwidth = (x >> 16) - ix;
*dst_ptr++ = SumBox(boxwidth, boxheight, src_stride, src_ptr + ix) /
(boxwidth * boxheight);
}
}
__inline static uint32 SumPixels(int iboxwidth, const uint16* src_ptr) {
uint32 sum;
int x;
assert(iboxwidth > 0);
sum = 0u;
for (x = 0; x < iboxwidth; ++x) {
sum += src_ptr[x];
}
return sum;
}
static void ScaleAddCols2_C(int dst_width, int boxheight, int dx,
const uint16* src_ptr, uint8* dst_ptr) {
int scaletbl[2];
int minboxwidth = (dx >> 16);
scaletbl[0] = 65536 / (minboxwidth * boxheight);
scaletbl[1] = 65536 / ((minboxwidth + 1) * boxheight);
{
int *scaleptr = scaletbl - minboxwidth;
int x = 0;
int i;
for (i = 0; i < dst_width; ++i) {
int ix = x >> 16;
int boxwidth;
x += dx;
boxwidth = (x >> 16) - ix;
*dst_ptr++ = SumPixels(boxwidth, src_ptr + ix) * scaleptr[boxwidth] >> 16;
}
}
}
static void ScaleAddCols1_C(int dst_width, int boxheight, int dx,
const uint16* src_ptr, uint8* dst_ptr) {
int boxwidth = (dx >> 16);
int scaleval = 65536 / (boxwidth * boxheight);
int x = 0;
int i;
for (i = 0; i < dst_width; ++i) {
*dst_ptr++ = SumPixels(boxwidth, src_ptr + x) * scaleval >> 16;
x += boxwidth;
}
}
/**
* Scale plane down to any dimensions, with interpolation.
* (boxfilter).
*
* Same method as SimpleScale, which is fixed point, outputting
* one pixel of destination using fixed point (16.16) to step
* through source, sampling a box of pixel with simple
* averaging.
*/
static void ScalePlaneBox(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
int dx, dy;
assert(dst_width > 0);
assert(dst_height > 0);
dy = (src_height << 16) / dst_height;
dx = (src_width << 16) / dst_width;
if (!IS_ALIGNED(src_width, 16) || (src_width > kMaxInputWidth) ||
dst_height * 2 > src_height) {
uint8* dst = dst_ptr;
int dy = (src_height << 16) / dst_height;
int dx = (src_width << 16) / dst_width;
int y = 0;
int j;
for (j = 0; j < dst_height; ++j) {
int iy = y >> 16;
const uint8* const src = src_ptr + iy * src_stride;
int boxheight;
y += dy;
if (y > (src_height << 16)) {
y = (src_height << 16);
}
boxheight = (y >> 16) - iy;
ScalePlaneBoxRow(dst_width, boxheight,
dx, src_stride,
src, dst);
dst += dst_stride;
}
} else {
ALIGN16(uint16 row[kMaxInputWidth]);
void (*ScaleAddRows)(const uint8* src_ptr, int src_stride,
uint16* dst_ptr, int src_width, int src_height);
void (*ScaleAddCols)(int dst_width, int boxheight, int dx,
const uint16* src_ptr, uint8* dst_ptr);
#if defined(HAS_SCALEADDROWS_SSE2)
if (TestCpuFlag(kCpuHasSSE2) &&
IS_ALIGNED(src_stride, 16) && IS_ALIGNED(src_ptr, 16) &&
IS_ALIGNED(src_width, 16)) {
ScaleAddRows = ScaleAddRows_SSE2;
} else
#endif
{
ScaleAddRows = ScaleAddRows_C;
}
if (dx & 0xffff) {
ScaleAddCols = ScaleAddCols2_C;
} else {
ScaleAddCols = ScaleAddCols1_C;
}
{
int y = 0;
int j;
for (j = 0; j < dst_height; ++j) {
int iy = y >> 16;
const uint8* const src = src_ptr + iy * src_stride;
int boxheight;
y += dy;
if (y > (src_height << 16)) {
y = (src_height << 16);
}
boxheight = (y >> 16) - iy;
ScaleAddRows(src, src_stride, row, src_width, boxheight);
ScaleAddCols(dst_width, boxheight, dx, row, dst_ptr);
dst_ptr += dst_stride;
}
}
}
}
/**
* Scale plane to/from any dimensions, with interpolation.
*/
static void ScalePlaneBilinearSimple(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
int i, j;
uint8* dst = dst_ptr;
int dx = (src_width << 16) / dst_width;
int dy = (src_height << 16) / dst_height;
int maxx = ((src_width - 1) << 16) - 1;
int maxy = ((src_height - 1) << 16) - 1;
int y = (dst_height < src_height) ? 32768 :
(src_height << 16) / dst_height - 32768;
for (i = 0; i < dst_height; ++i) {
int cy = (y < 0) ? 0 : y;
int yi = cy >> 16;
int yf = cy & 0xffff;
const uint8* const src = src_ptr + yi * src_stride;
int x = (dst_width < src_width) ? 32768 :
(src_width << 16) / dst_width - 32768;
for (j = 0; j < dst_width; ++j) {
int cx = (x < 0) ? 0 : x;
int xi = cx >> 16;
int xf = cx & 0xffff;
int r0 = (src[xi] * (65536 - xf) + src[xi + 1] * xf) >> 16;
int r1 = (src[xi + src_stride] * (65536 - xf) +
src[xi + src_stride + 1] * xf) >> 16;
*dst++ = (r0 * (65536 - yf) + r1 * yf) >> 16;
x += dx;
if (x > maxx)
x = maxx;
}
dst += dst_stride - dst_width;
y += dy;
if (y > maxy)
y = maxy;
}
}
/**
* Scale plane to/from any dimensions, with bilinear
* interpolation.
*/
static void ScalePlaneBilinear(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
int dy;
int dx;
assert(dst_width > 0);
assert(dst_height > 0);
dy = (src_height << 16) / dst_height;
dx = (src_width << 16) / dst_width;
if (!IS_ALIGNED(src_width, 8) || (src_width > kMaxInputWidth)) {
ScalePlaneBilinearSimple(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src_ptr, dst_ptr);
} else {
ALIGN16(uint8 row[kMaxInputWidth + 1]);
void (*ScaleFilterRows)(uint8* dst_ptr, const uint8* src_ptr,
int src_stride,
int dst_width, int source_y_fraction);
void (*ScaleFilterCols)(uint8* dst_ptr, const uint8* src_ptr,
int dst_width, int dx);
#if defined(HAS_SCALEFILTERROWS_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3) &&
IS_ALIGNED(src_stride, 16) && IS_ALIGNED(src_ptr, 16) &&
IS_ALIGNED(src_width, 16)) {
ScaleFilterRows = ScaleFilterRows_SSSE3;
} else
#endif
#if defined(HAS_SCALEFILTERROWS_SSE2)
if (TestCpuFlag(kCpuHasSSE2) &&
IS_ALIGNED(src_stride, 16) && IS_ALIGNED(src_ptr, 16) &&
IS_ALIGNED(src_width, 16)) {
ScaleFilterRows = ScaleFilterRows_SSE2;
} else
#endif
{
ScaleFilterRows = ScaleFilterRows_C;
}
ScaleFilterCols = ScaleFilterCols_C;
{
int y = 0;
int maxy = ((src_height - 1) << 16) - 1; // max is filter of last 2 rows.
int j;
for (j = 0; j < dst_height; ++j) {
int iy = y >> 16;
int fy = (y >> 8) & 255;
const uint8* const src = src_ptr + iy * src_stride;
ScaleFilterRows(row, src, src_stride, src_width, fy);
ScaleFilterCols(dst_ptr, row, dst_width, dx);
dst_ptr += dst_stride;
y += dy;
if (y > maxy) {
y = maxy;
}
}
}
}
}
/**
* Scale plane to/from any dimensions, without interpolation.
* Fixed point math is used for performance: The upper 16 bits
* of x and dx is the integer part of the source position and
* the lower 16 bits are the fixed decimal part.
*/
static void ScalePlaneSimple(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
uint8* dst = dst_ptr;
int dx = (src_width << 16) / dst_width;
int y;
for (y = 0; y < dst_height; ++y) {
const uint8* const src = src_ptr + (y * src_height / dst_height) *
src_stride;
// TODO(fbarchard): Round X coordinate by setting x=0x8000.
int x = 0;
int i;
for (i = 0; i < dst_width; ++i) {
*dst++ = src[x >> 16];
x += dx;
}
dst += dst_stride - dst_width;
}
}
/**
* Scale plane to/from any dimensions.
*/
static void ScalePlaneAnySize(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
if (!filtering) {
ScalePlaneSimple(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src_ptr, dst_ptr);
} else {
// fall back to non-optimized version
ScalePlaneBilinear(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src_ptr, dst_ptr);
}
}
/**
* Scale plane down, any size
*
* This is an optimized version for scaling down a plane to any size.
* The current implementation is ~10 times faster compared to the
* reference implementation for e.g. XGA->LowResPAL
*
*/
static void ScalePlaneDown(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr,
FilterMode filtering) {
if (!filtering) {
ScalePlaneSimple(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src_ptr, dst_ptr);
} else if (filtering == kFilterBilinear || src_height * 2 > dst_height) {
// between 1/2x and 1x use bilinear
ScalePlaneBilinear(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src_ptr, dst_ptr);
} else {
ScalePlaneBox(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src_ptr, dst_ptr);
}
}
/**
* Copy plane, no scaling
*
* This simply copies the given plane without scaling.
* The current implementation is ~115 times faster
* compared to the reference implementation.
*
*/
static void CopyPlane(int src_width, int src_height,
int dst_width, int dst_height,
int src_stride, int dst_stride,
const uint8* src_ptr, uint8* dst_ptr) {
if (src_stride == src_width && dst_stride == dst_width) {
// All contiguous, so can use REALLY fast path.
memcpy(dst_ptr, src_ptr, src_width * src_height);
} else {
// Not all contiguous; must copy scanlines individually
const uint8* src = src_ptr;
uint8* dst = dst_ptr;
int i;
for (i = 0; i < src_height; ++i) {
memcpy(dst, src, src_width);
dst += dst_stride;
src += src_stride;
}
}
}
static void ScalePlane(const uint8* src, int src_stride,
int src_width, int src_height,
uint8* dst, int dst_stride,
int dst_width, int dst_height,
FilterMode filtering, int use_ref) {
// Use specialized scales to improve performance for common resolutions.
// For example, all the 1/2 scalings will use ScalePlaneDown2()
if (dst_width == src_width && dst_height == src_height) {
// Straight copy.
CopyPlane(src_width, src_height, dst_width, dst_height, src_stride,
dst_stride, src, dst);
} else if (dst_width <= src_width && dst_height <= src_height) {
// Scale down.
if (use_ref) {
// For testing, allow the optimized versions to be disabled.
ScalePlaneDown(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
} else if (4 * dst_width == 3 * src_width &&
4 * dst_height == 3 * src_height) {
// optimized, 3/4
ScalePlaneDown34(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
} else if (2 * dst_width == src_width && 2 * dst_height == src_height) {
// optimized, 1/2
ScalePlaneDown2(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
// 3/8 rounded up for odd sized chroma height.
} else if (8 * dst_width == 3 * src_width &&
dst_height == ((src_height * 3 + 7) / 8)) {
// optimized, 3/8
ScalePlaneDown38(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
} else if (4 * dst_width == src_width && 4 * dst_height == src_height) {
// optimized, 1/4
ScalePlaneDown4(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
} else if (8 * dst_width == src_width && 8 * dst_height == src_height) {
// optimized, 1/8
ScalePlaneDown8(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
} else {
// Arbitrary downsample
ScalePlaneDown(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
}
} else {
// Arbitrary scale up and/or down.
ScalePlaneAnySize(src_width, src_height, dst_width, dst_height,
src_stride, dst_stride, src, dst, filtering);
}
}
/**
* Scale a plane.
*
* This function in turn calls a scaling function
* suitable for handling the desired resolutions.
*
*/
int I420Scale(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
int src_width, int src_height,
uint8* dst_y, int dst_stride_y,
uint8* dst_u, int dst_stride_u,
uint8* dst_v, int dst_stride_v,
int dst_width, int dst_height,
FilterMode filtering) {
if (!src_y || !src_u || !src_v || src_width <= 0 || src_height == 0 ||
!dst_y || !dst_u || !dst_v || dst_width <= 0 || dst_height <= 0) {
return -1;
}
// Negative height means invert the image.
if (src_height < 0) {
int halfheight;
src_height = -src_height;
halfheight = (src_height + 1) >> 1;
src_y = src_y + (src_height - 1) * src_stride_y;
src_u = src_u + (halfheight - 1) * src_stride_u;
src_v = src_v + (halfheight - 1) * src_stride_v;
src_stride_y = -src_stride_y;
src_stride_u = -src_stride_u;
src_stride_v = -src_stride_v;
}
{
int src_halfwidth = (src_width + 1) >> 1;
int src_halfheight = (src_height + 1) >> 1;
int dst_halfwidth = (dst_width + 1) >> 1;
int dst_halfheight = (dst_height + 1) >> 1;
ScalePlane(src_y, src_stride_y, src_width, src_height,
dst_y, dst_stride_y, dst_width, dst_height,
filtering, use_reference_impl_);
ScalePlane(src_u, src_stride_u, src_halfwidth, src_halfheight,
dst_u, dst_stride_u, dst_halfwidth, dst_halfheight,
filtering, use_reference_impl_);
ScalePlane(src_v, src_stride_v, src_halfwidth, src_halfheight,
dst_v, dst_stride_v, dst_halfwidth, dst_halfheight,
filtering, use_reference_impl_);
}
return 0;
}
// Deprecated api
int Scale(const uint8* src_y, const uint8* src_u, const uint8* src_v,
int src_stride_y, int src_stride_u, int src_stride_v,
int src_width, int src_height,
uint8* dst_y, uint8* dst_u, uint8* dst_v,
int dst_stride_y, int dst_stride_u, int dst_stride_v,
int dst_width, int dst_height,
int interpolate) {
if (!src_y || !src_u || !src_v || src_width <= 0 || src_height == 0 ||
!dst_y || !dst_u || !dst_v || dst_width <= 0 || dst_height <= 0) {
return -1;
}
// Negative height means invert the image.
if (src_height < 0) {
int halfheight;
src_height = -src_height;
halfheight = (src_height + 1) >> 1;
src_y = src_y + (src_height - 1) * src_stride_y;
src_u = src_u + (halfheight - 1) * src_stride_u;
src_v = src_v + (halfheight - 1) * src_stride_v;
src_stride_y = -src_stride_y;
src_stride_u = -src_stride_u;
src_stride_v = -src_stride_v;
}
{
int src_halfwidth = (src_width + 1) >> 1;
int src_halfheight = (src_height + 1) >> 1;
int dst_halfwidth = (dst_width + 1) >> 1;
int dst_halfheight = (dst_height + 1) >> 1;
FilterMode filtering = interpolate ? kFilterBox : kFilterNone;
ScalePlane(src_y, src_stride_y, src_width, src_height,
dst_y, dst_stride_y, dst_width, dst_height,
filtering, use_reference_impl_);
ScalePlane(src_u, src_stride_u, src_halfwidth, src_halfheight,
dst_u, dst_stride_u, dst_halfwidth, dst_halfheight,
filtering, use_reference_impl_);
ScalePlane(src_v, src_stride_v, src_halfwidth, src_halfheight,
dst_v, dst_stride_v, dst_halfwidth, dst_halfheight,
filtering, use_reference_impl_);
}
return 0;
}
// Deprecated api
int ScaleOffset(const uint8* src, int src_width, int src_height,
uint8* dst, int dst_width, int dst_height, int dst_yoffset,
int interpolate) {
if (!src || src_width <= 0 || src_height <= 0 ||
!dst || dst_width <= 0 || dst_height <= 0 || dst_yoffset < 0 ||
dst_yoffset >= dst_height) {
return -1;
}
dst_yoffset = dst_yoffset & ~1; // chroma requires offset to multiple of 2.
{
int src_halfwidth = (src_width + 1) >> 1;
int src_halfheight = (src_height + 1) >> 1;
int dst_halfwidth = (dst_width + 1) >> 1;
int dst_halfheight = (dst_height + 1) >> 1;
int aheight = dst_height - dst_yoffset * 2; // actual output height
const uint8* const src_y = src;
const uint8* const src_u = src + src_width * src_height;
const uint8* const src_v = src + src_width * src_height +
src_halfwidth * src_halfheight;
uint8* dst_y = dst + dst_yoffset * dst_width;
uint8* dst_u = dst + dst_width * dst_height +
(dst_yoffset >> 1) * dst_halfwidth;
uint8* dst_v = dst + dst_width * dst_height + dst_halfwidth * dst_halfheight +
(dst_yoffset >> 1) * dst_halfwidth;
return Scale(src_y, src_u, src_v, src_width, src_halfwidth, src_halfwidth,
src_width, src_height, dst_y, dst_u, dst_v, dst_width,
dst_halfwidth, dst_halfwidth, dst_width, aheight, interpolate);
}
}
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
| 36.083398 | 94 | 0.439109 | [
"object"
] |
3c33a1127042aded59780d0ce5650089867e06b4 | 11,719 | c | C | bsp/stm32/stm32f103-epaper-dual75/packages/at_device-v2.0.3/class/rw007/at_device_rw007.c | faithsws/rt-thread | 703eada54fd78682b22977e3a6e74ef169706b2c | [
"Apache-2.0"
] | null | null | null | bsp/stm32/stm32f103-epaper-dual75/packages/at_device-v2.0.3/class/rw007/at_device_rw007.c | faithsws/rt-thread | 703eada54fd78682b22977e3a6e74ef169706b2c | [
"Apache-2.0"
] | null | null | null | bsp/stm32/stm32f103-epaper-dual75/packages/at_device-v2.0.3/class/rw007/at_device_rw007.c | faithsws/rt-thread | 703eada54fd78682b22977e3a6e74ef169706b2c | [
"Apache-2.0"
] | null | null | null | /*
* File : at_socket_rw007.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Change Logs:
* Date Author Notes
* 2018-06-20 chenyong first version
* 2019-05-12 chenyong multi AT socket client support
*/
#include <stdio.h>
#include <string.h>
#include <at_device_rw007.h>
#define LOG_TAG "at.dev.rw007"
#include <at_log.h>
#ifdef AT_DEVICE_USING_RW007
#define RW007_WAIT_CONNECT_TIME 5000
#define RW007_THREAD_STACK_SIZE 2048
#define RW007_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX / 2)
/* ============================= rw007 network interface operations ============================= */
static struct netdev *rw007_netdev_add(const char *netdev_name)
{
#define ETHERNET_MTU 1500
#define HWADDR_LEN 6
struct netdev *netdev = RT_NULL;
RT_ASSERT(netdev_name);
netdev = (struct netdev *)rt_calloc(1, sizeof(struct netdev));
if (netdev == RT_NULL)
{
return RT_NULL;
}
/* TODO: improve netdev adaptation */
netdev->mtu = ETHERNET_MTU;
netdev->hwaddr_len = HWADDR_LEN;
netdev->ops = RT_NULL;
#ifdef SAL_USING_AT
extern int sal_at_netdev_set_pf_info(struct netdev *netdev);
/* set the network interface socket/netdb operations */
sal_at_netdev_set_pf_info(netdev);
#endif
netdev_register(netdev, netdev_name, RT_NULL);
/*TODO: improve netdev adaptation */
netdev_low_level_set_status(netdev, RT_TRUE);
netdev_low_level_set_link_status(netdev, RT_TRUE);
netdev_low_level_set_dhcp_status(netdev, RT_TRUE);
netdev->flags |= NETDEV_FLAG_INTERNET_UP;
return netdev;
}
/* ============================= rw007 device operations ============================= */
#define AT_SEND_CMD(client, resp, cmd) \
do { \
(resp) = at_resp_set_info((resp), 256, 0, 5 * RT_TICK_PER_SECOND); \
if (at_obj_exec_cmd((client), (resp), (cmd)) < 0) \
{ \
result = -RT_ERROR; \
goto __exit; \
} \
} while(0) \
static void rw007_init_thread_entry(void *parameter)
{
#define INIT_RETRY 5
struct at_device *device = (struct at_device *) parameter;
struct at_device_rw007 *rw007 = (struct at_device_rw007 *) device->user_data;
struct at_client *client = device->client;
at_response_t resp = RT_NULL;
rt_err_t result = RT_EOK;
rt_size_t i = 0, retry_num = INIT_RETRY;
/* wait rw007 device startup finish */
if (at_client_obj_wait_connect(client, RW007_WAIT_CONNECT_TIME))
{
return;
}
resp = at_create_resp(128, 0, 5 * RT_TICK_PER_SECOND);
if (resp == RT_NULL)
{
LOG_E("no memory for resp create.");
return;
}
while (retry_num--)
{
/* reset module */
AT_SEND_CMD(client, resp, "AT+RST");
/* reset waiting delay */
rt_thread_mdelay(1000);
/* disable echo */
AT_SEND_CMD(client, resp, "ATE0");
/* set current mode to Wi-Fi station */
AT_SEND_CMD(client, resp, "AT+CWMODE=1");
/* get module version */
AT_SEND_CMD(client, resp, "AT+GMR");
/* show module version */
for (i = 0; i < resp->line_counts - 1; i++)
{
LOG_D("%s", at_resp_get_line(resp, i + 1));
}
/* connect to WiFi AP */
if (at_obj_exec_cmd(client, at_resp_set_info(resp, 128, 0, 20 * RT_TICK_PER_SECOND),
"AT+CWJAP=\"%s\",\"%s\"", rw007->wifi_ssid, rw007->wifi_password) != RT_EOK)
{
LOG_E("%s device wifi connect failed, check ssid(%s) and password(%s).",
device->name, rw007->wifi_ssid, rw007->wifi_password);
result = -RT_ERROR;
goto __exit;
}
AT_SEND_CMD(client, resp, "AT+CIPMUX=1");
/* initialize successfully */
result = RT_EOK;
break;
__exit:
if (result != RT_EOK)
{
rt_thread_mdelay(1000);
LOG_I("%s device initialize retry...", device->name);
}
}
if (resp)
{
at_delete_resp(resp);
}
if (result != RT_EOK)
{
netdev_low_level_set_status(device->netdev, RT_FALSE);
LOG_E("%s device network initialize failed(%d).", device->name, result);
}
else
{
netdev_low_level_set_status(device->netdev, RT_TRUE);
LOG_I("%s device network initialize success.", device->name);
}
}
int rw007_net_init(struct at_device *device)
{
#ifdef AT_DEVICE_RW007_INIT_ASYN
rt_thread_t tid;
tid = rt_thread_create("rw007_net", rw007_init_thread_entry,
(void *)device, RW007_THREAD_STACK_SIZE, RW007_THREAD_PRIORITY, 20);
if (tid)
{
rt_thread_startup(tid);
}
else
{
LOG_E("create %s device initialization thread failed.", device->name);
return -RT_ERROR;
}
#else
rw007_init_thread_entry(device);
#endif /* AT_DEVICE_RW007_INIT_ASYN */
return RT_EOK;
}
static void urc_busy_p_func(struct at_client *client, const char *data, rt_size_t size)
{
LOG_D("system is processing a commands...");
}
static void urc_busy_s_func(struct at_client *client, const char *data, rt_size_t size)
{
LOG_D("system is sending data...");
}
static void urc_func(struct at_client *client, const char *data, rt_size_t size)
{
struct at_device *device = RT_NULL;
char *client_name = client->device->parent.name;
RT_ASSERT(client && data && size);
device = at_device_get_by_name(AT_DEVICE_NAMETYPE_CLIENT, client_name);
if (device == RT_NULL)
{
LOG_E("get device(%s) failed.", client_name);
return;
}
if (rt_strstr(data, "WIFI CONNECTED"))
{
LOG_I("%s device wifi is connected.", device->name);
}
else if (rt_strstr(data, "WIFI DISCONNECT"))
{
LOG_I("%s device wifi is disconnect.", device->name);
}
}
static struct at_urc urc_table[] = {
{"busy p", "\r\n", urc_busy_p_func},
{"busy s", "\r\n", urc_busy_s_func},
{"WIFI CONNECTED", "\r\n", urc_func},
{"WIFI DISCONNECT", "\r\n", urc_func},
};
static int rw007_init(struct at_device *device)
{
struct at_device_rw007 *rw007 = (struct at_device_rw007 *) device->user_data;
/* initialize AT client */
at_client_init(rw007->client_name, rw007->recv_line_num);
device->client = at_client_get(rw007->client_name);
if (device->client == RT_NULL)
{
LOG_E("get AT client(%s) failed.", rw007->client_name);
return -RT_ERROR;
}
/* register URC data execution function */
at_obj_set_urc_table(device->client, urc_table, sizeof(urc_table) / sizeof(urc_table[0]));
#ifdef AT_USING_SOCKET
rw007_socket_init(device);
#endif
/* add rw007 device to the netdev list */
device->netdev = rw007_netdev_add(rw007->device_name);
if (device->netdev == RT_NULL)
{
LOG_E("get netdev(%s) failed.", rw007->device_name);
return -RT_ERROR;
}
/* initialize rw007 device network */
return rw007_net_init(device);
}
static int rw007_deinit(struct at_device *device)
{
// TODO add netdev operation
device->is_init = RT_FALSE;
return RT_EOK;
}
/* reset eap8266 device and initialize device network again */
static int rw007_reset(struct at_device *device)
{
int result = RT_EOK;
struct at_client *client = device->client;
/* send "AT+RST" commonds to rw007 device */
result = at_obj_exec_cmd(client, RT_NULL, "AT+RST");
rt_thread_delay(1000);
/* waiting 10 seconds for rw007 device reset */
device->is_init = RT_FALSE;
if (at_client_obj_wait_connect(client, RW007_WAIT_CONNECT_TIME))
{
return -RT_ETIMEOUT;
}
/* initialize rw007 device network */
rw007_net_init(device);
device->is_init = RT_TRUE;
return result;
}
/* change eap8266 wifi ssid and password information */
static int rw007_wifi_info_set(struct at_device *device, struct at_device_ssid_pwd *info)
{
int result = RT_EOK;
struct at_response *resp = RT_NULL;
if (info->ssid == RT_NULL || info->password == RT_NULL)
{
LOG_E("input wifi ssid(%s) and password(%s) error.", info->ssid, info->password);
return -RT_ERROR;
}
resp = at_create_resp(128, 0, 20 * RT_TICK_PER_SECOND);
if (resp == RT_NULL)
{
LOG_E("no memory for resp create.");
return -RT_ENOMEM;
}
/* connect to input wifi ap */
if (at_obj_exec_cmd(device->client, resp, "AT+CWJAP=\"%s\",\"%s\"", info->ssid, info->password) != RT_EOK)
{
LOG_E("%s device wifi connect failed, check ssid(%s) and password(%s).",
device->name, info->ssid, info->password);
result = -RT_ERROR;
}
if (resp)
{
at_delete_resp(resp);
}
return result;
}
static int rw007_control(struct at_device *device, int cmd, void *arg)
{
int result = -RT_ERROR;
RT_ASSERT(device);
switch (cmd)
{
case AT_DEVICE_CTRL_POWER_ON:
case AT_DEVICE_CTRL_POWER_OFF:
case AT_DEVICE_CTRL_LOW_POWER:
case AT_DEVICE_CTRL_SLEEP:
case AT_DEVICE_CTRL_WAKEUP:
case AT_DEVICE_CTRL_NET_CONN:
case AT_DEVICE_CTRL_NET_DISCONN:
case AT_DEVICE_CTRL_GET_SIGNAL:
case AT_DEVICE_CTRL_GET_GPS:
case AT_DEVICE_CTRL_GET_VER:
LOG_W("not support the control command(%d).", cmd);
break;
case AT_DEVICE_CTRL_RESET:
result = rw007_reset(device);
break;
case AT_DEVICE_CTRL_SET_WIFI_INFO:
result = rw007_wifi_info_set(device, (struct at_device_ssid_pwd *) arg);
break;
default:
LOG_E("input error control command(%d).", cmd);
break;
}
return result;
}
const struct at_device_ops rw007_device_ops =
{
rw007_init,
rw007_deinit,
rw007_control,
};
static int rw007_device_class_register(void)
{
struct at_device_class *class = RT_NULL;
class = (struct at_device_class *) rt_calloc(1, sizeof(struct at_device_class));
if (class == RT_NULL)
{
LOG_E("no memory for device class create.");
return -RT_ENOMEM;
}
/* fill rw007 device class object */
#ifdef AT_USING_SOCKET
rw007_socket_class_register(class);
#endif
class->device_ops = &rw007_device_ops;
return at_device_class_register(class, AT_DEVICE_CLASS_RW007);
}
INIT_DEVICE_EXPORT(rw007_device_class_register);
#endif /* AT_DEVICE_USING_RW007 */
| 29.370927 | 110 | 0.611912 | [
"object"
] |
3c360c64a2713e1f0d9341710f7030ef5bd9e1d7 | 5,167 | h | C | bins/broker/storage/MessageStorage.h | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | null | null | null | bins/broker/storage/MessageStorage.h | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | null | null | null | bins/broker/storage/MessageStorage.h | asvgit/broker | 766b66015b842be4d1106ff6c6145ad489c03c59 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014-present IVK JSC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BROKER_STORAGE_H
#define BROKER_STORAGE_H
#include <Poco/RWLock.h>
#include <memory>
#include <string>
#include "FixedSizeUnorderedMap.h"
#include "DBMSSession.h"
#include "MessageDataContainer.h"
#include "MoveableRWLock.h"
namespace upmq {
namespace broker {
class Session;
class Destination;
class Consumer;
namespace consumer {
struct Msg;
}
class Storage {
public:
using NonPersistentMessagesListType = FSUnorderedMap<std::string, std::shared_ptr<MessageDataContainer>>;
/// @brief TransactSessionsListType - set<transact_session_id>
using TransactSessionsListType = std::unordered_set<std::string>;
private:
std::string _messageTableID;
std::string _propertyTableID;
const Destination *_parent;
NonPersistentMessagesListType _nonPersistent;
std::string _extParentID;
TransactSessionsListType _txSessions;
mutable upmq::MRWLock _txSessionsLock;
private:
std::string saveTableName(const upmq::broker::Session &session) const;
std::shared_ptr<MessageDataContainer> makeMessage(storage::DBMSSession &dbSession,
const consumer::Msg &msgInfo,
const Consumer &consumer,
bool useFileLink);
void fillProperties(storage::DBMSSession &dbSession, Proto::Message &message);
int deleteMessageHeader(storage::DBMSSession &dbSession, const std::string &messageID);
void deleteMessageProperties(storage::DBMSSession &dbSession, const std::string &messageID);
int getSubscribersCount(storage::DBMSSession &dbSession, const std::string &messageID);
void updateSubscribersCount(storage::DBMSSession &dbSession, const std::string &messageID);
void deleteMessageInfoFromJournal(storage::DBMSSession &dbSession, const std::string &messageID);
void deleteMessageDataIfExists(const std::string &messageID, int persistent);
void saveMessageHeader(const upmq::broker::Session &session, const MessageDataContainer &sMessage);
void saveMessageProperties(const upmq::broker::Session &session, const Message &message);
bool checkTTLIsOut(const std::string &stringMessageTime, Poco::Int64 ttl);
public:
explicit Storage(const std::string &messageTableID, size_t nonPersistentSize);
Storage(Storage &&) = default;
Storage &operator=(Storage &&) = default;
virtual ~Storage();
void setParent(const broker::Destination *parent);
const std::string &messageTableID() const;
const std::string &propertyTableID() const;
void save(const upmq::broker::Session &session, const MessageDataContainer &sMessage);
std::shared_ptr<MessageDataContainer> get(const Consumer &consumer, bool useFileLink);
void removeGroupMessage(const std::string &groupID, const upmq::broker::Session &session);
void removeMessagesBySession(const upmq::broker::Session &session);
void resetMessagesBySession(const upmq::broker::Session &session);
void removeMessage(const std::string &messageID, storage::DBMSSession &extDBSession);
const std::string &uri() const;
void begin(const upmq::broker::Session &session, const std::string &extParentId = "");
void commit(const upmq::broker::Session &session);
void abort(const upmq::broker::Session &session);
std::string generateSQLMainTable(const std::string &tableName) const;
std::vector<std::string> generateSQLMainTableIndexes(const std::string &tableName) const;
std::string generateSQLProperties() const;
std::vector<MessageInfo> getMessagesBelow(const upmq::broker::Session &session, const std::string &messageID) const;
void setMessageToWasSent(const std::string &messageID, const Consumer &consumer);
void setMessagesToWasSent(storage::DBMSSession &dbSession, const Consumer &consumer);
void setMessageToDelivered(const upmq::broker::Session &session, const std::string &messageID);
void setMessagesToNotSent(const Consumer &consumer);
void setMessageToLastInGroup(const upmq::broker::Session &session, const std::string &messageID);
void dropTXTable(storage::DBMSSession &dbSession, const std::string &mainTXTable) const;
void copyTo(Storage &storage, const Consumer &consumer);
void resetNonPersistent(const NonPersistentMessagesListType &nonPersistentMessagesList);
int64_t size();
void dropTables();
bool hasTransaction(const upmq::broker::Session &session) const;
message::GroupStatus checkIsGroupClosed(const MessageDataContainer &sMessage, const upmq::broker::Session &session) const;
};
} // namespace broker
} // namespace upmq
#endif // BROKER_STORAGE_H
| 47.40367 | 124 | 0.756145 | [
"vector"
] |
3c3e4608a967bfc5adf64ac116eae707e88f2fad | 5,687 | h | C | external/blend2d/src/blend2d/blthreadpool_p.h | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 21 | 2016-04-05T06:08:41.000Z | 2022-03-28T10:20:22.000Z | external/blend2d/src/blend2d/blthreadpool_p.h | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | null | null | null | external/blend2d/src/blend2d/blthreadpool_p.h | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 2 | 2019-07-16T00:37:21.000Z | 2021-11-10T06:14:09.000Z | // [Blend2D]
// 2D Vector Graphics Powered by a JIT Compiler.
//
// [License]
// Zlib - See LICENSE.md file in the package.
#ifndef BLEND2D_BLTHREADPOOL_P_H
#define BLEND2D_BLTHREADPOOL_P_H
#include "./blapi-internal_p.h"
#include "./blthreading_p.h"
#include "./blbitarray_p.h"
//! \cond INTERNAL
//! \addtogroup blend2d_internal
//! \{
// ============================================================================
// [Forward Declarations]
// ============================================================================
struct BLThreadPool;
struct BLThreadPoolVirt;
// ============================================================================
// [Constants]
// ============================================================================
enum BLThreadPoolAcquireFlags : uint32_t {
//! Try to acquire the number of threads specified, if it's not possible then
//! don't acquire any threads and return.
//!
//! \note This flag has precedence over `BL_THREAD_POOL_ACQUIRE_FLAG_FORCE_ONE`
//! and `BL_THREAD_POOL_ACQUIRE_FLAG_FORCE_ALL`, so it doesn't matter if these
//! flags were specified or not when `BL_THREAD_POOL_ACQUIRE_FLAG_TRY` is used.
BL_THREAD_POOL_ACQUIRE_FLAG_TRY = 0x00000001u,
//! Force to acquire / create at least one thread.
BL_THREAD_POOL_ACQUIRE_FLAG_FORCE_ONE = 0x00000002u,
//! Force to acquire / create extra threads if the thread-pool is full, these
//! threads will be then destroyed upon release. This mode ensures that the
//! user gets the number of threads asked for, but with a possible overhead of
//! creating additional threads when necessary.
BL_THREAD_POOL_ACQUIRE_FLAG_FORCE_ALL = 0x00000004u
};
// ============================================================================
// [BLThreadPool]
// ============================================================================
struct BLThreadPoolVirt {
BLThreadPool* (BL_CDECL* addRef)(BLThreadPool* self) BL_NOEXCEPT;
BLResult (BL_CDECL* release)(BLThreadPool* self) BL_NOEXCEPT;
uint32_t (BL_CDECL* maxThreadCount)(const BLThreadPool* self) BL_NOEXCEPT;
uint32_t (BL_CDECL* pooledThreadCount)(const BLThreadPool* self) BL_NOEXCEPT;
BLResult (BL_CDECL* setThreadAttributes)(BLThreadPool* self, const BLThreadAttributes* attributes) BL_NOEXCEPT;
uint32_t (BL_CDECL* cleanup)(BLThreadPool* self) BL_NOEXCEPT;
uint32_t (BL_CDECL* acquireThreads)(BLThreadPool* self, BLThread** threads, uint32_t n, uint32_t flags) BL_NOEXCEPT;
void (BL_CDECL* releaseThreads)(BLThreadPool* self, BLThread** threads, uint32_t n) BL_NOEXCEPT;
};
struct BLThreadPool {
const BLThreadPoolVirt* virt;
// --------------------------------------------------------------------------
#ifdef __cplusplus
BL_INLINE BLThreadPool* addRef() noexcept { return virt->addRef(this); }
BL_INLINE BLResult release() noexcept { return virt->release(this); }
//! Returns the number of threads that are pooled at the moment.
//!
//! \note This is mostly informative as it's not guaranteed that successive
//! calls to `pooledThreadCount()` would return the same result as some
//! threads may be acquired during the request by another thread.
//!
//! \threadsafe
BL_INLINE uint32_t pooledThreadCount() const noexcept {
return virt->pooledThreadCount(this);
}
//! Returns the maximum number of threads that would be allocated by the
//! thread-pool.
//!
//! \threadsafe
BL_INLINE uint32_t maxThreadCount() const noexcept {
return virt->maxThreadCount(this);
}
//! Sets attributes that will affect only new threads created by thread-pool.
//! It's only recommended to set attributes immediately after the thread-pool
//! has been created as having threads with various attributes in a single
//! thread-pool could lead into unpredictable behavior and hard to find bugs.
BL_INLINE BLResult setThreadAttributes(const BLThreadAttributes& attributes) noexcept {
return virt->setThreadAttributes(this, &attributes);
}
//! Cleans up all pooled threads at the moment.
//!
//! Cleaning up means to release all pooled threads to the operating system
//! to free all associated resources with such threads. This operation should
//! not be called often, it's ideal to call it when application was minimized,
//! for example, or when the application knows that it completed an expensive
//! task, etc...
BL_INLINE uint32_t cleanup() noexcept {
return virt->cleanup(this);
}
//! Acquire `n` threads and store `BLThread*` to the given `threads` array.
//!
//! If `exact` is `true` then only the exact number of threads will be acquired,
//! and if it's not possible then no threads will be acquired. If `exact` is
//! `false` then the number of acquired threads can be less than `n` in case
//! that acquiring `n` threads is not possible due to reaching `maxThreadCount()`.
BL_INLINE uint32_t acquireThreads(BLThread** threads, uint32_t n, uint32_t flags = 0) noexcept {
return virt->acquireThreads(this, threads, n, flags);
}
//! Release `n` threads that were previously acquired by `acquireThreads()`.
BL_INLINE void releaseThreads(BLThread** threads, uint32_t n) noexcept {
return virt->releaseThreads(this, threads, n);
}
#endif
// --------------------------------------------------------------------------
};
// ============================================================================
// [BLInternalThreadPool]
// ============================================================================
BL_HIDDEN BLThreadPool* blThreadPoolGlobal() noexcept;
BL_HIDDEN BLThreadPool* blThreadPoolCreate() noexcept;
//! \}
//! \endcond
#endif // BLEND2D_BLTHREADPOOL_P_H
| 41.210145 | 118 | 0.637243 | [
"vector"
] |
3c4541fd76f98aa1f58adaad1112e8304feae902 | 9,887 | h | C | src/components/autofill/browser/form_structure.h | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | components/autofill/browser/form_structure.h | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/browser/form_structure.h | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.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 COMPONENTS_AUTOFILL_BROWSER_FORM_STRUCTURE_H_
#define COMPONENTS_AUTOFILL_BROWSER_FORM_STRUCTURE_H_
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "components/autofill/browser/autofill_field.h"
#include "components/autofill/browser/autofill_type.h"
#include "components/autofill/browser/field_types.h"
#include "components/autofill/common/web_element_descriptor.h"
#include "googleurl/src/gurl.h"
enum RequestMethod {
GET,
POST
};
enum UploadRequired {
UPLOAD_NOT_REQUIRED,
UPLOAD_REQUIRED,
USE_UPLOAD_RATES
};
namespace base {
class TimeTicks;
}
namespace buzz {
class XmlElement;
}
namespace autofill {
class AutofillMetrics;
struct AutocheckoutPageMetaData;
struct FormData;
struct FormDataPredictions;
// FormStructure stores a single HTML form together with the values entered
// in the fields along with additional information needed by Autofill.
class FormStructure {
public:
FormStructure(const FormData& form,
const std::string& autocheckout_url_prefix);
virtual ~FormStructure();
// Runs several heuristics against the form fields to determine their possible
// types.
void DetermineHeuristicTypes(const AutofillMetrics& metric_logger);
// Encodes the XML upload request from this FormStructure.
bool EncodeUploadRequest(const FieldTypeSet& available_field_types,
bool form_was_autofilled,
std::string* encoded_xml) const;
// Encodes a XML block contains autofill field type from this FormStructure.
// This XML will be written VLOG only, never be sent to server. It will
// help make FieldAssignments and feed back to autofill server as
// experiment data.
bool EncodeFieldAssignments(const FieldTypeSet& available_field_types,
std::string* encoded_xml) const;
// Encodes the XML query request for the set of forms.
// All fields are returned in one XML. For example, there are three forms,
// with 2, 4, and 3 fields. The returned XML would have type info for 9
// fields, first two of which would be for the first form, next 4 for the
// second, and the rest is for the third.
static bool EncodeQueryRequest(const std::vector<FormStructure*>& forms,
std::vector<std::string>* encoded_signatures,
std::string* encoded_xml);
// Parses the field types from the server query response. |forms| must be the
// same as the one passed to EncodeQueryRequest when constructing the query.
static void ParseQueryResponse(
const std::string& response_xml,
const std::vector<FormStructure*>& forms,
autofill::AutocheckoutPageMetaData* page_meta_data,
const AutofillMetrics& metric_logger);
// Fills |forms| with the details from the given |form_structures| and their
// fields' predicted types.
static void GetFieldTypePredictions(
const std::vector<FormStructure*>& form_structures,
std::vector<FormDataPredictions>* forms);
// The unique signature for this form, composed of the target url domain,
// the form name, and the form field names in a 64-bit hash.
std::string FormSignature() const;
// Runs a quick heuristic to rule out forms that are obviously not
// auto-fillable, like google/yahoo/msn search, etc. The requirement that the
// form's method be POST is only applied if |require_method_post| is true.
bool IsAutofillable(bool require_method_post) const;
// Resets |autofill_count_| and counts the number of auto-fillable fields.
// This is used when we receive server data for form fields. At that time,
// we may have more known fields than just the number of fields we matched
// heuristically.
void UpdateAutofillCount();
// Returns true if this form matches the structural requirements for Autofill.
// The requirement that the form's method be POST is only applied if
// |require_method_post| is true.
bool ShouldBeParsed(bool require_method_post) const;
// Returns true if we should query the crowdsourcing server to determine this
// form's field types. If the form includes author-specified types, this will
// return false.
bool ShouldBeCrowdsourced() const;
// Sets the field types and experiment id to be those set for |cached_form|.
void UpdateFromCache(const FormStructure& cached_form);
// Logs quality metrics for |this|, which should be a user-submitted form.
// This method should only be called after the possible field types have been
// set for each field. |interaction_time| should be a timestamp corresponding
// to the user's first interaction with the form. |submission_time| should be
// a timestamp corresponding to the form's submission.
void LogQualityMetrics(const AutofillMetrics& metric_logger,
const base::TimeTicks& load_time,
const base::TimeTicks& interaction_time,
const base::TimeTicks& submission_time) const;
// Classifies each field in |fields_| based upon its |autocomplete| attribute,
// if the attribute is available. The association is stored into the field's
// |heuristic_type|.
// Fills |found_types| with |true| if the attribute is available and neither
// empty nor set to the special values "on" or "off" for at least one field.
// Fills |found_sections| with |true| if the attribute specifies a section for
// at least one field.
void ParseFieldTypesFromAutocompleteAttributes(bool* found_types,
bool* found_sections);
const AutofillField* field(size_t index) const;
AutofillField* field(size_t index);
size_t field_count() const;
// Returns the number of fields that are able to be autofilled.
size_t autofill_count() const { return autofill_count_; }
// Used for iterating over the fields.
std::vector<AutofillField*>::const_iterator begin() const {
return fields_.begin();
}
std::vector<AutofillField*>::const_iterator end() const {
return fields_.end();
}
const GURL& source_url() const { return source_url_; }
UploadRequired upload_required() const { return upload_required_; }
virtual std::string server_experiment_id() const;
// Returns a FormData containing the data this form structure knows about.
// |user_submitted| is currently always false.
FormData ToFormData() const;
bool filled_by_autocheckout() const { return filled_by_autocheckout_; }
void set_filled_by_autocheckout(bool filled_by_autocheckout) {
filled_by_autocheckout_ = filled_by_autocheckout;
}
bool operator==(const FormData& form) const;
bool operator!=(const FormData& form) const;
private:
friend class FormStructureTest;
FRIEND_TEST_ALL_PREFIXES(AutofillDownloadTest, QueryAndUploadTest);
// 64-bit hash of the string - used in FormSignature and unit-tests.
static std::string Hash64Bit(const std::string& str);
enum EncodeRequestType {
QUERY,
UPLOAD,
FIELD_ASSIGNMENTS,
};
// Adds form info to |encompassing_xml_element|. |request_type| indicates if
// it is a query or upload.
bool EncodeFormRequest(EncodeRequestType request_type,
buzz::XmlElement* encompassing_xml_element) const;
// Classifies each field in |fields_| into a logical section.
// Sections are identified by the heuristic that a logical section should not
// include multiple fields of the same autofill type (with some exceptions, as
// described in the implementation). Sections are furthermore distinguished
// as either credit card or non-credit card sections.
// If |has_author_specified_sections| is true, only the second pass --
// distinguishing credit card sections from non-credit card ones -- is made.
void IdentifySections(bool has_author_specified_sections);
bool IsAutocheckoutEnabled() const;
// Returns the minimal number of fillable fields required to start autofill.
size_t RequiredFillableFields() const;
size_t active_field_count() const;
// The name of the form.
base::string16 form_name_;
// The source URL.
GURL source_url_;
// The target URL.
GURL target_url_;
// The number of fields able to be auto-filled.
size_t autofill_count_;
// A vector of all the input fields in the form.
ScopedVector<AutofillField> fields_;
// The number of fields counted towards form signature and request to Autofill
// server.
size_t active_field_count_;
// The names of the form input elements, that are part of the form signature.
// The string starts with "&" and the names are also separated by the "&"
// character. E.g.: "&form_input1_name&form_input2_name&...&form_inputN_name"
std::string form_signature_field_names_;
// Whether the server expects us to always upload, never upload, or default
// to the stored upload rates.
UploadRequired upload_required_;
// The server experiment corresponding to the server types returned for this
// form.
std::string server_experiment_id_;
// GET or POST.
RequestMethod method_;
// Whether the form includes any field types explicitly specified by the site
// author, via the |autocompletetype| attribute.
bool has_author_specified_types_;
// The URL prefix matched in autocheckout whitelist. An empty string implies
// autocheckout is not enabled for this form.
std::string autocheckout_url_prefix_;
// Whether or not this form was filled by Autocheckout.
bool filled_by_autocheckout_;
DISALLOW_COPY_AND_ASSIGN(FormStructure);
};
} // namespace autofill
#endif // COMPONENTS_AUTOFILL_BROWSER_FORM_STRUCTURE_H_
| 38.026923 | 80 | 0.736118 | [
"vector"
] |
3c48a185c3941941611c27f895786eea0214cd51 | 423 | h | C | src/Data/TSWXMainDT.h | pavanad/language-tools | e431f547161583b17046aa2952bd0bd435842155 | [
"MIT"
] | 3 | 2018-08-16T20:15:42.000Z | 2021-06-13T06:47:06.000Z | src/Data/TSWXMainDT.h | pavanad/language-tools | e431f547161583b17046aa2952bd0bd435842155 | [
"MIT"
] | null | null | null | src/Data/TSWXMainDT.h | pavanad/language-tools | e431f547161583b17046aa2952bd0bd435842155 | [
"MIT"
] | 2 | 2018-07-24T19:13:29.000Z | 2019-04-06T17:36:18.000Z | //---------------------------------------------------------------------------
#ifndef TSWXMainDTH
#define TSWXMainDTH
#include <vector>
#include <Classes.hpp>
//---------------------------------------------------------------------------
class TSWXMainDT
{
public:
std::vector<UnicodeString> m_list;
void SetData(std::vector<UnicodeString> list);
std::vector<UnicodeString> GetData();
};
#endif
| 22.263158 | 78 | 0.434988 | [
"vector"
] |
3c48ee467fe87fe6baf54d05055cbfeeea6b3a20 | 4,938 | h | C | libHDiffPatch/HDiff/diff.h | eerimoq/HDiffPatch | e6245fc2fb363b6f2ac12a319de4ccd94480bfc3 | [
"MIT"
] | null | null | null | libHDiffPatch/HDiff/diff.h | eerimoq/HDiffPatch | e6245fc2fb363b6f2ac12a319de4ccd94480bfc3 | [
"MIT"
] | null | null | null | libHDiffPatch/HDiff/diff.h | eerimoq/HDiffPatch | e6245fc2fb363b6f2ac12a319de4ccd94480bfc3 | [
"MIT"
] | null | null | null | //diff.h
//
/*
The MIT License (MIT)
Copyright (c) 2012-2018 HouSisong
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 HDiff_diff_h
#define HDiff_diff_h
#include <vector>
#include "diff_types.h"
static const int kMinSingleMatchScore_default = 6;
//create a diff data between oldData and newData
// out_diff is uncompressed, you can use create_compressed_diff()
// or create_compressed_diff_stream() create compressed diff data
// recommended always use create_compressed_diff() replace create_diff()
// kMinSingleMatchScore: default 6, bin: 0--4 text: 4--9
void create_diff(const unsigned char* newData,const unsigned char* newData_end,
const unsigned char* oldData,const unsigned char* oldData_end,
std::vector<unsigned char>& out_diff,
int kMinSingleMatchScore=kMinSingleMatchScore_default);
//return patch(oldData+diff)==newData?
bool check_diff(const unsigned char* newData,const unsigned char* newData_end,
const unsigned char* oldData,const unsigned char* oldData_end,
const unsigned char* diff,const unsigned char* diff_end);
//create a compressed diffData between oldData and newData
// out_diff compressed by compressPlugin
// kMinSingleMatchScore: default 6, bin: 0--4 text: 4--9
void create_compressed_diff(const unsigned char *newData,
const unsigned char *newData_end,
const unsigned char *oldData,
const unsigned char *oldData_end,
std::vector<unsigned char>& out_diff,
const hdiff_TCompress *compressPlugin=0,
int kMinSingleMatchScore=kMinSingleMatchScore_default,
int patch_type=0);
//return patch_decompress(oldData+diff)==newData?
bool check_compressed_diff(const unsigned char* newData,const unsigned char* newData_end,
const unsigned char* oldData,const unsigned char* oldData_end,
const unsigned char* diff,const unsigned char* diff_end,
hpatch_TDecompress* decompressPlugin);
//see check_compressed_diff
bool check_compressed_diff_stream(const hpatch_TStreamInput* newData,
const hpatch_TStreamInput* oldData,
const hpatch_TStreamInput* compressed_diff,
hpatch_TDecompress* decompressPlugin);
//diff by stream:
// can control memory requires and run speed by different kMatchBlockSize value,
// but out_diff size is larger than create_compressed_diff()
// recommended used in limited environment or support large file
// kMatchBlockSize: recommended (1<<4)--(1<<14)
// if increase kMatchBlockSize then run faster and require less memory, but out_diff size increase
// NOTICE: out_diff->write()'s writeToPos may be back to update headData!
// throw std::runtime_error when I/O error,etc.
static const size_t kMatchBlockSize_default = (1<<6);
void create_compressed_diff_stream(const hpatch_TStreamInput* newData,
const hpatch_TStreamInput* oldData,
const hpatch_TStreamOutput* out_diff,
const hdiff_TCompress* compressPlugin=0,
size_t kMatchBlockSize=kMatchBlockSize_default,
int patch_type=0);
//resave compressed_diff
// decompress in_diff and recompress to out_diff
// throw std::runtime_error when input file error or I/O error,etc.
void resave_compressed_diff(const hpatch_TStreamInput* in_diff,
hpatch_TDecompress* decompressPlugin,
const hpatch_TStreamOutput* out_diff,
const hdiff_TCompress* compressPlugin);
#endif
| 47.028571 | 101 | 0.681045 | [
"vector"
] |
3c4d6034040fb9455329acddd3b935965770adc7 | 4,655 | h | C | src/sysc/kernel/sc_module_name.h | dwoo-cad/systemc | 9def831390ef9f1a63c219d6a16ed97560ec0d10 | [
"Apache-2.0"
] | null | null | null | src/sysc/kernel/sc_module_name.h | dwoo-cad/systemc | 9def831390ef9f1a63c219d6a16ed97560ec0d10 | [
"Apache-2.0"
] | null | null | null | src/sysc/kernel/sc_module_name.h | dwoo-cad/systemc | 9def831390ef9f1a63c219d6a16ed97560ec0d10 | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera 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.
*****************************************************************************/
/*****************************************************************************
sc_module_name.h -- An object used to help manage object names
and hierarchy.
Original Author: Stan Y. Liao, Synopsys, Inc.
CHANGE LOG AT THE END OF THE FILE
*****************************************************************************/
// $Log: sc_module_name.h,v $
// Revision 1.5 2011/08/26 20:46:10 acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
#ifndef SC_MODULE_NAME_H
#define SC_MODULE_NAME_H
#include <string>
namespace sc_core {
class sc_module;
class sc_simcontext;
// ----------------------------------------------------------------------------
// CLASS : sc_module_name
//
// Module name class.
// ----------------------------------------------------------------------------
class SC_API sc_module_name
{
friend class sc_module;
friend class sc_object_manager;
public:
sc_module_name( const char* );
sc_module_name( const sc_module_name& );
~sc_module_name();
operator const char*() const;
protected:
inline void clear_module( sc_module* module_p );
inline void set_module( sc_module* module_p );
private:
std::string m_name;
sc_module* m_module_p;
sc_module_name* m_next;
sc_simcontext* m_simc;
bool m_pushed;
private:
// disabled
sc_module_name();
sc_module_name& operator = ( const sc_module_name& );
};
inline void sc_module_name::clear_module( sc_module* module_p )
{
sc_assert( m_module_p == module_p );
m_module_p = module_p = 0; // avoid unused parameter warning (module_p)
}
inline void sc_module_name::set_module( sc_module* module_p )
{
m_module_p = module_p;
}
} // namespace sc_core
// Revision 1.4 2011/02/18 20:27:14 acg
// Andy Goodrich: Updated Copyrights.
//
// Revision 1.3 2011/02/13 21:47:37 acg
// Andy Goodrich: update copyright notice.
//
// Revision 1.2 2008/05/22 17:06:26 acg
// Andy Goodrich: updated copyright notice to include 2008.
//
// Revision 1.1.1.1 2006/12/15 20:20:05 acg
// SystemC 2.3
//
// Revision 1.4 2006/03/14 23:56:58 acg
// Andy Goodrich: This fixes a bug when an exception is thrown in
// sc_module::sc_module() for a dynamically allocated sc_module
// object. We are calling sc_module::end_module() on a module that has
// already been deleted. The scenario runs like this:
//
// a) the sc_module constructor is entered
// b) the exception is thrown
// c) the exception processor deletes the storage for the sc_module
// d) the stack is unrolled causing the sc_module_name instance to be deleted
// e) ~sc_module_name() calls end_module() with its pointer to the sc_module
// f) because the sc_module has been deleted its storage is corrupted,
// either by linking it to a free space chain, or by reuse of some sort
// g) the m_simc field is garbage
// h) the m_object_manager field is also garbage
// i) an exception occurs
//
// This does not happen for automatic sc_module instances since the
// storage for the module is not reclaimed its just part of the stack.
//
// I am fixing this by having the destructor for sc_module clear the
// module pointer in its sc_module_name instance. That cuts things at
// step (e) above, since the pointer will be null if the module has
// already been deleted. To make sure the module stack is okay, I call
// end-module() in ~sc_module in the case where there is an
// sc_module_name pointer lying around.
//
// Revision 1.3 2006/01/13 18:44:30 acg
// Added $Log to record CVS changes into the source.
#endif
| 32.78169 | 79 | 0.643824 | [
"object"
] |
3c4dfee7b150fb189ae75abdd19d0fce455f98db | 3,912 | h | C | hlsdk/engine/bspfile.h | d3m37r4/VoiceTranscoder | a9ae70b436e26f6589ac7841749ce281c227bb2c | [
"Unlicense"
] | 19 | 2019-11-26T13:49:34.000Z | 2021-12-21T03:27:33.000Z | hlsdk/engine/bspfile.h | d3m37r4/VoiceTranscoder | a9ae70b436e26f6589ac7841749ce281c227bb2c | [
"Unlicense"
] | 17 | 2019-11-27T11:16:26.000Z | 2021-02-04T07:21:01.000Z | hlsdk/engine/bspfile.h | andrewlindberg/VoiceTranscoder | a9ae70b436e26f6589ac7841749ce281c227bb2c | [
"Unlicense"
] | 7 | 2019-11-26T13:09:34.000Z | 2020-12-13T05:48:27.000Z | /*
*
* 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
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#pragma once
// header
#define Q1BSP_VERSION 29 // quake1 regular version (beta is 28)
#define HLBSP_VERSION 30 // half-life regular version
#define MAX_MAP_HULLS 4
#define CONTENTS_ORIGIN -7 // removed at csg time
#define CONTENTS_CLIP -8 // changed to contents_solid
#define CONTENTS_CURRENT_0 -9
#define CONTENTS_CURRENT_90 -10
#define CONTENTS_CURRENT_180 -11
#define CONTENTS_CURRENT_270 -12
#define CONTENTS_CURRENT_UP -13
#define CONTENTS_CURRENT_DOWN -14
#define CONTENTS_TRANSLUCENT -15
#define LUMP_ENTITIES 0
#define LUMP_PLANES 1
#define LUMP_TEXTURES 2
#define LUMP_VERTEXES 3
#define LUMP_VISIBILITY 4
#define LUMP_NODES 5
#define LUMP_TEXINFO 6
#define LUMP_FACES 7
#define LUMP_LIGHTING 8
#define LUMP_CLIPNODES 9
#define LUMP_LEAFS 10
#define LUMP_MARKSURFACES 11
#define LUMP_EDGES 12
#define LUMP_SURFEDGES 13
#define LUMP_MODELS 14
#define HEADER_LUMPS 15
typedef struct lump_s
{
int fileofs;
int filelen;
} lump_t;
typedef struct dmodel_s
{
float mins[3], maxs[3];
float origin[3];
int headnode[MAX_MAP_HULLS];
int visleafs; // not including the solid leaf 0
int firstface, numfaces;
} dmodel_t;
typedef struct dheader_s
{
int version;
lump_t lumps[15];
} dheader_t;
typedef struct dmiptexlump_s
{
int _nummiptex;
int dataofs[4];
} dmiptexlump_t;
typedef struct miptex_s
{
char name[16];
unsigned width;
unsigned height;
unsigned offsets[4];
} miptex_t;
typedef struct dvertex_s
{
float point[3];
} dvertex_t;
typedef struct dplane_s
{
float normal[3];
float dist;
int type;
} dplane_t;
typedef struct dnode_s
{
int planenum;
short children[2];
short mins[3];
short maxs[3];
unsigned short firstface;
unsigned short numfaces;
} dnode_t;
typedef struct dclipnode_s
{
int planenum;
short children[2]; // negative numbers are contents
} dclipnode_t;
typedef struct texinfo_s
{
float vecs[2][4];
int _miptex;
int flags;
} texinfo_t;
typedef struct dedge_s
{
unsigned short v[2];
} dedge_t;
typedef struct dface_s
{
short planenum;
short side;
int firstedge;
short numedges;
short texinfo;
byte styles[4];
int lightofs;
} dface_t;
typedef struct dleaf_s
{
int contents;
int visofs;
short mins[3];
short maxs[3];
unsigned short firstmarksurface;
unsigned short nummarksurfaces;
byte ambient_level[4];
} dleaf_t;
| 24.298137 | 77 | 0.693252 | [
"solid"
] |
2c5c3ef9dfb9769f84997fb99f8c4d70470e836f | 9,905 | h | C | src/gromacs/modularsimulator/computeglobalselement.h | hejamu/gromacs | 4f4b9e4b197ae78456faada74c9f4cab7d128de6 | [
"BSD-2-Clause"
] | 3 | 2020-11-09T14:24:00.000Z | 2022-03-09T19:24:17.000Z | src/gromacs/modularsimulator/computeglobalselement.h | hejamu/gromacs | 4f4b9e4b197ae78456faada74c9f4cab7d128de6 | [
"BSD-2-Clause"
] | 2 | 2020-11-09T14:16:24.000Z | 2022-02-14T14:07:53.000Z | src/gromacs/modularsimulator/computeglobalselement.h | hejamu/gromacs | 4f4b9e4b197ae78456faada74c9f4cab7d128de6 | [
"BSD-2-Clause"
] | 1 | 2020-11-04T05:48:35.000Z | 2020-11-04T05:48:35.000Z | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
* \brief Declares the global reduction element for the modular simulator
*
* \author Pascal Merz <pascal.merz@me.com>
* \ingroup module_modularsimulator
*
* This header is only used within the modular simulator module
*/
#ifndef GMX_MODULARSIMULATOR_COMPUTEGLOBALSELEMENT_H
#define GMX_MODULARSIMULATOR_COMPUTEGLOBALSELEMENT_H
#include "gromacs/mdlib/simulationsignal.h"
#include "gromacs/mdlib/vcm.h"
#include "energydata.h"
#include "modularsimulatorinterfaces.h"
#include "statepropagatordata.h"
#include "topologyholder.h"
struct gmx_global_stat;
struct gmx_wallcycle;
struct t_nrnb;
namespace gmx
{
class FreeEnergyPerturbationData;
class LegacySimulatorData;
class MDAtoms;
class MDLogger;
class ObservablesReducer;
//! \addtogroup module_modularsimulator
//! \{
//! The different global reduction schemes we know about
enum class ComputeGlobalsAlgorithm
{
LeapFrog,
VelocityVerlet
};
//! The function type allowing to request a check of the number of bonded interactions
typedef std::function<void()> CheckBondedInteractionsCallback;
/*! \internal
* \brief Encapsulate the calls to `compute_globals`
*
* This element aims at offering an interface to the legacy
* implementation which is compatible with the new simulator approach.
*
* The element comes in 3 (templated) flavors: the leap-frog case, the first
* call during a velocity-verlet integrator, and the second call during a
* velocity-verlet integrator. In velocity verlet, the state at the beginning
* of the step corresponds to
* positions at time t
* velocities at time t - dt/2
* The first velocity propagation (+dt/2) therefore actually corresponds to the
* previous step, bringing the state to the full timestep at time t. Most global
* reductions are made at this point. The second call is needed to correct the
* constraint virial after the second propagation of velocities (+dt/2) and of
* the positions (+dt).
*
* \tparam algorithm The global reduction scheme
*/
template<ComputeGlobalsAlgorithm algorithm>
class ComputeGlobalsElement final : public ISimulatorElement, public IEnergySignallerClient, public ITrajectorySignallerClient
{
public:
//! Constructor
ComputeGlobalsElement(StatePropagatorData* statePropagatorData,
EnergyData* energyData,
FreeEnergyPerturbationData* freeEnergyPerturbationData,
SimulationSignals* signals,
int nstglobalcomm,
FILE* fplog,
const MDLogger& mdlog,
t_commrec* cr,
const t_inputrec* inputrec,
const MDAtoms* mdAtoms,
t_nrnb* nrnb,
gmx_wallcycle* wcycle,
t_forcerec* fr,
const gmx_mtop_t& global_top,
Constraints* constr,
ObservablesReducer* observablesReducer);
//! Destructor
~ComputeGlobalsElement() override;
/*! \brief Element setup - first call to compute_globals
*
*/
void elementSetup() override;
/*! \brief Register run function for step / time
*
* This registers the call to compute_globals when needed.
*
* \param step The step number
* \param time The time
* \param registerRunFunction Function allowing to register a run function
*/
void scheduleTask(Step step, Time time, const RegisterRunFunction& registerRunFunction) override;
//! No element teardown needed
void elementTeardown() override {}
/*! \brief Factory method implementation
*
* \param legacySimulatorData Pointer allowing access to simulator level data
* \param builderHelper ModularSimulatorAlgorithmBuilder helper object
* \param statePropagatorData Pointer to the \c StatePropagatorData object
* \param energyData Pointer to the \c EnergyData object
* \param freeEnergyPerturbationData Pointer to the \c FreeEnergyPerturbationData object
* \param globalCommunicationHelper Pointer to the \c GlobalCommunicationHelper object
* \param observablesReducer Pointer to the \c ObservablesReducer object
*
* \throws std::bad_any_cast on internal error in VelocityVerlet algorithm builder.
* \throws std::bad_alloc when out of memory.
*
* \return Pointer to the element to be added. Element needs to have been stored using \c storeElement
*/
static ISimulatorElement* getElementPointerImpl(LegacySimulatorData* legacySimulatorData,
ModularSimulatorAlgorithmBuilderHelper* builderHelper,
StatePropagatorData* statePropagatorData,
EnergyData* energyData,
FreeEnergyPerturbationData* freeEnergyPerturbationData,
GlobalCommunicationHelper* globalCommunicationHelper,
ObservablesReducer* observablesReducer);
private:
//! IEnergySignallerClient implementation
std::optional<SignallerCallback> registerEnergyCallback(EnergySignallerEvent event) override;
//! ITrajectorySignallerClient implementation
std::optional<SignallerCallback> registerTrajectorySignallerCallback(TrajectoryEvent event) override;
//! The compute_globals call
void compute(Step step, unsigned int flags, SimulationSignaller* signaller, bool useLastBox, bool isInit = false);
//! Next step at which energy needs to be reduced
Step energyReductionStep_;
//! Next step at which virial needs to be reduced
Step virialReductionStep_;
//! For VV only, we need to schedule twice per step. This keeps track of the scheduling stage.
Step vvSchedulingStep_;
//! Whether center of mass motion stopping is enabled
const bool doStopCM_;
//! Number of steps after which center of mass motion is removed
int nstcomm_;
//! Compute globals communication period
int nstglobalcomm_;
//! The last (planned) step (only used for LF)
const Step lastStep_;
//! The initial step (only used for VV)
const Step initStep_;
//! A dummy signaller (used for setup and VV)
std::unique_ptr<SimulationSignaller> nullSignaller_;
//! Global reduction struct
gmx_global_stat* gstat_;
// TODO: Clarify relationship to data objects and find a more robust alternative to raw pointers (#3583)
//! Pointer to the microstate
StatePropagatorData* statePropagatorData_;
//! Pointer to the energy data (needed for the tensors and mu_tot)
EnergyData* energyData_;
//! Pointer to the free energy perturbation data
FreeEnergyPerturbationData* freeEnergyPerturbationData_;
//! Center of mass motion removal
t_vcm vcm_;
//! Signals
SimulationSignals* signals_;
// Access to ISimulator data
//! Handles logging.
FILE* fplog_;
//! Handles logging.
const MDLogger& mdlog_;
//! Handles communication.
t_commrec* cr_;
//! Contains user input mdp options.
const t_inputrec* inputrec_;
//! Full system topology - only needed for checkNumberOfBondedInteractions.
const gmx_mtop_t& top_global_;
//! Atom parameters for this domain.
const MDAtoms* mdAtoms_;
//! Handles constraints.
Constraints* constr_;
//! Manages flop accounting.
t_nrnb* nrnb_;
//! Manages wall cycle accounting.
gmx_wallcycle* wcycle_;
//! Parameters for force calculations.
t_forcerec* fr_;
//! Coordinates reduction for observables
ObservablesReducer* observablesReducer_;
};
//! \}
} // namespace gmx
#endif // GMX_MODULARSIMULATOR_COMPUTEGLOBALSELEMENT_H
| 41.270833 | 126 | 0.676325 | [
"object"
] |
2c65722704408ce3810f46a1d81d82827d800ac1 | 18,951 | h | C | src/seqan/sequence/iter_concat_virtual.h | gosianow/MeDiChISeq | 211fff318638d543e7725edd8e6afa3ee69a182a | [
"BSD-3-Clause"
] | null | null | null | src/seqan/sequence/iter_concat_virtual.h | gosianow/MeDiChISeq | 211fff318638d543e7725edd8e6afa3ee69a182a | [
"BSD-3-Clause"
] | 2 | 2017-01-15T16:12:40.000Z | 2017-01-15T16:13:44.000Z | src/seqan/sequence/iter_concat_virtual.h | gosianow/MeDiChISeq | 211fff318638d543e7725edd8e6afa3ee69a182a | [
"BSD-3-Clause"
] | null | null | null | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Andreas Gogol-Doering <andreas.doering@mdc-berlin.de>
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
// Implementation of the specialization ConcatVirtual of class Iter that
// allows the iteration of arbitrary StringSet objects as if they were
// the concatenation of all strings.
// ==========================================================================
#ifndef SEQAN_SEQUENCE_ITER_CONCAT_VIRTUAL_H_
#define SEQAN_SEQUENCE_ITER_CONCAT_VIRTUAL_H_
namespace seqan {
// ============================================================================
// Forwards
// ============================================================================
// The Metafunction Concatenator is actually defined in string_set_base.h.
template <typename T>
struct Concatenator;
// ============================================================================
// Tags, Classes, Enums
// ============================================================================
template <typename TDelimiter = void >
struct ConcatVirtual;
// TODO(holtgrew): Ask David about objNo and offset.
/**
.Spec.ConcatVirtual Iterator
..cat:Sequences
..general:Class.Iter
..summary:Iterator that sequentially iterates through the elements of a @Class.StringSet@ as if they were directly concatenated, cmp. @Spec.ConcatDirect@.
..signature:Iter<TStringSet, ConcatVirtual<TSpec> >
..param.TStringSet:Type of the @Class.StringSet@.
..param.TSpec:The delimiter to use.
..include:seqan/sequence.h
.Memfunc.ConcatVirtual Iterator#Iter:
..class:Spec.ConcatVirtual Iterator
..summary:Constructor
..signature:Iter(host)
..signature:Iter(host, objNo, offset)
..param.host:Container to iterate.
..param.objNo:Sequence number to set the iterator to.
..param.offset:Offset in the object (specified by objNo) to point to.
..remarks:If $objNo$ and $offset$ are not given, the iterator will point to the first element with offset 0.
*/
template <typename TStringSet, typename TSpec >
class Iter<TStringSet, ConcatVirtual<TSpec> >
{
public:
typedef typename Value<TStringSet>::Type TString;
typedef typename Value<TString>::Type TValue;
typedef typename Size<TString>::Type TSize;
// TODO(holtgrew): obj_iterator and const_obj_iterator do not appear to be in any C++/STL standard and do not conform to SeqAn's naming scheme.
typedef typename Iterator<TString, Standard>::Type obj_iterator;
typedef typename Iterator<TString const, Standard>::Type const_obj_iterator;
// ----------------------------------------------------------------------
// STL compatible public iterator interface
typedef Iter iterator;
typedef ::std::bidirectional_iterator_tag iterator_category;
typedef TValue value_type;
typedef TValue & reference;
typedef TValue const & const_reference;
typedef TValue * pointer;
typedef TSize size_type;
typedef typename Difference<TString>::Type difference_type;
// ----------------------------------------------------------------------
TStringSet * host;
unsigned objNo;
obj_iterator _begin, _cur, _end;
inline Iter() {}
inline Iter(TStringSet &_host)
: host(&_host)
{
objNo = 0;
_begin = _cur = begin(_host[objNo]);
_end = end(_host[objNo]);
_testEnd();
}
inline Iter(TStringSet &_host, unsigned _objNo, difference_type _offset)
: host(&_host)
{
if (_objNo <length(_host)) {
objNo = _objNo;
_begin = _cur = begin(_host[objNo]);
_end = end(_host[objNo]);
goFurther(_cur, _offset);
_testEnd();
} else {
objNo = length(_host) - 1;
_begin = begin(_host[objNo]);
_cur = _end = end(_host[objNo]);
}
}
// ----------------------------------------------------------------------
// Conversion operators; have to be defined in class def.
// ----------------------------------------------------------------------
inline operator obj_iterator()
{
return _cur;
}
inline operator void * ()
{
return _cur;
}
// ----------------------------------------------------------------------
// Shared methods for methods that *have* to be defined in the class def.
// ----------------------------------------------------------------------
// _testEnd() is used in the constructors only, so having it here as a
// non-public function is allowed.
inline void _testEnd()
{
while (_cur == _end && objNo < (length(*host) - 1)) {
++objNo;
_begin = _cur = begin((*host)[objNo]);
_end = end((*host)[objNo]);
};
}
};
// ============================================================================
// Metafunctions
// ============================================================================
// --------------------------------------------------------------------------
// Metafunction Value
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
struct Value<Iter<TStringSet, ConcatVirtual<TSpec> > >
: Value<typename Value<TStringSet>::Type> {};
template <typename TStringSet, typename TSpec>
struct Value<Iter<TStringSet, ConcatVirtual<TSpec> > const>
: Value<typename Value<TStringSet>::Type> {};
// --------------------------------------------------------------------------
// Metafunction GetValue
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
struct GetValue<Iter<TStringSet, ConcatVirtual<TSpec> > >
: GetValue<typename Value<TStringSet>::Type> {};
template <typename TStringSet, typename TSpec>
struct GetValue<Iter<TStringSet, ConcatVirtual<TSpec> > const>
: GetValue<typename Value<TStringSet>::Type> {};
// --------------------------------------------------------------------------
// Metafunction Size
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
struct Size<Iter<TStringSet, ConcatVirtual<TSpec> > >
: Size<typename Value<TStringSet>::Type> {};
// Default implementation Size<T const> redirects to non-const variant.
// --------------------------------------------------------------------------
// Metafunction Reference
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
struct Reference<Iter<TStringSet, ConcatVirtual<TSpec> > >
: Reference<typename Value<TStringSet>::Type> {};
template <typename TStringSet, typename TSpec>
struct Reference<Iter<TStringSet, ConcatVirtual<TSpec> > const >
: Reference<typename Value<TStringSet>::Type> {};
// ============================================================================
// Functions
// ============================================================================
// --------------------------------------------------------------------------
// Functions value(), operator*()
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
inline typename Reference<Iter<TStringSet, ConcatVirtual<TSpec> > const>::Type
value(Iter<TStringSet, ConcatVirtual<TSpec> > const & me)
{
return *me._cur;
}
template <typename TStringSet, typename TSpec>
inline typename Reference<Iter<TStringSet, ConcatVirtual<TSpec> > >::Type
value(Iter<TStringSet, ConcatVirtual<TSpec> > & me)
{
return *me._cur;
}
template <typename TStringSet, typename TSpec>
inline typename Reference<Iter<TStringSet, ConcatVirtual<TSpec> > const>::Type
operator*(Iter<TStringSet, ConcatVirtual<TSpec> > const & me)
{
return *me._cur;
}
template <typename TStringSet, typename TSpec>
inline typename Reference<Iter<TStringSet, ConcatVirtual<TSpec> > >::Type
operator*(Iter<TStringSet, ConcatVirtual<TSpec> > & me)
{
return *me._cur;
}
// --------------------------------------------------------------------------
// Functions goNext(), operator++()
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
inline void
goNext(Iter<TStringSet, ConcatVirtual<TSpec> > & me)
{
++me._cur;
me._testEnd();
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator++(Iter<TStringSet, ConcatVirtual<TSpec> > & me)
{
goNext(me);
return me;
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator++(Iter<TStringSet, ConcatVirtual<TSpec> > & me, int)
{
Iter<TStringSet, ConcatVirtual<TSpec> > before = me;
goNext(me);
return before;
}
// --------------------------------------------------------------------------
// Functions goPrevious(), operator++()
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
inline void
goPrevious(Iter<TStringSet, ConcatVirtual<TSpec> > & me)
{
while (me._cur == me._begin && me.objNo > 0) {
--me.objNo;
me._begin = begin((*me.host)[me.objNo]);
me._end = me._cur = end((*me.host)[me.objNo]);
}
--me._cur;
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator--(Iter<TStringSet, ConcatVirtual<TSpec> > & me)
{
goPrevious(me);
return me;
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator--(Iter<TStringSet, ConcatVirtual<TSpec> > & me, int)
{
Iter<TStringSet, ConcatVirtual<TSpec> > before = me;
goPrevious(me);
return before;
}
// --------------------------------------------------------------------------
// Helper function _tell()
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec>
inline typename Size<typename Value<TStringSet>::Type >::Type
_tell(Iter<TStringSet, ConcatVirtual<TSpec> > const & me)
{
typedef typename Size<typename Value<TStringSet>::Type >::Type TSize;
typedef Pair<unsigned, TSize> TPair;
return posGlobalize(TPair(me.objNo, difference(me._begin, me._cur)), stringSetLimits(*me.host));
}
// --------------------------------------------------------------------------
// Function operator+()
// --------------------------------------------------------------------------
template <typename TStringSet, typename TSpec, typename TDelta>
inline Iter<TStringSet, ConcatVirtual<TSpec> >
operator+(Iter<TStringSet, ConcatVirtual<TSpec> > const & me, TDelta delta)
{
Pair<unsigned, typename Size<typename Value<TStringSet>::Type>::Type> pos;
posLocalize(pos, _tell(me) + delta, stringSetLimits(*me.host));
return Iter<TStringSet, ConcatVirtual<TSpec> > (*me.host, getValueI1(pos), getValueI2(pos));
}
template <typename TStringSet, typename TSpec, typename T1, typename T2, typename TPack>
inline Iter<TStringSet, ConcatVirtual<TSpec> >
operator+(Iter<TStringSet, ConcatVirtual<TSpec> > const & me, Pair<T1, T2, TPack> delta)
{
Pair<unsigned, typename Size<typename Value<TStringSet>::Type>::Type> pos;
posLocalize(pos, _tell(me) + delta, stringSetLimits(*me.host));
return Iter<TStringSet, ConcatVirtual<TSpec> > (*me.host, getValueI1(pos), getValueI2(pos));
}
// --------------------------------------------------------------------------
// Function operator-()
// --------------------------------------------------------------------------
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
typename Difference<Iter<TSSetL, ConcatVirtual<TSpecL> > >::Type
operator-(
Iter<TSSetL, ConcatVirtual<TSpecL> > const & L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const & R)
{
return _tell(L) - _tell(R);
}
template <typename TStringSet, typename TSpec, typename TDelta>
inline Iter<TStringSet, ConcatVirtual<TSpec> >
operator-(Iter<TStringSet, ConcatVirtual<TSpec> > const & me, TDelta delta)
{
Pair<unsigned, typename Size<typename Value<TStringSet>::Type>::Type> pos;
posLocalize(pos, _tell(me) - delta, stringSetLimits(*me.host));
return Iter<TStringSet, ConcatVirtual<TSpec> > (*me.host, getValueI1(pos), getValueI2(pos));
}
// --------------------------------------------------------------------------
// Function operator==()
// --------------------------------------------------------------------------
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator==(
Iter<TSSetL, ConcatVirtual<TSpecL> > const & L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const & R)
{
SEQAN_ASSERT_EQ(L.host, R.host);
return L.objNo == R.objNo && L._cur == R._cur;
}
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator!=(
Iter<TSSetL, ConcatVirtual<TSpecL> > const & L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const & R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo != R.objNo || L._cur != R._cur;
}
// --------------------------------------------------------------------------
// Function operator<()
// --------------------------------------------------------------------------
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator<(
Iter<TSSetL, ConcatVirtual<TSpecL> > const & L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const & R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo < R.objNo || (L.objNo == R.objNo && L._cur < R._cur);
}
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator > (
Iter<TSSetL, ConcatVirtual<TSpecL> > const & L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const & R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo > R.objNo || (L.objNo == R.objNo && L._cur > R._cur);
}
// --------------------------------------------------------------------------
// Function container()
// --------------------------------------------------------------------------
template <typename TSSet, typename TSpec>
inline typename Concatenator<TSSet>::Type
container(Iter<TSSet, ConcatVirtual<TSpec> > & me)
{
return concat(*me.host);
}
template <typename TSSet, typename TSpec>
inline typename Concatenator<TSSet>::Type
container(Iter<TSSet, ConcatVirtual<TSpec> > const & me)
{
return concat(*me.host);
}
// --------------------------------------------------------------------------
// Function atBegin()
// --------------------------------------------------------------------------
template <typename TSSet, typename TSpec>
inline bool
atBegin(Iter<TSSet, ConcatVirtual<TSpec> > & me)
{
return me._cur == me._begin && me.objNo == 0;
}
template <typename TSSet, typename TSpec>
inline bool
atBegin(Iter<TSSet, ConcatVirtual<TSpec> > const & me)
{
return me._cur == me._begin && me.objNo == 0;
}
// --------------------------------------------------------------------------
// Function atEnd()
// --------------------------------------------------------------------------
template <typename TSSet, typename TSpec>
inline bool
atEnd(Iter<TSSet, ConcatVirtual<TSpec> > & me)
{
return me._cur == me._end && me.objNo == (length(*me.host) - 1);
}
template <typename TSSet, typename TSpec>
inline bool
atEnd(Iter<TSSet, ConcatVirtual<TSpec> > const & me)
{
return me._cur == me._end && me.objNo == (length(*me.host) - 1);
}
// --------------------------------------------------------------------------
// Function atEndOfSequence()
// --------------------------------------------------------------------------
// TODO(holtgrew): Specifying a catch-all implementation appears a bit too generous, what about concept checking?
/**
.Function.atEndOfSequence
..class:Spec.ConcatVirtual Iterator
..summary:Returns true if the iterator is at the end of a sequence.
..cat:Sequences
..signature:atEndOfSequence(iter)
..param.iter:Iterator to test.
...type:Spec.ConcatVirtual Iterator
...type:Class.Iter
..returns:$true$ if the iterator is at the end of a sequence.
...type:nolink:$bool$
..include:seqan/sequence.h
*/
template <typename TIterator>
inline bool
atEndOfSequence(TIterator const & me)
{
return atEnd(me);
}
template <typename TSSet, typename TSpec>
inline bool
atEndOfSequence(Iter<TSSet, ConcatVirtual<TSpec> > const & me)
{
if (me._cur == me._begin && me.objNo > 0)
return true;
if (me._cur == me._end)
return true;
return false;
}
template <typename TIterator>
inline bool
atEndOfSequence(TIterator & me)
{
return atEndOfSequence(reinterpret_cast<TIterator const &>(me));
}
} // namespace seqan
#endif // #ifndef SEQAN_SEQUENCE_ITER_CONCAT_VIRTUAL_H_
| 36.514451 | 154 | 0.553427 | [
"object"
] |
2c680465d017ba4fbd23d9a78b718d31ccea867e | 23,905 | c | C | sdk_k64f/boards/frdmk64f/demo_apps/power_mode_switch/power_mode_switch.c | Sir-Branch/k64f-starter-template | f8959fd185f090363d180d69f84c2727e37cbeeb | [
"MIT"
] | 1 | 2020-08-23T20:24:19.000Z | 2020-08-23T20:24:19.000Z | sdk_k64f/boards/frdmk64f/demo_apps/power_mode_switch/power_mode_switch.c | Sir-Branch/xxxx-starter-template | f8959fd185f090363d180d69f84c2727e37cbeeb | [
"MIT"
] | 1 | 2020-08-24T00:41:48.000Z | 2020-08-24T02:17:44.000Z | sdk_k64f/boards/frdmk64f/demo_apps/power_mode_switch/power_mode_switch.c | Sir-Branch/xxxx-starter-template | f8959fd185f090363d180d69f84c2727e37cbeeb | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_common.h"
#include "fsl_smc.h"
#include "fsl_rcm.h"
#include "fsl_port.h"
#include "power_mode_switch.h"
#include "board.h"
#include "fsl_debug_console.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "fsl_pmc.h"
#include "fsl_uart.h"
/*******************************************************************************
* Definitions
******************************************************************************/
#define APP_DEBUG_UART_BAUDRATE 9600 /* Debug console baud rate. */
#define APP_DEBUG_UART_CLKSRC_NAME kCLOCK_CoreSysClk /* System clock. */
#define APP_LLWU DEMO_LLWU_PERIPHERAL
#define APP_LLWU_IRQHANDLER DEMO_LLWU_IRQHANDLER
#define APP_LPTMR DEMO_LPTMR_PERIPHERAL
#define APP_LPTMR_IRQHANDLER DEMO_LPTMR_IRQHANDLER
#define LLWU_LPTMR_IDX 0U /* LLWU_M0IF */
#define LLWU_WAKEUP_PIN_IDX 10U /* LLWU_P10 */
#define LLWU_WAKEUP_PIN_TYPE kLLWU_ExternalPinFallingEdge
#define APP_WAKEUP_BUTTON_GPIO BOARD_SW2_GPIO
#define APP_WAKEUP_BUTTON_PORT BOARD_SW2_PORT
#define APP_WAKEUP_BUTTON_GPIO_PIN BOARD_SW2_GPIO_PIN
#define APP_WAKEUP_BUTTON_IRQ BOARD_SW2_IRQ
#define APP_WAKEUP_BUTTON_IRQ_HANDLER BOARD_SW2_IRQ_HANDLER
#define APP_WAKEUP_BUTTON_NAME BOARD_SW2_NAME
#define APP_WAKEUP_BUTTON_IRQ_TYPE kPORT_InterruptFallingEdge
/* Debug console RX pin: PORTB16 MUX: 3 */
#define DEBUG_CONSOLE_RX_PORT PORTB
#define DEBUG_CONSOLE_RX_GPIO GPIOB
#define DEBUG_CONSOLE_RX_PIN 16
#define DEBUG_CONSOLE_RX_PINMUX kPORT_MuxAlt3
/* Debug console TX pin: PORTB17 MUX: 3 */
#define DEBUG_CONSOLE_TX_PORT PORTB
#define DEBUG_CONSOLE_TX_GPIO GPIOB
#define DEBUG_CONSOLE_TX_PIN 17
#define DEBUG_CONSOLE_TX_PINMUX kPORT_MuxAlt3
#define CORE_CLK_FREQ CLOCK_GetFreq(kCLOCK_CoreSysClk)
/*******************************************************************************
* Prototypes
******************************************************************************/
void APP_PowerPreSwitchHook(smc_power_state_t originPowerState, app_power_mode_t targetMode);
void APP_PowerPostSwitchHook(smc_power_state_t originPowerState, app_power_mode_t targetMode);
/*
* Set the clock configuration for RUN mode from VLPR mode.
*/
extern void APP_SetClockRunFromVlpr(void);
/*
* Set the clock configuration for VLPR mode.
*/
extern void APP_SetClockVlpr(void);
/*
* Hook function called before power mode switch.
*/
extern void APP_PowerPreSwitchHook(smc_power_state_t originPowerState, app_power_mode_t targetMode);
/*
* Hook function called after power mode switch.
*/
extern void APP_PowerPostSwitchHook(smc_power_state_t originPowerState, app_power_mode_t targetMode);
/*******************************************************************************
* Variables
******************************************************************************/
static uint8_t s_wakeupTimeout; /* Wakeup timeout. (Unit: Second) */
static app_wakeup_source_t s_wakeupSource; /* Wakeup source. */
/*******************************************************************************
* Code
******************************************************************************/
void APP_SetClockVlpr(void)
{
const sim_clock_config_t simConfig = {
.pllFllSel = 3U, /* PLLFLLSEL select IRC48MCLK. */
.er32kSrc = 2U, /* ERCLK32K selection, use RTC. */
.clkdiv1 = 0x00040000U, /* SIM_CLKDIV1. */
};
CLOCK_SetSimSafeDivs();
CLOCK_SetInternalRefClkConfig(kMCG_IrclkEnable, kMCG_IrcFast, 0U);
/* MCG works in PEE mode now, will switch to BLPI mode. */
CLOCK_ExternalModeToFbeModeQuick(); /* Enter FBE. */
CLOCK_SetFbiMode(kMCG_Dmx32Default, kMCG_DrsLow, NULL); /* Enter FBI. */
CLOCK_SetLowPowerEnable(true); /* Enter BLPI. */
CLOCK_SetSimConfig(&simConfig);
}
void APP_SetClockRunFromVlpr(void)
{
const sim_clock_config_t simConfig = {
.pllFllSel = 1U, /* PLLFLLSEL select PLL. */
.er32kSrc = 2U, /* ERCLK32K selection, use RTC. */
.clkdiv1 = 0x01140000U, /* SIM_CLKDIV1. */
};
const mcg_pll_config_t pll0Config = {
.enableMode = 0U,
.prdiv = 0x13U,
.vdiv = 0x18U,
};
CLOCK_SetSimSafeDivs();
/* Currently in BLPI mode, will switch to PEE mode. */
/* Enter FBI. */
CLOCK_SetLowPowerEnable(false);
/* Enter FBE. */
CLOCK_SetFbeMode(7U, kMCG_Dmx32Default, kMCG_DrsLow, NULL);
/* Enter PBE. */
CLOCK_SetPbeMode(kMCG_PllClkSelPll0, &pll0Config);
/* Enter PEE. */
CLOCK_SetPeeMode();
CLOCK_SetSimConfig(&simConfig);
}
static void APP_InitDebugConsole(void)
{
uint32_t uartClkSrcFreq;
uartClkSrcFreq = CLOCK_GetFreq(APP_DEBUG_UART_CLKSRC_NAME);
DbgConsole_Init(BOARD_DEBUG_UART_INSTANCE, APP_DEBUG_UART_BAUDRATE, BOARD_DEBUG_UART_TYPE, uartClkSrcFreq);
}
void APP_PowerPreSwitchHook(smc_power_state_t originPowerState, app_power_mode_t targetMode)
{
/* Wait for debug console output finished. */
while (!(kUART_TransmissionCompleteFlag & UART_GetStatusFlags((UART_Type *)BOARD_DEBUG_UART_BASEADDR)))
{
}
DbgConsole_Deinit();
if ((kAPP_PowerModeRun != targetMode) && (kAPP_PowerModeVlpr != targetMode))
{
/*
* Set pin for current leakage.
* Debug console RX pin: Set to pinmux to disable.
* Debug console TX pin: Don't need to change.
*/
PORT_SetPinMux(DEBUG_CONSOLE_RX_PORT, DEBUG_CONSOLE_RX_PIN, kPORT_PinDisabledOrAnalog);
PORT_SetPinMux(DEBUG_CONSOLE_TX_PORT, DEBUG_CONSOLE_TX_PIN, kPORT_PinDisabledOrAnalog);
}
/* Disable the PLL in WAIT mode to same more power. FEI mode. */
if (kAPP_PowerModeWait == targetMode)
{
const mcg_config_t mcgConfigStruct = {
.mcgMode = kMCG_ModeFEI, /* FEI - FLL with internal RTC. */
.irclkEnableMode = kMCG_IrclkEnable, /* MCGIRCLK enabled, MCGIRCLK disabled in STOP mode */
.ircs = kMCG_IrcSlow, /* Slow internal reference clock selected */
.fcrdiv = 0x0U, /* Fast IRC divider: divided by 1 */
.frdiv = 0x0U, /* FLL reference clock divider: divided by 32 */
.drs = kMCG_DrsLow, /* Low frequency range */
.dmx32 = kMCG_Dmx32Default, /* DCO has a default range of 25% */
.oscsel = kMCG_OscselOsc, /* Selects System Oscillator (OSCCLK) */
.pll0Config =
{
.enableMode = 0, /* MCGPLLCLK disabled */
.prdiv = 0x13U, /* PLL Reference divider: divided by 20 */
.vdiv = 0x18U, /* VCO divider: multiplied by 48 */
},
};
CLOCK_SetMcgConfig(&mcgConfigStruct);
}
}
void APP_PowerPostSwitchHook(smc_power_state_t originPowerState, app_power_mode_t targetMode)
{
/* Restore the UART pins. */
if ((kAPP_PowerModeRun != targetMode) && (kAPP_PowerModeVlpr != targetMode))
{
/*
* Debug console RX pin is set to disable for current leakage, nee to re-configure pinmux.
* Debug console TX pin: Don't need to change.
*/
PORT_SetPinMux(DEBUG_CONSOLE_RX_PORT, DEBUG_CONSOLE_RX_PIN, DEBUG_CONSOLE_RX_PINMUX);
PORT_SetPinMux(DEBUG_CONSOLE_TX_PORT, DEBUG_CONSOLE_TX_PIN, DEBUG_CONSOLE_TX_PINMUX);
}
/*
* For some other platforms, if enter LLS mode from VLPR mode, when wakeup, the
* power mode is VLPR. But for some platforms, if enter LLS mode from VLPR mode,
* when wakeup, the power mode is RUN. In this case, the clock setting is still
* VLPR mode setting, so change to RUN mode setting here.
*/
if ((kSMC_PowerStateVlpr == originPowerState) && (kSMC_PowerStateRun == SMC_GetPowerModeState(SMC)))
{
APP_SetClockRunFromVlpr();
}
/*
* If enter stop modes when MCG in PEE mode, then after wakeup, the MCG is in PBE mode,
* need to enter PEE mode manually.
*/
if ((kAPP_PowerModeRun != targetMode) && (kAPP_PowerModeWait != targetMode) && (kAPP_PowerModeVlpw != targetMode) &&
(kAPP_PowerModeVlpr != targetMode))
{
if (kSMC_PowerStateRun == originPowerState)
{
/* Wait for PLL lock. */
while (!(kMCG_Pll0LockFlag & CLOCK_GetStatusFlags()))
{
}
CLOCK_SetPeeMode();
}
}
/* Return the PEE mode when come back to RUN mode from WAIT mode. */
if ((kAPP_PowerModeWait == targetMode) && (kSMC_PowerStateRun == originPowerState))
{
const mcg_config_t mcgConfigStruct = {
.mcgMode = kMCG_ModePEE, /* PEE - PLL Engaged External */
.irclkEnableMode = kMCG_IrclkEnable, /* MCGIRCLK enabled, MCGIRCLK disabled in STOP mode */
.ircs = kMCG_IrcSlow, /* Slow internal reference clock selected */
.fcrdiv = 0x0U, /* Fast IRC divider: divided by 1 */
.frdiv = 0x0U, /* FLL reference clock divider: divided by 32 */
.drs = kMCG_DrsLow, /* Low frequency range */
.dmx32 = kMCG_Dmx32Default, /* DCO has a default range of 25% */
.oscsel = kMCG_OscselOsc, /* Selects System Oscillator (OSCCLK) */
.pll0Config =
{
.enableMode = 0, /* MCGPLLCLK disabled */
.prdiv = 0x13U, /* PLL Reference divider: divided by 20 */
.vdiv = 0x18U, /* VCO divider: multiplied by 48 */
},
};
CLOCK_SetMcgConfig(&mcgConfigStruct);
}
APP_InitDebugConsole();
}
/*!
* @brief LLWU interrupt handler.
*/
void APP_LLWU_IRQHANDLER(void)
{
/* If wakeup by LPTMR. */
if (LLWU_GetInternalWakeupModuleFlag(APP_LLWU, LLWU_LPTMR_IDX))
{
/* Disable lptmr as a wakeup source, so that lptmr's IRQ Handler will be executed when reset from VLLSx mode. */
LLWU_EnableInternalModuleInterruptWakup(APP_LLWU, LLWU_LPTMR_IDX, false);
}
/* If wakeup by external pin. */
if (LLWU_GetExternalWakeupPinFlag(APP_LLWU, LLWU_WAKEUP_PIN_IDX))
{
/* Disable WAKEUP pin as a wakeup source, so that WAKEUP pin's IRQ Handler will be executed when reset from
* VLLSx mode. */
LLWU_ClearExternalWakeupPinFlag(APP_LLWU, LLWU_WAKEUP_PIN_IDX);
}
/* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
exception return operation might vector to incorrect interrupt */
__DSB();
}
void APP_LPTMR_IRQHANDLER(void)
{
if (kLPTMR_TimerInterruptEnable & LPTMR_GetEnabledInterrupts(APP_LPTMR))
{
LPTMR_DisableInterrupts(APP_LPTMR, kLPTMR_TimerInterruptEnable);
LPTMR_ClearStatusFlags(APP_LPTMR, kLPTMR_TimerCompareFlag);
LPTMR_StopTimer(APP_LPTMR);
}
/* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
exception return operation might vector to incorrect interrupt */
__DSB();
}
void APP_WAKEUP_BUTTON_IRQ_HANDLER(void)
{
if ((1U << APP_WAKEUP_BUTTON_GPIO_PIN) & PORT_GetPinsInterruptFlags(APP_WAKEUP_BUTTON_PORT))
{
/* Disable interrupt. */
PORT_SetPinInterruptConfig(APP_WAKEUP_BUTTON_PORT, APP_WAKEUP_BUTTON_GPIO_PIN, kPORT_InterruptOrDMADisabled);
PORT_ClearPinsInterruptFlags(APP_WAKEUP_BUTTON_PORT, (1U << APP_WAKEUP_BUTTON_GPIO_PIN));
}
/* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping
exception return operation might vector to incorrect interrupt */
__DSB();
}
/*!
* @brief Get input from user about wakeup timeout
*/
static uint8_t APP_GetWakeupTimeout(void)
{
uint8_t timeout;
while (1)
{
PRINTF("Select the wake up timeout in seconds.\r\n");
PRINTF("The allowed range is 1s ~ 9s.\r\n");
PRINTF("Eg. enter 5 to wake up in 5 seconds.\r\n");
PRINTF("\r\nWaiting for input timeout value...\r\n\r\n");
timeout = GETCHAR();
PRINTF("%c\r\n", timeout);
if ((timeout > '0') && (timeout <= '9'))
{
return timeout - '0';
}
PRINTF("Wrong value!\r\n");
}
}
/* Get wakeup source by user input. */
static app_wakeup_source_t APP_GetWakeupSource(void)
{
uint8_t ch;
while (1)
{
PRINTF("Select the wake up source:\r\n");
PRINTF("Press T for LPTMR - Low Power Timer\r\n");
PRINTF("Press S for switch/button %s. \r\n", APP_WAKEUP_BUTTON_NAME);
PRINTF("\r\nWaiting for key press..\r\n\r\n");
ch = GETCHAR();
if ((ch >= 'a') && (ch <= 'z'))
{
ch -= 'a' - 'A';
}
if (ch == 'T')
{
return kAPP_WakeupSourceLptmr;
}
else if (ch == 'S')
{
return kAPP_WakeupSourcePin;
}
else
{
PRINTF("Wrong value!\r\n");
}
}
}
/* Get wakeup timeout and wakeup source. */
void APP_GetWakeupConfig(app_power_mode_t targetMode)
{
/* Get wakeup source by user input. */
if (targetMode == kAPP_PowerModeVlls0)
{
/* In VLLS0 mode, the LPO is disabled, LPTMR could not work. */
PRINTF("Not support LPTMR wakeup because LPO is disabled in VLLS0 mode.\r\n");
s_wakeupSource = kAPP_WakeupSourcePin;
}
else
{
/* Get wakeup source by user input. */
s_wakeupSource = APP_GetWakeupSource();
}
if (kAPP_WakeupSourceLptmr == s_wakeupSource)
{
/* Wakeup source is LPTMR, user should input wakeup timeout value. */
s_wakeupTimeout = APP_GetWakeupTimeout();
PRINTF("Will wakeup in %d seconds.\r\n", s_wakeupTimeout);
}
else
{
PRINTF("Press %s to wake up.\r\n", APP_WAKEUP_BUTTON_NAME);
}
}
void APP_SetWakeupConfig(app_power_mode_t targetMode)
{
/* Set LPTMR timeout value. */
if (kAPP_WakeupSourceLptmr == s_wakeupSource)
{
LPTMR_SetTimerPeriod(APP_LPTMR, (LPO_CLK_FREQ * s_wakeupTimeout) - 1U);
LPTMR_StartTimer(APP_LPTMR);
}
/* Set the wakeup module. */
if (kAPP_WakeupSourceLptmr == s_wakeupSource)
{
LPTMR_EnableInterrupts(APP_LPTMR, kLPTMR_TimerInterruptEnable);
}
else
{
PORT_SetPinInterruptConfig(APP_WAKEUP_BUTTON_PORT, APP_WAKEUP_BUTTON_GPIO_PIN, APP_WAKEUP_BUTTON_IRQ_TYPE);
}
/* If targetMode is VLLS/LLS, setup LLWU. */
if ((kAPP_PowerModeWait != targetMode) && (kAPP_PowerModeVlpw != targetMode) &&
(kAPP_PowerModeVlps != targetMode) && (kAPP_PowerModeStop != targetMode))
{
if (kAPP_WakeupSourceLptmr == s_wakeupSource)
{
LLWU_EnableInternalModuleInterruptWakup(APP_LLWU, LLWU_LPTMR_IDX, true);
}
else
{
LLWU_SetExternalWakeupPinMode(APP_LLWU, LLWU_WAKEUP_PIN_IDX, LLWU_WAKEUP_PIN_TYPE);
}
NVIC_EnableIRQ(LLWU_IRQn);
}
}
void APP_ShowPowerMode(smc_power_state_t powerMode)
{
switch (powerMode)
{
case kSMC_PowerStateRun:
PRINTF(" Power mode: RUN\r\n");
break;
case kSMC_PowerStateVlpr:
PRINTF(" Power mode: VLPR\r\n");
break;
default:
PRINTF(" Power mode wrong\r\n");
break;
}
}
/*
* Check whether could switch to target power mode from current mode.
* Return true if could switch, return false if could not switch.
*/
bool APP_CheckPowerMode(smc_power_state_t curPowerState, app_power_mode_t targetPowerMode)
{
bool modeValid = true;
/*
* Check wether the mode change is allowed.
*
* 1. If current mode is HSRUN mode, the target mode must be RUN mode.
* 2. If current mode is RUN mode, the target mode must not be VLPW mode.
* 3. If current mode is VLPR mode, the target mode must not be HSRUN/WAIT/STOP mode.
* 4. If already in the target mode.
*/
switch (curPowerState)
{
case kSMC_PowerStateRun:
if (kAPP_PowerModeVlpw == targetPowerMode)
{
PRINTF("Could not enter VLPW mode from RUN mode.\r\n");
modeValid = false;
}
break;
case kSMC_PowerStateVlpr:
if ((kAPP_PowerModeWait == targetPowerMode) || (kAPP_PowerModeStop == targetPowerMode))
{
PRINTF("Could not enter HSRUN/STOP/WAIT modes from VLPR mode.\r\n");
modeValid = false;
}
break;
default:
PRINTF("Wrong power state.\r\n");
modeValid = false;
break;
}
if (!modeValid)
{
return false;
}
/* Don't need to change power mode if current mode is already the target mode. */
if (((kAPP_PowerModeRun == targetPowerMode) && (kSMC_PowerStateRun == curPowerState)) ||
((kAPP_PowerModeVlpr == targetPowerMode) && (kSMC_PowerStateVlpr == curPowerState)))
{
PRINTF("Already in the target power mode.\r\n");
return false;
}
return true;
}
/*
* Power mode switch.
*/
void APP_PowerModeSwitch(smc_power_state_t curPowerState, app_power_mode_t targetPowerMode)
{
smc_power_mode_vlls_config_t vlls_config;
vlls_config.enablePorDetectInVlls0 = true;
switch (targetPowerMode)
{
case kAPP_PowerModeVlpr:
APP_SetClockVlpr();
SMC_SetPowerModeVlpr(SMC, false);
while (kSMC_PowerStateVlpr != SMC_GetPowerModeState(SMC))
{
}
break;
case kAPP_PowerModeRun:
/* Power mode change. */
SMC_SetPowerModeRun(SMC);
while (kSMC_PowerStateRun != SMC_GetPowerModeState(SMC))
{
}
/* If enter RUN from VLPR, change clock after the power mode change. */
if (kSMC_PowerStateVlpr == curPowerState)
{
APP_SetClockRunFromVlpr();
}
break;
case kAPP_PowerModeWait:
SMC_PreEnterWaitModes();
SMC_SetPowerModeWait(SMC);
SMC_PostExitWaitModes();
break;
case kAPP_PowerModeStop:
SMC_PreEnterStopModes();
SMC_SetPowerModeStop(SMC, kSMC_PartialStop);
SMC_PostExitStopModes();
break;
case kAPP_PowerModeVlpw:
SMC_PreEnterWaitModes();
SMC_SetPowerModeVlpw(SMC);
SMC_PostExitWaitModes();
break;
case kAPP_PowerModeVlps:
SMC_PreEnterStopModes();
SMC_SetPowerModeVlps(SMC);
SMC_PostExitStopModes();
break;
case kAPP_PowerModeLls:
SMC_PreEnterStopModes();
SMC_SetPowerModeLls(SMC);
SMC_PostExitStopModes();
break;
case kAPP_PowerModeVlls0:
vlls_config.subMode = kSMC_StopSub0;
SMC_PreEnterStopModes();
SMC_SetPowerModeVlls(SMC, &vlls_config);
SMC_PostExitStopModes();
break;
case kAPP_PowerModeVlls1:
vlls_config.subMode = kSMC_StopSub1;
SMC_PreEnterStopModes();
SMC_SetPowerModeVlls(SMC, &vlls_config);
SMC_PostExitStopModes();
break;
case kAPP_PowerModeVlls2:
vlls_config.subMode = kSMC_StopSub2;
SMC_PreEnterStopModes();
SMC_SetPowerModeVlls(SMC, &vlls_config);
SMC_PostExitStopModes();
break;
case kAPP_PowerModeVlls3:
vlls_config.subMode = kSMC_StopSub3;
SMC_PreEnterStopModes();
SMC_SetPowerModeVlls(SMC, &vlls_config);
SMC_PostExitStopModes();
break;
default:
PRINTF("Wrong value");
break;
}
}
/*!
* @brief main demo function.
*/
int main(void)
{
uint32_t freq = 0;
uint8_t ch;
smc_power_state_t curPowerState;
app_power_mode_t targetPowerMode;
bool needSetWakeup; /* Need to set wakeup. */
/* Must configure pins before PMC_ClearPeriphIOIsolationFlag */
BOARD_InitPins();
/* Power related. */
SMC_SetPowerModeProtection(SMC, kSMC_AllowPowerModeAll);
if (kRCM_SourceWakeup & RCM_GetPreviousResetSources(RCM)) /* Wakeup from VLLS. */
{
PMC_ClearPeriphIOIsolationFlag(PMC);
NVIC_ClearPendingIRQ(LLWU_IRQn);
}
BOARD_InitBootClocks();
APP_InitDebugConsole();
BOARD_InitBootPeripherals();
NVIC_EnableIRQ(APP_WAKEUP_BUTTON_IRQ);
if (kRCM_SourceWakeup & RCM_GetPreviousResetSources(RCM)) /* Wakeup from VLLS. */
{
PRINTF("\r\nMCU wakeup from VLLS modes...\r\n");
}
while (1)
{
curPowerState = SMC_GetPowerModeState(SMC);
freq = CLOCK_GetFreq(kCLOCK_CoreSysClk);
PRINTF("\r\n#################### Power Mode Switch Demo ####################\n\r\n");
PRINTF(" Core Clock = %dHz \r\n", freq);
APP_ShowPowerMode(curPowerState);
PRINTF("\r\nSelect the desired operation \n\r\n");
PRINTF("Press %c for enter: RUN - Normal RUN mode\r\n", kAPP_PowerModeRun);
PRINTF("Press %c for enter: WAIT - Wait mode\r\n", kAPP_PowerModeWait);
PRINTF("Press %c for enter: STOP - Stop mode\r\n", kAPP_PowerModeStop);
PRINTF("Press %c for enter: VLPR - Very Low Power Run mode\r\n", kAPP_PowerModeVlpr);
PRINTF("Press %c for enter: VLPW - Very Low Power Wait mode\r\n", kAPP_PowerModeVlpw);
PRINTF("Press %c for enter: VLPS - Very Low Power Stop mode\r\n", kAPP_PowerModeVlps);
PRINTF("Press %c for enter: LLS/LLS3 - Low Leakage Stop mode\r\n", kAPP_PowerModeLls);
PRINTF("Press %c for enter: VLLS0 - Very Low Leakage Stop 0 mode\r\n", kAPP_PowerModeVlls0);
PRINTF("Press %c for enter: VLLS1 - Very Low Leakage Stop 1 mode\r\n", kAPP_PowerModeVlls1);
PRINTF("Press %c for enter: VLLS2 - Very Low Leakage Stop 2 mode\r\n", kAPP_PowerModeVlls2);
PRINTF("Press %c for enter: VLLS3 - Very Low Leakage Stop 3 mode\r\n", kAPP_PowerModeVlls3);
PRINTF("\r\nWaiting for power mode select..\r\n\r\n");
/* Wait for user response */
ch = GETCHAR();
if ((ch >= 'a') && (ch <= 'z'))
{
ch -= 'a' - 'A';
}
targetPowerMode = (app_power_mode_t)ch;
if ((targetPowerMode > kAPP_PowerModeMin) && (targetPowerMode < kAPP_PowerModeMax))
{
/* If could not set the target power mode, loop continue. */
if (!APP_CheckPowerMode(curPowerState, targetPowerMode))
{
continue;
}
/* If target mode is RUN/VLPR/HSRUN, don't need to set wakeup source. */
if ((kAPP_PowerModeRun == targetPowerMode) || (kAPP_PowerModeVlpr == targetPowerMode))
{
needSetWakeup = false;
}
else
{
needSetWakeup = true;
}
if (needSetWakeup)
{
APP_GetWakeupConfig(targetPowerMode);
}
APP_PowerPreSwitchHook(curPowerState, targetPowerMode);
if (needSetWakeup)
{
APP_SetWakeupConfig(targetPowerMode);
}
APP_PowerModeSwitch(curPowerState, targetPowerMode);
APP_PowerPostSwitchHook(curPowerState, targetPowerMode);
PRINTF("\r\nNext loop\r\n");
}
}
}
| 33.955966 | 120 | 0.606568 | [
"vector"
] |
2c6b0eaf8b254b7a34a1a2baf20a0ab419a6f612 | 1,925 | h | C | algorithms/medium/1452. People Whose List of Favorite Companies Is Not a Subset of Another List.h | MultivacX/letcode2020 | f86289f8718237303918a7705ae31625a12b68f6 | [
"MIT"
] | null | null | null | algorithms/medium/1452. People Whose List of Favorite Companies Is Not a Subset of Another List.h | MultivacX/letcode2020 | f86289f8718237303918a7705ae31625a12b68f6 | [
"MIT"
] | null | null | null | algorithms/medium/1452. People Whose List of Favorite Companies Is Not a Subset of Another List.h | MultivacX/letcode2020 | f86289f8718237303918a7705ae31625a12b68f6 | [
"MIT"
] | null | null | null | // 1452. People Whose List of Favorite Companies Is Not a Subset of Another List
// https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/
// Runtime: 276 ms, faster than 95.33% of C++ online submissions for People Whose List of Favorite Companies Is Not a Subset of Another List.
// Memory Usage: 53.8 MB, less than 63.08% of C++ online submissions for People Whose List of Favorite Companies Is Not a Subset of Another List.
class Solution {
public:
vector<int> peopleIndexes(vector<vector<string>>& favoriteCompanies) {
const int N = favoriteCompanies.size();
unordered_map<string, int> companies;
vector<vector<uint64_t>> fids(N);
for (int i = 0, company_id = 0; i < N; ++i) {
auto& ids = fids[i];
for (const auto& c : favoriteCompanies[i]) {
if (!companies.count(c)) {
companies.insert({c, company_id++});
}
int id = companies[c];
int n = id / 64 + 1;
int b = id % 64;
if (ids.size() < n) ids.resize(n);
ids[n - 1] |= (uint64_t)1 << b;
}
}
vector<int> ans;
for (int i = 0; i < N; ++i) {
const int M = fids[i].size();
bool isSubset = false;
for (int j = 0; j < N && !isSubset; ++j) {
if (i == j || M > fids[j].size()) continue;
int k = 0;
for (; k < M; ++k)
if ((fids[i][k] & fids[j][k]) != fids[i][k])
break;
if (k == M) isSubset = true;
}
if (!isSubset) ans.push_back(i);
}
// for (auto& s : fids) {
// for (auto id : s) cout << bitset<64>(id) << " ";
// cout << endl;
// }
return ans;
}
}; | 40.104167 | 145 | 0.482078 | [
"vector"
] |
2c77ac2fbe17fe79d7285ab7bc9cc92d9091d0e2 | 1,523 | h | C | chrome/browser/android/ntp/ntp_snippets_launcher.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | chrome/browser/android/ntp/ntp_snippets_launcher.h | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/android/ntp/ntp_snippets_launcher.h | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ANDROID_NTP_NTP_SNIPPETS_LAUNCHER_H_
#define CHROME_BROWSER_ANDROID_NTP_NTP_SNIPPETS_LAUNCHER_H_
#include "base/android/jni_android.h"
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/time/time.h"
#include "components/ntp_snippets/ntp_snippets_scheduler.h"
// Android implementation of ntp_snippets::NTPSnippetsScheduler.
// The NTPSnippetsLauncher singleton owns the Java SnippetsLauncher object, and
// is used to schedule the fetching of snippets. Runs on the UI thread.
class NTPSnippetsLauncher : public ntp_snippets::NTPSnippetsScheduler {
public:
static NTPSnippetsLauncher* Get();
static bool Register(JNIEnv* env);
// ntp_snippets::NTPSnippetsScheduler implementation.
bool Schedule(base::TimeDelta period_wifi_charging,
base::TimeDelta period_wifi,
base::TimeDelta period_fallback,
base::Time reschedule_time) override;
bool Unschedule() override;
private:
friend struct base::DefaultLazyInstanceTraits<NTPSnippetsLauncher>;
// Constructor and destructor marked private to enforce singleton.
NTPSnippetsLauncher();
virtual ~NTPSnippetsLauncher();
base::android::ScopedJavaGlobalRef<jobject> java_launcher_;
DISALLOW_COPY_AND_ASSIGN(NTPSnippetsLauncher);
};
#endif // CHROME_BROWSER_ANDROID_NTP_NTP_SNIPPETS_LAUNCHER_H_
| 35.418605 | 79 | 0.785292 | [
"object"
] |
2c7c65ab024a96154d5af782765913ed7a2cde09 | 29,342 | c | C | lib/kernel/printf.c | alexbatashev/pocl | 68273059e19462a061551f30a8a9e1a976adf178 | [
"MIT"
] | null | null | null | lib/kernel/printf.c | alexbatashev/pocl | 68273059e19462a061551f30a8a9e1a976adf178 | [
"MIT"
] | null | null | null | lib/kernel/printf.c | alexbatashev/pocl | 68273059e19462a061551f30a8a9e1a976adf178 | [
"MIT"
] | null | null | null | /* OpenCL built-in library: printf()
Copyright (c) 2013 Erik Schnetter <eschnetter@perimeterinstitute.ca>
Perimeter Institute for Theoretical Physics
Copyright (c) 2018 Michal Babej / Tampere University of Technology
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 "printf_base.h"
#include <stdarg.h>
#define OCL_C_AS
/* The OpenCL printf routine.
*
* For debugging
* Use as: DEBUG_PRINTF((fmt, args...)) -- note double parentheses!
int printf(const char *format, ...);
#define DEBUG_PRINTF(args) (printf args)
*/
#define DEBUG_PRINTF(args) ((void)0)
/**************************************************************************/
#define DEFINE_PRINT_INTS(NAME, INT_TYPE, UINT_TYPE) \
void __pocl_print_ints_##NAME (param_t *p, OCL_C_AS const void *vals, \
int n, int is_unsigned) \
{ \
DEBUG_PRINTF (("[printf:ints:n=%df]\n", n)); \
flags_t saved_user_flags = p->flags; \
for (size_t d = 0; d < n; ++d) \
{ \
DEBUG_PRINTF (("[printf:ints:d=%d]\n", d)); \
p->flags = saved_user_flags; \
if (d != 0) \
__pocl_printf_putcf (p, ','); \
if (is_unsigned) \
__pocl_printf_ulong ( \
p, (UINT_T) (((OCL_C_AS const UINT_TYPE *)vals)[d])); \
else \
__pocl_printf_long ( \
p, (INT_T) (((OCL_C_AS const INT_TYPE *)vals)[d])); \
} \
DEBUG_PRINTF (("[printf:ints:done]\n")); \
}
DEFINE_PRINT_INTS (uchar, int8_t, uint8_t)
DEFINE_PRINT_INTS (ushort, int16_t, uint16_t)
DEFINE_PRINT_INTS (uint, int32_t, uint32_t)
#ifdef cl_khr_int64
DEFINE_PRINT_INTS (ulong, int64_t, uint64_t)
#endif
#undef DEFINE_PRINT_INTS
/**************************************************************************/
/* Note: NANs are printed always positive.
* This is required to pass 1.2 conformance test. */
#define DEFINE_PRINT_FLOATS(FLOAT_TYPE) \
void __pocl_print_floats_##FLOAT_TYPE (param_t *p, \
OCL_C_AS const void *vals, int n) \
{ \
const char *NANs[2] = { "nan", "NAN" }; \
const char *INFs[2] = { "inf", "INF" }; \
\
DEBUG_PRINTF (("[printf:floats:n=%d]\n", n)); \
flags_t saved_user_flags = p->flags; \
for (int d = 0; d < n; ++d) \
{ \
DEBUG_PRINTF (("[printf:floats:d=%d]\n", d)); \
p->flags = saved_user_flags; \
if (d != 0) \
__pocl_printf_putcf (p, ','); \
FLOAT_T val = *((OCL_C_AS const FLOAT_TYPE *)vals + d); \
const char *other = NULL; \
if (val != val) \
other = NANs[p->flags.uc ? 1 : 0]; \
if (val == (-INFINITY)) \
{ \
val = INFINITY; \
p->flags.sign = 1; \
} \
if (val == (INFINITY)) \
other = INFs[p->flags.uc ? 1 : 0]; \
if (other) \
__pocl_printf_nonfinite (p, other); \
else \
__pocl_printf_float (p, val); \
} \
DEBUG_PRINTF (("[printf:floats:done]\n")); \
}
#ifdef cl_khr_fp16
DEFINE_PRINT_FLOATS (half)
#endif
DEFINE_PRINT_FLOATS (float)
#ifdef cl_khr_fp64
DEFINE_PRINT_FLOATS (double)
#endif
#undef DEFINE_PRINT_FLOATS
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
#define ERROR_STRING " printf format string error: 0x"
#define ERROR_NULL_AFTER_FORMAT_SIGN 0x11
#define ERROR_REPEATED_FLAG_MINUS 0x12
#define ERROR_REPEATED_FLAG_PLUS 0x13
#define ERROR_REPEATED_FLAG_SPACE 0x14
#define ERROR_REPEATED_FLAG_SHARP 0x15
#define ERROR_REPEATED_FLAG_ZERO 0x16
#define ERROR_FIELD_WIDTH_ZERO 0x17
#define ERROR_FIELD_WIDTH_OVERFLOW 0x18
#define ERROR_PRECISION_OVERFLOW 0x19
#define ERROR_VECTOR_LENGTH_ZERO 0x20
#define ERROR_VECTOR_LENGTH_OVERFLOW 0x21
#define ERROR_VECTOR_LENGTH_UNKNOWN 0x22
#define ERROR_VECTOR_LENGTH_WITHOUT_ELEMENT_SIZE 0x23
#define ERROR_HL_MODIFIER_USED_WITHOUT_VECTOR_LENGTH 0x24
#define ERROR_FLAGS_WITH_C_CONVERSION_SPECIFIER 0x25
#define ERROR_PRECISION_WITH_C_CONVERSION_SPECIFIER 0x25
#define ERROR_VECTOR_LENGTH_WITH_C_CONVERSION_SPECIFIER 0x25
#define ERROR_LENGTH_MODIFIER_WITH_C_CONVERSION_SPECIFIER 0x25
#define ERROR_FLAGS_WITH_S_CONVERSION_SPECIFIER 0x26
#define ERROR_VECTOR_LENGTH_WITH_S_CONVERSION_SPECIFIER 0x27
#define ERROR_LENGTH_MODIFIER_WITH_S_CONVERSION_SPECIFIER 0x28
#define ERROR_FLAGS_WITH_P_CONVERSION_SPECIFIER 0x29
#define ERROR_PRECISION_WITH_P_CONVERSION_SPECIFIER 0x30
#define ERROR_VECTOR_LENGTH_WITH_P_CONVERSION_SPECIFIER 0x31
#define ERROR_LENGTH_MODIFIER_WITH_P_CONVERSION_SPECIFIER 0x32
#define ERROR_UNKNOWN_CONVERSION_SPECIFIER 0x33
int
__pocl_printf_format_full (const OCL_CONSTANT_AS char *restrict format,
param_t *p, va_list ap)
{
DEBUG_PRINTF (("[printf:format=%s]\n", format));
char bf[BUFSIZE];
p->bf = bf;
char ch;
unsigned errcode;
while ((ch = *format++))
{
if (ch == '%')
{
ch = *format++;
if (ch == 0)
{
errcode = ERROR_NULL_AFTER_FORMAT_SIGN;
goto error;
}
if (ch == '%')
{
DEBUG_PRINTF (("[printf:%%]\n"));
__pocl_printf_putcf (p, '%'); /* literal % */
}
else
{
DEBUG_PRINTF (("[printf:arg]\n"));
// Flags
flags_t flags;
flags.align_left = 0;
flags.sign = 0;
flags.space = 0;
flags.alt = 0;
flags.zero = 0;
flags.uc = 0;
flags.always_sign = 0;
for (;;)
{
switch (ch)
{
case '-':
if (flags.align_left)
{
errcode = ERROR_REPEATED_FLAG_MINUS;
goto error;
}
flags.align_left = 1;
break;
case '+':
if (flags.always_sign)
{
errcode = ERROR_REPEATED_FLAG_PLUS;
goto error;
}
flags.always_sign = 1;
break;
case ' ':
if (flags.space)
{
errcode = ERROR_REPEATED_FLAG_SPACE;
goto error;
}
flags.space = 1;
break;
case '#':
if (flags.alt)
{
errcode = ERROR_REPEATED_FLAG_SHARP;
goto error;
}
flags.alt = 1;
break;
case '0':
if (flags.zero)
{
errcode = ERROR_REPEATED_FLAG_ZERO;
goto error;
}
if (flags.align_left == 0)
flags.zero = 1;
break;
default:
goto flags_done;
}
ch = *format++;
}
flags_done:;
DEBUG_PRINTF (
("[printf:flags:left=%d,plus=%d,space=%d,alt=%d,zero=%d]\n",
flags.align_left, flags.sign, flags.space, flags.alt,
flags.zero));
/* Field width */
size_t field_width = 0;
while (ch >= '0' && ch <= '9')
{
if (ch == '0' && field_width == 0)
{
errcode = ERROR_FIELD_WIDTH_ZERO;
goto error;
}
if (field_width > (INT_MAX - 9) / 10)
{
errcode = ERROR_FIELD_WIDTH_OVERFLOW;
goto error;
}
field_width = 10 * field_width + (ch - '0');
ch = *format++;
}
DEBUG_PRINTF (("[printf:width=%d]\n", field_width));
/* Precision */
int precision = -1;
if (ch == '.')
{
precision = 0;
ch = *format++;
while (ch >= '0' && ch <= '9')
{
if (precision > (INT_MAX - 9) / 10)
{
errcode = ERROR_PRECISION_OVERFLOW;
goto error;
}
precision = 10 * precision + (ch - '0');
ch = *format++;
}
}
DEBUG_PRINTF (("[printf:precision=%d]\n", precision));
// Vector specifier
size_t vector_length = 0;
if (ch == 'v')
{
ch = *format++;
while (ch >= '0' && ch <= '9')
{
if (ch == '0' && vector_length == 0)
{
errcode = ERROR_VECTOR_LENGTH_ZERO;
goto error;
}
if (vector_length > (INT_MAX - 9) / 10)
{
errcode = ERROR_VECTOR_LENGTH_OVERFLOW;
goto error;
}
vector_length = 10 * vector_length + (ch - '0');
ch = *format++;
}
if (!(vector_length == 2 || vector_length == 3
|| vector_length == 4 || vector_length == 8
|| vector_length == 16))
{
errcode = ERROR_VECTOR_LENGTH_UNKNOWN;
goto error;
}
}
DEBUG_PRINTF (("[printf:vector_length=%d]\n", vector_length));
/* Length modifier */
size_t length = 0;
if (ch == 'h')
{
ch = *format++;
if (ch == 'h')
{
ch = *format++;
length = 1; /* "hh" -> char */
}
else if (ch == 'l')
{
ch = *format++;
length = 4; /* "hl" -> int */
}
else
{
length = 2; /* "h" -> short */
}
}
else if (ch == 'l')
{
ch = *format++;
length = 8; /* "l" -> long */
}
if (vector_length > 0 && length == 0)
{
errcode = ERROR_VECTOR_LENGTH_WITHOUT_ELEMENT_SIZE;
goto error;
}
if (vector_length == 0 && length == 4)
{
errcode = ERROR_HL_MODIFIER_USED_WITHOUT_VECTOR_LENGTH;
goto error;
}
if (vector_length == 0)
vector_length = 1;
DEBUG_PRINTF (("[printf:length=%d]\n", length));
p->flags = flags;
p->conv = ch;
p->width = field_width;
p->precision = precision;
switch (ch)
{
/* Output integers */
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'X':
{
unsigned base = 10;
if (ch == 'x' || ch == 'X')
base = 16;
if (ch == 'o')
base = 8;
if (ch == 'X')
p->flags.uc = 1;
int is_unsigned = (ch == 'u') || (base != 10);
/* if a precision is specified, the 0 flag is ignored */
if (p->precision > 0)
p->flags.zero = 0; /* The default precision is 1. */
if (precision < 0)
precision = p->precision = 1;
p->base = base;
/* TODO: 3-size vector va-arg crashes LLVM when compiled with -O > 0 */
#define CALL_PRINT_INTS(WIDTH, PROMOTED_WIDTH) \
{ \
WIDTH##16 val; \
switch (vector_length) \
{ \
default: \
__builtin_unreachable (); \
case 1: \
val.s0 = va_arg (ap, PROMOTED_WIDTH); \
break; \
case 2: \
val.s01 = va_arg (ap, WIDTH##2); \
break; \
case 3: \
case 4: \
val.s0123 = va_arg (ap, WIDTH##4); \
break; \
case 8: \
val.lo = va_arg (ap, WIDTH##8); \
break; \
case 16: \
val = va_arg (ap, WIDTH##16); \
break; \
} \
__pocl_print_ints_##WIDTH (p, &val, vector_length, is_unsigned); \
}
DEBUG_PRINTF (("[printf:int:conversion=%c]\n", ch));
switch (length)
{
case 1:
CALL_PRINT_INTS (uchar, uint);
break;
case 2:
CALL_PRINT_INTS (ushort, uint);
break;
case 0:
case 4:
CALL_PRINT_INTS (uint, uint);
break;
#ifdef cl_khr_int64
case 8:
CALL_PRINT_INTS (ulong, ulong);
break;
#endif
default:
__builtin_unreachable ();
}
}
#undef CALL_PRINT_INTS
break;
/* Output floats */
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
case 'a':
case 'A':
{
p->base = 10;
if (ch < 'X')
{
p->flags.uc = 1;
p->conv += 32;
}
/* TODO: 3-size vector va-arg crashes LLVM when compiled with -O > 0 */
#define CALL_PRINT_FLOATS(WIDTH, PROMOTED_WIDTH) \
{ \
WIDTH##16 val; \
switch (vector_length) \
{ \
default: \
__builtin_unreachable (); \
case 1: \
val.s0 = va_arg (ap, PROMOTED_WIDTH); \
break; \
case 2: \
val.s01 = va_arg (ap, WIDTH##2); \
break; \
case 3: \
case 4: \
val.s0123 = va_arg (ap, WIDTH##4); \
break; \
case 8: \
val.lo = va_arg (ap, WIDTH##8); \
break; \
case 16: \
val = va_arg (ap, WIDTH##16); \
break; \
} \
__pocl_print_floats_##WIDTH (p, &val, vector_length); \
}
DEBUG_PRINTF (("[printf:float:conversion=%c]\n", ch));
switch (length)
{
default:
__builtin_unreachable ();
#ifdef cl_khr_fp16
/* case 2: CALL_PRINT_FLOATS(half, double); break; */
case 2:
goto error; /* not yet implemented */
#endif
case 0:
#ifdef cl_khr_fp64
case 4:
CALL_PRINT_FLOATS (float, double);
break;
case 8:
CALL_PRINT_FLOATS (double, double);
break;
#else
case 4:
CALL_PRINT_FLOATS (float, float);
break;
#endif
break;
}
}
#undef CALL_PRINT_FLOATS
break;
/* Output a character */
case 'c':
{
DEBUG_PRINTF (("[printf:char]\n"));
if (flags.always_sign || flags.space || flags.alt
|| flags.zero)
{
errcode = ERROR_FLAGS_WITH_C_CONVERSION_SPECIFIER;
goto error;
}
DEBUG_PRINTF (("[printf:char1]\n"));
if (precision >= 0)
{
errcode = ERROR_PRECISION_WITH_C_CONVERSION_SPECIFIER;
goto error;
}
DEBUG_PRINTF (("[printf:char2]\n"));
if (vector_length != 1)
{
errcode
= ERROR_VECTOR_LENGTH_WITH_C_CONVERSION_SPECIFIER;
goto error;
}
DEBUG_PRINTF (("[printf:char3]\n"));
if (length != 0)
{
errcode
= ERROR_LENGTH_MODIFIER_WITH_C_CONVERSION_SPECIFIER;
goto error;
}
DEBUG_PRINTF (("[printf:char4]\n"));
/* The int argument is converted to an unsigned char, and
* the resulting character is written */
int i = va_arg (ap, int);
bf[0] = (char)i;
bf[1] = 0;
__pocl_printf_putchw (p);
break;
}
/**************************************************************************/
/* Output a string */
case 's':
{
if (flags.always_sign || flags.space || flags.alt
|| flags.zero)
{
errcode = ERROR_FLAGS_WITH_S_CONVERSION_SPECIFIER;
goto error;
}
if (vector_length != 1)
{
errcode
= ERROR_VECTOR_LENGTH_WITH_S_CONVERSION_SPECIFIER;
goto error;
}
if (length != 0)
{
errcode
= ERROR_LENGTH_MODIFIER_WITH_S_CONVERSION_SPECIFIER;
goto error;
}
OCL_C_AS const char *val
= va_arg (ap, OCL_C_AS const char *);
if (val == 0)
__pocl_printf_puts_ljust (p, "(null)", field_width,
precision);
else if (flags.align_left)
__pocl_printf_puts_ljust (p, val, field_width,
precision);
else
__pocl_printf_puts_rjust (p, val, field_width,
precision);
break;
}
/**************************************************************************/
/* Output a pointer */
case 'p':
{
if (flags.always_sign || flags.space || flags.alt
|| flags.zero)
{
errcode = ERROR_FLAGS_WITH_P_CONVERSION_SPECIFIER;
goto error;
}
if (precision >= 0)
{
errcode = ERROR_PRECISION_WITH_P_CONVERSION_SPECIFIER;
goto error;
}
if (vector_length != 1)
{
errcode
= ERROR_VECTOR_LENGTH_WITH_P_CONVERSION_SPECIFIER;
goto error;
}
if (length != 0)
{
errcode
= ERROR_LENGTH_MODIFIER_WITH_P_CONVERSION_SPECIFIER;
goto error;
}
OCL_C_AS const void *val
= va_arg (ap, OCL_C_AS const void *);
__pocl_printf_ptr (p, val);
break;
}
/**************************************************************************/
default:
{
errcode = ERROR_UNKNOWN_CONVERSION_SPECIFIER;
goto error;
}
}
}
}
else
{
DEBUG_PRINTF (("[printf:literal]\n"));
__pocl_printf_putcf (p, ch);
}
}
DEBUG_PRINTF (("[printf:done]\n"));
return 0;
error:;
DEBUG_PRINTF (("[printf:error]\n"));
const char *err_str = ERROR_STRING;
__pocl_printf_puts (p, err_str);
char c1 = '0' + (char)(errcode >> 4);
char c2 = '0' + (char)(errcode & 7);
__pocl_printf_putcf (p, c1);
__pocl_printf_putcf (p, c2);
__pocl_printf_putcf (p, '\n');
return -1;
}
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
/* This is the actual printf function that will be used,
* after the external (buffer) variables are handled in a LLVM pass. */
int
__pocl_printf (char *restrict __buffer, uint32_t *__buffer_index,
uint32_t __buffer_capacity,
const OCL_CONSTANT_AS char *restrict fmt, ...)
{
param_t p = { 0 };
p.printf_buffer = __buffer;
p.printf_buffer_capacity = __buffer_capacity;
p.printf_buffer_index = *__buffer_index;
va_list va;
va_start (va, fmt);
__pocl_printf_format_full (fmt, &p, va);
va_end (va);
*__buffer_index = p.printf_buffer_index;
return 0;
}
/**************************************************************************/
extern char *_printf_buffer;
extern uint32_t *_printf_buffer_position;
extern uint32_t _printf_buffer_capacity;
/* This is a placeholder printf function that will be replaced by calls
* to __pocl_printf(), after a LLVM pass handles the hidden arguments.
* both __pocl_printf and __pocl_printf_format_simple must be referenced
* here, so that the kernel library linker pulls them in. */
int
printf (const OCL_CONSTANT_AS char *restrict fmt, ...)
{
va_list va;
va_start (va, fmt);
__pocl_printf_format_full (fmt, NULL, va);
va_end (va);
__pocl_printf (_printf_buffer, _printf_buffer_position,
_printf_buffer_capacity, NULL);
return 0;
}
/**************************************************************************/
| 39.975477 | 94 | 0.352328 | [
"vector"
] |
2c7f5e363140d7a630f7ff718710c22a3b3b4740 | 3,314 | h | C | Sources/API/App/clanapp.h | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/API/App/clanapp.h | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/API/App/clanapp.h | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | /*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#pragma once
#include <vector>
#include <string>
#include <memory>
namespace clan
{
/// \addtogroup clanApp_System clanApp System
/// \{
/// \brief Base class for the application object
///
/// All applications using the clanApp module need to inherit from this class. See ApplicationInstance for more information.
class Application
{
public:
virtual ~Application() { }
/// \brief Main loop update handler
///
/// Once the target environment has been initialized this function is called continously to update and render the application.
/// If the function returns false the main loop will end and the application will exit.
virtual bool update() { return true; }
/// \brief Set update handler to wait a certain amount of milliseconds between each update
static void use_timeout_timing(int timeout_ms);
/// \brief Returns the command line arguments passed to the application
static const std::vector<std::string> &main_args();
};
class ApplicationInstancePrivate
{
public:
ApplicationInstancePrivate(bool catch_exceptions = true);
virtual std::unique_ptr<Application> create() = 0;
};
/// \brief Helper class to create cross platform applications
///
/// To use this class, inherit from Application and make a single global instance of ApplicationInstance<YourClass>.
///
/// \code
/// class MyApplication : public clan::Application
/// {
/// public:
/// bool update() override;
/// };
///
/// ApplicationInstance<MyApplication> clanapp;
/// \endcode
/// If you do not want exceptions to be automatically caught, pass "false" to the optional catch_exceptions parameter in Application\n
/// Your program does not have to use this class. For more advanced usage use a normal main function for the target platform and interface with the RunLoop class in clanDisplay\n
template<typename ApplicationClass>
class ApplicationInstance : ApplicationInstancePrivate
{
public:
/// \brief Constructor
ApplicationInstance(bool catch_exceptions = true) : ApplicationInstancePrivate(catch_exceptions)
{
}
private:
std::unique_ptr<Application> create() override
{
return std::unique_ptr<Application>(new ApplicationClass());
}
};
/// \}
}
| 32.811881 | 179 | 0.732046 | [
"render",
"object",
"vector"
] |
2c86247b917d503884385df4cdad5ab63aad0d5d | 22,885 | c | C | examples/idas/serial/idasRoberts_ASAi_dns.c | chrispbradley/sundials | 8242ba0b361e285b0f826fc3e077e0d8e3e81ee2 | [
"BSD-3-Clause"
] | 36 | 2022-02-02T00:26:38.000Z | 2022-03-13T06:20:47.000Z | examples/idas/serial/idasRoberts_ASAi_dns.c | chrispbradley/sundials | 8242ba0b361e285b0f826fc3e077e0d8e3e81ee2 | [
"BSD-3-Clause"
] | 9 | 2022-02-02T01:41:33.000Z | 2022-03-09T17:06:14.000Z | examples/idas/serial/idasRoberts_ASAi_dns.c | chrispbradley/sundials | 8242ba0b361e285b0f826fc3e077e0d8e3e81ee2 | [
"BSD-3-Clause"
] | 3 | 2022-02-03T12:41:46.000Z | 2022-03-13T06:21:01.000Z | /* -----------------------------------------------------------------
* Programmer(s): Radu Serban and Cosmin Petra @ LLNL
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2022, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
* Adjoint sensitivity example problem.
*
* This simple example problem for IDAS, due to Robertson,
* is from chemical kinetics, and consists of the following three
* equations:
*
* dy1/dt + p1*y1 - p2*y2*y3 = 0
* dy2/dt - p1*y1 + p2*y2*y3 + p3*y2**2 = 0
* y1 + y2 + y3 - 1 = 0
*
* on the interval from t = 0.0 to t = 4.e10, with initial
* conditions: y1 = 1, y2 = y3 = 0.The reaction rates are: p1=0.04,
* p2=1e4, and p3=3e7
*
* It uses a scalar relative tolerance and a vector absolute
* tolerance.
*
* IDAS can also compute sensitivities with respect to
* the problem parameters p1, p2, and p3 of the following quantity:
* G = int_t0^t1 g(t,p,y) dt
* where
* g(t,p,y) = y3
*
* The gradient dG/dp is obtained as:
* dG/dp = int_t0^t1 (g_p - lambda^T F_p ) dt -
* lambda^T*F_y'*y_p | _t0^t1
* = int_t0^t1 (lambda^T*F_p) dt
* where lambda and are solutions of the adjoint system:
* d(lambda^T * F_y' )/dt -lambda^T F_y = -g_y
*
* During the backward integration, IDAS also evaluates G as
* G = - phi(t0)
* where
* d(phi)/dt = g(t,y,p)
* phi(t1) = 0
* -----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <idas/idas.h> /* prototypes for IDA fcts., consts. */
#include <nvector/nvector_serial.h> /* access to serial N_Vector */
#include <sunmatrix/sunmatrix_dense.h> /* access to dense SUNMatrix */
#include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver */
#include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */
#include <sundials/sundials_math.h> /* defs. of SUNRabs, SUNRexp, etc. */
/* Accessor macros */
#define Ith(v,i) NV_Ith_S(v,i-1) /* i-th vector component i= 1..NEQ */
#define IJth(A,i,j) SM_ELEMENT_D(A,i-1,j-1) /* (i,j)-th matrix component i,j = 1..NEQ */
/* Problem Constants */
#define NEQ 3 /* number of equations */
#define RTOL RCONST(1e-06) /* scalar relative tolerance */
#define ATOL1 RCONST(1e-08) /* vector absolute tolerance components */
#define ATOL2 RCONST(1e-12)
#define ATOL3 RCONST(1e-08)
#define ATOLA RCONST(1e-08) /* absolute tolerance for adjoint vars. */
#define ATOLQ RCONST(1e-06) /* absolute tolerance for quadratures */
#define T0 RCONST(0.0) /* initial time */
#define TOUT RCONST(4e10) /* final time */
#define TB1 RCONST(50.0) /* starting point for adjoint problem */
#define TB2 TOUT /* starting point for adjoint problem */
#define T1B RCONST(49.0) /* for IDACalcICB */
#define STEPS 100 /* number of steps between check points */
#define NP 3 /* number of problem parameters */
#define ONE RCONST(1.0)
#define ZERO RCONST(0.0)
/* Type : UserData */
typedef struct {
realtype p[3];
} *UserData;
/* Prototypes of user-supplied functions */
static int res(realtype t, N_Vector yy, N_Vector yp,
N_Vector resval, void *user_data);
static int Jac(realtype t, realtype cj,
N_Vector yy, N_Vector yp, N_Vector resvec,
SUNMatrix J, void *user_data,
N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
static int rhsQ(realtype t, N_Vector yy, N_Vector yp, N_Vector qdot, void *user_data);
static int ewt(N_Vector y, N_Vector w, void *user_data);
static int resB(realtype tt,
N_Vector yy, N_Vector yp,
N_Vector yyB, N_Vector ypB, N_Vector rrB,
void *user_dataB);
static int JacB(realtype tt, realtype cjB,
N_Vector yy, N_Vector yp,
N_Vector yyB, N_Vector ypB, N_Vector rrB,
SUNMatrix JB, void *user_data,
N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B);
static int rhsQB(realtype tt,
N_Vector yy, N_Vector yp,
N_Vector yyB, N_Vector ypB,
N_Vector rrQB, void *user_dataB);
/* Prototypes of private functions */
static void PrintOutput(realtype tfinal, N_Vector yB, N_Vector ypB, N_Vector qB);
static int check_retval(void *returnvalue, const char *funcname, int opt);
/*
*--------------------------------------------------------------------
* MAIN PROGRAM
*--------------------------------------------------------------------
*/
int main(int argc, char *argv[])
{
SUNContext ctx;
UserData data;
void *ida_mem;
SUNMatrix A, AB;
SUNLinearSolver LS, LSB;
realtype reltolQ, abstolQ;
N_Vector yy, yp, q;
N_Vector yyTB1, ypTB1;
N_Vector id;
int steps;
int indexB;
realtype reltolB, abstolB, abstolQB;
N_Vector yB, ypB, qB;
realtype time;
int retval, ncheck;
IDAadjCheckPointRec *ckpnt;
long int nst, nstB;
data = NULL;
ckpnt = NULL;
ida_mem = NULL;
A = AB = NULL;
LS = LSB = NULL;
yy = yp = yB = qB = NULL;
/* Print problem description */
printf("\nAdjoint Sensitivity Example for Chemical Kinetics\n");
printf("-------------------------------------------------\n\n");
printf("DAE: dy1/dt + p1*y1 - p2*y2*y3 = 0\n");
printf(" dy2/dt - p1*y1 + p2*y2*y3 + p3*(y2)^2 = 0\n");
printf(" y1 + y2 + y3 = 0\n\n");
printf("Find dG/dp for\n");
printf(" G = int_t0^tB0 g(t,p,y) dt\n");
printf(" g(t,p,y) = y3\n\n\n");
/* Create the SUNDIALS context object for this simulation */
retval = SUNContext_Create(NULL, &ctx);
if (check_retval(&retval, "SUNContext_Create", 1)) return 1;
/* User data structure */
data = (UserData) malloc(sizeof *data);
if (check_retval((void *)data, "malloc", 2)) return(1);
data->p[0] = RCONST(0.04);
data->p[1] = RCONST(1.0e4);
data->p[2] = RCONST(3.0e7);
/* Initialize y */
yy = N_VNew_Serial(NEQ, ctx);
if (check_retval((void *)yy, "N_VNew_Serial", 0)) return(1);
Ith(yy,1) = ONE;
Ith(yy,2) = ZERO;
Ith(yy,3) = ZERO;
/* Initialize yprime */
yp = N_VClone(yy);
if (check_retval((void *)yp, "N_VNew_Serial", 0)) return(1);
Ith(yp,1) = RCONST(-0.04);
Ith(yp,2) = RCONST( 0.04);
Ith(yp,3) = ZERO;
/* Initialize q */
q = N_VNew_Serial(1, ctx);
if (check_retval((void *)q, "N_VNew_Serial", 0)) return(1);
Ith(q,1) = ZERO;
/* Set the scalar realtive and absolute tolerances reltolQ and abstolQ */
reltolQ = RTOL;
abstolQ = ATOLQ;
/* Create and allocate IDAS memory for forward run */
printf("Create and allocate IDAS memory for forward runs\n");
ida_mem = IDACreate(ctx);
if (check_retval((void *)ida_mem, "IDACreate", 0)) return(1);
retval = IDAInit(ida_mem, res, T0, yy, yp);
if (check_retval(&retval, "IDAInit", 1)) return(1);
retval = IDAWFtolerances(ida_mem, ewt);
if (check_retval(&retval, "IDAWFtolerances", 1)) return(1);
retval = IDASetUserData(ida_mem, data);
if (check_retval(&retval, "IDASetUserData", 1)) return(1);
/* Create dense SUNMatrix for use in linear solves */
A = SUNDenseMatrix(NEQ, NEQ, ctx);
if(check_retval((void *)A, "SUNDenseMatrix", 0)) return(1);
/* Create dense SUNLinearSolver object */
LS = SUNLinSol_Dense(yy, A, ctx);
if(check_retval((void *)LS, "SUNLinSol_Dense", 0)) return(1);
/* Attach the matrix and linear solver */
retval = IDASetLinearSolver(ida_mem, LS, A);
if(check_retval(&retval, "IDASetLinearSolver", 1)) return(1);
/* Set the user-supplied Jacobian routine */
retval = IDASetJacFn(ida_mem, Jac);
if(check_retval(&retval, "IDASetJacFn", 1)) return(1);
/* Setup quadrature integration */
retval = IDAQuadInit(ida_mem, rhsQ, q);
if (check_retval(&retval, "IDAQuadInit", 1)) return(1);
retval = IDAQuadSStolerances(ida_mem, reltolQ, abstolQ);
if (check_retval(&retval, "IDAQuadSStolerances", 1)) return(1);
retval = IDASetQuadErrCon(ida_mem, SUNTRUE);
if (check_retval(&retval, "IDASetQuadErrCon", 1)) return(1);
/* Call IDASetMaxNumSteps to set the maximum number of steps the
* solver will take in an attempt to reach the next output time
* during forward integration. */
retval = IDASetMaxNumSteps(ida_mem, 2500);
if (check_retval(&retval, "IDASetMaxNumSteps", 1)) return(1);
/* Allocate global memory */
steps = STEPS;
retval = IDAAdjInit(ida_mem, steps, IDA_HERMITE);
/*retval = IDAAdjInit(ida_mem, steps, IDA_POLYNOMIAL);*/
if (check_retval(&retval, "IDAAdjInit", 1)) return(1);
/* Perform forward run */
printf("Forward integration ... ");
/* Integrate till TB1 and get the solution (y, y') at that time. */
retval = IDASolveF(ida_mem, TB1, &time, yy, yp, IDA_NORMAL, &ncheck);
if (check_retval(&retval, "IDASolveF", 1)) return(1);
yyTB1 = N_VClone(yy);
ypTB1 = N_VClone(yp);
/* Save the states at t=TB1. */
N_VScale(ONE, yy, yyTB1);
N_VScale(ONE, yp, ypTB1);
/* Continue integrating till TOUT is reached. */
retval = IDASolveF(ida_mem, TOUT, &time, yy, yp, IDA_NORMAL, &ncheck);
if (check_retval(&retval, "IDASolveF", 1)) return(1);
retval = IDAGetNumSteps(ida_mem, &nst);
if (check_retval(&retval, "IDAGetNumSteps", 1)) return(1);
printf("done ( nst = %ld )\n",nst);
retval = IDAGetQuad(ida_mem, &time, q);
if (check_retval(&retval, "IDAGetQuad", 1)) return(1);
printf("--------------------------------------------------------\n");
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("G: %12.4Le \n",Ith(q,1));
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("G: %12.4e \n",Ith(q,1));
#else
printf("G: %12.4e \n",Ith(q,1));
#endif
printf("--------------------------------------------------------\n\n");
/* Test check point linked list
(uncomment next block to print check point information) */
/*
{
int i;
printf("\nList of Check Points (ncheck = %d)\n\n", ncheck);
ckpnt = (IDAadjCheckPointRec *) malloc ( (ncheck+1)*sizeof(IDAadjCheckPointRec));
IDAGetAdjCheckPointsInfo(ida_mem, ckpnt);
for (i=0;i<=ncheck;i++) {
printf("Address: %p\n",ckpnt[i].my_addr);
printf("Next: %p\n",ckpnt[i].next_addr);
printf("Time interval: %le %le\n",ckpnt[i].t0, ckpnt[i].t1);
printf("Step number: %ld\n",ckpnt[i].nstep);
printf("Order: %d\n",ckpnt[i].order);
printf("Step size: %le\n",ckpnt[i].step);
printf("\n");
}
}
*/
/* Create BACKWARD problem. */
/* Allocate yB (i.e. lambda_0). */
yB = N_VClone(yy);
if (check_retval((void *)yB, "N_VNew_Serial", 0)) return(1);
/* Consistently initialize yB. */
Ith(yB,1) = ZERO;
Ith(yB,2) = ZERO;
Ith(yB,3) = ONE;
/* Allocate ypB (i.e. lambda'_0). */
ypB = N_VClone(yy);
if (check_retval((void *)ypB, "N_VNew_Serial", 0)) return(1);
/* Consistently initialize ypB. */
Ith(ypB,1) = ONE;
Ith(ypB,2) = ONE;
Ith(ypB,3) = ZERO;
/* Set the scalar relative tolerance reltolB */
reltolB = RTOL;
/* Set the scalar absolute tolerance abstolB */
abstolB = ATOLA;
/* Set the scalar absolute tolerance abstolQB */
abstolQB = ATOLQ;
/* Create and allocate IDAS memory for backward run */
printf("Create and allocate IDAS memory for backward run\n");
retval = IDACreateB(ida_mem, &indexB);
if (check_retval(&retval, "IDACreateB", 1)) return(1);
retval = IDAInitB(ida_mem, indexB, resB, TB2, yB, ypB);
if (check_retval(&retval, "IDAInitB", 1)) return(1);
retval = IDASStolerancesB(ida_mem, indexB, reltolB, abstolB);
if (check_retval(&retval, "IDASStolerancesB", 1)) return(1);
retval = IDASetUserDataB(ida_mem, indexB, data);
if (check_retval(&retval, "IDASetUserDataB", 1)) return(1);
retval = IDASetMaxNumStepsB(ida_mem, indexB, 1000);
if (check_retval(&retval, "IDASetMaxNumStepsB", 1)) return(1);
/* Create dense SUNMatrix for use in linear solves */
AB = SUNDenseMatrix(NEQ, NEQ, ctx);
if(check_retval((void *)AB, "SUNDenseMatrix", 0)) return(1);
/* Create dense SUNLinearSolver object */
LSB = SUNLinSol_Dense(yB, AB, ctx);
if(check_retval((void *)LSB, "SUNLinSol_Dense", 0)) return(1);
/* Attach the matrix and linear solver */
retval = IDASetLinearSolverB(ida_mem, indexB, LSB, AB);
if(check_retval(&retval, "IDASetLinearSolverB", 1)) return(1);
/* Set the user-supplied Jacobian routine */
retval = IDASetJacFnB(ida_mem, indexB, JacB);
if(check_retval(&retval, "IDASetJacFnB", 1)) return(1);
/* Quadrature for backward problem. */
/* Initialize qB */
qB = N_VNew_Serial(NP, ctx);
if (check_retval((void *)qB, "N_VNew", 0)) return(1);
Ith(qB,1) = ZERO;
Ith(qB,2) = ZERO;
Ith(qB,3) = ZERO;
retval = IDAQuadInitB(ida_mem, indexB, rhsQB, qB);
if (check_retval(&retval, "IDAQuadInitB", 1)) return(1);
retval = IDAQuadSStolerancesB(ida_mem, indexB, reltolB, abstolQB);
if (check_retval(&retval, "IDAQuadSStolerancesB", 1)) return(1);
/* Include quadratures in error control. */
retval = IDASetQuadErrConB(ida_mem, indexB, SUNTRUE);
if (check_retval(&retval, "IDASetQuadErrConB", 1)) return(1);
/* Backward Integration */
printf("Backward integration ... ");
retval = IDASolveB(ida_mem, T0, IDA_NORMAL);
if (check_retval(&retval, "IDASolveB", 1)) return(1);
IDAGetNumSteps(IDAGetAdjIDABmem(ida_mem, indexB), &nstB);
printf("done ( nst = %ld )\n", nstB);
retval = IDAGetB(ida_mem, indexB, &time, yB, ypB);
if (check_retval(&retval, "IDAGetB", 1)) return(1);
retval = IDAGetQuadB(ida_mem, indexB, &time, qB);
if (check_retval(&retval, "IDAGetB", 1)) return(1);
PrintOutput(TB2, yB, ypB, qB);
/* Reinitialize backward phase and start from a different time (TB1). */
printf("Re-initialize IDAS memory for backward run\n");
/* Both algebraic part from y and the entire y' are computed by IDACalcIC. */
Ith(yB,1) = ZERO;
Ith(yB,2) = ZERO;
Ith(yB,3) = RCONST(0.50); /* not consistent */
/* Rough guess for ypB. */
Ith(ypB,1) = RCONST(0.80);
Ith(ypB,2) = RCONST(0.75);
Ith(ypB,3) = ZERO;
/* Initialize qB */
Ith(qB,1) = ZERO;
Ith(qB,2) = ZERO;
Ith(qB,3) = ZERO;
retval = IDAReInitB(ida_mem, indexB, TB1, yB, ypB);
if (check_retval(&retval, "IDAReInitB", 1)) return(1);
/* Also reinitialize quadratures. */
retval = IDAQuadReInitB(ida_mem, indexB, qB);
if (check_retval(&retval, "IDAQuadReInitB", 1)) return(1);
/* Use IDACalcICB to compute consistent initial conditions
for this backward problem. */
id = N_VClone(yy);
Ith(id,1) = 1.0;
Ith(id,2) = 1.0;
Ith(id,3) = 0.0;
/* Specify which variables are differential (1) and which algebraic (0).*/
retval = IDASetIdB(ida_mem, indexB, id);
if (check_retval(&retval, "IDASetId", 1)) return(1);
retval = IDACalcICB(ida_mem, indexB, T1B, yyTB1, ypTB1);
if (check_retval(&retval, "IDACalcICB", 1)) return(1);
/* Get the consistent IC found by IDAS. */
retval = IDAGetConsistentICB(ida_mem, indexB, yB, ypB);
if (check_retval(&retval, "IDAGetConsistentICB", 1)) return(1);
printf("Backward integration ... ");
retval = IDASolveB(ida_mem, T0, IDA_NORMAL);
if (check_retval(&retval, "IDASolveB", 1)) return(1);
IDAGetNumSteps(IDAGetAdjIDABmem(ida_mem, indexB), &nstB);
printf("done ( nst = %ld )\n", nstB);
retval = IDAGetB(ida_mem, indexB, &time, yB, ypB);
if (check_retval(&retval, "IDAGetB", 1)) return(1);
retval = IDAGetQuadB(ida_mem, indexB, &time, qB);
if (check_retval(&retval, "IDAGetQuadB", 1)) return(1);
PrintOutput(TB1, yB, ypB, qB);
/* Free any memory used.*/
printf("Free memory\n\n");
IDAFree(&ida_mem);
SUNLinSolFree(LS);
SUNMatDestroy(A);
SUNLinSolFree(LSB);
SUNMatDestroy(AB);
N_VDestroy(yy);
N_VDestroy(yp);
N_VDestroy(q);
N_VDestroy(yB);
N_VDestroy(ypB);
N_VDestroy(qB);
N_VDestroy(id);
N_VDestroy(yyTB1);
N_VDestroy(ypTB1);
if (ckpnt != NULL) free(ckpnt);
free(data);
SUNContext_Free(&ctx);
return(0);
}
/*
*--------------------------------------------------------------------
* FUNCTIONS CALLED BY IDAS
*--------------------------------------------------------------------
*/
/*
* f routine. Compute f(t,y).
*/
static int res(realtype t, N_Vector yy, N_Vector yp, N_Vector resval, void *user_data)
{
realtype y1, y2, y3, yp1, yp2, *rval;
UserData data;
realtype p1, p2, p3;
y1 = Ith(yy,1); y2 = Ith(yy,2); y3 = Ith(yy,3);
yp1 = Ith(yp,1); yp2 = Ith(yp,2);
rval = N_VGetArrayPointer(resval);
data = (UserData) user_data;
p1 = data->p[0]; p2 = data->p[1]; p3 = data->p[2];
rval[0] = p1*y1-p2*y2*y3;
rval[1] = -rval[0] + p3*y2*y2 + yp2;
rval[0]+= yp1;
rval[2] = y1+y2+y3-1;
return(0);
}
/*
* Jacobian routine. Compute J(t,y).
*/
static int Jac(realtype t, realtype cj,
N_Vector yy, N_Vector yp, N_Vector resvec,
SUNMatrix J, void *user_data,
N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
{
realtype y2, y3;
UserData data;
realtype p1, p2, p3;
y2 = Ith(yy,2); y3 = Ith(yy,3);
data = (UserData) user_data;
p1 = data->p[0]; p2 = data->p[1]; p3 = data->p[2];
IJth(J,1,1) = p1+cj;
IJth(J,2,1) = -p1;
IJth(J,3,1) = ONE;
IJth(J,1,2) = -p2*y3;
IJth(J,2,2) = p2*y3+2*p3*y2+cj;
IJth(J,3,2) = ONE;
IJth(J,1,3) = -p2*y2;
IJth(J,2,3) = p2*y2;
IJth(J,3,3) = ONE;
return(0);
}
/*
* rhsQ routine. Compute fQ(t,y).
*/
static int rhsQ(realtype t, N_Vector yy, N_Vector yp, N_Vector qdot, void *user_data)
{
Ith(qdot,1) = Ith(yy,3);
return(0);
}
/*
* EwtSet function. Computes the error weights at the current solution.
*/
static int ewt(N_Vector y, N_Vector w, void *user_data)
{
int i;
realtype yy, ww, rtol, atol[3];
rtol = RTOL;
atol[0] = ATOL1;
atol[1] = ATOL2;
atol[2] = ATOL3;
for (i=1; i<=3; i++) {
yy = Ith(y,i);
ww = rtol * SUNRabs(yy) + atol[i-1];
if (ww <= 0.0) return (-1);
Ith(w,i) = 1.0/ww;
}
return(0);
}
/*
* resB routine.
*/
static int resB(realtype tt,
N_Vector yy, N_Vector yp,
N_Vector yyB, N_Vector ypB, N_Vector rrB,
void *user_dataB)
{
UserData data;
realtype y2, y3;
realtype p1, p2, p3;
realtype l1, l2, l3;
realtype lp1, lp2;
realtype l21;
data = (UserData) user_dataB;
/* The p vector */
p1 = data->p[0]; p2 = data->p[1]; p3 = data->p[2];
/* The y vector */
y2 = Ith(yy,2); y3 = Ith(yy,3);
/* The lambda vector */
l1 = Ith(yyB,1); l2 = Ith(yyB,2); l3 = Ith(yyB,3);
/* The lambda dot vector */
lp1 = Ith(ypB,1); lp2 = Ith(ypB,2);
/* Temporary variables */
l21 = l2-l1;
/* Load residual. */
Ith(rrB,1) = lp1 + p1*l21 - l3;
Ith(rrB,2) = lp2 - p2*y3*l21 - RCONST(2.0)*p3*y2*l2-l3;
Ith(rrB,3) = - p2*y2*l21 -l3 + RCONST(1.0);
return(0);
}
/*Jacobian for backward problem. */
static int JacB(realtype tt, realtype cj,
N_Vector yy, N_Vector yp,
N_Vector yyB, N_Vector ypB, N_Vector rrB,
SUNMatrix JB, void *user_data,
N_Vector tmp1B, N_Vector tmp2B, N_Vector tmp3B)
{
realtype y2, y3;
UserData data;
realtype p1, p2, p3;
y2 = Ith(yy,2); y3 = Ith(yy,3);
data = (UserData) user_data;
p1 = data->p[0]; p2 = data->p[1]; p3 = data->p[2];
IJth(JB,1,1) = -p1+cj;
IJth(JB,1,2) = p1;
IJth(JB,1,3) = -ONE;
IJth(JB,2,1) = p2*y3;
IJth(JB,2,2) = -(p2*y3+RCONST(2.0)*p3*y2)+cj;
IJth(JB,2,3) = -ONE;
IJth(JB,3,1) = p2*y2;
IJth(JB,3,2) = -p2*y2;
IJth(JB,3,3) = -ONE;
return(0);
}
static int rhsQB(realtype tt,
N_Vector yy, N_Vector yp,
N_Vector yyB, N_Vector ypB,
N_Vector rrQB, void *user_dataB)
{
realtype y1, y2, y3;
realtype l1, l2;
realtype l21;
/* The y vector */
y1 = Ith(yy,1); y2 = Ith(yy,2); y3 = Ith(yy,3);
/* The lambda vector */
l1 = Ith(yyB,1); l2 = Ith(yyB,2);
/* Temporary variables */
l21 = l2-l1;
Ith(rrQB,1) = y1*l21;
Ith(rrQB,2) = -y3*y2*l21;
Ith(rrQB,3) = -y2*y2*l2;
return(0);
}
/*
*--------------------------------------------------------------------
* PRIVATE FUNCTIONS
*--------------------------------------------------------------------
*/
/*
* Print results after backward integration
*/
static void PrintOutput(realtype tfinal, N_Vector yB, N_Vector ypB, N_Vector qB)
{
printf("--------------------------------------------------------\n");
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("tB0: %12.4Le\n",tfinal);
printf("dG/dp: %12.4Le %12.4Le %12.4Le\n",
-Ith(qB,1), -Ith(qB,2), -Ith(qB,3));
printf("lambda(t0): %12.4Le %12.4Le %12.4Le\n",
Ith(yB,1), Ith(yB,2), Ith(yB,3));
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("tB0: %12.4e\n",tfinal);
printf("dG/dp: %12.4e %12.4e %12.4e\n",
-Ith(qB,1), -Ith(qB,2), -Ith(qB,3));
printf("lambda(t0): %12.4e %12.4e %12.4e\n",
Ith(yB,1), Ith(yB,2), Ith(yB,3));
#else
printf("tB0: %12.4e\n",tfinal);
printf("dG/dp: %12.4e %12.4e %12.4e\n",
-Ith(qB,1), -Ith(qB,2), -Ith(qB,3));
printf("lambda(t0): %12.4e %12.4e %12.4e\n",
Ith(yB,1), Ith(yB,2), Ith(yB,3));
#endif
printf("--------------------------------------------------------\n\n");
}
/*
* Check function return value.
* opt == 0 means SUNDIALS function allocates memory so check if
* returned NULL pointer
* opt == 1 means SUNDIALS function returns an integer value so check if
* retval < 0
* opt == 2 means function allocates memory so check if returned
* NULL pointer
*/
static int check_retval(void *returnvalue, const char *funcname, int opt)
{
int *retval;
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
if (opt == 0 && returnvalue == NULL) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
/* Check if retval < 0 */
else if (opt == 1) {
retval = (int *) returnvalue;
if (*retval < 0) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n",
funcname, *retval);
return(1); }}
/* Check if function returned NULL pointer - no memory allocated */
else if (opt == 2 && returnvalue == NULL) {
fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
return(0);
}
| 28.895202 | 88 | 0.591392 | [
"object",
"vector"
] |
2c8aca26d3e466716b38fc6cb3624bc904e93c8f | 29,952 | h | C | applications/ContactStructuralMechanicsApplication/custom_strategies/custom_strategies/residualbased_newton_raphson_mpc_contact_strategy.h | SADPR/Kratos | 82d1e335d2e7e674f77022a3d91c958168805d59 | [
"BSD-4-Clause"
] | null | null | null | applications/ContactStructuralMechanicsApplication/custom_strategies/custom_strategies/residualbased_newton_raphson_mpc_contact_strategy.h | SADPR/Kratos | 82d1e335d2e7e674f77022a3d91c958168805d59 | [
"BSD-4-Clause"
] | null | null | null | applications/ContactStructuralMechanicsApplication/custom_strategies/custom_strategies/residualbased_newton_raphson_mpc_contact_strategy.h | SADPR/Kratos | 82d1e335d2e7e674f77022a3d91c958168805d59 | [
"BSD-4-Clause"
] | null | null | null | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_RESIDUALBASED_NEWTON_RAPHSON_MPC_CONTACT_STRATEGY)
#define KRATOS_RESIDUALBASED_NEWTON_RAPHSON_MPC_CONTACT_STRATEGY
/* System Includes */
/* External Includes */
/* Project includes */
#include "contact_structural_mechanics_application_variables.h"
#include "includes/kratos_parameters.h"
#include "includes/define.h"
#include "includes/model_part.h"
#include "includes/variables.h"
// Strategies
#include "solving_strategies/strategies/residualbased_newton_raphson_strategy.h"
// Contact criteria
#include "custom_strategies/custom_convergencecriterias/mpc_contact_criteria.h"
// Utilities
#include "utilities/variable_utils.h"
#include "utilities/color_utilities.h"
#include "utilities/math_utils.h"
// // Processes
// #include "processes/fast_transfer_between_model_parts_process.h"
namespace Kratos {
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class ResidualBasedNewtonRaphsonMPCContactStrategy
* @ingroup ContactStructuralMechanicsApplication
* @brief Contact Newton Raphson class
* @details This class is a specialization of the Newton Raphson strategy with some custom modifications for contact problems
* @author Vicente Mataix Ferrandiz
*/
template<class TSparseSpace,
class TDenseSpace, // = DenseSpace<double>,
class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace>
>
class ResidualBasedNewtonRaphsonMPCContactStrategy :
public ResidualBasedNewtonRaphsonStrategy< TSparseSpace, TDenseSpace, TLinearSolver >
{
public:
///@name Type Definitions
///@{
/** Counted pointer of ClassName */
KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedNewtonRaphsonMPCContactStrategy );
typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> StrategyBaseType;
typedef ResidualBasedNewtonRaphsonStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType;
typedef ConvergenceCriteria<TSparseSpace, TDenseSpace> TConvergenceCriteriaType;
typedef MPCContactCriteria<TSparseSpace, TDenseSpace> TMPCContactCriteriaType;
typedef typename BaseType::TBuilderAndSolverType TBuilderAndSolverType;
typedef typename BaseType::TDataType TDataType;
typedef TSparseSpace SparseSpaceType;
typedef typename BaseType::TSchemeType TSchemeType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType;
typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType;
typedef ModelPart::NodesContainerType NodesArrayType;
typedef ModelPart::ElementsContainerType ElementsArrayType;
typedef ModelPart::ConditionsContainerType ConditionsArrayType;
typedef ModelPart::MasterSlaveConstraintContainerType ConstraintArrayType;
typedef std::size_t IndexType;
typedef std::size_t SizeType;
/**
* @brief Default constructor
* @param rModelPart The model part of the problem
* @param pScheme The integration scheme
* @param pNewConvergenceCriteria The convergence criteria employed
* @param MaxIterations The maximum number of iterations
* @param CalculateReactions The flag for the reaction calculation
* @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF
* @param MoveMeshFlag The flag that allows to move the mesh
*/
ResidualBasedNewtonRaphsonMPCContactStrategy(
ModelPart& rModelPart,
typename TSchemeType::Pointer pScheme,
typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria,
typename TBuilderAndSolverType::Pointer pNewBuilderAndSolver,
IndexType MaxIterations = 30,
bool CalculateReactions = false,
bool ReformDofSetAtEachStep = false,
bool MoveMeshFlag = false,
Parameters ThisParameters = Parameters(R"({})")
)
: ResidualBasedNewtonRaphsonStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, pScheme, pNewConvergenceCriteria, pNewBuilderAndSolver, MaxIterations, CalculateReactions, ReformDofSetAtEachStep, MoveMeshFlag ),
mThisParameters(ThisParameters)
{
KRATOS_TRY;
// We create the contact criteria
mpMPCContactCriteria = Kratos::make_shared<TMPCContactCriteriaType>();
Parameters default_parameters = GetDefaultParameters();
mThisParameters.ValidateAndAssignDefaults(default_parameters);
KRATOS_CATCH("");
}
/**
* @brief Default constructor
* @param rModelPart The model part of the problem
* @param pScheme The integration scheme
* @param pNewLinearSolver The linear solver employed
* @param pNewConvergenceCriteria The convergence criteria employed
* @param MaxIterations The maximum number of iterations
* @param CalculateReactions The flag for the reaction calculation
* @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF
* @param MoveMeshFlag The flag that allows to move the mesh
*/
ResidualBasedNewtonRaphsonMPCContactStrategy(
ModelPart& rModelPart,
typename TSchemeType::Pointer pScheme,
typename TLinearSolver::Pointer pNewLinearSolver,
typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria,
IndexType MaxIterations = 30,
bool CalculateReactions = false,
bool ReformDofSetAtEachStep = false,
bool MoveMeshFlag = false,
Parameters ThisParameters = Parameters(R"({})")
)
: ResidualBasedNewtonRaphsonStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, pScheme, pNewLinearSolver, pNewConvergenceCriteria, MaxIterations, CalculateReactions, ReformDofSetAtEachStep, MoveMeshFlag),
mThisParameters(ThisParameters)
{
KRATOS_TRY;
// We create the contact criteria
mpMPCContactCriteria = Kratos::make_shared<TMPCContactCriteriaType>();
Parameters default_parameters = GetDefaultParameters();
mThisParameters.ValidateAndAssignDefaults(default_parameters);
KRATOS_CATCH("");
}
/**
* @brief Default constructor
* @param rModelPart The model part of the problem
* @param pScheme The integration scheme
* @param pNewLinearSolver The linear solver employed
* @param pNewConvergenceCriteria The convergence criteria employed
* @param MaxIterations The maximum number of iterations
* @param CalculateReactions The flag for the reaction calculation
* @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF
* @param MoveMeshFlag The flag that allows to move the mesh
*/
ResidualBasedNewtonRaphsonMPCContactStrategy(
ModelPart& rModelPart,
typename TSchemeType::Pointer pScheme,
typename TLinearSolver::Pointer pNewLinearSolver,
typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria,
typename TBuilderAndSolverType::Pointer pNewBuilderAndSolver,
IndexType MaxIterations = 30,
bool CalculateReactions = false,
bool ReformDofSetAtEachStep = false,
bool MoveMeshFlag = false,
Parameters ThisParameters = Parameters(R"({})")
)
: ResidualBasedNewtonRaphsonStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, pScheme, pNewLinearSolver, pNewConvergenceCriteria, pNewBuilderAndSolver, MaxIterations, CalculateReactions, ReformDofSetAtEachStep, MoveMeshFlag ),
mThisParameters(ThisParameters)
{
KRATOS_TRY;
// We create the contact criteria
mpMPCContactCriteria = Kratos::make_shared<TMPCContactCriteriaType>();
Parameters default_parameters = GetDefaultParameters();
mThisParameters.ValidateAndAssignDefaults(default_parameters);
KRATOS_CATCH("");
}
/**
* Destructor.
*/
~ResidualBasedNewtonRaphsonMPCContactStrategy() override
= default;
//******************** OPERATIONS ACCESSIBLE FROM THE INPUT: ************************//
//***********************************************************************************//
/**
* @brief Operation to predict the solution ... if it is not called a trivial predictor is used in which the
* values of the solution step of interest are assumed equal to the old values
*/
void Predict() override
{
KRATOS_TRY
BaseType::Predict();
// Getting model part
ModelPart& r_model_part = StrategyBaseType::GetModelPart();
// We get the system
TSystemMatrixType& rA = *BaseType::mpA;
TSystemVectorType& rDx = *BaseType::mpDx;
TSystemVectorType& rb = *BaseType::mpb;
// We solve the system in order to check the active set once
TSparseSpace::SetToZero(rA);
TSparseSpace::SetToZero(rDx);
TSparseSpace::SetToZero(rb);
typename TSchemeType::Pointer p_scheme = BaseType::GetScheme();
typename TBuilderAndSolverType::Pointer p_builder_and_solver = BaseType::GetBuilderAndSolver();
p_builder_and_solver->BuildAndSolve(p_scheme, BaseType::GetModelPart(), rA, rDx, rb);
// Check active set
const SizeType echo_level_convergence_criteria = BaseType::mpConvergenceCriteria->GetEchoLevel();
BaseType::mpConvergenceCriteria->SetEchoLevel(0);
mpMPCContactCriteria->PostCriteria(r_model_part, BaseType::GetBuilderAndSolver()->GetDofSet(), rA, rDx, rb);
BaseType::mpConvergenceCriteria->SetEchoLevel(echo_level_convergence_criteria);
KRATOS_CATCH("")
}
/**
* @brief Initialization of member variables and prior operations
*/
void Initialize() override
{
KRATOS_TRY;
// Computing nodal weights
ComputeNodalWeights();
BaseType::Initialize();
KRATOS_CATCH("");
}
/**
* @brief The problem of interest is solved.
* @details This function calls sequentially: Initialize(), InitializeSolutionStep(), Predict(),
* SolveSolutionStep() and FinalizeSolutionStep().
* All those functions can otherwise be called separately.
*/
double Solve() override
{
this->Initialize();
this->InitializeSolutionStep();
this->Predict();
this->SolveSolutionStep();
this->FinalizeSolutionStep(); // TODO: Comment for proper work of interaction
return 0.0;
}
/**
* @brief Performs all the required operations that should be done (for each step)
* before solving the solution step.
* @details A member variable should be used as a flag to make sure this function is called only once per step.
*/
void InitializeSolutionStep() override
{
// Computing nodal weights
ComputeNodalWeights();
BaseType::InitializeSolutionStep();
// // If enforcing NTN
// const bool enforce_ntn = mThisParameters["enforce_ntn"].GetBool();
// if (enforce_ntn) {
// EnforcingNTN();
// }
}
/**
* @brief Performs all the required operations that should be done (for each step)
* after solving the solution step.
*/
void FinalizeSolutionStep() override
{
KRATOS_TRY;
BaseType::FinalizeSolutionStep();
KRATOS_CATCH("");
}
/**
* @brief Solves the current step.
* @details This function returns true if a solution has been found, false otherwise.
*/
bool SolveSolutionStep() override
{
KRATOS_TRY;
bool is_converged = false;
// Getting model part
ModelPart& r_model_part = StrategyBaseType::GetModelPart();
// We get the process info
ProcessInfo& r_process_info = r_model_part.GetProcessInfo();
if (r_process_info.Is(INTERACTION)) {
// We get the system
TSystemMatrixType& rA = *BaseType::mpA;
TSystemVectorType& rDx = *BaseType::mpDx;
TSystemVectorType& rb = *BaseType::mpb;
int inner_iteration = 0;
const SizeType echo_level_convergence_criteria = BaseType::mpConvergenceCriteria->GetEchoLevel();
while (!is_converged && inner_iteration < mThisParameters["inner_loop_iterations"].GetInt()) {
++inner_iteration;
if (echo_level_convergence_criteria > 0 && r_model_part.GetCommunicator().MyPID() == 0 ) {
KRATOS_INFO("Simplified semi-smooth strategy") << BOLDFONT("INNER ITERATION: ") << inner_iteration << std::endl;
}
// We solve one loop
r_process_info[NL_ITERATION_NUMBER] = 1;
is_converged = AuxiliarSolveSolutionStep();
// We check the convergence
if (r_process_info[NL_ITERATION_NUMBER] == 1) r_process_info[NL_ITERATION_NUMBER] = 2; // Trigger check
is_converged = mpMPCContactCriteria->PostCriteria(r_model_part, BaseType::GetBuilderAndSolver()->GetDofSet(), rA, rDx, rb);
if (echo_level_convergence_criteria > 0 && r_model_part.GetCommunicator().MyPID() == 0 ) {
if (is_converged) KRATOS_INFO("Simplified semi-smooth strategy") << BOLDFONT("Simplified semi-smooth strategy. INNER ITERATION: ") << BOLDFONT(FGRN("CONVERGED")) << std::endl;
else KRATOS_INFO("Simplified semi-smooth strategy") << BOLDFONT("INNER ITERATION: ") << BOLDFONT(FRED("NOT CONVERGED")) << std::endl;
}
}
} else {
is_converged = AuxiliarSolveSolutionStep();
}
return is_converged;
KRATOS_CATCH("");
}
/**
* @brief Solves the current step. This function returns true if a solution has been found, false otherwise. (auxiliar method)
*/
bool AuxiliarSolveSolutionStep()
{
// Getting flag INTERACTION
ModelPart& r_model_part = StrategyBaseType::GetModelPart();
const bool update_each_nl_iteration = mThisParameters["update_each_nl_iteration"].GetBool();
VariableUtils().SetFlag(INTERACTION, update_each_nl_iteration, r_model_part.GetSubModelPart("ComputingContact").Conditions());
// Pointers needed in the solution
typename TSchemeType::Pointer p_scheme = this->GetScheme();
typename TBuilderAndSolverType::Pointer p_builder_and_solver = this->GetBuilderAndSolver();
auto& r_dof_set = p_builder_and_solver->GetDofSet();
TSystemMatrixType& rA = *BaseType::mpA;
TSystemVectorType& rDx = *BaseType::mpDx;
TSystemVectorType& rb = *BaseType::mpb;
// Initializing the parameters of the Newton-Raphson cycle
unsigned int iteration_number = 1;
r_model_part.GetProcessInfo()[NL_ITERATION_NUMBER] = iteration_number;
bool is_converged = false;
bool residual_is_updated = false;
// Computing nodal weights
ComputeNodalWeights();
p_scheme->InitializeNonLinIteration(r_model_part, rA, rDx, rb);
BaseType::mpConvergenceCriteria->InitializeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb);
is_converged = BaseType::mpConvergenceCriteria->PreCriteria(r_model_part, p_builder_and_solver->GetDofSet(), rA, rDx, rb);
// // If enforcing NTN
// const bool enforce_ntn = mThisParameters["enforce_ntn"].GetBool();
// if (enforce_ntn) {
// EnforcingNTN();
// }
// Function to perform the building and the solving phase.
if (StrategyBaseType::mRebuildLevel > 0 || StrategyBaseType::mStiffnessMatrixIsBuilt == false) {
TSparseSpace::SetToZero(rA);
TSparseSpace::SetToZero(rDx);
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildAndSolve(p_scheme, r_model_part, rA, rDx, rb);
} else {
TSparseSpace::SetToZero(rDx); //Dx=0.00;
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildRHSAndSolve(p_scheme, r_model_part, rA, rDx, rb);
}
// Debugging info
BaseType::EchoInfo(iteration_number);
// Updating the results stored in the database
BaseType::UpdateDatabase(rA, rDx, rb, StrategyBaseType::MoveMeshFlag());
p_scheme->FinalizeNonLinIteration(r_model_part, rA, rDx, rb);
BaseType::mpConvergenceCriteria->FinalizeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb);
// Calculate reactions if required
if (BaseType::mCalculateReactionsFlag)
p_builder_and_solver->CalculateReactions(p_scheme, r_model_part, rA, rDx, rb);
if (is_converged) {
if (BaseType::mpConvergenceCriteria->GetActualizeRHSflag()) {
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildRHS(p_scheme, r_model_part, rb);
}
is_converged = BaseType::mpConvergenceCriteria->PostCriteria(r_model_part, p_builder_and_solver->GetDofSet(), rA, rDx, rb);
}
// Iteration Cycle... performed only for NonLinearProblems
while (!is_converged && iteration_number++ < BaseType::mMaxIterationNumber) {
// Setting the number of iteration
r_model_part.GetProcessInfo()[NL_ITERATION_NUMBER] = iteration_number;
// Computing nodal weights
ComputeNodalWeights();
// Calling InitializeNonLinIteration
p_scheme->InitializeNonLinIteration(r_model_part, rA, rDx, rb);
BaseType::mpConvergenceCriteria->InitializeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb);
// Shaping correctly the system
if (update_each_nl_iteration) {
p_builder_and_solver->SetUpDofSet(p_scheme, r_model_part);
p_builder_and_solver->SetUpSystem(r_model_part);
p_builder_and_solver->ResizeAndInitializeVectors(p_scheme, BaseType::mpA, BaseType::mpDx, BaseType::mpb, r_model_part);
}
is_converged = BaseType::mpConvergenceCriteria->PreCriteria(r_model_part, p_builder_and_solver->GetDofSet(), rA, rDx, rb);
// Call the linear system solver to find the correction mDx for the it is not called if there is no system to solve
if (SparseSpaceType::Size(rDx) != 0) {
if (StrategyBaseType::mRebuildLevel > 1 || !StrategyBaseType::mStiffnessMatrixIsBuilt) {
if (!BaseType::GetKeepSystemConstantDuringIterations()) {
//A = 0.00;
TSparseSpace::SetToZero(rA);
TSparseSpace::SetToZero(rDx);
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildAndSolve(p_scheme, r_model_part, rA, rDx, rb);
} else {
TSparseSpace::SetToZero(rDx);
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildRHSAndSolve(p_scheme, r_model_part, rA, rDx, rb);
}
} else {
TSparseSpace::SetToZero(rDx);
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildRHSAndSolve(p_scheme, r_model_part, rA, rDx, rb);
}
} else {
KRATOS_WARNING("NO DOFS") << "ATTENTION: no free DOFs!! " << std::endl;
}
// Debugging info
BaseType::EchoInfo(iteration_number);
// Updating the results stored in the database
BaseType::UpdateDatabase(rA, rDx, rb, StrategyBaseType::MoveMeshFlag());
p_scheme->FinalizeNonLinIteration(r_model_part, rA, rDx, rb);
BaseType::mpConvergenceCriteria->FinalizeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb);
residual_is_updated = false;
// Calculate reactions if required
if (BaseType::mCalculateReactionsFlag)
p_builder_and_solver->CalculateReactions(p_scheme, r_model_part, rA, rDx, rb);
if (is_converged) {
if (BaseType::mpConvergenceCriteria->GetActualizeRHSflag()) {
TSparseSpace::SetToZero(rb);
p_builder_and_solver->BuildRHS(p_scheme, r_model_part, rb);
residual_is_updated = true;
}
is_converged = BaseType::mpConvergenceCriteria->PostCriteria(r_model_part, p_builder_and_solver->GetDofSet(), rA, rDx, rb);
}
}
// Plots a warning if the maximum number of iterations is exceeded
if (iteration_number >= BaseType::mMaxIterationNumber) {
BaseType::MaxIterationsExceeded();
} else {
KRATOS_INFO_IF("NR-Strategy", this->GetEchoLevel() > 0) << "Convergence achieved after " << iteration_number << " / " << BaseType::mMaxIterationNumber << " iterations" << std::endl;
}
// Recalculate residual if needed (note that some convergence criteria need it to be recalculated)
if (!residual_is_updated) {
// NOTE:
// The following part will be commented because it is time consuming
// and there is no obvious reason to be here. If someone need this
// part please notify the community via mailing list before uncommenting it.
// Pooyan.
// TSparseSpace::SetToZero(mb);
// p_builder_and_solver->BuildRHS(p_scheme, r_model_part, mb);
}
// Calculate reactions if required
if (BaseType::mCalculateReactionsFlag)
p_builder_and_solver->CalculateReactions(p_scheme, r_model_part, rA, rDx, rb);
return is_converged;
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
Parameters mThisParameters; /// The configuration parameters
typename TConvergenceCriteriaType::Pointer mpMPCContactCriteria; /// The contact criteria
///@}
///@name Protected Operators
///@{
/**
* @brief This method returns the defaulr parameters in order to avoid code duplication
* @return Returns the default parameters
*/
Parameters GetDefaultParameters()
{
Parameters default_parameters = Parameters(R"(
{
"inner_loop_iterations" : 5,
"update_each_nl_iteration" : false,
"enforce_ntn" : false
})" );
return default_parameters;
}
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@{
/**
* Copy constructor.
*/
ResidualBasedNewtonRaphsonMPCContactStrategy(const ResidualBasedNewtonRaphsonMPCContactStrategy& Other)
{
};
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
// /**
// * @brief This inforces NTN formulation
// */
// void EnforcingNTN()
// {
// // List of enforced nodes to not repeat
// std::unordered_set<IndexType> enforced_nodes;
//
// // Getting contact model part
// ModelPart& r_root_model_part = StrategyBaseType::GetModelPart().GetRootModelPart();
// ModelPart& r_computing_contact_model_part = StrategyBaseType::GetModelPart().GetSubModelPart("ComputingContact");
//
// // The process info
// const auto& r_process_info = r_root_model_part.GetProcessInfo();
//
// // Reset the pointers of the conditions
// for (auto& r_cond : r_computing_contact_model_part.Conditions()) {
// if (r_cond.Has(CONSTRAINT_POINTER)) {
// r_cond.SetValue(CONSTRAINT_POINTER, nullptr);
// }
// }
//
// // Iterate over the constraints
// IndexType counter = 1;
// for (auto& r_const : r_root_model_part.MasterSlaveConstraints()) {
// r_const.SetId(counter);
// ++counter;
// }
//
// // Auxiliar classes
// Matrix original_relation_matrix, relation_matrix;
// Vector original_constant_vector, constant_vector;
// ModelPart::DofsVectorType original_master_dofs, master_dofs, original_slave_dofs, slave_dofs;
//
// // Iterate over the constraints
// for (auto& r_const : r_computing_contact_model_part.MasterSlaveConstraints()) {
// // Getting original system
// r_const.GetLocalSystem(original_relation_matrix, original_constant_vector, r_process_info);
// r_const.GetDofList(original_slave_dofs, original_master_dofs, r_process_info);
//
// // TODO: Finish rebuild
//
// // Creating new constraint
// r_root_model_part.CreateNewMasterSlaveConstraint("LinearMasterSlaveConstraint", counter, master_dofs, slave_dofs, relation_matrix, constant_vector);
//
// // Setting to remove the old constraints
// r_const.Set(TO_ERASE, true);
//
// ++counter;
// }
//
// // Remove old constraints
// r_root_model_part.RemoveMasterSlaveConstraintsFromAllLevels(TO_ERASE);
//
// // Transfer constraints from the root to the computing model part
// FastTransferBetweenModelPartsProcess(r_computing_contact_model_part, r_root_model_part, FastTransferBetweenModelPartsProcess::EntityTransfered::CONSTRAINTS).Execute();
//
// // Reorder ids
// counter = 1;
// for (auto& r_const : r_root_model_part.MasterSlaveConstraints()) {
// r_const.SetId(counter);
// ++counter;
// }
// }
/**
* @brief This computes the nodal weights
*/
void ComputeNodalWeights()
{
// Getting contact model part
ModelPart& r_contact_model_part = StrategyBaseType::GetModelPart().GetSubModelPart("Contact");
// Reset the NODAL_PAUX and NODAL_MAUX
auto& r_nodes_array = r_contact_model_part.Nodes();
VariableUtils().SetNonHistoricalVariableToZero(NODAL_PAUX, r_nodes_array);
VariableUtils().SetNonHistoricalVariableToZero(NODAL_MAUX, r_nodes_array);
// We set the constraints active and inactive in function of the active set
auto& r_conditions_array = r_contact_model_part.Conditions();
auto it_cond_begin = r_conditions_array.begin();
// If enforcing NTN
const bool enforce_ntn = false;
// const bool enforce_ntn = mThisParameters["enforce_ntn"].GetBool();
// if (enforce_ntn) {
// VariableUtils().SetNonHistoricalVariable(NODAL_PAUX, 1.0, r_nodes_array);
// }
#pragma omp parallel for
for(int i = 0; i < static_cast<int>(r_conditions_array.size()); ++i) {
auto it_cond = it_cond_begin + i;
// Only slave conditions
if (it_cond->Is(SLAVE)) {
auto& r_geometry = it_cond->GetGeometry();
Vector lumping_factor;
lumping_factor = r_geometry.LumpingFactors(lumping_factor);
const double domain_size = r_geometry.DomainSize();
for (IndexType i_node = 0; i_node < r_geometry.size(); ++i_node) {
auto& r_node = r_geometry[i_node];
if (!enforce_ntn) {
#pragma omp atomic
r_node.GetValue(NODAL_PAUX) += 1.0;
}
#pragma omp atomic
r_node.GetValue(NODAL_MAUX) += lumping_factor[i_node] * domain_size;
}
}
}
}
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedNewtonRaphsonMPCContactStrategy */
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
} // namespace Kratos
#endif /* KRATOS_RESIDUALBASED_NEWTON_RAPHSON_MPC_CONTACT_STRATEGY */
| 37.44 | 247 | 0.631644 | [
"mesh",
"vector",
"model"
] |
2c8b0fad93c4781665b16bb975eba910a5c6cff9 | 8,879 | h | C | src/dory/debug/debug_setup.h | femtonaut/dory | aec0ae0ae6ba2bb2137af7d5c5f523884e1d4372 | [
"Apache-2.0"
] | null | null | null | src/dory/debug/debug_setup.h | femtonaut/dory | aec0ae0ae6ba2bb2137af7d5c5f523884e1d4372 | [
"Apache-2.0"
] | null | null | null | src/dory/debug/debug_setup.h | femtonaut/dory | aec0ae0ae6ba2bb2137af7d5c5f523884e1d4372 | [
"Apache-2.0"
] | 2 | 2016-12-07T23:06:59.000Z | 2021-09-06T23:12:14.000Z | /* <dory/debug/debug_setup.h>
----------------------------------------------------------------------------
Copyright 2013-2014 if(we)
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.
----------------------------------------------------------------------------
Debugging stuff.
*/
#pragma once
#include <algorithm>
#include <cassert>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_set>
#include <base/fd.h>
#include <base/no_copy_semantics.h>
#include <base/opt.h>
namespace Dory {
namespace Debug {
class TDebugSetup final {
NO_COPY_SEMANTICS(TDebugSetup);
public:
enum class TLogId {
MSG_RECEIVE = 0,
MSG_SEND = 1,
MSG_GOT_ACK = 2
}; // TLogId
static const size_t NUM_LOG_FILES = 3;
static size_t ToIndex(TLogId id) {
size_t index = static_cast<size_t>(id);
assert(index < NUM_LOG_FILES);
return index;
}
class TSettings final {
NO_COPY_SEMANTICS(TSettings);
public:
using TPtr = std::shared_ptr<TSettings>;
static bool EnableIsSpecified(
const std::unordered_set<std::string> *topics) {
return (topics == nullptr) || !topics->empty();
}
/* Return nullptr if all topics are enabled. Otherwise return a
pointer to the set of enabled topics. */
const std::unordered_set<std::string> *GetDebugTopics() const {
assert(this);
return DebugTopics.IsKnown() ? &*DebugTopics : nullptr;
}
size_t GetVersion() const {
assert(this);
return Version;
}
bool LoggingIsEnabled() const {
assert(this);
return LoggingEnabled;
}
int GetLogFileDescriptor(TLogId log_id) const {
assert(this);
return LogFds[ToIndex(log_id)];
}
bool RequestLogBytes(size_t num_bytes) {
assert(this);
std::lock_guard<std::mutex> lock(Mutex);
if (BytesRemaining < num_bytes) {
return false;
}
BytesRemaining -= num_bytes;
return true;
}
private:
/* If 'debug_topics' is null, the created TSettings object will specify
"all topics". Otherwise, the contents of *debug_topics will be
moved into the created TSettings object (leaving *debug_topics
empty). "No topics" is specified by providing an empty set. */
static TPtr Create(size_t version,
std::unordered_set<std::string> *debug_topics,
const char *msg_receive_log_path,
const char *msg_send_log_path,
const char *msg_got_ack_log_path, size_t byte_limit,
bool truncate_files) {
return TPtr(new TSettings(version, debug_topics,
msg_receive_log_path, msg_send_log_path,
msg_got_ack_log_path, byte_limit,
truncate_files));
}
Base::TFd &GetLogFd(TLogId log_id) {
assert(this);
return LogFds[ToIndex(log_id)];
}
TSettings(size_t version,
std::unordered_set<std::string> *debug_topics,
const char *msg_receive_log_path, const char *msg_send_log_path,
const char *msg_got_ack_log_path, size_t byte_limit,
bool truncate_files);
const size_t Version;
const bool LoggingEnabled;
Base::TFd LogFds[NUM_LOG_FILES];
/* The absence of a set of strings means "all topics". The presence of
an empty set of strings means "no topics". */
Base::TOpt<const std::unordered_set<std::string>> DebugTopics;
/* Protects 'BytesRemaining'. */
std::mutex Mutex;
/* As a safeguard, we limit the number of bytes that can be logged. */
size_t BytesRemaining;
/* For access to static Create() method. */
friend class TDebugSetup;
}; // TSettings
/* For convenience. */
static const size_t MAX_LIMIT = std::numeric_limits<size_t>::max();
TDebugSetup(const char *debug_dir, size_t kill_switch_limit_seconds,
size_t kill_switch_limit_bytes)
: DebugDir(debug_dir),
KillSwitchLimitSeconds(kill_switch_limit_seconds),
KillSwitchLimitBytes(kill_switch_limit_bytes),
SettingsVersion(0) {
GetLogPath(TLogId::MSG_RECEIVE) =
std::move(std::string(debug_dir) + "/msg_receive");
GetLogPath(TLogId::MSG_SEND) =
std::move(std::string(debug_dir) + "/msg_send");
GetLogPath(TLogId::MSG_GOT_ACK) =
std::move(std::string(debug_dir) + "/msg_got_ack");
Settings = CreateInitialSettings();
SettingsVersion = Settings->GetVersion();
}
const std::string &GetLogPath(TLogId log_id) const {
assert(this);
return LogPaths[ToIndex(log_id)];
}
size_t GetKillSwitchLimitSeconds() const {
return KillSwitchLimitSeconds;
}
bool MySettingsAreOld(size_t my_version) const {
assert(this);
/* We can get away without grabbing 'Mutex' here. */
return SettingsVersion != my_version;
}
TSettings::TPtr GetSettings() const {
assert(this);
std::lock_guard<std::mutex> lock(Mutex);
assert(Settings);
return Settings;
}
bool AddDebugTopic(const char *topic);
bool DelDebugTopic(const char *topic);
/* If 'debug_topics' is null, "all topics" is specified. Otherwise, the
contents of *debug_topics are moved and left empty. "No topics" is
specified by providing an empty set. */
void SetDebugTopics(std::unordered_set<std::string> *debug_topics);
void ClearDebugTopics() {
assert(this);
std::unordered_set<std::string> no_topics;
SetDebugTopics(&no_topics);
}
void TruncateDebugFiles();
private:
std::string &GetLogPath(TLogId log_id) {
assert(this);
return LogPaths[ToIndex(log_id)];
}
void CreateDebugDir();
void DeleteOldDebugFiles(const TSettings::TPtr &old_settings);
void DeleteOldDebugFiles() {
TSettings::TPtr no_settings;
DeleteOldDebugFiles(no_settings);
}
TSettings::TPtr CreateInitialSettings() {
DeleteOldDebugFiles();
std::unordered_set<std::string> no_topics;
return TSettings::Create(0, &no_topics,
GetLogPath(TLogId::MSG_RECEIVE).c_str(),
GetLogPath(TLogId::MSG_SEND).c_str(),
GetLogPath(TLogId::MSG_GOT_ACK).c_str(),
KillSwitchLimitBytes, true);
}
/* If 'debug_topics' is null, the created TSettings object will specify
"all topics". Otherwise, the contents of *debug_topics will be moved
into the created TSettings object (leaving *debug_topics empty). "No
topics" is specified by providing an empty set. Caller must hold
'Mutex'. */
void ReplaceSettings(std::unordered_set<std::string> *debug_topics) {
assert(Settings);
bool delete_old_data = TSettings::EnableIsSpecified(debug_topics) &&
!Settings->LoggingIsEnabled();
if (delete_old_data) {
DeleteOldDebugFiles(Settings);
}
Settings = TSettings::Create(Settings->GetVersion() + 1, debug_topics,
GetLogPath(TLogId::MSG_RECEIVE).c_str(),
GetLogPath(TLogId::MSG_SEND).c_str(),
GetLogPath(TLogId::MSG_GOT_ACK).c_str(),
KillSwitchLimitBytes, delete_old_data);
SettingsVersion = Settings->GetVersion();
}
const std::string DebugDir;
const size_t KillSwitchLimitSeconds;
const size_t KillSwitchLimitBytes;
std::string LogPaths[NUM_LOG_FILES];
mutable std::mutex Mutex;
TSettings::TPtr Settings;
size_t SettingsVersion;
}; // TDebugSetup
} // Debug
} // Dory
| 32.054152 | 79 | 0.588017 | [
"object"
] |
2c8ebc7f7fcc034ce96d9746d3b889e078c34a08 | 3,846 | h | C | OpenSim 3.1/sdk/include/SimTK/include/simbody/internal/MobilizedBody_Cylinder.h | chrisdembia/opensim-metabolicsprobes | 7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0 | [
"Apache-2.0"
] | 1 | 2019-11-19T23:40:52.000Z | 2019-11-19T23:40:52.000Z | OpenSim 3.1/sdk/include/SimTK/include/simbody/internal/MobilizedBody_Cylinder.h | chrisdembia/opensim-metabolicsprobes | 7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0 | [
"Apache-2.0"
] | 1 | 2021-01-11T13:45:54.000Z | 2021-01-11T13:45:54.000Z | OpenSim 3.1/sdk/include/SimTK/include/simbody/internal/MobilizedBody_Cylinder.h | chrisdembia/opensim-metabolicsprobes | 7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0 | [
"Apache-2.0"
] | 3 | 2019-05-17T02:17:10.000Z | 2020-11-05T20:31:55.000Z | #ifndef SimTK_SIMBODY_MOBILIZED_BODY_CYLINDER_H_
#define SimTK_SIMBODY_MOBILIZED_BODY_CYLINDER_H_
/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2007-12 Stanford University and the Authors. *
* Authors: Michael Sherman *
* Contributors: Paul Mitiguy, Peter Eastman *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
/** @file
Declares the MobilizedBody::Cylinder class. **/
#include "simbody/internal/MobilizedBody.h"
namespace SimTK {
/// Two mobilities -- rotation and translation along the common z axis
/// of the inboard and outboard mobilizer frames.
class SimTK_SIMBODY_EXPORT MobilizedBody::Cylinder : public MobilizedBody {
public:
explicit Cylinder(Direction=Forward);
/// By default the parent body frame and the body's own frame are
/// used as the inboard and outboard mobilizer frames, resp.
Cylinder(MobilizedBody& parent, const Body&, Direction=Forward);
/// Use this constructor to specify mobilizer frames which are
/// not coincident with the body frames.
Cylinder(MobilizedBody& parent, const Transform& inbFrame,
const Body&, const Transform& outbFrame, Direction=Forward);
Cylinder& addBodyDecoration(const Transform& X_BD, const DecorativeGeometry& g) {
(void)MobilizedBody::addBodyDecoration(X_BD,g); return *this;
}
Cylinder& addOutboardDecoration(const Transform& X_MD, const DecorativeGeometry& g) {
(void)MobilizedBody::addOutboardDecoration(X_MD,g); return *this;
}
Cylinder& addInboardDecoration (const Transform& X_FD, const DecorativeGeometry& g) {
(void)MobilizedBody::addInboardDecoration(X_FD,g); return *this;
}
Cylinder& setDefaultInboardFrame(const Transform& X_PF) {
(void)MobilizedBody::setDefaultInboardFrame(X_PF); return *this;
}
Cylinder& setDefaultOutboardFrame(const Transform& X_BM) {
(void)MobilizedBody::setDefaultOutboardFrame(X_BM); return *this;
}
/** @cond **/ // Don't let doxygen see this
SimTK_INSERT_DERIVED_HANDLE_DECLARATIONS(Cylinder, CylinderImpl,
MobilizedBody);
/** @endcond **/
};
} // namespace SimTK
#endif // SimTK_SIMBODY_MOBILIZED_BODY_CYLINDER_H_
| 48.075 | 91 | 0.569943 | [
"transform"
] |
2c8fcbd3a3491cdcbf188470834f48fbb17404ed | 4,284 | h | C | src/avt/Database/Formats/avtMTMDFileFormat.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 226 | 2018-12-29T01:13:49.000Z | 2022-03-30T19:16:31.000Z | src/avt/Database/Formats/avtMTMDFileFormat.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 5,100 | 2019-01-14T18:19:25.000Z | 2022-03-31T23:08:36.000Z | src/avt/Database/Formats/avtMTMDFileFormat.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 84 | 2019-01-24T17:41:50.000Z | 2022-03-10T10:01:46.000Z | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
// ************************************************************************* //
// avtMTMDFileFormat.h //
// ************************************************************************* //
#ifndef AVT_MTMD_FILE_FORMAT_H
#define AVT_MTMD_FILE_FORMAT_H
#include <database_exports.h>
#include <avtFileFormat.h>
#include <vector>
#include <void_ref_ptr.h>
class vtkDataSet;
class vtkDataArray;
class avtIOInformation;
// ****************************************************************************
// Class: avtMTMDFileFormat
//
// Purpose:
// This is an implementation of avtFileFormat for file formats that have
// a Multiple Timesteps and Multiple Domains.
//
// Programmer: Hank Childs
// Creation: April 4, 2003
//
// Modifications:
// Brad Whitlock, Mon Oct 13 14:17:30 PST 2003
// Added a method to get the times.
//
// Mark C. Miller, Mon Feb 23 20:38:47 PST 2004
// Added method, ActivateTimestep
//
// Mark C. Miller, Tue Mar 16 14:28:42 PST 2004
// Added method, PopulateIOInformation
//
// Mark C. Miller, Tue May 17 18:48:38 PDT 2005
// Moved GetCycles/Times to base class, avtFileFormat
// Added SetDatabaseMetaData (moved it down from base class)
// Added time-qualified and non-time-qualified PopulateDatabaseMetaData
// methods, the later for backward compatibility
//
// Hank Childs, Sun May 9 18:47:06 CDT 2010
// Add support for time slice offsets (used when group MT files with .visit
// files).
//
// Mark C. Miller, Fri Oct 29 09:58:43 PDT 2010
// Moved implementation of SetDatabaseMetaData to the .C file.
//
// Hank Childs, Tue Apr 10 15:12:58 PDT 2012
// Add method SetReadAllCyclesAndTimes.
//
// Brad Whitlock, Thu Jun 19 10:50:25 PDT 2014
// Pass mesh name to PopulateIOInformation.
//
// ****************************************************************************
class DATABASE_API avtMTMDFileFormat : public avtFileFormat
{
public:
avtMTMDFileFormat(const char *);
virtual ~avtMTMDFileFormat();
virtual void *GetAuxiliaryData(const char *var, int, int,
const char *type, void *args,
DestructorFunction &);
virtual int GetNTimesteps(void);
virtual const char *GetFilename(void) { return filename; };
virtual vtkDataSet *GetMesh(int, int, const char *) = 0;
virtual vtkDataArray *GetVar(int, int, const char *) = 0;
virtual vtkDataArray *GetVectorVar(int, int, const char *);
virtual void ActivateTimestep(int ts)
{ avtFileFormat::ActivateTimestep(); };
using avtFileFormat::ActivateTimestep;
virtual bool PopulateIOInformation(int ts, const std::string &meshname,
avtIOInformation& ioInfo) { return false; }
virtual void SetDatabaseMetaData(avtDatabaseMetaData *md, int ts = 0);
void SetTimeSliceOffset(int ts) { timeSliceOffset = ts; };
void SetReadAllCyclesAndTimes(bool b)
{ readAllCyclesAndTimes = b; };
bool GetReadAllCyclesAndTimes(void)
{ return readAllCyclesAndTimes; };
protected:
char *filename;
int timeSliceOffset;
bool readAllCyclesAndTimes;
// The second of these should really be pure virtual and the first
// non-existant. However, both are just virtual to maintain
// backward compatibility with older MTXX plugins and to allow
// MTXX plugins to implement a time-qualified request to populate
// database metadata.
virtual void PopulateDatabaseMetaData(avtDatabaseMetaData *md);
virtual void PopulateDatabaseMetaData(avtDatabaseMetaData *md, int);
};
#endif
| 35.7 | 92 | 0.574463 | [
"mesh",
"vector"
] |
2c903e75edeabf2fbd97cb549ec0c4ad954a282f | 23,009 | c | C | lib/abc/src/base/cba/cbaReadBlif.c | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | 9 | 2017-06-12T17:58:42.000Z | 2021-02-04T00:02:29.000Z | reproduction-artifact/ssatABC/src/base/cba/cbaReadBlif.c | nianzelee/PhD-Dissertation | 061e22dd55b4e58b3de3b0e58bb1cbe11435decd | [
"Apache-2.0"
] | 1 | 2020-12-15T05:59:37.000Z | 2020-12-15T05:59:37.000Z | reproduction-artifact/ssatABC/src/base/cba/cbaReadBlif.c | nianzelee/PhD-Dissertation | 061e22dd55b4e58b3de3b0e58bb1cbe11435decd | [
"Apache-2.0"
] | 3 | 2018-04-23T22:52:53.000Z | 2020-12-15T16:36:19.000Z | /**CFile****************************************************************
FileName [cbaReadBlif.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Hierarchical word-level netlist.]
Synopsis [BLIF parser.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - November 29, 2014.]
Revision [$Id: cbaReadBlif.c,v 1.00 2014/11/29 00:00:00 alanmi Exp $]
***********************************************************************/
#include "cba.h"
#include "cbaPrs.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
// BLIF keywords
typedef enum {
PRS_BLIF_NONE = 0, // 0: unused
PRS_BLIF_MODEL, // 1: .model
PRS_BLIF_INOUTS, // 2: .inouts
PRS_BLIF_INPUTS, // 3: .inputs
PRS_BLIF_OUTPUTS, // 4: .outputs
PRS_BLIF_NAMES, // 5: .names
PRS_BLIF_SUBCKT, // 6: .subckt
PRS_BLIF_GATE, // 7: .gate
PRS_BLIF_LATCH, // 8: .latch
PRS_BLIF_SHORT, // 9: .short
PRS_BLIF_END, // 10: .end
PRS_BLIF_UNKNOWN // 11: unknown
} Cba_BlifType_t;
static const char * s_BlifTypes[PRS_BLIF_UNKNOWN+1] = {
NULL, // 0: unused
".model", // 1: .model
".inouts", // 2: .inputs
".inputs", // 3: .inputs
".outputs", // 4: .outputs
".names", // 5: .names
".subckt", // 6: .subckt
".gate", // 7: .gate
".latch", // 8: .latch
".short", // 9: .short
".end", // 10: .end
NULL // 11: unknown
};
static inline void Prs_NtkAddBlifDirectives( Prs_Man_t * p )
{
int i;
for ( i = 1; s_BlifTypes[i]; i++ )
Abc_NamStrFindOrAdd( p->pStrs, (char *)s_BlifTypes[i], NULL );
assert( Abc_NamObjNumMax(p->pStrs) == i );
}
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Reading characters.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline int Prs_CharIsSpace( char c ) { return c == ' ' || c == '\t' || c == '\r'; }
static inline int Prs_CharIsStop( char c ) { return c == '#' || c == '\\' || c == '\n' || c == '='; }
static inline int Prs_CharIsLit( char c ) { return c == '0' || c == '1' || c == '-'; }
static inline int Prs_ManIsSpace( Prs_Man_t * p ) { return Prs_CharIsSpace(*p->pCur); }
static inline int Prs_ManIsStop( Prs_Man_t * p ) { return Prs_CharIsStop(*p->pCur); }
static inline int Prs_ManIsLit( Prs_Man_t * p ) { return Prs_CharIsLit(*p->pCur); }
static inline int Prs_ManIsChar( Prs_Man_t * p, char c ) { return *p->pCur == c; }
static inline int Prs_ManIsChar2( Prs_Man_t * p, char c ) { return *p->pCur++ == c; }
static inline void Prs_ManSkip( Prs_Man_t * p ) { p->pCur++; }
static inline char Prs_ManSkip2( Prs_Man_t * p ) { return *p->pCur++; }
/**Function*************************************************************
Synopsis [Reading names.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Prs_ManSkipToChar( Prs_Man_t * p, char c )
{
while ( !Prs_ManIsChar(p, c) )
Prs_ManSkip(p);
}
static inline void Prs_ManSkipSpaces( Prs_Man_t * p )
{
while ( 1 )
{
while ( Prs_ManIsSpace(p) )
Prs_ManSkip(p);
if ( Prs_ManIsChar(p, '\\') )
{
Prs_ManSkipToChar( p, '\n' );
Prs_ManSkip(p);
continue;
}
if ( Prs_ManIsChar(p, '#') )
Prs_ManSkipToChar( p, '\n' );
break;
}
assert( !Prs_ManIsSpace(p) );
}
static inline int Prs_ManReadName( Prs_Man_t * p )
{
char * pStart;
Prs_ManSkipSpaces( p );
if ( Prs_ManIsChar(p, '\n') )
return 0;
pStart = p->pCur;
while ( !Prs_ManIsSpace(p) && !Prs_ManIsStop(p) )
Prs_ManSkip(p);
if ( pStart == p->pCur )
return 0;
return Abc_NamStrFindOrAddLim( p->pStrs, pStart, p->pCur, NULL );
}
static inline int Prs_ManReadList( Prs_Man_t * p, Vec_Int_t * vOrder, int Type )
{
int iToken;
Vec_IntClear( &p->vTemp );
while ( (iToken = Prs_ManReadName(p)) )
{
Vec_IntPush( &p->vTemp, iToken );
Vec_IntPush( vOrder, Abc_Var2Lit2(iToken, Type) );
}
if ( Vec_IntSize(&p->vTemp) == 0 ) return Prs_ManErrorSet(p, "Signal list is empty.", 1);
return 0;
}
static inline int Prs_ManReadList2( Prs_Man_t * p )
{
int iToken;
Vec_IntClear( &p->vTemp );
while ( (iToken = Prs_ManReadName(p)) )
Vec_IntPushTwo( &p->vTemp, 0, iToken );
if ( Vec_IntSize(&p->vTemp) == 0 ) return Prs_ManErrorSet(p, "Signal list is empty.", 1);
return 0;
}
static inline int Prs_ManReadList3( Prs_Man_t * p )
{
Vec_IntClear( &p->vTemp );
while ( !Prs_ManIsChar(p, '\n') )
{
int iToken = Prs_ManReadName(p);
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read formal name.", 1);
Vec_IntPush( &p->vTemp, iToken );
Prs_ManSkipSpaces( p );
if ( !Prs_ManIsChar2(p, '=') ) return Prs_ManErrorSet(p, "Cannot find symbol \"=\".", 1);
iToken = Prs_ManReadName(p);
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read actual name.", 1);
Vec_IntPush( &p->vTemp, iToken );
Prs_ManSkipSpaces( p );
}
if ( Vec_IntSize(&p->vTemp) == 0 ) return Prs_ManErrorSet(p, "Cannot read a list of formal/actual names.", 1);
if ( Vec_IntSize(&p->vTemp) % 2 ) return Prs_ManErrorSet(p, "The number of formal/actual names is not even.", 1);
return 0;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline int Prs_ManReadCube( Prs_Man_t * p )
{
assert( Prs_ManIsLit(p) );
while ( Prs_ManIsLit(p) )
Vec_StrPush( &p->vCover, Prs_ManSkip2(p) );
Prs_ManSkipSpaces( p );
if ( Prs_ManIsChar(p, '\n') )
{
if ( Vec_StrSize(&p->vCover) != 1 ) return Prs_ManErrorSet(p, "Cannot read cube.", 1);
// fix single literal cube by adding space
Vec_StrPush( &p->vCover, Vec_StrEntry(&p->vCover,0) );
Vec_StrWriteEntry( &p->vCover, 0, ' ' );
Vec_StrPush( &p->vCover, '\n' );
return 0;
}
if ( !Prs_ManIsLit(p) ) return Prs_ManErrorSet(p, "Cannot read output literal.", 1);
Vec_StrPush( &p->vCover, ' ' );
Vec_StrPush( &p->vCover, Prs_ManSkip2(p) );
Vec_StrPush( &p->vCover, '\n' );
Prs_ManSkipSpaces( p );
if ( !Prs_ManIsChar(p, '\n') ) return Prs_ManErrorSet(p, "Cannot read end of cube.", 1);
return 0;
}
static inline void Prs_ManSaveCover( Prs_Man_t * p )
{
int iToken;
if ( Vec_StrSize(&p->vCover) == 0 )
p->pNtk->fHasC0s = 1;
else if ( Vec_StrSize(&p->vCover) == 2 )
{
if ( Vec_StrEntryLast(&p->vCover) == '0' )
p->pNtk->fHasC0s = 1;
else if ( Vec_StrEntryLast(&p->vCover) == '1' )
p->pNtk->fHasC1s = 1;
else assert( 0 );
}
assert( Vec_StrSize(&p->vCover) > 0 );
Vec_StrPush( &p->vCover, '\0' );
// iToken = Ptr_SopToType( Vec_StrArray(&p->vCover) );
iToken = Abc_NamStrFindOrAdd( p->pFuns, Vec_StrArray(&p->vCover), NULL );
Vec_StrClear( &p->vCover );
// set the cover to the module of this box
assert( Prs_BoxNtk(p->pNtk, Prs_NtkBoxNum(p->pNtk)-1) == 1 ); // default const 0
Prs_BoxSetNtk( p->pNtk, Prs_NtkBoxNum(p->pNtk)-1, iToken );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline int Prs_ManReadInouts( Prs_Man_t * p )
{
if ( Prs_ManReadList(p, &p->pNtk->vOrder, 3) ) return 1;
Vec_IntAppend( &p->pNtk->vInouts, &p->vTemp );
return 0;
}
static inline int Prs_ManReadInputs( Prs_Man_t * p )
{
if ( Prs_ManReadList(p, &p->pNtk->vOrder, 1) ) return 1;
Vec_IntAppend( &p->pNtk->vInputs, &p->vTemp );
return 0;
}
static inline int Prs_ManReadOutputs( Prs_Man_t * p )
{
if ( Prs_ManReadList(p, &p->pNtk->vOrder, 2) ) return 1;
Vec_IntAppend( &p->pNtk->vOutputs, &p->vTemp );
return 0;
}
static inline int Prs_ManReadNode( Prs_Man_t * p )
{
if ( Prs_ManReadList2(p) ) return 1;
// save results
Prs_NtkAddBox( p->pNtk, 1, 0, &p->vTemp ); // default const 0 function
return 0;
}
static inline int Prs_ManReadBox( Prs_Man_t * p, int fGate )
{
int iToken = Prs_ManReadName(p);
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read model name.", 1);
if ( Prs_ManReadList3(p) ) return 1;
// save results
Prs_NtkAddBox( p->pNtk, iToken, 0, &p->vTemp );
if ( fGate ) p->pNtk->fMapped = 1;
return 0;
}
static inline int Prs_ManReadLatch( Prs_Man_t * p )
{
int iToken = Prs_ManReadName(p);
Vec_IntClear( &p->vTemp );
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read latch input.", 1);
Vec_IntWriteEntry( &p->vTemp, 1, iToken );
iToken = Prs_ManReadName(p);
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read latch output.", 1);
Vec_IntWriteEntry( &p->vTemp, 0, iToken );
Prs_ManSkipSpaces( p );
if ( Prs_ManIsChar(p, '0') )
iToken = 0;
else if ( Prs_ManIsChar(p, '1') )
iToken = 1;
else
iToken = 2;
Prs_ManSkipToChar( p, '\n' );
// save results
Prs_NtkAddBox( p->pNtk, -1, iToken, &p->vTemp ); // -1 stands for latch
return 0;
}
static inline int Prs_ManReadShort( Prs_Man_t * p )
{
int iToken = Prs_ManReadName(p);
Vec_IntClear( &p->vTemp );
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read .short input.", 1);
Vec_IntWriteEntry( &p->vTemp, 1, iToken );
iToken = Prs_ManReadName(p);
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read .short output.", 1);
Vec_IntWriteEntry( &p->vTemp, 0, iToken );
Prs_ManSkipSpaces( p );
if ( !Prs_ManIsChar(p, '\n') ) return Prs_ManErrorSet(p, "Trailing symbols on .short line.", 1);
// save results
iToken = Abc_NamStrFindOrAdd( p->pStrs, "1 1\n", NULL );
Prs_NtkAddBox( p->pNtk, iToken, 0, &p->vTemp );
return 0;
}
static inline int Prs_ManReadModel( Prs_Man_t * p )
{
int iToken;
if ( p->pNtk != NULL ) return Prs_ManErrorSet(p, "Parsing previous model is unfinished.", 1);
iToken = Prs_ManReadName(p);
if ( iToken == 0 ) return Prs_ManErrorSet(p, "Cannot read model name.", 1);
Prs_ManInitializeNtk( p, iToken, 0 );
Prs_ManSkipSpaces( p );
if ( !Prs_ManIsChar(p, '\n') ) return Prs_ManErrorSet(p, "Trailing symbols on .model line.", 1);
return 0;
}
static inline int Prs_ManReadEnd( Prs_Man_t * p )
{
if ( p->pNtk == 0 ) return Prs_ManErrorSet(p, "Directive .end without .model.", 1);
//printf( "Saving model \"%s\".\n", Abc_NamStr(p->pStrs, p->iModuleName) );
Prs_ManFinalizeNtk( p );
Prs_ManSkipSpaces( p );
if ( !Prs_ManIsChar(p, '\n') ) return Prs_ManErrorSet(p, "Trailing symbols on .end line.", 1);
return 0;
}
static inline int Prs_ManReadDirective( Prs_Man_t * p )
{
int iToken;
if ( !Prs_ManIsChar(p, '.') )
return Prs_ManReadCube( p );
if ( Vec_StrSize(&p->vCover) > 0 ) // SOP was specified for the previous node
Prs_ManSaveCover( p );
iToken = Prs_ManReadName( p );
if ( iToken == PRS_BLIF_MODEL )
return Prs_ManReadModel( p );
if ( iToken == PRS_BLIF_INOUTS )
return Prs_ManReadInouts( p );
if ( iToken == PRS_BLIF_INPUTS )
return Prs_ManReadInputs( p );
if ( iToken == PRS_BLIF_OUTPUTS )
return Prs_ManReadOutputs( p );
if ( iToken == PRS_BLIF_NAMES )
return Prs_ManReadNode( p );
if ( iToken == PRS_BLIF_SUBCKT )
return Prs_ManReadBox( p, 0 );
if ( iToken == PRS_BLIF_GATE )
return Prs_ManReadBox( p, 1 );
if ( iToken == PRS_BLIF_LATCH )
return Prs_ManReadLatch( p );
if ( iToken == PRS_BLIF_SHORT )
return Prs_ManReadShort( p );
if ( iToken == PRS_BLIF_END )
return Prs_ManReadEnd( p );
printf( "Cannot read directive \"%s\".\n", Abc_NamStr(p->pStrs, iToken) );
return 1;
}
static inline int Prs_ManReadLines( Prs_Man_t * p )
{
while ( p->pCur[1] != '\0' )
{
assert( Prs_ManIsChar(p, '\n') );
Prs_ManSkip(p);
Prs_ManSkipSpaces( p );
if ( Prs_ManIsChar(p, '\n') )
continue;
if ( Prs_ManReadDirective(p) )
return 1;
}
return 0;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Ptr_t * Prs_ManReadBlif( char * pFileName )
{
Vec_Ptr_t * vPrs = NULL;
Prs_Man_t * p = Prs_ManAlloc( pFileName );
if ( p == NULL )
return NULL;
Abc_NamStrFindOrAdd( p->pFuns, " 0\n", NULL );
Abc_NamStrFindOrAdd( p->pFuns, " 1\n", NULL );
Prs_NtkAddBlifDirectives( p );
Prs_ManReadLines( p );
if ( Prs_ManErrorPrint(p) )
ABC_SWAP( Vec_Ptr_t *, vPrs, p->vNtks );
Prs_ManFree( p );
return vPrs;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Prs_ManReadBlifTest( char * pFileName )
{
abctime clk = Abc_Clock();
Vec_Ptr_t * vPrs = Prs_ManReadBlif( pFileName );
if ( !vPrs ) return;
printf( "Finished reading %d networks. ", Vec_PtrSize(vPrs) );
printf( "NameIDs = %d. ", Abc_NamObjNumMax(Prs_ManNameMan(vPrs)) );
printf( "Memory = %.2f MB. ", 1.0*Prs_ManMemory(vPrs)/(1<<20) );
Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
// Abc_NamPrint( p->pStrs );
Prs_ManWriteBlif( Extra_FileNameGenericAppend(pFileName, "_out.blif"), vPrs );
Prs_ManVecFree( vPrs );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Prs_CreateBlifFindFon( Cba_Ntk_t * p, int NameId )
{
int iFon = Cba_NtkGetMap( p, NameId );
if ( iFon )
return iFon;
printf( "Network \"%s\": Signal \"%s\" is not driven.\n", Cba_NtkName(p), Cba_NtkStr(p, NameId) );
return 0;
}
void Prs_CreateBlifPio( Cba_Ntk_t * p, Prs_Ntk_t * pNtk )
{
int i, NameId, iObj, iFon;
Cba_NtkCleanObjFuncs( p );
Cba_NtkCleanObjNames( p );
Cba_NtkCleanFonNames( p );
// create inputs
Prs_NtkForEachPi( pNtk, NameId, i )
{
iObj = Cba_ObjAlloc( p, CBA_OBJ_PI, 0, 1 );
Cba_ObjSetName( p, iObj, NameId );
iFon = Cba_ObjFon0(p, iObj);
Cba_FonSetName( p, iFon, NameId );
Cba_NtkSetMap( p, NameId, iFon );
Vec_IntPush( &p->vOrder, iObj );
}
// create outputs
Prs_NtkForEachPo( pNtk, NameId, i )
{
iObj = Cba_ObjAlloc( p, CBA_OBJ_PO, 1, 0 );
Cba_ObjSetName( p, iObj, NameId );
Vec_IntPush( &p->vOrder, iObj );
}
}
int Prs_CreateBlifNtk( Cba_Ntk_t * p, Prs_Ntk_t * pNtk )
{
Vec_Int_t * vBox;
int i, k, iObj, iTerm, iFon, FormId, ActId;
// map inputs
Cba_NtkCleanMap( p );
Cba_NtkForEachPi( p, iObj, i )
Cba_NtkSetMap( p, Cba_ObjName(p, iObj), Cba_ObjFon0(p, iObj) );
// create objects
Prs_NtkForEachBox( pNtk, vBox, i )
{
int FuncId = Prs_BoxNtk(pNtk, i);
assert( Prs_BoxIONum(pNtk, i) > 0 );
assert( Vec_IntSize(vBox) % 2 == 0 );
if ( FuncId == -1 ) // latch
{
iObj = Cba_ObjAlloc( p, CBA_BOX_DFFRS, 4, 1 );
Cba_NtkSetMap( p, Vec_IntEntry(vBox, 3), Cba_ObjFon0(p, iObj) ); // latch output
Cba_ObjSetFunc( p, iObj, Prs_BoxName(pNtk, i)+1 ); // init + 1
}
else if ( Prs_BoxIsNode(pNtk, i) ) // node
{
iObj = Cba_ObjAlloc( p, CBA_BOX_NODE, Prs_BoxIONum(pNtk, i)-1, 1 );
Cba_FonSetName( p, Cba_ObjFon0(p, iObj), Vec_IntEntryLast(vBox) ); // node output
Cba_NtkSetMap( p, Vec_IntEntryLast(vBox), Cba_ObjFon0(p, iObj) );
Cba_ObjSetFunc( p, iObj, FuncId );
}
else // box
{
Cba_Ntk_t * pBox = Cba_ManNtkFind( p->pDesign, Prs_NtkStr(pNtk, FuncId) );
iObj = Cba_ObjAlloc( p, CBA_OBJ_BOX, Cba_NtkPiNum(pBox), Cba_NtkPoNum(pBox) );
Cba_ObjSetFunc( p, iObj, Cba_NtkId(pBox) );
// mark PO objects
Cba_NtkCleanMap2( p );
Cba_NtkForEachPo( pBox, iTerm, k )
Cba_NtkSetMap2( p, Cba_ObjName(pBox, iTerm), k+1 );
// map box fons
Vec_IntForEachEntryDouble( vBox, FormId, ActId, k )
if ( Cba_NtkGetMap2(p, FormId) )
{
iFon = Cba_ObjFon(p, iObj, Cba_NtkGetMap2(p, FormId)-1);
Cba_FonSetName( p, iFon, ActId );
Cba_NtkSetMap( p, ActId, iFon );
}
}
}
// connect objects
Prs_NtkForEachBox( pNtk, vBox, i )
{
iObj = Cba_NtkPiNum(p) + Cba_NtkPoNum(p) + i + 1;
if ( Prs_BoxNtk(pNtk, i) == -1 ) // latch
{
assert( Cba_ObjType(p, iObj) == CBA_BOX_DFFRS );
iFon = Prs_CreateBlifFindFon( p, Vec_IntEntry(vBox, 1) ); // latch input
if ( iFon )
Cba_ObjSetFinFon( p, iObj, 0, iFon );
}
else if ( Prs_BoxIsNode(pNtk, i) ) // node
{
assert( Cba_ObjType(p, iObj) == CBA_BOX_NODE );
Vec_IntForEachEntryDouble( vBox, FormId, ActId, k )
{
if ( k == 2 * Cba_ObjFinNum(p, iObj) ) // stop at node output
break;
iFon = Prs_CreateBlifFindFon( p, ActId );
if ( iFon )
Cba_ObjSetFinFon( p, iObj, k/2, iFon );
}
}
else // box
{
// mark PI objects
Cba_Ntk_t * pBox = Cba_ObjNtk(p, iObj);
assert( Cba_NtkPiNum(pBox) == Cba_ObjFinNum(p, iObj) );
assert( Cba_NtkPoNum(pBox) == Cba_ObjFonNum(p, iObj) );
Cba_NtkCleanMap2( p );
Cba_NtkForEachPi( pBox, iTerm, k )
Cba_NtkSetMap2( p, Cba_ObjName(pBox, iTerm), k+1 );
// connect box fins
Vec_IntForEachEntryDouble( vBox, FormId, ActId, k )
if ( Cba_NtkGetMap2(p, FormId) )
{
iFon = Prs_CreateBlifFindFon( p, ActId );
if ( iFon )
Cba_ObjSetFinFon( p, iObj, Cba_NtkGetMap2(p, FormId)-1, iFon );
}
}
}
// connect outputs
Cba_NtkForEachPo( p, iObj, i )
{
iFon = Prs_CreateBlifFindFon( p, Cba_ObjName(p, iObj) );
if ( iFon )
Cba_ObjSetFinFon( p, iObj, 0, iFon );
}
return 0;
}
Cba_Man_t * Prs_ManBuildCbaBlif( char * pFileName, Vec_Ptr_t * vDes )
{
Prs_Ntk_t * pPrsNtk; int i, fError = 0;
Prs_Ntk_t * pPrsRoot = Prs_ManRoot(vDes);
// start the manager
Abc_Nam_t * pStrs = Abc_NamRef(pPrsRoot->pStrs);
Abc_Nam_t * pFuns = Abc_NamRef(pPrsRoot->pFuns);
Abc_Nam_t * pMods = Abc_NamStart( 100, 24 );
Cba_Man_t * p = Cba_ManAlloc( pFileName, Vec_PtrSize(vDes), pStrs, pFuns, pMods, NULL );
// initialize networks
Vec_PtrForEachEntry( Prs_Ntk_t *, vDes, pPrsNtk, i )
{
Cba_Ntk_t * pNtk = Cba_NtkAlloc( p, Prs_NtkId(pPrsNtk), Prs_NtkPiNum(pPrsNtk), Prs_NtkPoNum(pPrsNtk), Prs_NtkObjNum(pPrsNtk), 100, 100 );
Prs_CreateBlifPio( pNtk, pPrsNtk );
Cba_NtkAdd( p, pNtk );
}
// create networks
Vec_PtrForEachEntry( Prs_Ntk_t *, vDes, pPrsNtk, i )
{
printf( "Elaboration module \"%s\"...\n", Prs_NtkName(pPrsNtk) );
fError = Prs_CreateBlifNtk( Cba_ManNtk(p, i+1), pPrsNtk );
if ( fError )
break;
}
if ( fError )
printf( "Quitting because of errors.\n" );
else
Cba_ManPrepareSeq( p );
return p;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Cba_Man_t * Cba_ManReadBlif( char * pFileName )
{
Cba_Man_t * p = NULL;
Vec_Ptr_t * vDes = Prs_ManReadBlif( pFileName );
if ( vDes && Vec_PtrSize(vDes) )
p = Prs_ManBuildCbaBlif( pFileName, vDes );
if ( vDes )
Prs_ManVecFree( vDes );
return p;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
| 35.562597 | 146 | 0.497762 | [
"model"
] |
2c94f4c7ff9420dba3fa672ceca28b6412bcbbee | 13,518 | h | C | interface/include/psa/service.h | andvib/trusted-firmware-m | e9c174a98ac13ae1776d9f9908879bb9c3cc847f | [
"BSD-3-Clause"
] | null | null | null | interface/include/psa/service.h | andvib/trusted-firmware-m | e9c174a98ac13ae1776d9f9908879bb9c3cc847f | [
"BSD-3-Clause"
] | null | null | null | interface/include/psa/service.h | andvib/trusted-firmware-m | e9c174a98ac13ae1776d9f9908879bb9c3cc847f | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018-2021, Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef __PSA_SERVICE_H__
#define __PSA_SERVICE_H__
#include <stddef.h>
#include <stdint.h>
#include "psa/client.h"
#include "psa_config.h"
#include "psa/error.h"
#ifdef __cplusplus
extern "C" {
#endif
/********************** PSA Secure Partition Macros and Types ****************/
/**
* A timeout value that requests a polling wait operation.
*/
#define PSA_POLL (0x00000000u)
/**
* A timeout value that requests a blocking wait operation.
*/
#define PSA_BLOCK (0x80000000u)
/**
* A mask value that includes all Secure Partition signals.
*/
#define PSA_WAIT_ANY (0xFFFFFFFFu)
/**
* The signal number for the Secure Partition doorbell.
*/
#define PSA_DOORBELL (0x00000008u)
/* PSA message types */
/* An IPC message type that indicates a new connection. */
#define PSA_IPC_CONNECT (-1)
/* An IPC message type that indicates the end of a connection. */
#define PSA_IPC_DISCONNECT (-2)
/* FLIH return types */
#define PSA_FLIH_NO_SIGNAL ((psa_flih_result_t) 0)
#define PSA_FLIH_SIGNAL ((psa_flih_result_t) 1)
/* Store a set of one or more Secure Partition signals */
typedef uint32_t psa_signal_t;
/* A type used to temporarily store a previous interrupt state. */
typedef uint32_t psa_irq_status_t;
/* The type of the return value from an FLIH function */
typedef uint32_t psa_flih_result_t;
/**
* Describe a message received by an RoT Service after calling \ref psa_get().
*/
typedef struct psa_msg_t {
int32_t type; /* One of the following values:
* \ref PSA_IPC_CONNECT
* >= 0
* \ref PSA_IPC_DISCONNECT
*/
psa_handle_t handle; /* A reference generated by the SPM to the
* message returned by psa_get().
*/
int32_t client_id; /* Partition ID of the sender of the message */
void *rhandle; /* Be useful for binding a connection to some
* application-specific data or function
* pointer within the RoT Service
* implementation.
*/
size_t in_size[PSA_MAX_IOVEC]; /* Provide the size of each client input
* vector in bytes.
*/
size_t out_size[PSA_MAX_IOVEC];/* Provide the size of each client output
* vector in bytes.
*/
} psa_msg_t;
/************************* PSA Secure Partition API **************************/
/**
* \brief Return the Secure Partition interrupt signals that have been asserted
* from a subset of signals provided by the caller.
*
* \param[in] signal_mask A set of signals to query. Signals that are not
* in this set will be ignored.
* \param[in] timeout Specify either blocking \ref PSA_BLOCK or
* polling \ref PSA_POLL operation.
*
* \retval >0 At least one signal is asserted.
* \retval 0 No signals are asserted. This is only seen when
* a polling timeout is used.
*/
psa_signal_t psa_wait(psa_signal_t signal_mask, uint32_t timeout);
/**
* \brief Retrieve the message which corresponds to a given RoT Service signal
* and remove the message from the RoT Service queue.
*
* \param[in] signal The signal value for an asserted RoT Service.
* \param[out] msg Pointer to \ref psa_msg_t object for receiving
* the message.
*
* \retval PSA_SUCCESS Success, *msg will contain the delivered
* message.
* \retval PSA_ERROR_DOES_NOT_EXIST Message could not be delivered.
* \retval "PROGRAMMER ERROR" The call is invalid because one or more of the
* following are true:
* \arg signal has more than a single bit set.
* \arg signal does not correspond to an RoT Service.
* \arg The RoT Service signal is not currently
* asserted.
* \arg The msg pointer provided is not a valid memory
* reference.
*/
psa_status_t psa_get(psa_signal_t signal, psa_msg_t *msg);
/**
* \brief Associate some RoT Service private data with a client connection.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] rhandle Reverse handle allocated by the RoT Service.
*
* \retval void Success, rhandle will be provided with all
* subsequent messages delivered on this
* connection.
* \retval "PROGRAMMER ERROR" msg_handle is invalid.
*/
void psa_set_rhandle(psa_handle_t msg_handle, void *rhandle);
/**
* \brief Read a message parameter or part of a message parameter from a client
* input vector.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] invec_idx Index of the input vector to read from. Must be
* less than \ref PSA_MAX_IOVEC.
* \param[out] buffer Buffer in the Secure Partition to copy the
* requested data to.
* \param[in] num_bytes Maximum number of bytes to be read from the
* client input vector.
*
* \retval >0 Number of bytes copied.
* \retval 0 There was no remaining data in this input
* vector.
* \retval "PROGRAMMER ERROR" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg msg_handle does not refer to a
* \ref PSA_IPC_CALL message.
* \arg invec_idx is equal to or greater than
* \ref PSA_MAX_IOVEC.
* \arg the memory reference for buffer is invalid or
* not writable.
*/
size_t psa_read(psa_handle_t msg_handle, uint32_t invec_idx,
void *buffer, size_t num_bytes);
/**
* \brief Skip over part of a client input vector.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] invec_idx Index of input vector to skip from. Must be
* less than \ref PSA_MAX_IOVEC.
* \param[in] num_bytes Maximum number of bytes to skip in the client
* input vector.
*
* \retval >0 Number of bytes skipped.
* \retval 0 There was no remaining data in this input
* vector.
* \retval "PROGRAMMER ERROR" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg msg_handle does not refer to a request
* message.
* \arg invec_idx is equal to or greater than
* \ref PSA_MAX_IOVEC.
*/
size_t psa_skip(psa_handle_t msg_handle, uint32_t invec_idx, size_t num_bytes);
/**
* \brief Write a message response to a client output vector.
*
* \param[in] msg_handle Handle for the client's message.
* \param[out] outvec_idx Index of output vector in message to write to.
* Must be less than \ref PSA_MAX_IOVEC.
* \param[in] buffer Buffer with the data to write.
* \param[in] num_bytes Number of bytes to write to the client output
* vector.
*
* \retval void Success
* \retval "PROGRAMMER ERROR" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg msg_handle does not refer to a request
* message.
* \arg outvec_idx is equal to or greater than
* \ref PSA_MAX_IOVEC.
* \arg The memory reference for buffer is invalid.
* \arg The call attempts to write data past the end
* of the client output vector.
*/
void psa_write(psa_handle_t msg_handle, uint32_t outvec_idx,
const void *buffer, size_t num_bytes);
/**
* \brief Complete handling of a specific message and unblock the client.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] status Message result value to be reported to the
* client.
*
* \retval void Success.
* \retval "PROGRAMMER ERROR" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg An invalid status code is specified for the
* type of message.
*/
void psa_reply(psa_handle_t msg_handle, psa_status_t status);
/**
* \brief Send a PSA_DOORBELL signal to a specific Secure Partition.
*
* \param[in] partition_id Secure Partition ID of the target partition.
*
* \retval void Success.
* \retval "PROGRAMMER ERROR" partition_id does not correspond to a Secure
* Partition.
*/
void psa_notify(int32_t partition_id);
/**
* \brief Clear the PSA_DOORBELL signal.
*
* \retval void Success.
* \retval "PROGRAMMER ERROR" The Secure Partition's doorbell signal is not
* currently asserted.
*/
void psa_clear(void);
/**
* \brief Inform the SPM that an interrupt has been handled (end of interrupt).
*
* \param[in] irq_signal The interrupt signal that has been processed.
*
* \retval void Success.
* \retval "PROGRAMMER ERROR" The call is invalid, one or more of the
* following are true:
* \arg irq_signal is not an interrupt signal.
* \arg irq_signal indicates more than one signal.
* \arg irq_signal is not currently asserted.
* \arg The interrupt is not using SLIH.
*/
void psa_eoi(psa_signal_t irq_signal);
/**
* \brief Terminate execution within the calling Secure Partition and will not
* return.
*
* \retval "Does not return"
*/
void psa_panic(void);
/**
* \brief Enable an interrupt.
*
* \param[in] irq_signal The signal for the interrupt to be enabled.
* This must have a single bit set, which must be the
* signal value for an interrupt in the calling Secure
* Partition.
*
* \retval void
* \retval "PROGRAMMER ERROR" If one or more of the following are true:
* \arg \a irq_signal is not an interrupt signal.
* \arg \a irq_signal indicates more than one signal.
*/
void psa_irq_enable(psa_signal_t irq_signal);
/**
* \brief Disable an interrupt and return the status of the interrupt prior to
* being disabled by this call.
*
* \param[in] irq_signal The signal for the interrupt to be disabled.
* This must have a single bit set, which must be the
* signal value for an interrupt in the calling Secure
* Partition.
*
* \retval 0 The interrupt was disabled prior to this call.
* 1 The interrupt was enabled prior to this call.
* \retval "PROGRAMMER ERROR" If one or more of the following are true:
* \arg \a irq_signal is not an interrupt signal.
* \arg \a irq_signal indicates more than one signal.
*
* \note The current implementation always return 1. Do not use the return.
*/
psa_irq_status_t psa_irq_disable(psa_signal_t irq_signal);
/**
* \brief Reset the signal for an interrupt that is using FLIH handling.
*
* \param[in] irq_signal The interrupt signal to be reset.
* This must have a single bit set, corresponding to a
* currently asserted signal for an interrupt that is
* defined to use FLIH handling.
*
* \retval void
* \retval "Programmer Error" if one or more of the following are true:
* \arg \a irq_signal is not a signal for an interrupt
* that is specified with FLIH handling in the Secure
* Partition manifest.
* \arg \a irq_signal indicates more than one signal.
* \arg \a irq_signal is not currently asserted.
*/
void psa_reset_signal(psa_signal_t irq_signal);
#ifdef __cplusplus
}
#endif
#endif /* __PSA_SERVICE_H__ */
| 40.716867 | 80 | 0.555704 | [
"object",
"vector"
] |
2c9bbf651bae37b29512d6eaf32f1e45b9e79332 | 208,906 | c | C | Dmf/Modules.Library/Dmf_ComponentFirmwareUpdate.c | girishpattabiraman/DMF | 4da6d1ee36699fbba5247684c4946370dea745bb | [
"MIT"
] | null | null | null | Dmf/Modules.Library/Dmf_ComponentFirmwareUpdate.c | girishpattabiraman/DMF | 4da6d1ee36699fbba5247684c4946370dea745bb | [
"MIT"
] | null | null | null | Dmf/Modules.Library/Dmf_ComponentFirmwareUpdate.c | girishpattabiraman/DMF | 4da6d1ee36699fbba5247684c4946370dea745bb | [
"MIT"
] | null | null | null | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT license.
Module Name:
Dmf_ComponentFirmwareUpdate.c
Abstract:
This Module handles Component Firmware Update Protocol.
Environment:
User-mode Driver Framework
--*/
// DMF and this Module's Library specific definitions.
//
#include "DmfModule.h"
#include "DmfModules.Library.h"
#include "DmfModules.Library.Trace.h"
#if defined(DMF_INCLUDE_TMH)
#include "Dmf_ComponentFirmwareUpdate.tmh"
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Module Private Enumerations and Structures
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
#include <intsafe.h>
// Defines a single offer and payload content.
//
typedef struct _FIRMWARE_INFORMATION
{
// Size in bytes of the Offer and Payload that is sent to device.
//
size_t OfferSize;
size_t PayloadSize;
// Holds the buffer either created locally or the client given.
//
WDFMEMORY OfferContentMemory;
// Holds the buffer either created locally or the client given.
//
WDFMEMORY PayloadContentMemory;
} FIRMWARE_INFORMATION;
// Defines all the firmware update status that are used internally.
// These values are updated in the registry to mark various stages of protocol sequence.
//
typedef enum _FIRMWARE_UPDATE_STATUS
{
FIRMWARE_UPDATE_STATUS_NOT_STARTED = 0x00,
FIRMWARE_UPDATE_STATUS_UPDATE_REJECTED,
FIRMWARE_UPDATE_STATUS_DOWNLOADING_UPDATE,
FIRMWARE_UPDATE_STATUS_BUSY_PROCESSING_UPDATE,
FIRMWARE_UPDATE_STATUS_PENDING_RESET,
FIRMWARE_UPDATE_STATUS_UP_TO_DATE,
FIRMWARE_UPDATE_STATUS_ERROR = 0xFF
} FIRMWARE_UPDATE_STATUS;
// Size of the maximum value name in registry (per MSDN).
//
#define MAXIMUM_VALUE_NAME_SIZE 16382
// Protocol versions.
//
#define PROTOCOL_VERSION_2 0x2
#define PROTOCOL_VERSION_4 0x4
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Module Private Context.
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Structure to hold a response to a payload chunk that was sent to device.
// Response message includes a sequence number and the response status.
//
typedef struct _PAYLOAD_RESPONSE
{
UINT16 SequenceNumber;
COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE ResponseStatus;
} PAYLOAD_RESPONSE;
// This context associated with the plugged in protocol Module.
//
typedef struct _CONTEXT_ComponentFirmwareUpdateTransaction
{
// Asynchronous Response Handling Contexts.
// ----------------------------------------
//
// Callback Status.
NTSTATUS ntStatus;
// Buffer List to hold the Payload Responses.
//
DMFMODULE DmfModuleBufferQueue;
// Offer Response.
//
OFFER_RESPONSE OfferResponse;
// Firmware Versions.
//
COMPONENT_FIRMWARE_VERSIONS FirmwareVersions;
// Event to Signal threads that are waiting for a response from transport.
//
DMF_PORTABLE_EVENT DmfResponseCompletionEvent;
// Event to Signal Cancellation of protocol transaction.
//
DMF_PORTABLE_EVENT DmfProtocolTransactionCancelEvent;
// Asynchronous Response Handling Contexts.
// ----------------------------------------
} CONTEXT_ComponentFirmwareUpdateTransaction;
WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CONTEXT_ComponentFirmwareUpdateTransaction, ComponentFirmwareUpdateTransactionContextGet)
// Private context the Protocol Module associates with an Interface.
//
typedef struct _CONTEXT_ComponentFirmwareUpdateTransport
{
// Wait Time out in Ms for response from transport.
//
ULONG TransportWaitTimeout;
// Size of TransportHeader in bytes.
// The protocol module will allocate header block at the beginning of the buffer for to transport to use.
//
ULONG TransportHeaderSize;
// Required size of Firmware Payload Buffer this transport needs (excluding the TransportHeaderSize above).
//
ULONG TransportFirmwarePayloadBufferRequiredSize;
// Required size of Offer Buffer this transport needs (excluding the TransportHeaderSize above).
//
ULONG TransportOfferBufferRequiredSize;
// Required size of FirmwareVersion Buffer this transport needs (excluding the TransportHeaderSize above).
//
ULONG TransportFirmwareVersionBufferRequiredSize;
// Payload buffer fill alignment this transport needs.
//
UINT TransportPayloadFillAlignment;
} CONTEXT_ComponentFirmwareUpdateTransport;
WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(CONTEXT_ComponentFirmwareUpdateTransport, ComponentFirmwareUpdateTransportContextGet)
typedef struct
{
// Protocol sequence Thread Handle.
//
DMFMODULE DmfModuleThread;
// Interface Handle.
//
DMFINTERFACE DmfInterfaceComponentFirmwareUpdate;
// Firmware blob containing the firmware data (offers & payloads) that this Module needs to send to device.
//
WDFCOLLECTION FirmwareBlobCollection;
// Registry Key to store Firmware Update Process related book keeping information in registry.
//
WDFKEY DeviceRegistryKey;
// Is a protocol transaction in progress?.
//
BOOLEAN TransactionInProgress;
} DMF_CONTEXT_ComponentFirmwareUpdate;
// This macro declares the following function:
// DMF_CONTEXT_GET()
//
DMF_MODULE_DECLARE_CONTEXT(ComponentFirmwareUpdate)
// This macro declares the following function:
// DMF_CONFIG_GET()
//
DMF_MODULE_DECLARE_CONFIG(ComponentFirmwareUpdate)
///////////////////////////////////////////////////////////////////////////////////////////////////////
// DMF Module Support Code
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Registry Keys Firmware Update Status (Keeping the existing registry key names).
//
PCWSTR ComponentFirmwareUpdate_CurrentFwVersionValueName = L"CurrentFwVersion";
PCWSTR ComponentFirmwareUpdate_OfferFwVersionValueName = L"OfferFwVersion";
PCWSTR ComponentFirmwareUpdate_FirmwareUpdateStatusValueName = L"FirmwareUpdateStatus";
PCWSTR ComponentFirmwareUpdate_FirmwareUpdateStatusRejectReasonValueName = L"FirmwareUpdateStatusRejectReason";
PCWSTR ComponentFirmwareUpdate_ResumePayloadBufferBinRecordIndexValueName = L"ResumePayloadBinRecordIndex";
PCWSTR ComponentFirmwareUpdate_ResumePayloadBufferBinRecordDataOffsetValueName = L"ResumePayloadBufferBinRecordDataOffset";
PCWSTR ComponentFirmwareUpdate_ResumeSequenceNumberValueName = L"ResumeSequenceNumber";
PCWSTR ComponentFirmwareUpdate_ResumeOnConnectValueName = L"ResumeOnConnect";
// Based on Specification.
//
// Each time 60 bytes of Payload sent.
//
#define SizeOfPayload (60)
// Offer is 16 bytes long.
//
#define SizeOfOffer (4*sizeof(ULONG))
// Firmware Version is 60 bytes long.
//
#define SizeOfFirmwareVersion (60)
#define Thread_NumberOfWaitObjects (2)
const BYTE FWUPDATE_DRIVER_TOKEN = 0xA0;
const BYTE FWUPDATE_INFORMATION_TOKEN = 0xFF;
const BYTE FWUPDATE_COMMAND_TOKEN = 0xFE;
// Memory Pool Tag.
//
#define MemoryTag 'tUFC'
// This macro takes a variable name (usually an enum) and has the function return.
// a c-string interpretation of the variable name.
// Ex: MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_SUCCESS) returns "COMPONENT_FIRMWARE_UPDATE_SUCCESS".
//
#define MAKE_CASE(x) case x: return #x;
PCSTR
ComponentFirmwareUpdatePayloadResponseString(
_In_ const COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE firmwareUpdateDataStatus
)
{
switch (firmwareUpdateDataStatus)
{
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_SUCCESS);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_PREPARE);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_WRITE);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_COMPLETE);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_VERIFY);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_CRC);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_SIGNATURE);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_VERSION);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_SWAP_PENDING);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_INVALID_ADDR);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_NO_OFFER);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_ERROR_INVALID);
default:
DmfAssert(FALSE);
return "Unknown";
}
}
PCSTR
ComponentFirmwareUpdateOfferInformationCodeString(
_In_ const COMPONENT_FIRMWARE_UPDATE_OFFER_INFORMATION_CODE FirmwareUpdateOfferInformationCode
)
{
switch (FirmwareUpdateOfferInformationCode)
{
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_INFO_START_ENTIRE_TRANSACTION);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_INFO_START_OFFER_LIST);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_INFO_END_OFFER_LIST);
default:
DmfAssert(FALSE);
return "Unknown";
}
}
PCSTR
ComponentFirmwareUpdateOfferCommandCodeString(
_In_ const COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_CODE FirmwareUpdateOfferCommandCode
)
{
switch (FirmwareUpdateOfferCommandCode)
{
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_NOTIFY_ON_READY);
default:
DmfAssert(FALSE);
return "Unknown";
}
}
PCSTR
ComponentFirmwareUpdateOfferResponseString(
_In_ const COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE FirmwareUpdateOfferResponse
)
{
switch (FirmwareUpdateOfferResponse)
{
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_SKIP);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_ACCEPT);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_BUSY);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_READY);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_NOT_SUPPORTED);
default:
DmfAssert(FALSE);
return "Unknown";
}
}
PCSTR
ComponentFirmwareUpdateOfferResponseRejectString(
_In_ const COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON FirmwareUpdateOfferRejectReason
)
{
switch (FirmwareUpdateOfferRejectReason)
{
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_OLD_FW);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_INV_MCU);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_SWAP_PENDING);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_MISMATCH);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_BANK);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_PLATFORM);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_MILESTONE);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_INV_PCOL_REV);
MAKE_CASE(COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_VARIANT);
default:
if (FirmwareUpdateOfferRejectReason >= COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_VENDOR_SPECIFIC_MIN &&
FirmwareUpdateOfferRejectReason <= COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_VENDOR_SPECIFIC_MAX)
{
return "COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_VENDOR_SPECIFIC";
}
else
{
DmfAssert(FALSE);
return "Unknown";
}
}
}
//-- Helper functions ---
//--------START----------
//
#pragma code_seg("PAGE")
NTSTATUS
ComponentFirmwareUpdate_WaitForResponse(
_In_ DMFMODULE DmfModule,
_In_ ULONG TransportWaitTimeoutMs
)
/*++
Routine Description:
Helper function that waits until there is either a response or timeout or error in wait.
Parameters:
DmfModule - This Module's DMF Object.
TransportWaitTimeoutMs - TransportWaitTimeout in Milliseconds.
Return:
NTSTATUS This returns STATUS_SUCCESS only when there is an actual response completion in time.
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
DMF_PORTABLE_EVENT* waitObjects[Thread_NumberOfWaitObjects];
NTSTATUS waitStatus;
PAGED_CODE();
moduleContext = DMF_CONTEXT_GET(DmfModule);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
// Wait for response.
//
waitObjects[0] = &componentFirmwareUpdateTransactionContext->DmfResponseCompletionEvent;
waitObjects[1] = &componentFirmwareUpdateTransactionContext->DmfProtocolTransactionCancelEvent;
waitStatus = DMF_Portable_EventWaitForMultiple(ARRAYSIZE(waitObjects),
waitObjects,
FALSE,
&TransportWaitTimeoutMs,
FALSE);
switch (waitStatus)
{
case STATUS_WAIT_0:
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Response Received.");
ntStatus = STATUS_SUCCESS;
break;
}
case STATUS_WAIT_1:
{
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Operation cancelled.");
ntStatus = STATUS_TRANSACTION_ABORTED;
goto Exit;
}
case WAIT_TIMEOUT:
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Read operation timed out");
ntStatus = STATUS_INVALID_DEVICE_STATE;
goto Exit;
}
default:
{
DmfAssert(FALSE);
ntStatus = STATUS_INVALID_DEVICE_STATE;
goto Exit;
}
}
Exit:
return ntStatus;
}
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
NTSTATUS
ComponentFirmwareUpdate_PayloadResponseProcess(
_In_ DMFMODULE DmfModule,
_In_ UINT16 ExpectedSequenceNumber,
_Out_ COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE* PayloadResponse
)
/*++
Routine Description:
Helper is a function that Waits for & then processe the response to a payload message that was send to device.
The response have a sequence number; This function matches the response sequence number to the one specified as argument.
Parameters:
DmfModule - This Module's DMF Object.
ExpectedSequenceNumber - Sequence Number that we are expecting see in the response.
PayloadResponse - Response retrieved from the device.
Return:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
const UINT maxSequenceNumberMatchAttempts = 3;
UINT sequenceNumberMatchAttempts;
BOOL sequenceNumberMatches;
VOID* clientBuffer = NULL;
VOID* clientBufferContext = NULL;
PAGED_CODE();
FuncEntry(DMF_TRACE);
moduleContext = DMF_CONTEXT_GET(DmfModule);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransportContext != NULL);
ntStatus = STATUS_SUCCESS;
// Loop until we receive a response with the matching sequence number.
// Only loop a maximum number of times.
//
sequenceNumberMatches = FALSE;
sequenceNumberMatchAttempts = 0;
while (!sequenceNumberMatches && (sequenceNumberMatchAttempts < maxSequenceNumberMatchAttempts))
{
// Wait for response.
//
ntStatus = ComponentFirmwareUpdate_WaitForResponse(DmfModule,
componentFirmwareUpdateTransportContext->TransportWaitTimeout);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WaitForResponse fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Get all the completed responses and see if we have a matching sequence number.
//
do
{
clientBufferContext = NULL;
clientBuffer = NULL;
// Process the response.
//
ntStatus = DMF_BufferQueue_Dequeue(componentFirmwareUpdateTransactionContext->DmfModuleBufferQueue,
&clientBuffer,
&clientBufferContext);
if (!NT_SUCCESS(ntStatus))
{
// There is no data buffer for the processing.
//
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"No more buffer for Payload Response Processing");
// We dont expect to hit this first time in this loop.
//
DmfAssert(sequenceNumberMatchAttempts != 0);
break;
}
DmfAssert(clientBuffer != NULL);
DmfAssert(clientBufferContext != NULL);
PAYLOAD_RESPONSE* payloadResponse = (PAYLOAD_RESPONSE*)clientBuffer;
#if defined(DEBUG)
ULONG* payloadResponseLength = (ULONG*)clientBufferContext;
DmfAssert(*payloadResponseLength == sizeof(PAYLOAD_RESPONSE));
#endif // defined(DEBUG)
if (ExpectedSequenceNumber > payloadResponse->SequenceNumber)
{
// This can happen if the device resends a message {Historical reason may be}.
//
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"sequenceNumber(%d) > responseSequenceNumber(%d) in sequenceNumberMatchAttempt(%d)",
ExpectedSequenceNumber,
payloadResponse->SequenceNumber,
sequenceNumberMatchAttempts);
// Continue with the loop.
//
}
else if (ExpectedSequenceNumber < payloadResponse->SequenceNumber)
{
// This is an error case.
//
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"sequenceNumber(%d) < responseSequenceNumber(%d) in sequenceNumberMatchAttempt(%d)",
ExpectedSequenceNumber,
payloadResponse->SequenceNumber,
sequenceNumberMatchAttempts);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
}
else
{
// We found a matching sequence number. (ExpectedSequenceNumber == responseSequenceNumber)
//
*PayloadResponse = payloadResponse->ResponseStatus;
sequenceNumberMatches = TRUE;
}
// NOTE: clientBuffer is always valid here and it needs to be returned.
//
// We are done with the buffer from consumer; put it back to producer.
//
DMF_BufferQueue_Reuse(componentFirmwareUpdateTransactionContext->DmfModuleBufferQueue,
clientBuffer);
clientBuffer = NULL;
if (!NT_SUCCESS(ntStatus))
{
break;
}
sequenceNumberMatchAttempts++;
} while (!sequenceNumberMatches && sequenceNumberMatchAttempts < maxSequenceNumberMatchAttempts);
}
if (!sequenceNumberMatches)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Never matched sequence number.");
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_PayloadBufferFill(
_In_ DMFMODULE DmfModule,
_In_ const UINT16 SequenceNumber,
_In_reads_(PayloadBufferSize) const BYTE* PayloadBuffer,
_In_ const size_t PayloadBufferSize,
_Inout_ ULONG &PayloadBufferBinRecordStartIndex,
_Inout_ BYTE &PayloadBufferBinRecordDataOffset,
_Out_writes_(TransferBufferSize) UCHAR* TransferBuffer,
_In_ const BYTE TransferBufferSize
)
/*++
Routine Description:
Reads whole payload data and fill up a payload chunk ready to send to device.
TransferBuffer holds the prepared data and
PayloadBufferBinRecordStartIndex updated to index to the next unread entry in payloadBuffer and
PayloadBufferBinRecordDataOffset updated to how far into the entry we have read.
Arguments:
DmfModule - This Module's DMF Object.
SequenceNumber - Sequence number to be used in this payload.
PayloadBuffer - Payload data from the blob. This is the whole payload.
PayloadBufferSize - Size of the above buffer.
PayloadBufferBinRecordStartIndex - Index into PayloadBuffer that corresponds to a bin record's beginning.
PayloadBufferBinRecordDataOffset - Data offset into the current bin record.
TransferBuffer - Buffer where the data will be written. This is the current payload chunk.
TransferBufferSize - Size of TransferBuffer.
Return Value:
NTSTATUS
--*/
{
// Enable 1 byte packing for our structs.
//
#include <pshpack1.h>
// This private structure holds the CFU formatted bin file, which is ||ADDR|L|DATA....
// Addr is 4 bytes, length is 1 bytes, and data[] as defined by length.
//
typedef struct _BIN_RECORD
{
ULONG Address;
BYTE Length;
BYTE BinData[1];
} BIN_RECORD;
// This private structure is used to build the Transfer buffer.
//
typedef struct _PAYLOAD
{
BYTE Flags;
BYTE DataLength;
UINT16 SequenceNumber;
ULONG Address;
BYTE PayloadData[1];
} PAYLOAD;
#include <poppack.h>
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
errno_t errorNumber;
BYTE dataLength;
BYTE remainingPayloadBufferLength;
UINT32 lastAddressConsumed;
BYTE payloadBufferOffset;
BIN_RECORD *currentBinRecord;
PAYLOAD *payload;
const UINT32 BinRecordHeaderLength = sizeof(ULONG) + sizeof(BYTE);
const UINT32 PayloadHeaderLength = sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) + sizeof(ULONG);
PAGED_CODE();
FuncEntry(DMF_TRACE);
DmfAssert(PayloadBuffer != NULL);
DmfAssert(TransferBuffer != NULL);
moduleContext = DMF_CONTEXT_GET(DmfModule);
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
ntStatus = STATUS_SUCCESS;
// Check if the input buffer size has the minimum length requirement for Address and Length.
// We will check if the data field is valid later.
//
if ( PayloadBufferSize - PayloadBufferBinRecordStartIndex < BinRecordHeaderLength)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Payload Buffer is corrupted. Size remaining %Iu is less than the minimum required (%Iu)",
(PayloadBufferSize - PayloadBufferBinRecordStartIndex),
BinRecordHeaderLength);
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
// Clear the output buffer.
//
ZeroMemory(TransferBuffer,
TransferBufferSize);
currentBinRecord = (BIN_RECORD*) (PayloadBuffer + PayloadBufferBinRecordStartIndex);
payload = (PAYLOAD*) TransferBuffer;
payload->Address = currentBinRecord->Address + PayloadBufferBinRecordDataOffset;
payload->SequenceNumber = SequenceNumber;
payload->Flags = COMPONENT_FIRMWARE_UPDATE_FLAG_DEFAULT;
remainingPayloadBufferLength = TransferBufferSize - PayloadHeaderLength;
// Adjust the RemainingPayloadBufferLength as per the alignment.
//
if (remainingPayloadBufferLength % componentFirmwareUpdateTransportContext->TransportPayloadFillAlignment == 0)
{
// Do nothing, already aligned.
}
else
{
remainingPayloadBufferLength -= (remainingPayloadBufferLength % componentFirmwareUpdateTransportContext->TransportPayloadFillAlignment);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Setting buffer length to %d to meet alignment requirements.",
remainingPayloadBufferLength);
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"PayloadBufferIndex[0x%x] address 0x%x length %d PayloadBufferSize 0x%Ix TransferBufferSize 0x%Ix",
PayloadBufferBinRecordStartIndex,
currentBinRecord->Address,
currentBinRecord->Length,
PayloadBufferSize,
TransferBufferSize);
payloadBufferOffset = 0;
while (1)
{
// We check if the length of the payload buffer has the length specified by the length field.
// Note: we can only check if the required length is satisfied, we have no way to know if the data
// is correct or not.
//
if (PayloadBufferBinRecordStartIndex + BinRecordHeaderLength + currentBinRecord->Length > PayloadBufferSize)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Payload Buffer is corrupted. Length of buffer remaining is %Iu, which is less than the length specified (%Iu)",
(PayloadBufferSize - PayloadBufferBinRecordStartIndex - BinRecordHeaderLength),
currentBinRecord->Length);
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
// PayloadBufferBinRecordDataOffset should always be smaller than the currentBinRecord length.
//
DmfAssert(PayloadBufferBinRecordDataOffset < currentBinRecord->Length);
// Add flags depending on whether this is the first block.
//
if (PayloadBufferBinRecordStartIndex == 0 && PayloadBufferBinRecordDataOffset == 0)
{
payload->Flags |= COMPONENT_FIRMWARE_UPDATE_FLAG_FIRST_BLOCK;
}
lastAddressConsumed = currentBinRecord->Address + PayloadBufferBinRecordDataOffset;
// dataLength is the number of uncopied bytes in the current bin record, or the
// remaining size of the payload. Whichever is less.
//
dataLength = currentBinRecord->Length - PayloadBufferBinRecordDataOffset;
if (dataLength > remainingPayloadBufferLength)
{
dataLength = remainingPayloadBufferLength;
}
errorNumber = memcpy_s(&(payload->PayloadData[payloadBufferOffset]),
remainingPayloadBufferLength,
&(currentBinRecord->BinData[PayloadBufferBinRecordDataOffset]),
dataLength);
if (errorNumber)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"memcpy_s fails with errno_t: %d",
errorNumber);
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
// Keep track of how many bytes remain in our payload.
//
remainingPayloadBufferLength -= dataLength;
// Gather the address we have consumed so far.
//
lastAddressConsumed += dataLength;
// Increment pointer to the next empty byte in our payload.
//
payloadBufferOffset += dataLength;
// Keep track of how many bytes we consumed of the current bin record.
//
PayloadBufferBinRecordDataOffset += dataLength;
payload->DataLength = payloadBufferOffset;
// If we are done reading this bin record. Advance to the next one.
//
if (PayloadBufferBinRecordDataOffset == currentBinRecord->Length)
{
PayloadBufferBinRecordStartIndex += BinRecordHeaderLength + currentBinRecord->Length;
// Check if this was the last block.
//
if (PayloadBufferBinRecordStartIndex == PayloadBufferSize)
{
// We consumed all the data.
//
payload->Flags |= COMPONENT_FIRMWARE_UPDATE_FLAG_LAST_BLOCK;
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Last Block at PayloadBufferIndex[0x%x] length 0x%x TransferBufferSize 0x%Ix",
PayloadBufferBinRecordStartIndex - BinRecordHeaderLength - currentBinRecord->Length,
dataLength,
TransferBufferSize);
break;
}
// Check if there is enough buffer left.
//
if (PayloadBufferSize - PayloadBufferBinRecordStartIndex < BinRecordHeaderLength)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Payload Buffer is corrupted. Size %Iu is less than the minimum required (%u)",
(PayloadBufferSize - PayloadBufferBinRecordStartIndex),
BinRecordHeaderLength);
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
currentBinRecord = (BIN_RECORD*)(PayloadBuffer + PayloadBufferBinRecordStartIndex);
PayloadBufferBinRecordDataOffset = 0;
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"next block: PayloadBufferIndex[0x%x] address 0x%x length 0x%x",
PayloadBufferBinRecordStartIndex,
currentBinRecord->Address,
currentBinRecord->Length);
}
if (remainingPayloadBufferLength == 0)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Buffer Full PayloadBufferIndex[0x%x] Position: [0x%x]",
PayloadBufferBinRecordStartIndex,
currentBinRecord->Address + PayloadBufferBinRecordDataOffset);
break;
}
// Verify that nextAddress is sequentially after address.
//
if (lastAddressConsumed != currentBinRecord->Address)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Cannot clump nonsequential messages");
break;
}
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Clumped %x data till lastAddress[0x%x]",
payloadBufferOffset,
lastAddressConsumed);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Exiting with PayloadBufferStartIndex[0x%x]",
PayloadBufferBinRecordStartIndex);
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
//-- Helper functions ---
//--------END------------
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
ComponentFirmwareUpdate_ComponentFirmwareUpdateDeinitialize(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Destroy the context information.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
None
--*/
{
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
PAGED_CODE();
FuncEntry(DMF_TRACE);
moduleContext = DMF_CONTEXT_GET(DmfModule);
// Clean up registry keys.
//
if (NULL != moduleContext->DeviceRegistryKey)
{
WdfRegistryClose(moduleContext->DeviceRegistryKey);
moduleContext->DeviceRegistryKey = NULL;
}
// Clean up collection.
//
if (NULL != moduleContext->FirmwareBlobCollection)
{
WdfObjectDelete(moduleContext->FirmwareBlobCollection);
moduleContext->FirmwareBlobCollection = NULL;
}
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
NTSTATUS
ComponentFirmwareUpdate_ComponentFirmwareUpdateInitialize(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Initialize's this Module's context.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
WDFDEVICE device;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
WDF_OBJECT_ATTRIBUTES objectAttributes;
ULONG firmwareComponentIndex;
size_t offerBufferSize;
size_t payloadBufferSize;
BYTE* payloadBufferFromClient = NULL;
BYTE* offerBufferFromClient = NULL;
PAGED_CODE();
FuncEntry(DMF_TRACE);
device = DMF_ParentDeviceGet(DmfModule);
moduleContext = DMF_CONTEXT_GET(DmfModule);
moduleConfig = DMF_CONFIG_GET(DmfModule);
// Validate the Module Config.
//
// Callback functions are mandatory as they provide the payload and offer blob.
//
if ((moduleConfig->EvtComponentFirmwareUpdateFirmwareOfferGet == NULL) ||
(moduleConfig->EvtComponentFirmwareUpdateFirmwarePayloadGet == NULL))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Invalid callback function to get offer/payload 0x%p 0x%p",
moduleConfig->EvtComponentFirmwareUpdateFirmwareOfferGet,
moduleConfig->EvtComponentFirmwareUpdateFirmwarePayloadGet);
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
// Check to ensure the length is in bound.
// (+1) to Consider the NULL termination also.
//
if ((moduleConfig->InstanceIdentifierLength + 1) > MAX_INSTANCE_IDENTIFIER_LENGTH)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Invalid size of Instance Identifier String %d",
moduleConfig->InstanceIdentifierLength);
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Number of Firmaware components %d",
moduleConfig->NumberOfFirmwareComponents);
// Open ServiceName registry subkey under the device's hardware key.
// Registry location {DESKTOP}: HKLM\SYSTEM\CurrentControlSet\Enum\{5E9A8CDC-14AB-4609-A017-68BCE594AB68}\<ServiceName>\.
//
WDFKEY key = NULL;
ntStatus = WdfDeviceOpenRegistryKey(device,
PLUGPLAY_REGKEY_DEVICE | WDF_REGKEY_DEVICE_SUBKEY,
(KEY_READ | KEY_SET_VALUE),
WDF_NO_OBJECT_ATTRIBUTES,
&key);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfDeviceOpenRegistryKey failed to open device hw key ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
moduleContext->DeviceRegistryKey = key;
// Create a collection to hold all the firmware informations.
//
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = DmfModule;
ntStatus = WdfCollectionCreate(&objectAttributes,
&moduleContext->FirmwareBlobCollection);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"WdfCollectionCreate fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// For each of the firmware components that we need to consume, get the firmware information from the client.
//
for (firmwareComponentIndex = 0;
firmwareComponentIndex < moduleConfig->NumberOfFirmwareComponents;
++firmwareComponentIndex)
{
// Get payload buffer and payload size.
//
payloadBufferSize = 0;
ntStatus = moduleConfig->EvtComponentFirmwareUpdateFirmwarePayloadGet(DmfModule,
firmwareComponentIndex,
&payloadBufferFromClient,
&payloadBufferSize);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"EvtComponentFirmwareUpdateFirmwarePayloadGet at %d fails: ntStatus=%!STATUS!",
firmwareComponentIndex,
ntStatus);
goto Exit;
}
// Get offer buffer and offer size.
//
offerBufferSize = 0;
ntStatus = moduleConfig->EvtComponentFirmwareUpdateFirmwareOfferGet(DmfModule,
firmwareComponentIndex,
&offerBufferFromClient,
&offerBufferSize);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"EvtComponentFirmwareUpdateFirmwareOfferGet at %d fails: ntStatus=%!STATUS!",
firmwareComponentIndex,
ntStatus);
goto Exit;
}
// Can not have zero size offer or payload buffers.
//
if (payloadBufferSize == 0 ||
offerBufferSize == 0)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"EvtComponentFirmwareUpdateFirmwareOfferGet at %d fails: 0 size firmware!",
firmwareComponentIndex);
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
// Can not have null offer or payload buffers.
//
if (offerBufferFromClient == NULL ||
payloadBufferFromClient == NULL)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"EvtComponentFirmwareUpdateFirmwareOfferGet at %d fails: null firmware buffer!",
firmwareComponentIndex);
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
WDFMEMORY firmwareMemory;
FIRMWARE_INFORMATION* firmwareInformation;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = moduleContext->FirmwareBlobCollection;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
0,
sizeof(FIRMWARE_INFORMATION),
&firmwareMemory,
(VOID**)&firmwareInformation);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for Firmware fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
ZeroMemory(firmwareInformation,
sizeof(*firmwareInformation));
firmwareInformation->OfferSize = offerBufferSize;
firmwareInformation->PayloadSize = payloadBufferSize;
firmwareInformation->OfferContentMemory = WDF_NO_HANDLE;
firmwareInformation->PayloadContentMemory = WDF_NO_HANDLE;
// Client's firmware buffers are not persisted. So will need to keep a copy internally.
// Allocate memory locally and copy the firmware buffer contents.
//
if (moduleConfig->FirmwareBuffersNotInPresistantMemory)
{
WDFMEMORY payloadMemory;
BYTE* payloadBufferLocallyCreated;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = firmwareMemory;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
MemoryTag,
firmwareInformation->PayloadSize,
&payloadMemory,
(VOID**)&payloadBufferLocallyCreated);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for Firmware fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
CopyMemory(payloadBufferLocallyCreated,
payloadBufferFromClient,
payloadBufferSize);
firmwareInformation->PayloadContentMemory = payloadMemory;
}
else
{
// Use the Buffer from client; Don't copy.
//
WDFMEMORY payloadMemory;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = firmwareMemory;
ntStatus = WdfMemoryCreatePreallocated(&objectAttributes,
payloadBufferFromClient,
payloadBufferSize,
&payloadMemory);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreatePreallocated for Firmware fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
firmwareInformation->PayloadContentMemory = payloadMemory;
}
// Client's firmware buffers are not persisted. So will need to keep a copy internally.
// Allocate memory locally and copy the firmware buffer contents.
//
if (moduleConfig->FirmwareBuffersNotInPresistantMemory)
{
WDFMEMORY offerMemory;
BYTE* offerBufferLocallyCreated;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = firmwareMemory;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
MemoryTag,
firmwareInformation->OfferSize,
&offerMemory,
(VOID**)&offerBufferLocallyCreated);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for Firmware fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
CopyMemory(offerBufferLocallyCreated,
offerBufferFromClient,
offerBufferSize);
firmwareInformation->OfferContentMemory = offerMemory;
}
else
{
// Use the Buffer from client; Don't copy.
//
WDFMEMORY offerMemory;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = firmwareMemory;
ntStatus = WdfMemoryCreatePreallocated(&objectAttributes,
offerBufferFromClient,
offerBufferSize,
&offerMemory);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreatePreallocated for Firmware fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
firmwareInformation->OfferContentMemory = offerMemory;
}
// Add the memory to collection. These will be retrieved during the protocol sequence.
//
ntStatus = WdfCollectionAdd(moduleContext->FirmwareBlobCollection,
firmwareMemory);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfCollectionAdd for firmware fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
}
Exit:
// Cleanup everything if we ran into a problem.
//
if (! NT_SUCCESS(ntStatus))
{
ComponentFirmwareUpdate_ComponentFirmwareUpdateDeinitialize(DmfModule);
}
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
// Registry Related (BEGIN)
//-------------------------
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_RegistryComponentValueNameGet(
_In_ DMFMODULE DmfModule,
_In_ PCWSTR RegistryValueName,
_In_ BYTE ComponentIdentifier,
_Inout_ UNICODE_STRING* RegistryValueNameString
)
/*++
Routine Description:
Build a registry Name value string based on the provided Component Identifier and ValueName.
Arguments:
DmfModule - This Module's DMF Object.
RegistryValueName - Value Name to be used while generating the registry value name string.
ComponentIdentifier - Component Identifier to be used to uniquely identify registry entry.
RegistryValueNameString- A Unicode string that returns the generated registry value name string.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
HRESULT hr;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
moduleConfig = DMF_CONFIG_GET(DmfModule);
DmfAssert(RegistryValueNameString != NULL);
DmfAssert(RegistryValueNameString->MaximumLength != 0);
RegistryValueNameString->Length = 0;
// Create the Key Value Name string with the information provided.
//
// Key Value Name: generate could be
// InstanceID:<ModuleConfig->InstanceIdentifier>:Component<ComponentIdentifier><RegistryValueName>
// OR
// Component<ComponentIdentifier><RegistryValueName>
// depending on whether Module configuration has an instance identifier or not.
//
// E.g.
// If RegistryValueName is "FwUpdateStatus" & ModuleConfig->InstanceIdentifier is "84229" & ComponentIdentifier is 7
// the function returns the following string in RegistryValueNameString "InstanceID:84229:Component7FwUpdateStatus".
//
if (moduleConfig->InstanceIdentifierLength != 0)
{
// Create the registry value name as InstanceID:<ModuleConfig->InstanceIdentifier>:Component<ComponentIdentifier><ValueName>.
//
hr = StringCchPrintf(RegistryValueNameString->Buffer,
RegistryValueNameString->MaximumLength,
L"InstanceID:%s:Component%02X%s",
moduleConfig->InstanceIdentifier,
ComponentIdentifier,
RegistryValueName);
}
else
{
// Create the registry value name as Component<ComponentIdentifier><ValueName>.
//
hr = StringCchPrintf(RegistryValueNameString->Buffer,
RegistryValueNameString->MaximumLength,
L"Component%02X%s",
ComponentIdentifier,
RegistryValueName);
}
if (FAILED(hr))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"StringCchPrintf fails: %!HRESULT!",
hr);
// This can fail with STRSAFE_E_INVALID_PARAMETER/STRSAFE_E_INSUFFICIENT_BUFFER.
// Treat as INVALID_PARAMETER.
//
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
size_t combinedValueNameLength;
// NOTE: combinedValueNameLength excludes terminating null.
//
hr = StringCbLength(RegistryValueNameString->Buffer,
RegistryValueNameString->MaximumLength,
&combinedValueNameLength);
if (FAILED(hr))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"StringCbLength fails: %!HRESULT!",
hr);
// This can fail with STRSAFE_E_INVALID_PARAMETER.
// Treat as INVALID_PARAMETER.
//
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
RegistryValueNameString->Length = (USHORT)combinedValueNameLength;
ntStatus = STATUS_SUCCESS;
Exit:
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_RegistryRemoveComponentValue(
_In_ DMFMODULE DmfModule,
_In_ PCWSTR RegistryValueName,
_In_ BYTE ComponentIdentifier
)
/*++
Routine Description:
Removes a single value to the registry with the Value Name based on Component Indentifier and ValueName.
Arguments:
DmfModule - This Module's DMF Object.
ValueName - Name of the Registry Value to be removed.
ComponentIdentifier - Component Identifier for identifying the unique registry entry.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
const size_t combinedValueNameMaxLength = MAXIMUM_VALUE_NAME_SIZE;
WCHAR combinedValueNameBuffer[combinedValueNameMaxLength] = { 0 };
UNICODE_STRING registryValueNameString;
FuncEntry(DMF_TRACE);
moduleContext = DMF_CONTEXT_GET(DmfModule);
DmfAssert(RegistryValueName != NULL);
RtlInitUnicodeString(®istryValueNameString,
combinedValueNameBuffer);
registryValueNameString.MaximumLength = (USHORT)combinedValueNameMaxLength;
ntStatus = ComponentFirmwareUpdate_RegistryComponentValueNameGet(DmfModule,
RegistryValueName,
ComponentIdentifier,
®istryValueNameString);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryComponentValueNameGet fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Remove from Device registry location.
//
ntStatus = WdfRegistryRemoveValue(moduleContext->DeviceRegistryKey,
®istryValueNameString);
if (ntStatus == STATUS_OBJECT_NAME_NOT_FOUND)
{
ntStatus = STATUS_SUCCESS;
}
else if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DeviceRegistryRemoveValue fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, ntStatus="%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_RegistryAssignComponentUlong(
_In_ DMFMODULE DmfModule,
_In_ PCWSTR RegistryValueName,
_In_ BYTE ComponentIdentifier,
_In_ ULONG RegistryValue
)
/*++
Routine Description:
Writes a single value to the registry with the Value Name based on Component Identifier and ValueName.
Arguments:
DmfModule - This Module's DMF Object.
RegistryValueName - Name of the Registry Value to be assigned.
ComponentIdentifier - Component Identifier for identifying the unique registry entry.
RegistryValue - Registry value to be assigned to.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
const size_t combinedValueNameMaxLength = MAXIMUM_VALUE_NAME_SIZE;
WCHAR combinedValueNameBuffer[combinedValueNameMaxLength] = { 0 };
UNICODE_STRING registryValueNameString;
FuncEntry(DMF_TRACE);
moduleContext = DMF_CONTEXT_GET(DmfModule);
DmfAssert(RegistryValueName != NULL);
RtlInitUnicodeString(®istryValueNameString,
combinedValueNameBuffer);
registryValueNameString.MaximumLength = (USHORT)combinedValueNameMaxLength;
ntStatus = ComponentFirmwareUpdate_RegistryComponentValueNameGet(DmfModule,
RegistryValueName,
ComponentIdentifier,
®istryValueNameString);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_RegistryComponentValueNameGet fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
ntStatus = WdfRegistryAssignULong(moduleContext->DeviceRegistryKey,
®istryValueNameString,
RegistryValue);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"RegistryAssignComponentUlong fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, ntStatus="%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_RegistryQueryComponentUlong(
_In_ DMFMODULE DmfModule,
_In_ PCWSTR RegistryValueName,
_In_ BYTE ComponentIdentifier,
_In_ ULONG* RegistryValue
)
/*++
Routine Description:
Query a ulong value from registry with the Value Name based on Component Identifier and ValueName.
Arguments:
DmfModule - This Module's DMF Object.
RegistryValueName - Name of the Registry Value to be assigned.
ComponentIdentifier - Component Identifier for identifying the unique registry entry.
RegistryValue - Registry value returned.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
const size_t combinedValueNameMaxLength = MAXIMUM_VALUE_NAME_SIZE;
WCHAR combinedValueNameBuffer[combinedValueNameMaxLength] = { 0 };
UNICODE_STRING registryValueNameString;
FuncEntry(DMF_TRACE);
moduleContext = DMF_CONTEXT_GET(DmfModule);
DmfAssert(RegistryValueName != NULL);
DmfAssert(RegistryValue != NULL);
RtlInitUnicodeString(®istryValueNameString,
combinedValueNameBuffer);
registryValueNameString.MaximumLength = (USHORT)combinedValueNameMaxLength;
ntStatus = ComponentFirmwareUpdate_RegistryComponentValueNameGet(DmfModule,
RegistryValueName,
ComponentIdentifier,
®istryValueNameString);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_RegistryComponentValueNameGet fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
ntStatus = WdfRegistryQueryULong(moduleContext->DeviceRegistryKey,
®istryValueNameString,
RegistryValue);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfRegistryQueryULong fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
// Registry Related (END)
//------------------------
// Transport Related (BEGIN)
//--------------------------
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferCommandSend(
_In_ DMFMODULE DmfModule,
_In_ COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_CODE OfferCommandCode,
_Out_ COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE* OfferResponseStatus,
_Out_ COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON* OfferResponseReason
)
/*++
Routine Description:
Send an offer command to the device and retrieve response.
Arguments:
DmfModule - This Module's DMF Object.
OfferCommandCode - Offer Command to Send.
OfferResponseStatus - Response received for the command.
OfferResponseReason - Reason for the response.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
ULONG transportWaitTimeout;
ULONG offerCommand;
const BYTE informationPacketMarker = FWUPDATE_COMMAND_TOKEN;
const BYTE outputToken = FWUPDATE_DRIVER_TOKEN;
WDF_OBJECT_ATTRIBUTES objectAttributes;
WDFMEMORY offerCommandMemory;
UCHAR* bufferHeader;
UCHAR* offerCommandBuffer;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DmfAssert(OfferResponseStatus != NULL);
DmfAssert(OfferResponseReason != NULL);
moduleContext = DMF_CONTEXT_GET(DmfModule);
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransportContext != NULL);
size_t allocatedSize = componentFirmwareUpdateTransportContext->TransportOfferBufferRequiredSize + componentFirmwareUpdateTransportContext->TransportHeaderSize;
offerCommandMemory = WDF_NO_HANDLE;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = DmfModule;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
0,
allocatedSize,
&offerCommandMemory,
(VOID**)&bufferHeader);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for OfferCommandSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
RtlZeroMemory(bufferHeader,
allocatedSize);
// Update Byte 0, 2 and 3.
//
offerCommand = 0;
offerCommand |= ((BYTE)OfferCommandCode << 0);
offerCommand |= (informationPacketMarker << 16);
offerCommand |= (outputToken << 24);
offerCommandBuffer = bufferHeader + componentFirmwareUpdateTransportContext->TransportHeaderSize;
RtlCopyMemory(offerCommandBuffer,
&offerCommand,
sizeof(offerCommand));
ntStatus = DMF_ComponentFirmwareUpdate_TransportOfferCommandSend(moduleContext->DmfInterfaceComponentFirmwareUpdate,
bufferHeader,
allocatedSize,
componentFirmwareUpdateTransportContext->TransportHeaderSize);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdate_TransportOfferCommandSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Wait for response availability.
// Adjust the timeout based on the specification.
// for COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_NOTIFY_ON_READY - timeout is INFINITE.
//
if (OfferCommandCode == COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_NOTIFY_ON_READY)
{
transportWaitTimeout = INFINITE;
}
else
{
transportWaitTimeout = componentFirmwareUpdateTransportContext->TransportWaitTimeout;
}
// Wait for response.
//
ntStatus = ComponentFirmwareUpdate_WaitForResponse(DmfModule,
transportWaitTimeout);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WaitForResponse fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Offer Response Received.");
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
ntStatus = componentFirmwareUpdateTransactionContext->ntStatus;
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"OfferCommandSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
*OfferResponseStatus = componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus;
*OfferResponseReason = componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason;
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Offer Command for %s(%d) returned response status %s(%d)",
ComponentFirmwareUpdateOfferCommandCodeString(OfferCommandCode),
OfferCommandCode,
ComponentFirmwareUpdateOfferResponseString(componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus),
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus);
// Decide the next course of actions based on the response status.
//
// In the absence of a formal state machine implementation, decisions are done in a switch case.
//
switch (componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus)
{
case COMPONENT_FIRMWARE_UPDATE_OFFER_ACCEPT:
{
// Expected Normal Result.
//
;
break;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_SKIP:
// Fall through.
//
case COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT:
{
// These are unexpected returns.
//
ntStatus = STATUS_ABANDONED;
TraceEvents(TRACE_LEVEL_WARNING,
DMF_TRACE,
"Offer Reject Reason Code %s(%d)",
ComponentFirmwareUpdateOfferResponseRejectString(componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason),
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason);
goto Exit;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_READY:
{
// Expected Result.
//
;
break;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_NOT_SUPPORTED:
{
// Expected Result.
//
;
TraceEvents(TRACE_LEVEL_WARNING,
DMF_TRACE,
"Offer Command for %s(%d) was not supported",
ComponentFirmwareUpdateOfferCommandCodeString(OfferCommandCode),
OfferCommandCode);
break;
}
default:
{
// Unexpected returns.
//
ntStatus = STATUS_ABANDONED;
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Received unknown offerResponseStatus %d",
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus);
goto Exit;
}
}
Exit:
if (offerCommandMemory != WDF_NO_HANDLE)
{
WdfObjectDelete(offerCommandMemory);
offerCommandMemory = WDF_NO_HANDLE;
}
FuncExit(DMF_TRACE, "%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_SendOfferInformation(
_In_ DMFMODULE DmfModule,
_In_ COMPONENT_FIRMWARE_UPDATE_OFFER_INFORMATION_CODE OfferInformationCode,
_Out_ COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE* OfferResponseStatus,
_Out_ COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON* OfferResponseReason
)
/*++
Routine Description:
Send an offer information meta data to the transport and retrieve response.
Arguments:
DmfModule - This Module's DMF Object.
OfferInformationCode - Offer Information Code to Send.
OfferResponseStatus - Response to the command.
OfferResponseReason - Reason for the response.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
WDF_OBJECT_ATTRIBUTES objectAttributes;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
ULONG offerInformation;
const BYTE informationPacketMarker = FWUPDATE_INFORMATION_TOKEN;
const BYTE outputToken = FWUPDATE_DRIVER_TOKEN;
WDFMEMORY offerInformationMemory;
UCHAR* bufferHeader;
UCHAR* offerInformationBuffer;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DmfAssert(OfferResponseStatus != NULL);
DmfAssert(OfferResponseReason != NULL);
moduleContext = DMF_CONTEXT_GET(DmfModule);
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransportContext != NULL);
size_t allocatedSize = componentFirmwareUpdateTransportContext->TransportOfferBufferRequiredSize + componentFirmwareUpdateTransportContext->TransportHeaderSize;
offerInformationMemory = WDF_NO_HANDLE;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = DmfModule;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
0,
allocatedSize,
&offerInformationMemory,
(VOID**)&bufferHeader);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for OfferInformationSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
RtlZeroMemory(bufferHeader,
allocatedSize);
// Update Byte 0, 2 and 3.
//
offerInformation = 0;
offerInformation |= ((BYTE)OfferInformationCode << 0);
offerInformation |= (informationPacketMarker << 16);
offerInformation |= (outputToken << 24);
offerInformationBuffer = bufferHeader + componentFirmwareUpdateTransportContext->TransportHeaderSize;
RtlCopyMemory(offerInformationBuffer,
&offerInformation,
sizeof(offerInformation));
ntStatus = DMF_ComponentFirmwareUpdate_TransportOfferInformationSend(moduleContext->DmfInterfaceComponentFirmwareUpdate,
bufferHeader,
allocatedSize,
componentFirmwareUpdateTransportContext->TransportHeaderSize);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdateTransport_OfferInformationSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Wait for response.
//
ntStatus = ComponentFirmwareUpdate_WaitForResponse(DmfModule,
componentFirmwareUpdateTransportContext->TransportWaitTimeout);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WaitForResponse fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Offer Response Received.");
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
ntStatus = componentFirmwareUpdateTransactionContext->ntStatus;
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"OfferInformationSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
*OfferResponseStatus = componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus;
*OfferResponseReason = componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason;
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Offer Information for %s(%d) returned response status %s(%d)",
ComponentFirmwareUpdateOfferInformationCodeString(OfferInformationCode),
OfferInformationCode,
ComponentFirmwareUpdateOfferResponseString(componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus),
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus);
// Decide the next course of actions based on the response status.
//
// In the absence of a formal state machine implementation, decisions are done in a switch case.
//
switch (*OfferResponseStatus)
{
case COMPONENT_FIRMWARE_UPDATE_OFFER_ACCEPT:
{
// Expected Normal Result.
//
;
break;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_SKIP:
// Fall through.
//
case COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT:
{
// These are unexpected returns.
//
ntStatus = STATUS_ABANDONED;
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Offer Reject Reason Code %s(%d)",
ComponentFirmwareUpdateOfferResponseRejectString(componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason),
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason);
goto Exit;
}
default:
{
// These are unexpected returns.
//
ntStatus = STATUS_ABANDONED;
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Received unknown offerResponseStatus %d",
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus);
goto Exit;
}
};
Exit:
if (offerInformationMemory != WDF_NO_HANDLE)
{
WdfObjectDelete(offerInformationMemory);
offerInformationMemory = WDF_NO_HANDLE;
}
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferSend(
_In_ DMFMODULE DmfModule,
_In_reads_bytes_(OfferBufferSize) ULONG* OfferBuffer,
_In_ ULONG OfferBufferSize,
_Out_ COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE* OfferResponseStatus,
_Out_ COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON* OfferResponseReason
)
/*++
Routine Description:
Send the offer data to the device and receive the response.
Arguments:
DmfModule - This Module's DMF Object.
OfferBuffer -- offer data to be sent to the device.
OfferBufferSize - offer data size.
OfferResponseStatus -- response received from device.
OfferResponseRejectReason - reject reason code for the response.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
const UINT numberOfUlongsInOffer = 4;
const ULONG offerSize = sizeof(ULONG) * numberOfUlongsInOffer;
const BYTE outputToken = FWUPDATE_DRIVER_TOKEN;
WDF_OBJECT_ATTRIBUTES objectAttributes;
WDFMEMORY offerMemory;
UCHAR* bufferHeader;
ULONG* offerBuffer;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DmfAssert(OfferBuffer != NULL);
DmfAssert(OfferResponseStatus != NULL);
DmfAssert(OfferResponseReason != NULL);
UNREFERENCED_PARAMETER(OfferBufferSize);
ntStatus = STATUS_SUCCESS;
offerMemory = WDF_NO_HANDLE;
moduleContext = DMF_CONTEXT_GET(DmfModule);
moduleConfig = DMF_CONFIG_GET(DmfModule);
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransportContext != NULL);
size_t allocatedSize = componentFirmwareUpdateTransportContext->TransportOfferBufferRequiredSize + componentFirmwareUpdateTransportContext->TransportHeaderSize;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = DmfModule;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
0,
allocatedSize,
&offerMemory,
(VOID**)&bufferHeader);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for Offer fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
RtlZeroMemory(bufferHeader,
allocatedSize);
offerBuffer = (ULONG*) (bufferHeader + componentFirmwareUpdateTransportContext->TransportHeaderSize);
ULONG* offersFromBlob = (ULONG*)OfferBuffer;
for (USHORT blobIndex = 0; blobIndex < numberOfUlongsInOffer; ++blobIndex)
{
offerBuffer[blobIndex] = offersFromBlob[blobIndex];
}
// Update Component info field of offer as needed.
//
// Set the Most Significant Byte to outputToken.
//
offerBuffer[0] = (offerBuffer[0] & 0x00FFFFFF) | (outputToken << 24);
if (moduleConfig->ForceImmediateReset)
{
// Set the Force Immediate Reset bit to 1.
//
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Setting Force Immediate Reset bit");
offerBuffer[0] |= (1 << 14);
}
if (moduleConfig->ForceIgnoreVersion)
{
// Set the Force Ignore Version bit to 1.
//
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Setting Force Ignore Version bit");
offerBuffer[0] |= (1 << 15);
}
ntStatus = DMF_ComponentFirmwareUpdate_TransportOfferSend(moduleContext->DmfInterfaceComponentFirmwareUpdate,
bufferHeader,
allocatedSize,
componentFirmwareUpdateTransportContext->TransportHeaderSize);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdate_TransportOfferSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Wait for response.
//
ntStatus = ComponentFirmwareUpdate_WaitForResponse(DmfModule,
componentFirmwareUpdateTransportContext->TransportWaitTimeout);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WaitForResponse fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Offer Response Received.");
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
ntStatus = componentFirmwareUpdateTransactionContext->ntStatus;
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"OfferSend Fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
*OfferResponseStatus = componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus;
*OfferResponseReason = componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason;
Exit:
if (offerMemory != WDF_NO_HANDLE)
{
WdfObjectDelete(offerMemory);
offerMemory = WDF_NO_HANDLE;
}
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_SendPayload(
_In_ DMFMODULE DmfModule,
_In_ UINT32 PayloadIndex,
_In_ BYTE ComponentIdentifier,
_Out_ COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE* PayloadResponse
)
/*++
Routine Description:
Retrieve the payload data for the specified index from the context and send it to the device & receive the response.
Arguments:
DmfModule - This Module's DMF Object.
PayloadIndex - Index of this payload in the payload collection.
ComponentIdentifier - Component Indentifier that uniquely identifies this component being updated.
PayloadResponse - Response received from the device.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
FIRMWARE_INFORMATION* firmwareInformation;
WDFMEMORY firmwareInformationMemory;
ULONG* payloadContent;
size_t payloadSizeFromCollection;
WDF_OBJECT_ATTRIBUTES objectAttributes;
WDFMEMORY payloadChunkMemory;
// Buffer that is send down to hardware.
//
UCHAR* bufferHeader;
UCHAR* payloadBuffer;
BYTE payloadBufferLength;
// Index in the whole payload buffer that tracks the begining of a Bin Record.
// Each Bin Record has {address, length, data}
//
ULONG payloadBufferBinRecordStartIndex = 0;
// Keep track of where we left off.
//
ULONG resumePayloadBufferBinRecordStartIndex = 0;
// Offset in the current bin record in the payload buffer.
//
BYTE payloadBufferBinRecordDataOffset = 0;
// Keep track of this offset in case of interruption.
//
ULONG resumePayloadBufferBinRecordDataOffset = 0;
// Do not start at 0 due to firmware limitations.
//
const UINT16 sequenceNumberStart = 0x0001;
UINT16 sequenceNumber = 0;
UINT16 resumeSequenceNumber = 0;
// Read a ULONG from registry.
//
ULONG resumeSequenceNumberFromRegistry = 0;
BOOL updateInterruptedFromIoFailure = FALSE;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DmfAssert(PayloadResponse != NULL);
moduleContext = DMF_CONTEXT_GET(DmfModule);
moduleConfig = DMF_CONFIG_GET(DmfModule);
DmfAssert(PayloadIndex < WdfCollectionGetCount(moduleContext->FirmwareBlobCollection));
firmwareInformationMemory = (WDFMEMORY)WdfCollectionGetItem(moduleContext->FirmwareBlobCollection,
PayloadIndex);
firmwareInformation = (FIRMWARE_INFORMATION*)WdfMemoryGetBuffer(firmwareInformationMemory,
NULL);
payloadContent = (ULONG*)WdfMemoryGetBuffer(firmwareInformation->PayloadContentMemory,
&payloadSizeFromCollection);
DmfAssert(payloadSizeFromCollection == firmwareInformation->PayloadSize);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransportContext != NULL);
payloadChunkMemory = WDF_NO_HANDLE;
// Allocate memory for payload chunk, and reuse it for the sending the whole payload.
//
size_t allocatedSize = componentFirmwareUpdateTransportContext->TransportFirmwarePayloadBufferRequiredSize + componentFirmwareUpdateTransportContext->TransportHeaderSize;
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = DmfModule;
ntStatus = WdfMemoryCreate(&objectAttributes,
NonPagedPoolNx,
0,
allocatedSize,
&payloadChunkMemory,
(VOID**)&bufferHeader);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate for Offer fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
RtlZeroMemory(bufferHeader,
allocatedSize);
// Ensure the driver is packing 60 bytes of payload everytime.
//
payloadBuffer = (UCHAR*)(bufferHeader + componentFirmwareUpdateTransportContext->TransportHeaderSize);
payloadBufferLength = SizeOfPayload;
// Check whether the update should resume from a previously interrupted update.
// This can only occur if the same pair 'that was interrupted last attempt matches the first pair to be accepted this attempt'.
//
payloadBufferBinRecordStartIndex = 0;
sequenceNumber = sequenceNumberStart;
do
{
// No need to check further if the Resume On Connect is not supported.
//
if (moduleConfig->SupportResumeOnConnect == FALSE)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"ResumeOnConnect is not supported");
break;
}
ULONG resumeOnConnect = 0;
ULONG resumePairIndex = 0;
// Check whether a resume is desired.
// This is TRUE if we had an interruption on our previous payload send attempt for the same component.
//
ntStatus = ComponentFirmwareUpdate_RegistryQueryComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumeOnConnectValueName,
ComponentIdentifier,
&resumeOnConnect);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryQueryComponentUlong fails for ResumeOnConnect ntStatus=%!STATUS!",
ntStatus);
break;
}
// Skip if we dont have any interruption that is resumable.
//
if (resumeOnConnect == 0)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"No interrupted and Resumable previous failed Payload Send attempt.");
break;
}
// Make sure to set ResumeOnConnect to false so the next pair does not go through this again.
//
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumeOnConnectValueName,
ComponentIdentifier,
FALSE);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfRegistryAssignULong fails for ResumeOnConnect ntStatus=%!STATUS!",
ntStatus);
break;
}
// Get the payload data index to use upon resume.
//
ntStatus = ComponentFirmwareUpdate_RegistryQueryComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumePayloadBufferBinRecordIndexValueName,
ComponentIdentifier,
&resumePayloadBufferBinRecordStartIndex);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryQueryComponentUlong failed for ResumeResourceDataIndex ntStatus=%!STATUS!",
ntStatus);
break;
}
// Get the sequence number to use upon resume.
//
ntStatus = ComponentFirmwareUpdate_RegistryQueryComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumeSequenceNumberValueName,
ComponentIdentifier,
&resumeSequenceNumberFromRegistry);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfRegistryQueryULong fails for ResumeSequenceNumber ntStatus=%!STATUS!",
ntStatus);
break;
}
// Get the payload buffer offset to use upon resume.
//
ntStatus = ComponentFirmwareUpdate_RegistryQueryComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumePayloadBufferBinRecordDataOffsetValueName,
ComponentIdentifier,
&resumePayloadBufferBinRecordDataOffset);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfRegistryQueryULong fails for ResumePayloadBufferAddressOffset ntStatus=%!STATUS!",
ntStatus);
break;
}
// PayloadBufferBinRecordDataOffset is of type Byte, this is a sanity check for registry value to make sure
// the registry didn't corrupt the value.
//
DmfAssert(resumePayloadBufferBinRecordDataOffset <= BYTE_MAX);
// Sequence number size is 2 Bytes.
//
DmfAssert(resumeSequenceNumberFromRegistry <= UINT16_MAX);
resumeSequenceNumber = (UINT16) resumeSequenceNumberFromRegistry;
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Resuming interrupted update on PairIndex %d at ResourceDataIndex %d with SequenceNumber %d",
resumePairIndex,
resumePayloadBufferBinRecordStartIndex,
resumeSequenceNumber);
payloadBufferBinRecordStartIndex = resumePayloadBufferBinRecordStartIndex;
sequenceNumber = resumeSequenceNumber;
payloadBufferBinRecordDataOffset = (BYTE) resumePayloadBufferBinRecordDataOffset;
} while (0);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Started sending firmware data");
// Index of the payload contents that need to be send to the device cannot be beyond or equal to the payload size.
// There needs to be have some payload content to be send (applicable for both resume from interrupted case or normal)
// otherwise it is an error case.
//
if (payloadBufferBinRecordStartIndex >= firmwareInformation->PayloadSize)
{
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
// Proceed while there is some payload data still needed to send..
//
while (payloadBufferBinRecordStartIndex < firmwareInformation->PayloadSize)
{
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Current sequenceNumber: %d, PayloadIndex: %d, Payload Total size: %Iu",
sequenceNumber,
payloadBufferBinRecordStartIndex,
firmwareInformation->PayloadSize);
// Preserve the currently completed numbers as a checkpoint.
//
resumeSequenceNumber = sequenceNumber;
resumePayloadBufferBinRecordStartIndex = payloadBufferBinRecordStartIndex;
resumePayloadBufferBinRecordDataOffset = payloadBufferBinRecordDataOffset;
// Fill the output buffer with the next chunk of payload to send.
// Content is Copied From payloadContent to payloadBuffer.
// payloadBufferIndex is updated inside as the payloadBuffer is filled up.
//
ntStatus = ComponentFirmwareUpdate_PayloadBufferFill(DmfModule,
sequenceNumber,
(BYTE*)payloadContent,
firmwareInformation->PayloadSize,
payloadBufferBinRecordStartIndex,
payloadBufferBinRecordDataOffset,
payloadBuffer,
payloadBufferLength);
if (FAILED(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"PayloadBufferFill fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
ntStatus = DMF_ComponentFirmwareUpdate_TransportPayloadSend(moduleContext->DmfInterfaceComponentFirmwareUpdate,
bufferHeader,
allocatedSize,
componentFirmwareUpdateTransportContext->TransportHeaderSize);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdateTransport_PayloadSend fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Wait for response with the right sequence number.
//
ntStatus = ComponentFirmwareUpdate_PayloadResponseProcess(DmfModule,
sequenceNumber,
PayloadResponse);
if (!NT_SUCCESS(ntStatus))
{
// Treat timeout as IoFailure.
//
if (ntStatus == STATUS_INVALID_DEVICE_STATE)
{
updateInterruptedFromIoFailure = TRUE;
}
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"PayloadResponseProcess fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
if (*PayloadResponse != COMPONENT_FIRMWARE_UPDATE_SUCCESS)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"PayloadResponseProcess returns: %d",
*PayloadResponse);
goto Exit;
// Do not flag this with ntStatus.
//
}
++sequenceNumber;
}
Exit:
if (payloadChunkMemory != WDF_NO_HANDLE)
{
WdfObjectDelete(payloadChunkMemory);
payloadChunkMemory = WDF_NO_HANDLE;
payloadBuffer = NULL;
}
// If the update was interrupted and the device supports resume on connect, store the current progress in the registry
// Make sure to mark ResumeOnConnect last and not set it to true if any of the others fail.
//
if (moduleConfig->SupportResumeOnConnect && updateInterruptedFromIoFailure)
{
do
{
NTSTATUS ntStatusLocal;
ntStatusLocal = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumePayloadBufferBinRecordIndexValueName,
ComponentIdentifier,
resumePayloadBufferBinRecordStartIndex);
if (!NT_SUCCESS(ntStatusLocal))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for ResumePayloadBufferBinRecordIndex: ntStatus=%!STATUS!",
ntStatusLocal);
break;
}
ntStatusLocal = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumePayloadBufferBinRecordDataOffsetValueName,
ComponentIdentifier,
resumePayloadBufferBinRecordDataOffset);
if (!NT_SUCCESS(ntStatusLocal))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for ResumePayloadBufferBinRecordDataOffset: ntStatus=%!STATUS!",
ntStatusLocal);
break;
}
ntStatusLocal = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumeSequenceNumberValueName,
ComponentIdentifier,
resumeSequenceNumber);
if (!NT_SUCCESS(ntStatusLocal))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for ResumeSequenceNumber: ntStatus=%!STATUS!",
ntStatusLocal);
break;
}
ntStatusLocal = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_ResumeOnConnectValueName,
ComponentIdentifier,
TRUE);
if (!NT_SUCCESS(ntStatusLocal))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for ResumeOnConnect: ntStatus=%!STATUS!",
ntStatusLocal);
break;
}
} while (0);
}
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_FirmwareVersionsGet(
_In_ DMFMODULE DmfModule,
_Out_ COMPONENT_FIRMWARE_VERSIONS* VersionsOfFirmware
)
/*++
Routine Description:
Get the current version of the firmware from device.
Arguments:
DmfModule - This Module's DMF Object.
VersionsOfFirmware - returned version information from the device.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
CONTEXT_ComponentFirmwareUpdateTransport* componentFirmwareUpdateTransportContext;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DmfAssert(VersionsOfFirmware != NULL);
ZeroMemory(VersionsOfFirmware, sizeof(*VersionsOfFirmware));
moduleContext = DMF_CONTEXT_GET(DmfModule);
ntStatus = DMF_ComponentFirmwareUpdate_TransportFirmwareVersionGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdateTransport_FirmwareVersionGet fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
componentFirmwareUpdateTransportContext = ComponentFirmwareUpdateTransportContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransportContext != NULL);
// Wait for response.
//
ntStatus = ComponentFirmwareUpdate_WaitForResponse(DmfModule,
componentFirmwareUpdateTransportContext->TransportWaitTimeout);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WaitForResponse fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Firmware version Response Received.");
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
ntStatus = componentFirmwareUpdateTransactionContext->ntStatus;
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareVersionGet fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Copy Firmware Information.
//
RtlCopyMemory(VersionsOfFirmware,
&componentFirmwareUpdateTransactionContext->FirmwareVersions,
sizeof(componentFirmwareUpdateTransactionContext->FirmwareVersions));
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_ProtocolStop(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
This cleans up the protocol transaction and let the transport do its specific actions needed when the protocol is being stopped.
Parameters:
DmfModule - This Module's DMF Object.
Return:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
moduleContext = DMF_CONTEXT_GET(DmfModule);
PAGED_CODE();
FuncEntry(DMF_TRACE);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
// Set Cancel Event so that any pending wait for responses are returned.
//
DMF_Portable_EventSet(&componentFirmwareUpdateTransactionContext->DmfProtocolTransactionCancelEvent);
// Let the specific action be done at the interface implementation.
//
ntStatus = DMF_ComponentFirmwareUpdate_TransportProtocolStop(moduleContext->DmfInterfaceComponentFirmwareUpdate);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdate_TransportProtocolStop fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_ProtocolStart(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
This prepares for the protocol transaction and let the transport do its specific actions needed when the protocol is about to be started.
Parameters:
DmfModule - This Module's DMF Object.
Return:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
moduleContext = DMF_CONTEXT_GET(DmfModule);
PAGED_CODE();
FuncEntry(DMF_TRACE);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(moduleContext->DmfInterfaceComponentFirmwareUpdate);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
// Clear the Cancel Event that may have been set and not cleared.
//
DMF_Portable_EventReset(&componentFirmwareUpdateTransactionContext->DmfProtocolTransactionCancelEvent);
// Let the specific action be done at the interface implementation.
//
ntStatus = DMF_ComponentFirmwareUpdate_TransportProtocolStart(moduleContext->DmfInterfaceComponentFirmwareUpdate);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdateTransport_ProtocolStart fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
// Transport Related (END)
//--------------------------
// CFU Protocol Related (BEGIN)
//=============================
BOOL
ComponentFirmwareUpdate_IsProtocolStopRequestPending(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Checks whether a protocol stop request is already made or not.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
TRUE if stop is already requested, otherwise FALSE.
--*/
{
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
moduleContext = DMF_CONTEXT_GET(DmfModule);
return DMF_Thread_IsStopPending(moduleContext->DmfModuleThread);
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferVersionsRegistryDelete(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Helper function to delete all the offer versions in registry that may have been
saved earlier.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
HANDLE handle;
LPTSTR valueNameMemoryBuffer;
WDFMEMORY valueNameMemory;
DWORD valueNameCount = 0;
DWORD valueNameElementCountMaximum = 0;
WDFCOLLECTION registryValueNamesToBeDeleted;
WDF_OBJECT_ATTRIBUTES objectAttributes;
FuncEntry(DMF_TRACE);
moduleContext = DMF_CONTEXT_GET(DmfModule);
moduleConfig = DMF_CONFIG_GET(DmfModule);
registryValueNamesToBeDeleted = WDF_NO_HANDLE;
valueNameMemory = WDF_NO_HANDLE;
handle = WdfRegistryWdmGetHandle(moduleContext->DeviceRegistryKey);
ntStatus = RegQueryInfoKey((HKEY)handle,
NULL,
0,
NULL,
NULL,
NULL,
NULL,
&valueNameCount,
&valueNameElementCountMaximum,
NULL,
NULL,
NULL);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"RegQueryInfoKey fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Enumerate all values in this registry and delete the
// keys that matches the offer versions pattern ("[InstanceID:%s:]Offer:*")
//
// If there are no values, no need to do anything further.
//
if (0 == valueNameCount)
{
goto Exit;
}
// Build the pattern that is to be matched.
// It is either "InstanceID:.*:Offer:.*" or "Offer:.*"
//
WCHAR patternToMatch[MAXIMUM_VALUE_NAME_SIZE];
HRESULT hr;
if (moduleConfig->InstanceIdentifierLength != 0)
{
hr = StringCchPrintf(patternToMatch,
_countof(patternToMatch),
L"InstanceID:%s:Offer:",
moduleConfig->InstanceIdentifier);
}
else
{
hr = StringCchPrintf(patternToMatch,
_countof(patternToMatch),
L"Offer:");
}
if (FAILED(hr))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"StringCchPrintf fails: %!HRESULT!",
hr);
// This can fail with STRSAFE_E_INVALID_PARAMETER/STRSAFE_E_INSUFFICIENT_BUFFER.
// Treat as INVALID_PARAMETER.
//
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
size_t patternToMatchLength;
hr = StringCbLength(patternToMatch,
sizeof(patternToMatch),
&patternToMatchLength);
if (FAILED(hr))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"StringCbLength fails: %!HRESULT!",
hr);
// This can fail with STRSAFE_E_INVALID_PARAMETER/STRSAFE_E_INSUFFICIENT_BUFFER.
// Treat as INVALID_PARAMETER.
//
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = DmfModule;
ntStatus = WdfCollectionCreate(&objectAttributes,
®istryValueNamesToBeDeleted);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfCollectionCreate fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Create buffer(s) which is/are big enough to hold the largest valuename.
// Account for NULL as well. Note: No overflow check as the registry value length maximum is limited.
//
DWORD valueNameElementCount = valueNameElementCountMaximum + 1;
const size_t valueNameBytesRequired = (valueNameElementCount * sizeof(TCHAR));
valueNameMemoryBuffer = NULL;
// Compare the pattern with the value name in the registry and
// delete the matched entry
//
for (DWORD valueIndex = 0; valueIndex < valueNameCount; valueIndex++)
{
// Create new or reuse the existing memory object.
//
if (WDF_NO_HANDLE == valueNameMemory)
{
ntStatus = WdfMemoryCreate(&objectAttributes,
PagedPool,
MemoryTag,
valueNameBytesRequired,
&valueNameMemory,
(PVOID*)&valueNameMemoryBuffer);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfMemoryCreate fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
SecureZeroMemory(valueNameMemoryBuffer,
valueNameBytesRequired);
}
valueNameElementCount = valueNameElementCountMaximum + 1;
// Read the value name.
//
ntStatus = RegEnumValue((HKEY)handle,
valueIndex,
valueNameMemoryBuffer,
(LPDWORD)&valueNameElementCount,
NULL,
NULL,
NULL,
NULL);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"RegEnumValue fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
size_t bytesMatched = RtlCompareMemory((VOID*)valueNameMemoryBuffer,
patternToMatch,
patternToMatchLength);
// The start of the string should match.
//
if (bytesMatched != patternToMatchLength)
{
continue;
}
else
{
// Add to collection.
//
ntStatus = WdfCollectionAdd(registryValueNamesToBeDeleted,
valueNameMemory);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfCollectionAdd fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// We consumed this object.
//
valueNameMemory = WDF_NO_HANDLE;
}
}
// Remove the registry value names collected.
//
ULONG numberOfValueNamesToBeDeleted = WdfCollectionGetCount(registryValueNamesToBeDeleted);
for (ULONG index = 0; index < numberOfValueNamesToBeDeleted; index++)
{
WDFMEMORY registryValueNameMemory = (WDFMEMORY)WdfCollectionGetItem(registryValueNamesToBeDeleted,
index);
valueNameMemoryBuffer = (LPTSTR)WdfMemoryGetBuffer(registryValueNameMemory,
NULL);
// Delete the name value.
//
ntStatus = RegDeleteValue((HKEY)handle,
valueNameMemoryBuffer);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"RegDeleteValue fails: ntStatus=%!STATUS!",
ntStatus );
goto Exit;
}
}
Exit:
if (registryValueNamesToBeDeleted != WDF_NO_HANDLE)
{
WDFMEMORY registryValueNameMemory;
while ((registryValueNameMemory = (WDFMEMORY)WdfCollectionGetFirstItem(registryValueNamesToBeDeleted)) != NULL)
{
WdfCollectionRemoveItem(registryValueNamesToBeDeleted,
0);
WdfObjectDelete(registryValueNameMemory);
}
WdfObjectDelete(registryValueNamesToBeDeleted);
}
if (valueNameMemory != WDF_NO_HANDLE)
{
WdfObjectDelete(valueNameMemory);
}
return ntStatus;
}
typedef
NTSTATUS
ComponentFirmwareUpdate_OfferVersionsEnumerationFunctionType(
_In_ VOID* ClientContext,
_In_ UNICODE_STRING* OfferString
);
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferVersionSave (
_In_ VOID* ClientContext,
_In_ UNICODE_STRING* OfferString
)
/*++
Routine Description:
This callback function saves the given value name string in registry.
Arguments:
ClientContext - The client context. This Module's DMF Object.
OfferString - Value name string to save.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMFMODULE dmfModule;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
ULONG registryValue = 1;
dmfModule = (DMFMODULE)ClientContext;
moduleContext = DMF_CONTEXT_GET(dmfModule);
ntStatus = WdfRegistryAssignULong(moduleContext->DeviceRegistryKey,
OfferString,
registryValue);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfRegistryAssignULong fails: for offerVersion %S ntStatus=%!STATUS!",
OfferString->Buffer,
ntStatus);
goto Exit;
}
Exit:
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferVersionQuery (
_In_ VOID* ClientContext,
_In_ UNICODE_STRING* OfferString
)
/*++
Routine Description:
This callback function queries for a given value name string from the registry.
Arguments:
ClientContext - The client context. This Module's DMF Object.
OfferString - value name string to query.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMFMODULE dmfModule;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
ULONG registryValue;
dmfModule = (DMFMODULE)ClientContext;
moduleContext = DMF_CONTEXT_GET(dmfModule);
ntStatus = WdfRegistryQueryULong(moduleContext->DeviceRegistryKey,
OfferString,
®istryValue);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfRegistryQueryULong fails: for offerVersion %S ntStatus=%!STATUS!",
OfferString->Buffer,
ntStatus);
goto Exit;
}
Exit:
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_EnumeratesAllOffers (
_In_ DMFMODULE DmfModule,
_In_ ComponentFirmwareUpdate_OfferVersionsEnumerationFunctionType* OfferVersionsEnumerationFunction
)
/*++
Routine Description:
Helper function to enumerate all the offers that this driver has and for each offer, invoke
the callback the client has provided.
Arguments:
DmfModule - This Module's DMF Object.
OfferVersionsEnumerationFunction - The function that does the actual work with the enumerated offer.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
FIRMWARE_INFORMATION* firmwareInformation;
WDFMEMORY firmwareInformationMemory;
ULONG* offerContent;
size_t offerSizeFromCollection;
// OfferList Contents should have 1 offer.
//
ULONG* offerListData;
size_t offerListDataSize;
UNICODE_STRING offerVersionNameValueString;
WCHAR offerString[MAXIMUM_VALUE_NAME_SIZE];
// Size of each offer is 4 ULONGs as per spec.
//
const UINT sizeOfOneOffer = SizeOfOffer;
moduleContext = DMF_CONTEXT_GET(DmfModule);
moduleConfig = DMF_CONFIG_GET(DmfModule);
ntStatus = STATUS_UNSUCCESSFUL;
// For each offer file, get list of offers in it and call the client callback with it.
//
ULONG countOfOffers = WdfCollectionGetCount(moduleContext->FirmwareBlobCollection);
for (UINT offerFileIndex = 0; offerFileIndex < countOfOffers; ++offerFileIndex)
{
// Retrieve and validate the offer data.
//
firmwareInformationMemory = (WDFMEMORY)WdfCollectionGetItem(moduleContext->FirmwareBlobCollection,
offerFileIndex);
firmwareInformation = (FIRMWARE_INFORMATION*)WdfMemoryGetBuffer(firmwareInformationMemory,
NULL);
offerContent = (ULONG*)WdfMemoryGetBuffer(firmwareInformation->OfferContentMemory,
&offerSizeFromCollection);
DmfAssert(offerSizeFromCollection == firmwareInformation->OfferSize);
offerListData = (ULONG*)offerContent;
offerListDataSize = firmwareInformation->OfferSize;
// As per Specificiation the offer file should contain atmost one offer which is 16 bytes.
//
if (offerListDataSize != sizeOfOneOffer)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"OfferDataSize(%Id) is not 16 bytes (offer size)",
offerListDataSize);
ntStatus = STATUS_BAD_DATA;
goto Exit;
}
// Loop through each offer in the offerlist.
//
ULONG* currentOffer;
HRESULT hr;
RtlZeroMemory(offerString,
sizeof(offerString));
currentOffer = offerListData;
if (moduleConfig->InstanceIdentifierLength != 0)
{
hr = StringCchPrintf(offerString,
_countof(offerString),
L"InstanceID:%s:Offer:%X%X%X%X",
moduleConfig->InstanceIdentifier,
currentOffer[0],
currentOffer[1],
currentOffer[2],
currentOffer[3]);
} else
{
hr = StringCchPrintf(offerString,
_countof(offerString),
L"Offer:%X%X%X%X",
currentOffer[0],
currentOffer[1],
currentOffer[2],
currentOffer[3]);
}
if (FAILED(hr))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"StringCchPrintf fails: %!HRESULT!",
hr);
// This can fail with STRSAFE_E_INVALID_PARAMETER/STRSAFE_E_INSUFFICIENT_BUFFER.
// Treat as INVALID_PARAMETER.
//
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
// Call the client callback.
// Do not enumerate further if the client callback fails.
//
RtlInitUnicodeString(&offerVersionNameValueString,
(PCWSTR)offerString);
ntStatus = OfferVersionsEnumerationFunction(DmfModule,
&offerVersionNameValueString);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"OfferVersionsEnumerationFunction fails: for offerVersion %S ntStatus=%!STATUS!",
offerVersionNameValueString.Buffer,
ntStatus);
goto Exit;
}
// for each of the offer file.
//
}
Exit:
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferVersionsRegistryUpdate (
_In_ DMFMODULE DmfModule,
_In_ BOOL StoreOfferVersions
)
/*++
Routine Description:
Helper function to update the offer versions in registry.
If the Skip optimization feature is enabled,
this function will delete the obselete offer versions in the registry.
If needed, the new versions will be added back to the registry.
Arguments:
DmfModule - This Module's DMF Object.
StoreOfferVersions - Indicates whether to update the new set of offer versions or not.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
FuncEntry(DMF_TRACE);
moduleConfig = DMF_CONFIG_GET(DmfModule);
// No need to do anything further if the Skip optimization of CFU transaction is not supported.
//
if (moduleConfig->SupportProtocolTransactionSkipOptimization == FALSE)
{
ntStatus = STATUS_SUCCESS;
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Transaction Skip Optimization is not supported");
goto Exit;
}
// Remove all offer versions that may have been stored earlier.
//
ntStatus = ComponentFirmwareUpdate_OfferVersionsRegistryDelete(DmfModule);
if (!NT_SUCCESS(ntStatus))
{
goto Exit;
}
if (StoreOfferVersions)
{
ntStatus = ComponentFirmwareUpdate_EnumeratesAllOffers(DmfModule,
ComponentFirmwareUpdate_OfferVersionSave);
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
BOOLEAN
ComponentFirmwareUpdate_CurrentAndLastOfferVersionsCompare(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Helper function to compare the versions of the offers that the driver currently has and
the one it had recorded in registry earlier.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
BOOLEAN - TRUE if the versions matched, otherwise FALSE.
--*/
{
NTSTATUS ntStatus;
BOOLEAN offersMatched;
FuncEntry(DMF_TRACE);
offersMatched = FALSE;
// Enumerate the offer versions and check whether all the offer versions are present in the registy.
// Callback function, which does the query of the offer version, will fail if the offer is not found
// in registry.
//
ntStatus = ComponentFirmwareUpdate_EnumeratesAllOffers(DmfModule,
ComponentFirmwareUpdate_OfferVersionQuery);
if (!NT_SUCCESS(ntStatus))
{
goto Exit;
}
// All the enumerated functions returned SUCCESS; which means
// all the offer versions the driver has currently are all matched fully in the registry.
//
offersMatched = TRUE;
Exit:
FuncExit(DMF_TRACE, "offersMatched=%d", offersMatched);
return offersMatched;
}
BOOLEAN
ComponentFirmwareUpdate_IsProtocolTransactionSkippable(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Checks whether the CFU Protocol transaction can be skipped altogether or not.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
TRUE if there is no need for continuing CFU protocol transaction, otherwise FALSE.
--*/
{
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
BOOLEAN transactionSkippable = FALSE;
moduleConfig = DMF_CONFIG_GET(DmfModule);
// Protocol Transaction is skippable 'iff'
// Protocol Transaction Skip option setting is enabled AND
// Previous transaction indicates the firmware as all Up-to-date AND
// Current Offers the drive has is same as the one that was offered (and found to be up-to-date).
//
// No need to check further if the Skip optimization of CFU transaction is not supported.
//
if (moduleConfig->SupportProtocolTransactionSkipOptimization == FALSE)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Transaction Skip Optimization is not supported");
goto Exit;
}
// Compare the current offers and the last offers.
// If they match, Protocol transaction can be skipped.
//
transactionSkippable = ComponentFirmwareUpdate_CurrentAndLastOfferVersionsCompare(DmfModule);
Exit:
return transactionSkippable;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferListSend(
_In_ DMFMODULE DmfModule,
_In_ UINT32 OfferIndex,
_Out_ BYTE* ComponentIdentifier,
_Out_ BOOLEAN* OfferAccepted,
_Out_ BOOLEAN* OfferSkipped,
_Out_ BOOLEAN* OfferUpToDate
)
/*++
Routine Description:
Read offer data for the specified index from the context and send each offers one by one to the transport & receive the response.
Arguments:
DmfModule - This Module's DMF Object.
OfferIndex - Index of the offerlist in {offerlist,payload} pairs.
ComponentIdentifier - Component identifier from the offer data.
OfferAccepted - Indicates whether any of the offer is accepted or not.
OfferSkipped - Indicates whether any of the offer is skipped or not.
OfferUpToDate - FALSE if any offer was ACCEPT or SWAP_PENDING, TRUE otherwise.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_CODE offerCommandCode;
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE offerResponse;
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON offerResponseRejectReason;
FIRMWARE_INFORMATION* firmwareInformation;
WDFMEMORY firmwareInformationMemory;
ULONG* offerContent;
size_t offerSizeFromCollection;
// OfferList Contents should have 1 offer.
//
ULONG* offerListData = NULL;
size_t offerListDataSize;
// Size of each offer is 4 ULONGs as per spec.
//
const UINT sizeOfOneOffer = SizeOfOffer;
DWORD offerVersion;
BYTE componentIdentifier;
BOOLEAN retryOffer;
FuncEntry(DMF_TRACE);
DmfAssert(ComponentIdentifier != NULL);
DmfAssert(OfferAccepted != NULL);
DmfAssert(OfferSkipped != NULL);
DmfAssert(OfferUpToDate != NULL);
moduleContext = DMF_CONTEXT_GET(DmfModule);
*OfferAccepted = FALSE;
*OfferSkipped = FALSE;
*OfferUpToDate = TRUE; // Default to true until an offer is accepted or rejected with SWAP_PENDING.
// Retrieve and validate the offer data.
//
firmwareInformationMemory = (WDFMEMORY)WdfCollectionGetItem(moduleContext->FirmwareBlobCollection,
OfferIndex);
firmwareInformation = (FIRMWARE_INFORMATION*)WdfMemoryGetBuffer(firmwareInformationMemory,
NULL);
offerContent = (ULONG*)WdfMemoryGetBuffer(firmwareInformation->OfferContentMemory,
&offerSizeFromCollection);
DmfAssert(offerSizeFromCollection == firmwareInformation->OfferSize);
offerListData = (ULONG*)offerContent;
offerListDataSize = firmwareInformation->OfferSize;
// Spec says the offer should contain the atmost one offer which is 16 bytes.
//
if (offerListDataSize != sizeOfOneOffer)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"OfferDataSize(%Id) is not 16 bytes (offer size)",
offerListDataSize);
ntStatus = STATUS_BAD_DATA;
goto Exit;
}
// Get Component Identifier and Offer Version from the offer data.
//
componentIdentifier = ((offerListData)[0] >> 16) & 0xFF;
offerVersion = (offerListData)[1];
*ComponentIdentifier = componentIdentifier;
// Store the firmware offer version in the Registry.
//
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_OfferFwVersionValueName,
componentIdentifier,
offerVersion);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_OfferFwVersionValueName,
componentIdentifier,
offerVersion,
ntStatus);
goto Exit;
}
// Send that offer and retry as necessary.
//
while (1)
{
// Clear the retry flag.
//
retryOffer = FALSE;
// Send an offer from the offerlist.
//
ntStatus = ComponentFirmwareUpdate_OfferSend(DmfModule,
offerListData,
sizeOfOneOffer,
&offerResponse,
&offerResponseRejectReason);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveOffer fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Process the response to the offer.
//
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Offer from pair %d with Component%x returned response %s(%d)",
OfferIndex,
componentIdentifier,
ComponentFirmwareUpdateOfferResponseString(offerResponse),
offerResponse);
// Decide the next course of actions based on the response status.
//
// In the absense of a formal state machine implementation, decisions are made to a swich case.
//
switch (offerResponse)
{
case COMPONENT_FIRMWARE_UPDATE_OFFER_ACCEPT:
{
// Offer was accepted.
//
*OfferAccepted = TRUE;
*OfferUpToDate = FALSE;
goto Exit;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_SKIP:
{
// The device can choose to Skip an offer if it wants to control the order of Accepted payloads.
// Mark the flags so the caller can know to retry this function.
//
*OfferSkipped = TRUE;
break;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT:
{
// The device Rejects the offer. Store the Status and RejectReason in the registry.
// If the device Rejects with specific reasons, we can be confident that the device is up-to-date.
//
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Offer rejected due to reason %s(%d)",
ComponentFirmwareUpdateOfferResponseRejectString(offerResponseRejectReason),
offerResponseRejectReason);
// For historical telemetry reasons, we use a different code for UP_TO_DATE than REJECTED, so we remap it here.
// Response Reason FIRMWARE_UPDATE_OFFER_REJECT_OLD_FW means firmware on the device is uptodate (FIRMWARE_UPDATE_STATUS_UP_TO_DATE).
//
if (offerResponseRejectReason == COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_OLD_FW)
{
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_UP_TO_DATE);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_UP_TO_DATE,
ntStatus);
goto Exit;
}
}
else
{
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_UPDATE_REJECTED);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_UPDATE_REJECTED,
ntStatus);
goto Exit;
}
}
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusRejectReasonValueName,
componentIdentifier,
offerResponseRejectReason);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusRejectReasonValueName,
componentIdentifier,
offerResponseRejectReason,
ntStatus);
goto Exit;
}
// Not up to date if a swap is still pending.
//
if (offerResponseRejectReason == COMPONENT_FIRMWARE_UPDATE_OFFER_REJECT_SWAP_PENDING)
{
*OfferUpToDate = FALSE;
}
break;
}
case COMPONENT_FIRMWARE_UPDATE_OFFER_BUSY:
{
// The device can respond that it is Busy and needs to delay before an offer can be processed.
// In this case, we send OFFER_COMMAND_NOTIFY_ON_READY which waits infinitely for a response. The device responds whenever it is ready.
// Once we get the response, we retry the offer that originally received the OFFER_BUSY response.
//
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Waiting for the firmware to no longer be busy");
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_BUSY_PROCESSING_UPDATE);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_BUSY_PROCESSING_UPDATE,
ntStatus);
goto Exit;
}
// Wait for firmware to be ready.
//
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE offerResponseStatus;
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON offerResponseReason;
offerCommandCode = COMPONENT_FIRMWARE_UPDATE_OFFER_COMMAND_NOTIFY_ON_READY;
ntStatus = ComponentFirmwareUpdate_OfferCommandSend(DmfModule,
offerCommandCode,
&offerResponseStatus,
&offerResponseReason);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveOfferInformation fails for offerCommandCode %s(%d): ntStatus=%!STATUS!",
ComponentFirmwareUpdateOfferCommandCodeString(offerCommandCode),
offerCommandCode,
ntStatus);
goto Exit;
}
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Retrying offer for Component%x",
componentIdentifier);
retryOffer = TRUE;
break;
}
default:
{
// Unexpected offer response.
//
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Received unknown offerResponse %d",
offerResponse);
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
}
// exit the loop if not retrying.
//
if (! retryOffer)
{
break;
}
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Must_inspect_result_
static
NTSTATUS
ComponentFirmwareUpdate_OfferPayloadPairsSendAll(
_In_ DMFMODULE DmfModule,
_Out_ BOOLEAN* AnyAccepted,
_Out_ BOOLEAN* AnySkipped,
_Out_ BOOLEAN* AllUpToDate
)
/*++
Routine Description:
Outer functions for the protocol. Picks up the offers and send to transport; Based on the response send the payload.
Arguments:
DmfModule - DMFModule Handle for this Module.
AnyAccepted - Indicates whether any of the offer is accepted or not.
AnySkipped - Indicates whether any of the offer is skipped or not.
AllUpToDate - Indicates whether current Firmware is uptodate or not.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
BYTE componentIdentifier;
ULONG countOfOfferPayloadPairs;
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE offerResponseStatus;
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON offerResponseReason;
COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE payloadResponse;
COMPONENT_FIRMWARE_UPDATE_OFFER_INFORMATION_CODE offerInformationCode;
// Update protocol is aborted or not.
//
BOOLEAN forcedExit;
// True if any offer was accepted and payload transferred successfully.
//
BOOLEAN anyAccepted;
BOOLEAN anySkipped;
BOOLEAN payloadUpdateFailed;
// Initialized to TRUE, set to false if anything was accepted, skipped, or rejected for bad reasons.
//
BOOLEAN allUpToDate;
FuncEntry(DMF_TRACE);
DmfAssert(AnyAccepted != NULL);
DmfAssert(AnySkipped != NULL);
DmfAssert(AllUpToDate != NULL);
moduleContext = DMF_CONTEXT_GET(DmfModule);
payloadUpdateFailed = FALSE;
componentIdentifier = 0;
forcedExit = FALSE;
anyAccepted = FALSE;
anySkipped = FALSE;
allUpToDate = TRUE;
*AnyAccepted = FALSE;
*AnySkipped = FALSE;
*AllUpToDate = TRUE;
countOfOfferPayloadPairs = WdfCollectionGetCount(moduleContext->FirmwareBlobCollection);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Sending %d image pairs",
countOfOfferPayloadPairs);
// Send a meta-command to notify the device that this is the start of the list.
//
offerInformationCode = COMPONENT_FIRMWARE_UPDATE_OFFER_INFO_START_OFFER_LIST;
ntStatus = ComponentFirmwareUpdate_SendOfferInformation(DmfModule,
offerInformationCode,
&offerResponseStatus,
&offerResponseReason);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveOfferInformation fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Send each offer/firmware pair. If any are Accepted or Skipped, mark restartLoop as TRUE.
//
for (UINT32 pairIndex = 0; pairIndex < countOfOfferPayloadPairs; ++pairIndex)
{
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Sending image pair %d (zero index) of %d",
pairIndex,
countOfOfferPayloadPairs);
BOOLEAN currentOfferAccepted = FALSE;
BOOLEAN currentOfferSkipped = FALSE;
BOOLEAN currentStatusUpToDate = FALSE;
payloadResponse = COMPONENT_FIRMWARE_UPDATE_SUCCESS;
// Skip the protocol if the client has requested a stop request already.
//
if (ComponentFirmwareUpdate_IsProtocolStopRequestPending(DmfModule))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate protocol Stopped");
forcedExit = TRUE;
goto Exit;
}
// Send all the offers in the offer file and determine whether to send the payload.
//
ntStatus = ComponentFirmwareUpdate_OfferListSend(DmfModule,
pairIndex,
&componentIdentifier,
¤tOfferAccepted,
¤tOfferSkipped,
¤tStatusUpToDate);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_OfferPayloadPairsSendReceiveOne fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
anySkipped |= currentOfferSkipped;
// Clear if any offer response indicates firmware is not up to date.
//
allUpToDate &= currentStatusUpToDate;
// Skip the protocol if the client has requested a stop request already.
//
if (ComponentFirmwareUpdate_IsProtocolStopRequestPending(DmfModule))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate protocol Stopped");
forcedExit = TRUE;
goto Exit;
}
if (currentOfferAccepted)
{
DmfAssert(allUpToDate == FALSE);
// The device wants the driver to deliver the payload.
// Mark the download status in the registry while delivering the payload.
//
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_DOWNLOADING_UPDATE);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_DOWNLOADING_UPDATE,
ntStatus);
goto Exit;
}
ntStatus = ComponentFirmwareUpdate_SendPayload(DmfModule,
pairIndex,
componentIdentifier,
&payloadResponse);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveFirmware fails for firmwareIntegerValue %d: ntStatus=%!STATUS!",
pairIndex,
ntStatus);
goto Exit;
}
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Firmware from pair %d returned response %s(%d)",
pairIndex,
ComponentFirmwareUpdatePayloadResponseString(payloadResponse),
payloadResponse);
if (payloadResponse == COMPONENT_FIRMWARE_UPDATE_SUCCESS)
{
// Payload sent successfully, mark this current offer as accepted.
//
anyAccepted |= currentOfferAccepted;
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_PENDING_RESET);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_PENDING_RESET,
ntStatus);
goto Exit;
}
}
}
// if the offer was accepted and yet the payload is rejected, exit.
//
if (currentOfferAccepted && (payloadResponse != COMPONENT_FIRMWARE_UPDATE_SUCCESS))
{
payloadUpdateFailed = TRUE;
goto Exit;
}
}
// Skip the protocol if the client has requested a stop request already.
//
if (ComponentFirmwareUpdate_IsProtocolStopRequestPending(DmfModule))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate protocol Stopped");
forcedExit = TRUE;
goto Exit;
}
// Send a meta-command to notify the device that this is the end of the list.
//
offerInformationCode = COMPONENT_FIRMWARE_UPDATE_OFFER_INFO_END_OFFER_LIST;
ntStatus = ComponentFirmwareUpdate_SendOfferInformation(DmfModule,
offerInformationCode,
&offerResponseStatus,
&offerResponseReason);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveOfferInformation fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
*AnyAccepted = anyAccepted;
*AnySkipped = anySkipped;
*AllUpToDate = allUpToDate;
Exit:
if (! NT_SUCCESS(ntStatus) || payloadUpdateFailed)
{
// Write the status as Error in the case of an error.
//
NTSTATUS ntStatus2 = ComponentFirmwareUpdate_RegistryAssignComponentUlong(DmfModule,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_ERROR);
if (!NT_SUCCESS(ntStatus2))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong fails for %ws with Component%x and value 0x%x: ntStatus=%!STATUS!",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_ERROR,
ntStatus2);
}
}
if (forcedExit)
{
ntStatus = STATUS_ABANDONED;
}
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
_Function_class_(EVT_DMF_Thread_Function)
VOID
ComponentFirmwareUpdate_FirmwareUpdatePre(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Callback function for Child DMF Module Thread Pre.
Opens the transport.
Arguments:
DmfModule - The Child Module from which this callback is called.
Return Value:
None
--*/
{
NTSTATUS ntStatus;
DMFMODULE dmfModuleComponentFirmwareUpdate;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
FuncEntry(DMF_TRACE);
// This Module is the parent of the Child Module that is passed in.
// (Module callbacks always receive the Child Module's handle.)
//
dmfModuleComponentFirmwareUpdate = DMF_ParentModuleGet(DmfModule);
moduleContext = DMF_CONTEXT_GET(dmfModuleComponentFirmwareUpdate);
DMF_ModuleLock(dmfModuleComponentFirmwareUpdate);
moduleContext->TransactionInProgress = TRUE;
DMF_ModuleUnlock(dmfModuleComponentFirmwareUpdate);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Sending a Open command to transport");
// Call Open to the transport to allow it to preform any preparation steps to receive the protocol transaction.
//
ntStatus = ComponentFirmwareUpdate_ProtocolStart(dmfModuleComponentFirmwareUpdate);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_ProtocolStart fails: ntStatus=%!STATUS!",
ntStatus);
// Don't do the 'work' when Pre fails.
//
DMF_Thread_Stop(DmfModule);
goto Exit;
}
Exit:
FuncExitVoid(DMF_TRACE);
}
_Function_class_(EVT_DMF_Thread_Function)
VOID
ComponentFirmwareUpdate_FirmwareUpdatePost(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Callback function for Child DMF Module Thread Post.
Arguments:
DmfModule - The Child Module from which this callback is called.
Return Value:
None
--*/
{
DMFMODULE dmfModuleComponentFirmwareUpdate;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
FuncEntry(DMF_TRACE);
// This Module is the parent of the Child Module that is passed in.
// (Module callbacks always receive the Child Module's handle.)
//
dmfModuleComponentFirmwareUpdate = DMF_ParentModuleGet(DmfModule);
moduleContext = DMF_CONTEXT_GET(dmfModuleComponentFirmwareUpdate);
DMF_ModuleLock(dmfModuleComponentFirmwareUpdate);
moduleContext->TransactionInProgress = FALSE;
DMF_ModuleUnlock(dmfModuleComponentFirmwareUpdate);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"CFU Transaction finished");
FuncExitVoid(DMF_TRACE);
}
_Function_class_(EVT_DMF_Thread_Function)
VOID
ComponentFirmwareUpdate_FirmwareUpdateWork(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Callback function for Child DMF Module Thread.
"Work" is to perform firmware update protocol as per the specification.
Arguments:
DmfModule - The Child Module from which this callback is called.
Return Value:
None
--*/
{
NTSTATUS ntStatus;
DMFMODULE dmfModuleComponentFirmwareUpdate;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
COMPONENT_FIRMWARE_VERSIONS firmwareVersions = { 0 };
BOOLEAN skipProtocolTransaction;
UINT8 loopIteration;
BOOLEAN restartLoop;
BOOLEAN anyAccepted;
BOOLEAN anySkipped;
BOOLEAN allUpToDate;
FuncEntry(DMF_TRACE);
// This Module is the parent of the Child Module that is passed in.
// (Module callbacks always receive the Child Module's handle.)
//
dmfModuleComponentFirmwareUpdate = DMF_ParentModuleGet(DmfModule);
moduleContext = DMF_CONTEXT_GET(dmfModuleComponentFirmwareUpdate);
moduleConfig = DMF_CONFIG_GET(dmfModuleComponentFirmwareUpdate);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Start of the CFU protocol.");
anyAccepted = FALSE;
anySkipped = FALSE;
allUpToDate = FALSE;
skipProtocolTransaction = FALSE;
loopIteration = 0;
ULONG countOfOfferPayloadPairs = WdfCollectionGetCount(moduleContext->FirmwareBlobCollection);
if (countOfOfferPayloadPairs == 0)
{
TraceEvents(TRACE_LEVEL_WARNING,
DMF_TRACE,
"No Firmware available to process. Skipping the entire transaction.");
ntStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Component Firmware Update Transaction Start");
// Get the firmware versions of each components from device and store in the registry.
// These can be useful for external tools that scans the registry and collect information on various stages
// of firmware update protocol.
// The version returned from this call is not used in any decision making. So a failure here is
// NOT considered critical and is ignored.
//
ntStatus = ComponentFirmwareUpdate_FirmwareVersionsGet(dmfModuleComponentFirmwareUpdate,
&firmwareVersions);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_GetFirmwareVersions fails: %!STATUS!, but continuing because this is not a critical failure",
ntStatus);
ntStatus = STATUS_SUCCESS;
ZeroMemory(&firmwareVersions,
sizeof(firmwareVersions));
}
else
{
for (UINT componentIndex = 0;
componentIndex < firmwareVersions.componentCount;
++componentIndex)
{
BYTE componentIdentifier = firmwareVersions.ComponentIdentifiers[componentIndex];
DWORD componentFirmwareVersion = firmwareVersions.FirmwareVersion[componentIndex];
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(dmfModuleComponentFirmwareUpdate,
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_NOT_STARTED);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong failed for %ws with Component%x and value 0x%x %!STATUS!, but ignoring error",
ComponentFirmwareUpdate_FirmwareUpdateStatusValueName,
componentIdentifier,
FIRMWARE_UPDATE_STATUS_NOT_STARTED,
ntStatus);
ntStatus = STATUS_SUCCESS;
}
ntStatus = ComponentFirmwareUpdate_RegistryAssignComponentUlong(dmfModuleComponentFirmwareUpdate,
ComponentFirmwareUpdate_CurrentFwVersionValueName,
componentIdentifier,
componentFirmwareVersion);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_RegistryAssignComponentUlong failed for %ws with Component%x and value 0x%x %!STATUS!, but ignoring error",
ComponentFirmwareUpdate_CurrentFwVersionValueName,
componentIdentifier,
componentFirmwareVersion,
ntStatus);
ntStatus = STATUS_SUCCESS;
}
ntStatus = ComponentFirmwareUpdate_RegistryRemoveComponentValue(dmfModuleComponentFirmwareUpdate,
ComponentFirmwareUpdate_FirmwareUpdateStatusRejectReasonValueName,
componentIdentifier);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_RegistryRemoveComponentValue failed for %ws with Component%x %!STATUS!, but ignoring error",
ComponentFirmwareUpdate_FirmwareUpdateStatusRejectReasonValueName,
componentIdentifier,
ntStatus);
ntStatus = STATUS_SUCCESS;
}
}
}
// Skip the protocol if the client has requested a stop request already.
//
if (ComponentFirmwareUpdate_IsProtocolStopRequestPending(dmfModuleComponentFirmwareUpdate))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate protocol Stopped");
goto Exit;
}
// Skip the protocol if there is nothing new to offer to the firmware and its already known to be up-to-date.
//
skipProtocolTransaction = ComponentFirmwareUpdate_IsProtocolTransactionSkippable(dmfModuleComponentFirmwareUpdate);
if (skipProtocolTransaction)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Skipping the entire transaction");
goto Exit;
}
// Send a meta-command to notify the device that this is the start of the entire transaction.
//
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE offerResponseStatus;
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON offerResponseReason;
COMPONENT_FIRMWARE_UPDATE_OFFER_INFORMATION_CODE offerInformationCode = COMPONENT_FIRMWARE_UPDATE_OFFER_INFO_START_ENTIRE_TRANSACTION;
ntStatus = ComponentFirmwareUpdate_SendOfferInformation(dmfModuleComponentFirmwareUpdate,
offerInformationCode,
&offerResponseStatus,
&offerResponseReason);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveOfferInformation fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Send every payload pair. Repeat until all of the offers are Rejected.
// This allows the device to control the order that payloads are taken.
//
restartLoop = FALSE;
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Start sending %d offer/payload pairs",
WdfCollectionGetCount(moduleContext->FirmwareBlobCollection));
do
{
// Skip the protocol if the client has requested a stop request already.
//
if (ComponentFirmwareUpdate_IsProtocolStopRequestPending(dmfModuleComponentFirmwareUpdate))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate protocol Stopped");
ntStatus = STATUS_ABANDONED;
goto Exit;
}
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Start iteration %d",
loopIteration);
ntStatus = ComponentFirmwareUpdate_OfferPayloadPairsSendAll(dmfModuleComponentFirmwareUpdate,
&anyAccepted,
&anySkipped,
&allUpToDate);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareUpdate_SendReceiveOfferPayloadPairs fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// If nothing was accepted on an iteration after the first, do not restart the loop to prevent infinite loop.
//
if (
(loopIteration == 0 && (anyAccepted || anySkipped)) ||
(loopIteration > 0 && anyAccepted)
)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Restarting loop with loopIteration(%d), anyAccepted(%d), anySkipped(%d)",
loopIteration,
anyAccepted,
anySkipped);
restartLoop = TRUE;
}
else
{
restartLoop = FALSE;
}
if (moduleConfig->ForceIgnoreVersion)
{
// If we are force ignoring the version, every offer will be accepted. We have to prevent an infinite loop.
//
restartLoop = FALSE;
}
++loopIteration;
} while (restartLoop == TRUE);
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Exited the loop normally after %d iterations.",
loopIteration);
if (allUpToDate)
{
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Firmware is all up-to-date");
}
// Update the firmware versions in Registry as needed.
//
NTSTATUS ntStatus2 = ComponentFirmwareUpdate_OfferVersionsRegistryUpdate(dmfModuleComponentFirmwareUpdate,
allUpToDate);
if (! NT_SUCCESS(ntStatus2))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_OfferVersionsRegistryUpdate fails: ntStatus=%!STATUS!",
ntStatus2);
goto Exit;
}
Exit:
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"End of the CFU protocol.");
FuncExitVoid(DMF_TRACE);
}
// CFU Protocol Related (END)
//=============================
///////////////////////////////////////////////////////////////////////////////////////////////////////
// WDF Module Callbacks
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////////////////////////////
// DMF Module Callbacks
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Protocol Generic Callbacks.
// (Implementation of publicly accessible callbacks required by the Interface.)
//
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
DMF_ComponentFirmwareUpdate_PostBind(
_In_ DMFINTERFACE DmfInterface
)
/*++
Routine Description:
This callback tells the given Protocol Module that it is bound to the given
Transport Module.
Arguments:
DmfInterface - Interface handle.
Return Value:
NTSTATUS
--*/
{
PAGED_CODE();
UNREFERENCED_PARAMETER(DmfInterface);
FuncEntry(DMF_TRACE);
// NOP.
// It is now possible to use Methods provided by the Transport.
//
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
DMF_ComponentFirmwareUpdate_PreUnbind(
_In_ DMFINTERFACE DmfInterface
)
/*++
Routine Description:
This callback tells the given Protocol Module that it is about to be unbound from
the given Transport Module.
Arguments:
DmfInterface - Interface handle.
Return Value:
None
--*/
{
PAGED_CODE();
UNREFERENCED_PARAMETER(DmfInterface);
FuncEntry(DMF_TRACE);
// NOP.
//
// Stop using Methods provided by Transport after this callback completes (except for Unbind).
//
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
NTSTATUS
DMF_ComponentFirmwareUpdate_Bind(
_In_ DMFINTERFACE DmfInterface
)
/*++
Routine Description:
Binds the given Protocol Module to the given Transport Module.
Arguments:
DmfInterface - Interface handle.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
WDFDEVICE device;
WDF_OBJECT_ATTRIBUTES attributes;
DMF_MODULE_ATTRIBUTES moduleAttributes;
DMF_INTERFACE_PROTOCOL_ComponentFirmwareUpdate_BIND_DATA protocolBindData;
DMF_INTERFACE_TRANSPORT_ComponentFirmwareUpdate_BIND_DATA transportBindData;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
CONTEXT_ComponentFirmwareUpdateTransport* configComponentFirmwareUpdateTransport;
DMFMODULE protocolModule;
PAGED_CODE();
FuncEntry(DMF_TRACE);
protocolModule = DMF_InterfaceProtocolModuleGet(DmfInterface);
moduleContext = DMF_CONTEXT_GET(protocolModule);
moduleConfig = DMF_CONFIG_GET(protocolModule);
RtlZeroMemory(&protocolBindData,
sizeof(protocolBindData));
// Call the Interface's Bind function.
//
ntStatus = DMF_ComponentFirmwareUpdate_TransportBind(DmfInterface,
&protocolBindData,
&transportBindData);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ComponentFirmwareUpdate_TransportBind fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Save the Interface handle representing the interface binding.
//
moduleContext->DmfInterfaceComponentFirmwareUpdate = DmfInterface;
// Check the TransportPayloadRequiredSize to ensure that it meets minimal packet size requirement.
// Driver needs the following size per specification.
// Offer Command is 16 bytes.
// Offer Information is 16 bytes.
// Offer is 16 bytes.
// Payload Chunk size is variable; The maximum driver can send is 60 bytes.
//
if (transportBindData.TransportFirmwarePayloadBufferRequiredSize < SizeOfPayload)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Transport payload size (%Id) is insufficient",
transportBindData.TransportFirmwarePayloadBufferRequiredSize);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
// Check for Overflow.
//
if (transportBindData.TransportFirmwarePayloadBufferRequiredSize > transportBindData.TransportFirmwarePayloadBufferRequiredSize + transportBindData.TransportHeaderSize)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Payload size Overflow (%d)+(%d)",
transportBindData.TransportFirmwarePayloadBufferRequiredSize,
transportBindData.TransportHeaderSize);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
if (transportBindData.TransportFirmwareVersionBufferRequiredSize < SizeOfFirmwareVersion)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Transport Firmware Version size (%Id) is insufficient",
transportBindData.TransportFirmwareVersionBufferRequiredSize);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
// Check for Overflow.
//
if (transportBindData.TransportFirmwareVersionBufferRequiredSize > transportBindData.TransportFirmwareVersionBufferRequiredSize + transportBindData.TransportHeaderSize)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Payload size Overflow (%d)+(%d)",
transportBindData.TransportFirmwareVersionBufferRequiredSize,
transportBindData.TransportHeaderSize);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
if (transportBindData.TransportOfferBufferRequiredSize < SizeOfOffer)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Transport Offer size (%Id) is insufficient",
transportBindData.TransportOfferBufferRequiredSize);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
// Check for Overflow.
//
if (transportBindData.TransportOfferBufferRequiredSize > transportBindData.TransportOfferBufferRequiredSize + transportBindData.TransportHeaderSize)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Payload size Overflow (%d)+(%d)",
transportBindData.TransportOfferBufferRequiredSize,
transportBindData.TransportHeaderSize);
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
if (transportBindData.TransportPayloadFillAlignment == 0)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Invalid TransportPayloadFillAlignment. It can not be 0");
ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
configComponentFirmwareUpdateTransport = ComponentFirmwareUpdateTransportContextGet(DmfInterface);
configComponentFirmwareUpdateTransport->TransportHeaderSize = transportBindData.TransportHeaderSize;
configComponentFirmwareUpdateTransport->TransportFirmwarePayloadBufferRequiredSize = transportBindData.TransportFirmwarePayloadBufferRequiredSize;
configComponentFirmwareUpdateTransport->TransportFirmwareVersionBufferRequiredSize = transportBindData.TransportFirmwareVersionBufferRequiredSize;
configComponentFirmwareUpdateTransport->TransportOfferBufferRequiredSize = transportBindData.TransportOfferBufferRequiredSize;
configComponentFirmwareUpdateTransport->TransportWaitTimeout = transportBindData.TransportWaitTimeout;
configComponentFirmwareUpdateTransport->TransportPayloadFillAlignment = transportBindData.TransportPayloadFillAlignment;
// Allocate a Context to keep items for transaction response response specific processing.
//
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes,
CONTEXT_ComponentFirmwareUpdateTransaction);
ntStatus = WdfObjectAllocateContext(DmfInterface,
&attributes,
(VOID**) &componentFirmwareUpdateTransactionContext);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"WdfObjectAllocateContext fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = protocolModule;
device = DMF_ParentDeviceGet(protocolModule);
// BufferQueue
// -----------
//
DMF_CONFIG_BufferQueue bufferQueueModuleConfig;
DMF_CONFIG_BufferQueue_AND_ATTRIBUTES_INIT(&bufferQueueModuleConfig,
&moduleAttributes);
bufferQueueModuleConfig.SourceSettings.EnableLookAside = TRUE;
bufferQueueModuleConfig.SourceSettings.BufferCount = 5;
bufferQueueModuleConfig.SourceSettings.BufferSize = sizeof(PAYLOAD_RESPONSE);
bufferQueueModuleConfig.SourceSettings.BufferContextSize = sizeof(ULONG);
bufferQueueModuleConfig.SourceSettings.PoolType = NonPagedPoolNx;
ntStatus = DMF_BufferQueue_Create(device,
&moduleAttributes,
&attributes,
&componentFirmwareUpdateTransactionContext->DmfModuleBufferQueue);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_BufferQueue_Create fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
// Create the Work Ready Event.
//
DMF_Portable_EventCreate(&componentFirmwareUpdateTransactionContext->DmfResponseCompletionEvent,
SynchronizationEvent,
FALSE);
// Create the Protocol Transaction Cancel Event.
//
DMF_Portable_EventCreate(&componentFirmwareUpdateTransactionContext->DmfProtocolTransactionCancelEvent,
SynchronizationEvent,
FALSE);
TraceEvents(TRACE_LEVEL_INFORMATION, DMF_TRACE, "DMF_ComponentFirmwareUpdate_Bind success");
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
DMF_ComponentFirmwareUpdate_Unbind(
_In_ DMFINTERFACE DmfInterface
)
/*++
Routine Description:
Unbinds the given Protocol Module from the given Transport Module.
Arguments:
DmfInterface - Interface handle.
Return Value:
None
--*/
{
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
PAGED_CODE();
FuncEntry(DMF_TRACE);
// Call the Interface's Unbind function.
//
DMF_ComponentFirmwareUpdate_TransportUnbind(DmfInterface);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(DmfInterface);
DMF_Portable_EventClose(&componentFirmwareUpdateTransactionContext->DmfResponseCompletionEvent);
DMF_Portable_EventClose(&componentFirmwareUpdateTransactionContext->DmfProtocolTransactionCancelEvent);
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
// Callback Implementation
// --------START----------
//
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
DMF_ComponentFirmwareUpdate_FirmwareVersionResponseEvt(
_In_ DMFINTERFACE DmfInterface,
_In_ UCHAR* FirmwareVersionsBuffer,
_In_ size_t FirmwareVersionsBufferSize,
_In_ NTSTATUS ntStatusCallback
)
/*++
Routine Description:
Callback to indicate the firmware versions.
This unpacks the message and store the response in a context and signal event
to wakeup the thread that is waiting for response.
Parameters:
DmfInterface - Interface handle.
FirmwareVersionsBuffer - Buffer with firmware information.
FirmwareVersionsBufferSize - size of the above in bytes.
ntStatusCallback - NTSTATUS for the FirmwareVersionGet.
Return:
NTSTATUS
--*/
{
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
FuncEntry(DMF_TRACE);
UNREFERENCED_PARAMETER(FirmwareVersionsBufferSize);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(DmfInterface);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
componentFirmwareUpdateTransactionContext->ntStatus = ntStatusCallback;
if (!NT_SUCCESS(ntStatusCallback))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"FirmwareVersionGet fails: ntStatus=%!STATUS!",
ntStatusCallback);
goto Exit;
}
DmfAssert(FirmwareVersionsBuffer != NULL);
// Parse and store the response data.
//
BYTE componentCount;
BYTE firmwareUpdateProtocolRevision;
// Byte 0 is Component Count.
//
componentCount = (BYTE)FirmwareVersionsBuffer[0];
if (componentCount == 0)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Invalid Response from Device. ComponentCount == 0.");
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
// We have a limitation on the number of components (7).
//
if (componentFirmwareUpdateTransactionContext->FirmwareVersions.componentCount >= MAX_NUMBER_OF_IMAGE_PAIRS)
{
DmfAssert(FALSE);
TraceError(DMF_TRACE,
"Invalid ComponentCount(%d) greater than max supported(%d).",
componentCount,
MAX_NUMBER_OF_IMAGE_PAIRS);
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
componentFirmwareUpdateTransactionContext->FirmwareVersions.componentCount = componentCount;
firmwareUpdateProtocolRevision = FirmwareVersionsBuffer[3] & 0xF;
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Device is using FW Update Protocol Revision %d",
firmwareUpdateProtocolRevision);
DWORD* firmwareVersion = NULL;
if (firmwareUpdateProtocolRevision == PROTOCOL_VERSION_2 || firmwareUpdateProtocolRevision == PROTOCOL_VERSION_4)
{
// Header is 4 bytes.
//
const UINT versionTableOffset = 4;
// Component ID is 6th byte.
//
const UINT componentIDOffset = 5;
// Each component takes up 8 bytes.
//
const UINT componentDataSize = 8;
DmfAssert(FirmwareVersionsBufferSize >= versionTableOffset + componentCount * componentDataSize);
for (int componentIndex = 0; componentIndex < componentCount; ++componentIndex)
{
componentFirmwareUpdateTransactionContext->FirmwareVersions.ComponentIdentifiers[componentIndex] = (BYTE)FirmwareVersionsBuffer[versionTableOffset + componentIndex * componentDataSize + componentIDOffset];
firmwareVersion = &componentFirmwareUpdateTransactionContext->FirmwareVersions.FirmwareVersion[componentIndex];
*firmwareVersion = 0;
*firmwareVersion |= ((FirmwareVersionsBuffer[versionTableOffset + componentIndex * componentDataSize + 0] & 0xFF) << 0);
*firmwareVersion |= ((FirmwareVersionsBuffer[versionTableOffset + componentIndex * componentDataSize + 1] & 0xFF) << 8);
*firmwareVersion |= ((FirmwareVersionsBuffer[versionTableOffset + componentIndex * componentDataSize + 2] & 0xFF) << 16);
*firmwareVersion |= ((FirmwareVersionsBuffer[versionTableOffset + componentIndex * componentDataSize + 3] & 0xFF) << 24);
TraceEvents(TRACE_LEVEL_VERBOSE,
DMF_TRACE,
"Component%02x has version 0x%x",
componentFirmwareUpdateTransactionContext->FirmwareVersions.ComponentIdentifiers[componentIndex],
*firmwareVersion);
}
}
else
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Unrecognized FW Update Protocol Revision %d",
firmwareUpdateProtocolRevision);
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
goto Exit;
}
Exit:
// Set Event the event so that the sending thread gets the response.
//
DMF_Portable_EventSet(&componentFirmwareUpdateTransactionContext->DmfResponseCompletionEvent);
FuncExitVoid(DMF_TRACE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
DMF_ComponentFirmwareUpdate_OfferResponseEvt(
_In_ DMFINTERFACE DmfInterface,
_In_ UCHAR* ResponseBuffer,
_In_ size_t ResponseBufferSize,
_In_ NTSTATUS ntStatusCallback
)
/*++
Routine Description:
Callback to indicate the response to an offer that was sent to device.
Parameters:
DmfInterface - Interface handle.
ResponseBuffer - Buffer with response information.
ResponseBufferSize - size of the above in bytes.
ntStatusCallback - NTSTATUS for the command that was sent down.
Return:
NTSTATUS
--*/
{
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
ULONG numberOfUlongsInResponse = 4;
const BYTE outputToken = FWUPDATE_DRIVER_TOKEN;
FuncEntry(DMF_TRACE);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(DmfInterface);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
componentFirmwareUpdateTransactionContext->ntStatus = ntStatusCallback;
if (!NT_SUCCESS(ntStatusCallback))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Offer send fails: ntStatus=%!STATUS!",
ntStatusCallback);
goto Exit;
}
// Offer response size is 4 * ULONG .
//
if (numberOfUlongsInResponse * sizeof(ULONG) > ResponseBufferSize)
{
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Return Buffer size (%Id) insufficient",
ResponseBufferSize);
goto Exit;
}
ULONG* offerResponseLocal = (ULONG*)ResponseBuffer;
// Get Token (Byte 3) and Validate it.
//
BYTE tokenResponse = (offerResponseLocal[0] >> 24) & 0xFF;
if (outputToken != tokenResponse)
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Output Token(%d) did not match Returned Token(%d)",
outputToken,
tokenResponse);
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_INVALID_DEVICE_STATE;
goto Exit;
}
// Get Offer Response Reason (Byte 0).
//
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON offerResponseReason = (COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE_REJECT_REASON)((offerResponseLocal[2]) & 0xFF);
// Get Offer Response Status (Byte 0).
//
COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE offerResponseStatus = (COMPONENT_FIRMWARE_UPDATE_OFFER_RESPONSE)((offerResponseLocal[3]) & 0xFF);
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseStatus = offerResponseStatus;
componentFirmwareUpdateTransactionContext->OfferResponse.OfferResponseReason = offerResponseReason;
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_SUCCESS;
Exit:
// Set Event the event so that the sending thread gets the response.
//
DMF_Portable_EventSet(&componentFirmwareUpdateTransactionContext->DmfResponseCompletionEvent);
FuncExitVoid(DMF_TRACE);
}
// Callback to response to payload that is sent to device.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
DMF_ComponentFirmwareUpdate_PayloadResponseEvt(
_In_ DMFINTERFACE DmfInterface,
_In_ UCHAR* ResponseBuffer,
_In_ size_t ResponseBufferSize,
_In_ NTSTATUS ntStatusCallback
)
/*++
Routine Description:
Callback to indicate the response to a payload that was sent to device.
Parameters:
DmfInterface - Interface handle.
ResponseBuffer - Buffer with response information.
ResponseBufferSize - size of the above in bytes.
ntStatusCallback - NTSTATUS for the command that was sent down.
Return:
NTSTATUS
--*/
{
CONTEXT_ComponentFirmwareUpdateTransaction* componentFirmwareUpdateTransactionContext;
ULONG numberOfUlongsInResponse = 4;
VOID* clientBuffer= NULL;
VOID* clientBufferContext = NULL;
FuncEntry(DMF_TRACE);
componentFirmwareUpdateTransactionContext = ComponentFirmwareUpdateTransactionContextGet(DmfInterface);
DmfAssert(componentFirmwareUpdateTransactionContext != NULL);
DmfAssert(ResponseBuffer != NULL);
componentFirmwareUpdateTransactionContext->ntStatus = ntStatusCallback;
if (!NT_SUCCESS(ntStatusCallback))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"PayloadSend fails: ntStatus=%!STATUS!",
ntStatusCallback);
goto Exit;
}
// Payload response size is 4 * ULONG.
//
if (numberOfUlongsInResponse * sizeof(ULONG) > ResponseBufferSize)
{
componentFirmwareUpdateTransactionContext->ntStatus = STATUS_DEVICE_PROTOCOL_ERROR;
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"Return Buffer size (%Id) in sufficient",
ResponseBufferSize);
goto Exit;
}
ULONG* payloadResponseLocal = (ULONG*)ResponseBuffer;
// Get Response Sequence Number (Bytes 0-1).
//
UINT16 responseSequenceNumber = (UINT16)((payloadResponseLocal[0] >> 0) & 0xFFFF);
// Get Payload Response Status (Byte 0).
//
COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE responseSequenceStatus = (COMPONENT_FIRMWARE_UPDATE_PAYLOAD_RESPONSE)((payloadResponseLocal[1] >> 0) & 0xFF);
// Get a buffer from Producer for feature Report.
//
componentFirmwareUpdateTransactionContext->ntStatus = DMF_BufferQueue_Fetch(componentFirmwareUpdateTransactionContext->DmfModuleBufferQueue,
&clientBuffer,
&clientBufferContext);
if (!NT_SUCCESS(componentFirmwareUpdateTransactionContext->ntStatus))
{
// There is no data buffer to save the response.
//
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_BufferQueue_ClientBufferGetProducer fails: ntStatus=%!STATUS!",
componentFirmwareUpdateTransactionContext->ntStatus);
goto Exit;
}
DmfAssert(clientBuffer != NULL);
DmfAssert(clientBufferContext != NULL);
PAYLOAD_RESPONSE* payloadResponse = (PAYLOAD_RESPONSE*)clientBuffer;
ULONG* payloadResponseSize = (ULONG*)clientBufferContext;
payloadResponse->SequenceNumber = responseSequenceNumber;
payloadResponse->ResponseStatus = responseSequenceStatus;
// put this to the consumer.
//
*payloadResponseSize = sizeof(PAYLOAD_RESPONSE);
DMF_BufferQueue_Enqueue(componentFirmwareUpdateTransactionContext->DmfModuleBufferQueue,
clientBuffer);
Exit:
// Set Event the event so that the sending thread gets the response.
//
DMF_Portable_EventSet(&componentFirmwareUpdateTransactionContext->DmfResponseCompletionEvent);
FuncExitVoid(DMF_TRACE);
}
// Callback Implementation
// --------END------------
#pragma code_seg("PAGE")
_Function_class_(DMF_ChildModulesAdd)
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_ComponentFirmwareUpdate_ChildModulesAdd(
_In_ DMFMODULE DmfModule,
_In_ DMF_MODULE_ATTRIBUTES* DmfParentModuleAttributes,
_In_ PDMFMODULE_INIT DmfModuleInit
)
/*++
Routine Description:
Configure and add the required Child Modules to the given Parent Module.
Arguments:
DmfModule - The given Parent Module.
DmfParentModuleAttributes - Pointer to the parent DMF_MODULE_ATTRIBUTES structure.
DmfModuleInit - Opaque structure to be passed to DMF_DmfModuleAdd.
Return Value:
None
--*/
{
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
DMF_MODULE_ATTRIBUTES moduleAttributes;
DMF_CONFIG_Thread threadModuleConfig;
PAGED_CODE();
UNREFERENCED_PARAMETER(DmfParentModuleAttributes);
UNREFERENCED_PARAMETER(DmfModuleInit);
FuncEntry(DMF_TRACE);
moduleConfig = DMF_CONFIG_GET(DmfModule);
moduleContext = DMF_CONTEXT_GET(DmfModule);
RtlZeroMemory(moduleContext,
sizeof(DMF_CONTEXT_ComponentFirmwareUpdate));
// Thread
// ------
//
DMF_CONFIG_Thread_AND_ATTRIBUTES_INIT(&threadModuleConfig,
&moduleAttributes);
threadModuleConfig.ThreadControlType = ThreadControlType_DmfControl;
threadModuleConfig.ThreadControl.DmfControl.EvtThreadPre = ComponentFirmwareUpdate_FirmwareUpdatePre;
threadModuleConfig.ThreadControl.DmfControl.EvtThreadPost = ComponentFirmwareUpdate_FirmwareUpdatePost;
threadModuleConfig.ThreadControl.DmfControl.EvtThreadWork = ComponentFirmwareUpdate_FirmwareUpdateWork;
DMF_DmfModuleAdd(DmfModuleInit,
&moduleAttributes,
WDF_NO_OBJECT_ATTRIBUTES,
&moduleContext->DmfModuleThread);
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
#pragma code_seg("PAGE")
_Function_class_(DMF_Open)
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
static
NTSTATUS
DMF_ComponentFirmwareUpdate_Open(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Initialize an instance of a DMF Module of type ComponentFirmwareUpdate.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONFIG_ComponentFirmwareUpdate* moduleConfig;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
PAGED_CODE();
FuncEntry(DMF_TRACE);
moduleConfig = DMF_CONFIG_GET(DmfModule);
moduleContext = DMF_CONTEXT_GET(DmfModule);
ntStatus = ComponentFirmwareUpdate_ComponentFirmwareUpdateInitialize(DmfModule);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"ComponentFirmwareUpdate_ComponentFirmwareUpdateInitialize fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
#pragma code_seg("PAGE")
_Function_class_(DMF_Close)
_IRQL_requires_max_(PASSIVE_LEVEL)
static
VOID
DMF_ComponentFirmwareUpdate_Close(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Uninitialize an instance of a DMF Module of type ComponentFirmwareUpdate.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
NTSTATUS
--*/
{
PAGED_CODE();
FuncEntry(DMF_TRACE);
ComponentFirmwareUpdate_ComponentFirmwareUpdateDeinitialize(DmfModule);
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Public Calls by Client
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
NTSTATUS
DMF_ComponentFirmwareUpdate_Create(
_In_ WDFDEVICE Device,
_In_ DMF_MODULE_ATTRIBUTES* DmfModuleAttributes,
_In_ WDF_OBJECT_ATTRIBUTES* ObjectAttributes,
_Out_ DMFMODULE* DmfModule
)
/*++
Routine Description:
Create an instance of a DMF Module of type Component Firmware Update.
Arguments:
Device - This device.
DmfModuleAttributes - Opaque structure that contains parameters DMF needs to initialize the Module.
ObjectAttributes - WDF object attributes for DMFMODULE.
DmfModule - Address of the location where the created DMFMODULE handle is returned.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_MODULE_DESCRIPTOR dmfModuleDescriptor_ComponentFirmwareUpdate;
DMF_CALLBACKS_DMF dmfCallbacksDmf_ComponentFirmwareUpdate;
DMF_INTERFACE_PROTOCOL_ComponentFirmwareUpdate_DECLARATION_DATA protocolDeclarationData;
DMFMODULE dmfModule;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DMF_CALLBACKS_DMF_INIT(&dmfCallbacksDmf_ComponentFirmwareUpdate);
dmfCallbacksDmf_ComponentFirmwareUpdate.ChildModulesAdd = DMF_ComponentFirmwareUpdate_ChildModulesAdd;
dmfCallbacksDmf_ComponentFirmwareUpdate.DeviceOpen = DMF_ComponentFirmwareUpdate_Open;
dmfCallbacksDmf_ComponentFirmwareUpdate.DeviceClose = DMF_ComponentFirmwareUpdate_Close;
DMF_MODULE_DESCRIPTOR_INIT_CONTEXT_TYPE(dmfModuleDescriptor_ComponentFirmwareUpdate,
ComponentFirmwareUpdate,
DMF_CONTEXT_ComponentFirmwareUpdate,
DMF_MODULE_OPTIONS_PASSIVE,
DMF_MODULE_OPEN_OPTION_OPEN_Create);
dmfModuleDescriptor_ComponentFirmwareUpdate.CallbacksDmf = &dmfCallbacksDmf_ComponentFirmwareUpdate;
ntStatus = DMF_ModuleCreate(Device,
DmfModuleAttributes,
ObjectAttributes,
&dmfModuleDescriptor_ComponentFirmwareUpdate,
&dmfModule);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_ModuleCreate fails: ntStatus=%!STATUS!",
ntStatus);
}
// Initialize Protocol's declaration data.
//
DMF_INTERFACE_PROTOCOL_ComponentFirmwareUpdate_DESCRIPTOR_INIT(&protocolDeclarationData,
DMF_ComponentFirmwareUpdate_Bind,
DMF_ComponentFirmwareUpdate_Unbind,
DMF_ComponentFirmwareUpdate_PostBind,
DMF_ComponentFirmwareUpdate_PreUnbind,
DMF_ComponentFirmwareUpdate_FirmwareVersionResponseEvt,
DMF_ComponentFirmwareUpdate_OfferResponseEvt,
DMF_ComponentFirmwareUpdate_PayloadResponseEvt);
// An optional context can be set by the Protocol module on the bind instance
// This is a unique context for each instance of Protocol Transport binding.
// E.g. in case a protocol module is bound to multiple modules, the Protocol
// Module will get a unique instance of this context each binding.
//
DMF_INTERFACE_DESCRIPTOR_SET_CONTEXT_TYPE(&protocolDeclarationData,
CONTEXT_ComponentFirmwareUpdateTransport);
// Add the interface to the Protocol Module.
//
ntStatus = DMF_ModuleInterfaceDescriptorAdd(dmfModule,
(DMF_INTERFACE_DESCRIPTOR*)&protocolDeclarationData);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "DMF_ModuleInterfaceDescriptorAdd fails: ntStatus=%!STATUS!", ntStatus);
goto Exit;
}
Exit:
*DmfModule = dmfModule;
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return(ntStatus);
}
#pragma code_seg()
// Module Methods
//
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
NTSTATUS
DMF_ComponentFirmwareUpdate_Start(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Starts the Component Firmware Update Protocol.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DMFMODULE_VALIDATE_IN_METHOD(DmfModule,
ComponentFirmwareUpdate);
moduleContext = DMF_CONTEXT_GET(DmfModule);
ULONG countOfOfferPayloadPairs = WdfCollectionGetCount(moduleContext->FirmwareBlobCollection);
if (countOfOfferPayloadPairs == 0)
{
TraceEvents(TRACE_LEVEL_WARNING,
DMF_TRACE,
"No Firmware available to process. Skipping the entire transaction.");
ntStatus = STATUS_SUCCESS;
goto Exit;
}
BOOLEAN TransactionInProgress = FALSE;
DMF_ModuleLock(DmfModule);
TransactionInProgress = moduleContext->TransactionInProgress;
DMF_ModuleUnlock(DmfModule);
// allow only one protocol transaction at a time.
//
if (TransactionInProgress == TRUE)
{
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Protocol thread is already runinng. Skipping the request to start protocol.");
ntStatus = STATUS_SUCCESS;
goto Exit;
}
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Creating a thread to start the protocol sequence.");
ntStatus = DMF_Thread_Start(moduleContext->DmfModuleThread);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR,
DMF_TRACE,
"DMF_Thread_Start fails: ntStatus=%!STATUS!",
ntStatus);
goto Exit;
}
DMF_Thread_WorkReady(moduleContext->DmfModuleThread);
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
#pragma code_seg("PAGE")
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_ComponentFirmwareUpdate_Stop(
_In_ DMFMODULE DmfModule
)
/*++
Routine Description:
Stop the Component Firmware Update Protocol.
Arguments:
DmfModule - This Module's DMF Object.
Return Value:
None
--*/
{
NTSTATUS ntStatus;
DMF_CONTEXT_ComponentFirmwareUpdate* moduleContext;
PAGED_CODE();
FuncEntry(DMF_TRACE);
DMFMODULE_VALIDATE_IN_METHOD(DmfModule,
ComponentFirmwareUpdate);
moduleContext = DMF_CONTEXT_GET(DmfModule);
ULONG countOfOfferPayloadPairs = WdfCollectionGetCount(moduleContext->FirmwareBlobCollection);
if (countOfOfferPayloadPairs == 0)
{
TraceEvents(TRACE_LEVEL_WARNING,
DMF_TRACE,
"No Firmware available to process. Skipping Stop request.");
ntStatus = STATUS_SUCCESS;
goto Exit;
}
BOOLEAN transactionInProgress = FALSE;
DMF_ModuleLock(DmfModule);
transactionInProgress = moduleContext->TransactionInProgress;
DMF_ModuleUnlock(DmfModule);
// We allow only 1 protocol sequence at a time.
//
if (transactionInProgress == FALSE)
{
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Protocol thread is not runinng. Skipping the Stop protocol request.");
ntStatus = STATUS_SUCCESS;
goto Exit;
}
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Sending a PreClose command to transport");
// Send Protocol Stop to Transport as we are about to wind up the protocol sequences.
//
ntStatus = ComponentFirmwareUpdate_ProtocolStop(DmfModule);
if (!NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_WARNING,
DMF_TRACE,
"ComponentFirmwareUpdate_ProtocolStop fails: ntStatus=%!STATUS!",
ntStatus);
//Continue Stopping the thread.
//
ntStatus = STATUS_SUCCESS;
}
TraceEvents(TRACE_LEVEL_INFORMATION,
DMF_TRACE,
"Stopping the protocol sequence thread.");
// Signal the thread to stop and wait for it to complete.
//
DMF_Thread_Stop(moduleContext->DmfModuleThread);
Exit:
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
// eof: Dmf_ComponentFirmwareUpdate.c
//
| 35.869849 | 218 | 0.596278 | [
"object"
] |
2ca0caaf8cc3300aa4dde7099da41db04e933f7c | 1,646 | h | C | Game/OGRE/Samples/VolumeTex/include/ThingRenderable.h | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/Samples/VolumeTex/include/ThingRenderable.h | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/Samples/VolumeTex/include/ThingRenderable.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
You may use this sample code for anything you like, it is not covered by the
LGPL like the rest of the engine.
-----------------------------------------------------------------------------
*/
#ifndef H_THINGRENDERABLE
#define H_THINGRENDERABLE
#include <OgrePrerequisites.h>
#include <OgreSimpleRenderable.h>
#include <OgreQuaternion.h>
#include <OgreVector3.h>
/** Quad fragments that rotate around origin (0,0,0) in a random orbit, always oriented to 0,0,0.
@author W.J. van der Laan
*/
class ThingRenderable: public Ogre::SimpleRenderable {
public:
/** Create one this object.
@param radius Radius of orbits
@param count Number of quads
@param qsize Size of quads
*/
ThingRenderable(float radius, size_t count, float qsize);
~ThingRenderable();
/**
* Retrieves ratios of the origin-centered bounding sphere for this
* object.
*/
Ogre::Real getBoundingRadius() const;
/**
* Returns the camera-relative squared depth of this renderable.
*/
Ogre::Real getSquaredViewDepth(const Ogre::Camera*) const;
/**
* Notify that t seconds have elapsed.
*/
void addTime(float t);
protected:
void initialise();
void fillBuffer();
Ogre::HardwareVertexBufferSharedPtr vbuf;// Our vertex buffer
float mRadius;
size_t mCount;
float mQSize;
std::vector <Ogre::Quaternion> things;
std::vector <Ogre::Quaternion> orbits;
};
#endif
| 27.433333 | 97 | 0.669502 | [
"object",
"vector"
] |
2ca6601c39d51847719ead91812f66b75287cc47 | 4,962 | c | C | vehicle/OVMS.V3/components/duktape/extras/console/duk_console.c | goev/Open-Vehicle-Monitoring-System-3 | f2efd1898ec1df19eb730c1eda9a1999a00b36b4 | [
"MIT"
] | 199 | 2017-04-06T15:20:50.000Z | 2020-10-16T12:32:56.000Z | extras/console/duk_console.c | KiraanRK/esp32-duktape | 1b7fbcb8bd6bfc346d92df30ec099df7f13b03aa | [
"MIT"
] | 9 | 2017-04-09T03:07:11.000Z | 2017-04-11T02:23:18.000Z | extras/console/duk_console.c | KiraanRK/esp32-duktape | 1b7fbcb8bd6bfc346d92df30ec099df7f13b03aa | [
"MIT"
] | 8 | 2017-04-09T04:49:00.000Z | 2018-07-17T15:55:04.000Z | /*
* Minimal 'console' binding.
*
* https://github.com/DeveloperToolsWG/console-object/blob/master/api.md
* https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference
* https://developer.mozilla.org/en/docs/Web/API/console
*/
#include <stdio.h>
#include <stdarg.h>
#include "duktape.h"
#include "duk_console.h"
/* XXX: Add some form of log level filtering. */
/* XXX: For now logs everything to stdout, V8/Node.js logs debug/info level
* to stdout, warn and above to stderr. Should this extra do the same?
*/
/* XXX: Should all output be written via e.g. console.write(formattedMsg)?
* This would make it easier for user code to redirect all console output
* to a custom backend.
*/
/* XXX: For now output is not flushed, add a flush flag, or maybe add flush
* to info level and above only.
*/
/* XXX: Init console object using duk_def_prop() when that call is available. */
static duk_ret_t duk__console_log_helper(duk_context *ctx, const char *error_name) {
duk_idx_t i, n;
n = duk_get_top(ctx);
duk_get_global_string(ctx, "console");
duk_get_prop_string(ctx, -1, "format");
for (i = 0; i < n; i++) {
if (duk_check_type_mask(ctx, i, DUK_TYPE_MASK_OBJECT)) {
/* Slow path formatting. */
duk_dup(ctx, -1); /* console.format */
duk_dup(ctx, i);
duk_call(ctx, 1);
duk_replace(ctx, i); /* arg[i] = console.format(arg[i]); */
}
}
duk_pop_2(ctx);
duk_push_string(ctx, " ");
duk_insert(ctx, 0);
duk_join(ctx, n);
if (error_name) {
duk_push_error_object(ctx, DUK_ERR_ERROR, "%s", duk_require_string(ctx, -1));
duk_push_string(ctx, "name");
duk_push_string(ctx, error_name);
duk_def_prop(ctx, -3, DUK_DEFPROP_FORCE | DUK_DEFPROP_HAVE_VALUE); /* to get e.g. 'Trace: 1 2 3' */
duk_get_prop_string(ctx, -1, "stack");
}
printf("%s\n", duk_to_string(ctx, -1));
return 0;
}
static duk_ret_t duk__console_assert(duk_context *ctx) {
if (duk_to_boolean(ctx, 0)) {
return 0;
}
duk_remove(ctx, 0);
return duk__console_log_helper(ctx, "AssertionError");
}
static duk_ret_t duk__console_log(duk_context *ctx) {
return duk__console_log_helper(ctx, NULL);
}
static duk_ret_t duk__console_trace(duk_context *ctx) {
return duk__console_log_helper(ctx, "Trace");
}
static duk_ret_t duk__console_info(duk_context *ctx) {
return duk__console_log_helper(ctx, NULL);
}
static duk_ret_t duk__console_warn(duk_context *ctx) {
return duk__console_log_helper(ctx, NULL);
}
static duk_ret_t duk__console_error(duk_context *ctx) {
return duk__console_log_helper(ctx, "Error");
}
static duk_ret_t duk__console_dir(duk_context *ctx) {
/* For now, just share the formatting of .log() */
return duk__console_log_helper(ctx, 0);
}
static void duk__console_reg_vararg_func(duk_context *ctx, duk_c_function func, const char *name) {
duk_push_c_function(ctx, func, DUK_VARARGS);
duk_push_string(ctx, "name");
duk_push_string(ctx, name);
duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_FORCE); /* Improve stacktraces by displaying function name */
duk_put_prop_string(ctx, -2, name);
}
void duk_console_init(duk_context *ctx, duk_uint_t flags) {
duk_push_object(ctx);
/* Custom function to format objects; user can replace.
* For now, try JX-formatting and if that fails, fall back
* to ToString(v).
*/
duk_eval_string(ctx,
"(function (E) {"
"return function format(v){"
"try{"
"return E('jx',v);"
"}catch(e){"
"return String(v);" /* String() allows symbols, ToString() internal algorithm doesn't. */
"}"
"};"
"})(Duktape.enc)");
duk_put_prop_string(ctx, -2, "format");
duk__console_reg_vararg_func(ctx, duk__console_assert, "assert");
duk__console_reg_vararg_func(ctx, duk__console_log, "log");
duk__console_reg_vararg_func(ctx, duk__console_log, "debug"); /* alias to console.log */
duk__console_reg_vararg_func(ctx, duk__console_trace, "trace");
duk__console_reg_vararg_func(ctx, duk__console_info, "info");
duk__console_reg_vararg_func(ctx, duk__console_warn, "warn");
duk__console_reg_vararg_func(ctx, duk__console_error, "error");
duk__console_reg_vararg_func(ctx, duk__console_error, "exception"); /* alias to console.error */
duk__console_reg_vararg_func(ctx, duk__console_dir, "dir");
duk_put_global_string(ctx, "console");
/* Proxy wrapping: ensures any undefined console method calls are
* ignored silently. This is required specifically by the
* DeveloperToolsWG proposal (and is implemented also by Firefox:
* https://bugzilla.mozilla.org/show_bug.cgi?id=629607).
*/
if (flags & DUK_CONSOLE_PROXY_WRAPPER) {
/* Tolerate errors: Proxy may be disabled. */
duk_peval_string_noresult(ctx,
"(function(){"
"var D=function(){};"
"console=new Proxy(console,{"
"get:function(t,k){"
"var v=t[k];"
"return typeof v==='function'?v:D;"
"}"
"});"
"})();"
);
}
}
| 30.819876 | 122 | 0.701532 | [
"object"
] |
2ca916338666f5de033fefe33400ee20e1390c2b | 2,264 | h | C | code/steps/header/model/wtg_models/wt_aerodynamic_model/aerd0.h | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 29 | 2019-10-30T07:04:10.000Z | 2022-02-22T06:34:32.000Z | code/steps/header/model/wtg_models/wt_aerodynamic_model/aerd0.h | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 1 | 2021-09-25T15:29:59.000Z | 2022-01-05T14:04:18.000Z | code/steps/header/model/wtg_models/wt_aerodynamic_model/aerd0.h | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 8 | 2019-12-20T16:13:46.000Z | 2022-03-20T14:58:23.000Z | #ifndef AERD0_H
#define AERD0_H
#include "header/model/wtg_models/wt_aerodynamic_model/wt_aerodynamic_model.h"
#include <cstdlib>
class AERD0 : public WT_AERODYNAMIC_MODEL
{
public:
AERD0(STEPS& toolkit);
AERD0(const AERD0& model);
virtual ~AERD0();
virtual AERD0& operator=(const AERD0& model);
public:
void set_C1(double c);
void set_C2(double c);
void set_C3(double c);
void set_C4(double c);
void set_C5(double c);
void set_C6(double c);
void set_C7(double c);
void set_C8(double c);
double get_C1() const;
double get_C2() const;
double get_C3() const;
double get_C4() const;
double get_C5() const;
double get_C6() const;
double get_C7() const;
double get_C8() const;
public:
virtual double get_Cp(double lambda, double pitch_deg) const;
virtual double get_derivative_of_Cp_over_lambda(double lambda, double pitch_deg) const;
public:
virtual string get_model_name() const;
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 check();
virtual void clear();
virtual void report();
virtual void save();
virtual string get_standard_psse_string(bool export_internal_bus_number=false) 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 AERD0& model);
// Cp function parameters
double Cp_Coefficients[8];
};
#endif // AERD0_H
| 34.30303 | 95 | 0.683746 | [
"vector",
"model"
] |
2ca9b27c9db3074f28979ea90da98db01751ace5 | 2,548 | h | C | Project/Shared/Classes/Model/Geometries/SGMultiPolygon.h | simplegeo/SimpleGeo.framework | 70d92d014a00df4b84e1e57ef60c3da230b8038f | [
"BSD-3-Clause"
] | 3 | 2015-04-18T05:41:56.000Z | 2017-02-06T11:38:58.000Z | Project/Shared/Classes/Model/Geometries/SGMultiPolygon.h | simplegeo/SimpleGeo.framework | 70d92d014a00df4b84e1e57ef60c3da230b8038f | [
"BSD-3-Clause"
] | null | null | null | Project/Shared/Classes/Model/Geometries/SGMultiPolygon.h | simplegeo/SimpleGeo.framework | 70d92d014a00df4b84e1e57ef60c3da230b8038f | [
"BSD-3-Clause"
] | null | null | null | //
// SGMultiPolygon.h
// SimpleGeo.framework
//
// Copyright (c) 2010, SimpleGeo Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#import "SGGeometry.h"
@class SGPoint;
@class SGEnvelope;
/**
* An SGMultiPolygon object stores information about a multi-polygon — an array of SGPolygons representing a single feature.
*
* A good example of a multi-polygon is the state of Hawaii, a single feature composed of many polygons.
*/
@interface SGMultiPolygon : SGGeometry <SGRegionGeometry>
{
@private
NSArray *polygons;
}
/// Polygons that define this multi-polygon
@property (nonatomic, retain) NSArray *polygons;
/// Bounding box for the multi-polygon
@property (nonatomic, readonly) SGEnvelope *envelope;
#pragma mark -
#pragma mark Instantiation
/**
* Create a multi-polygon from a set of Polygons
* @param polygons Polygons
*/
+ (SGMultiPolygon *)multiPolygonWithPolygons:(NSArray *)polygons;
/**
* Construct a multi-polygon from a set of Polygons
* @param polygons Polygons
*/
- (id)initWithPolygons:(NSArray *)polygons;
@end | 37.470588 | 124 | 0.748038 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.